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