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