1 /* $OpenBSD: sshd.c,v 1.349 2007/02/21 11:00:05 dtucker 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"
74 #include <openssl/dh.h>
75 #include <openssl/bn.h>
76 #include <openssl/md5.h>
77 #include <openssl/rand.h>
78 #ifdef HAVE_SECUREWARE
79 #include <sys/security.h>
99 #include "myproposal.h"
100 #include "authfile.h"
101 #include "pathnames.h"
102 #include "atomicio.h"
103 #include "canohost.h"
104 #include "hostfile.h"
108 #include "dispatch.h"
109 #include "channels.h"
111 #include "monitor_mm.h"
116 #include "monitor_wrap.h"
117 #include "monitor_fdpass.h"
120 #ifdef USE_SECURITY_SESSION_API
121 #include <Security/AuthSession.h>
127 int allow_severity = LOG_INFO;
128 int deny_severity = LOG_WARNING;
136 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
137 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
138 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
139 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
141 extern char *__progname;
143 /* Server configuration options. */
144 ServerOptions options;
146 /* Name of the server configuration file. */
147 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
150 * Debug mode flag. This can be set on the command line. If debug
151 * mode is enabled, extra debugging output will be sent to the system
152 * log, the daemon will not go to background, and will exit after processing
153 * the first connection.
157 /* Flag indicating that the daemon should only test the configuration and keys. */
160 /* Flag indicating that the daemon is being started from inetd. */
163 /* Flag indicating that sshd should not detach and become a daemon. */
164 int no_daemon_flag = 0;
166 /* debug goes to stderr unless inetd_flag is set */
169 /* Saved arguments to main(). */
174 int rexeced_flag = 0;
180 * The sockets that the server is listening; this is used in the SIGHUP
183 #define MAX_LISTEN_SOCKS 16
184 int listen_socks[MAX_LISTEN_SOCKS];
185 int num_listen_socks = 0;
188 * the client's version string, passed by sshd2 in compat mode. if != NULL,
189 * sshd will skip the version-number exchange
191 char *client_version_string = NULL;
192 char *server_version_string = NULL;
194 /* for rekeying XXX fixme */
198 * Any really sensitive data in the application is contained in this
199 * structure. The idea is that this structure could be locked into memory so
200 * that the pages do not get written into swap. However, there are some
201 * problems. The private key contains BIGNUMs, and we do not (in principle)
202 * have access to the internals of them, and locking just the structure is
203 * not very useful. Currently, memory locking is not implemented.
206 Key *server_key; /* ephemeral server key */
207 Key *ssh1_host_key; /* ssh1 host key */
208 Key **host_keys; /* all private host keys */
211 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
215 * Flag indicating whether the RSA server key needs to be regenerated.
216 * Is set in the SIGALRM handler and cleared when the key is regenerated.
218 static volatile sig_atomic_t key_do_regen = 0;
220 /* This is set to true when a signal is received. */
221 static volatile sig_atomic_t received_sighup = 0;
222 static volatile sig_atomic_t received_sigterm = 0;
224 /* session identifier, used by RSA-auth */
225 u_char session_id[16];
228 u_char *session_id2 = NULL;
229 u_int session_id2_len = 0;
231 /* record remote hostname or ip */
232 u_int utmp_len = MAXHOSTNAMELEN;
234 /* options.max_startup sized array of fd ints */
235 int *startup_pipes = NULL;
236 int startup_pipe; /* in child */
238 /* variables used for privilege separation */
239 int use_privsep = -1;
240 struct monitor *pmonitor = NULL;
242 /* global authentication context */
243 Authctxt *the_authctxt = NULL;
245 /* sshd_config buffer */
248 /* message to be displayed after login */
251 /* Unprivileged user */
252 struct passwd *privsep_pw = NULL;
254 /* Prototypes for various functions defined later in this file. */
255 void destroy_sensitive_data(void);
256 void demote_sensitive_data(void);
258 static void do_ssh1_kex(void);
259 static void do_ssh2_kex(void);
262 * Close all listening sockets
265 close_listen_socks(void)
269 for (i = 0; i < num_listen_socks; i++)
270 close(listen_socks[i]);
271 num_listen_socks = -1;
275 close_startup_pipes(void)
280 for (i = 0; i < options.max_startups; i++)
281 if (startup_pipes[i] != -1)
282 close(startup_pipes[i]);
286 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
287 * the effect is to reread the configuration file (and to regenerate
293 sighup_handler(int sig)
295 int save_errno = errno;
298 signal(SIGHUP, sighup_handler);
303 * Called from the main program after receiving SIGHUP.
304 * Restarts the server.
309 logit("Received SIGHUP; restarting.");
310 close_listen_socks();
311 close_startup_pipes();
312 alarm(0); /* alarm timer persists across exec */
313 execv(saved_argv[0], saved_argv);
314 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
320 * Generic signal handler for terminating signals in the master daemon.
324 sigterm_handler(int sig)
326 received_sigterm = sig;
330 * SIGCHLD handler. This is called whenever a child dies. This will then
331 * reap any zombies left by exited children.
335 main_sigchld_handler(int sig)
337 int save_errno = errno;
341 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
342 (pid < 0 && errno == EINTR))
345 signal(SIGCHLD, main_sigchld_handler);
350 * Signal handler for the alarm after the login grace period has expired.
354 grace_alarm_handler(int sig)
356 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
357 kill(pmonitor->m_pid, SIGALRM);
359 /* Log error and exit. */
360 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
364 * Signal handler for the key regeneration alarm. Note that this
365 * alarm only occurs in the daemon waiting for connections, and it does not
366 * do anything with the private key or random state before forking.
367 * Thus there should be no concurrency control/asynchronous execution
371 generate_ephemeral_server_key(void)
376 verbose("Generating %s%d bit RSA key.",
377 sensitive_data.server_key ? "new " : "", options.server_key_bits);
378 if (sensitive_data.server_key != NULL)
379 key_free(sensitive_data.server_key);
380 sensitive_data.server_key = key_generate(KEY_RSA1,
381 options.server_key_bits);
382 verbose("RSA key generation complete.");
384 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
387 sensitive_data.ssh1_cookie[i] = rnd & 0xff;
395 key_regeneration_alarm(int sig)
397 int save_errno = errno;
399 signal(SIGALRM, SIG_DFL);
405 sshd_exchange_identification(int sock_in, int sock_out)
409 int remote_major, remote_minor;
412 char buf[256]; /* Must not be larger than remote_version. */
413 char remote_version[256]; /* Must be at least as big as buf. */
415 if ((options.protocol & SSH_PROTO_1) &&
416 (options.protocol & SSH_PROTO_2)) {
417 major = PROTOCOL_MAJOR_1;
419 } else if (options.protocol & SSH_PROTO_2) {
420 major = PROTOCOL_MAJOR_2;
421 minor = PROTOCOL_MINOR_2;
423 major = PROTOCOL_MAJOR_1;
424 minor = PROTOCOL_MINOR_1;
426 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_RELEASE);
427 server_version_string = xstrdup(buf);
429 /* Send our protocol version identification. */
430 if (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 (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;
555 sensitive_data.ssh1_host_key = NULL;
556 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
559 /* Demote private to public keys for network child */
561 demote_sensitive_data(void)
566 if (sensitive_data.server_key) {
567 tmp = key_demote(sensitive_data.server_key);
568 key_free(sensitive_data.server_key);
569 sensitive_data.server_key = tmp;
572 for (i = 0; i < options.num_host_key_files; i++) {
573 if (sensitive_data.host_keys[i]) {
574 tmp = key_demote(sensitive_data.host_keys[i]);
575 key_free(sensitive_data.host_keys[i]);
576 sensitive_data.host_keys[i] = tmp;
577 if (tmp->type == KEY_RSA1)
578 sensitive_data.ssh1_host_key = tmp;
582 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
586 privsep_preauth_child(void)
592 /* Enable challenge-response authentication for privilege separation */
593 privsep_challenge_enable();
595 for (i = 0; i < 256; i++)
596 rnd[i] = arc4random();
597 RAND_seed(rnd, sizeof(rnd));
599 /* Demote the private keys to public keys. */
600 demote_sensitive_data();
602 /* Change our root directory */
603 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
604 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
606 if (chdir("/") == -1)
607 fatal("chdir(\"/\"): %s", strerror(errno));
609 /* Drop our privileges */
610 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
611 (u_int)privsep_pw->pw_gid);
613 /* XXX not ready, too heavy after chroot */
614 do_setusercontext(privsep_pw);
616 gidset[0] = privsep_pw->pw_gid;
617 if (setgroups(1, gidset) < 0)
618 fatal("setgroups: %.100s", strerror(errno));
619 permanently_set_uid(privsep_pw);
624 privsep_preauth(Authctxt *authctxt)
629 /* Set up unprivileged child process to deal with network data */
630 pmonitor = monitor_init();
631 /* Store a pointer to the kex for later rekeying */
632 pmonitor->m_pkex = &xxx_kex;
636 fatal("fork of unprivileged child failed");
637 } else if (pid != 0) {
638 debug2("Network child is on pid %ld", (long)pid);
640 close(pmonitor->m_recvfd);
641 pmonitor->m_pid = pid;
642 monitor_child_preauth(authctxt, pmonitor);
643 close(pmonitor->m_sendfd);
646 monitor_sync(pmonitor);
648 /* Wait for the child's exit status */
649 while (waitpid(pid, &status, 0) < 0)
656 close(pmonitor->m_sendfd);
658 /* Demote the child */
659 if (getuid() == 0 || geteuid() == 0)
660 privsep_preauth_child();
661 setproctitle("%s", "[net]");
667 privsep_postauth(Authctxt *authctxt)
669 #ifdef DISABLE_FD_PASSING
672 if (authctxt->pw->pw_uid == 0 || options.use_login) {
674 /* File descriptor passing is broken or root login */
679 /* New socket pair */
680 monitor_reinit(pmonitor);
682 pmonitor->m_pid = fork();
683 if (pmonitor->m_pid == -1)
684 fatal("fork of unprivileged child failed");
685 else if (pmonitor->m_pid != 0) {
686 debug2("User child is on pid %ld", (long)pmonitor->m_pid);
687 close(pmonitor->m_recvfd);
688 buffer_clear(&loginmsg);
689 monitor_child_postauth(pmonitor);
695 close(pmonitor->m_sendfd);
697 /* Demote the private keys to public keys. */
698 demote_sensitive_data();
700 /* Drop privileges */
701 do_setusercontext(authctxt->pw);
704 /* It is safe now to apply the key state */
705 monitor_apply_keystate(pmonitor);
708 * Tell the packet layer that authentication was successful, since
709 * this information is not part of the key state.
711 packet_set_authenticated();
715 list_hostkey_types(void)
723 for (i = 0; i < options.num_host_key_files; i++) {
724 Key *key = sensitive_data.host_keys[i];
730 if (buffer_len(&b) > 0)
731 buffer_append(&b, ",", 1);
732 p = key_ssh_name(key);
733 buffer_append(&b, p, strlen(p));
737 buffer_append(&b, "\0", 1);
738 ret = xstrdup(buffer_ptr(&b));
740 debug("list_hostkey_types: %s", ret);
745 get_hostkey_by_type(int type)
749 for (i = 0; i < options.num_host_key_files; i++) {
750 Key *key = sensitive_data.host_keys[i];
751 if (key != NULL && key->type == type)
758 get_hostkey_by_index(int ind)
760 if (ind < 0 || ind >= options.num_host_key_files)
762 return (sensitive_data.host_keys[ind]);
766 get_hostkey_index(Key *key)
770 for (i = 0; i < options.num_host_key_files; i++) {
771 if (key == sensitive_data.host_keys[i])
778 * returns 1 if connection should be dropped, 0 otherwise.
779 * dropping starts at connection #max_startups_begin with a probability
780 * of (max_startups_rate/100). the probability increases linearly until
781 * all connections are dropped for startups > max_startups
784 drop_connection(int startups)
788 if (startups < options.max_startups_begin)
790 if (startups >= options.max_startups)
792 if (options.max_startups_rate == 100)
795 p = 100 - options.max_startups_rate;
796 p *= startups - options.max_startups_begin;
797 p /= options.max_startups - options.max_startups_begin;
798 p += options.max_startups_rate;
799 r = arc4random() % 100;
801 debug("drop_connection: p %d, r %d", p, r);
802 return (r < p) ? 1 : 0;
808 fprintf(stderr, "%s, %s\n",
809 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
811 "usage: sshd [-46Ddeiqt] [-b bits] [-f config_file] [-g login_grace_time]\n"
812 " [-h host_key_file] [-k key_gen_time] [-o option] [-p port] [-u len]\n"
818 send_rexec_state(int fd, Buffer *conf)
822 debug3("%s: entering fd = %d config len %d", __func__, fd,
826 * Protocol from reexec master to child:
827 * string configuration
828 * u_int ephemeral_key_follows
829 * bignum e (only if ephemeral_key_follows == 1)
835 * string rngseed (only if OpenSSL is not self-seeded)
838 buffer_put_cstring(&m, buffer_ptr(conf));
840 if (sensitive_data.server_key != NULL &&
841 sensitive_data.server_key->type == KEY_RSA1) {
842 buffer_put_int(&m, 1);
843 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
844 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
845 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
846 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
847 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
848 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
850 buffer_put_int(&m, 0);
852 #ifndef OPENSSL_PRNG_ONLY
853 rexec_send_rng_seed(&m);
856 if (ssh_msg_send(fd, 0, &m) == -1)
857 fatal("%s: ssh_msg_send failed", __func__);
861 debug3("%s: done", __func__);
865 recv_rexec_state(int fd, Buffer *conf)
871 debug3("%s: entering fd = %d", __func__, fd);
875 if (ssh_msg_recv(fd, &m) == -1)
876 fatal("%s: ssh_msg_recv failed", __func__);
877 if (buffer_get_char(&m) != 0)
878 fatal("%s: rexec version mismatch", __func__);
880 cp = buffer_get_string(&m, &len);
882 buffer_append(conf, cp, len + 1);
885 if (buffer_get_int(&m)) {
886 if (sensitive_data.server_key != NULL)
887 key_free(sensitive_data.server_key);
888 sensitive_data.server_key = key_new_private(KEY_RSA1);
889 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
890 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
891 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
892 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
893 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
894 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
895 rsa_generate_additional_parameters(
896 sensitive_data.server_key->rsa);
899 #ifndef OPENSSL_PRNG_ONLY
900 rexec_recv_rng_seed(&m);
905 debug3("%s: done", __func__);
908 /* Accept a connection from inetd */
910 server_accept_inetd(int *sock_in, int *sock_out)
916 close(REEXEC_CONFIG_PASS_FD);
917 *sock_in = *sock_out = dup(STDIN_FILENO);
919 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
920 close(REEXEC_STARTUP_PIPE_FD);
923 *sock_in = dup(STDIN_FILENO);
924 *sock_out = dup(STDOUT_FILENO);
927 * We intentionally do not close the descriptors 0, 1, and 2
928 * as our code for setting the descriptors won't work if
929 * ttyfd happens to be one of those.
931 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
932 dup2(fd, STDIN_FILENO);
933 dup2(fd, STDOUT_FILENO);
934 if (fd > STDOUT_FILENO)
937 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
941 * Listen for TCP connections
946 int ret, listen_sock, on = 1;
948 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
950 int socksizelen = sizeof(int);
952 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
953 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
955 if (num_listen_socks >= MAX_LISTEN_SOCKS)
956 fatal("Too many listen sockets. "
957 "Enlarge MAX_LISTEN_SOCKS");
958 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
959 ntop, sizeof(ntop), strport, sizeof(strport),
960 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
961 error("getnameinfo failed: %.100s",
962 (ret != EAI_SYSTEM) ? gai_strerror(ret) :
966 /* Create socket for listening. */
967 listen_sock = socket(ai->ai_family, ai->ai_socktype,
969 if (listen_sock < 0) {
970 /* kernel may not support ipv6 */
971 verbose("socket: %.100s", strerror(errno));
974 if (set_nonblock(listen_sock) == -1) {
979 * Set socket options.
980 * Allow local port reuse in TIME_WAIT.
982 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
983 &on, sizeof(on)) == -1)
984 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
986 debug("Bind to port %s on %s.", strport, ntop);
988 getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF,
989 &socksize, &socksizelen);
990 debug("Server TCP RWIN socket size: %d", socksize);
991 debug("HPN Buffer Size: %d", options.hpn_buffer_size);
993 /* Bind the socket to the desired port. */
994 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
995 error("Bind to port %s on %s failed: %.200s.",
996 strport, ntop, strerror(errno));
1000 listen_socks[num_listen_socks] = listen_sock;
1003 /* Start listening on the port. */
1004 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1005 fatal("listen on [%s]:%s: %.100s",
1006 ntop, strport, strerror(errno));
1007 logit("Server listening on %s port %s.", ntop, strport);
1009 freeaddrinfo(options.listen_addrs);
1011 if (!num_listen_socks)
1012 fatal("Cannot bind any address.");
1016 * The main TCP accept loop. Note that, for the non-debug case, returns
1017 * from this function are in a forked subprocess.
1020 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1023 int i, j, ret, maxfd;
1024 int key_used = 0, startups = 0;
1025 int startup_p[2] = { -1 , -1 };
1026 struct sockaddr_storage from;
1030 /* setup fd set for accept */
1033 for (i = 0; i < num_listen_socks; i++)
1034 if (listen_socks[i] > maxfd)
1035 maxfd = listen_socks[i];
1036 /* pipes connected to unauthenticated childs */
1037 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1038 for (i = 0; i < options.max_startups; i++)
1039 startup_pipes[i] = -1;
1042 * Stay listening for connections until the system crashes or
1043 * the daemon is killed with a signal.
1046 if (received_sighup)
1050 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1053 for (i = 0; i < num_listen_socks; i++)
1054 FD_SET(listen_socks[i], fdset);
1055 for (i = 0; i < options.max_startups; i++)
1056 if (startup_pipes[i] != -1)
1057 FD_SET(startup_pipes[i], fdset);
1059 /* Wait in select until there is a connection. */
1060 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1061 if (ret < 0 && errno != EINTR)
1062 error("select: %.100s", strerror(errno));
1063 if (received_sigterm) {
1064 logit("Received signal %d; terminating.",
1065 (int) received_sigterm);
1066 close_listen_socks();
1067 unlink(options.pid_file);
1070 if (key_used && key_do_regen) {
1071 generate_ephemeral_server_key();
1078 for (i = 0; i < options.max_startups; i++)
1079 if (startup_pipes[i] != -1 &&
1080 FD_ISSET(startup_pipes[i], fdset)) {
1082 * the read end of the pipe is ready
1083 * if the child has closed the pipe
1084 * after successful authentication
1085 * or if the child has died
1087 close(startup_pipes[i]);
1088 startup_pipes[i] = -1;
1091 for (i = 0; i < num_listen_socks; i++) {
1092 if (!FD_ISSET(listen_socks[i], fdset))
1094 fromlen = sizeof(from);
1095 *newsock = accept(listen_socks[i],
1096 (struct sockaddr *)&from, &fromlen);
1098 if (errno != EINTR && errno != EWOULDBLOCK)
1099 error("accept: %.100s", strerror(errno));
1102 if (unset_nonblock(*newsock) == -1) {
1106 if (drop_connection(startups) == 1) {
1107 debug("drop connection #%d", startups);
1111 if (pipe(startup_p) == -1) {
1116 if (rexec_flag && socketpair(AF_UNIX,
1117 SOCK_STREAM, 0, config_s) == -1) {
1118 error("reexec socketpair: %s",
1121 close(startup_p[0]);
1122 close(startup_p[1]);
1126 for (j = 0; j < options.max_startups; j++)
1127 if (startup_pipes[j] == -1) {
1128 startup_pipes[j] = startup_p[0];
1129 if (maxfd < startup_p[0])
1130 maxfd = startup_p[0];
1136 * Got connection. Fork a child to handle it, unless
1137 * we are in debugging mode.
1141 * In debugging mode. Close the listening
1142 * socket, and start processing the
1143 * connection without forking.
1145 debug("Server will not fork when running in debugging mode.");
1146 close_listen_socks();
1147 *sock_in = *newsock;
1148 *sock_out = *newsock;
1149 close(startup_p[0]);
1150 close(startup_p[1]);
1154 send_rexec_state(config_s[0],
1162 * Normal production daemon. Fork, and have
1163 * the child process the connection. The
1164 * parent continues listening.
1166 platform_pre_fork();
1167 if ((pid = fork()) == 0) {
1169 * Child. Close the listening and
1170 * max_startup sockets. Start using
1171 * the accepted socket. Reinitialize
1172 * logging (since our pid has changed).
1173 * We break out of the loop to handle
1176 platform_post_fork_child();
1177 startup_pipe = startup_p[1];
1178 close_startup_pipes();
1179 close_listen_socks();
1180 *sock_in = *newsock;
1181 *sock_out = *newsock;
1182 log_init(__progname,
1184 options.log_facility,
1191 /* Parent. Stay in the loop. */
1192 platform_post_fork_parent(pid);
1194 error("fork: %.100s", strerror(errno));
1196 debug("Forked child %ld.", (long)pid);
1198 close(startup_p[1]);
1201 send_rexec_state(config_s[0], &cfg);
1207 * Mark that the key has been used (it
1208 * was "given" to the child).
1210 if ((options.protocol & SSH_PROTO_1) &&
1212 /* Schedule server key regeneration alarm. */
1213 signal(SIGALRM, key_regeneration_alarm);
1214 alarm(options.key_regeneration_time);
1221 * Ensure that our random state differs
1222 * from that of the child
1227 /* child process check (or debug mode) */
1228 if (num_listen_socks < 0)
1235 * Main program for the daemon.
1238 main(int ac, char **av)
1240 extern char *optarg;
1243 int sock_in = -1, sock_out = -1, newsock = -1;
1244 const char *remote_ip;
1247 int config_s[2] = { -1 , -1 };
1251 #ifdef HAVE_SECUREWARE
1252 (void)set_auth_parameters(ac, av);
1254 __progname = ssh_get_progname(av[0]);
1257 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1260 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1261 for (i = 0; i < ac; i++)
1262 saved_argv[i] = xstrdup(av[i]);
1263 saved_argv[i] = NULL;
1265 #ifndef HAVE_SETPROCTITLE
1266 /* Prepare for later setproctitle emulation */
1267 compat_init_setproctitle(ac, av);
1271 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1272 debug("setgroups(): %.200s", strerror(errno));
1274 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1277 /* Initialize configuration options to their default values. */
1278 initialize_server_options(&options);
1280 /* Parse command-line arguments. */
1281 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:dDeiqrtQR46")) != -1) {
1284 options.address_family = AF_INET;
1287 options.address_family = AF_INET6;
1290 config_file_name = optarg;
1293 if (debug_flag == 0) {
1295 options.log_level = SYSLOG_LEVEL_DEBUG1;
1296 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1297 options.log_level++;
1319 options.log_level = SYSLOG_LEVEL_QUIET;
1322 options.server_key_bits = (int)strtonum(optarg, 256,
1326 options.ports_from_cmdline = 1;
1327 if (options.num_ports >= MAX_PORTS) {
1328 fprintf(stderr, "too many ports.\n");
1331 options.ports[options.num_ports++] = a2port(optarg);
1332 if (options.ports[options.num_ports-1] == 0) {
1333 fprintf(stderr, "Bad port number.\n");
1338 if ((options.login_grace_time = convtime(optarg)) == -1) {
1339 fprintf(stderr, "Invalid login grace time.\n");
1344 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1345 fprintf(stderr, "Invalid key regeneration interval.\n");
1350 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1351 fprintf(stderr, "too many host keys.\n");
1354 options.host_key_files[options.num_host_key_files++] = optarg;
1360 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1361 if (utmp_len > MAXHOSTNAMELEN) {
1362 fprintf(stderr, "Invalid utmp length.\n");
1367 line = xstrdup(optarg);
1368 if (process_server_config_line(&options, line,
1369 "command-line", 0, NULL, NULL, NULL, NULL) != 0)
1379 if (rexeced_flag || inetd_flag)
1381 if (rexec_flag && (av[0] == NULL || *av[0] != '/'))
1382 fatal("sshd re-exec requires execution with an absolute path");
1384 closefrom(REEXEC_MIN_FREE_FD);
1386 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1388 SSLeay_add_all_algorithms();
1391 * Force logging to stderr until we have loaded the private host
1392 * key (unless started from inetd)
1394 log_init(__progname,
1395 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1396 SYSLOG_LEVEL_INFO : options.log_level,
1397 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1398 SYSLOG_FACILITY_AUTH : options.log_facility,
1399 log_stderr || !inetd_flag);
1402 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1403 * root's environment
1405 if (getenv("KRB5CCNAME") != NULL)
1406 unsetenv("KRB5CCNAME");
1409 /* Cray can define user privs drop all privs now!
1410 * Not needed on PRIV_SU systems!
1415 sensitive_data.server_key = NULL;
1416 sensitive_data.ssh1_host_key = NULL;
1417 sensitive_data.have_ssh1_key = 0;
1418 sensitive_data.have_ssh2_key = 0;
1420 /* Fetch our configuration */
1423 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1425 load_server_config(config_file_name, &cfg);
1427 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1428 &cfg, NULL, NULL, NULL);
1432 /* Fill in default values for those options not explicitly set. */
1433 fill_default_server_options(&options);
1435 /* set default channel AF */
1436 channel_set_af(options.address_family);
1438 /* Check that there are no remaining arguments. */
1440 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1444 debug("sshd version %.100s", SSH_RELEASE);
1446 /* Store privilege separation user for later use if required. */
1447 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1448 if (use_privsep || options.kerberos_authentication)
1449 fatal("Privilege separation user %s does not exist",
1452 memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1453 privsep_pw = pwcopy(privsep_pw);
1454 xfree(privsep_pw->pw_passwd);
1455 privsep_pw->pw_passwd = xstrdup("*");
1459 /* load private host keys */
1460 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1462 for (i = 0; i < options.num_host_key_files; i++)
1463 sensitive_data.host_keys[i] = NULL;
1465 for (i = 0; i < options.num_host_key_files; i++) {
1466 key = key_load_private(options.host_key_files[i], "", NULL);
1467 sensitive_data.host_keys[i] = key;
1469 error("Could not load host key: %s",
1470 options.host_key_files[i]);
1471 sensitive_data.host_keys[i] = NULL;
1474 switch (key->type) {
1476 sensitive_data.ssh1_host_key = key;
1477 sensitive_data.have_ssh1_key = 1;
1481 sensitive_data.have_ssh2_key = 1;
1484 debug("private host key: #%d type %d %s", i, key->type,
1487 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1488 logit("Disabling protocol version 1. Could not load host key");
1489 options.protocol &= ~SSH_PROTO_1;
1492 /* The GSSAPI key exchange can run without a host key */
1493 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1494 logit("Disabling protocol version 2. Could not load host key");
1495 options.protocol &= ~SSH_PROTO_2;
1498 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1499 logit("sshd: no hostkeys available -- exiting.");
1503 /* Check certain values for sanity. */
1504 if (options.protocol & SSH_PROTO_1) {
1505 if (options.server_key_bits < 512 ||
1506 options.server_key_bits > 32768) {
1507 fprintf(stderr, "Bad server key size.\n");
1511 * Check that server and host key lengths differ sufficiently. This
1512 * is necessary to make double encryption work with rsaref. Oh, I
1513 * hate software patents. I dont know if this can go? Niels
1515 if (options.server_key_bits >
1516 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1517 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1518 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1519 SSH_KEY_BITS_RESERVED) {
1520 options.server_key_bits =
1521 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1522 SSH_KEY_BITS_RESERVED;
1523 debug("Forcing server key to %d bits to make it differ from host key.",
1524 options.server_key_bits);
1531 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1532 (S_ISDIR(st.st_mode) == 0))
1533 fatal("Missing privilege separation directory: %s",
1534 _PATH_PRIVSEP_CHROOT_DIR);
1537 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1538 (st.st_uid != getuid () ||
1539 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1541 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1543 fatal("%s must be owned by root and not group or "
1544 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1547 /* Configuration looks good, so exit if in test mode. */
1552 * Clear out any supplemental groups we may have inherited. This
1553 * prevents inadvertent creation of files with bad modes (in the
1554 * portable version at least, it's certainly possible for PAM
1555 * to create a file, and we can't control the code in every
1556 * module which might be used).
1558 if (setgroups(0, NULL) < 0)
1559 debug("setgroups() failed: %.200s", strerror(errno));
1562 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1563 for (i = 0; i < rexec_argc; i++) {
1564 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1565 rexec_argv[i] = saved_argv[i];
1567 rexec_argv[rexec_argc] = "-R";
1568 rexec_argv[rexec_argc + 1] = NULL;
1571 /* Initialize the log (it is reinitialized below in case we forked). */
1572 if (debug_flag && (!inetd_flag || rexeced_flag))
1574 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1577 * If not in debugging mode, and not started from inetd, disconnect
1578 * from the controlling terminal, and fork. The original process
1581 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1584 #endif /* TIOCNOTTY */
1585 if (daemon(0, 0) < 0)
1586 fatal("daemon() failed: %.200s", strerror(errno));
1588 /* Disconnect from the controlling tty. */
1590 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1592 (void) ioctl(fd, TIOCNOTTY, NULL);
1595 #endif /* TIOCNOTTY */
1597 /* Reinitialize the log (because of the fork above). */
1598 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1600 /* Initialize the random number generator. */
1603 /* Chdir to the root directory so that the current disk can be
1604 unmounted if desired. */
1607 /* ignore SIGPIPE */
1608 signal(SIGPIPE, SIG_IGN);
1610 /* Get a connection, either from inetd or a listening TCP socket */
1612 server_accept_inetd(&sock_in, &sock_out);
1614 if ((options.protocol & SSH_PROTO_1) &&
1615 sensitive_data.server_key == NULL)
1616 generate_ephemeral_server_key();
1620 if (options.protocol & SSH_PROTO_1)
1621 generate_ephemeral_server_key();
1623 signal(SIGHUP, sighup_handler);
1624 signal(SIGCHLD, main_sigchld_handler);
1625 signal(SIGTERM, sigterm_handler);
1626 signal(SIGQUIT, sigterm_handler);
1629 * Write out the pid file after the sigterm handler
1630 * is setup and the listen sockets are bound
1633 FILE *f = fopen(options.pid_file, "w");
1636 error("Couldn't create pid file \"%s\": %s",
1637 options.pid_file, strerror(errno));
1639 fprintf(f, "%ld\n", (long) getpid());
1644 /* Accept a connection and return in a forked child */
1645 server_accept_loop(&sock_in, &sock_out,
1646 &newsock, config_s);
1649 /* This is the child processing a new connection. */
1650 setproctitle("%s", "[accepted]");
1653 * Create a new session and process group since the 4.4BSD
1654 * setlogin() affects the entire process group. We don't
1655 * want the child to be able to affect the parent.
1657 #if !defined(SSHD_ACQUIRES_CTTY)
1659 * If setsid is called, on some platforms sshd will later acquire a
1660 * controlling terminal which will result in "could not set
1661 * controlling tty" errors.
1663 if (!debug_flag && !inetd_flag && setsid() < 0)
1664 error("setsid: %.100s", strerror(errno));
1670 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1671 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1672 dup2(newsock, STDIN_FILENO);
1673 dup2(STDIN_FILENO, STDOUT_FILENO);
1674 if (startup_pipe == -1)
1675 close(REEXEC_STARTUP_PIPE_FD);
1677 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1679 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1681 if (startup_pipe != -1)
1682 close(startup_pipe);
1684 execv(rexec_argv[0], rexec_argv);
1686 /* Reexec has failed, fall back and continue */
1687 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1688 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1689 log_init(__progname, options.log_level,
1690 options.log_facility, log_stderr);
1693 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1695 close(REEXEC_CONFIG_PASS_FD);
1696 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1697 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1698 dup2(fd, STDIN_FILENO);
1699 dup2(fd, STDOUT_FILENO);
1700 if (fd > STDERR_FILENO)
1703 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1704 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1708 * Disable the key regeneration alarm. We will not regenerate the
1709 * key since we are no longer in a position to give it to anyone. We
1710 * will not restart on SIGHUP since it no longer makes sense.
1713 signal(SIGALRM, SIG_DFL);
1714 signal(SIGHUP, SIG_DFL);
1715 signal(SIGTERM, SIG_DFL);
1716 signal(SIGQUIT, SIG_DFL);
1717 signal(SIGCHLD, SIG_DFL);
1718 signal(SIGINT, SIG_DFL);
1721 * Register our connection. This turns encryption off because we do
1724 packet_set_connection(sock_in, sock_out);
1725 packet_set_server();
1727 /* Set SO_KEEPALIVE if requested. */
1728 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1729 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1730 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1732 if ((remote_port = get_remote_port()) < 0) {
1733 debug("get_remote_port failed");
1738 * We use get_canonical_hostname with usedns = 0 instead of
1739 * get_remote_ipaddr here so IP options will be checked.
1741 (void) get_canonical_hostname(0);
1743 * The rest of the code depends on the fact that
1744 * get_remote_ipaddr() caches the remote ip, even if
1745 * the socket goes away.
1747 remote_ip = get_remote_ipaddr();
1749 #ifdef SSH_AUDIT_EVENTS
1750 audit_connection_from(remote_ip, remote_port);
1753 /* Check whether logins are denied from this host. */
1754 if (packet_connection_is_on_socket()) {
1755 struct request_info req;
1757 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1760 if (!hosts_access(&req)) {
1761 debug("Connection refused by tcp wrapper");
1764 fatal("libwrap refuse returns");
1767 #endif /* LIBWRAP */
1769 /* Log the connection. */
1770 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1772 #ifdef USE_SECURITY_SESSION_API
1774 * Create a new security session for use by the new user login if
1775 * the current session is the root session or we are not launched
1776 * by inetd (eg: debugging mode or server mode). We do not
1777 * necessarily need to create a session if we are launched from
1778 * inetd because Panther xinetd will create a session for us.
1780 * The only case where this logic will fail is if there is an
1781 * inetd running in a non-root session which is not creating
1782 * new sessions for us. Then all the users will end up in the
1783 * same session (bad).
1785 * When the client exits, the session will be destroyed for us
1788 * We must create the session before any credentials are stored
1789 * (including AFS pags, which happens a few lines below).
1793 SecuritySessionId sid = 0;
1794 SessionAttributeBits sattrs = 0;
1796 err = SessionGetInfo(callerSecuritySession, &sid, &sattrs);
1798 error("SessionGetInfo() failed with error %.8X",
1801 debug("Current Session ID is %.8X / Session Attributes are %.8X",
1802 (unsigned) sid, (unsigned) sattrs);
1804 if (inetd_flag && !(sattrs & sessionIsRoot))
1805 debug("Running in inetd mode in a non-root session... "
1806 "assuming inetd created the session for us.");
1808 debug("Creating new security session...");
1809 err = SessionCreate(0, sessionHasTTY | sessionIsRemote);
1811 error("SessionCreate() failed with error %.8X",
1814 err = SessionGetInfo(callerSecuritySession, &sid,
1817 error("SessionGetInfo() failed with error %.8X",
1820 debug("New Session ID is %.8X / Session Attributes are %.8X",
1821 (unsigned) sid, (unsigned) sattrs);
1827 * We don't want to listen forever unless the other side
1828 * successfully authenticates itself. So we set up an alarm which is
1829 * cleared after successful authentication. A limit of zero
1830 * indicates no limit. Note that we don't set the alarm in debugging
1831 * mode; it is just annoying to have the server exit just when you
1832 * are about to discover the bug.
1834 signal(SIGALRM, grace_alarm_handler);
1836 alarm(options.login_grace_time);
1838 sshd_exchange_identification(sock_in, sock_out);
1839 #if defined(AFS_KRB5)
1840 /* If machine has AFS, set process authentication group. */
1845 #endif /* AFS || AFS_KRB5 */
1847 packet_set_nonblocking();
1849 /* allocate authentication context */
1850 authctxt = xcalloc(1, sizeof(*authctxt));
1852 authctxt->loginmsg = &loginmsg;
1854 /* XXX global for cleanup, access from other modules */
1855 the_authctxt = authctxt;
1857 /* prepare buffer to collect messages to display to user after login */
1858 buffer_init(&loginmsg);
1861 if (privsep_preauth(authctxt) == 1)
1864 /* perform the key exchange */
1865 /* authenticate user and start session */
1868 do_authentication2(authctxt);
1871 do_authentication(authctxt);
1874 * If we use privilege separation, the unprivileged child transfers
1875 * the current keystate and exits
1878 mm_send_keystate(pmonitor);
1884 * Cancel the alarm we set to limit the time taken for
1888 signal(SIGALRM, SIG_DFL);
1889 authctxt->authenticated = 1;
1890 if (startup_pipe != -1) {
1891 close(startup_pipe);
1895 #ifdef SSH_AUDIT_EVENTS
1896 audit_event(SSH_AUTH_SUCCESS);
1900 * In privilege separation, we fork another child and prepare
1901 * file descriptor passing.
1904 privsep_postauth(authctxt);
1905 /* the monitor process [priv] will not return */
1907 destroy_sensitive_data();
1910 /* Start session. */
1911 do_authenticated(authctxt);
1913 /* The connection has been terminated. */
1914 verbose("Closing connection to %.100s", remote_ip);
1917 if (options.use_pam)
1919 #endif /* USE_PAM */
1921 #ifdef SSH_AUDIT_EVENTS
1922 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
1934 * Decrypt session_key_int using our private server key and private host key
1935 * (key with larger modulus first).
1938 ssh1_session_key(BIGNUM *session_key_int)
1942 if (BN_cmp(sensitive_data.server_key->rsa->n,
1943 sensitive_data.ssh1_host_key->rsa->n) > 0) {
1944 /* Server key has bigger modulus. */
1945 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1946 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1947 SSH_KEY_BITS_RESERVED) {
1948 fatal("do_connection: %s: "
1949 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1950 get_remote_ipaddr(),
1951 BN_num_bits(sensitive_data.server_key->rsa->n),
1952 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1953 SSH_KEY_BITS_RESERVED);
1955 if (rsa_private_decrypt(session_key_int, session_key_int,
1956 sensitive_data.server_key->rsa) <= 0)
1958 if (rsa_private_decrypt(session_key_int, session_key_int,
1959 sensitive_data.ssh1_host_key->rsa) <= 0)
1962 /* Host key has bigger modulus (or they are equal). */
1963 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1964 BN_num_bits(sensitive_data.server_key->rsa->n) +
1965 SSH_KEY_BITS_RESERVED) {
1966 fatal("do_connection: %s: "
1967 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1968 get_remote_ipaddr(),
1969 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1970 BN_num_bits(sensitive_data.server_key->rsa->n),
1971 SSH_KEY_BITS_RESERVED);
1973 if (rsa_private_decrypt(session_key_int, session_key_int,
1974 sensitive_data.ssh1_host_key->rsa) < 0)
1976 if (rsa_private_decrypt(session_key_int, session_key_int,
1977 sensitive_data.server_key->rsa) < 0)
1990 BIGNUM *session_key_int;
1991 u_char session_key[SSH_SESSION_KEY_LENGTH];
1993 u_int cipher_type, auth_mask, protocol_flags;
1997 * Generate check bytes that the client must send back in the user
1998 * packet in order for it to be accepted; this is used to defy ip
1999 * spoofing attacks. Note that this only works against somebody
2000 * doing IP spoofing from a remote machine; any machine on the local
2001 * network can still see outgoing packets and catch the random
2002 * cookie. This only affects rhosts authentication, and this is one
2003 * of the reasons why it is inherently insecure.
2005 for (i = 0; i < 8; i++) {
2008 cookie[i] = rnd & 0xff;
2013 * Send our public key. We include in the packet 64 bits of random
2014 * data that must be matched in the reply in order to prevent IP
2017 packet_start(SSH_SMSG_PUBLIC_KEY);
2018 for (i = 0; i < 8; i++)
2019 packet_put_char(cookie[i]);
2021 /* Store our public server RSA key. */
2022 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2023 packet_put_bignum(sensitive_data.server_key->rsa->e);
2024 packet_put_bignum(sensitive_data.server_key->rsa->n);
2026 /* Store our public host RSA key. */
2027 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2028 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2029 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2031 /* Put protocol flags. */
2032 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2034 /* Declare which ciphers we support. */
2035 packet_put_int(cipher_mask_ssh1(0));
2037 /* Declare supported authentication types. */
2039 if (options.rhosts_rsa_authentication)
2040 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2041 if (options.rsa_authentication)
2042 auth_mask |= 1 << SSH_AUTH_RSA;
2043 if (options.challenge_response_authentication == 1)
2044 auth_mask |= 1 << SSH_AUTH_TIS;
2045 if (options.password_authentication)
2046 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2047 packet_put_int(auth_mask);
2049 /* Send the packet and wait for it to be sent. */
2051 packet_write_wait();
2053 debug("Sent %d bit server key and %d bit host key.",
2054 BN_num_bits(sensitive_data.server_key->rsa->n),
2055 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2057 /* Read clients reply (cipher type and session key). */
2058 packet_read_expect(SSH_CMSG_SESSION_KEY);
2060 /* Get cipher type and check whether we accept this. */
2061 cipher_type = packet_get_char();
2063 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2064 packet_disconnect("Warning: client selects unsupported cipher.");
2066 /* Get check bytes from the packet. These must match those we
2067 sent earlier with the public key packet. */
2068 for (i = 0; i < 8; i++)
2069 if (cookie[i] != packet_get_char())
2070 packet_disconnect("IP Spoofing check bytes do not match.");
2072 debug("Encryption type: %.200s", cipher_name(cipher_type));
2074 /* Get the encrypted integer. */
2075 if ((session_key_int = BN_new()) == NULL)
2076 fatal("do_ssh1_kex: BN_new failed");
2077 packet_get_bignum(session_key_int);
2079 protocol_flags = packet_get_int();
2080 packet_set_protocol_flags(protocol_flags);
2083 /* Decrypt session_key_int using host/server keys */
2084 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2087 * Extract session key from the decrypted integer. The key is in the
2088 * least significant 256 bits of the integer; the first byte of the
2089 * key is in the highest bits.
2092 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2093 len = BN_num_bytes(session_key_int);
2094 if (len < 0 || (u_int)len > sizeof(session_key)) {
2095 error("do_ssh1_kex: bad session key len from %s: "
2096 "session_key_int %d > sizeof(session_key) %lu",
2097 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2100 memset(session_key, 0, sizeof(session_key));
2101 BN_bn2bin(session_key_int,
2102 session_key + sizeof(session_key) - len);
2104 derive_ssh1_session_id(
2105 sensitive_data.ssh1_host_key->rsa->n,
2106 sensitive_data.server_key->rsa->n,
2107 cookie, session_id);
2109 * Xor the first 16 bytes of the session key with the
2112 for (i = 0; i < 16; i++)
2113 session_key[i] ^= session_id[i];
2117 int bytes = BN_num_bytes(session_key_int);
2118 u_char *buf = xmalloc(bytes);
2121 logit("do_connection: generating a fake encryption key");
2122 BN_bn2bin(session_key_int, buf);
2124 MD5_Update(&md, buf, bytes);
2125 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2126 MD5_Final(session_key, &md);
2128 MD5_Update(&md, session_key, 16);
2129 MD5_Update(&md, buf, bytes);
2130 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2131 MD5_Final(session_key + 16, &md);
2132 memset(buf, 0, bytes);
2134 for (i = 0; i < 16; i++)
2135 session_id[i] = session_key[i] ^ session_key[i + 16];
2137 /* Destroy the private and public keys. No longer. */
2138 destroy_sensitive_data();
2141 mm_ssh1_session_id(session_id);
2143 /* Destroy the decrypted integer. It is no longer needed. */
2144 BN_clear_free(session_key_int);
2146 /* Set the session key. From this on all communications will be encrypted. */
2147 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2149 /* Destroy our copy of the session key. It is no longer needed. */
2150 memset(session_key, 0, sizeof(session_key));
2152 debug("Received session key; encryption turned on.");
2154 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2155 packet_start(SSH_SMSG_SUCCESS);
2157 packet_write_wait();
2161 * SSH2 key exchange: diffie-hellman-group1-sha1
2168 if (options.ciphers != NULL) {
2169 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2170 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2171 } else if (options.none_enabled == 1) {
2172 debug ("WARNING: None cipher enabled");
2173 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2174 myproposal[PROPOSAL_ENC_ALGS_STOC] = KEX_ENCRYPT_INCLUDE_NONE;
2176 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2177 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2178 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2179 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2181 if (options.macs != NULL) {
2182 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2183 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2185 if (options.compression == COMP_NONE) {
2186 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2187 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2188 } else if (options.compression == COMP_DELAYED) {
2189 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2190 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2193 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2199 char *newstr = NULL;
2200 orig = myproposal[PROPOSAL_KEX_ALGS];
2203 * If we don't have a host key, then there's no point advertising
2204 * the other key exchange algorithms
2207 if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]) == 0)
2210 if (options.gss_keyex)
2211 gss = ssh_gssapi_server_mechanisms();
2216 xasprintf(&newstr, "%s,%s", gss, orig);
2223 * If we've got GSSAPI mechanisms, then we've got the 'null' host
2224 * key alg, but we can't tell people about it unless its the only
2225 * host key algorithm we support
2227 if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0)
2228 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = "null";
2231 myproposal[PROPOSAL_KEX_ALGS] = newstr;
2233 fatal("No supported key exchange algorithms");
2237 /* start key exchange */
2238 /* start key exchange */
2239 kex = kex_setup(myproposal);
2240 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2241 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2242 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2243 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2245 kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
2246 kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
2247 kex->kex[KEX_GSS_GEX_SHA1] = kexgss_server;
2250 kex->client_version_string=client_version_string;
2251 kex->server_version_string=server_version_string;
2252 kex->load_host_key=&get_hostkey_by_type;
2253 kex->host_key_index=&get_hostkey_index;
2257 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2259 session_id2 = kex->session_id;
2260 session_id2_len = kex->session_id_len;
2263 /* send 1st encrypted/maced/compressed message */
2264 packet_start(SSH2_MSG_IGNORE);
2265 packet_put_cstring("markus");
2267 packet_write_wait();
2272 /* server specific fatal cleanup */
2277 do_cleanup(the_authctxt);
2278 #ifdef SSH_AUDIT_EVENTS
2279 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2280 if (!use_privsep || mm_is_monitor())
2281 audit_event(SSH_CONNECTION_ABANDON);