1 /* $OpenBSD: sshd.c,v 1.381 2011/01/11 06:13:10 djm 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.
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>
53 #ifdef HAVE_SYS_TIME_H
54 # include <sys/time.h>
56 #include "openbsd-compat/sys-tree.h"
57 #include "openbsd-compat/sys-queue.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>
102 #include "myproposal.h"
103 #include "authfile.h"
104 #include "pathnames.h"
105 #include "atomicio.h"
106 #include "canohost.h"
107 #include "hostfile.h"
111 #include "dispatch.h"
112 #include "channels.h"
114 #include "monitor_mm.h"
119 #include "monitor_wrap.h"
123 #ifdef USE_SECURITY_SESSION_API
124 #include <Security/AuthSession.h>
139 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
140 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
141 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
142 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
144 extern char *__progname;
146 /* Server configuration options. */
147 ServerOptions options;
149 /* Name of the server configuration file. */
150 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
153 * Debug mode flag. This can be set on the command line. If debug
154 * mode is enabled, extra debugging output will be sent to the system
155 * log, the daemon will not go to background, and will exit after processing
156 * the first connection.
160 /* Flag indicating that the daemon should only test the configuration and keys. */
163 /* Flag indicating that the daemon is being started from inetd. */
166 /* Flag indicating that sshd should not detach and become a daemon. */
167 int no_daemon_flag = 0;
169 /* debug goes to stderr unless inetd_flag is set */
172 /* Saved arguments to main(). */
177 int rexeced_flag = 0;
183 * The sockets that the server is listening; this is used in the SIGHUP
186 #define MAX_LISTEN_SOCKS 16
187 int listen_socks[MAX_LISTEN_SOCKS];
188 int num_listen_socks = 0;
191 * the client's version string, passed by sshd2 in compat mode. if != NULL,
192 * sshd will skip the version-number exchange
194 char *client_version_string = NULL;
195 char *server_version_string = NULL;
197 /* for rekeying XXX fixme */
201 * Any really sensitive data in the application is contained in this
202 * structure. The idea is that this structure could be locked into memory so
203 * that the pages do not get written into swap. However, there are some
204 * problems. The private key contains BIGNUMs, and we do not (in principle)
205 * have access to the internals of them, and locking just the structure is
206 * not very useful. Currently, memory locking is not implemented.
209 Key *server_key; /* ephemeral server key */
210 Key *ssh1_host_key; /* ssh1 host key */
211 Key **host_keys; /* all private host keys */
212 Key **host_certificates; /* all public host certificates */
215 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
219 * Flag indicating whether the RSA server key needs to be regenerated.
220 * Is set in the SIGALRM handler and cleared when the key is regenerated.
222 static volatile sig_atomic_t key_do_regen = 0;
224 /* This is set to true when a signal is received. */
225 static volatile sig_atomic_t received_sighup = 0;
226 static volatile sig_atomic_t received_sigterm = 0;
228 /* session identifier, used by RSA-auth */
229 u_char session_id[16];
232 u_char *session_id2 = NULL;
233 u_int session_id2_len = 0;
235 /* record remote hostname or ip */
236 u_int utmp_len = MAXHOSTNAMELEN;
238 /* options.max_startup sized array of fd ints */
239 int *startup_pipes = NULL;
240 int startup_pipe; /* in child */
242 /* variables used for privilege separation */
243 int use_privsep = -1;
244 struct monitor *pmonitor = NULL;
246 /* global authentication context */
247 Authctxt *the_authctxt = NULL;
249 /* sshd_config buffer */
252 /* message to be displayed after login */
255 /* Unprivileged user */
256 struct passwd *privsep_pw = NULL;
258 /* Prototypes for various functions defined later in this file. */
259 void destroy_sensitive_data(void);
260 void demote_sensitive_data(void);
262 static void do_ssh1_kex(void);
263 static void do_ssh2_kex(void);
266 * Close all listening sockets
269 close_listen_socks(void)
273 for (i = 0; i < num_listen_socks; i++)
274 close(listen_socks[i]);
275 num_listen_socks = -1;
279 close_startup_pipes(void)
284 for (i = 0; i < options.max_startups; i++)
285 if (startup_pipes[i] != -1)
286 close(startup_pipes[i]);
290 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
291 * the effect is to reread the configuration file (and to regenerate
297 sighup_handler(int sig)
299 int save_errno = errno;
302 signal(SIGHUP, sighup_handler);
307 * Called from the main program after receiving SIGHUP.
308 * Restarts the server.
313 logit("Received SIGHUP; restarting.");
314 close_listen_socks();
315 close_startup_pipes();
316 alarm(0); /* alarm timer persists across exec */
317 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
318 execv(saved_argv[0], saved_argv);
319 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
325 * Generic signal handler for terminating signals in the master daemon.
329 sigterm_handler(int sig)
331 received_sigterm = sig;
335 * SIGCHLD handler. This is called whenever a child dies. This will then
336 * reap any zombies left by exited children.
340 main_sigchld_handler(int sig)
342 int save_errno = errno;
346 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
347 (pid < 0 && errno == EINTR))
350 signal(SIGCHLD, main_sigchld_handler);
355 * Signal handler for the alarm after the login grace period has expired.
359 grace_alarm_handler(int sig)
361 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
362 kill(pmonitor->m_pid, SIGALRM);
364 /* Log error and exit. */
365 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
369 * Signal handler for the key regeneration alarm. Note that this
370 * alarm only occurs in the daemon waiting for connections, and it does not
371 * do anything with the private key or random state before forking.
372 * Thus there should be no concurrency control/asynchronous execution
376 generate_ephemeral_server_key(void)
378 verbose("Generating %s%d bit RSA key.",
379 sensitive_data.server_key ? "new " : "", options.server_key_bits);
380 if (sensitive_data.server_key != NULL)
381 key_free(sensitive_data.server_key);
382 sensitive_data.server_key = key_generate(KEY_RSA1,
383 options.server_key_bits);
384 verbose("RSA key generation complete.");
386 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
392 key_regeneration_alarm(int sig)
394 int save_errno = errno;
396 signal(SIGALRM, SIG_DFL);
402 sshd_exchange_identification(int sock_in, int sock_out)
406 int remote_major, remote_minor;
408 char *s, *newline = "\n";
409 char buf[256]; /* Must not be larger than remote_version. */
410 char remote_version[256]; /* Must be at least as big as buf. */
412 if ((options.protocol & SSH_PROTO_1) &&
413 (options.protocol & SSH_PROTO_2)) {
414 major = PROTOCOL_MAJOR_1;
416 } else if (options.protocol & SSH_PROTO_2) {
417 major = PROTOCOL_MAJOR_2;
418 minor = PROTOCOL_MINOR_2;
421 major = PROTOCOL_MAJOR_1;
422 minor = PROTOCOL_MINOR_1;
424 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s%s", major, minor,
425 options.debian_banner ? SSH_RELEASE : SSH_RELEASE_MINIMUM,
427 server_version_string = xstrdup(buf);
429 /* Send our protocol version identification. */
430 if (roaming_atomicio(vwrite, sock_out, server_version_string,
431 strlen(server_version_string))
432 != strlen(server_version_string)) {
433 logit("Could not write ident string to %s", get_remote_ipaddr());
437 /* Read other sides version identification. */
438 memset(buf, 0, sizeof(buf));
439 for (i = 0; i < sizeof(buf) - 1; i++) {
440 if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
441 logit("Did not receive identification string from %s",
442 get_remote_ipaddr());
445 if (buf[i] == '\r') {
447 /* Kludge for F-Secure Macintosh < 1.0.2 */
449 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
453 if (buf[i] == '\n') {
458 buf[sizeof(buf) - 1] = 0;
459 client_version_string = xstrdup(buf);
462 * Check that the versions match. In future this might accept
463 * several versions and set appropriate flags to handle them.
465 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
466 &remote_major, &remote_minor, remote_version) != 3) {
467 s = "Protocol mismatch.\n";
468 (void) atomicio(vwrite, sock_out, s, strlen(s));
471 logit("Bad protocol version identification '%.100s' from %s",
472 client_version_string, get_remote_ipaddr());
475 debug("Client protocol version %d.%d; client software version %.100s",
476 remote_major, remote_minor, remote_version);
478 compat_datafellows(remote_version);
480 if (datafellows & SSH_BUG_PROBE) {
481 logit("probed from %s with %s. Don't panic.",
482 get_remote_ipaddr(), client_version_string);
486 if (datafellows & SSH_BUG_SCANNER) {
487 logit("scanned from %s with %s. Don't panic.",
488 get_remote_ipaddr(), client_version_string);
493 switch (remote_major) {
495 if (remote_minor == 99) {
496 if (options.protocol & SSH_PROTO_2)
502 if (!(options.protocol & SSH_PROTO_1)) {
506 if (remote_minor < 3) {
507 packet_disconnect("Your ssh version is too old and "
508 "is no longer supported. Please install a newer version.");
509 } else if (remote_minor == 3) {
510 /* note that this disables agent-forwarding */
515 if (options.protocol & SSH_PROTO_2) {
524 chop(server_version_string);
525 debug("Local version string %.200s", server_version_string);
528 s = "Protocol major versions differ.\n";
529 (void) atomicio(vwrite, sock_out, s, strlen(s));
532 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
534 server_version_string, client_version_string);
539 /* Destroy the host and server keys. They will no longer be needed. */
541 destroy_sensitive_data(void)
545 if (sensitive_data.server_key) {
546 key_free(sensitive_data.server_key);
547 sensitive_data.server_key = NULL;
549 for (i = 0; i < options.num_host_key_files; i++) {
550 if (sensitive_data.host_keys[i]) {
551 key_free(sensitive_data.host_keys[i]);
552 sensitive_data.host_keys[i] = NULL;
554 if (sensitive_data.host_certificates[i]) {
555 key_free(sensitive_data.host_certificates[i]);
556 sensitive_data.host_certificates[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;
584 /* Certs do not need demotion */
587 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
591 privsep_preauth_child(void)
596 /* Enable challenge-response authentication for privilege separation */
597 privsep_challenge_enable();
600 arc4random_buf(rnd, sizeof(rnd));
601 RAND_seed(rnd, sizeof(rnd));
603 /* Demote the private keys to public keys. */
604 demote_sensitive_data();
606 /* Change our root directory */
607 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
608 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
610 if (chdir("/") == -1)
611 fatal("chdir(\"/\"): %s", strerror(errno));
613 /* Drop our privileges */
614 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
615 (u_int)privsep_pw->pw_gid);
617 /* XXX not ready, too heavy after chroot */
618 do_setusercontext(privsep_pw);
620 gidset[0] = privsep_pw->pw_gid;
621 if (setgroups(1, gidset) < 0)
622 fatal("setgroups: %.100s", strerror(errno));
623 permanently_set_uid(privsep_pw);
628 privsep_preauth(Authctxt *authctxt)
633 /* Set up unprivileged child process to deal with network data */
634 pmonitor = monitor_init();
635 /* Store a pointer to the kex for later rekeying */
636 pmonitor->m_pkex = &xxx_kex;
640 fatal("fork of unprivileged child failed");
641 } else if (pid != 0) {
642 debug2("Network child is on pid %ld", (long)pid);
644 close(pmonitor->m_recvfd);
645 pmonitor->m_pid = pid;
646 monitor_child_preauth(authctxt, pmonitor);
647 close(pmonitor->m_sendfd);
650 monitor_sync(pmonitor);
652 /* Wait for the child's exit status */
653 while (waitpid(pid, &status, 0) < 0)
660 close(pmonitor->m_sendfd);
662 /* Demote the child */
663 if (getuid() == 0 || geteuid() == 0)
664 privsep_preauth_child();
665 setproctitle("%s", "[net]");
671 privsep_postauth(Authctxt *authctxt)
675 #ifdef DISABLE_FD_PASSING
678 if (authctxt->pw->pw_uid == 0 || options.use_login) {
680 /* File descriptor passing is broken or root login */
685 /* New socket pair */
686 monitor_reinit(pmonitor);
688 pmonitor->m_pid = fork();
689 if (pmonitor->m_pid == -1)
690 fatal("fork of unprivileged child failed");
691 else if (pmonitor->m_pid != 0) {
692 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
693 close(pmonitor->m_recvfd);
694 buffer_clear(&loginmsg);
695 monitor_child_postauth(pmonitor);
701 close(pmonitor->m_sendfd);
703 /* Demote the private keys to public keys. */
704 demote_sensitive_data();
707 arc4random_buf(rnd, sizeof(rnd));
708 RAND_seed(rnd, sizeof(rnd));
710 /* Drop privileges */
711 do_setusercontext(authctxt->pw, authctxt->role);
714 /* It is safe now to apply the key state */
715 monitor_apply_keystate(pmonitor);
718 * Tell the packet layer that authentication was successful, since
719 * this information is not part of the key state.
721 packet_set_authenticated();
725 list_hostkey_types(void)
734 for (i = 0; i < options.num_host_key_files; i++) {
735 key = sensitive_data.host_keys[i];
742 if (buffer_len(&b) > 0)
743 buffer_append(&b, ",", 1);
744 p = key_ssh_name(key);
745 buffer_append(&b, p, strlen(p));
748 /* If the private key has a cert peer, then list that too */
749 key = sensitive_data.host_certificates[i];
753 case KEY_RSA_CERT_V00:
754 case KEY_DSA_CERT_V00:
758 if (buffer_len(&b) > 0)
759 buffer_append(&b, ",", 1);
760 p = key_ssh_name(key);
761 buffer_append(&b, p, strlen(p));
765 buffer_append(&b, "\0", 1);
766 ret = xstrdup(buffer_ptr(&b));
768 debug("list_hostkey_types: %s", ret);
773 get_hostkey_by_type(int type, int need_private)
778 for (i = 0; i < options.num_host_key_files; i++) {
780 case KEY_RSA_CERT_V00:
781 case KEY_DSA_CERT_V00:
785 key = sensitive_data.host_certificates[i];
788 key = sensitive_data.host_keys[i];
791 if (key != NULL && key->type == type)
792 return need_private ?
793 sensitive_data.host_keys[i] : key;
799 get_hostkey_public_by_type(int type)
801 return get_hostkey_by_type(type, 0);
805 get_hostkey_private_by_type(int type)
807 return get_hostkey_by_type(type, 1);
811 get_hostkey_by_index(int ind)
813 if (ind < 0 || ind >= options.num_host_key_files)
815 return (sensitive_data.host_keys[ind]);
819 get_hostkey_index(Key *key)
823 for (i = 0; i < options.num_host_key_files; i++) {
824 if (key_is_cert(key)) {
825 if (key == sensitive_data.host_certificates[i])
828 if (key == sensitive_data.host_keys[i])
836 * returns 1 if connection should be dropped, 0 otherwise.
837 * dropping starts at connection #max_startups_begin with a probability
838 * of (max_startups_rate/100). the probability increases linearly until
839 * all connections are dropped for startups > max_startups
842 drop_connection(int startups)
846 if (startups < options.max_startups_begin)
848 if (startups >= options.max_startups)
850 if (options.max_startups_rate == 100)
853 p = 100 - options.max_startups_rate;
854 p *= startups - options.max_startups_begin;
855 p /= options.max_startups - options.max_startups_begin;
856 p += options.max_startups_rate;
857 r = arc4random_uniform(100);
859 debug("drop_connection: p %d, r %d", p, r);
860 return (r < p) ? 1 : 0;
866 fprintf(stderr, "%s, %s\n",
867 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
869 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
870 " [-f config_file] [-g login_grace_time] [-h host_key_file]\n"
871 " [-k key_gen_time] [-o option] [-p port] [-u len]\n"
877 send_rexec_state(int fd, Buffer *conf)
881 debug3("%s: entering fd = %d config len %d", __func__, fd,
885 * Protocol from reexec master to child:
886 * string configuration
887 * u_int ephemeral_key_follows
888 * bignum e (only if ephemeral_key_follows == 1)
894 * string rngseed (only if OpenSSL is not self-seeded)
897 buffer_put_cstring(&m, buffer_ptr(conf));
899 if (sensitive_data.server_key != NULL &&
900 sensitive_data.server_key->type == KEY_RSA1) {
901 buffer_put_int(&m, 1);
902 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
903 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
904 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
905 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
906 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
907 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
909 buffer_put_int(&m, 0);
911 #ifndef OPENSSL_PRNG_ONLY
912 rexec_send_rng_seed(&m);
915 if (ssh_msg_send(fd, 0, &m) == -1)
916 fatal("%s: ssh_msg_send failed", __func__);
920 debug3("%s: done", __func__);
924 recv_rexec_state(int fd, Buffer *conf)
930 debug3("%s: entering fd = %d", __func__, fd);
934 if (ssh_msg_recv(fd, &m) == -1)
935 fatal("%s: ssh_msg_recv failed", __func__);
936 if (buffer_get_char(&m) != 0)
937 fatal("%s: rexec version mismatch", __func__);
939 cp = buffer_get_string(&m, &len);
941 buffer_append(conf, cp, len + 1);
944 if (buffer_get_int(&m)) {
945 if (sensitive_data.server_key != NULL)
946 key_free(sensitive_data.server_key);
947 sensitive_data.server_key = key_new_private(KEY_RSA1);
948 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
949 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
950 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
951 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
952 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
953 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
954 rsa_generate_additional_parameters(
955 sensitive_data.server_key->rsa);
958 #ifndef OPENSSL_PRNG_ONLY
959 rexec_recv_rng_seed(&m);
964 debug3("%s: done", __func__);
967 /* Accept a connection from inetd */
969 server_accept_inetd(int *sock_in, int *sock_out)
975 close(REEXEC_CONFIG_PASS_FD);
976 *sock_in = *sock_out = dup(STDIN_FILENO);
978 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
979 close(REEXEC_STARTUP_PIPE_FD);
982 *sock_in = dup(STDIN_FILENO);
983 *sock_out = dup(STDOUT_FILENO);
986 * We intentionally do not close the descriptors 0, 1, and 2
987 * as our code for setting the descriptors won't work if
988 * ttyfd happens to be one of those.
990 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
991 dup2(fd, STDIN_FILENO);
992 dup2(fd, STDOUT_FILENO);
993 if (fd > STDOUT_FILENO)
996 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1000 * Listen for TCP connections
1005 int ret, listen_sock, on = 1;
1006 struct addrinfo *ai;
1007 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1009 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1010 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1012 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1013 fatal("Too many listen sockets. "
1014 "Enlarge MAX_LISTEN_SOCKS");
1015 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1016 ntop, sizeof(ntop), strport, sizeof(strport),
1017 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1018 error("getnameinfo failed: %.100s",
1019 ssh_gai_strerror(ret));
1022 /* Create socket for listening. */
1023 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1025 if (listen_sock < 0) {
1026 /* kernel may not support ipv6 */
1027 verbose("socket: %.100s", strerror(errno));
1030 if (set_nonblock(listen_sock) == -1) {
1035 * Set socket options.
1036 * Allow local port reuse in TIME_WAIT.
1038 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1039 &on, sizeof(on)) == -1)
1040 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1042 /* Only communicate in IPv6 over AF_INET6 sockets. */
1043 if (ai->ai_family == AF_INET6)
1044 sock_set_v6only(listen_sock);
1046 debug("Bind to port %s on %s.", strport, ntop);
1048 /* Bind the socket to the desired port. */
1049 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1050 error("Bind to port %s on %s failed: %.200s.",
1051 strport, ntop, strerror(errno));
1055 listen_socks[num_listen_socks] = listen_sock;
1058 /* Start listening on the port. */
1059 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1060 fatal("listen on [%s]:%s: %.100s",
1061 ntop, strport, strerror(errno));
1062 logit("Server listening on %s port %s.", ntop, strport);
1064 freeaddrinfo(options.listen_addrs);
1066 if (!num_listen_socks)
1067 fatal("Cannot bind any address.");
1071 * The main TCP accept loop. Note that, for the non-debug case, returns
1072 * from this function are in a forked subprocess.
1075 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1078 int i, j, ret, maxfd;
1079 int key_used = 0, startups = 0;
1080 int startup_p[2] = { -1 , -1 };
1081 struct sockaddr_storage from;
1085 /* setup fd set for accept */
1088 for (i = 0; i < num_listen_socks; i++)
1089 if (listen_socks[i] > maxfd)
1090 maxfd = listen_socks[i];
1091 /* pipes connected to unauthenticated childs */
1092 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1093 for (i = 0; i < options.max_startups; i++)
1094 startup_pipes[i] = -1;
1097 * Stay listening for connections until the system crashes or
1098 * the daemon is killed with a signal.
1101 if (received_sighup)
1105 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1108 for (i = 0; i < num_listen_socks; i++)
1109 FD_SET(listen_socks[i], fdset);
1110 for (i = 0; i < options.max_startups; i++)
1111 if (startup_pipes[i] != -1)
1112 FD_SET(startup_pipes[i], fdset);
1114 /* Wait in select until there is a connection. */
1115 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1116 if (ret < 0 && errno != EINTR)
1117 error("select: %.100s", strerror(errno));
1118 if (received_sigterm) {
1119 logit("Received signal %d; terminating.",
1120 (int) received_sigterm);
1121 close_listen_socks();
1122 unlink(options.pid_file);
1125 if (key_used && key_do_regen) {
1126 generate_ephemeral_server_key();
1133 for (i = 0; i < options.max_startups; i++)
1134 if (startup_pipes[i] != -1 &&
1135 FD_ISSET(startup_pipes[i], fdset)) {
1137 * the read end of the pipe is ready
1138 * if the child has closed the pipe
1139 * after successful authentication
1140 * or if the child has died
1142 close(startup_pipes[i]);
1143 startup_pipes[i] = -1;
1146 for (i = 0; i < num_listen_socks; i++) {
1147 if (!FD_ISSET(listen_socks[i], fdset))
1149 fromlen = sizeof(from);
1150 *newsock = accept(listen_socks[i],
1151 (struct sockaddr *)&from, &fromlen);
1153 if (errno != EINTR && errno != EAGAIN &&
1154 errno != EWOULDBLOCK)
1155 error("accept: %.100s", strerror(errno));
1158 if (unset_nonblock(*newsock) == -1) {
1162 if (drop_connection(startups) == 1) {
1163 debug("drop connection #%d", startups);
1167 if (pipe(startup_p) == -1) {
1172 if (rexec_flag && socketpair(AF_UNIX,
1173 SOCK_STREAM, 0, config_s) == -1) {
1174 error("reexec socketpair: %s",
1177 close(startup_p[0]);
1178 close(startup_p[1]);
1182 for (j = 0; j < options.max_startups; j++)
1183 if (startup_pipes[j] == -1) {
1184 startup_pipes[j] = startup_p[0];
1185 if (maxfd < startup_p[0])
1186 maxfd = startup_p[0];
1192 * Got connection. Fork a child to handle it, unless
1193 * we are in debugging mode.
1197 * In debugging mode. Close the listening
1198 * socket, and start processing the
1199 * connection without forking.
1201 debug("Server will not fork when running in debugging mode.");
1202 close_listen_socks();
1203 *sock_in = *newsock;
1204 *sock_out = *newsock;
1205 close(startup_p[0]);
1206 close(startup_p[1]);
1210 send_rexec_state(config_s[0],
1218 * Normal production daemon. Fork, and have
1219 * the child process the connection. The
1220 * parent continues listening.
1222 platform_pre_fork();
1223 if ((pid = fork()) == 0) {
1225 * Child. Close the listening and
1226 * max_startup sockets. Start using
1227 * the accepted socket. Reinitialize
1228 * logging (since our pid has changed).
1229 * We break out of the loop to handle
1232 platform_post_fork_child();
1233 startup_pipe = startup_p[1];
1234 close_startup_pipes();
1235 close_listen_socks();
1236 *sock_in = *newsock;
1237 *sock_out = *newsock;
1238 log_init(__progname,
1240 options.log_facility,
1247 /* Parent. Stay in the loop. */
1248 platform_post_fork_parent(pid);
1250 error("fork: %.100s", strerror(errno));
1252 debug("Forked child %ld.", (long)pid);
1254 close(startup_p[1]);
1257 send_rexec_state(config_s[0], &cfg);
1263 * Mark that the key has been used (it
1264 * was "given" to the child).
1266 if ((options.protocol & SSH_PROTO_1) &&
1268 /* Schedule server key regeneration alarm. */
1269 signal(SIGALRM, key_regeneration_alarm);
1270 alarm(options.key_regeneration_time);
1277 * Ensure that our random state differs
1278 * from that of the child
1283 /* child process check (or debug mode) */
1284 if (num_listen_socks < 0)
1291 * Main program for the daemon.
1294 main(int ac, char **av)
1296 extern char *optarg;
1298 int opt, i, j, on = 1;
1299 int sock_in = -1, sock_out = -1, newsock = -1;
1300 const char *remote_ip;
1301 char *test_user = NULL, *test_host = NULL, *test_addr = NULL;
1303 char *line, *p, *cp;
1304 int config_s[2] = { -1 , -1 };
1305 u_int64_t ibytes, obytes;
1310 #ifdef HAVE_SECUREWARE
1311 (void)set_auth_parameters(ac, av);
1313 __progname = ssh_get_progname(av[0]);
1316 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1319 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1320 for (i = 0; i < ac; i++)
1321 saved_argv[i] = xstrdup(av[i]);
1322 saved_argv[i] = NULL;
1324 #ifndef HAVE_SETPROCTITLE
1325 /* Prepare for later setproctitle emulation */
1326 compat_init_setproctitle(ac, av);
1330 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1331 debug("setgroups(): %.200s", strerror(errno));
1333 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1336 /* Initialize configuration options to their default values. */
1337 initialize_server_options(&options);
1339 /* Parse command-line arguments. */
1340 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeiqrtQRT46")) != -1) {
1343 options.address_family = AF_INET;
1346 options.address_family = AF_INET6;
1349 config_file_name = optarg;
1352 if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1353 fprintf(stderr, "too many host certificates.\n");
1356 options.host_cert_files[options.num_host_cert_files++] =
1357 derelativise_path(optarg);
1360 if (debug_flag == 0) {
1362 options.log_level = SYSLOG_LEVEL_DEBUG1;
1363 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1364 options.log_level++;
1386 options.log_level = SYSLOG_LEVEL_QUIET;
1389 options.server_key_bits = (int)strtonum(optarg, 256,
1393 options.ports_from_cmdline = 1;
1394 if (options.num_ports >= MAX_PORTS) {
1395 fprintf(stderr, "too many ports.\n");
1398 options.ports[options.num_ports++] = a2port(optarg);
1399 if (options.ports[options.num_ports-1] <= 0) {
1400 fprintf(stderr, "Bad port number.\n");
1405 if ((options.login_grace_time = convtime(optarg)) == -1) {
1406 fprintf(stderr, "Invalid login grace time.\n");
1411 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1412 fprintf(stderr, "Invalid key regeneration interval.\n");
1417 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1418 fprintf(stderr, "too many host keys.\n");
1421 options.host_key_files[options.num_host_key_files++] =
1422 derelativise_path(optarg);
1432 while ((p = strsep(&cp, ",")) && *p != '\0') {
1433 if (strncmp(p, "addr=", 5) == 0)
1434 test_addr = xstrdup(p + 5);
1435 else if (strncmp(p, "host=", 5) == 0)
1436 test_host = xstrdup(p + 5);
1437 else if (strncmp(p, "user=", 5) == 0)
1438 test_user = xstrdup(p + 5);
1440 fprintf(stderr, "Invalid test "
1441 "mode specification %s\n", p);
1447 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1448 if (utmp_len > MAXHOSTNAMELEN) {
1449 fprintf(stderr, "Invalid utmp length.\n");
1454 line = xstrdup(optarg);
1455 if (process_server_config_line(&options, line,
1456 "command-line", 0, NULL, NULL, NULL, NULL) != 0)
1466 if (rexeced_flag || inetd_flag)
1468 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1469 fatal("sshd re-exec requires execution with an absolute path");
1471 closefrom(REEXEC_MIN_FREE_FD);
1473 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1475 OpenSSL_add_all_algorithms();
1478 * Force logging to stderr until we have loaded the private host
1479 * key (unless started from inetd)
1481 log_init(__progname,
1482 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1483 SYSLOG_LEVEL_INFO : options.log_level,
1484 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1485 SYSLOG_FACILITY_AUTH : options.log_facility,
1486 log_stderr || !inetd_flag);
1489 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1490 * root's environment
1492 if (getenv("KRB5CCNAME") != NULL)
1493 unsetenv("KRB5CCNAME");
1496 /* Cray can define user privs drop all privs now!
1497 * Not needed on PRIV_SU systems!
1502 sensitive_data.server_key = NULL;
1503 sensitive_data.ssh1_host_key = NULL;
1504 sensitive_data.have_ssh1_key = 0;
1505 sensitive_data.have_ssh2_key = 0;
1508 * If we're doing an extended config test, make sure we have all of
1509 * the parameters we need. If we're not doing an extended test,
1510 * do not silently ignore connection test params.
1512 if (test_flag >= 2 &&
1513 (test_user != NULL || test_host != NULL || test_addr != NULL)
1514 && (test_user == NULL || test_host == NULL || test_addr == NULL))
1515 fatal("user, host and addr are all required when testing "
1517 if (test_flag < 2 && (test_user != NULL || test_host != NULL ||
1519 fatal("Config test connection parameter (-C) provided without "
1522 /* Fetch our configuration */
1525 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1527 load_server_config(config_file_name, &cfg);
1529 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1530 &cfg, NULL, NULL, NULL);
1534 /* Fill in default values for those options not explicitly set. */
1535 fill_default_server_options(&options);
1537 /* challenge-response is implemented via keyboard interactive */
1538 if (options.challenge_response_authentication)
1539 options.kbd_interactive_authentication = 1;
1541 /* set default channel AF */
1542 channel_set_af(options.address_family);
1544 /* Check that there are no remaining arguments. */
1546 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1550 debug("sshd version %.100s", SSH_RELEASE);
1552 /* Store privilege separation user for later use if required. */
1553 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1554 if (use_privsep || options.kerberos_authentication)
1555 fatal("Privilege separation user %s does not exist",
1558 memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1559 privsep_pw = pwcopy(privsep_pw);
1560 xfree(privsep_pw->pw_passwd);
1561 privsep_pw->pw_passwd = xstrdup("*");
1565 /* load private host keys */
1566 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1568 for (i = 0; i < options.num_host_key_files; i++)
1569 sensitive_data.host_keys[i] = NULL;
1571 for (i = 0; i < options.num_host_key_files; i++) {
1572 key = key_load_private(options.host_key_files[i], "", NULL);
1573 sensitive_data.host_keys[i] = key;
1575 error("Could not load host key: %s",
1576 options.host_key_files[i]);
1577 sensitive_data.host_keys[i] = NULL;
1580 if (auth_key_is_revoked(key, 1)) {
1582 sensitive_data.host_keys[i] = NULL;
1585 switch (key->type) {
1587 sensitive_data.ssh1_host_key = key;
1588 sensitive_data.have_ssh1_key = 1;
1593 sensitive_data.have_ssh2_key = 1;
1596 debug("private host key: #%d type %d %s", i, key->type,
1599 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1600 logit("Disabling protocol version 1. Could not load host key");
1601 options.protocol &= ~SSH_PROTO_1;
1604 /* The GSSAPI key exchange can run without a host key */
1605 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1606 logit("Disabling protocol version 2. Could not load host key");
1607 options.protocol &= ~SSH_PROTO_2;
1610 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1611 logit("sshd: no hostkeys available -- exiting.");
1616 * Load certificates. They are stored in an array at identical
1617 * indices to the public keys that they relate to.
1619 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1621 for (i = 0; i < options.num_host_key_files; i++)
1622 sensitive_data.host_certificates[i] = NULL;
1624 for (i = 0; i < options.num_host_cert_files; i++) {
1625 key = key_load_public(options.host_cert_files[i], NULL);
1627 error("Could not load host certificate: %s",
1628 options.host_cert_files[i]);
1631 if (!key_is_cert(key)) {
1632 error("Certificate file is not a certificate: %s",
1633 options.host_cert_files[i]);
1637 /* Find matching private key */
1638 for (j = 0; j < options.num_host_key_files; j++) {
1639 if (key_equal_public(key,
1640 sensitive_data.host_keys[j])) {
1641 sensitive_data.host_certificates[j] = key;
1645 if (j >= options.num_host_key_files) {
1646 error("No matching private key for certificate: %s",
1647 options.host_cert_files[i]);
1651 sensitive_data.host_certificates[j] = key;
1652 debug("host certificate: #%d type %d %s", j, key->type,
1655 /* Check certain values for sanity. */
1656 if (options.protocol & SSH_PROTO_1) {
1657 if (options.server_key_bits < 512 ||
1658 options.server_key_bits > 32768) {
1659 fprintf(stderr, "Bad server key size.\n");
1663 * Check that server and host key lengths differ sufficiently. This
1664 * is necessary to make double encryption work with rsaref. Oh, I
1665 * hate software patents. I dont know if this can go? Niels
1667 if (options.server_key_bits >
1668 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1669 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1670 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1671 SSH_KEY_BITS_RESERVED) {
1672 options.server_key_bits =
1673 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1674 SSH_KEY_BITS_RESERVED;
1675 debug("Forcing server key to %d bits to make it differ from host key.",
1676 options.server_key_bits);
1683 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1684 (S_ISDIR(st.st_mode) == 0))
1685 fatal("Missing privilege separation directory: %s",
1686 _PATH_PRIVSEP_CHROOT_DIR);
1689 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1690 (st.st_uid != getuid () ||
1691 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1693 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1695 fatal("%s must be owned by root and not group or "
1696 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1699 if (test_flag > 1) {
1700 if (test_user != NULL && test_addr != NULL && test_host != NULL)
1701 parse_server_match_config(&options, test_user,
1702 test_host, test_addr);
1703 dump_config(&options);
1706 /* Configuration looks good, so exit if in test mode. */
1711 * Clear out any supplemental groups we may have inherited. This
1712 * prevents inadvertent creation of files with bad modes (in the
1713 * portable version at least, it's certainly possible for PAM
1714 * to create a file, and we can't control the code in every
1715 * module which might be used).
1717 if (setgroups(0, NULL) < 0)
1718 debug("setgroups() failed: %.200s", strerror(errno));
1721 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1722 for (i = 0; i < rexec_argc; i++) {
1723 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1724 rexec_argv[i] = saved_argv[i];
1726 rexec_argv[rexec_argc] = "-R";
1727 rexec_argv[rexec_argc + 1] = NULL;
1730 /* Ensure that umask disallows at least group and world write */
1731 new_umask = umask(0077) | 0022;
1732 (void) umask(new_umask);
1734 /* Initialize the log (it is reinitialized below in case we forked). */
1735 if (debug_flag && (!inetd_flag || rexeced_flag))
1737 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1740 * If not in debugging mode, and not started from inetd, disconnect
1741 * from the controlling terminal, and fork. The original process
1744 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1747 #endif /* TIOCNOTTY */
1748 if (daemon(0, 0) < 0)
1749 fatal("daemon() failed: %.200s", strerror(errno));
1751 /* Disconnect from the controlling tty. */
1753 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1755 (void) ioctl(fd, TIOCNOTTY, NULL);
1758 #endif /* TIOCNOTTY */
1760 /* Reinitialize the log (because of the fork above). */
1761 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1763 /* Initialize the random number generator. */
1766 /* Chdir to the root directory so that the current disk can be
1767 unmounted if desired. */
1770 /* ignore SIGPIPE */
1771 signal(SIGPIPE, SIG_IGN);
1773 /* Get a connection, either from inetd or a listening TCP socket */
1775 server_accept_inetd(&sock_in, &sock_out);
1777 platform_pre_listen();
1780 if (options.protocol & SSH_PROTO_1)
1781 generate_ephemeral_server_key();
1783 signal(SIGHUP, sighup_handler);
1784 signal(SIGCHLD, main_sigchld_handler);
1785 signal(SIGTERM, sigterm_handler);
1786 signal(SIGQUIT, sigterm_handler);
1789 * Write out the pid file after the sigterm handler
1790 * is setup and the listen sockets are bound
1793 FILE *f = fopen(options.pid_file, "w");
1796 error("Couldn't create pid file \"%s\": %s",
1797 options.pid_file, strerror(errno));
1799 fprintf(f, "%ld\n", (long) getpid());
1804 /* Accept a connection and return in a forked child */
1805 server_accept_loop(&sock_in, &sock_out,
1806 &newsock, config_s);
1809 /* This is the child processing a new connection. */
1810 setproctitle("%s", "[accepted]");
1813 * Create a new session and process group since the 4.4BSD
1814 * setlogin() affects the entire process group. We don't
1815 * want the child to be able to affect the parent.
1817 #if !defined(SSHD_ACQUIRES_CTTY)
1819 * If setsid is called, on some platforms sshd will later acquire a
1820 * controlling terminal which will result in "could not set
1821 * controlling tty" errors.
1823 if (!debug_flag && !inetd_flag && setsid() < 0)
1824 error("setsid: %.100s", strerror(errno));
1830 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1831 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1832 dup2(newsock, STDIN_FILENO);
1833 dup2(STDIN_FILENO, STDOUT_FILENO);
1834 if (startup_pipe == -1)
1835 close(REEXEC_STARTUP_PIPE_FD);
1837 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1839 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1841 if (startup_pipe != -1)
1842 close(startup_pipe);
1844 execv(rexec_argv[0], rexec_argv);
1846 /* Reexec has failed, fall back and continue */
1847 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1848 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1849 log_init(__progname, options.log_level,
1850 options.log_facility, log_stderr);
1853 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1855 close(REEXEC_CONFIG_PASS_FD);
1856 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1857 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1858 dup2(fd, STDIN_FILENO);
1859 dup2(fd, STDOUT_FILENO);
1860 if (fd > STDERR_FILENO)
1863 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1864 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1867 /* Executed child processes don't need these. */
1868 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1869 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1872 * Disable the key regeneration alarm. We will not regenerate the
1873 * key since we are no longer in a position to give it to anyone. We
1874 * will not restart on SIGHUP since it no longer makes sense.
1877 signal(SIGALRM, SIG_DFL);
1878 signal(SIGHUP, SIG_DFL);
1879 signal(SIGTERM, SIG_DFL);
1880 signal(SIGQUIT, SIG_DFL);
1881 signal(SIGCHLD, SIG_DFL);
1882 signal(SIGINT, SIG_DFL);
1885 * Register our connection. This turns encryption off because we do
1888 packet_set_connection(sock_in, sock_out);
1889 packet_set_server();
1891 /* Set SO_KEEPALIVE if requested. */
1892 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1893 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1894 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1896 if ((remote_port = get_remote_port()) < 0) {
1897 debug("get_remote_port failed");
1902 * We use get_canonical_hostname with usedns = 0 instead of
1903 * get_remote_ipaddr here so IP options will be checked.
1905 (void) get_canonical_hostname(0);
1907 * The rest of the code depends on the fact that
1908 * get_remote_ipaddr() caches the remote ip, even if
1909 * the socket goes away.
1911 remote_ip = get_remote_ipaddr();
1913 #ifdef SSH_AUDIT_EVENTS
1914 audit_connection_from(remote_ip, remote_port);
1917 allow_severity = options.log_facility|LOG_INFO;
1918 deny_severity = options.log_facility|LOG_WARNING;
1919 /* Check whether logins are denied from this host. */
1920 if (packet_connection_is_on_socket()) {
1921 struct request_info req;
1923 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1926 if (!hosts_access(&req)) {
1927 debug("Connection refused by tcp wrapper");
1930 fatal("libwrap refuse returns");
1933 #endif /* LIBWRAP */
1935 /* Log the connection. */
1936 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1938 #ifdef USE_SECURITY_SESSION_API
1940 * Create a new security session for use by the new user login if
1941 * the current session is the root session or we are not launched
1942 * by inetd (eg: debugging mode or server mode). We do not
1943 * necessarily need to create a session if we are launched from
1944 * inetd because Panther xinetd will create a session for us.
1946 * The only case where this logic will fail is if there is an
1947 * inetd running in a non-root session which is not creating
1948 * new sessions for us. Then all the users will end up in the
1949 * same session (bad).
1951 * When the client exits, the session will be destroyed for us
1954 * We must create the session before any credentials are stored
1955 * (including AFS pags, which happens a few lines below).
1959 SecuritySessionId sid = 0;
1960 SessionAttributeBits sattrs = 0;
1962 err = SessionGetInfo(callerSecuritySession, &sid, &sattrs);
1964 error("SessionGetInfo() failed with error %.8X",
1967 debug("Current Session ID is %.8X / Session Attributes are %.8X",
1968 (unsigned) sid, (unsigned) sattrs);
1970 if (inetd_flag && !(sattrs & sessionIsRoot))
1971 debug("Running in inetd mode in a non-root session... "
1972 "assuming inetd created the session for us.");
1974 debug("Creating new security session...");
1975 err = SessionCreate(0, sessionHasTTY | sessionIsRemote);
1977 error("SessionCreate() failed with error %.8X",
1980 err = SessionGetInfo(callerSecuritySession, &sid,
1983 error("SessionGetInfo() failed with error %.8X",
1986 debug("New Session ID is %.8X / Session Attributes are %.8X",
1987 (unsigned) sid, (unsigned) sattrs);
1993 * We don't want to listen forever unless the other side
1994 * successfully authenticates itself. So we set up an alarm which is
1995 * cleared after successful authentication. A limit of zero
1996 * indicates no limit. Note that we don't set the alarm in debugging
1997 * mode; it is just annoying to have the server exit just when you
1998 * are about to discover the bug.
2000 signal(SIGALRM, grace_alarm_handler);
2002 alarm(options.login_grace_time);
2004 sshd_exchange_identification(sock_in, sock_out);
2006 /* In inetd mode, generate ephemeral key only for proto 1 connections */
2007 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2008 generate_ephemeral_server_key();
2010 packet_set_nonblocking();
2012 /* allocate authentication context */
2013 authctxt = xcalloc(1, sizeof(*authctxt));
2015 authctxt->loginmsg = &loginmsg;
2017 /* XXX global for cleanup, access from other modules */
2018 the_authctxt = authctxt;
2020 /* prepare buffer to collect messages to display to user after login */
2021 buffer_init(&loginmsg);
2025 if (privsep_preauth(authctxt) == 1)
2028 /* perform the key exchange */
2029 /* authenticate user and start session */
2032 do_authentication2(authctxt);
2035 do_authentication(authctxt);
2038 * If we use privilege separation, the unprivileged child transfers
2039 * the current keystate and exits
2042 mm_send_keystate(pmonitor);
2048 * Cancel the alarm we set to limit the time taken for
2052 signal(SIGALRM, SIG_DFL);
2053 authctxt->authenticated = 1;
2054 if (startup_pipe != -1) {
2055 close(startup_pipe);
2059 #ifdef SSH_AUDIT_EVENTS
2060 audit_event(SSH_AUTH_SUCCESS);
2064 if (options.gss_authentication) {
2065 temporarily_use_uid(authctxt->pw);
2066 ssh_gssapi_storecreds();
2071 if (options.use_pam) {
2078 * In privilege separation, we fork another child and prepare
2079 * file descriptor passing.
2082 privsep_postauth(authctxt);
2083 /* the monitor process [priv] will not return */
2085 destroy_sensitive_data();
2088 packet_set_timeout(options.client_alive_interval,
2089 options.client_alive_count_max);
2091 /* Start session. */
2092 do_authenticated(authctxt);
2094 /* The connection has been terminated. */
2095 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
2096 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
2097 verbose("Transferred: sent %llu, received %llu bytes",
2098 (unsigned long long)obytes, (unsigned long long)ibytes);
2100 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2103 if (options.use_pam)
2105 #endif /* USE_PAM */
2107 #ifdef SSH_AUDIT_EVENTS
2108 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2120 * Decrypt session_key_int using our private server key and private host key
2121 * (key with larger modulus first).
2124 ssh1_session_key(BIGNUM *session_key_int)
2128 if (BN_cmp(sensitive_data.server_key->rsa->n,
2129 sensitive_data.ssh1_host_key->rsa->n) > 0) {
2130 /* Server key has bigger modulus. */
2131 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2132 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2133 SSH_KEY_BITS_RESERVED) {
2134 fatal("do_connection: %s: "
2135 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2136 get_remote_ipaddr(),
2137 BN_num_bits(sensitive_data.server_key->rsa->n),
2138 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2139 SSH_KEY_BITS_RESERVED);
2141 if (rsa_private_decrypt(session_key_int, session_key_int,
2142 sensitive_data.server_key->rsa) <= 0)
2144 if (rsa_private_decrypt(session_key_int, session_key_int,
2145 sensitive_data.ssh1_host_key->rsa) <= 0)
2148 /* Host key has bigger modulus (or they are equal). */
2149 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2150 BN_num_bits(sensitive_data.server_key->rsa->n) +
2151 SSH_KEY_BITS_RESERVED) {
2152 fatal("do_connection: %s: "
2153 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2154 get_remote_ipaddr(),
2155 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2156 BN_num_bits(sensitive_data.server_key->rsa->n),
2157 SSH_KEY_BITS_RESERVED);
2159 if (rsa_private_decrypt(session_key_int, session_key_int,
2160 sensitive_data.ssh1_host_key->rsa) < 0)
2162 if (rsa_private_decrypt(session_key_int, session_key_int,
2163 sensitive_data.server_key->rsa) < 0)
2176 BIGNUM *session_key_int;
2177 u_char session_key[SSH_SESSION_KEY_LENGTH];
2179 u_int cipher_type, auth_mask, protocol_flags;
2182 * Generate check bytes that the client must send back in the user
2183 * packet in order for it to be accepted; this is used to defy ip
2184 * spoofing attacks. Note that this only works against somebody
2185 * doing IP spoofing from a remote machine; any machine on the local
2186 * network can still see outgoing packets and catch the random
2187 * cookie. This only affects rhosts authentication, and this is one
2188 * of the reasons why it is inherently insecure.
2190 arc4random_buf(cookie, sizeof(cookie));
2193 * Send our public key. We include in the packet 64 bits of random
2194 * data that must be matched in the reply in order to prevent IP
2197 packet_start(SSH_SMSG_PUBLIC_KEY);
2198 for (i = 0; i < 8; i++)
2199 packet_put_char(cookie[i]);
2201 /* Store our public server RSA key. */
2202 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2203 packet_put_bignum(sensitive_data.server_key->rsa->e);
2204 packet_put_bignum(sensitive_data.server_key->rsa->n);
2206 /* Store our public host RSA key. */
2207 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2208 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2209 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2211 /* Put protocol flags. */
2212 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2214 /* Declare which ciphers we support. */
2215 packet_put_int(cipher_mask_ssh1(0));
2217 /* Declare supported authentication types. */
2219 if (options.rhosts_rsa_authentication)
2220 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2221 if (options.rsa_authentication)
2222 auth_mask |= 1 << SSH_AUTH_RSA;
2223 if (options.challenge_response_authentication == 1)
2224 auth_mask |= 1 << SSH_AUTH_TIS;
2225 if (options.password_authentication)
2226 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2227 packet_put_int(auth_mask);
2229 /* Send the packet and wait for it to be sent. */
2231 packet_write_wait();
2233 debug("Sent %d bit server key and %d bit host key.",
2234 BN_num_bits(sensitive_data.server_key->rsa->n),
2235 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2237 /* Read clients reply (cipher type and session key). */
2238 packet_read_expect(SSH_CMSG_SESSION_KEY);
2240 /* Get cipher type and check whether we accept this. */
2241 cipher_type = packet_get_char();
2243 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2244 packet_disconnect("Warning: client selects unsupported cipher.");
2246 /* Get check bytes from the packet. These must match those we
2247 sent earlier with the public key packet. */
2248 for (i = 0; i < 8; i++)
2249 if (cookie[i] != packet_get_char())
2250 packet_disconnect("IP Spoofing check bytes do not match.");
2252 debug("Encryption type: %.200s", cipher_name(cipher_type));
2254 /* Get the encrypted integer. */
2255 if ((session_key_int = BN_new()) == NULL)
2256 fatal("do_ssh1_kex: BN_new failed");
2257 packet_get_bignum(session_key_int);
2259 protocol_flags = packet_get_int();
2260 packet_set_protocol_flags(protocol_flags);
2263 /* Decrypt session_key_int using host/server keys */
2264 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2267 * Extract session key from the decrypted integer. The key is in the
2268 * least significant 256 bits of the integer; the first byte of the
2269 * key is in the highest bits.
2272 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2273 len = BN_num_bytes(session_key_int);
2274 if (len < 0 || (u_int)len > sizeof(session_key)) {
2275 error("do_ssh1_kex: bad session key len from %s: "
2276 "session_key_int %d > sizeof(session_key) %lu",
2277 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2280 memset(session_key, 0, sizeof(session_key));
2281 BN_bn2bin(session_key_int,
2282 session_key + sizeof(session_key) - len);
2284 derive_ssh1_session_id(
2285 sensitive_data.ssh1_host_key->rsa->n,
2286 sensitive_data.server_key->rsa->n,
2287 cookie, session_id);
2289 * Xor the first 16 bytes of the session key with the
2292 for (i = 0; i < 16; i++)
2293 session_key[i] ^= session_id[i];
2297 int bytes = BN_num_bytes(session_key_int);
2298 u_char *buf = xmalloc(bytes);
2301 logit("do_connection: generating a fake encryption key");
2302 BN_bn2bin(session_key_int, buf);
2304 MD5_Update(&md, buf, bytes);
2305 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2306 MD5_Final(session_key, &md);
2308 MD5_Update(&md, session_key, 16);
2309 MD5_Update(&md, buf, bytes);
2310 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2311 MD5_Final(session_key + 16, &md);
2312 memset(buf, 0, bytes);
2314 for (i = 0; i < 16; i++)
2315 session_id[i] = session_key[i] ^ session_key[i + 16];
2317 /* Destroy the private and public keys. No longer. */
2318 destroy_sensitive_data();
2321 mm_ssh1_session_id(session_id);
2323 /* Destroy the decrypted integer. It is no longer needed. */
2324 BN_clear_free(session_key_int);
2326 /* Set the session key. From this on all communications will be encrypted. */
2327 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2329 /* Destroy our copy of the session key. It is no longer needed. */
2330 memset(session_key, 0, sizeof(session_key));
2332 debug("Received session key; encryption turned on.");
2334 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2335 packet_start(SSH_SMSG_SUCCESS);
2337 packet_write_wait();
2341 * SSH2 key exchange: diffie-hellman-group1-sha1
2348 if (options.ciphers != NULL) {
2349 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2350 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2352 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2353 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2354 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2355 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2357 if (options.macs != NULL) {
2358 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2359 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2361 if (options.compression == COMP_NONE) {
2362 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2363 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2364 } else if (options.compression == COMP_DELAYED) {
2365 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2366 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2368 if (options.kex_algorithms != NULL)
2369 myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
2371 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2377 char *newstr = NULL;
2378 orig = myproposal[PROPOSAL_KEX_ALGS];
2381 * If we don't have a host key, then there's no point advertising
2382 * the other key exchange algorithms
2385 if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]) == 0)
2388 if (options.gss_keyex)
2389 gss = ssh_gssapi_server_mechanisms();
2394 xasprintf(&newstr, "%s,%s", gss, orig);
2401 * If we've got GSSAPI mechanisms, then we've got the 'null' host
2402 * key alg, but we can't tell people about it unless its the only
2403 * host key algorithm we support
2405 if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0)
2406 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = "null";
2409 myproposal[PROPOSAL_KEX_ALGS] = newstr;
2411 fatal("No supported key exchange algorithms");
2415 /* start key exchange */
2416 kex = kex_setup(myproposal);
2417 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2418 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2419 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2420 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2421 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2423 if (options.gss_keyex) {
2424 kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
2425 kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
2426 kex->kex[KEX_GSS_GEX_SHA1] = kexgss_server;
2430 kex->client_version_string=client_version_string;
2431 kex->server_version_string=server_version_string;
2432 kex->load_host_public_key=&get_hostkey_public_by_type;
2433 kex->load_host_private_key=&get_hostkey_private_by_type;
2434 kex->host_key_index=&get_hostkey_index;
2438 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2440 session_id2 = kex->session_id;
2441 session_id2_len = kex->session_id_len;
2444 /* send 1st encrypted/maced/compressed message */
2445 packet_start(SSH2_MSG_IGNORE);
2446 packet_put_cstring("markus");
2448 packet_write_wait();
2453 /* server specific fatal cleanup */
2458 do_cleanup(the_authctxt);
2459 #ifdef SSH_AUDIT_EVENTS
2460 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2461 if (!use_privsep || mm_is_monitor())
2462 audit_event(SSH_CONNECTION_ABANDON);