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