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