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