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