Upgrade build for OpenSSH 5.1p1.
[dragonfly.git] / crypto / openssh-5 / sshd.c
blob3c9be53cb9e0054888a401fe16e82b27be00f8de
1 /* $OpenBSD: sshd.c,v 1.364 2008/07/10 18:08:11 markus 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.
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".
18 * SSH2 implementation:
19 * Privilege Separation:
21 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
22 * Copyright (c) 2002 Niels Provos. All rights reserved.
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.
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.
45 #include "includes.h"
47 #include <sys/types.h>
48 #include <sys/ioctl.h>
49 #include <sys/socket.h>
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
52 #endif
53 #ifdef HAVE_SYS_TIME_H
54 # include <sys/time.h>
55 #endif
56 #include "openbsd-compat/sys-tree.h"
57 #include "openbsd-compat/sys-queue.h"
58 #include <sys/wait.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <netdb.h>
63 #ifdef HAVE_PATHS_H
64 #include <paths.h>
65 #endif
66 #include <grp.h>
67 #include <pwd.h>
68 #include <signal.h>
69 #include <stdarg.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <unistd.h>
75 #include <openssl/dh.h>
76 #include <openssl/bn.h>
77 #include <openssl/md5.h>
78 #include <openssl/rand.h>
79 #include "openbsd-compat/openssl-compat.h"
81 #ifdef HAVE_SECUREWARE
82 #include <sys/security.h>
83 #include <prot.h>
84 #endif
86 #include <resolv.h>
87 #include "xmalloc.h"
88 #include "ssh.h"
89 #include "ssh1.h"
90 #include "ssh2.h"
91 #include "rsa.h"
92 #include "sshpty.h"
93 #include "packet.h"
94 #include "log.h"
95 #include "buffer.h"
96 #include "servconf.h"
97 #include "uidswap.h"
98 #include "compat.h"
99 #include "cipher.h"
100 #include "key.h"
101 #include "kex.h"
102 #include "dh.h"
103 #include "myproposal.h"
104 #include "authfile.h"
105 #include "pathnames.h"
106 #include "atomicio.h"
107 #include "canohost.h"
108 #include "hostfile.h"
109 #include "auth.h"
110 #include "misc.h"
111 #include "msg.h"
112 #include "dispatch.h"
113 #include "channels.h"
114 #include "session.h"
115 #include "monitor_mm.h"
116 #include "monitor.h"
117 #ifdef GSSAPI
118 #include "ssh-gss.h"
119 #endif
120 #include "monitor_wrap.h"
121 #include "monitor_fdpass.h"
122 #include "version.h"
124 #ifdef LIBWRAP
125 #include <tcpd.h>
126 #include <syslog.h>
127 int allow_severity;
128 int deny_severity;
129 #endif /* LIBWRAP */
131 #ifndef O_NOCTTY
132 #define O_NOCTTY 0
133 #endif
135 /* Re-exec fds */
136 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
137 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
138 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
139 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
141 extern char *__progname;
143 /* Server configuration options. */
144 ServerOptions options;
146 /* Name of the server configuration file. */
147 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
150 * Debug mode flag. This can be set on the command line. If debug
151 * mode is enabled, extra debugging output will be sent to the system
152 * log, the daemon will not go to background, and will exit after processing
153 * the first connection.
155 int debug_flag = 0;
157 /* Flag indicating that the daemon should only test the configuration and keys. */
158 int test_flag = 0;
160 /* Flag indicating that the daemon is being started from inetd. */
161 int inetd_flag = 0;
163 /* Flag indicating that sshd should not detach and become a daemon. */
164 int no_daemon_flag = 0;
166 /* debug goes to stderr unless inetd_flag is set */
167 int log_stderr = 0;
169 /* Saved arguments to main(). */
170 char **saved_argv;
171 int saved_argc;
173 /* re-exec */
174 int rexeced_flag = 0;
175 int rexec_flag = 1;
176 int rexec_argc = 0;
177 char **rexec_argv;
180 * The sockets that the server is listening; this is used in the SIGHUP
181 * signal handler.
183 #define MAX_LISTEN_SOCKS 16
184 int listen_socks[MAX_LISTEN_SOCKS];
185 int num_listen_socks = 0;
188 * the client's version string, passed by sshd2 in compat mode. if != NULL,
189 * sshd will skip the version-number exchange
191 char *client_version_string = NULL;
192 char *server_version_string = NULL;
194 /* for rekeying XXX fixme */
195 Kex *xxx_kex;
198 * Any really sensitive data in the application is contained in this
199 * structure. The idea is that this structure could be locked into memory so
200 * that the pages do not get written into swap. However, there are some
201 * problems. The private key contains BIGNUMs, and we do not (in principle)
202 * have access to the internals of them, and locking just the structure is
203 * not very useful. Currently, memory locking is not implemented.
205 struct {
206 Key *server_key; /* ephemeral server key */
207 Key *ssh1_host_key; /* ssh1 host key */
208 Key **host_keys; /* all private host keys */
209 int have_ssh1_key;
210 int have_ssh2_key;
211 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
212 } sensitive_data;
215 * Flag indicating whether the RSA server key needs to be regenerated.
216 * Is set in the SIGALRM handler and cleared when the key is regenerated.
218 static volatile sig_atomic_t key_do_regen = 0;
220 /* This is set to true when a signal is received. */
221 static volatile sig_atomic_t received_sighup = 0;
222 static volatile sig_atomic_t received_sigterm = 0;
224 /* session identifier, used by RSA-auth */
225 u_char session_id[16];
227 /* same for ssh2 */
228 u_char *session_id2 = NULL;
229 u_int session_id2_len = 0;
231 /* record remote hostname or ip */
232 u_int utmp_len = MAXHOSTNAMELEN;
234 /* options.max_startup sized array of fd ints */
235 int *startup_pipes = NULL;
236 int startup_pipe; /* in child */
238 /* variables used for privilege separation */
239 int use_privsep = -1;
240 struct monitor *pmonitor = NULL;
242 /* global authentication context */
243 Authctxt *the_authctxt = NULL;
245 /* sshd_config buffer */
246 Buffer cfg;
248 /* message to be displayed after login */
249 Buffer loginmsg;
251 /* Unprivileged user */
252 struct passwd *privsep_pw = NULL;
254 /* Prototypes for various functions defined later in this file. */
255 void destroy_sensitive_data(void);
256 void demote_sensitive_data(void);
258 static void do_ssh1_kex(void);
259 static void do_ssh2_kex(void);
262 * Close all listening sockets
264 static void
265 close_listen_socks(void)
267 int i;
269 for (i = 0; i < num_listen_socks; i++)
270 close(listen_socks[i]);
271 num_listen_socks = -1;
274 static void
275 close_startup_pipes(void)
277 int i;
279 if (startup_pipes)
280 for (i = 0; i < options.max_startups; i++)
281 if (startup_pipes[i] != -1)
282 close(startup_pipes[i]);
286 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
287 * the effect is to reread the configuration file (and to regenerate
288 * the server key).
291 /*ARGSUSED*/
292 static void
293 sighup_handler(int sig)
295 int save_errno = errno;
297 received_sighup = 1;
298 signal(SIGHUP, sighup_handler);
299 errno = save_errno;
303 * Called from the main program after receiving SIGHUP.
304 * Restarts the server.
306 static void
307 sighup_restart(void)
309 logit("Received SIGHUP; restarting.");
310 close_listen_socks();
311 close_startup_pipes();
312 alarm(0); /* alarm timer persists across exec */
313 execv(saved_argv[0], saved_argv);
314 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
315 strerror(errno));
316 exit(1);
320 * Generic signal handler for terminating signals in the master daemon.
322 /*ARGSUSED*/
323 static void
324 sigterm_handler(int sig)
326 received_sigterm = sig;
330 * SIGCHLD handler. This is called whenever a child dies. This will then
331 * reap any zombies left by exited children.
333 /*ARGSUSED*/
334 static void
335 main_sigchld_handler(int sig)
337 int save_errno = errno;
338 pid_t pid;
339 int status;
341 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
342 (pid < 0 && errno == EINTR))
345 signal(SIGCHLD, main_sigchld_handler);
346 errno = save_errno;
350 * Signal handler for the alarm after the login grace period has expired.
352 /*ARGSUSED*/
353 static void
354 grace_alarm_handler(int sig)
356 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
357 kill(pmonitor->m_pid, SIGALRM);
359 /* Log error and exit. */
360 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
364 * Signal handler for the key regeneration alarm. Note that this
365 * alarm only occurs in the daemon waiting for connections, and it does not
366 * do anything with the private key or random state before forking.
367 * Thus there should be no concurrency control/asynchronous execution
368 * problems.
370 static void
371 generate_ephemeral_server_key(void)
373 verbose("Generating %s%d bit RSA key.",
374 sensitive_data.server_key ? "new " : "", options.server_key_bits);
375 if (sensitive_data.server_key != NULL)
376 key_free(sensitive_data.server_key);
377 sensitive_data.server_key = key_generate(KEY_RSA1,
378 options.server_key_bits);
379 verbose("RSA key generation complete.");
381 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
382 arc4random_stir();
385 /*ARGSUSED*/
386 static void
387 key_regeneration_alarm(int sig)
389 int save_errno = errno;
391 signal(SIGALRM, SIG_DFL);
392 errno = save_errno;
393 key_do_regen = 1;
396 static void
397 sshd_exchange_identification(int sock_in, int sock_out)
399 u_int i;
400 int mismatch;
401 int remote_major, remote_minor;
402 int major, minor;
403 char *s, *newline = "\n";
404 char buf[256]; /* Must not be larger than remote_version. */
405 char remote_version[256]; /* Must be at least as big as buf. */
407 if ((options.protocol & SSH_PROTO_1) &&
408 (options.protocol & SSH_PROTO_2)) {
409 major = PROTOCOL_MAJOR_1;
410 minor = 99;
411 } else if (options.protocol & SSH_PROTO_2) {
412 major = PROTOCOL_MAJOR_2;
413 minor = PROTOCOL_MINOR_2;
414 newline = "\r\n";
415 } else {
416 major = PROTOCOL_MAJOR_1;
417 minor = PROTOCOL_MINOR_1;
419 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s%s", major, minor,
420 SSH_VERSION, newline);
421 server_version_string = xstrdup(buf);
423 /* Send our protocol version identification. */
424 if (atomicio(vwrite, sock_out, server_version_string,
425 strlen(server_version_string))
426 != strlen(server_version_string)) {
427 logit("Could not write ident string to %s", get_remote_ipaddr());
428 cleanup_exit(255);
431 /* Read other sides version identification. */
432 memset(buf, 0, sizeof(buf));
433 for (i = 0; i < sizeof(buf) - 1; i++) {
434 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
435 logit("Did not receive identification string from %s",
436 get_remote_ipaddr());
437 cleanup_exit(255);
439 if (buf[i] == '\r') {
440 buf[i] = 0;
441 /* Kludge for F-Secure Macintosh < 1.0.2 */
442 if (i == 12 &&
443 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
444 break;
445 continue;
447 if (buf[i] == '\n') {
448 buf[i] = 0;
449 break;
452 buf[sizeof(buf) - 1] = 0;
453 client_version_string = xstrdup(buf);
456 * Check that the versions match. In future this might accept
457 * several versions and set appropriate flags to handle them.
459 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
460 &remote_major, &remote_minor, remote_version) != 3) {
461 s = "Protocol mismatch.\n";
462 (void) atomicio(vwrite, sock_out, s, strlen(s));
463 close(sock_in);
464 close(sock_out);
465 logit("Bad protocol version identification '%.100s' from %s",
466 client_version_string, get_remote_ipaddr());
467 cleanup_exit(255);
469 debug("Client protocol version %d.%d; client software version %.100s",
470 remote_major, remote_minor, remote_version);
472 compat_datafellows(remote_version);
474 if (datafellows & SSH_BUG_PROBE) {
475 logit("probed from %s with %s. Don't panic.",
476 get_remote_ipaddr(), client_version_string);
477 cleanup_exit(255);
480 if (datafellows & SSH_BUG_SCANNER) {
481 logit("scanned from %s with %s. Don't panic.",
482 get_remote_ipaddr(), client_version_string);
483 cleanup_exit(255);
486 mismatch = 0;
487 switch (remote_major) {
488 case 1:
489 if (remote_minor == 99) {
490 if (options.protocol & SSH_PROTO_2)
491 enable_compat20();
492 else
493 mismatch = 1;
494 break;
496 if (!(options.protocol & SSH_PROTO_1)) {
497 mismatch = 1;
498 break;
500 if (remote_minor < 3) {
501 packet_disconnect("Your ssh version is too old and "
502 "is no longer supported. Please install a newer version.");
503 } else if (remote_minor == 3) {
504 /* note that this disables agent-forwarding */
505 enable_compat13();
507 break;
508 case 2:
509 if (options.protocol & SSH_PROTO_2) {
510 enable_compat20();
511 break;
513 /* FALLTHROUGH */
514 default:
515 mismatch = 1;
516 break;
518 chop(server_version_string);
519 debug("Local version string %.200s", server_version_string);
521 if (mismatch) {
522 s = "Protocol major versions differ.\n";
523 (void) atomicio(vwrite, sock_out, s, strlen(s));
524 close(sock_in);
525 close(sock_out);
526 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
527 get_remote_ipaddr(),
528 server_version_string, client_version_string);
529 cleanup_exit(255);
533 /* Destroy the host and server keys. They will no longer be needed. */
534 void
535 destroy_sensitive_data(void)
537 int i;
539 if (sensitive_data.server_key) {
540 key_free(sensitive_data.server_key);
541 sensitive_data.server_key = NULL;
543 for (i = 0; i < options.num_host_key_files; i++) {
544 if (sensitive_data.host_keys[i]) {
545 key_free(sensitive_data.host_keys[i]);
546 sensitive_data.host_keys[i] = NULL;
549 sensitive_data.ssh1_host_key = NULL;
550 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
553 /* Demote private to public keys for network child */
554 void
555 demote_sensitive_data(void)
557 Key *tmp;
558 int i;
560 if (sensitive_data.server_key) {
561 tmp = key_demote(sensitive_data.server_key);
562 key_free(sensitive_data.server_key);
563 sensitive_data.server_key = tmp;
566 for (i = 0; i < options.num_host_key_files; i++) {
567 if (sensitive_data.host_keys[i]) {
568 tmp = key_demote(sensitive_data.host_keys[i]);
569 key_free(sensitive_data.host_keys[i]);
570 sensitive_data.host_keys[i] = tmp;
571 if (tmp->type == KEY_RSA1)
572 sensitive_data.ssh1_host_key = tmp;
576 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
579 static void
580 privsep_preauth_child(void)
582 u_int32_t rnd[256];
583 gid_t gidset[1];
585 /* Enable challenge-response authentication for privilege separation */
586 privsep_challenge_enable();
588 arc4random_stir();
589 arc4random_buf(rnd, sizeof(rnd));
590 RAND_seed(rnd, sizeof(rnd));
592 /* Demote the private keys to public keys. */
593 demote_sensitive_data();
595 /* Change our root directory */
596 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
597 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
598 strerror(errno));
599 if (chdir("/") == -1)
600 fatal("chdir(\"/\"): %s", strerror(errno));
602 /* Drop our privileges */
603 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
604 (u_int)privsep_pw->pw_gid);
605 #if 0
606 /* XXX not ready, too heavy after chroot */
607 do_setusercontext(privsep_pw);
608 #else
609 gidset[0] = privsep_pw->pw_gid;
610 if (setgroups(1, gidset) < 0)
611 fatal("setgroups: %.100s", strerror(errno));
612 permanently_set_uid(privsep_pw);
613 #endif
616 static int
617 privsep_preauth(Authctxt *authctxt)
619 int status;
620 pid_t pid;
622 /* Set up unprivileged child process to deal with network data */
623 pmonitor = monitor_init();
624 /* Store a pointer to the kex for later rekeying */
625 pmonitor->m_pkex = &xxx_kex;
627 pid = fork();
628 if (pid == -1) {
629 fatal("fork of unprivileged child failed");
630 } else if (pid != 0) {
631 debug2("Network child is on pid %ld", (long)pid);
633 close(pmonitor->m_recvfd);
634 pmonitor->m_pid = pid;
635 monitor_child_preauth(authctxt, pmonitor);
636 close(pmonitor->m_sendfd);
638 /* Sync memory */
639 monitor_sync(pmonitor);
641 /* Wait for the child's exit status */
642 while (waitpid(pid, &status, 0) < 0)
643 if (errno != EINTR)
644 break;
645 return (1);
646 } else {
647 /* child */
649 close(pmonitor->m_sendfd);
651 /* Demote the child */
652 if (getuid() == 0 || geteuid() == 0)
653 privsep_preauth_child();
654 setproctitle("%s", "[net]");
656 return (0);
659 static void
660 privsep_postauth(Authctxt *authctxt)
662 u_int32_t rnd[256];
664 #ifdef DISABLE_FD_PASSING
665 if (1) {
666 #else
667 if (authctxt->pw->pw_uid == 0 || options.use_login) {
668 #endif
669 /* File descriptor passing is broken or root login */
670 use_privsep = 0;
671 goto skip;
674 /* New socket pair */
675 monitor_reinit(pmonitor);
677 pmonitor->m_pid = fork();
678 if (pmonitor->m_pid == -1)
679 fatal("fork of unprivileged child failed");
680 else if (pmonitor->m_pid != 0) {
681 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
682 close(pmonitor->m_recvfd);
683 buffer_clear(&loginmsg);
684 monitor_child_postauth(pmonitor);
686 /* NEVERREACHED */
687 exit(0);
690 close(pmonitor->m_sendfd);
692 /* Demote the private keys to public keys. */
693 demote_sensitive_data();
695 arc4random_stir();
696 arc4random_buf(rnd, sizeof(rnd));
697 RAND_seed(rnd, sizeof(rnd));
699 /* Drop privileges */
700 do_setusercontext(authctxt->pw);
702 skip:
703 /* It is safe now to apply the key state */
704 monitor_apply_keystate(pmonitor);
707 * Tell the packet layer that authentication was successful, since
708 * this information is not part of the key state.
710 packet_set_authenticated();
713 static char *
714 list_hostkey_types(void)
716 Buffer b;
717 const char *p;
718 char *ret;
719 int i;
721 buffer_init(&b);
722 for (i = 0; i < options.num_host_key_files; i++) {
723 Key *key = sensitive_data.host_keys[i];
724 if (key == NULL)
725 continue;
726 switch (key->type) {
727 case KEY_RSA:
728 case KEY_DSA:
729 if (buffer_len(&b) > 0)
730 buffer_append(&b, ",", 1);
731 p = key_ssh_name(key);
732 buffer_append(&b, p, strlen(p));
733 break;
736 buffer_append(&b, "\0", 1);
737 ret = xstrdup(buffer_ptr(&b));
738 buffer_free(&b);
739 debug("list_hostkey_types: %s", ret);
740 return ret;
743 Key *
744 get_hostkey_by_type(int type)
746 int i;
748 for (i = 0; i < options.num_host_key_files; i++) {
749 Key *key = sensitive_data.host_keys[i];
750 if (key != NULL && key->type == type)
751 return key;
753 return NULL;
756 Key *
757 get_hostkey_by_index(int ind)
759 if (ind < 0 || ind >= options.num_host_key_files)
760 return (NULL);
761 return (sensitive_data.host_keys[ind]);
765 get_hostkey_index(Key *key)
767 int i;
769 for (i = 0; i < options.num_host_key_files; i++) {
770 if (key == sensitive_data.host_keys[i])
771 return (i);
773 return (-1);
777 * returns 1 if connection should be dropped, 0 otherwise.
778 * dropping starts at connection #max_startups_begin with a probability
779 * of (max_startups_rate/100). the probability increases linearly until
780 * all connections are dropped for startups > max_startups
782 static int
783 drop_connection(int startups)
785 int p, r;
787 if (startups < options.max_startups_begin)
788 return 0;
789 if (startups >= options.max_startups)
790 return 1;
791 if (options.max_startups_rate == 100)
792 return 1;
794 p = 100 - options.max_startups_rate;
795 p *= startups - options.max_startups_begin;
796 p /= options.max_startups - options.max_startups_begin;
797 p += options.max_startups_rate;
798 r = arc4random_uniform(100);
800 debug("drop_connection: p %d, r %d", p, r);
801 return (r < p) ? 1 : 0;
804 static void
805 usage(void)
807 fprintf(stderr, "%s, %s\n",
808 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
809 fprintf(stderr,
810 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-f config_file]\n"
811 " [-g login_grace_time] [-h host_key_file] [-k key_gen_time]\n"
812 " [-o option] [-p port] [-u len]\n"
814 exit(1);
817 static void
818 send_rexec_state(int fd, Buffer *conf)
820 Buffer m;
822 debug3("%s: entering fd = %d config len %d", __func__, fd,
823 buffer_len(conf));
826 * Protocol from reexec master to child:
827 * string configuration
828 * u_int ephemeral_key_follows
829 * bignum e (only if ephemeral_key_follows == 1)
830 * bignum n "
831 * bignum d "
832 * bignum iqmp "
833 * bignum p "
834 * bignum q "
835 * string rngseed (only if OpenSSL is not self-seeded)
837 buffer_init(&m);
838 buffer_put_cstring(&m, buffer_ptr(conf));
840 if (sensitive_data.server_key != NULL &&
841 sensitive_data.server_key->type == KEY_RSA1) {
842 buffer_put_int(&m, 1);
843 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
844 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
845 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
846 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
847 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
848 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
849 } else
850 buffer_put_int(&m, 0);
852 #ifndef OPENSSL_PRNG_ONLY
853 rexec_send_rng_seed(&m);
854 #endif
856 if (ssh_msg_send(fd, 0, &m) == -1)
857 fatal("%s: ssh_msg_send failed", __func__);
859 buffer_free(&m);
861 debug3("%s: done", __func__);
864 static void
865 recv_rexec_state(int fd, Buffer *conf)
867 Buffer m;
868 char *cp;
869 u_int len;
871 debug3("%s: entering fd = %d", __func__, fd);
873 buffer_init(&m);
875 if (ssh_msg_recv(fd, &m) == -1)
876 fatal("%s: ssh_msg_recv failed", __func__);
877 if (buffer_get_char(&m) != 0)
878 fatal("%s: rexec version mismatch", __func__);
880 cp = buffer_get_string(&m, &len);
881 if (conf != NULL)
882 buffer_append(conf, cp, len + 1);
883 xfree(cp);
885 if (buffer_get_int(&m)) {
886 if (sensitive_data.server_key != NULL)
887 key_free(sensitive_data.server_key);
888 sensitive_data.server_key = key_new_private(KEY_RSA1);
889 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
890 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
891 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
892 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
893 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
894 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
895 rsa_generate_additional_parameters(
896 sensitive_data.server_key->rsa);
899 #ifndef OPENSSL_PRNG_ONLY
900 rexec_recv_rng_seed(&m);
901 #endif
903 buffer_free(&m);
905 debug3("%s: done", __func__);
908 /* Accept a connection from inetd */
909 static void
910 server_accept_inetd(int *sock_in, int *sock_out)
912 int fd;
914 startup_pipe = -1;
915 if (rexeced_flag) {
916 close(REEXEC_CONFIG_PASS_FD);
917 *sock_in = *sock_out = dup(STDIN_FILENO);
918 if (!debug_flag) {
919 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
920 close(REEXEC_STARTUP_PIPE_FD);
922 } else {
923 *sock_in = dup(STDIN_FILENO);
924 *sock_out = dup(STDOUT_FILENO);
927 * We intentionally do not close the descriptors 0, 1, and 2
928 * as our code for setting the descriptors won't work if
929 * ttyfd happens to be one of those.
931 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
932 dup2(fd, STDIN_FILENO);
933 dup2(fd, STDOUT_FILENO);
934 if (fd > STDOUT_FILENO)
935 close(fd);
937 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
941 * Listen for TCP connections
943 static void
944 server_listen(void)
946 int ret, listen_sock, on = 1;
947 struct addrinfo *ai;
948 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
950 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
951 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
952 continue;
953 if (num_listen_socks >= MAX_LISTEN_SOCKS)
954 fatal("Too many listen sockets. "
955 "Enlarge MAX_LISTEN_SOCKS");
956 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
957 ntop, sizeof(ntop), strport, sizeof(strport),
958 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
959 error("getnameinfo failed: %.100s",
960 ssh_gai_strerror(ret));
961 continue;
963 /* Create socket for listening. */
964 listen_sock = socket(ai->ai_family, ai->ai_socktype,
965 ai->ai_protocol);
966 if (listen_sock < 0) {
967 /* kernel may not support ipv6 */
968 verbose("socket: %.100s", strerror(errno));
969 continue;
971 if (set_nonblock(listen_sock) == -1) {
972 close(listen_sock);
973 continue;
976 * Set socket options.
977 * Allow local port reuse in TIME_WAIT.
979 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
980 &on, sizeof(on)) == -1)
981 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
983 #ifdef IPV6_V6ONLY
984 /* Only communicate in IPv6 over AF_INET6 sockets. */
985 if (ai->ai_family == AF_INET6) {
986 if (setsockopt(listen_sock, IPPROTO_IPV6, IPV6_V6ONLY,
987 &on, sizeof(on)) == -1)
988 error("setsockopt IPV6_V6ONLY: %s",
989 strerror(errno));
991 #endif
993 debug("Bind to port %s on %s.", strport, ntop);
995 /* Bind the socket to the desired port. */
996 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
997 error("Bind to port %s on %s failed: %.200s.",
998 strport, ntop, strerror(errno));
999 close(listen_sock);
1000 continue;
1002 listen_socks[num_listen_socks] = listen_sock;
1003 num_listen_socks++;
1005 /* Start listening on the port. */
1006 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1007 fatal("listen on [%s]:%s: %.100s",
1008 ntop, strport, strerror(errno));
1009 logit("Server listening on %s port %s.", ntop, strport);
1011 freeaddrinfo(options.listen_addrs);
1013 if (!num_listen_socks)
1014 fatal("Cannot bind any address.");
1018 * The main TCP accept loop. Note that, for the non-debug case, returns
1019 * from this function are in a forked subprocess.
1021 static void
1022 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1024 fd_set *fdset;
1025 int i, j, ret, maxfd;
1026 int key_used = 0, startups = 0;
1027 int startup_p[2] = { -1 , -1 };
1028 struct sockaddr_storage from;
1029 socklen_t fromlen;
1030 pid_t pid;
1032 /* setup fd set for accept */
1033 fdset = NULL;
1034 maxfd = 0;
1035 for (i = 0; i < num_listen_socks; i++)
1036 if (listen_socks[i] > maxfd)
1037 maxfd = listen_socks[i];
1038 /* pipes connected to unauthenticated childs */
1039 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1040 for (i = 0; i < options.max_startups; i++)
1041 startup_pipes[i] = -1;
1044 * Stay listening for connections until the system crashes or
1045 * the daemon is killed with a signal.
1047 for (;;) {
1048 if (received_sighup)
1049 sighup_restart();
1050 if (fdset != NULL)
1051 xfree(fdset);
1052 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1053 sizeof(fd_mask));
1055 for (i = 0; i < num_listen_socks; i++)
1056 FD_SET(listen_socks[i], fdset);
1057 for (i = 0; i < options.max_startups; i++)
1058 if (startup_pipes[i] != -1)
1059 FD_SET(startup_pipes[i], fdset);
1061 /* Wait in select until there is a connection. */
1062 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1063 if (ret < 0 && errno != EINTR)
1064 error("select: %.100s", strerror(errno));
1065 if (received_sigterm) {
1066 logit("Received signal %d; terminating.",
1067 (int) received_sigterm);
1068 close_listen_socks();
1069 unlink(options.pid_file);
1070 exit(255);
1072 if (key_used && key_do_regen) {
1073 generate_ephemeral_server_key();
1074 key_used = 0;
1075 key_do_regen = 0;
1077 if (ret < 0)
1078 continue;
1080 for (i = 0; i < options.max_startups; i++)
1081 if (startup_pipes[i] != -1 &&
1082 FD_ISSET(startup_pipes[i], fdset)) {
1084 * the read end of the pipe is ready
1085 * if the child has closed the pipe
1086 * after successful authentication
1087 * or if the child has died
1089 close(startup_pipes[i]);
1090 startup_pipes[i] = -1;
1091 startups--;
1093 for (i = 0; i < num_listen_socks; i++) {
1094 if (!FD_ISSET(listen_socks[i], fdset))
1095 continue;
1096 fromlen = sizeof(from);
1097 *newsock = accept(listen_socks[i],
1098 (struct sockaddr *)&from, &fromlen);
1099 if (*newsock < 0) {
1100 if (errno != EINTR && errno != EAGAIN &&
1101 errno != EWOULDBLOCK)
1102 error("accept: %.100s", strerror(errno));
1103 continue;
1105 if (unset_nonblock(*newsock) == -1) {
1106 close(*newsock);
1107 continue;
1109 if (drop_connection(startups) == 1) {
1110 debug("drop connection #%d", startups);
1111 close(*newsock);
1112 continue;
1114 if (pipe(startup_p) == -1) {
1115 close(*newsock);
1116 continue;
1119 if (rexec_flag && socketpair(AF_UNIX,
1120 SOCK_STREAM, 0, config_s) == -1) {
1121 error("reexec socketpair: %s",
1122 strerror(errno));
1123 close(*newsock);
1124 close(startup_p[0]);
1125 close(startup_p[1]);
1126 continue;
1129 for (j = 0; j < options.max_startups; j++)
1130 if (startup_pipes[j] == -1) {
1131 startup_pipes[j] = startup_p[0];
1132 if (maxfd < startup_p[0])
1133 maxfd = startup_p[0];
1134 startups++;
1135 break;
1139 * Got connection. Fork a child to handle it, unless
1140 * we are in debugging mode.
1142 if (debug_flag) {
1144 * In debugging mode. Close the listening
1145 * socket, and start processing the
1146 * connection without forking.
1148 debug("Server will not fork when running in debugging mode.");
1149 close_listen_socks();
1150 *sock_in = *newsock;
1151 *sock_out = *newsock;
1152 close(startup_p[0]);
1153 close(startup_p[1]);
1154 startup_pipe = -1;
1155 pid = getpid();
1156 if (rexec_flag) {
1157 send_rexec_state(config_s[0],
1158 &cfg);
1159 close(config_s[0]);
1161 break;
1165 * Normal production daemon. Fork, and have
1166 * the child process the connection. The
1167 * parent continues listening.
1169 platform_pre_fork();
1170 if ((pid = fork()) == 0) {
1172 * Child. Close the listening and
1173 * max_startup sockets. Start using
1174 * the accepted socket. Reinitialize
1175 * logging (since our pid has changed).
1176 * We break out of the loop to handle
1177 * the connection.
1179 platform_post_fork_child();
1180 startup_pipe = startup_p[1];
1181 close_startup_pipes();
1182 close_listen_socks();
1183 *sock_in = *newsock;
1184 *sock_out = *newsock;
1185 log_init(__progname,
1186 options.log_level,
1187 options.log_facility,
1188 log_stderr);
1189 if (rexec_flag)
1190 close(config_s[0]);
1191 break;
1194 /* Parent. Stay in the loop. */
1195 platform_post_fork_parent(pid);
1196 if (pid < 0)
1197 error("fork: %.100s", strerror(errno));
1198 else
1199 debug("Forked child %ld.", (long)pid);
1201 close(startup_p[1]);
1203 if (rexec_flag) {
1204 send_rexec_state(config_s[0], &cfg);
1205 close(config_s[0]);
1206 close(config_s[1]);
1210 * Mark that the key has been used (it
1211 * was "given" to the child).
1213 if ((options.protocol & SSH_PROTO_1) &&
1214 key_used == 0) {
1215 /* Schedule server key regeneration alarm. */
1216 signal(SIGALRM, key_regeneration_alarm);
1217 alarm(options.key_regeneration_time);
1218 key_used = 1;
1221 close(*newsock);
1224 * Ensure that our random state differs
1225 * from that of the child
1227 arc4random_stir();
1230 /* child process check (or debug mode) */
1231 if (num_listen_socks < 0)
1232 break;
1238 * Main program for the daemon.
1241 main(int ac, char **av)
1243 extern char *optarg;
1244 extern int optind;
1245 int opt, i, on = 1;
1246 int sock_in = -1, sock_out = -1, newsock = -1;
1247 const char *remote_ip;
1248 char *test_user = NULL, *test_host = NULL, *test_addr = NULL;
1249 int remote_port;
1250 char *line, *p, *cp;
1251 int config_s[2] = { -1 , -1 };
1252 u_int64_t ibytes, obytes;
1253 mode_t new_umask;
1254 Key *key;
1255 Authctxt *authctxt;
1257 #ifdef HAVE_SECUREWARE
1258 (void)set_auth_parameters(ac, av);
1259 #endif
1260 __progname = ssh_get_progname(av[0]);
1261 init_rng();
1263 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1264 saved_argc = ac;
1265 rexec_argc = ac;
1266 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1267 for (i = 0; i < ac; i++)
1268 saved_argv[i] = xstrdup(av[i]);
1269 saved_argv[i] = NULL;
1271 #ifndef HAVE_SETPROCTITLE
1272 /* Prepare for later setproctitle emulation */
1273 compat_init_setproctitle(ac, av);
1274 av = saved_argv;
1275 #endif
1277 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1278 debug("setgroups(): %.200s", strerror(errno));
1280 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1281 sanitise_stdfd();
1283 /* Initialize configuration options to their default values. */
1284 initialize_server_options(&options);
1286 /* Parse command-line arguments. */
1287 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeiqrtQRT46")) != -1) {
1288 switch (opt) {
1289 case '4':
1290 options.address_family = AF_INET;
1291 break;
1292 case '6':
1293 options.address_family = AF_INET6;
1294 break;
1295 case 'f':
1296 config_file_name = optarg;
1297 break;
1298 case 'd':
1299 if (debug_flag == 0) {
1300 debug_flag = 1;
1301 options.log_level = SYSLOG_LEVEL_DEBUG1;
1302 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1303 options.log_level++;
1304 break;
1305 case 'D':
1306 no_daemon_flag = 1;
1307 break;
1308 case 'e':
1309 log_stderr = 1;
1310 break;
1311 case 'i':
1312 inetd_flag = 1;
1313 break;
1314 case 'r':
1315 rexec_flag = 0;
1316 break;
1317 case 'R':
1318 rexeced_flag = 1;
1319 inetd_flag = 1;
1320 break;
1321 case 'Q':
1322 /* ignored */
1323 break;
1324 case 'q':
1325 options.log_level = SYSLOG_LEVEL_QUIET;
1326 break;
1327 case 'b':
1328 options.server_key_bits = (int)strtonum(optarg, 256,
1329 32768, NULL);
1330 break;
1331 case 'p':
1332 options.ports_from_cmdline = 1;
1333 if (options.num_ports >= MAX_PORTS) {
1334 fprintf(stderr, "too many ports.\n");
1335 exit(1);
1337 options.ports[options.num_ports++] = a2port(optarg);
1338 if (options.ports[options.num_ports-1] == 0) {
1339 fprintf(stderr, "Bad port number.\n");
1340 exit(1);
1342 break;
1343 case 'g':
1344 if ((options.login_grace_time = convtime(optarg)) == -1) {
1345 fprintf(stderr, "Invalid login grace time.\n");
1346 exit(1);
1348 break;
1349 case 'k':
1350 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1351 fprintf(stderr, "Invalid key regeneration interval.\n");
1352 exit(1);
1354 break;
1355 case 'h':
1356 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1357 fprintf(stderr, "too many host keys.\n");
1358 exit(1);
1360 options.host_key_files[options.num_host_key_files++] = optarg;
1361 break;
1362 case 't':
1363 test_flag = 1;
1364 break;
1365 case 'T':
1366 test_flag = 2;
1367 break;
1368 case 'C':
1369 cp = optarg;
1370 while ((p = strsep(&cp, ",")) && *p != '\0') {
1371 if (strncmp(p, "addr=", 5) == 0)
1372 test_addr = xstrdup(p + 5);
1373 else if (strncmp(p, "host=", 5) == 0)
1374 test_host = xstrdup(p + 5);
1375 else if (strncmp(p, "user=", 5) == 0)
1376 test_user = xstrdup(p + 5);
1377 else {
1378 fprintf(stderr, "Invalid test "
1379 "mode specification %s\n", p);
1380 exit(1);
1383 break;
1384 case 'u':
1385 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1386 if (utmp_len > MAXHOSTNAMELEN) {
1387 fprintf(stderr, "Invalid utmp length.\n");
1388 exit(1);
1390 break;
1391 case 'o':
1392 line = xstrdup(optarg);
1393 if (process_server_config_line(&options, line,
1394 "command-line", 0, NULL, NULL, NULL, NULL) != 0)
1395 exit(1);
1396 xfree(line);
1397 break;
1398 case '?':
1399 default:
1400 usage();
1401 break;
1404 if (rexeced_flag || inetd_flag)
1405 rexec_flag = 0;
1406 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1407 fatal("sshd re-exec requires execution with an absolute path");
1408 if (rexeced_flag)
1409 closefrom(REEXEC_MIN_FREE_FD);
1410 else
1411 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1413 SSLeay_add_all_algorithms();
1416 * Force logging to stderr until we have loaded the private host
1417 * key (unless started from inetd)
1419 log_init(__progname,
1420 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1421 SYSLOG_LEVEL_INFO : options.log_level,
1422 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1423 SYSLOG_FACILITY_AUTH : options.log_facility,
1424 log_stderr || !inetd_flag);
1427 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1428 * root's environment
1430 if (getenv("KRB5CCNAME") != NULL)
1431 unsetenv("KRB5CCNAME");
1433 #ifdef _UNICOS
1434 /* Cray can define user privs drop all privs now!
1435 * Not needed on PRIV_SU systems!
1437 drop_cray_privs();
1438 #endif
1440 sensitive_data.server_key = NULL;
1441 sensitive_data.ssh1_host_key = NULL;
1442 sensitive_data.have_ssh1_key = 0;
1443 sensitive_data.have_ssh2_key = 0;
1446 * If we're doing an extended config test, make sure we have all of
1447 * the parameters we need. If we're not doing an extended test,
1448 * do not silently ignore connection test params.
1450 if (test_flag >= 2 &&
1451 (test_user != NULL || test_host != NULL || test_addr != NULL)
1452 && (test_user == NULL || test_host == NULL || test_addr == NULL))
1453 fatal("user, host and addr are all required when testing "
1454 "Match configs");
1455 if (test_flag < 2 && (test_user != NULL || test_host != NULL ||
1456 test_addr != NULL))
1457 fatal("Config test connection parameter (-C) provided without "
1458 "test mode (-T)");
1460 /* Fetch our configuration */
1461 buffer_init(&cfg);
1462 if (rexeced_flag)
1463 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1464 else
1465 load_server_config(config_file_name, &cfg);
1467 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1468 &cfg, NULL, NULL, NULL);
1470 seed_rng();
1472 /* Fill in default values for those options not explicitly set. */
1473 fill_default_server_options(&options);
1475 /* challenge-response is implemented via keyboard interactive */
1476 if (options.challenge_response_authentication)
1477 options.kbd_interactive_authentication = 1;
1479 /* set default channel AF */
1480 channel_set_af(options.address_family);
1482 /* Check that there are no remaining arguments. */
1483 if (optind < ac) {
1484 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1485 exit(1);
1488 debug("sshd version %.100s", SSH_RELEASE);
1490 /* Store privilege separation user for later use if required. */
1491 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1492 if (use_privsep || options.kerberos_authentication)
1493 fatal("Privilege separation user %s does not exist",
1494 SSH_PRIVSEP_USER);
1495 } else {
1496 memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1497 privsep_pw = pwcopy(privsep_pw);
1498 xfree(privsep_pw->pw_passwd);
1499 privsep_pw->pw_passwd = xstrdup("*");
1501 endpwent();
1503 /* load private host keys */
1504 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1505 sizeof(Key *));
1506 for (i = 0; i < options.num_host_key_files; i++)
1507 sensitive_data.host_keys[i] = NULL;
1509 for (i = 0; i < options.num_host_key_files; i++) {
1510 key = key_load_private(options.host_key_files[i], "", NULL);
1511 if (key && blacklisted_key(key)) {
1512 char *fp;
1513 fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
1514 if (options.permit_blacklisted_keys)
1515 error("Host key %s blacklisted (see "
1516 "ssh-vulnkey(1)); continuing anyway", fp);
1517 else
1518 error("Host key %s blacklisted (see "
1519 "ssh-vulnkey(1))", fp);
1520 xfree(fp);
1521 if (!options.permit_blacklisted_keys) {
1522 sensitive_data.host_keys[i] = NULL;
1523 continue;
1526 sensitive_data.host_keys[i] = key;
1527 if (key == NULL) {
1528 error("Could not load host key: %s",
1529 options.host_key_files[i]);
1530 sensitive_data.host_keys[i] = NULL;
1531 continue;
1533 switch (key->type) {
1534 case KEY_RSA1:
1535 sensitive_data.ssh1_host_key = key;
1536 sensitive_data.have_ssh1_key = 1;
1537 break;
1538 case KEY_RSA:
1539 case KEY_DSA:
1540 sensitive_data.have_ssh2_key = 1;
1541 break;
1543 debug("private host key: #%d type %d %s", i, key->type,
1544 key_type(key));
1546 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1547 logit("Disabling protocol version 1. Could not load host key");
1548 options.protocol &= ~SSH_PROTO_1;
1550 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1551 logit("Disabling protocol version 2. Could not load host key");
1552 options.protocol &= ~SSH_PROTO_2;
1554 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1555 logit("sshd: no hostkeys available -- exiting.");
1556 exit(1);
1559 /* Check certain values for sanity. */
1560 if (options.protocol & SSH_PROTO_1) {
1561 if (options.server_key_bits < 512 ||
1562 options.server_key_bits > 32768) {
1563 fprintf(stderr, "Bad server key size.\n");
1564 exit(1);
1567 * Check that server and host key lengths differ sufficiently. This
1568 * is necessary to make double encryption work with rsaref. Oh, I
1569 * hate software patents. I dont know if this can go? Niels
1571 if (options.server_key_bits >
1572 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1573 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1574 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1575 SSH_KEY_BITS_RESERVED) {
1576 options.server_key_bits =
1577 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1578 SSH_KEY_BITS_RESERVED;
1579 debug("Forcing server key to %d bits to make it differ from host key.",
1580 options.server_key_bits);
1584 if (use_privsep) {
1585 struct stat st;
1587 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1588 (S_ISDIR(st.st_mode) == 0))
1589 fatal("Missing privilege separation directory: %s",
1590 _PATH_PRIVSEP_CHROOT_DIR);
1592 #ifdef HAVE_CYGWIN
1593 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1594 (st.st_uid != getuid () ||
1595 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1596 #else
1597 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1598 #endif
1599 fatal("%s must be owned by root and not group or "
1600 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1603 if (test_flag > 1) {
1604 if (test_user != NULL && test_addr != NULL && test_host != NULL)
1605 parse_server_match_config(&options, test_user,
1606 test_host, test_addr);
1607 dump_config(&options);
1610 /* Configuration looks good, so exit if in test mode. */
1611 if (test_flag)
1612 exit(0);
1615 * Clear out any supplemental groups we may have inherited. This
1616 * prevents inadvertent creation of files with bad modes (in the
1617 * portable version at least, it's certainly possible for PAM
1618 * to create a file, and we can't control the code in every
1619 * module which might be used).
1621 if (setgroups(0, NULL) < 0)
1622 debug("setgroups() failed: %.200s", strerror(errno));
1624 if (rexec_flag) {
1625 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1626 for (i = 0; i < rexec_argc; i++) {
1627 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1628 rexec_argv[i] = saved_argv[i];
1630 rexec_argv[rexec_argc] = "-R";
1631 rexec_argv[rexec_argc + 1] = NULL;
1634 /* Ensure that umask disallows at least group and world write */
1635 new_umask = umask(0077) | 0022;
1636 (void) umask(new_umask);
1638 /* Initialize the log (it is reinitialized below in case we forked). */
1639 if (debug_flag && (!inetd_flag || rexeced_flag))
1640 log_stderr = 1;
1641 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1644 * If not in debugging mode, and not started from inetd, disconnect
1645 * from the controlling terminal, and fork. The original process
1646 * exits.
1648 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1649 #ifdef TIOCNOTTY
1650 int fd;
1651 #endif /* TIOCNOTTY */
1652 if (daemon(0, 0) < 0)
1653 fatal("daemon() failed: %.200s", strerror(errno));
1655 /* Disconnect from the controlling tty. */
1656 #ifdef TIOCNOTTY
1657 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1658 if (fd >= 0) {
1659 (void) ioctl(fd, TIOCNOTTY, NULL);
1660 close(fd);
1662 #endif /* TIOCNOTTY */
1664 /* Reinitialize the log (because of the fork above). */
1665 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1667 /* Initialize the random number generator. */
1668 arc4random_stir();
1670 /* Chdir to the root directory so that the current disk can be
1671 unmounted if desired. */
1672 chdir("/");
1674 /* ignore SIGPIPE */
1675 signal(SIGPIPE, SIG_IGN);
1677 /* Get a connection, either from inetd or a listening TCP socket */
1678 if (inetd_flag) {
1679 server_accept_inetd(&sock_in, &sock_out);
1680 } else {
1681 server_listen();
1683 if (options.protocol & SSH_PROTO_1)
1684 generate_ephemeral_server_key();
1686 signal(SIGHUP, sighup_handler);
1687 signal(SIGCHLD, main_sigchld_handler);
1688 signal(SIGTERM, sigterm_handler);
1689 signal(SIGQUIT, sigterm_handler);
1692 * Write out the pid file after the sigterm handler
1693 * is setup and the listen sockets are bound
1695 if (!debug_flag) {
1696 FILE *f = fopen(options.pid_file, "w");
1698 if (f == NULL) {
1699 error("Couldn't create pid file \"%s\": %s",
1700 options.pid_file, strerror(errno));
1701 } else {
1702 fprintf(f, "%ld\n", (long) getpid());
1703 fclose(f);
1707 /* Accept a connection and return in a forked child */
1708 server_accept_loop(&sock_in, &sock_out,
1709 &newsock, config_s);
1712 /* This is the child processing a new connection. */
1713 setproctitle("%s", "[accepted]");
1716 * Initialize the resolver. This may not happen automatically
1717 * before privsep chroot().
1719 if ((_res.options & RES_INIT) == 0) {
1720 debug("res_init()");
1721 res_init();
1725 * Create a new session and process group since the 4.4BSD
1726 * setlogin() affects the entire process group. We don't
1727 * want the child to be able to affect the parent.
1729 #if !defined(SSHD_ACQUIRES_CTTY)
1731 * If setsid is called, on some platforms sshd will later acquire a
1732 * controlling terminal which will result in "could not set
1733 * controlling tty" errors.
1735 if (!debug_flag && !inetd_flag && setsid() < 0)
1736 error("setsid: %.100s", strerror(errno));
1737 #endif
1739 if (rexec_flag) {
1740 int fd;
1742 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1743 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1744 dup2(newsock, STDIN_FILENO);
1745 dup2(STDIN_FILENO, STDOUT_FILENO);
1746 if (startup_pipe == -1)
1747 close(REEXEC_STARTUP_PIPE_FD);
1748 else
1749 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1751 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1752 close(config_s[1]);
1753 if (startup_pipe != -1)
1754 close(startup_pipe);
1756 execv(rexec_argv[0], rexec_argv);
1758 /* Reexec has failed, fall back and continue */
1759 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1760 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1761 log_init(__progname, options.log_level,
1762 options.log_facility, log_stderr);
1764 /* Clean up fds */
1765 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1766 close(config_s[1]);
1767 close(REEXEC_CONFIG_PASS_FD);
1768 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1769 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1770 dup2(fd, STDIN_FILENO);
1771 dup2(fd, STDOUT_FILENO);
1772 if (fd > STDERR_FILENO)
1773 close(fd);
1775 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1776 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1780 * Disable the key regeneration alarm. We will not regenerate the
1781 * key since we are no longer in a position to give it to anyone. We
1782 * will not restart on SIGHUP since it no longer makes sense.
1784 alarm(0);
1785 signal(SIGALRM, SIG_DFL);
1786 signal(SIGHUP, SIG_DFL);
1787 signal(SIGTERM, SIG_DFL);
1788 signal(SIGQUIT, SIG_DFL);
1789 signal(SIGCHLD, SIG_DFL);
1790 signal(SIGINT, SIG_DFL);
1793 * Register our connection. This turns encryption off because we do
1794 * not have a key.
1796 packet_set_connection(sock_in, sock_out);
1797 packet_set_server();
1799 /* Set SO_KEEPALIVE if requested. */
1800 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1801 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1802 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1804 if ((remote_port = get_remote_port()) < 0) {
1805 debug("get_remote_port failed");
1806 cleanup_exit(255);
1810 * We use get_canonical_hostname with usedns = 0 instead of
1811 * get_remote_ipaddr here so IP options will be checked.
1813 (void) get_canonical_hostname(0);
1815 * The rest of the code depends on the fact that
1816 * get_remote_ipaddr() caches the remote ip, even if
1817 * the socket goes away.
1819 remote_ip = get_remote_ipaddr();
1821 #ifdef SSH_AUDIT_EVENTS
1822 audit_connection_from(remote_ip, remote_port);
1823 #endif
1824 #ifdef LIBWRAP
1825 allow_severity = options.log_facility|LOG_INFO;
1826 deny_severity = options.log_facility|LOG_WARNING;
1827 /* Check whether logins are denied from this host. */
1828 if (packet_connection_is_on_socket()) {
1829 struct request_info req;
1831 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1832 fromhost(&req);
1834 if (!hosts_access(&req)) {
1835 debug("Connection refused by tcp wrapper");
1836 refuse(&req);
1837 /* NOTREACHED */
1838 fatal("libwrap refuse returns");
1841 #endif /* LIBWRAP */
1843 /* Log the connection. */
1844 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1847 * We don't want to listen forever unless the other side
1848 * successfully authenticates itself. So we set up an alarm which is
1849 * cleared after successful authentication. A limit of zero
1850 * indicates no limit. Note that we don't set the alarm in debugging
1851 * mode; it is just annoying to have the server exit just when you
1852 * are about to discover the bug.
1854 signal(SIGALRM, grace_alarm_handler);
1855 if (!debug_flag)
1856 alarm(options.login_grace_time);
1858 sshd_exchange_identification(sock_in, sock_out);
1860 /* In inetd mode, generate ephemeral key only for proto 1 connections */
1861 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
1862 generate_ephemeral_server_key();
1864 packet_set_nonblocking();
1866 /* allocate authentication context */
1867 authctxt = xcalloc(1, sizeof(*authctxt));
1869 authctxt->loginmsg = &loginmsg;
1871 /* XXX global for cleanup, access from other modules */
1872 the_authctxt = authctxt;
1874 /* prepare buffer to collect messages to display to user after login */
1875 buffer_init(&loginmsg);
1877 if (use_privsep)
1878 if (privsep_preauth(authctxt) == 1)
1879 goto authenticated;
1881 /* perform the key exchange */
1882 /* authenticate user and start session */
1883 if (compat20) {
1884 do_ssh2_kex();
1885 do_authentication2(authctxt);
1886 } else {
1887 do_ssh1_kex();
1888 do_authentication(authctxt);
1891 * If we use privilege separation, the unprivileged child transfers
1892 * the current keystate and exits
1894 if (use_privsep) {
1895 mm_send_keystate(pmonitor);
1896 exit(0);
1899 authenticated:
1901 * Cancel the alarm we set to limit the time taken for
1902 * authentication.
1904 alarm(0);
1905 signal(SIGALRM, SIG_DFL);
1906 authctxt->authenticated = 1;
1907 if (startup_pipe != -1) {
1908 close(startup_pipe);
1909 startup_pipe = -1;
1912 #ifdef SSH_AUDIT_EVENTS
1913 audit_event(SSH_AUTH_SUCCESS);
1914 #endif
1916 #ifdef GSSAPI
1917 if (options.gss_authentication) {
1918 temporarily_use_uid(authctxt->pw);
1919 ssh_gssapi_storecreds();
1920 restore_uid();
1922 #endif
1923 #ifdef USE_PAM
1924 if (options.use_pam) {
1925 do_pam_setcred(1);
1926 do_pam_session();
1928 #endif
1931 * In privilege separation, we fork another child and prepare
1932 * file descriptor passing.
1934 if (use_privsep) {
1935 privsep_postauth(authctxt);
1936 /* the monitor process [priv] will not return */
1937 if (!compat20)
1938 destroy_sensitive_data();
1941 packet_set_timeout(options.client_alive_interval,
1942 options.client_alive_count_max);
1944 /* Start session. */
1945 do_authenticated(authctxt);
1947 /* The connection has been terminated. */
1948 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1949 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1950 verbose("Transferred: sent %llu, received %llu bytes", obytes, ibytes);
1952 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1954 #ifdef USE_PAM
1955 if (options.use_pam)
1956 finish_pam();
1957 #endif /* USE_PAM */
1959 #ifdef SSH_AUDIT_EVENTS
1960 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
1961 #endif
1963 packet_close();
1965 if (use_privsep)
1966 mm_terminate();
1968 exit(0);
1972 * Decrypt session_key_int using our private server key and private host key
1973 * (key with larger modulus first).
1976 ssh1_session_key(BIGNUM *session_key_int)
1978 int rsafail = 0;
1980 if (BN_cmp(sensitive_data.server_key->rsa->n,
1981 sensitive_data.ssh1_host_key->rsa->n) > 0) {
1982 /* Server key has bigger modulus. */
1983 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1984 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1985 SSH_KEY_BITS_RESERVED) {
1986 fatal("do_connection: %s: "
1987 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1988 get_remote_ipaddr(),
1989 BN_num_bits(sensitive_data.server_key->rsa->n),
1990 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1991 SSH_KEY_BITS_RESERVED);
1993 if (rsa_private_decrypt(session_key_int, session_key_int,
1994 sensitive_data.server_key->rsa) <= 0)
1995 rsafail++;
1996 if (rsa_private_decrypt(session_key_int, session_key_int,
1997 sensitive_data.ssh1_host_key->rsa) <= 0)
1998 rsafail++;
1999 } else {
2000 /* Host key has bigger modulus (or they are equal). */
2001 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2002 BN_num_bits(sensitive_data.server_key->rsa->n) +
2003 SSH_KEY_BITS_RESERVED) {
2004 fatal("do_connection: %s: "
2005 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2006 get_remote_ipaddr(),
2007 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2008 BN_num_bits(sensitive_data.server_key->rsa->n),
2009 SSH_KEY_BITS_RESERVED);
2011 if (rsa_private_decrypt(session_key_int, session_key_int,
2012 sensitive_data.ssh1_host_key->rsa) < 0)
2013 rsafail++;
2014 if (rsa_private_decrypt(session_key_int, session_key_int,
2015 sensitive_data.server_key->rsa) < 0)
2016 rsafail++;
2018 return (rsafail);
2021 * SSH1 key exchange
2023 static void
2024 do_ssh1_kex(void)
2026 int i, len;
2027 int rsafail = 0;
2028 BIGNUM *session_key_int;
2029 u_char session_key[SSH_SESSION_KEY_LENGTH];
2030 u_char cookie[8];
2031 u_int cipher_type, auth_mask, protocol_flags;
2034 * Generate check bytes that the client must send back in the user
2035 * packet in order for it to be accepted; this is used to defy ip
2036 * spoofing attacks. Note that this only works against somebody
2037 * doing IP spoofing from a remote machine; any machine on the local
2038 * network can still see outgoing packets and catch the random
2039 * cookie. This only affects rhosts authentication, and this is one
2040 * of the reasons why it is inherently insecure.
2042 arc4random_buf(cookie, sizeof(cookie));
2045 * Send our public key. We include in the packet 64 bits of random
2046 * data that must be matched in the reply in order to prevent IP
2047 * spoofing.
2049 packet_start(SSH_SMSG_PUBLIC_KEY);
2050 for (i = 0; i < 8; i++)
2051 packet_put_char(cookie[i]);
2053 /* Store our public server RSA key. */
2054 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2055 packet_put_bignum(sensitive_data.server_key->rsa->e);
2056 packet_put_bignum(sensitive_data.server_key->rsa->n);
2058 /* Store our public host RSA key. */
2059 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2060 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2061 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2063 /* Put protocol flags. */
2064 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2066 /* Declare which ciphers we support. */
2067 packet_put_int(cipher_mask_ssh1(0));
2069 /* Declare supported authentication types. */
2070 auth_mask = 0;
2071 if (options.rhosts_rsa_authentication)
2072 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2073 if (options.rsa_authentication)
2074 auth_mask |= 1 << SSH_AUTH_RSA;
2075 if (options.challenge_response_authentication == 1)
2076 auth_mask |= 1 << SSH_AUTH_TIS;
2077 if (options.password_authentication)
2078 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2079 packet_put_int(auth_mask);
2081 /* Send the packet and wait for it to be sent. */
2082 packet_send();
2083 packet_write_wait();
2085 debug("Sent %d bit server key and %d bit host key.",
2086 BN_num_bits(sensitive_data.server_key->rsa->n),
2087 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2089 /* Read clients reply (cipher type and session key). */
2090 packet_read_expect(SSH_CMSG_SESSION_KEY);
2092 /* Get cipher type and check whether we accept this. */
2093 cipher_type = packet_get_char();
2095 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2096 packet_disconnect("Warning: client selects unsupported cipher.");
2098 /* Get check bytes from the packet. These must match those we
2099 sent earlier with the public key packet. */
2100 for (i = 0; i < 8; i++)
2101 if (cookie[i] != packet_get_char())
2102 packet_disconnect("IP Spoofing check bytes do not match.");
2104 debug("Encryption type: %.200s", cipher_name(cipher_type));
2106 /* Get the encrypted integer. */
2107 if ((session_key_int = BN_new()) == NULL)
2108 fatal("do_ssh1_kex: BN_new failed");
2109 packet_get_bignum(session_key_int);
2111 protocol_flags = packet_get_int();
2112 packet_set_protocol_flags(protocol_flags);
2113 packet_check_eom();
2115 /* Decrypt session_key_int using host/server keys */
2116 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2119 * Extract session key from the decrypted integer. The key is in the
2120 * least significant 256 bits of the integer; the first byte of the
2121 * key is in the highest bits.
2123 if (!rsafail) {
2124 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2125 len = BN_num_bytes(session_key_int);
2126 if (len < 0 || (u_int)len > sizeof(session_key)) {
2127 error("do_ssh1_kex: bad session key len from %s: "
2128 "session_key_int %d > sizeof(session_key) %lu",
2129 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2130 rsafail++;
2131 } else {
2132 memset(session_key, 0, sizeof(session_key));
2133 BN_bn2bin(session_key_int,
2134 session_key + sizeof(session_key) - len);
2136 derive_ssh1_session_id(
2137 sensitive_data.ssh1_host_key->rsa->n,
2138 sensitive_data.server_key->rsa->n,
2139 cookie, session_id);
2141 * Xor the first 16 bytes of the session key with the
2142 * session id.
2144 for (i = 0; i < 16; i++)
2145 session_key[i] ^= session_id[i];
2148 if (rsafail) {
2149 int bytes = BN_num_bytes(session_key_int);
2150 u_char *buf = xmalloc(bytes);
2151 MD5_CTX md;
2153 logit("do_connection: generating a fake encryption key");
2154 BN_bn2bin(session_key_int, buf);
2155 MD5_Init(&md);
2156 MD5_Update(&md, buf, bytes);
2157 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2158 MD5_Final(session_key, &md);
2159 MD5_Init(&md);
2160 MD5_Update(&md, session_key, 16);
2161 MD5_Update(&md, buf, bytes);
2162 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2163 MD5_Final(session_key + 16, &md);
2164 memset(buf, 0, bytes);
2165 xfree(buf);
2166 for (i = 0; i < 16; i++)
2167 session_id[i] = session_key[i] ^ session_key[i + 16];
2169 /* Destroy the private and public keys. No longer. */
2170 destroy_sensitive_data();
2172 if (use_privsep)
2173 mm_ssh1_session_id(session_id);
2175 /* Destroy the decrypted integer. It is no longer needed. */
2176 BN_clear_free(session_key_int);
2178 /* Set the session key. From this on all communications will be encrypted. */
2179 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2181 /* Destroy our copy of the session key. It is no longer needed. */
2182 memset(session_key, 0, sizeof(session_key));
2184 debug("Received session key; encryption turned on.");
2186 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2187 packet_start(SSH_SMSG_SUCCESS);
2188 packet_send();
2189 packet_write_wait();
2193 * SSH2 key exchange: diffie-hellman-group1-sha1
2195 static void
2196 do_ssh2_kex(void)
2198 Kex *kex;
2200 if (options.ciphers != NULL) {
2201 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2202 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2204 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2205 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2206 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2207 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2209 if (options.macs != NULL) {
2210 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2211 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2213 if (options.compression == COMP_NONE) {
2214 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2215 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2216 } else if (options.compression == COMP_DELAYED) {
2217 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2218 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2221 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2223 /* start key exchange */
2224 kex = kex_setup(myproposal);
2225 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2226 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2227 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2228 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2229 kex->server = 1;
2230 kex->client_version_string=client_version_string;
2231 kex->server_version_string=server_version_string;
2232 kex->load_host_key=&get_hostkey_by_type;
2233 kex->host_key_index=&get_hostkey_index;
2235 xxx_kex = kex;
2237 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2239 session_id2 = kex->session_id;
2240 session_id2_len = kex->session_id_len;
2242 #ifdef DEBUG_KEXDH
2243 /* send 1st encrypted/maced/compressed message */
2244 packet_start(SSH2_MSG_IGNORE);
2245 packet_put_cstring("markus");
2246 packet_send();
2247 packet_write_wait();
2248 #endif
2249 debug("KEX done");
2252 /* server specific fatal cleanup */
2253 void
2254 cleanup_exit(int i)
2256 if (the_authctxt)
2257 do_cleanup(the_authctxt);
2258 #ifdef SSH_AUDIT_EVENTS
2259 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2260 if (!use_privsep || mm_is_monitor())
2261 audit_event(SSH_CONNECTION_ABANDON);
2262 #endif
2263 _exit(i);