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