1 /* $OpenBSD: sshd.c,v 1.364 2008/07/10 18:08:11 markus Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
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
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.
48 #include <sys/types.h>
49 #include <sys/ioctl.h>
50 #include <sys/socket.h>
51 #ifdef HAVE_SYS_STAT_H
52 # include <sys/stat.h>
54 #ifdef HAVE_SYS_TIME_H
55 # include <sys/time.h>
57 #include "openbsd-compat/sys-tree.h"
58 #include "openbsd-compat/sys-queue.h"
77 #include <openssl/dh.h>
78 #include <openssl/bn.h>
79 #include <openssl/md5.h>
80 #include <openssl/rand.h>
81 #include "openbsd-compat/openssl-compat.h"
83 #ifdef HAVE_SECUREWARE
84 #include <sys/security.h>
90 #if defined(GSSAPI) && defined(HAVE_GSSAPI_H)
92 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
93 #include <gssapi/gssapi.h>
106 #include "servconf.h"
113 #include "myproposal.h"
114 #include "authfile.h"
115 #include "pathnames.h"
116 #include "atomicio.h"
117 #include "canohost.h"
118 #include "hostfile.h"
122 #include "dispatch.h"
123 #include "channels.h"
125 #include "monitor_mm.h"
130 #include "monitor_wrap.h"
131 #include "monitor_fdpass.h"
146 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
147 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
148 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
149 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
151 extern char *__progname;
153 /* Server configuration options. */
154 ServerOptions options;
156 /* Name of the server configuration file. */
157 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
160 * Debug mode flag. This can be set on the command line. If debug
161 * mode is enabled, extra debugging output will be sent to the system
162 * log, the daemon will not go to background, and will exit after processing
163 * the first connection.
167 /* Flag indicating that the daemon should only test the configuration and keys. */
170 /* Flag indicating that the daemon is being started from inetd. */
173 /* Flag indicating that sshd should not detach and become a daemon. */
174 int no_daemon_flag = 0;
176 /* debug goes to stderr unless inetd_flag is set */
179 /* Saved arguments to main(). */
184 int rexeced_flag = 0;
190 * The sockets that the server is listening; this is used in the SIGHUP
193 #define MAX_LISTEN_SOCKS 16
194 int listen_socks[MAX_LISTEN_SOCKS];
195 int num_listen_socks = 0;
198 * the client's version string, passed by sshd2 in compat mode. if != NULL,
199 * sshd will skip the version-number exchange
201 char *client_version_string = NULL;
202 char *server_version_string = NULL;
204 /* for rekeying XXX fixme */
208 * Any really sensitive data in the application is contained in this
209 * structure. The idea is that this structure could be locked into memory so
210 * that the pages do not get written into swap. However, there are some
211 * problems. The private key contains BIGNUMs, and we do not (in principle)
212 * have access to the internals of them, and locking just the structure is
213 * not very useful. Currently, memory locking is not implemented.
216 Key *server_key; /* ephemeral server key */
217 Key *ssh1_host_key; /* ssh1 host key */
218 Key **host_keys; /* all private host keys */
221 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
225 * Flag indicating whether the RSA server key needs to be regenerated.
226 * Is set in the SIGALRM handler and cleared when the key is regenerated.
228 static volatile sig_atomic_t key_do_regen = 0;
230 /* This is set to true when a signal is received. */
231 static volatile sig_atomic_t received_sighup = 0;
232 static volatile sig_atomic_t received_sigterm = 0;
234 /* session identifier, used by RSA-auth */
235 u_char session_id[16];
238 u_char *session_id2 = NULL;
239 u_int session_id2_len = 0;
241 /* record remote hostname or ip */
242 u_int utmp_len = UT_HOSTSIZE;
244 /* options.max_startup sized array of fd ints */
245 int *startup_pipes = NULL;
246 int startup_pipe; /* in child */
248 /* variables used for privilege separation */
249 int use_privsep = -1;
250 struct monitor *pmonitor = NULL;
252 /* global authentication context */
253 Authctxt *the_authctxt = NULL;
255 /* sshd_config buffer */
258 /* message to be displayed after login */
261 /* Unprivileged user */
262 struct passwd *privsep_pw = NULL;
264 /* Prototypes for various functions defined later in this file. */
265 void destroy_sensitive_data(void);
266 void demote_sensitive_data(void);
268 static void do_ssh1_kex(void);
269 static void do_ssh2_kex(void);
272 * Close all listening sockets
275 close_listen_socks(void)
279 for (i = 0; i < num_listen_socks; i++)
280 close(listen_socks[i]);
281 num_listen_socks = -1;
285 close_startup_pipes(void)
290 for (i = 0; i < options.max_startups; i++)
291 if (startup_pipes[i] != -1)
292 close(startup_pipes[i]);
296 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
297 * the effect is to reread the configuration file (and to regenerate
303 sighup_handler(int sig)
305 int save_errno = errno;
308 signal(SIGHUP, sighup_handler);
313 * Called from the main program after receiving SIGHUP.
314 * Restarts the server.
319 logit("Received SIGHUP; restarting.");
320 close_listen_socks();
321 close_startup_pipes();
322 alarm(0); /* alarm timer persists across exec */
323 execv(saved_argv[0], saved_argv);
324 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
330 * Generic signal handler for terminating signals in the master daemon.
334 sigterm_handler(int sig)
336 received_sigterm = sig;
340 * SIGCHLD handler. This is called whenever a child dies. This will then
341 * reap any zombies left by exited children.
345 main_sigchld_handler(int sig)
347 int save_errno = errno;
351 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
352 (pid < 0 && errno == EINTR))
355 signal(SIGCHLD, main_sigchld_handler);
360 * Signal handler for the alarm after the login grace period has expired.
364 grace_alarm_handler(int sig)
366 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
367 kill(pmonitor->m_pid, SIGALRM);
369 /* Log error and exit. */
370 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
374 * Signal handler for the key regeneration alarm. Note that this
375 * alarm only occurs in the daemon waiting for connections, and it does not
376 * do anything with the private key or random state before forking.
377 * Thus there should be no concurrency control/asynchronous execution
381 generate_ephemeral_server_key(void)
383 verbose("Generating %s%d bit RSA key.",
384 sensitive_data.server_key ? "new " : "", options.server_key_bits);
385 if (sensitive_data.server_key != NULL)
386 key_free(sensitive_data.server_key);
387 sensitive_data.server_key = key_generate(KEY_RSA1,
388 options.server_key_bits);
389 verbose("RSA key generation complete.");
391 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
397 key_regeneration_alarm(int sig)
399 int save_errno = errno;
401 signal(SIGALRM, SIG_DFL);
407 sshd_exchange_identification(int sock_in, int sock_out)
411 int remote_major, remote_minor;
413 char *s, *newline = "\n";
414 char buf[256]; /* Must not be larger than remote_version. */
415 char remote_version[256]; /* Must be at least as big as buf. */
417 if ((options.protocol & SSH_PROTO_1) &&
418 (options.protocol & SSH_PROTO_2)) {
419 major = PROTOCOL_MAJOR_1;
421 } else if (options.protocol & SSH_PROTO_2) {
422 major = PROTOCOL_MAJOR_2;
423 minor = PROTOCOL_MINOR_2;
426 major = PROTOCOL_MAJOR_1;
427 minor = PROTOCOL_MINOR_1;
429 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s%s", major, minor,
430 SSH_VERSION, newline);
431 server_version_string = xstrdup(buf);
433 /* Send our protocol version identification. */
434 if (atomicio(vwrite, sock_out, server_version_string,
435 strlen(server_version_string))
436 != strlen(server_version_string)) {
437 logit("Could not write ident string to %s", get_remote_ipaddr());
441 /* Read other sides version identification. */
442 memset(buf, 0, sizeof(buf));
443 for (i = 0; i < sizeof(buf) - 1; i++) {
444 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
445 logit("Did not receive identification string from %s",
446 get_remote_ipaddr());
449 if (buf[i] == '\r') {
451 /* Kludge for F-Secure Macintosh < 1.0.2 */
453 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
457 if (buf[i] == '\n') {
462 buf[sizeof(buf) - 1] = 0;
463 client_version_string = xstrdup(buf);
466 * Check that the versions match. In future this might accept
467 * several versions and set appropriate flags to handle them.
469 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
470 &remote_major, &remote_minor, remote_version) != 3) {
471 s = "Protocol mismatch.\n";
472 (void) atomicio(vwrite, sock_out, s, strlen(s));
475 logit("Bad protocol version identification '%.100s' from %s",
476 client_version_string, get_remote_ipaddr());
479 debug("Client protocol version %d.%d; client software version %.100s",
480 remote_major, remote_minor, remote_version);
482 compat_datafellows(remote_version);
484 if (datafellows & SSH_BUG_PROBE) {
485 logit("probed from %s with %s. Don't panic.",
486 get_remote_ipaddr(), client_version_string);
490 if (datafellows & SSH_BUG_SCANNER) {
491 logit("scanned from %s with %s. Don't panic.",
492 get_remote_ipaddr(), client_version_string);
497 switch (remote_major) {
499 if (remote_minor == 99) {
500 if (options.protocol & SSH_PROTO_2)
506 if (!(options.protocol & SSH_PROTO_1)) {
510 if (remote_minor < 3) {
511 packet_disconnect("Your ssh version is too old and "
512 "is no longer supported. Please install a newer version.");
513 } else if (remote_minor == 3) {
514 /* note that this disables agent-forwarding */
519 if (options.protocol & SSH_PROTO_2) {
528 chop(server_version_string);
529 debug("Local version string %.200s", server_version_string);
532 s = "Protocol major versions differ.\n";
533 (void) atomicio(vwrite, sock_out, s, strlen(s));
536 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
538 server_version_string, client_version_string);
543 /* Destroy the host and server keys. They will no longer be needed. */
545 destroy_sensitive_data(void)
549 if (sensitive_data.server_key) {
550 key_free(sensitive_data.server_key);
551 sensitive_data.server_key = NULL;
553 for (i = 0; i < options.num_host_key_files; i++) {
554 if (sensitive_data.host_keys[i]) {
555 key_free(sensitive_data.host_keys[i]);
556 sensitive_data.host_keys[i] = NULL;
559 sensitive_data.ssh1_host_key = NULL;
560 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
563 /* Demote private to public keys for network child */
565 demote_sensitive_data(void)
570 if (sensitive_data.server_key) {
571 tmp = key_demote(sensitive_data.server_key);
572 key_free(sensitive_data.server_key);
573 sensitive_data.server_key = tmp;
576 for (i = 0; i < options.num_host_key_files; i++) {
577 if (sensitive_data.host_keys[i]) {
578 tmp = key_demote(sensitive_data.host_keys[i]);
579 key_free(sensitive_data.host_keys[i]);
580 sensitive_data.host_keys[i] = tmp;
581 if (tmp->type == KEY_RSA1)
582 sensitive_data.ssh1_host_key = tmp;
586 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
590 privsep_preauth_child(void)
595 /* Enable challenge-response authentication for privilege separation */
596 privsep_challenge_enable();
599 arc4random_buf(rnd, sizeof(rnd));
600 RAND_seed(rnd, sizeof(rnd));
602 /* Demote the private keys to public keys. */
603 demote_sensitive_data();
605 /* Change our root directory */
606 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
607 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
609 if (chdir("/") == -1)
610 fatal("chdir(\"/\"): %s", strerror(errno));
612 /* Drop our privileges */
613 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
614 (u_int)privsep_pw->pw_gid);
616 /* XXX not ready, too heavy after chroot */
617 do_setusercontext(privsep_pw);
619 gidset[0] = privsep_pw->pw_gid;
620 if (setgroups(1, gidset) < 0)
621 fatal("setgroups: %.100s", strerror(errno));
622 permanently_set_uid(privsep_pw);
627 privsep_preauth(Authctxt *authctxt)
632 /* Set up unprivileged child process to deal with network data */
633 pmonitor = monitor_init();
634 /* Store a pointer to the kex for later rekeying */
635 pmonitor->m_pkex = &xxx_kex;
639 fatal("fork of unprivileged child failed");
640 } else if (pid != 0) {
641 debug2("Network child is on pid %ld", (long)pid);
643 close(pmonitor->m_recvfd);
644 pmonitor->m_pid = pid;
645 monitor_child_preauth(authctxt, pmonitor);
646 close(pmonitor->m_sendfd);
649 monitor_sync(pmonitor);
651 /* Wait for the child's exit status */
652 while (waitpid(pid, &status, 0) < 0)
659 close(pmonitor->m_sendfd);
661 /* Demote the child */
662 if (getuid() == 0 || geteuid() == 0)
663 privsep_preauth_child();
664 setproctitle("%s", "[net]");
670 privsep_postauth(Authctxt *authctxt)
674 #ifdef DISABLE_FD_PASSING
677 if (authctxt->pw->pw_uid == 0 || options.use_login) {
679 /* File descriptor passing is broken or root login */
684 /* New socket pair */
685 monitor_reinit(pmonitor);
687 pmonitor->m_pid = fork();
688 if (pmonitor->m_pid == -1)
689 fatal("fork of unprivileged child failed");
690 else if (pmonitor->m_pid != 0) {
691 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
692 close(pmonitor->m_recvfd);
693 buffer_clear(&loginmsg);
694 monitor_child_postauth(pmonitor);
700 close(pmonitor->m_sendfd);
702 /* Demote the private keys to public keys. */
703 demote_sensitive_data();
706 arc4random_buf(rnd, sizeof(rnd));
707 RAND_seed(rnd, sizeof(rnd));
709 /* Drop privileges */
710 do_setusercontext(authctxt->pw);
713 /* It is safe now to apply the key state */
714 monitor_apply_keystate(pmonitor);
717 * Tell the packet layer that authentication was successful, since
718 * this information is not part of the key state.
720 packet_set_authenticated();
724 list_hostkey_types(void)
732 for (i = 0; i < options.num_host_key_files; i++) {
733 Key *key = sensitive_data.host_keys[i];
739 if (buffer_len(&b) > 0)
740 buffer_append(&b, ",", 1);
741 p = key_ssh_name(key);
742 buffer_append(&b, p, strlen(p));
746 buffer_append(&b, "\0", 1);
747 ret = xstrdup(buffer_ptr(&b));
749 debug("list_hostkey_types: %s", ret);
754 get_hostkey_by_type(int type)
758 for (i = 0; i < options.num_host_key_files; i++) {
759 Key *key = sensitive_data.host_keys[i];
760 if (key != NULL && key->type == type)
767 get_hostkey_by_index(int ind)
769 if (ind < 0 || ind >= options.num_host_key_files)
771 return (sensitive_data.host_keys[ind]);
775 get_hostkey_index(Key *key)
779 for (i = 0; i < options.num_host_key_files; i++) {
780 if (key == sensitive_data.host_keys[i])
787 * returns 1 if connection should be dropped, 0 otherwise.
788 * dropping starts at connection #max_startups_begin with a probability
789 * of (max_startups_rate/100). the probability increases linearly until
790 * all connections are dropped for startups > max_startups
793 drop_connection(int startups)
797 if (startups < options.max_startups_begin)
799 if (startups >= options.max_startups)
801 if (options.max_startups_rate == 100)
804 p = 100 - options.max_startups_rate;
805 p *= startups - options.max_startups_begin;
806 p /= options.max_startups - options.max_startups_begin;
807 p += options.max_startups_rate;
808 r = arc4random_uniform(100);
810 debug("drop_connection: p %d, r %d", p, r);
811 return (r < p) ? 1 : 0;
817 fprintf(stderr, "%s, %s\n",
818 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
820 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-f config_file]\n"
821 " [-g login_grace_time] [-h host_key_file] [-k key_gen_time]\n"
822 " [-o option] [-p port] [-u len]\n"
828 send_rexec_state(int fd, Buffer *conf)
832 debug3("%s: entering fd = %d config len %d", __func__, fd,
836 * Protocol from reexec master to child:
837 * string configuration
838 * u_int ephemeral_key_follows
839 * bignum e (only if ephemeral_key_follows == 1)
845 * string rngseed (only if OpenSSL is not self-seeded)
848 buffer_put_cstring(&m, buffer_ptr(conf));
850 if (sensitive_data.server_key != NULL &&
851 sensitive_data.server_key->type == KEY_RSA1) {
852 buffer_put_int(&m, 1);
853 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
854 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
855 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
856 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
857 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
858 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
860 buffer_put_int(&m, 0);
862 #ifndef OPENSSL_PRNG_ONLY
863 rexec_send_rng_seed(&m);
866 if (ssh_msg_send(fd, 0, &m) == -1)
867 fatal("%s: ssh_msg_send failed", __func__);
871 debug3("%s: done", __func__);
875 recv_rexec_state(int fd, Buffer *conf)
881 debug3("%s: entering fd = %d", __func__, fd);
885 if (ssh_msg_recv(fd, &m) == -1)
886 fatal("%s: ssh_msg_recv failed", __func__);
887 if (buffer_get_char(&m) != 0)
888 fatal("%s: rexec version mismatch", __func__);
890 cp = buffer_get_string(&m, &len);
892 buffer_append(conf, cp, len + 1);
895 if (buffer_get_int(&m)) {
896 if (sensitive_data.server_key != NULL)
897 key_free(sensitive_data.server_key);
898 sensitive_data.server_key = key_new_private(KEY_RSA1);
899 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
900 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
901 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
902 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
903 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
904 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
905 rsa_generate_additional_parameters(
906 sensitive_data.server_key->rsa);
909 #ifndef OPENSSL_PRNG_ONLY
910 rexec_recv_rng_seed(&m);
915 debug3("%s: done", __func__);
918 /* Accept a connection from inetd */
920 server_accept_inetd(int *sock_in, int *sock_out)
926 close(REEXEC_CONFIG_PASS_FD);
927 *sock_in = *sock_out = dup(STDIN_FILENO);
929 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
930 close(REEXEC_STARTUP_PIPE_FD);
933 *sock_in = dup(STDIN_FILENO);
934 *sock_out = dup(STDOUT_FILENO);
937 * We intentionally do not close the descriptors 0, 1, and 2
938 * as our code for setting the descriptors won't work if
939 * ttyfd happens to be one of those.
941 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
942 dup2(fd, STDIN_FILENO);
943 dup2(fd, STDOUT_FILENO);
944 if (fd > STDOUT_FILENO)
947 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
951 * Listen for TCP connections
956 int ret, listen_sock, on = 1;
958 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
960 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
961 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
963 if (num_listen_socks >= MAX_LISTEN_SOCKS)
964 fatal("Too many listen sockets. "
965 "Enlarge MAX_LISTEN_SOCKS");
966 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
967 ntop, sizeof(ntop), strport, sizeof(strport),
968 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
969 error("getnameinfo failed: %.100s",
970 ssh_gai_strerror(ret));
973 /* Create socket for listening. */
974 listen_sock = socket(ai->ai_family, ai->ai_socktype,
976 if (listen_sock < 0) {
977 /* kernel may not support ipv6 */
978 verbose("socket: %.100s", strerror(errno));
981 if (set_nonblock(listen_sock) == -1) {
986 * Set socket options.
987 * Allow local port reuse in TIME_WAIT.
989 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
990 &on, sizeof(on)) == -1)
991 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
994 /* Only communicate in IPv6 over AF_INET6 sockets. */
995 if (ai->ai_family == AF_INET6) {
996 if (setsockopt(listen_sock, IPPROTO_IPV6, IPV6_V6ONLY,
997 &on, sizeof(on)) == -1)
998 error("setsockopt IPV6_V6ONLY: %s",
1003 debug("Bind to port %s on %s.", strport, ntop);
1005 /* Bind the socket to the desired port. */
1006 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1007 error("Bind to port %s on %s failed: %.200s.",
1008 strport, ntop, strerror(errno));
1012 listen_socks[num_listen_socks] = listen_sock;
1015 /* Start listening on the port. */
1016 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1017 fatal("listen on [%s]:%s: %.100s",
1018 ntop, strport, strerror(errno));
1019 logit("Server listening on %s port %s.", ntop, strport);
1021 freeaddrinfo(options.listen_addrs);
1023 if (!num_listen_socks)
1024 fatal("Cannot bind any address.");
1028 * The main TCP accept loop. Note that, for the non-debug case, returns
1029 * from this function are in a forked subprocess.
1032 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1035 int i, j, ret, maxfd;
1036 int key_used = 0, startups = 0;
1037 int startup_p[2] = { -1 , -1 };
1038 struct sockaddr_storage from;
1042 /* setup fd set for accept */
1045 for (i = 0; i < num_listen_socks; i++)
1046 if (listen_socks[i] > maxfd)
1047 maxfd = listen_socks[i];
1048 /* pipes connected to unauthenticated childs */
1049 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1050 for (i = 0; i < options.max_startups; i++)
1051 startup_pipes[i] = -1;
1054 * Stay listening for connections until the system crashes or
1055 * the daemon is killed with a signal.
1058 if (received_sighup)
1062 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1065 for (i = 0; i < num_listen_socks; i++)
1066 FD_SET(listen_socks[i], fdset);
1067 for (i = 0; i < options.max_startups; i++)
1068 if (startup_pipes[i] != -1)
1069 FD_SET(startup_pipes[i], fdset);
1071 /* Wait in select until there is a connection. */
1072 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1073 if (ret < 0 && errno != EINTR)
1074 error("select: %.100s", strerror(errno));
1075 if (received_sigterm) {
1076 logit("Received signal %d; terminating.",
1077 (int) received_sigterm);
1078 close_listen_socks();
1079 unlink(options.pid_file);
1082 if (key_used && key_do_regen) {
1083 generate_ephemeral_server_key();
1090 for (i = 0; i < options.max_startups; i++)
1091 if (startup_pipes[i] != -1 &&
1092 FD_ISSET(startup_pipes[i], fdset)) {
1094 * the read end of the pipe is ready
1095 * if the child has closed the pipe
1096 * after successful authentication
1097 * or if the child has died
1099 close(startup_pipes[i]);
1100 startup_pipes[i] = -1;
1103 for (i = 0; i < num_listen_socks; i++) {
1104 if (!FD_ISSET(listen_socks[i], fdset))
1106 fromlen = sizeof(from);
1107 *newsock = accept(listen_socks[i],
1108 (struct sockaddr *)&from, &fromlen);
1110 if (errno != EINTR && errno != EAGAIN &&
1111 errno != EWOULDBLOCK)
1112 error("accept: %.100s", strerror(errno));
1115 if (unset_nonblock(*newsock) == -1) {
1119 if (drop_connection(startups) == 1) {
1120 debug("drop connection #%d", startups);
1124 if (pipe(startup_p) == -1) {
1129 if (rexec_flag && socketpair(AF_UNIX,
1130 SOCK_STREAM, 0, config_s) == -1) {
1131 error("reexec socketpair: %s",
1134 close(startup_p[0]);
1135 close(startup_p[1]);
1139 for (j = 0; j < options.max_startups; j++)
1140 if (startup_pipes[j] == -1) {
1141 startup_pipes[j] = startup_p[0];
1142 if (maxfd < startup_p[0])
1143 maxfd = startup_p[0];
1149 * Got connection. Fork a child to handle it, unless
1150 * we are in debugging mode.
1154 * In debugging mode. Close the listening
1155 * socket, and start processing the
1156 * connection without forking.
1158 debug("Server will not fork when running in debugging mode.");
1159 close_listen_socks();
1160 *sock_in = *newsock;
1161 *sock_out = *newsock;
1162 close(startup_p[0]);
1163 close(startup_p[1]);
1167 send_rexec_state(config_s[0],
1175 * Normal production daemon. Fork, and have
1176 * the child process the connection. The
1177 * parent continues listening.
1179 platform_pre_fork();
1180 if ((pid = fork()) == 0) {
1182 * Child. Close the listening and
1183 * max_startup sockets. Start using
1184 * the accepted socket. Reinitialize
1185 * logging (since our pid has changed).
1186 * We break out of the loop to handle
1189 platform_post_fork_child();
1190 startup_pipe = startup_p[1];
1191 close_startup_pipes();
1192 close_listen_socks();
1193 *sock_in = *newsock;
1194 *sock_out = *newsock;
1195 log_init(__progname,
1197 options.log_facility,
1204 /* Parent. Stay in the loop. */
1205 platform_post_fork_parent(pid);
1207 error("fork: %.100s", strerror(errno));
1209 debug("Forked child %ld.", (long)pid);
1211 close(startup_p[1]);
1214 send_rexec_state(config_s[0], &cfg);
1220 * Mark that the key has been used (it
1221 * was "given" to the child).
1223 if ((options.protocol & SSH_PROTO_1) &&
1225 /* Schedule server key regeneration alarm. */
1226 signal(SIGALRM, key_regeneration_alarm);
1227 alarm(options.key_regeneration_time);
1234 * Ensure that our random state differs
1235 * from that of the child
1240 /* child process check (or debug mode) */
1241 if (num_listen_socks < 0)
1248 * Main program for the daemon.
1251 main(int ac, char **av)
1253 extern char *optarg;
1256 int sock_in = -1, sock_out = -1, newsock = -1;
1257 const char *remote_ip;
1258 char *test_user = NULL, *test_host = NULL, *test_addr = NULL;
1260 char *line, *p, *cp;
1261 int config_s[2] = { -1 , -1 };
1262 u_int64_t ibytes, obytes;
1267 #ifdef HAVE_SECUREWARE
1268 (void)set_auth_parameters(ac, av);
1270 __progname = ssh_get_progname(av[0]);
1273 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1276 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1277 for (i = 0; i < ac; i++)
1278 saved_argv[i] = xstrdup(av[i]);
1279 saved_argv[i] = NULL;
1281 #ifndef HAVE_SETPROCTITLE
1282 /* Prepare for later setproctitle emulation */
1283 compat_init_setproctitle(ac, av);
1287 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1288 debug("setgroups(): %.200s", strerror(errno));
1290 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1293 /* Initialize configuration options to their default values. */
1294 initialize_server_options(&options);
1296 /* Parse command-line arguments. */
1297 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeiqrtQRT46")) != -1) {
1300 options.address_family = AF_INET;
1303 options.address_family = AF_INET6;
1306 config_file_name = optarg;
1309 if (debug_flag == 0) {
1311 options.log_level = SYSLOG_LEVEL_DEBUG1;
1312 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1313 options.log_level++;
1335 options.log_level = SYSLOG_LEVEL_QUIET;
1338 options.server_key_bits = (int)strtonum(optarg, 256,
1342 options.ports_from_cmdline = 1;
1343 if (options.num_ports >= MAX_PORTS) {
1344 fprintf(stderr, "too many ports.\n");
1347 options.ports[options.num_ports++] = a2port(optarg);
1348 if (options.ports[options.num_ports-1] == 0) {
1349 fprintf(stderr, "Bad port number.\n");
1354 if ((options.login_grace_time = convtime(optarg)) == -1) {
1355 fprintf(stderr, "Invalid login grace time.\n");
1360 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1361 fprintf(stderr, "Invalid key regeneration interval.\n");
1366 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1367 fprintf(stderr, "too many host keys.\n");
1370 options.host_key_files[options.num_host_key_files++] = optarg;
1380 while ((p = strsep(&cp, ",")) && *p != '\0') {
1381 if (strncmp(p, "addr=", 5) == 0)
1382 test_addr = xstrdup(p + 5);
1383 else if (strncmp(p, "host=", 5) == 0)
1384 test_host = xstrdup(p + 5);
1385 else if (strncmp(p, "user=", 5) == 0)
1386 test_user = xstrdup(p + 5);
1388 fprintf(stderr, "Invalid test "
1389 "mode specification %s\n", p);
1395 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1396 if (utmp_len > MAXHOSTNAMELEN) {
1397 fprintf(stderr, "Invalid utmp length.\n");
1402 line = xstrdup(optarg);
1403 if (process_server_config_line(&options, line,
1404 "command-line", 0, NULL, NULL, NULL, NULL) != 0)
1414 if (rexeced_flag || inetd_flag)
1416 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1417 fatal("sshd re-exec requires execution with an absolute path");
1419 closefrom(REEXEC_MIN_FREE_FD);
1421 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1423 SSLeay_add_all_algorithms();
1426 * Force logging to stderr until we have loaded the private host
1427 * key (unless started from inetd)
1429 log_init(__progname,
1430 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1431 SYSLOG_LEVEL_INFO : options.log_level,
1432 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1433 SYSLOG_FACILITY_AUTH : options.log_facility,
1434 log_stderr || !inetd_flag);
1437 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1438 * root's environment
1440 if (getenv("KRB5CCNAME") != NULL)
1441 unsetenv("KRB5CCNAME");
1444 /* Cray can define user privs drop all privs now!
1445 * Not needed on PRIV_SU systems!
1450 sensitive_data.server_key = NULL;
1451 sensitive_data.ssh1_host_key = NULL;
1452 sensitive_data.have_ssh1_key = 0;
1453 sensitive_data.have_ssh2_key = 0;
1456 * If we're doing an extended config test, make sure we have all of
1457 * the parameters we need. If we're not doing an extended test,
1458 * do not silently ignore connection test params.
1460 if (test_flag >= 2 &&
1461 (test_user != NULL || test_host != NULL || test_addr != NULL)
1462 && (test_user == NULL || test_host == NULL || test_addr == NULL))
1463 fatal("user, host and addr are all required when testing "
1465 if (test_flag < 2 && (test_user != NULL || test_host != NULL ||
1467 fatal("Config test connection parameter (-C) provided without "
1470 /* Fetch our configuration */
1473 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1475 load_server_config(config_file_name, &cfg);
1477 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1478 &cfg, NULL, NULL, NULL);
1482 /* Fill in default values for those options not explicitly set. */
1483 fill_default_server_options(&options);
1485 /* challenge-response is implemented via keyboard interactive */
1486 if (options.challenge_response_authentication)
1487 options.kbd_interactive_authentication = 1;
1489 /* set default channel AF */
1490 channel_set_af(options.address_family);
1492 /* Check that there are no remaining arguments. */
1494 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1498 debug("sshd version %.100s", SSH_RELEASE);
1500 /* Store privilege separation user for later use if required. */
1501 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1502 if (use_privsep || options.kerberos_authentication)
1503 fatal("Privilege separation user %s does not exist",
1506 memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1507 privsep_pw = pwcopy(privsep_pw);
1508 xfree(privsep_pw->pw_passwd);
1509 privsep_pw->pw_passwd = xstrdup("*");
1513 /* load private host keys */
1514 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1516 for (i = 0; i < options.num_host_key_files; i++)
1517 sensitive_data.host_keys[i] = NULL;
1519 for (i = 0; i < options.num_host_key_files; i++) {
1520 key = key_load_private(options.host_key_files[i], "", NULL);
1521 sensitive_data.host_keys[i] = key;
1523 error("Could not load host key: %s",
1524 options.host_key_files[i]);
1525 sensitive_data.host_keys[i] = NULL;
1528 switch (key->type) {
1530 sensitive_data.ssh1_host_key = key;
1531 sensitive_data.have_ssh1_key = 1;
1535 sensitive_data.have_ssh2_key = 1;
1538 debug("private host key: #%d type %d %s", i, key->type,
1541 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1542 logit("Disabling protocol version 1. Could not load host key");
1543 options.protocol &= ~SSH_PROTO_1;
1545 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1546 logit("Disabling protocol version 2. Could not load host key");
1547 options.protocol &= ~SSH_PROTO_2;
1549 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1550 logit("sshd: no hostkeys available -- exiting.");
1554 /* Check certain values for sanity. */
1555 if (options.protocol & SSH_PROTO_1) {
1556 if (options.server_key_bits < 512 ||
1557 options.server_key_bits > 32768) {
1558 fprintf(stderr, "Bad server key size.\n");
1562 * Check that server and host key lengths differ sufficiently. This
1563 * is necessary to make double encryption work with rsaref. Oh, I
1564 * hate software patents. I dont know if this can go? Niels
1566 if (options.server_key_bits >
1567 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1568 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1569 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1570 SSH_KEY_BITS_RESERVED) {
1571 options.server_key_bits =
1572 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1573 SSH_KEY_BITS_RESERVED;
1574 debug("Forcing server key to %d bits to make it differ from host key.",
1575 options.server_key_bits);
1582 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1583 (S_ISDIR(st.st_mode) == 0))
1584 fatal("Missing privilege separation directory: %s",
1585 _PATH_PRIVSEP_CHROOT_DIR);
1588 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1589 (st.st_uid != getuid () ||
1590 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1592 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1594 fatal("%s must be owned by root and not group or "
1595 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1598 if (test_flag > 1) {
1599 if (test_user != NULL && test_addr != NULL && test_host != NULL)
1600 parse_server_match_config(&options, test_user,
1601 test_host, test_addr);
1602 dump_config(&options);
1605 /* Configuration looks good, so exit if in test mode. */
1610 * Clear out any supplemental groups we may have inherited. This
1611 * prevents inadvertent creation of files with bad modes (in the
1612 * portable version at least, it's certainly possible for PAM
1613 * to create a file, and we can't control the code in every
1614 * module which might be used).
1616 if (setgroups(0, NULL) < 0)
1617 debug("setgroups() failed: %.200s", strerror(errno));
1620 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1621 for (i = 0; i < rexec_argc; i++) {
1622 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1623 rexec_argv[i] = saved_argv[i];
1625 rexec_argv[rexec_argc] = "-R";
1626 rexec_argv[rexec_argc + 1] = NULL;
1629 /* Ensure that umask disallows at least group and world write */
1630 new_umask = umask(0077) | 0022;
1631 (void) umask(new_umask);
1633 /* Initialize the log (it is reinitialized below in case we forked). */
1634 if (debug_flag && (!inetd_flag || rexeced_flag))
1636 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1639 * If not in debugging mode, and not started from inetd, disconnect
1640 * from the controlling terminal, and fork. The original process
1643 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1646 #endif /* TIOCNOTTY */
1647 if (daemon(0, 0) < 0)
1648 fatal("daemon() failed: %.200s", strerror(errno));
1650 /* Disconnect from the controlling tty. */
1652 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1654 (void) ioctl(fd, TIOCNOTTY, NULL);
1657 #endif /* TIOCNOTTY */
1659 /* Reinitialize the log (because of the fork above). */
1660 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1662 /* Initialize the random number generator. */
1665 /* Chdir to the root directory so that the current disk can be
1666 unmounted if desired. */
1669 /* ignore SIGPIPE */
1670 signal(SIGPIPE, SIG_IGN);
1672 /* Get a connection, either from inetd or a listening TCP socket */
1674 server_accept_inetd(&sock_in, &sock_out);
1678 if (options.protocol & SSH_PROTO_1)
1679 generate_ephemeral_server_key();
1681 signal(SIGHUP, sighup_handler);
1682 signal(SIGCHLD, main_sigchld_handler);
1683 signal(SIGTERM, sigterm_handler);
1684 signal(SIGQUIT, sigterm_handler);
1687 * Write out the pid file after the sigterm handler
1688 * is setup and the listen sockets are bound
1691 FILE *f = fopen(options.pid_file, "w");
1694 error("Couldn't create pid file \"%s\": %s",
1695 options.pid_file, strerror(errno));
1697 fprintf(f, "%ld\n", (long) getpid());
1702 /* Accept a connection and return in a forked child */
1703 server_accept_loop(&sock_in, &sock_out,
1704 &newsock, config_s);
1707 /* This is the child processing a new connection. */
1708 setproctitle("%s", "[accepted]");
1711 * Create a new session and process group since the 4.4BSD
1712 * setlogin() affects the entire process group. We don't
1713 * want the child to be able to affect the parent.
1715 #if !defined(SSHD_ACQUIRES_CTTY)
1717 * If setsid is called, on some platforms sshd will later acquire a
1718 * controlling terminal which will result in "could not set
1719 * controlling tty" errors.
1721 if (!debug_flag && !inetd_flag && setsid() < 0)
1722 error("setsid: %.100s", strerror(errno));
1728 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1729 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1730 dup2(newsock, STDIN_FILENO);
1731 dup2(STDIN_FILENO, STDOUT_FILENO);
1732 if (startup_pipe == -1)
1733 close(REEXEC_STARTUP_PIPE_FD);
1735 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1737 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1739 if (startup_pipe != -1)
1740 close(startup_pipe);
1742 execv(rexec_argv[0], rexec_argv);
1744 /* Reexec has failed, fall back and continue */
1745 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1746 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1747 log_init(__progname, options.log_level,
1748 options.log_facility, log_stderr);
1751 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1753 close(REEXEC_CONFIG_PASS_FD);
1754 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1755 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1756 dup2(fd, STDIN_FILENO);
1757 dup2(fd, STDOUT_FILENO);
1758 if (fd > STDERR_FILENO)
1761 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1762 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1766 * Disable the key regeneration alarm. We will not regenerate the
1767 * key since we are no longer in a position to give it to anyone. We
1768 * will not restart on SIGHUP since it no longer makes sense.
1771 signal(SIGALRM, SIG_DFL);
1772 signal(SIGHUP, SIG_DFL);
1773 signal(SIGTERM, SIG_DFL);
1774 signal(SIGQUIT, SIG_DFL);
1775 signal(SIGCHLD, SIG_DFL);
1776 signal(SIGINT, SIG_DFL);
1780 * Initialize the resolver. This may not happen automatically
1781 * before privsep chroot().
1783 if ((_res.options & RES_INIT) == 0) {
1784 debug("res_init()");
1789 * Force GSS-API to parse its configuration and load any
1790 * mechanism plugins.
1794 OM_uint32 minor_status;
1795 gss_indicate_mechs(&minor_status, &mechs);
1796 gss_release_oid_set(&minor_status, &mechs);
1802 * Register our connection. This turns encryption off because we do
1805 packet_set_connection(sock_in, sock_out);
1806 packet_set_server();
1808 /* Set SO_KEEPALIVE if requested. */
1809 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1810 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1811 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1813 if ((remote_port = get_remote_port()) < 0) {
1814 debug("get_remote_port failed");
1819 * We use get_canonical_hostname with usedns = 0 instead of
1820 * get_remote_ipaddr here so IP options will be checked.
1822 (void) get_canonical_hostname(0);
1824 * The rest of the code depends on the fact that
1825 * get_remote_ipaddr() caches the remote ip, even if
1826 * the socket goes away.
1828 remote_ip = get_remote_ipaddr();
1830 #ifdef SSH_AUDIT_EVENTS
1831 audit_connection_from(remote_ip, remote_port);
1834 allow_severity = options.log_facility|LOG_INFO;
1835 deny_severity = options.log_facility|LOG_WARNING;
1836 /* Check whether logins are denied from this host. */
1837 if (packet_connection_is_on_socket()) {
1838 struct request_info req;
1840 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1843 if (!hosts_access(&req)) {
1844 debug("Connection refused by tcp wrapper");
1847 fatal("libwrap refuse returns");
1850 #endif /* LIBWRAP */
1852 /* Log the connection. */
1853 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1856 * We don't want to listen forever unless the other side
1857 * successfully authenticates itself. So we set up an alarm which is
1858 * cleared after successful authentication. A limit of zero
1859 * indicates no limit. Note that we don't set the alarm in debugging
1860 * mode; it is just annoying to have the server exit just when you
1861 * are about to discover the bug.
1863 signal(SIGALRM, grace_alarm_handler);
1865 alarm(options.login_grace_time);
1867 sshd_exchange_identification(sock_in, sock_out);
1869 /* In inetd mode, generate ephemeral key only for proto 1 connections */
1870 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
1871 generate_ephemeral_server_key();
1873 packet_set_nonblocking();
1875 /* allocate authentication context */
1876 authctxt = xcalloc(1, sizeof(*authctxt));
1878 authctxt->loginmsg = &loginmsg;
1880 /* XXX global for cleanup, access from other modules */
1881 the_authctxt = authctxt;
1883 /* prepare buffer to collect messages to display to user after login */
1884 buffer_init(&loginmsg);
1887 if (privsep_preauth(authctxt) == 1)
1890 /* perform the key exchange */
1891 /* authenticate user and start session */
1894 do_authentication2(authctxt);
1897 do_authentication(authctxt);
1900 * If we use privilege separation, the unprivileged child transfers
1901 * the current keystate and exits
1904 mm_send_keystate(pmonitor);
1910 * Cancel the alarm we set to limit the time taken for
1914 signal(SIGALRM, SIG_DFL);
1915 authctxt->authenticated = 1;
1916 if (startup_pipe != -1) {
1917 close(startup_pipe);
1921 #ifdef SSH_AUDIT_EVENTS
1922 audit_event(SSH_AUTH_SUCCESS);
1926 if (options.gss_authentication) {
1927 temporarily_use_uid(authctxt->pw);
1928 ssh_gssapi_storecreds();
1933 if (options.use_pam) {
1940 * In privilege separation, we fork another child and prepare
1941 * file descriptor passing.
1944 privsep_postauth(authctxt);
1945 /* the monitor process [priv] will not return */
1947 destroy_sensitive_data();
1950 packet_set_timeout(options.client_alive_interval,
1951 options.client_alive_count_max);
1953 /* Start session. */
1954 do_authenticated(authctxt);
1956 /* The connection has been terminated. */
1957 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1958 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1959 verbose("Transferred: sent %llu, received %llu bytes", obytes, ibytes);
1961 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1964 if (options.use_pam)
1966 #endif /* USE_PAM */
1968 #ifdef SSH_AUDIT_EVENTS
1969 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
1981 * Decrypt session_key_int using our private server key and private host key
1982 * (key with larger modulus first).
1985 ssh1_session_key(BIGNUM *session_key_int)
1989 if (BN_cmp(sensitive_data.server_key->rsa->n,
1990 sensitive_data.ssh1_host_key->rsa->n) > 0) {
1991 /* Server key has bigger modulus. */
1992 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1993 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1994 SSH_KEY_BITS_RESERVED) {
1995 fatal("do_connection: %s: "
1996 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1997 get_remote_ipaddr(),
1998 BN_num_bits(sensitive_data.server_key->rsa->n),
1999 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2000 SSH_KEY_BITS_RESERVED);
2002 if (rsa_private_decrypt(session_key_int, session_key_int,
2003 sensitive_data.server_key->rsa) <= 0)
2005 if (rsa_private_decrypt(session_key_int, session_key_int,
2006 sensitive_data.ssh1_host_key->rsa) <= 0)
2009 /* Host key has bigger modulus (or they are equal). */
2010 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2011 BN_num_bits(sensitive_data.server_key->rsa->n) +
2012 SSH_KEY_BITS_RESERVED) {
2013 fatal("do_connection: %s: "
2014 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2015 get_remote_ipaddr(),
2016 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2017 BN_num_bits(sensitive_data.server_key->rsa->n),
2018 SSH_KEY_BITS_RESERVED);
2020 if (rsa_private_decrypt(session_key_int, session_key_int,
2021 sensitive_data.ssh1_host_key->rsa) < 0)
2023 if (rsa_private_decrypt(session_key_int, session_key_int,
2024 sensitive_data.server_key->rsa) < 0)
2037 BIGNUM *session_key_int;
2038 u_char session_key[SSH_SESSION_KEY_LENGTH];
2040 u_int cipher_type, auth_mask, protocol_flags;
2043 * Generate check bytes that the client must send back in the user
2044 * packet in order for it to be accepted; this is used to defy ip
2045 * spoofing attacks. Note that this only works against somebody
2046 * doing IP spoofing from a remote machine; any machine on the local
2047 * network can still see outgoing packets and catch the random
2048 * cookie. This only affects rhosts authentication, and this is one
2049 * of the reasons why it is inherently insecure.
2051 arc4random_buf(cookie, sizeof(cookie));
2054 * Send our public key. We include in the packet 64 bits of random
2055 * data that must be matched in the reply in order to prevent IP
2058 packet_start(SSH_SMSG_PUBLIC_KEY);
2059 for (i = 0; i < 8; i++)
2060 packet_put_char(cookie[i]);
2062 /* Store our public server RSA key. */
2063 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2064 packet_put_bignum(sensitive_data.server_key->rsa->e);
2065 packet_put_bignum(sensitive_data.server_key->rsa->n);
2067 /* Store our public host RSA key. */
2068 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2069 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2070 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2072 /* Put protocol flags. */
2073 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2075 /* Declare which ciphers we support. */
2076 packet_put_int(cipher_mask_ssh1(0));
2078 /* Declare supported authentication types. */
2080 if (options.rhosts_rsa_authentication)
2081 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2082 if (options.rsa_authentication)
2083 auth_mask |= 1 << SSH_AUTH_RSA;
2084 if (options.challenge_response_authentication == 1)
2085 auth_mask |= 1 << SSH_AUTH_TIS;
2086 if (options.password_authentication)
2087 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2088 packet_put_int(auth_mask);
2090 /* Send the packet and wait for it to be sent. */
2092 packet_write_wait();
2094 debug("Sent %d bit server key and %d bit host key.",
2095 BN_num_bits(sensitive_data.server_key->rsa->n),
2096 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2098 /* Read clients reply (cipher type and session key). */
2099 packet_read_expect(SSH_CMSG_SESSION_KEY);
2101 /* Get cipher type and check whether we accept this. */
2102 cipher_type = packet_get_char();
2104 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2105 packet_disconnect("Warning: client selects unsupported cipher.");
2107 /* Get check bytes from the packet. These must match those we
2108 sent earlier with the public key packet. */
2109 for (i = 0; i < 8; i++)
2110 if (cookie[i] != packet_get_char())
2111 packet_disconnect("IP Spoofing check bytes do not match.");
2113 debug("Encryption type: %.200s", cipher_name(cipher_type));
2115 /* Get the encrypted integer. */
2116 if ((session_key_int = BN_new()) == NULL)
2117 fatal("do_ssh1_kex: BN_new failed");
2118 packet_get_bignum(session_key_int);
2120 protocol_flags = packet_get_int();
2121 packet_set_protocol_flags(protocol_flags);
2124 /* Decrypt session_key_int using host/server keys */
2125 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2128 * Extract session key from the decrypted integer. The key is in the
2129 * least significant 256 bits of the integer; the first byte of the
2130 * key is in the highest bits.
2133 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2134 len = BN_num_bytes(session_key_int);
2135 if (len < 0 || (u_int)len > sizeof(session_key)) {
2136 error("do_ssh1_kex: bad session key len from %s: "
2137 "session_key_int %d > sizeof(session_key) %lu",
2138 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2141 memset(session_key, 0, sizeof(session_key));
2142 BN_bn2bin(session_key_int,
2143 session_key + sizeof(session_key) - len);
2145 derive_ssh1_session_id(
2146 sensitive_data.ssh1_host_key->rsa->n,
2147 sensitive_data.server_key->rsa->n,
2148 cookie, session_id);
2150 * Xor the first 16 bytes of the session key with the
2153 for (i = 0; i < 16; i++)
2154 session_key[i] ^= session_id[i];
2158 int bytes = BN_num_bytes(session_key_int);
2159 u_char *buf = xmalloc(bytes);
2162 logit("do_connection: generating a fake encryption key");
2163 BN_bn2bin(session_key_int, buf);
2165 MD5_Update(&md, buf, bytes);
2166 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2167 MD5_Final(session_key, &md);
2169 MD5_Update(&md, session_key, 16);
2170 MD5_Update(&md, buf, bytes);
2171 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2172 MD5_Final(session_key + 16, &md);
2173 memset(buf, 0, bytes);
2175 for (i = 0; i < 16; i++)
2176 session_id[i] = session_key[i] ^ session_key[i + 16];
2178 /* Destroy the private and public keys. No longer. */
2179 destroy_sensitive_data();
2182 mm_ssh1_session_id(session_id);
2184 /* Destroy the decrypted integer. It is no longer needed. */
2185 BN_clear_free(session_key_int);
2187 /* Set the session key. From this on all communications will be encrypted. */
2188 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2190 /* Destroy our copy of the session key. It is no longer needed. */
2191 memset(session_key, 0, sizeof(session_key));
2193 debug("Received session key; encryption turned on.");
2195 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2196 packet_start(SSH_SMSG_SUCCESS);
2198 packet_write_wait();
2202 * SSH2 key exchange: diffie-hellman-group1-sha1
2209 if (options.ciphers != NULL) {
2210 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2211 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2213 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2214 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2215 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2216 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2218 if (options.macs != NULL) {
2219 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2220 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2222 if (options.compression == COMP_NONE) {
2223 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2224 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2225 } else if (options.compression == COMP_DELAYED) {
2226 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2227 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2230 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2232 /* start key exchange */
2233 kex = kex_setup(myproposal);
2234 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2235 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2236 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2237 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2239 kex->client_version_string=client_version_string;
2240 kex->server_version_string=server_version_string;
2241 kex->load_host_key=&get_hostkey_by_type;
2242 kex->host_key_index=&get_hostkey_index;
2246 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2248 session_id2 = kex->session_id;
2249 session_id2_len = kex->session_id_len;
2252 /* send 1st encrypted/maced/compressed message */
2253 packet_start(SSH2_MSG_IGNORE);
2254 packet_put_cstring("markus");
2256 packet_write_wait();
2261 /* server specific fatal cleanup */
2266 do_cleanup(the_authctxt);
2267 #ifdef SSH_AUDIT_EVENTS
2268 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2269 if (!use_privsep || mm_is_monitor())
2270 audit_event(SSH_CONNECTION_ABANDON);