]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/sshd.c
Upgrade our copy of llvm/clang to trunk r162107. With thanks to
[FreeBSD/FreeBSD.git] / crypto / openssh / sshd.c
1 /* $OpenBSD: sshd.c,v 1.385 2011/06/23 09:34:13 djm Exp $ */
2 /* $FreeBSD$ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * This program is the ssh daemon.  It listens for connections from clients,
8  * and performs authentication, executes use commands or shell, and forwards
9  * information to/from the application to the user client over an encrypted
10  * connection.  This can also handle forwarding of X11, TCP/IP, and
11  * authentication agent connections.
12  *
13  * As far as I am concerned, the code I have written for this software
14  * can be used freely for any purpose.  Any derived versions of this
15  * software must be clearly marked as such, and if the derived work is
16  * incompatible with the protocol description in the RFC file, it must be
17  * called by a name other than "ssh" or "Secure Shell".
18  *
19  * SSH2 implementation:
20  * Privilege Separation:
21  *
22  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
23  * Copyright (c) 2002 Niels Provos.  All rights reserved.
24  *
25  * Redistribution and use in source and binary forms, with or without
26  * modification, are permitted provided that the following conditions
27  * are met:
28  * 1. Redistributions of source code must retain the above copyright
29  *    notice, this list of conditions and the following disclaimer.
30  * 2. Redistributions in binary form must reproduce the above copyright
31  *    notice, this list of conditions and the following disclaimer in the
32  *    documentation and/or other materials provided with the distribution.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
35  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
36  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
37  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
38  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
39  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
40  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
41  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44  */
45
46 #include "includes.h"
47 __RCSID("$FreeBSD$");
48
49 #include <sys/types.h>
50 #include <sys/ioctl.h>
51 #include <sys/mman.h>
52 #include <sys/socket.h>
53 #ifdef HAVE_SYS_STAT_H
54 # include <sys/stat.h>
55 #endif
56 #ifdef HAVE_SYS_TIME_H
57 # include <sys/time.h>
58 #endif
59 #include "openbsd-compat/sys-tree.h"
60 #include "openbsd-compat/sys-queue.h"
61 #include <sys/wait.h>
62
63 #include <errno.h>
64 #include <fcntl.h>
65 #include <netdb.h>
66 #ifdef HAVE_PATHS_H
67 #include <paths.h>
68 #endif
69 #include <grp.h>
70 #include <pwd.h>
71 #include <signal.h>
72 #include <stdarg.h>
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <unistd.h>
77
78 #include <openssl/dh.h>
79 #include <openssl/bn.h>
80 #include <openssl/md5.h>
81 #include <openssl/rand.h>
82 #include "openbsd-compat/openssl-compat.h"
83
84 #ifdef HAVE_SECUREWARE
85 #include <sys/security.h>
86 #include <prot.h>
87 #endif
88
89 #ifdef __FreeBSD__
90 #include <resolv.h>
91 #if defined(GSSAPI) && defined(HAVE_GSSAPI_H)
92 #include <gssapi.h>
93 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
94 #include <gssapi/gssapi.h>
95 #endif
96 #endif
97
98 #include "xmalloc.h"
99 #include "ssh.h"
100 #include "ssh1.h"
101 #include "ssh2.h"
102 #include "rsa.h"
103 #include "sshpty.h"
104 #include "packet.h"
105 #include "log.h"
106 #include "buffer.h"
107 #include "servconf.h"
108 #include "uidswap.h"
109 #include "compat.h"
110 #include "cipher.h"
111 #include "key.h"
112 #include "kex.h"
113 #include "dh.h"
114 #include "myproposal.h"
115 #include "authfile.h"
116 #include "pathnames.h"
117 #include "atomicio.h"
118 #include "canohost.h"
119 #include "hostfile.h"
120 #include "auth.h"
121 #include "misc.h"
122 #include "msg.h"
123 #include "dispatch.h"
124 #include "channels.h"
125 #include "session.h"
126 #include "monitor_mm.h"
127 #include "monitor.h"
128 #ifdef GSSAPI
129 #include "ssh-gss.h"
130 #endif
131 #include "monitor_wrap.h"
132 #include "roaming.h"
133 #include "ssh-sandbox.h"
134 #include "version.h"
135
136 #ifdef LIBWRAP
137 #include <tcpd.h>
138 #include <syslog.h>
139 int allow_severity;
140 int deny_severity;
141 #endif /* LIBWRAP */
142
143 #ifndef O_NOCTTY
144 #define O_NOCTTY        0
145 #endif
146
147 /* Re-exec fds */
148 #define REEXEC_DEVCRYPTO_RESERVED_FD    (STDERR_FILENO + 1)
149 #define REEXEC_STARTUP_PIPE_FD          (STDERR_FILENO + 2)
150 #define REEXEC_CONFIG_PASS_FD           (STDERR_FILENO + 3)
151 #define REEXEC_MIN_FREE_FD              (STDERR_FILENO + 4)
152
153 extern char *__progname;
154
155 /* Server configuration options. */
156 ServerOptions options;
157
158 /* Name of the server configuration file. */
159 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
160
161 /*
162  * Debug mode flag.  This can be set on the command line.  If debug
163  * mode is enabled, extra debugging output will be sent to the system
164  * log, the daemon will not go to background, and will exit after processing
165  * the first connection.
166  */
167 int debug_flag = 0;
168
169 /* Flag indicating that the daemon should only test the configuration and keys. */
170 int test_flag = 0;
171
172 /* Flag indicating that the daemon is being started from inetd. */
173 int inetd_flag = 0;
174
175 /* Flag indicating that sshd should not detach and become a daemon. */
176 int no_daemon_flag = 0;
177
178 /* debug goes to stderr unless inetd_flag is set */
179 int log_stderr = 0;
180
181 /* Saved arguments to main(). */
182 char **saved_argv;
183 int saved_argc;
184
185 /* re-exec */
186 int rexeced_flag = 0;
187 int rexec_flag = 1;
188 int rexec_argc = 0;
189 char **rexec_argv;
190
191 /*
192  * The sockets that the server is listening; this is used in the SIGHUP
193  * signal handler.
194  */
195 #define MAX_LISTEN_SOCKS        16
196 int listen_socks[MAX_LISTEN_SOCKS];
197 int num_listen_socks = 0;
198
199 /*
200  * the client's version string, passed by sshd2 in compat mode. if != NULL,
201  * sshd will skip the version-number exchange
202  */
203 char *client_version_string = NULL;
204 char *server_version_string = NULL;
205
206 /* for rekeying XXX fixme */
207 Kex *xxx_kex;
208
209 /*
210  * Any really sensitive data in the application is contained in this
211  * structure. The idea is that this structure could be locked into memory so
212  * that the pages do not get written into swap.  However, there are some
213  * problems. The private key contains BIGNUMs, and we do not (in principle)
214  * have access to the internals of them, and locking just the structure is
215  * not very useful.  Currently, memory locking is not implemented.
216  */
217 struct {
218         Key     *server_key;            /* ephemeral server key */
219         Key     *ssh1_host_key;         /* ssh1 host key */
220         Key     **host_keys;            /* all private host keys */
221         Key     **host_certificates;    /* all public host certificates */
222         int     have_ssh1_key;
223         int     have_ssh2_key;
224         u_char  ssh1_cookie[SSH_SESSION_KEY_LENGTH];
225 } sensitive_data;
226
227 /*
228  * Flag indicating whether the RSA server key needs to be regenerated.
229  * Is set in the SIGALRM handler and cleared when the key is regenerated.
230  */
231 static volatile sig_atomic_t key_do_regen = 0;
232
233 /* This is set to true when a signal is received. */
234 static volatile sig_atomic_t received_sighup = 0;
235 static volatile sig_atomic_t received_sigterm = 0;
236
237 /* session identifier, used by RSA-auth */
238 u_char session_id[16];
239
240 /* same for ssh2 */
241 u_char *session_id2 = NULL;
242 u_int session_id2_len = 0;
243
244 /* record remote hostname or ip */
245 u_int utmp_len = MAXHOSTNAMELEN;
246
247 /* options.max_startup sized array of fd ints */
248 int *startup_pipes = NULL;
249 int startup_pipe;               /* in child */
250
251 /* variables used for privilege separation */
252 int use_privsep = -1;
253 struct monitor *pmonitor = NULL;
254
255 /* global authentication context */
256 Authctxt *the_authctxt = NULL;
257
258 /* sshd_config buffer */
259 Buffer cfg;
260
261 /* message to be displayed after login */
262 Buffer loginmsg;
263
264 /* Unprivileged user */
265 struct passwd *privsep_pw = NULL;
266
267 /* Prototypes for various functions defined later in this file. */
268 void destroy_sensitive_data(void);
269 void demote_sensitive_data(void);
270
271 static void do_ssh1_kex(void);
272 static void do_ssh2_kex(void);
273
274 /*
275  * Close all listening sockets
276  */
277 static void
278 close_listen_socks(void)
279 {
280         int i;
281
282         for (i = 0; i < num_listen_socks; i++)
283                 close(listen_socks[i]);
284         num_listen_socks = -1;
285 }
286
287 static void
288 close_startup_pipes(void)
289 {
290         int i;
291
292         if (startup_pipes)
293                 for (i = 0; i < options.max_startups; i++)
294                         if (startup_pipes[i] != -1)
295                                 close(startup_pipes[i]);
296 }
297
298 /*
299  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
300  * the effect is to reread the configuration file (and to regenerate
301  * the server key).
302  */
303
304 /*ARGSUSED*/
305 static void
306 sighup_handler(int sig)
307 {
308         int save_errno = errno;
309
310         received_sighup = 1;
311         signal(SIGHUP, sighup_handler);
312         errno = save_errno;
313 }
314
315 /*
316  * Called from the main program after receiving SIGHUP.
317  * Restarts the server.
318  */
319 static void
320 sighup_restart(void)
321 {
322         logit("Received SIGHUP; restarting.");
323         close_listen_socks();
324         close_startup_pipes();
325         alarm(0);  /* alarm timer persists across exec */
326         signal(SIGHUP, SIG_IGN); /* will be restored after exec */
327         execv(saved_argv[0], saved_argv);
328         logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
329             strerror(errno));
330         exit(1);
331 }
332
333 /*
334  * Generic signal handler for terminating signals in the master daemon.
335  */
336 /*ARGSUSED*/
337 static void
338 sigterm_handler(int sig)
339 {
340         received_sigterm = sig;
341 }
342
343 /*
344  * SIGCHLD handler.  This is called whenever a child dies.  This will then
345  * reap any zombies left by exited children.
346  */
347 /*ARGSUSED*/
348 static void
349 main_sigchld_handler(int sig)
350 {
351         int save_errno = errno;
352         pid_t pid;
353         int status;
354
355         while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
356             (pid < 0 && errno == EINTR))
357                 ;
358
359         signal(SIGCHLD, main_sigchld_handler);
360         errno = save_errno;
361 }
362
363 /*
364  * Signal handler for the alarm after the login grace period has expired.
365  */
366 /*ARGSUSED*/
367 static void
368 grace_alarm_handler(int sig)
369 {
370         if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
371                 kill(pmonitor->m_pid, SIGALRM);
372
373         /* Log error and exit. */
374         sigdie("Timeout before authentication for %s", get_remote_ipaddr());
375 }
376
377 /*
378  * Signal handler for the key regeneration alarm.  Note that this
379  * alarm only occurs in the daemon waiting for connections, and it does not
380  * do anything with the private key or random state before forking.
381  * Thus there should be no concurrency control/asynchronous execution
382  * problems.
383  */
384 static void
385 generate_ephemeral_server_key(void)
386 {
387         verbose("Generating %s%d bit RSA key.",
388             sensitive_data.server_key ? "new " : "", options.server_key_bits);
389         if (sensitive_data.server_key != NULL)
390                 key_free(sensitive_data.server_key);
391         sensitive_data.server_key = key_generate(KEY_RSA1,
392             options.server_key_bits);
393         verbose("RSA key generation complete.");
394
395         arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
396         arc4random_stir();
397 }
398
399 /*ARGSUSED*/
400 static void
401 key_regeneration_alarm(int sig)
402 {
403         int save_errno = errno;
404
405         signal(SIGALRM, SIG_DFL);
406         errno = save_errno;
407         key_do_regen = 1;
408 }
409
410 static void
411 sshd_exchange_identification(int sock_in, int sock_out)
412 {
413         u_int i;
414         int mismatch;
415         int remote_major, remote_minor;
416         int major, minor;
417         char *s, *newline = "\n";
418         char buf[256];                  /* Must not be larger than remote_version. */
419         char remote_version[256];       /* Must be at least as big as buf. */
420
421         if ((options.protocol & SSH_PROTO_1) &&
422             (options.protocol & SSH_PROTO_2)) {
423                 major = PROTOCOL_MAJOR_1;
424                 minor = 99;
425         } else if (options.protocol & SSH_PROTO_2) {
426                 major = PROTOCOL_MAJOR_2;
427                 minor = PROTOCOL_MINOR_2;
428                 newline = "\r\n";
429         } else {
430                 major = PROTOCOL_MAJOR_1;
431                 minor = PROTOCOL_MINOR_1;
432         }
433         snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s%s", major, minor,
434             ssh_version_get(options.hpn_disabled), newline);
435         server_version_string = xstrdup(buf);
436
437         /* Send our protocol version identification. */
438         if (roaming_atomicio(vwrite, sock_out, server_version_string,
439             strlen(server_version_string))
440             != strlen(server_version_string)) {
441                 logit("Could not write ident string to %s", get_remote_ipaddr());
442                 cleanup_exit(255);
443         }
444
445         /* Read other sides version identification. */
446         memset(buf, 0, sizeof(buf));
447         for (i = 0; i < sizeof(buf) - 1; i++) {
448                 if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
449                         logit("Did not receive identification string from %s",
450                             get_remote_ipaddr());
451                         cleanup_exit(255);
452                 }
453                 if (buf[i] == '\r') {
454                         buf[i] = 0;
455                         /* Kludge for F-Secure Macintosh < 1.0.2 */
456                         if (i == 12 &&
457                             strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
458                                 break;
459                         continue;
460                 }
461                 if (buf[i] == '\n') {
462                         buf[i] = 0;
463                         break;
464                 }
465         }
466         buf[sizeof(buf) - 1] = 0;
467         client_version_string = xstrdup(buf);
468
469         /*
470          * Check that the versions match.  In future this might accept
471          * several versions and set appropriate flags to handle them.
472          */
473         if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
474             &remote_major, &remote_minor, remote_version) != 3) {
475                 s = "Protocol mismatch.\n";
476                 (void) atomicio(vwrite, sock_out, s, strlen(s));
477                 close(sock_in);
478                 close(sock_out);
479                 logit("Bad protocol version identification '%.100s' from %s",
480                     client_version_string, get_remote_ipaddr());
481                 cleanup_exit(255);
482         }
483         debug("Client protocol version %d.%d; client software version %.100s",
484             remote_major, remote_minor, remote_version);
485
486         compat_datafellows(remote_version);
487
488         if (datafellows & SSH_BUG_PROBE) {
489                 logit("probed from %s with %s.  Don't panic.",
490                     get_remote_ipaddr(), client_version_string);
491                 cleanup_exit(255);
492         }
493
494         if (datafellows & SSH_BUG_SCANNER) {
495                 logit("scanned from %s with %s.  Don't panic.",
496                     get_remote_ipaddr(), client_version_string);
497                 cleanup_exit(255);
498         }
499
500         mismatch = 0;
501         switch (remote_major) {
502         case 1:
503                 if (remote_minor == 99) {
504                         if (options.protocol & SSH_PROTO_2)
505                                 enable_compat20();
506                         else
507                                 mismatch = 1;
508                         break;
509                 }
510                 if (!(options.protocol & SSH_PROTO_1)) {
511                         mismatch = 1;
512                         break;
513                 }
514                 if (remote_minor < 3) {
515                         packet_disconnect("Your ssh version is too old and "
516                             "is no longer supported.  Please install a newer version.");
517                 } else if (remote_minor == 3) {
518                         /* note that this disables agent-forwarding */
519                         enable_compat13();
520                 }
521                 break;
522         case 2:
523                 if (options.protocol & SSH_PROTO_2) {
524                         enable_compat20();
525                         break;
526                 }
527                 /* FALLTHROUGH */
528         default:
529                 mismatch = 1;
530                 break;
531         }
532         chop(server_version_string);
533         debug("Local version string %.200s", server_version_string);
534
535         if (mismatch) {
536                 s = "Protocol major versions differ.\n";
537                 (void) atomicio(vwrite, sock_out, s, strlen(s));
538                 close(sock_in);
539                 close(sock_out);
540                 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
541                     get_remote_ipaddr(),
542                     server_version_string, client_version_string);
543                 cleanup_exit(255);
544         }
545 }
546
547 /* Destroy the host and server keys.  They will no longer be needed. */
548 void
549 destroy_sensitive_data(void)
550 {
551         int i;
552
553         if (sensitive_data.server_key) {
554                 key_free(sensitive_data.server_key);
555                 sensitive_data.server_key = NULL;
556         }
557         for (i = 0; i < options.num_host_key_files; i++) {
558                 if (sensitive_data.host_keys[i]) {
559                         key_free(sensitive_data.host_keys[i]);
560                         sensitive_data.host_keys[i] = NULL;
561                 }
562                 if (sensitive_data.host_certificates[i]) {
563                         key_free(sensitive_data.host_certificates[i]);
564                         sensitive_data.host_certificates[i] = NULL;
565                 }
566         }
567         sensitive_data.ssh1_host_key = NULL;
568         memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
569 }
570
571 /* Demote private to public keys for network child */
572 void
573 demote_sensitive_data(void)
574 {
575         Key *tmp;
576         int i;
577
578         if (sensitive_data.server_key) {
579                 tmp = key_demote(sensitive_data.server_key);
580                 key_free(sensitive_data.server_key);
581                 sensitive_data.server_key = tmp;
582         }
583
584         for (i = 0; i < options.num_host_key_files; i++) {
585                 if (sensitive_data.host_keys[i]) {
586                         tmp = key_demote(sensitive_data.host_keys[i]);
587                         key_free(sensitive_data.host_keys[i]);
588                         sensitive_data.host_keys[i] = tmp;
589                         if (tmp->type == KEY_RSA1)
590                                 sensitive_data.ssh1_host_key = tmp;
591                 }
592                 /* Certs do not need demotion */
593         }
594
595         /* We do not clear ssh1_host key and cookie.  XXX - Okay Niels? */
596 }
597
598 static void
599 privsep_preauth_child(void)
600 {
601         u_int32_t rnd[256];
602         gid_t gidset[1];
603
604         /* Enable challenge-response authentication for privilege separation */
605         privsep_challenge_enable();
606
607         arc4random_stir();
608         arc4random_buf(rnd, sizeof(rnd));
609         RAND_seed(rnd, sizeof(rnd));
610
611         /* Demote the private keys to public keys. */
612         demote_sensitive_data();
613
614         /* Change our root directory */
615         if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
616                 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
617                     strerror(errno));
618         if (chdir("/") == -1)
619                 fatal("chdir(\"/\"): %s", strerror(errno));
620
621         /* Drop our privileges */
622         debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
623             (u_int)privsep_pw->pw_gid);
624 #if 0
625         /* XXX not ready, too heavy after chroot */
626         do_setusercontext(privsep_pw);
627 #else
628         gidset[0] = privsep_pw->pw_gid;
629         if (setgroups(1, gidset) < 0)
630                 fatal("setgroups: %.100s", strerror(errno));
631         permanently_set_uid(privsep_pw);
632 #endif
633 }
634
635 static int
636 privsep_preauth(Authctxt *authctxt)
637 {
638         int status;
639         pid_t pid;
640         struct ssh_sandbox *box = NULL;
641
642         /* Set up unprivileged child process to deal with network data */
643         pmonitor = monitor_init();
644         /* Store a pointer to the kex for later rekeying */
645         pmonitor->m_pkex = &xxx_kex;
646
647         if (use_privsep == PRIVSEP_SANDBOX)
648                 box = ssh_sandbox_init();
649         pid = fork();
650         if (pid == -1) {
651                 fatal("fork of unprivileged child failed");
652         } else if (pid != 0) {
653                 debug2("Network child is on pid %ld", (long)pid);
654
655                 if (box != NULL)
656                         ssh_sandbox_parent_preauth(box, pid);
657                 pmonitor->m_pid = pid;
658                 monitor_child_preauth(authctxt, pmonitor);
659
660                 /* Sync memory */
661                 monitor_sync(pmonitor);
662
663                 /* Wait for the child's exit status */
664                 while (waitpid(pid, &status, 0) < 0) {
665                         if (errno != EINTR)
666                                 fatal("%s: waitpid: %s", __func__,
667                                     strerror(errno));
668                 }
669                 if (WIFEXITED(status)) {
670                         if (WEXITSTATUS(status) != 0)
671                                 fatal("%s: preauth child exited with status %d",
672                                     __func__, WEXITSTATUS(status));
673                 } else if (WIFSIGNALED(status))
674                         fatal("%s: preauth child terminated by signal %d",
675                             __func__, WTERMSIG(status));
676                 if (box != NULL)
677                         ssh_sandbox_parent_finish(box);
678                 return 1;
679         } else {
680                 /* child */
681                 close(pmonitor->m_sendfd);
682                 close(pmonitor->m_log_recvfd);
683
684                 /* Arrange for logging to be sent to the monitor */
685                 set_log_handler(mm_log_handler, pmonitor);
686
687                 /* Demote the child */
688                 if (getuid() == 0 || geteuid() == 0)
689                         privsep_preauth_child();
690                 setproctitle("%s", "[net]");
691                 if (box != NULL)
692                         ssh_sandbox_child(box);
693
694                 return 0;
695         }
696 }
697
698 static void
699 privsep_postauth(Authctxt *authctxt)
700 {
701         u_int32_t rnd[256];
702
703 #ifdef DISABLE_FD_PASSING
704         if (1) {
705 #else
706         if (authctxt->pw->pw_uid == 0 || options.use_login) {
707 #endif
708                 /* File descriptor passing is broken or root login */
709                 use_privsep = 0;
710                 goto skip;
711         }
712
713         /* New socket pair */
714         monitor_reinit(pmonitor);
715
716         pmonitor->m_pid = fork();
717         if (pmonitor->m_pid == -1)
718                 fatal("fork of unprivileged child failed");
719         else if (pmonitor->m_pid != 0) {
720                 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
721                 buffer_clear(&loginmsg);
722                 monitor_child_postauth(pmonitor);
723
724                 /* NEVERREACHED */
725                 exit(0);
726         }
727
728         /* child */
729
730         close(pmonitor->m_sendfd);
731         pmonitor->m_sendfd = -1;
732
733         /* Demote the private keys to public keys. */
734         demote_sensitive_data();
735
736         arc4random_stir();
737         arc4random_buf(rnd, sizeof(rnd));
738         RAND_seed(rnd, sizeof(rnd));
739
740         /* Drop privileges */
741         do_setusercontext(authctxt->pw);
742
743  skip:
744         /* It is safe now to apply the key state */
745         monitor_apply_keystate(pmonitor);
746
747         /*
748          * Tell the packet layer that authentication was successful, since
749          * this information is not part of the key state.
750          */
751         packet_set_authenticated();
752 }
753
754 static char *
755 list_hostkey_types(void)
756 {
757         Buffer b;
758         const char *p;
759         char *ret;
760         int i;
761         Key *key;
762
763         buffer_init(&b);
764         for (i = 0; i < options.num_host_key_files; i++) {
765                 key = sensitive_data.host_keys[i];
766                 if (key == NULL)
767                         continue;
768                 switch (key->type) {
769                 case KEY_RSA:
770                 case KEY_DSA:
771                 case KEY_ECDSA:
772                         if (buffer_len(&b) > 0)
773                                 buffer_append(&b, ",", 1);
774                         p = key_ssh_name(key);
775                         buffer_append(&b, p, strlen(p));
776                         break;
777                 }
778                 /* If the private key has a cert peer, then list that too */
779                 key = sensitive_data.host_certificates[i];
780                 if (key == NULL)
781                         continue;
782                 switch (key->type) {
783                 case KEY_RSA_CERT_V00:
784                 case KEY_DSA_CERT_V00:
785                 case KEY_RSA_CERT:
786                 case KEY_DSA_CERT:
787                 case KEY_ECDSA_CERT:
788                         if (buffer_len(&b) > 0)
789                                 buffer_append(&b, ",", 1);
790                         p = key_ssh_name(key);
791                         buffer_append(&b, p, strlen(p));
792                         break;
793                 }
794         }
795         buffer_append(&b, "\0", 1);
796         ret = xstrdup(buffer_ptr(&b));
797         buffer_free(&b);
798         debug("list_hostkey_types: %s", ret);
799         return ret;
800 }
801
802 static Key *
803 get_hostkey_by_type(int type, int need_private)
804 {
805         int i;
806         Key *key;
807
808         for (i = 0; i < options.num_host_key_files; i++) {
809                 switch (type) {
810                 case KEY_RSA_CERT_V00:
811                 case KEY_DSA_CERT_V00:
812                 case KEY_RSA_CERT:
813                 case KEY_DSA_CERT:
814                 case KEY_ECDSA_CERT:
815                         key = sensitive_data.host_certificates[i];
816                         break;
817                 default:
818                         key = sensitive_data.host_keys[i];
819                         break;
820                 }
821                 if (key != NULL && key->type == type)
822                         return need_private ?
823                             sensitive_data.host_keys[i] : key;
824         }
825         return NULL;
826 }
827
828 Key *
829 get_hostkey_public_by_type(int type)
830 {
831         return get_hostkey_by_type(type, 0);
832 }
833
834 Key *
835 get_hostkey_private_by_type(int type)
836 {
837         return get_hostkey_by_type(type, 1);
838 }
839
840 Key *
841 get_hostkey_by_index(int ind)
842 {
843         if (ind < 0 || ind >= options.num_host_key_files)
844                 return (NULL);
845         return (sensitive_data.host_keys[ind]);
846 }
847
848 int
849 get_hostkey_index(Key *key)
850 {
851         int i;
852
853         for (i = 0; i < options.num_host_key_files; i++) {
854                 if (key_is_cert(key)) {
855                         if (key == sensitive_data.host_certificates[i])
856                                 return (i);
857                 } else {
858                         if (key == sensitive_data.host_keys[i])
859                                 return (i);
860                 }
861         }
862         return (-1);
863 }
864
865 /*
866  * returns 1 if connection should be dropped, 0 otherwise.
867  * dropping starts at connection #max_startups_begin with a probability
868  * of (max_startups_rate/100). the probability increases linearly until
869  * all connections are dropped for startups > max_startups
870  */
871 static int
872 drop_connection(int startups)
873 {
874         int p, r;
875
876         if (startups < options.max_startups_begin)
877                 return 0;
878         if (startups >= options.max_startups)
879                 return 1;
880         if (options.max_startups_rate == 100)
881                 return 1;
882
883         p  = 100 - options.max_startups_rate;
884         p *= startups - options.max_startups_begin;
885         p /= options.max_startups - options.max_startups_begin;
886         p += options.max_startups_rate;
887         r = arc4random_uniform(100);
888
889         debug("drop_connection: p %d, r %d", p, r);
890         return (r < p) ? 1 : 0;
891 }
892
893 static void
894 usage(void)
895 {
896         fprintf(stderr, "%s, %s\n",
897             ssh_version_get(0), SSLeay_version(SSLEAY_VERSION));
898         fprintf(stderr,
899 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
900 "            [-f config_file] [-g login_grace_time] [-h host_key_file]\n"
901 "            [-k key_gen_time] [-o option] [-p port] [-u len]\n"
902         );
903         exit(1);
904 }
905
906 static void
907 send_rexec_state(int fd, Buffer *conf)
908 {
909         Buffer m;
910
911         debug3("%s: entering fd = %d config len %d", __func__, fd,
912             buffer_len(conf));
913
914         /*
915          * Protocol from reexec master to child:
916          *      string  configuration
917          *      u_int   ephemeral_key_follows
918          *      bignum  e               (only if ephemeral_key_follows == 1)
919          *      bignum  n                       "
920          *      bignum  d                       "
921          *      bignum  iqmp                    "
922          *      bignum  p                       "
923          *      bignum  q                       "
924          *      string rngseed          (only if OpenSSL is not self-seeded)
925          */
926         buffer_init(&m);
927         buffer_put_cstring(&m, buffer_ptr(conf));
928
929         if (sensitive_data.server_key != NULL &&
930             sensitive_data.server_key->type == KEY_RSA1) {
931                 buffer_put_int(&m, 1);
932                 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
933                 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
934                 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
935                 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
936                 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
937                 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
938         } else
939                 buffer_put_int(&m, 0);
940
941 #ifndef OPENSSL_PRNG_ONLY
942         rexec_send_rng_seed(&m);
943 #endif
944
945         if (ssh_msg_send(fd, 0, &m) == -1)
946                 fatal("%s: ssh_msg_send failed", __func__);
947
948         buffer_free(&m);
949
950         debug3("%s: done", __func__);
951 }
952
953 static void
954 recv_rexec_state(int fd, Buffer *conf)
955 {
956         Buffer m;
957         char *cp;
958         u_int len;
959
960         debug3("%s: entering fd = %d", __func__, fd);
961
962         buffer_init(&m);
963
964         if (ssh_msg_recv(fd, &m) == -1)
965                 fatal("%s: ssh_msg_recv failed", __func__);
966         if (buffer_get_char(&m) != 0)
967                 fatal("%s: rexec version mismatch", __func__);
968
969         cp = buffer_get_string(&m, &len);
970         if (conf != NULL)
971                 buffer_append(conf, cp, len + 1);
972         xfree(cp);
973
974         if (buffer_get_int(&m)) {
975                 if (sensitive_data.server_key != NULL)
976                         key_free(sensitive_data.server_key);
977                 sensitive_data.server_key = key_new_private(KEY_RSA1);
978                 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
979                 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
980                 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
981                 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
982                 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
983                 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
984                 rsa_generate_additional_parameters(
985                     sensitive_data.server_key->rsa);
986         }
987
988 #ifndef OPENSSL_PRNG_ONLY
989         rexec_recv_rng_seed(&m);
990 #endif
991
992         buffer_free(&m);
993
994         debug3("%s: done", __func__);
995 }
996
997 /* Accept a connection from inetd */
998 static void
999 server_accept_inetd(int *sock_in, int *sock_out)
1000 {
1001         int fd;
1002
1003         startup_pipe = -1;
1004         if (rexeced_flag) {
1005                 close(REEXEC_CONFIG_PASS_FD);
1006                 *sock_in = *sock_out = dup(STDIN_FILENO);
1007                 if (!debug_flag) {
1008                         startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1009                         close(REEXEC_STARTUP_PIPE_FD);
1010                 }
1011         } else {
1012                 *sock_in = dup(STDIN_FILENO);
1013                 *sock_out = dup(STDOUT_FILENO);
1014         }
1015         /*
1016          * We intentionally do not close the descriptors 0, 1, and 2
1017          * as our code for setting the descriptors won't work if
1018          * ttyfd happens to be one of those.
1019          */
1020         if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1021                 dup2(fd, STDIN_FILENO);
1022                 dup2(fd, STDOUT_FILENO);
1023                 if (fd > STDOUT_FILENO)
1024                         close(fd);
1025         }
1026         debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1027 }
1028
1029 /*
1030  * Listen for TCP connections
1031  */
1032 static void
1033 server_listen(void)
1034 {
1035         int ret, listen_sock, on = 1;
1036         struct addrinfo *ai;
1037         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1038         int socksize;
1039         socklen_t len;
1040
1041         for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1042                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1043                         continue;
1044                 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1045                         fatal("Too many listen sockets. "
1046                             "Enlarge MAX_LISTEN_SOCKS");
1047                 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1048                     ntop, sizeof(ntop), strport, sizeof(strport),
1049                     NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1050                         error("getnameinfo failed: %.100s",
1051                             ssh_gai_strerror(ret));
1052                         continue;
1053                 }
1054                 /* Create socket for listening. */
1055                 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1056                     ai->ai_protocol);
1057                 if (listen_sock < 0) {
1058                         /* kernel may not support ipv6 */
1059                         verbose("socket: %.100s", strerror(errno));
1060                         continue;
1061                 }
1062                 if (set_nonblock(listen_sock) == -1) {
1063                         close(listen_sock);
1064                         continue;
1065                 }
1066                 /*
1067                  * Set socket options.
1068                  * Allow local port reuse in TIME_WAIT.
1069                  */
1070                 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1071                     &on, sizeof(on)) == -1)
1072                         error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1073
1074                 /* Only communicate in IPv6 over AF_INET6 sockets. */
1075                 if (ai->ai_family == AF_INET6)
1076                         sock_set_v6only(listen_sock);
1077
1078                 debug("Bind to port %s on %s.", strport, ntop);
1079
1080                 len = sizeof(socksize);
1081                 getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
1082                 debug("Server TCP RWIN socket size: %d", socksize);
1083                 debug("HPN Buffer Size: %d", options.hpn_buffer_size);
1084
1085                 /* Bind the socket to the desired port. */
1086                 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1087                         error("Bind to port %s on %s failed: %.200s.",
1088                             strport, ntop, strerror(errno));
1089                         close(listen_sock);
1090                         continue;
1091                 }
1092                 listen_socks[num_listen_socks] = listen_sock;
1093                 num_listen_socks++;
1094
1095                 /* Start listening on the port. */
1096                 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1097                         fatal("listen on [%s]:%s: %.100s",
1098                             ntop, strport, strerror(errno));
1099                 logit("Server listening on %s port %s.", ntop, strport);
1100         }
1101         freeaddrinfo(options.listen_addrs);
1102
1103         if (!num_listen_socks)
1104                 fatal("Cannot bind any address.");
1105 }
1106
1107 /*
1108  * The main TCP accept loop. Note that, for the non-debug case, returns
1109  * from this function are in a forked subprocess.
1110  */
1111 static void
1112 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1113 {
1114         fd_set *fdset;
1115         int i, j, ret, maxfd;
1116         int key_used = 0, startups = 0;
1117         int startup_p[2] = { -1 , -1 };
1118         struct sockaddr_storage from;
1119         socklen_t fromlen;
1120         pid_t pid;
1121
1122         /* setup fd set for accept */
1123         fdset = NULL;
1124         maxfd = 0;
1125         for (i = 0; i < num_listen_socks; i++)
1126                 if (listen_socks[i] > maxfd)
1127                         maxfd = listen_socks[i];
1128         /* pipes connected to unauthenticated childs */
1129         startup_pipes = xcalloc(options.max_startups, sizeof(int));
1130         for (i = 0; i < options.max_startups; i++)
1131                 startup_pipes[i] = -1;
1132
1133         /*
1134          * Stay listening for connections until the system crashes or
1135          * the daemon is killed with a signal.
1136          */
1137         for (;;) {
1138                 if (received_sighup)
1139                         sighup_restart();
1140                 if (fdset != NULL)
1141                         xfree(fdset);
1142                 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1143                     sizeof(fd_mask));
1144
1145                 for (i = 0; i < num_listen_socks; i++)
1146                         FD_SET(listen_socks[i], fdset);
1147                 for (i = 0; i < options.max_startups; i++)
1148                         if (startup_pipes[i] != -1)
1149                                 FD_SET(startup_pipes[i], fdset);
1150
1151                 /* Wait in select until there is a connection. */
1152                 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1153                 if (ret < 0 && errno != EINTR)
1154                         error("select: %.100s", strerror(errno));
1155                 if (received_sigterm) {
1156                         logit("Received signal %d; terminating.",
1157                             (int) received_sigterm);
1158                         close_listen_socks();
1159                         unlink(options.pid_file);
1160                         exit(received_sigterm == SIGTERM ? 0 : 255);
1161                 }
1162                 if (key_used && key_do_regen) {
1163                         generate_ephemeral_server_key();
1164                         key_used = 0;
1165                         key_do_regen = 0;
1166                 }
1167                 if (ret < 0)
1168                         continue;
1169
1170                 for (i = 0; i < options.max_startups; i++)
1171                         if (startup_pipes[i] != -1 &&
1172                             FD_ISSET(startup_pipes[i], fdset)) {
1173                                 /*
1174                                  * the read end of the pipe is ready
1175                                  * if the child has closed the pipe
1176                                  * after successful authentication
1177                                  * or if the child has died
1178                                  */
1179                                 close(startup_pipes[i]);
1180                                 startup_pipes[i] = -1;
1181                                 startups--;
1182                         }
1183                 for (i = 0; i < num_listen_socks; i++) {
1184                         if (!FD_ISSET(listen_socks[i], fdset))
1185                                 continue;
1186                         fromlen = sizeof(from);
1187                         *newsock = accept(listen_socks[i],
1188                             (struct sockaddr *)&from, &fromlen);
1189                         if (*newsock < 0) {
1190                                 if (errno != EINTR && errno != EAGAIN &&
1191                                     errno != EWOULDBLOCK)
1192                                         error("accept: %.100s", strerror(errno));
1193                                 continue;
1194                         }
1195                         if (unset_nonblock(*newsock) == -1) {
1196                                 close(*newsock);
1197                                 continue;
1198                         }
1199                         if (drop_connection(startups) == 1) {
1200                                 debug("drop connection #%d", startups);
1201                                 close(*newsock);
1202                                 continue;
1203                         }
1204                         if (pipe(startup_p) == -1) {
1205                                 close(*newsock);
1206                                 continue;
1207                         }
1208
1209                         if (rexec_flag && socketpair(AF_UNIX,
1210                             SOCK_STREAM, 0, config_s) == -1) {
1211                                 error("reexec socketpair: %s",
1212                                     strerror(errno));
1213                                 close(*newsock);
1214                                 close(startup_p[0]);
1215                                 close(startup_p[1]);
1216                                 continue;
1217                         }
1218
1219                         for (j = 0; j < options.max_startups; j++)
1220                                 if (startup_pipes[j] == -1) {
1221                                         startup_pipes[j] = startup_p[0];
1222                                         if (maxfd < startup_p[0])
1223                                                 maxfd = startup_p[0];
1224                                         startups++;
1225                                         break;
1226                                 }
1227
1228                         /*
1229                          * Got connection.  Fork a child to handle it, unless
1230                          * we are in debugging mode.
1231                          */
1232                         if (debug_flag) {
1233                                 /*
1234                                  * In debugging mode.  Close the listening
1235                                  * socket, and start processing the
1236                                  * connection without forking.
1237                                  */
1238                                 debug("Server will not fork when running in debugging mode.");
1239                                 close_listen_socks();
1240                                 *sock_in = *newsock;
1241                                 *sock_out = *newsock;
1242                                 close(startup_p[0]);
1243                                 close(startup_p[1]);
1244                                 startup_pipe = -1;
1245                                 pid = getpid();
1246                                 if (rexec_flag) {
1247                                         send_rexec_state(config_s[0],
1248                                             &cfg);
1249                                         close(config_s[0]);
1250                                 }
1251                                 break;
1252                         }
1253
1254                         /*
1255                          * Normal production daemon.  Fork, and have
1256                          * the child process the connection. The
1257                          * parent continues listening.
1258                          */
1259                         platform_pre_fork();
1260                         if ((pid = fork()) == 0) {
1261                                 /*
1262                                  * Child.  Close the listening and
1263                                  * max_startup sockets.  Start using
1264                                  * the accepted socket. Reinitialize
1265                                  * logging (since our pid has changed).
1266                                  * We break out of the loop to handle
1267                                  * the connection.
1268                                  */
1269                                 platform_post_fork_child();
1270                                 startup_pipe = startup_p[1];
1271                                 close_startup_pipes();
1272                                 close_listen_socks();
1273                                 *sock_in = *newsock;
1274                                 *sock_out = *newsock;
1275                                 log_init(__progname,
1276                                     options.log_level,
1277                                     options.log_facility,
1278                                     log_stderr);
1279                                 if (rexec_flag)
1280                                         close(config_s[0]);
1281                                 break;
1282                         }
1283
1284                         /* Parent.  Stay in the loop. */
1285                         platform_post_fork_parent(pid);
1286                         if (pid < 0)
1287                                 error("fork: %.100s", strerror(errno));
1288                         else
1289                                 debug("Forked child %ld.", (long)pid);
1290
1291                         close(startup_p[1]);
1292
1293                         if (rexec_flag) {
1294                                 send_rexec_state(config_s[0], &cfg);
1295                                 close(config_s[0]);
1296                                 close(config_s[1]);
1297                         }
1298
1299                         /*
1300                          * Mark that the key has been used (it
1301                          * was "given" to the child).
1302                          */
1303                         if ((options.protocol & SSH_PROTO_1) &&
1304                             key_used == 0) {
1305                                 /* Schedule server key regeneration alarm. */
1306                                 signal(SIGALRM, key_regeneration_alarm);
1307                                 alarm(options.key_regeneration_time);
1308                                 key_used = 1;
1309                         }
1310
1311                         close(*newsock);
1312
1313                         /*
1314                          * Ensure that our random state differs
1315                          * from that of the child
1316                          */
1317                         arc4random_stir();
1318                 }
1319
1320                 /* child process check (or debug mode) */
1321                 if (num_listen_socks < 0)
1322                         break;
1323         }
1324 }
1325
1326
1327 /*
1328  * Main program for the daemon.
1329  */
1330 int
1331 main(int ac, char **av)
1332 {
1333         extern char *optarg;
1334         extern int optind;
1335         int opt, i, j, on = 1;
1336         int sock_in = -1, sock_out = -1, newsock = -1;
1337         const char *remote_ip;
1338         char *test_user = NULL, *test_host = NULL, *test_addr = NULL;
1339         int remote_port;
1340         char *line, *p, *cp;
1341         int config_s[2] = { -1 , -1 };
1342         u_int64_t ibytes, obytes;
1343         mode_t new_umask;
1344         Key *key;
1345         Authctxt *authctxt;
1346
1347 #ifdef HAVE_SECUREWARE
1348         (void)set_auth_parameters(ac, av);
1349 #endif
1350         __progname = ssh_get_progname(av[0]);
1351
1352         /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1353         saved_argc = ac;
1354         rexec_argc = ac;
1355         saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1356         for (i = 0; i < ac; i++)
1357                 saved_argv[i] = xstrdup(av[i]);
1358         saved_argv[i] = NULL;
1359
1360 #ifndef HAVE_SETPROCTITLE
1361         /* Prepare for later setproctitle emulation */
1362         compat_init_setproctitle(ac, av);
1363         av = saved_argv;
1364 #endif
1365
1366         if (geteuid() == 0 && setgroups(0, NULL) == -1)
1367                 debug("setgroups(): %.200s", strerror(errno));
1368
1369         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1370         sanitise_stdfd();
1371
1372         /* Initialize configuration options to their default values. */
1373         initialize_server_options(&options);
1374
1375         /* Parse command-line arguments. */
1376         while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeiqrtQRT46")) != -1) {
1377                 switch (opt) {
1378                 case '4':
1379                         options.address_family = AF_INET;
1380                         break;
1381                 case '6':
1382                         options.address_family = AF_INET6;
1383                         break;
1384                 case 'f':
1385                         config_file_name = optarg;
1386                         break;
1387                 case 'c':
1388                         if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1389                                 fprintf(stderr, "too many host certificates.\n");
1390                                 exit(1);
1391                         }
1392                         options.host_cert_files[options.num_host_cert_files++] =
1393                            derelativise_path(optarg);
1394                         break;
1395                 case 'd':
1396                         if (debug_flag == 0) {
1397                                 debug_flag = 1;
1398                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
1399                         } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1400                                 options.log_level++;
1401                         break;
1402                 case 'D':
1403                         no_daemon_flag = 1;
1404                         break;
1405                 case 'e':
1406                         log_stderr = 1;
1407                         break;
1408                 case 'i':
1409                         inetd_flag = 1;
1410                         break;
1411                 case 'r':
1412                         rexec_flag = 0;
1413                         break;
1414                 case 'R':
1415                         rexeced_flag = 1;
1416                         inetd_flag = 1;
1417                         break;
1418                 case 'Q':
1419                         /* ignored */
1420                         break;
1421                 case 'q':
1422                         options.log_level = SYSLOG_LEVEL_QUIET;
1423                         break;
1424                 case 'b':
1425                         options.server_key_bits = (int)strtonum(optarg, 256,
1426                             32768, NULL);
1427                         break;
1428                 case 'p':
1429                         options.ports_from_cmdline = 1;
1430                         if (options.num_ports >= MAX_PORTS) {
1431                                 fprintf(stderr, "too many ports.\n");
1432                                 exit(1);
1433                         }
1434                         options.ports[options.num_ports++] = a2port(optarg);
1435                         if (options.ports[options.num_ports-1] <= 0) {
1436                                 fprintf(stderr, "Bad port number.\n");
1437                                 exit(1);
1438                         }
1439                         break;
1440                 case 'g':
1441                         if ((options.login_grace_time = convtime(optarg)) == -1) {
1442                                 fprintf(stderr, "Invalid login grace time.\n");
1443                                 exit(1);
1444                         }
1445                         break;
1446                 case 'k':
1447                         if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1448                                 fprintf(stderr, "Invalid key regeneration interval.\n");
1449                                 exit(1);
1450                         }
1451                         break;
1452                 case 'h':
1453                         if (options.num_host_key_files >= MAX_HOSTKEYS) {
1454                                 fprintf(stderr, "too many host keys.\n");
1455                                 exit(1);
1456                         }
1457                         options.host_key_files[options.num_host_key_files++] = 
1458                            derelativise_path(optarg);
1459                         break;
1460                 case 't':
1461                         test_flag = 1;
1462                         break;
1463                 case 'T':
1464                         test_flag = 2;
1465                         break;
1466                 case 'C':
1467                         cp = optarg;
1468                         while ((p = strsep(&cp, ",")) && *p != '\0') {
1469                                 if (strncmp(p, "addr=", 5) == 0)
1470                                         test_addr = xstrdup(p + 5);
1471                                 else if (strncmp(p, "host=", 5) == 0)
1472                                         test_host = xstrdup(p + 5);
1473                                 else if (strncmp(p, "user=", 5) == 0)
1474                                         test_user = xstrdup(p + 5);
1475                                 else {
1476                                         fprintf(stderr, "Invalid test "
1477                                             "mode specification %s\n", p);
1478                                         exit(1);
1479                                 }
1480                         }
1481                         break;
1482                 case 'u':
1483                         utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1484                         if (utmp_len > MAXHOSTNAMELEN) {
1485                                 fprintf(stderr, "Invalid utmp length.\n");
1486                                 exit(1);
1487                         }
1488                         break;
1489                 case 'o':
1490                         line = xstrdup(optarg);
1491                         if (process_server_config_line(&options, line,
1492                             "command-line", 0, NULL, NULL, NULL, NULL) != 0)
1493                                 exit(1);
1494                         xfree(line);
1495                         break;
1496                 case '?':
1497                 default:
1498                         usage();
1499                         break;
1500                 }
1501         }
1502         if (rexeced_flag || inetd_flag)
1503                 rexec_flag = 0;
1504         if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1505                 fatal("sshd re-exec requires execution with an absolute path");
1506         if (rexeced_flag)
1507                 closefrom(REEXEC_MIN_FREE_FD);
1508         else
1509                 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1510
1511         OpenSSL_add_all_algorithms();
1512
1513         /*
1514          * Force logging to stderr until we have loaded the private host
1515          * key (unless started from inetd)
1516          */
1517         log_init(__progname,
1518             options.log_level == SYSLOG_LEVEL_NOT_SET ?
1519             SYSLOG_LEVEL_INFO : options.log_level,
1520             options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1521             SYSLOG_FACILITY_AUTH : options.log_facility,
1522             log_stderr || !inetd_flag);
1523
1524         /*
1525          * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1526          * root's environment
1527          */
1528         if (getenv("KRB5CCNAME") != NULL)
1529                 unsetenv("KRB5CCNAME");
1530
1531 #ifdef _UNICOS
1532         /* Cray can define user privs drop all privs now!
1533          * Not needed on PRIV_SU systems!
1534          */
1535         drop_cray_privs();
1536 #endif
1537
1538         sensitive_data.server_key = NULL;
1539         sensitive_data.ssh1_host_key = NULL;
1540         sensitive_data.have_ssh1_key = 0;
1541         sensitive_data.have_ssh2_key = 0;
1542
1543         /*
1544          * If we're doing an extended config test, make sure we have all of
1545          * the parameters we need.  If we're not doing an extended test,
1546          * do not silently ignore connection test params.
1547          */
1548         if (test_flag >= 2 &&
1549            (test_user != NULL || test_host != NULL || test_addr != NULL)
1550             && (test_user == NULL || test_host == NULL || test_addr == NULL))
1551                 fatal("user, host and addr are all required when testing "
1552                    "Match configs");
1553         if (test_flag < 2 && (test_user != NULL || test_host != NULL ||
1554             test_addr != NULL))
1555                 fatal("Config test connection parameter (-C) provided without "
1556                    "test mode (-T)");
1557
1558         /* Fetch our configuration */
1559         buffer_init(&cfg);
1560         if (rexeced_flag)
1561                 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1562         else
1563                 load_server_config(config_file_name, &cfg);
1564
1565         parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1566             &cfg, NULL, NULL, NULL);
1567
1568         seed_rng();
1569
1570         /* Fill in default values for those options not explicitly set. */
1571         fill_default_server_options(&options);
1572
1573         /* challenge-response is implemented via keyboard interactive */
1574         if (options.challenge_response_authentication)
1575                 options.kbd_interactive_authentication = 1;
1576
1577         /* set default channel AF */
1578         channel_set_af(options.address_family);
1579
1580         /* Check that there are no remaining arguments. */
1581         if (optind < ac) {
1582                 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1583                 exit(1);
1584         }
1585
1586         debug("sshd version %.100s", ssh_version_get(options.hpn_disabled));
1587
1588         /* Store privilege separation user for later use if required. */
1589         if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1590                 if (use_privsep || options.kerberos_authentication)
1591                         fatal("Privilege separation user %s does not exist",
1592                             SSH_PRIVSEP_USER);
1593         } else {
1594                 memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1595                 privsep_pw = pwcopy(privsep_pw);
1596                 xfree(privsep_pw->pw_passwd);
1597                 privsep_pw->pw_passwd = xstrdup("*");
1598         }
1599         endpwent();
1600
1601         /* load private host keys */
1602         sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1603             sizeof(Key *));
1604         for (i = 0; i < options.num_host_key_files; i++)
1605                 sensitive_data.host_keys[i] = NULL;
1606
1607         for (i = 0; i < options.num_host_key_files; i++) {
1608                 key = key_load_private(options.host_key_files[i], "", NULL);
1609                 sensitive_data.host_keys[i] = key;
1610                 if (key == NULL) {
1611                         error("Could not load host key: %s",
1612                             options.host_key_files[i]);
1613                         sensitive_data.host_keys[i] = NULL;
1614                         continue;
1615                 }
1616                 switch (key->type) {
1617                 case KEY_RSA1:
1618                         sensitive_data.ssh1_host_key = key;
1619                         sensitive_data.have_ssh1_key = 1;
1620                         break;
1621                 case KEY_RSA:
1622                 case KEY_DSA:
1623                 case KEY_ECDSA:
1624                         sensitive_data.have_ssh2_key = 1;
1625                         break;
1626                 }
1627                 debug("private host key: #%d type %d %s", i, key->type,
1628                     key_type(key));
1629         }
1630         if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1631                 logit("Disabling protocol version 1. Could not load host key");
1632                 options.protocol &= ~SSH_PROTO_1;
1633         }
1634         if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1635                 logit("Disabling protocol version 2. Could not load host key");
1636                 options.protocol &= ~SSH_PROTO_2;
1637         }
1638         if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1639                 logit("sshd: no hostkeys available -- exiting.");
1640                 exit(1);
1641         }
1642
1643         /*
1644          * Load certificates. They are stored in an array at identical
1645          * indices to the public keys that they relate to.
1646          */
1647         sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1648             sizeof(Key *));
1649         for (i = 0; i < options.num_host_key_files; i++)
1650                 sensitive_data.host_certificates[i] = NULL;
1651
1652         for (i = 0; i < options.num_host_cert_files; i++) {
1653                 key = key_load_public(options.host_cert_files[i], NULL);
1654                 if (key == NULL) {
1655                         error("Could not load host certificate: %s",
1656                             options.host_cert_files[i]);
1657                         continue;
1658                 }
1659                 if (!key_is_cert(key)) {
1660                         error("Certificate file is not a certificate: %s",
1661                             options.host_cert_files[i]);
1662                         key_free(key);
1663                         continue;
1664                 }
1665                 /* Find matching private key */
1666                 for (j = 0; j < options.num_host_key_files; j++) {
1667                         if (key_equal_public(key,
1668                             sensitive_data.host_keys[j])) {
1669                                 sensitive_data.host_certificates[j] = key;
1670                                 break;
1671                         }
1672                 }
1673                 if (j >= options.num_host_key_files) {
1674                         error("No matching private key for certificate: %s",
1675                             options.host_cert_files[i]);
1676                         key_free(key);
1677                         continue;
1678                 }
1679                 sensitive_data.host_certificates[j] = key;
1680                 debug("host certificate: #%d type %d %s", j, key->type,
1681                     key_type(key));
1682         }
1683         /* Check certain values for sanity. */
1684         if (options.protocol & SSH_PROTO_1) {
1685                 if (options.server_key_bits < 512 ||
1686                     options.server_key_bits > 32768) {
1687                         fprintf(stderr, "Bad server key size.\n");
1688                         exit(1);
1689                 }
1690                 /*
1691                  * Check that server and host key lengths differ sufficiently. This
1692                  * is necessary to make double encryption work with rsaref. Oh, I
1693                  * hate software patents. I dont know if this can go? Niels
1694                  */
1695                 if (options.server_key_bits >
1696                     BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1697                     SSH_KEY_BITS_RESERVED && options.server_key_bits <
1698                     BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1699                     SSH_KEY_BITS_RESERVED) {
1700                         options.server_key_bits =
1701                             BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1702                             SSH_KEY_BITS_RESERVED;
1703                         debug("Forcing server key to %d bits to make it differ from host key.",
1704                             options.server_key_bits);
1705                 }
1706         }
1707
1708         if (use_privsep) {
1709                 struct stat st;
1710
1711                 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1712                     (S_ISDIR(st.st_mode) == 0))
1713                         fatal("Missing privilege separation directory: %s",
1714                             _PATH_PRIVSEP_CHROOT_DIR);
1715
1716 #ifdef HAVE_CYGWIN
1717                 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1718                     (st.st_uid != getuid () ||
1719                     (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1720 #else
1721                 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1722 #endif
1723                         fatal("%s must be owned by root and not group or "
1724                             "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1725         }
1726
1727         if (test_flag > 1) {
1728                 if (test_user != NULL && test_addr != NULL && test_host != NULL)
1729                         parse_server_match_config(&options, test_user,
1730                             test_host, test_addr);
1731                 dump_config(&options);
1732         }
1733
1734         /* Configuration looks good, so exit if in test mode. */
1735         if (test_flag)
1736                 exit(0);
1737
1738         /*
1739          * Clear out any supplemental groups we may have inherited.  This
1740          * prevents inadvertent creation of files with bad modes (in the
1741          * portable version at least, it's certainly possible for PAM
1742          * to create a file, and we can't control the code in every
1743          * module which might be used).
1744          */
1745         if (setgroups(0, NULL) < 0)
1746                 debug("setgroups() failed: %.200s", strerror(errno));
1747
1748         if (rexec_flag) {
1749                 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1750                 for (i = 0; i < rexec_argc; i++) {
1751                         debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1752                         rexec_argv[i] = saved_argv[i];
1753                 }
1754                 rexec_argv[rexec_argc] = "-R";
1755                 rexec_argv[rexec_argc + 1] = NULL;
1756         }
1757
1758         /* Ensure that umask disallows at least group and world write */
1759         new_umask = umask(0077) | 0022;
1760         (void) umask(new_umask);
1761
1762         /* Initialize the log (it is reinitialized below in case we forked). */
1763         if (debug_flag && (!inetd_flag || rexeced_flag))
1764                 log_stderr = 1;
1765         log_init(__progname, options.log_level, options.log_facility, log_stderr);
1766
1767         /*
1768          * If not in debugging mode, and not started from inetd, disconnect
1769          * from the controlling terminal, and fork.  The original process
1770          * exits.
1771          */
1772         if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1773 #ifdef TIOCNOTTY
1774                 int fd;
1775 #endif /* TIOCNOTTY */
1776                 if (daemon(0, 0) < 0)
1777                         fatal("daemon() failed: %.200s", strerror(errno));
1778
1779                 /* Disconnect from the controlling tty. */
1780 #ifdef TIOCNOTTY
1781                 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1782                 if (fd >= 0) {
1783                         (void) ioctl(fd, TIOCNOTTY, NULL);
1784                         close(fd);
1785                 }
1786 #endif /* TIOCNOTTY */
1787         }
1788         /* Reinitialize the log (because of the fork above). */
1789         log_init(__progname, options.log_level, options.log_facility, log_stderr);
1790
1791         /* Avoid killing the process in high-pressure swapping environments. */
1792         if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
1793                 debug("madvise(): %.200s", strerror(errno));
1794
1795         /* Initialize the random number generator. */
1796         arc4random_stir();
1797
1798         /* Chdir to the root directory so that the current disk can be
1799            unmounted if desired. */
1800         chdir("/");
1801
1802         /* ignore SIGPIPE */
1803         signal(SIGPIPE, SIG_IGN);
1804
1805         /* Get a connection, either from inetd or a listening TCP socket */
1806         if (inetd_flag) {
1807                 server_accept_inetd(&sock_in, &sock_out);
1808         } else {
1809                 platform_pre_listen();
1810                 server_listen();
1811
1812                 if (options.protocol & SSH_PROTO_1)
1813                         generate_ephemeral_server_key();
1814
1815                 signal(SIGHUP, sighup_handler);
1816                 signal(SIGCHLD, main_sigchld_handler);
1817                 signal(SIGTERM, sigterm_handler);
1818                 signal(SIGQUIT, sigterm_handler);
1819
1820                 /*
1821                  * Write out the pid file after the sigterm handler
1822                  * is setup and the listen sockets are bound
1823                  */
1824                 if (!debug_flag) {
1825                         FILE *f = fopen(options.pid_file, "w");
1826
1827                         if (f == NULL) {
1828                                 error("Couldn't create pid file \"%s\": %s",
1829                                     options.pid_file, strerror(errno));
1830                         } else {
1831                                 fprintf(f, "%ld\n", (long) getpid());
1832                                 fclose(f);
1833                         }
1834                 }
1835
1836                 /* Accept a connection and return in a forked child */
1837                 server_accept_loop(&sock_in, &sock_out,
1838                     &newsock, config_s);
1839         }
1840
1841         /* This is the child processing a new connection. */
1842         setproctitle("%s", "[accepted]");
1843
1844         /*
1845          * Create a new session and process group since the 4.4BSD
1846          * setlogin() affects the entire process group.  We don't
1847          * want the child to be able to affect the parent.
1848          */
1849 #if !defined(SSHD_ACQUIRES_CTTY)
1850         /*
1851          * If setsid is called, on some platforms sshd will later acquire a
1852          * controlling terminal which will result in "could not set
1853          * controlling tty" errors.
1854          */
1855         if (!debug_flag && !inetd_flag && setsid() < 0)
1856                 error("setsid: %.100s", strerror(errno));
1857 #endif
1858
1859         if (rexec_flag) {
1860                 int fd;
1861
1862                 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1863                     sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1864                 dup2(newsock, STDIN_FILENO);
1865                 dup2(STDIN_FILENO, STDOUT_FILENO);
1866                 if (startup_pipe == -1)
1867                         close(REEXEC_STARTUP_PIPE_FD);
1868                 else
1869                         dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1870
1871                 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1872                 close(config_s[1]);
1873                 if (startup_pipe != -1)
1874                         close(startup_pipe);
1875
1876                 execv(rexec_argv[0], rexec_argv);
1877
1878                 /* Reexec has failed, fall back and continue */
1879                 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1880                 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1881                 log_init(__progname, options.log_level,
1882                     options.log_facility, log_stderr);
1883
1884                 /* Clean up fds */
1885                 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1886                 close(config_s[1]);
1887                 close(REEXEC_CONFIG_PASS_FD);
1888                 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1889                 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1890                         dup2(fd, STDIN_FILENO);
1891                         dup2(fd, STDOUT_FILENO);
1892                         if (fd > STDERR_FILENO)
1893                                 close(fd);
1894                 }
1895                 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1896                     sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1897         }
1898
1899         /* Executed child processes don't need these. */
1900         fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1901         fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1902
1903         /*
1904          * Disable the key regeneration alarm.  We will not regenerate the
1905          * key since we are no longer in a position to give it to anyone. We
1906          * will not restart on SIGHUP since it no longer makes sense.
1907          */
1908         alarm(0);
1909         signal(SIGALRM, SIG_DFL);
1910         signal(SIGHUP, SIG_DFL);
1911         signal(SIGTERM, SIG_DFL);
1912         signal(SIGQUIT, SIG_DFL);
1913         signal(SIGCHLD, SIG_DFL);
1914         signal(SIGINT, SIG_DFL);
1915
1916 #ifdef __FreeBSD__
1917         /*
1918          * Initialize the resolver.  This may not happen automatically
1919          * before privsep chroot().
1920          */
1921         if ((_res.options & RES_INIT) == 0) {
1922                 debug("res_init()");
1923                 res_init();
1924         }
1925 #ifdef GSSAPI
1926         /*
1927          * Force GSS-API to parse its configuration and load any
1928          * mechanism plugins.
1929          */
1930         {
1931                 gss_OID_set mechs;
1932                 OM_uint32 minor_status;
1933                 gss_indicate_mechs(&minor_status, &mechs);
1934                 gss_release_oid_set(&minor_status, &mechs);
1935         }
1936 #endif
1937 #endif
1938
1939         /*
1940          * Register our connection.  This turns encryption off because we do
1941          * not have a key.
1942          */
1943         packet_set_connection(sock_in, sock_out);
1944         packet_set_server();
1945
1946         /* Set SO_KEEPALIVE if requested. */
1947         if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1948             setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1949                 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1950
1951         if ((remote_port = get_remote_port()) < 0) {
1952                 debug("get_remote_port failed");
1953                 cleanup_exit(255);
1954         }
1955
1956         /*
1957          * We use get_canonical_hostname with usedns = 0 instead of
1958          * get_remote_ipaddr here so IP options will be checked.
1959          */
1960         (void) get_canonical_hostname(0);
1961         /*
1962          * The rest of the code depends on the fact that
1963          * get_remote_ipaddr() caches the remote ip, even if
1964          * the socket goes away.
1965          */
1966         remote_ip = get_remote_ipaddr();
1967
1968 #ifdef SSH_AUDIT_EVENTS
1969         audit_connection_from(remote_ip, remote_port);
1970 #endif
1971 #ifdef LIBWRAP
1972         allow_severity = options.log_facility|LOG_INFO;
1973         deny_severity = options.log_facility|LOG_WARNING;
1974         /* Check whether logins are denied from this host. */
1975         if (packet_connection_is_on_socket()) {
1976                 struct request_info req;
1977
1978                 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1979                 fromhost(&req);
1980
1981                 if (!hosts_access(&req)) {
1982                         debug("Connection refused by tcp wrapper");
1983                         refuse(&req);
1984                         /* NOTREACHED */
1985                         fatal("libwrap refuse returns");
1986                 }
1987         }
1988 #endif /* LIBWRAP */
1989
1990         /* Log the connection. */
1991         verbose("Connection from %.500s port %d", remote_ip, remote_port);
1992
1993         /* Set HPN options for the child. */
1994         channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1995
1996         /*
1997          * We don't want to listen forever unless the other side
1998          * successfully authenticates itself.  So we set up an alarm which is
1999          * cleared after successful authentication.  A limit of zero
2000          * indicates no limit. Note that we don't set the alarm in debugging
2001          * mode; it is just annoying to have the server exit just when you
2002          * are about to discover the bug.
2003          */
2004         signal(SIGALRM, grace_alarm_handler);
2005         if (!debug_flag)
2006                 alarm(options.login_grace_time);
2007
2008         sshd_exchange_identification(sock_in, sock_out);
2009
2010         /* In inetd mode, generate ephemeral key only for proto 1 connections */
2011         if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2012                 generate_ephemeral_server_key();
2013
2014         packet_set_nonblocking();
2015
2016         /* allocate authentication context */
2017         authctxt = xcalloc(1, sizeof(*authctxt));
2018
2019         authctxt->loginmsg = &loginmsg;
2020
2021         /* XXX global for cleanup, access from other modules */
2022         the_authctxt = authctxt;
2023
2024         /* prepare buffer to collect messages to display to user after login */
2025         buffer_init(&loginmsg);
2026         auth_debug_reset();
2027
2028         if (use_privsep)
2029                 if (privsep_preauth(authctxt) == 1)
2030                         goto authenticated;
2031
2032         /* perform the key exchange */
2033         /* authenticate user and start session */
2034         if (compat20) {
2035                 do_ssh2_kex();
2036                 do_authentication2(authctxt);
2037         } else {
2038                 do_ssh1_kex();
2039                 do_authentication(authctxt);
2040         }
2041         /*
2042          * If we use privilege separation, the unprivileged child transfers
2043          * the current keystate and exits
2044          */
2045         if (use_privsep) {
2046                 mm_send_keystate(pmonitor);
2047                 exit(0);
2048         }
2049
2050  authenticated:
2051         /*
2052          * Cancel the alarm we set to limit the time taken for
2053          * authentication.
2054          */
2055         alarm(0);
2056         signal(SIGALRM, SIG_DFL);
2057         authctxt->authenticated = 1;
2058         if (startup_pipe != -1) {
2059                 close(startup_pipe);
2060                 startup_pipe = -1;
2061         }
2062
2063 #ifdef SSH_AUDIT_EVENTS
2064         audit_event(SSH_AUTH_SUCCESS);
2065 #endif
2066
2067 #ifdef GSSAPI
2068         if (options.gss_authentication) {
2069                 temporarily_use_uid(authctxt->pw);
2070                 ssh_gssapi_storecreds();
2071                 restore_uid();
2072         }
2073 #endif
2074 #ifdef USE_PAM
2075         if (options.use_pam) {
2076                 do_pam_setcred(1);
2077                 do_pam_session();
2078         }
2079 #endif
2080
2081         /*
2082          * In privilege separation, we fork another child and prepare
2083          * file descriptor passing.
2084          */
2085         if (use_privsep) {
2086                 privsep_postauth(authctxt);
2087                 /* the monitor process [priv] will not return */
2088                 if (!compat20)
2089                         destroy_sensitive_data();
2090         }
2091
2092         packet_set_timeout(options.client_alive_interval,
2093             options.client_alive_count_max);
2094
2095         /* Start session. */
2096         do_authenticated(authctxt);
2097
2098         /* The connection has been terminated. */
2099         packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
2100         packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
2101         verbose("Transferred: sent %llu, received %llu bytes",
2102             (unsigned long long)obytes, (unsigned long long)ibytes);
2103
2104         verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2105
2106 #ifdef USE_PAM
2107         if (options.use_pam)
2108                 finish_pam();
2109 #endif /* USE_PAM */
2110
2111 #ifdef SSH_AUDIT_EVENTS
2112         PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2113 #endif
2114
2115         packet_close();
2116
2117         if (use_privsep)
2118                 mm_terminate();
2119
2120         exit(0);
2121 }
2122
2123 /*
2124  * Decrypt session_key_int using our private server key and private host key
2125  * (key with larger modulus first).
2126  */
2127 int
2128 ssh1_session_key(BIGNUM *session_key_int)
2129 {
2130         int rsafail = 0;
2131
2132         if (BN_cmp(sensitive_data.server_key->rsa->n,
2133             sensitive_data.ssh1_host_key->rsa->n) > 0) {
2134                 /* Server key has bigger modulus. */
2135                 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2136                     BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2137                     SSH_KEY_BITS_RESERVED) {
2138                         fatal("do_connection: %s: "
2139                             "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2140                             get_remote_ipaddr(),
2141                             BN_num_bits(sensitive_data.server_key->rsa->n),
2142                             BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2143                             SSH_KEY_BITS_RESERVED);
2144                 }
2145                 if (rsa_private_decrypt(session_key_int, session_key_int,
2146                     sensitive_data.server_key->rsa) <= 0)
2147                         rsafail++;
2148                 if (rsa_private_decrypt(session_key_int, session_key_int,
2149                     sensitive_data.ssh1_host_key->rsa) <= 0)
2150                         rsafail++;
2151         } else {
2152                 /* Host key has bigger modulus (or they are equal). */
2153                 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2154                     BN_num_bits(sensitive_data.server_key->rsa->n) +
2155                     SSH_KEY_BITS_RESERVED) {
2156                         fatal("do_connection: %s: "
2157                             "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2158                             get_remote_ipaddr(),
2159                             BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2160                             BN_num_bits(sensitive_data.server_key->rsa->n),
2161                             SSH_KEY_BITS_RESERVED);
2162                 }
2163                 if (rsa_private_decrypt(session_key_int, session_key_int,
2164                     sensitive_data.ssh1_host_key->rsa) < 0)
2165                         rsafail++;
2166                 if (rsa_private_decrypt(session_key_int, session_key_int,
2167                     sensitive_data.server_key->rsa) < 0)
2168                         rsafail++;
2169         }
2170         return (rsafail);
2171 }
2172 /*
2173  * SSH1 key exchange
2174  */
2175 static void
2176 do_ssh1_kex(void)
2177 {
2178         int i, len;
2179         int rsafail = 0;
2180         BIGNUM *session_key_int;
2181         u_char session_key[SSH_SESSION_KEY_LENGTH];
2182         u_char cookie[8];
2183         u_int cipher_type, auth_mask, protocol_flags;
2184
2185         /*
2186          * Generate check bytes that the client must send back in the user
2187          * packet in order for it to be accepted; this is used to defy ip
2188          * spoofing attacks.  Note that this only works against somebody
2189          * doing IP spoofing from a remote machine; any machine on the local
2190          * network can still see outgoing packets and catch the random
2191          * cookie.  This only affects rhosts authentication, and this is one
2192          * of the reasons why it is inherently insecure.
2193          */
2194         arc4random_buf(cookie, sizeof(cookie));
2195
2196         /*
2197          * Send our public key.  We include in the packet 64 bits of random
2198          * data that must be matched in the reply in order to prevent IP
2199          * spoofing.
2200          */
2201         packet_start(SSH_SMSG_PUBLIC_KEY);
2202         for (i = 0; i < 8; i++)
2203                 packet_put_char(cookie[i]);
2204
2205         /* Store our public server RSA key. */
2206         packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2207         packet_put_bignum(sensitive_data.server_key->rsa->e);
2208         packet_put_bignum(sensitive_data.server_key->rsa->n);
2209
2210         /* Store our public host RSA key. */
2211         packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2212         packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2213         packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2214
2215         /* Put protocol flags. */
2216         packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2217
2218         /* Declare which ciphers we support. */
2219         packet_put_int(cipher_mask_ssh1(0));
2220
2221         /* Declare supported authentication types. */
2222         auth_mask = 0;
2223         if (options.rhosts_rsa_authentication)
2224                 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2225         if (options.rsa_authentication)
2226                 auth_mask |= 1 << SSH_AUTH_RSA;
2227         if (options.challenge_response_authentication == 1)
2228                 auth_mask |= 1 << SSH_AUTH_TIS;
2229         if (options.password_authentication)
2230                 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2231         packet_put_int(auth_mask);
2232
2233         /* Send the packet and wait for it to be sent. */
2234         packet_send();
2235         packet_write_wait();
2236
2237         debug("Sent %d bit server key and %d bit host key.",
2238             BN_num_bits(sensitive_data.server_key->rsa->n),
2239             BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2240
2241         /* Read clients reply (cipher type and session key). */
2242         packet_read_expect(SSH_CMSG_SESSION_KEY);
2243
2244         /* Get cipher type and check whether we accept this. */
2245         cipher_type = packet_get_char();
2246
2247         if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2248                 packet_disconnect("Warning: client selects unsupported cipher.");
2249
2250         /* Get check bytes from the packet.  These must match those we
2251            sent earlier with the public key packet. */
2252         for (i = 0; i < 8; i++)
2253                 if (cookie[i] != packet_get_char())
2254                         packet_disconnect("IP Spoofing check bytes do not match.");
2255
2256         debug("Encryption type: %.200s", cipher_name(cipher_type));
2257
2258         /* Get the encrypted integer. */
2259         if ((session_key_int = BN_new()) == NULL)
2260                 fatal("do_ssh1_kex: BN_new failed");
2261         packet_get_bignum(session_key_int);
2262
2263         protocol_flags = packet_get_int();
2264         packet_set_protocol_flags(protocol_flags);
2265         packet_check_eom();
2266
2267         /* Decrypt session_key_int using host/server keys */
2268         rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2269
2270         /*
2271          * Extract session key from the decrypted integer.  The key is in the
2272          * least significant 256 bits of the integer; the first byte of the
2273          * key is in the highest bits.
2274          */
2275         if (!rsafail) {
2276                 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2277                 len = BN_num_bytes(session_key_int);
2278                 if (len < 0 || (u_int)len > sizeof(session_key)) {
2279                         error("do_ssh1_kex: bad session key len from %s: "
2280                             "session_key_int %d > sizeof(session_key) %lu",
2281                             get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2282                         rsafail++;
2283                 } else {
2284                         memset(session_key, 0, sizeof(session_key));
2285                         BN_bn2bin(session_key_int,
2286                             session_key + sizeof(session_key) - len);
2287
2288                         derive_ssh1_session_id(
2289                             sensitive_data.ssh1_host_key->rsa->n,
2290                             sensitive_data.server_key->rsa->n,
2291                             cookie, session_id);
2292                         /*
2293                          * Xor the first 16 bytes of the session key with the
2294                          * session id.
2295                          */
2296                         for (i = 0; i < 16; i++)
2297                                 session_key[i] ^= session_id[i];
2298                 }
2299         }
2300         if (rsafail) {
2301                 int bytes = BN_num_bytes(session_key_int);
2302                 u_char *buf = xmalloc(bytes);
2303                 MD5_CTX md;
2304
2305                 logit("do_connection: generating a fake encryption key");
2306                 BN_bn2bin(session_key_int, buf);
2307                 MD5_Init(&md);
2308                 MD5_Update(&md, buf, bytes);
2309                 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2310                 MD5_Final(session_key, &md);
2311                 MD5_Init(&md);
2312                 MD5_Update(&md, session_key, 16);
2313                 MD5_Update(&md, buf, bytes);
2314                 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2315                 MD5_Final(session_key + 16, &md);
2316                 memset(buf, 0, bytes);
2317                 xfree(buf);
2318                 for (i = 0; i < 16; i++)
2319                         session_id[i] = session_key[i] ^ session_key[i + 16];
2320         }
2321         /* Destroy the private and public keys. No longer. */
2322         destroy_sensitive_data();
2323
2324         if (use_privsep)
2325                 mm_ssh1_session_id(session_id);
2326
2327         /* Destroy the decrypted integer.  It is no longer needed. */
2328         BN_clear_free(session_key_int);
2329
2330         /* Set the session key.  From this on all communications will be encrypted. */
2331         packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2332
2333         /* Destroy our copy of the session key.  It is no longer needed. */
2334         memset(session_key, 0, sizeof(session_key));
2335
2336         debug("Received session key; encryption turned on.");
2337
2338         /* Send an acknowledgment packet.  Note that this packet is sent encrypted. */
2339         packet_start(SSH_SMSG_SUCCESS);
2340         packet_send();
2341         packet_write_wait();
2342 }
2343
2344 /*
2345  * SSH2 key exchange: diffie-hellman-group1-sha1
2346  */
2347 static void
2348 do_ssh2_kex(void)
2349 {
2350         Kex *kex;
2351
2352         if (options.ciphers != NULL) {
2353                 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2354                 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2355 #ifdef  NONE_CIPHER_ENABLED
2356         } else if (options.none_enabled == 1) {
2357                 debug ("WARNING: None cipher enabled");
2358                 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2359                 myproposal[PROPOSAL_ENC_ALGS_STOC] = KEX_ENCRYPT_INCLUDE_NONE;
2360 #endif
2361         }
2362         myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2363             compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2364         myproposal[PROPOSAL_ENC_ALGS_STOC] =
2365             compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2366
2367         if (options.macs != NULL) {
2368                 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2369                 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2370         }
2371         if (options.compression == COMP_NONE) {
2372                 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2373                 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2374         } else if (options.compression == COMP_DELAYED) {
2375                 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2376                 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2377         }
2378         if (options.kex_algorithms != NULL)
2379                 myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
2380
2381         myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2382
2383         /* start key exchange */
2384         kex = kex_setup(myproposal);
2385         kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2386         kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2387         kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2388         kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2389         kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2390         kex->server = 1;
2391         kex->client_version_string=client_version_string;
2392         kex->server_version_string=server_version_string;
2393         kex->load_host_public_key=&get_hostkey_public_by_type;
2394         kex->load_host_private_key=&get_hostkey_private_by_type;
2395         kex->host_key_index=&get_hostkey_index;
2396
2397         xxx_kex = kex;
2398
2399         dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2400
2401         session_id2 = kex->session_id;
2402         session_id2_len = kex->session_id_len;
2403
2404 #ifdef DEBUG_KEXDH
2405         /* send 1st encrypted/maced/compressed message */
2406         packet_start(SSH2_MSG_IGNORE);
2407         packet_put_cstring("markus");
2408         packet_send();
2409         packet_write_wait();
2410 #endif
2411         debug("KEX done");
2412 }
2413
2414 /* server specific fatal cleanup */
2415 void
2416 cleanup_exit(int i)
2417 {
2418         if (the_authctxt)
2419                 do_cleanup(the_authctxt);
2420 #ifdef SSH_AUDIT_EVENTS
2421         /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2422         if (!use_privsep || mm_is_monitor())
2423                 audit_event(SSH_CONNECTION_ABANDON);
2424 #endif
2425         _exit(i);
2426 }