OSDN Git Service

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