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