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