1 /* $OpenBSD: sshd.c,v 1.397 2013/02/11 21:21:58 dtucker Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * This program is the ssh daemon. It listens for connections from clients,
8 * and performs authentication, executes use commands or shell, and forwards
9 * information to/from the application to the user client over an encrypted
10 * connection. This can also handle forwarding of X11, TCP/IP, and
11 * authentication agent connections.
13 * As far as I am concerned, the code I have written for this software
14 * can be used freely for any purpose. Any derived versions of this
15 * software must be clearly marked as such, and if the derived work is
16 * incompatible with the protocol description in the RFC file, it must be
17 * called by a name other than "ssh" or "Secure Shell".
19 * SSH2 implementation:
20 * Privilege Separation:
22 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
23 * Copyright (c) 2002 Niels Provos. All rights reserved.
25 * Redistribution and use in source and binary forms, with or without
26 * modification, are permitted provided that the following conditions
28 * 1. Redistributions of source code must retain the above copyright
29 * notice, this list of conditions and the following disclaimer.
30 * 2. Redistributions in binary form must reproduce the above copyright
31 * notice, this list of conditions and the following disclaimer in the
32 * documentation and/or other materials provided with the distribution.
34 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
35 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
36 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
37 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
38 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
39 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
40 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
41 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
49 #include <sys/types.h>
50 #include <sys/ioctl.h>
52 #include <sys/socket.h>
53 #ifdef HAVE_SYS_STAT_H
54 # include <sys/stat.h>
56 #ifdef HAVE_SYS_TIME_H
57 # include <sys/time.h>
59 #include "openbsd-compat/sys-tree.h"
60 #include "openbsd-compat/sys-queue.h"
78 #include <openssl/dh.h>
79 #include <openssl/bn.h>
80 #include <openssl/md5.h>
81 #include <openssl/rand.h>
82 #include "openbsd-compat/openssl-compat.h"
84 #ifdef HAVE_SECUREWARE
85 #include <sys/security.h>
91 #if defined(GSSAPI) && defined(HAVE_GSSAPI_H)
93 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
94 #include <gssapi/gssapi.h>
107 #include "servconf.h"
114 #include "myproposal.h"
115 #include "authfile.h"
116 #include "pathnames.h"
117 #include "atomicio.h"
118 #include "canohost.h"
119 #include "hostfile.h"
123 #include "dispatch.h"
124 #include "channels.h"
126 #include "monitor_mm.h"
131 #include "monitor_wrap.h"
133 #include "ssh-sandbox.h"
148 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
149 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
150 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
151 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
153 extern char *__progname;
155 /* Server configuration options. */
156 ServerOptions options;
158 /* Name of the server configuration file. */
159 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
162 * Debug mode flag. This can be set on the command line. If debug
163 * mode is enabled, extra debugging output will be sent to the system
164 * log, the daemon will not go to background, and will exit after processing
165 * the first connection.
169 /* Flag indicating that the daemon should only test the configuration and keys. */
172 /* Flag indicating that the daemon is being started from inetd. */
175 /* Flag indicating that sshd should not detach and become a daemon. */
176 int no_daemon_flag = 0;
178 /* debug goes to stderr unless inetd_flag is set */
181 /* Saved arguments to main(). */
186 int rexeced_flag = 0;
192 * The sockets that the server is listening; this is used in the SIGHUP
195 #define MAX_LISTEN_SOCKS 16
196 int listen_socks[MAX_LISTEN_SOCKS];
197 int num_listen_socks = 0;
200 * the client's version string, passed by sshd2 in compat mode. if != NULL,
201 * sshd will skip the version-number exchange
203 char *client_version_string = NULL;
204 char *server_version_string = NULL;
206 /* for rekeying XXX fixme */
210 * Any really sensitive data in the application is contained in this
211 * structure. The idea is that this structure could be locked into memory so
212 * that the pages do not get written into swap. However, there are some
213 * problems. The private key contains BIGNUMs, and we do not (in principle)
214 * have access to the internals of them, and locking just the structure is
215 * not very useful. Currently, memory locking is not implemented.
218 Key *server_key; /* ephemeral server key */
219 Key *ssh1_host_key; /* ssh1 host key */
220 Key **host_keys; /* all private host keys */
221 Key **host_certificates; /* all public host certificates */
224 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
228 * Flag indicating whether the RSA server key needs to be regenerated.
229 * Is set in the SIGALRM handler and cleared when the key is regenerated.
231 static volatile sig_atomic_t key_do_regen = 0;
233 /* This is set to true when a signal is received. */
234 static volatile sig_atomic_t received_sighup = 0;
235 static volatile sig_atomic_t received_sigterm = 0;
237 /* session identifier, used by RSA-auth */
238 u_char session_id[16];
241 u_char *session_id2 = NULL;
242 u_int session_id2_len = 0;
244 /* record remote hostname or ip */
245 u_int utmp_len = MAXHOSTNAMELEN;
247 /* options.max_startup sized array of fd ints */
248 int *startup_pipes = NULL;
249 int startup_pipe; /* in child */
251 /* variables used for privilege separation */
252 int use_privsep = -1;
253 struct monitor *pmonitor = NULL;
254 int privsep_is_preauth = 1;
256 /* global authentication context */
257 Authctxt *the_authctxt = NULL;
259 /* sshd_config buffer */
262 /* message to be displayed after login */
265 /* Unprivileged user */
266 struct passwd *privsep_pw = NULL;
268 /* Prototypes for various functions defined later in this file. */
269 void destroy_sensitive_data(void);
270 void demote_sensitive_data(void);
272 static void do_ssh1_kex(void);
273 static void do_ssh2_kex(void);
276 * Close all listening sockets
279 close_listen_socks(void)
283 for (i = 0; i < num_listen_socks; i++)
284 close(listen_socks[i]);
285 num_listen_socks = -1;
289 close_startup_pipes(void)
294 for (i = 0; i < options.max_startups; i++)
295 if (startup_pipes[i] != -1)
296 close(startup_pipes[i]);
300 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
301 * the effect is to reread the configuration file (and to regenerate
307 sighup_handler(int sig)
309 int save_errno = errno;
312 signal(SIGHUP, sighup_handler);
317 * Called from the main program after receiving SIGHUP.
318 * Restarts the server.
323 logit("Received SIGHUP; restarting.");
324 close_listen_socks();
325 close_startup_pipes();
326 alarm(0); /* alarm timer persists across exec */
327 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
328 execv(saved_argv[0], saved_argv);
329 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
335 * Generic signal handler for terminating signals in the master daemon.
339 sigterm_handler(int sig)
341 received_sigterm = sig;
345 * SIGCHLD handler. This is called whenever a child dies. This will then
346 * reap any zombies left by exited children.
350 main_sigchld_handler(int sig)
352 int save_errno = errno;
356 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
357 (pid < 0 && errno == EINTR))
360 signal(SIGCHLD, main_sigchld_handler);
365 * Signal handler for the alarm after the login grace period has expired.
369 grace_alarm_handler(int sig)
371 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
372 kill(pmonitor->m_pid, SIGALRM);
375 * Try to kill any processes that we have spawned, E.g. authorized
376 * keys command helpers.
378 if (getpgid(0) == getpid()) {
379 signal(SIGTERM, SIG_IGN);
383 /* Log error and exit. */
384 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
388 * Signal handler for the key regeneration alarm. Note that this
389 * alarm only occurs in the daemon waiting for connections, and it does not
390 * do anything with the private key or random state before forking.
391 * Thus there should be no concurrency control/asynchronous execution
395 generate_ephemeral_server_key(void)
397 verbose("Generating %s%d bit RSA key.",
398 sensitive_data.server_key ? "new " : "", options.server_key_bits);
399 if (sensitive_data.server_key != NULL)
400 key_free(sensitive_data.server_key);
401 sensitive_data.server_key = key_generate(KEY_RSA1,
402 options.server_key_bits);
403 verbose("RSA key generation complete.");
405 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
411 key_regeneration_alarm(int sig)
413 int save_errno = errno;
415 signal(SIGALRM, SIG_DFL);
421 sshd_exchange_identification(int sock_in, int sock_out)
425 int remote_major, remote_minor;
427 char *s, *newline = "\n";
428 char buf[256]; /* Must not be larger than remote_version. */
429 char remote_version[256]; /* Must be at least as big as buf. */
431 if ((options.protocol & SSH_PROTO_1) &&
432 (options.protocol & SSH_PROTO_2)) {
433 major = PROTOCOL_MAJOR_1;
435 } else if (options.protocol & SSH_PROTO_2) {
436 major = PROTOCOL_MAJOR_2;
437 minor = PROTOCOL_MINOR_2;
440 major = PROTOCOL_MAJOR_1;
441 minor = PROTOCOL_MINOR_1;
444 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s%s",
445 major, minor, SSH_VERSION,
446 options.hpn_disabled ? "" : SSH_VERSION_HPN,
447 *options.version_addendum == '\0' ? "" : " ",
448 options.version_addendum, newline);
450 /* Send our protocol version identification. */
451 if (roaming_atomicio(vwrite, sock_out, server_version_string,
452 strlen(server_version_string))
453 != strlen(server_version_string)) {
454 logit("Could not write ident string to %s", get_remote_ipaddr());
458 /* Read other sides version identification. */
459 memset(buf, 0, sizeof(buf));
460 for (i = 0; i < sizeof(buf) - 1; i++) {
461 if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
462 logit("Did not receive identification string from %s",
463 get_remote_ipaddr());
466 if (buf[i] == '\r') {
468 /* Kludge for F-Secure Macintosh < 1.0.2 */
470 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
474 if (buf[i] == '\n') {
479 buf[sizeof(buf) - 1] = 0;
480 client_version_string = xstrdup(buf);
483 * Check that the versions match. In future this might accept
484 * several versions and set appropriate flags to handle them.
486 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
487 &remote_major, &remote_minor, remote_version) != 3) {
488 s = "Protocol mismatch.\n";
489 (void) atomicio(vwrite, sock_out, s, strlen(s));
492 logit("Bad protocol version identification '%.100s' from %s",
493 client_version_string, get_remote_ipaddr());
496 debug("Client protocol version %d.%d; client software version %.100s",
497 remote_major, remote_minor, remote_version);
499 compat_datafellows(remote_version);
501 if (datafellows & SSH_BUG_PROBE) {
502 logit("probed from %s with %s. Don't panic.",
503 get_remote_ipaddr(), client_version_string);
507 if (datafellows & SSH_BUG_SCANNER) {
508 logit("scanned from %s with %s. Don't panic.",
509 get_remote_ipaddr(), client_version_string);
514 switch (remote_major) {
516 if (remote_minor == 99) {
517 if (options.protocol & SSH_PROTO_2)
523 if (!(options.protocol & SSH_PROTO_1)) {
527 if (remote_minor < 3) {
528 packet_disconnect("Your ssh version is too old and "
529 "is no longer supported. Please install a newer version.");
530 } else if (remote_minor == 3) {
531 /* note that this disables agent-forwarding */
536 if (options.protocol & SSH_PROTO_2) {
545 chop(server_version_string);
546 debug("Local version string %.200s", server_version_string);
549 s = "Protocol major versions differ.\n";
550 (void) atomicio(vwrite, sock_out, s, strlen(s));
553 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
555 server_version_string, client_version_string);
560 /* Destroy the host and server keys. They will no longer be needed. */
562 destroy_sensitive_data(void)
566 if (sensitive_data.server_key) {
567 key_free(sensitive_data.server_key);
568 sensitive_data.server_key = NULL;
570 for (i = 0; i < options.num_host_key_files; i++) {
571 if (sensitive_data.host_keys[i]) {
572 key_free(sensitive_data.host_keys[i]);
573 sensitive_data.host_keys[i] = NULL;
575 if (sensitive_data.host_certificates[i]) {
576 key_free(sensitive_data.host_certificates[i]);
577 sensitive_data.host_certificates[i] = NULL;
580 sensitive_data.ssh1_host_key = NULL;
581 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
584 /* Demote private to public keys for network child */
586 demote_sensitive_data(void)
591 if (sensitive_data.server_key) {
592 tmp = key_demote(sensitive_data.server_key);
593 key_free(sensitive_data.server_key);
594 sensitive_data.server_key = tmp;
597 for (i = 0; i < options.num_host_key_files; i++) {
598 if (sensitive_data.host_keys[i]) {
599 tmp = key_demote(sensitive_data.host_keys[i]);
600 key_free(sensitive_data.host_keys[i]);
601 sensitive_data.host_keys[i] = tmp;
602 if (tmp->type == KEY_RSA1)
603 sensitive_data.ssh1_host_key = tmp;
605 /* Certs do not need demotion */
608 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
612 privsep_preauth_child(void)
617 /* Enable challenge-response authentication for privilege separation */
618 privsep_challenge_enable();
621 arc4random_buf(rnd, sizeof(rnd));
622 RAND_seed(rnd, sizeof(rnd));
624 /* Demote the private keys to public keys. */
625 demote_sensitive_data();
627 /* Change our root directory */
628 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
629 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
631 if (chdir("/") == -1)
632 fatal("chdir(\"/\"): %s", strerror(errno));
634 /* Drop our privileges */
635 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
636 (u_int)privsep_pw->pw_gid);
638 /* XXX not ready, too heavy after chroot */
639 do_setusercontext(privsep_pw);
641 gidset[0] = privsep_pw->pw_gid;
642 if (setgroups(1, gidset) < 0)
643 fatal("setgroups: %.100s", strerror(errno));
644 permanently_set_uid(privsep_pw);
649 privsep_preauth(Authctxt *authctxt)
653 struct ssh_sandbox *box = NULL;
655 /* Set up unprivileged child process to deal with network data */
656 pmonitor = monitor_init();
657 /* Store a pointer to the kex for later rekeying */
658 pmonitor->m_pkex = &xxx_kex;
660 if (use_privsep == PRIVSEP_ON)
661 box = ssh_sandbox_init();
664 fatal("fork of unprivileged child failed");
665 } else if (pid != 0) {
666 debug2("Network child is on pid %ld", (long)pid);
668 pmonitor->m_pid = pid;
670 ssh_sandbox_parent_preauth(box, pid);
671 monitor_child_preauth(authctxt, pmonitor);
674 monitor_sync(pmonitor);
676 /* Wait for the child's exit status */
677 while (waitpid(pid, &status, 0) < 0) {
680 pmonitor->m_pid = -1;
681 fatal("%s: waitpid: %s", __func__, strerror(errno));
683 privsep_is_preauth = 0;
684 pmonitor->m_pid = -1;
685 if (WIFEXITED(status)) {
686 if (WEXITSTATUS(status) != 0)
687 fatal("%s: preauth child exited with status %d",
688 __func__, WEXITSTATUS(status));
689 } else if (WIFSIGNALED(status))
690 fatal("%s: preauth child terminated by signal %d",
691 __func__, WTERMSIG(status));
693 ssh_sandbox_parent_finish(box);
697 close(pmonitor->m_sendfd);
698 close(pmonitor->m_log_recvfd);
700 /* Arrange for logging to be sent to the monitor */
701 set_log_handler(mm_log_handler, pmonitor);
703 /* Demote the child */
704 if (getuid() == 0 || geteuid() == 0)
705 privsep_preauth_child();
706 setproctitle("%s", "[net]");
708 ssh_sandbox_child(box);
715 privsep_postauth(Authctxt *authctxt)
719 #ifdef DISABLE_FD_PASSING
722 if (authctxt->pw->pw_uid == 0 || options.use_login) {
724 /* File descriptor passing is broken or root login */
729 /* New socket pair */
730 monitor_reinit(pmonitor);
732 pmonitor->m_pid = fork();
733 if (pmonitor->m_pid == -1)
734 fatal("fork of unprivileged child failed");
735 else if (pmonitor->m_pid != 0) {
736 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
737 buffer_clear(&loginmsg);
738 monitor_child_postauth(pmonitor);
746 close(pmonitor->m_sendfd);
747 pmonitor->m_sendfd = -1;
749 /* Demote the private keys to public keys. */
750 demote_sensitive_data();
753 arc4random_buf(rnd, sizeof(rnd));
754 RAND_seed(rnd, sizeof(rnd));
756 /* Drop privileges */
757 do_setusercontext(authctxt->pw);
760 /* It is safe now to apply the key state */
761 monitor_apply_keystate(pmonitor);
764 * Tell the packet layer that authentication was successful, since
765 * this information is not part of the key state.
767 packet_set_authenticated();
771 list_hostkey_types(void)
780 for (i = 0; i < options.num_host_key_files; i++) {
781 key = sensitive_data.host_keys[i];
788 if (buffer_len(&b) > 0)
789 buffer_append(&b, ",", 1);
790 p = key_ssh_name(key);
791 buffer_append(&b, p, strlen(p));
794 /* If the private key has a cert peer, then list that too */
795 key = sensitive_data.host_certificates[i];
799 case KEY_RSA_CERT_V00:
800 case KEY_DSA_CERT_V00:
804 if (buffer_len(&b) > 0)
805 buffer_append(&b, ",", 1);
806 p = key_ssh_name(key);
807 buffer_append(&b, p, strlen(p));
811 buffer_append(&b, "\0", 1);
812 ret = xstrdup(buffer_ptr(&b));
814 debug("list_hostkey_types: %s", ret);
819 get_hostkey_by_type(int type, int need_private)
824 for (i = 0; i < options.num_host_key_files; i++) {
826 case KEY_RSA_CERT_V00:
827 case KEY_DSA_CERT_V00:
831 key = sensitive_data.host_certificates[i];
834 key = sensitive_data.host_keys[i];
837 if (key != NULL && key->type == type)
838 return need_private ?
839 sensitive_data.host_keys[i] : key;
845 get_hostkey_public_by_type(int type)
847 return get_hostkey_by_type(type, 0);
851 get_hostkey_private_by_type(int type)
853 return get_hostkey_by_type(type, 1);
857 get_hostkey_by_index(int ind)
859 if (ind < 0 || ind >= options.num_host_key_files)
861 return (sensitive_data.host_keys[ind]);
865 get_hostkey_index(Key *key)
869 for (i = 0; i < options.num_host_key_files; i++) {
870 if (key_is_cert(key)) {
871 if (key == sensitive_data.host_certificates[i])
874 if (key == sensitive_data.host_keys[i])
882 * returns 1 if connection should be dropped, 0 otherwise.
883 * dropping starts at connection #max_startups_begin with a probability
884 * of (max_startups_rate/100). the probability increases linearly until
885 * all connections are dropped for startups > max_startups
888 drop_connection(int startups)
892 if (startups < options.max_startups_begin)
894 if (startups >= options.max_startups)
896 if (options.max_startups_rate == 100)
899 p = 100 - options.max_startups_rate;
900 p *= startups - options.max_startups_begin;
901 p /= options.max_startups - options.max_startups_begin;
902 p += options.max_startups_rate;
903 r = arc4random_uniform(100);
905 debug("drop_connection: p %d, r %d", p, r);
906 return (r < p) ? 1 : 0;
912 if (options.version_addendum && *options.version_addendum != '\0')
913 fprintf(stderr, "%s%s %s, %s\n",
914 SSH_RELEASE, options.hpn_disabled ? "" : SSH_VERSION_HPN,
915 options.version_addendum, SSLeay_version(SSLEAY_VERSION));
917 fprintf(stderr, "%s%s, %s\n",
918 SSH_RELEASE, options.hpn_disabled ? "" : SSH_VERSION_HPN,
919 SSLeay_version(SSLEAY_VERSION));
921 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
922 " [-f config_file] [-g login_grace_time] [-h host_key_file]\n"
923 " [-k key_gen_time] [-o option] [-p port] [-u len]\n"
929 send_rexec_state(int fd, Buffer *conf)
933 debug3("%s: entering fd = %d config len %d", __func__, fd,
937 * Protocol from reexec master to child:
938 * string configuration
939 * u_int ephemeral_key_follows
940 * bignum e (only if ephemeral_key_follows == 1)
946 * string rngseed (only if OpenSSL is not self-seeded)
949 buffer_put_cstring(&m, buffer_ptr(conf));
951 if (sensitive_data.server_key != NULL &&
952 sensitive_data.server_key->type == KEY_RSA1) {
953 buffer_put_int(&m, 1);
954 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
955 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
956 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
957 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
958 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
959 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
961 buffer_put_int(&m, 0);
963 #ifndef OPENSSL_PRNG_ONLY
964 rexec_send_rng_seed(&m);
967 if (ssh_msg_send(fd, 0, &m) == -1)
968 fatal("%s: ssh_msg_send failed", __func__);
972 debug3("%s: done", __func__);
976 recv_rexec_state(int fd, Buffer *conf)
982 debug3("%s: entering fd = %d", __func__, fd);
986 if (ssh_msg_recv(fd, &m) == -1)
987 fatal("%s: ssh_msg_recv failed", __func__);
988 if (buffer_get_char(&m) != 0)
989 fatal("%s: rexec version mismatch", __func__);
991 cp = buffer_get_string(&m, &len);
993 buffer_append(conf, cp, len + 1);
996 if (buffer_get_int(&m)) {
997 if (sensitive_data.server_key != NULL)
998 key_free(sensitive_data.server_key);
999 sensitive_data.server_key = key_new_private(KEY_RSA1);
1000 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
1001 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
1002 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
1003 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1004 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
1005 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
1006 rsa_generate_additional_parameters(
1007 sensitive_data.server_key->rsa);
1010 #ifndef OPENSSL_PRNG_ONLY
1011 rexec_recv_rng_seed(&m);
1016 debug3("%s: done", __func__);
1019 /* Accept a connection from inetd */
1021 server_accept_inetd(int *sock_in, int *sock_out)
1027 close(REEXEC_CONFIG_PASS_FD);
1028 *sock_in = *sock_out = dup(STDIN_FILENO);
1030 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1031 close(REEXEC_STARTUP_PIPE_FD);
1034 *sock_in = dup(STDIN_FILENO);
1035 *sock_out = dup(STDOUT_FILENO);
1038 * We intentionally do not close the descriptors 0, 1, and 2
1039 * as our code for setting the descriptors won't work if
1040 * ttyfd happens to be one of those.
1042 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1043 dup2(fd, STDIN_FILENO);
1044 dup2(fd, STDOUT_FILENO);
1045 if (fd > STDOUT_FILENO)
1048 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1052 * Listen for TCP connections
1057 int ret, listen_sock, on = 1;
1058 struct addrinfo *ai;
1059 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1063 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1064 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1066 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1067 fatal("Too many listen sockets. "
1068 "Enlarge MAX_LISTEN_SOCKS");
1069 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1070 ntop, sizeof(ntop), strport, sizeof(strport),
1071 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1072 error("getnameinfo failed: %.100s",
1073 ssh_gai_strerror(ret));
1076 /* Create socket for listening. */
1077 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1079 if (listen_sock < 0) {
1080 /* kernel may not support ipv6 */
1081 verbose("socket: %.100s", strerror(errno));
1084 if (set_nonblock(listen_sock) == -1) {
1089 * Set socket options.
1090 * Allow local port reuse in TIME_WAIT.
1092 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1093 &on, sizeof(on)) == -1)
1094 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1096 /* Only communicate in IPv6 over AF_INET6 sockets. */
1097 if (ai->ai_family == AF_INET6)
1098 sock_set_v6only(listen_sock);
1100 debug("Bind to port %s on %s.", strport, ntop);
1102 len = sizeof(socksize);
1103 getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
1104 debug("Server TCP RWIN socket size: %d", socksize);
1105 debug("HPN Buffer Size: %d", options.hpn_buffer_size);
1107 /* Bind the socket to the desired port. */
1108 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1109 error("Bind to port %s on %s failed: %.200s.",
1110 strport, ntop, strerror(errno));
1114 listen_socks[num_listen_socks] = listen_sock;
1117 /* Start listening on the port. */
1118 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1119 fatal("listen on [%s]:%s: %.100s",
1120 ntop, strport, strerror(errno));
1121 logit("Server listening on %s port %s.", ntop, strport);
1123 freeaddrinfo(options.listen_addrs);
1125 if (!num_listen_socks)
1126 fatal("Cannot bind any address.");
1130 * The main TCP accept loop. Note that, for the non-debug case, returns
1131 * from this function are in a forked subprocess.
1134 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1137 int i, j, ret, maxfd;
1138 int key_used = 0, startups = 0;
1139 int startup_p[2] = { -1 , -1 };
1140 struct sockaddr_storage from;
1144 /* setup fd set for accept */
1147 for (i = 0; i < num_listen_socks; i++)
1148 if (listen_socks[i] > maxfd)
1149 maxfd = listen_socks[i];
1150 /* pipes connected to unauthenticated childs */
1151 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1152 for (i = 0; i < options.max_startups; i++)
1153 startup_pipes[i] = -1;
1156 * Stay listening for connections until the system crashes or
1157 * the daemon is killed with a signal.
1160 if (received_sighup)
1164 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1167 for (i = 0; i < num_listen_socks; i++)
1168 FD_SET(listen_socks[i], fdset);
1169 for (i = 0; i < options.max_startups; i++)
1170 if (startup_pipes[i] != -1)
1171 FD_SET(startup_pipes[i], fdset);
1173 /* Wait in select until there is a connection. */
1174 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1175 if (ret < 0 && errno != EINTR)
1176 error("select: %.100s", strerror(errno));
1177 if (received_sigterm) {
1178 logit("Received signal %d; terminating.",
1179 (int) received_sigterm);
1180 close_listen_socks();
1181 unlink(options.pid_file);
1182 exit(received_sigterm == SIGTERM ? 0 : 255);
1184 if (key_used && key_do_regen) {
1185 generate_ephemeral_server_key();
1192 for (i = 0; i < options.max_startups; i++)
1193 if (startup_pipes[i] != -1 &&
1194 FD_ISSET(startup_pipes[i], fdset)) {
1196 * the read end of the pipe is ready
1197 * if the child has closed the pipe
1198 * after successful authentication
1199 * or if the child has died
1201 close(startup_pipes[i]);
1202 startup_pipes[i] = -1;
1205 for (i = 0; i < num_listen_socks; i++) {
1206 if (!FD_ISSET(listen_socks[i], fdset))
1208 fromlen = sizeof(from);
1209 *newsock = accept(listen_socks[i],
1210 (struct sockaddr *)&from, &fromlen);
1212 if (errno != EINTR && errno != EAGAIN &&
1213 errno != EWOULDBLOCK)
1214 error("accept: %.100s",
1216 if (errno == EMFILE || errno == ENFILE)
1220 if (unset_nonblock(*newsock) == -1) {
1224 if (drop_connection(startups) == 1) {
1225 debug("drop connection #%d", startups);
1229 if (pipe(startup_p) == -1) {
1234 if (rexec_flag && socketpair(AF_UNIX,
1235 SOCK_STREAM, 0, config_s) == -1) {
1236 error("reexec socketpair: %s",
1239 close(startup_p[0]);
1240 close(startup_p[1]);
1244 for (j = 0; j < options.max_startups; j++)
1245 if (startup_pipes[j] == -1) {
1246 startup_pipes[j] = startup_p[0];
1247 if (maxfd < startup_p[0])
1248 maxfd = startup_p[0];
1254 * Got connection. Fork a child to handle it, unless
1255 * we are in debugging mode.
1259 * In debugging mode. Close the listening
1260 * socket, and start processing the
1261 * connection without forking.
1263 debug("Server will not fork when running in debugging mode.");
1264 close_listen_socks();
1265 *sock_in = *newsock;
1266 *sock_out = *newsock;
1267 close(startup_p[0]);
1268 close(startup_p[1]);
1272 send_rexec_state(config_s[0],
1280 * Normal production daemon. Fork, and have
1281 * the child process the connection. The
1282 * parent continues listening.
1284 platform_pre_fork();
1285 if ((pid = fork()) == 0) {
1287 * Child. Close the listening and
1288 * max_startup sockets. Start using
1289 * the accepted socket. Reinitialize
1290 * logging (since our pid has changed).
1291 * We break out of the loop to handle
1294 platform_post_fork_child();
1295 startup_pipe = startup_p[1];
1296 close_startup_pipes();
1297 close_listen_socks();
1298 *sock_in = *newsock;
1299 *sock_out = *newsock;
1300 log_init(__progname,
1302 options.log_facility,
1309 /* Parent. Stay in the loop. */
1310 platform_post_fork_parent(pid);
1312 error("fork: %.100s", strerror(errno));
1314 debug("Forked child %ld.", (long)pid);
1316 close(startup_p[1]);
1319 send_rexec_state(config_s[0], &cfg);
1325 * Mark that the key has been used (it
1326 * was "given" to the child).
1328 if ((options.protocol & SSH_PROTO_1) &&
1330 /* Schedule server key regeneration alarm. */
1331 signal(SIGALRM, key_regeneration_alarm);
1332 alarm(options.key_regeneration_time);
1339 * Ensure that our random state differs
1340 * from that of the child
1345 /* child process check (or debug mode) */
1346 if (num_listen_socks < 0)
1353 * Main program for the daemon.
1356 main(int ac, char **av)
1358 extern char *optarg;
1360 int opt, i, j, on = 1;
1361 int sock_in = -1, sock_out = -1, newsock = -1;
1362 const char *remote_ip;
1365 int config_s[2] = { -1 , -1 };
1367 u_int64_t ibytes, obytes;
1371 struct connection_info *connection_info = get_connection_info(0, 0);
1373 #ifdef HAVE_SECUREWARE
1374 (void)set_auth_parameters(ac, av);
1376 __progname = ssh_get_progname(av[0]);
1378 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1381 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1382 for (i = 0; i < ac; i++)
1383 saved_argv[i] = xstrdup(av[i]);
1384 saved_argv[i] = NULL;
1386 #ifndef HAVE_SETPROCTITLE
1387 /* Prepare for later setproctitle emulation */
1388 compat_init_setproctitle(ac, av);
1392 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1393 debug("setgroups(): %.200s", strerror(errno));
1395 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1398 /* Initialize configuration options to their default values. */
1399 initialize_server_options(&options);
1401 /* Parse command-line arguments. */
1402 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeiqrtQRT46")) != -1) {
1405 options.address_family = AF_INET;
1408 options.address_family = AF_INET6;
1411 config_file_name = optarg;
1414 if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1415 fprintf(stderr, "too many host certificates.\n");
1418 options.host_cert_files[options.num_host_cert_files++] =
1419 derelativise_path(optarg);
1422 if (debug_flag == 0) {
1424 options.log_level = SYSLOG_LEVEL_DEBUG1;
1425 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1426 options.log_level++;
1448 options.log_level = SYSLOG_LEVEL_QUIET;
1451 options.server_key_bits = (int)strtonum(optarg, 256,
1455 options.ports_from_cmdline = 1;
1456 if (options.num_ports >= MAX_PORTS) {
1457 fprintf(stderr, "too many ports.\n");
1460 options.ports[options.num_ports++] = a2port(optarg);
1461 if (options.ports[options.num_ports-1] <= 0) {
1462 fprintf(stderr, "Bad port number.\n");
1467 if ((options.login_grace_time = convtime(optarg)) == -1) {
1468 fprintf(stderr, "Invalid login grace time.\n");
1473 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1474 fprintf(stderr, "Invalid key regeneration interval.\n");
1479 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1480 fprintf(stderr, "too many host keys.\n");
1483 options.host_key_files[options.num_host_key_files++] =
1484 derelativise_path(optarg);
1493 if (parse_server_match_testspec(connection_info,
1498 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1499 if (utmp_len > MAXHOSTNAMELEN) {
1500 fprintf(stderr, "Invalid utmp length.\n");
1505 line = xstrdup(optarg);
1506 if (process_server_config_line(&options, line,
1507 "command-line", 0, NULL, NULL) != 0)
1517 if (rexeced_flag || inetd_flag)
1519 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1520 fatal("sshd re-exec requires execution with an absolute path");
1522 closefrom(REEXEC_MIN_FREE_FD);
1524 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1526 OpenSSL_add_all_algorithms();
1529 * Force logging to stderr until we have loaded the private host
1530 * key (unless started from inetd)
1532 log_init(__progname,
1533 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1534 SYSLOG_LEVEL_INFO : options.log_level,
1535 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1536 SYSLOG_FACILITY_AUTH : options.log_facility,
1537 log_stderr || !inetd_flag);
1540 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1541 * root's environment
1543 if (getenv("KRB5CCNAME") != NULL)
1544 (void) unsetenv("KRB5CCNAME");
1547 /* Cray can define user privs drop all privs now!
1548 * Not needed on PRIV_SU systems!
1553 sensitive_data.server_key = NULL;
1554 sensitive_data.ssh1_host_key = NULL;
1555 sensitive_data.have_ssh1_key = 0;
1556 sensitive_data.have_ssh2_key = 0;
1559 * If we're doing an extended config test, make sure we have all of
1560 * the parameters we need. If we're not doing an extended test,
1561 * do not silently ignore connection test params.
1563 if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1564 fatal("user, host and addr are all required when testing "
1566 if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1567 fatal("Config test connection parameter (-C) provided without "
1570 /* Fetch our configuration */
1573 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1575 load_server_config(config_file_name, &cfg);
1577 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1582 /* Fill in default values for those options not explicitly set. */
1583 fill_default_server_options(&options);
1585 /* challenge-response is implemented via keyboard interactive */
1586 if (options.challenge_response_authentication)
1587 options.kbd_interactive_authentication = 1;
1589 /* Check that options are sensible */
1590 if (options.authorized_keys_command_user == NULL &&
1591 (options.authorized_keys_command != NULL &&
1592 strcasecmp(options.authorized_keys_command, "none") != 0))
1593 fatal("AuthorizedKeysCommand set without "
1594 "AuthorizedKeysCommandUser");
1597 * Check whether there is any path through configured auth methods.
1598 * Unfortunately it is not possible to verify this generally before
1599 * daemonisation in the presence of Match block, but this catches
1600 * and warns for trivial misconfigurations that could break login.
1602 if (options.num_auth_methods != 0) {
1603 if ((options.protocol & SSH_PROTO_1))
1604 fatal("AuthenticationMethods is not supported with "
1606 for (n = 0; n < options.num_auth_methods; n++) {
1607 if (auth2_methods_valid(options.auth_methods[n],
1611 if (n >= options.num_auth_methods)
1612 fatal("AuthenticationMethods cannot be satisfied by "
1613 "enabled authentication methods");
1616 /* set default channel AF */
1617 channel_set_af(options.address_family);
1619 /* Check that there are no remaining arguments. */
1621 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1625 debug("sshd version %.100s%.100s%s%.100s, %.100s",
1627 options.hpn_disabled ? "" : SSH_VERSION_HPN,
1628 *options.version_addendum == '\0' ? "" : " ",
1629 options.version_addendum,
1630 SSLeay_version(SSLEAY_VERSION));
1632 /* Store privilege separation user for later use if required. */
1633 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1634 if (use_privsep || options.kerberos_authentication)
1635 fatal("Privilege separation user %s does not exist",
1638 memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1639 privsep_pw = pwcopy(privsep_pw);
1640 xfree(privsep_pw->pw_passwd);
1641 privsep_pw->pw_passwd = xstrdup("*");
1645 /* load private host keys */
1646 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1648 for (i = 0; i < options.num_host_key_files; i++)
1649 sensitive_data.host_keys[i] = NULL;
1651 for (i = 0; i < options.num_host_key_files; i++) {
1652 key = key_load_private(options.host_key_files[i], "", NULL);
1653 sensitive_data.host_keys[i] = key;
1655 error("Could not load host key: %s",
1656 options.host_key_files[i]);
1657 sensitive_data.host_keys[i] = NULL;
1660 switch (key->type) {
1662 sensitive_data.ssh1_host_key = key;
1663 sensitive_data.have_ssh1_key = 1;
1668 sensitive_data.have_ssh2_key = 1;
1671 debug("private host key: #%d type %d %s", i, key->type,
1674 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1675 logit("Disabling protocol version 1. Could not load host key");
1676 options.protocol &= ~SSH_PROTO_1;
1678 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1679 logit("Disabling protocol version 2. Could not load host key");
1680 options.protocol &= ~SSH_PROTO_2;
1682 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1683 logit("sshd: no hostkeys available -- exiting.");
1688 * Load certificates. They are stored in an array at identical
1689 * indices to the public keys that they relate to.
1691 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1693 for (i = 0; i < options.num_host_key_files; i++)
1694 sensitive_data.host_certificates[i] = NULL;
1696 for (i = 0; i < options.num_host_cert_files; i++) {
1697 key = key_load_public(options.host_cert_files[i], NULL);
1699 error("Could not load host certificate: %s",
1700 options.host_cert_files[i]);
1703 if (!key_is_cert(key)) {
1704 error("Certificate file is not a certificate: %s",
1705 options.host_cert_files[i]);
1709 /* Find matching private key */
1710 for (j = 0; j < options.num_host_key_files; j++) {
1711 if (key_equal_public(key,
1712 sensitive_data.host_keys[j])) {
1713 sensitive_data.host_certificates[j] = key;
1717 if (j >= options.num_host_key_files) {
1718 error("No matching private key for certificate: %s",
1719 options.host_cert_files[i]);
1723 sensitive_data.host_certificates[j] = key;
1724 debug("host certificate: #%d type %d %s", j, key->type,
1727 /* Check certain values for sanity. */
1728 if (options.protocol & SSH_PROTO_1) {
1729 if (options.server_key_bits < 512 ||
1730 options.server_key_bits > 32768) {
1731 fprintf(stderr, "Bad server key size.\n");
1735 * Check that server and host key lengths differ sufficiently. This
1736 * is necessary to make double encryption work with rsaref. Oh, I
1737 * hate software patents. I dont know if this can go? Niels
1739 if (options.server_key_bits >
1740 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1741 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1742 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1743 SSH_KEY_BITS_RESERVED) {
1744 options.server_key_bits =
1745 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1746 SSH_KEY_BITS_RESERVED;
1747 debug("Forcing server key to %d bits to make it differ from host key.",
1748 options.server_key_bits);
1755 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1756 (S_ISDIR(st.st_mode) == 0))
1757 fatal("Missing privilege separation directory: %s",
1758 _PATH_PRIVSEP_CHROOT_DIR);
1761 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1762 (st.st_uid != getuid () ||
1763 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1765 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1767 fatal("%s must be owned by root and not group or "
1768 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1771 if (test_flag > 1) {
1772 if (server_match_spec_complete(connection_info) == 1)
1773 parse_server_match_config(&options, connection_info);
1774 dump_config(&options);
1777 /* Configuration looks good, so exit if in test mode. */
1782 * Clear out any supplemental groups we may have inherited. This
1783 * prevents inadvertent creation of files with bad modes (in the
1784 * portable version at least, it's certainly possible for PAM
1785 * to create a file, and we can't control the code in every
1786 * module which might be used).
1788 if (setgroups(0, NULL) < 0)
1789 debug("setgroups() failed: %.200s", strerror(errno));
1792 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1793 for (i = 0; i < rexec_argc; i++) {
1794 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1795 rexec_argv[i] = saved_argv[i];
1797 rexec_argv[rexec_argc] = "-R";
1798 rexec_argv[rexec_argc + 1] = NULL;
1801 /* Ensure that umask disallows at least group and world write */
1802 new_umask = umask(0077) | 0022;
1803 (void) umask(new_umask);
1805 /* Initialize the log (it is reinitialized below in case we forked). */
1806 if (debug_flag && (!inetd_flag || rexeced_flag))
1808 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1811 * If not in debugging mode, and not started from inetd, disconnect
1812 * from the controlling terminal, and fork. The original process
1815 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1818 #endif /* TIOCNOTTY */
1819 if (daemon(0, 0) < 0)
1820 fatal("daemon() failed: %.200s", strerror(errno));
1822 /* Disconnect from the controlling tty. */
1824 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1826 (void) ioctl(fd, TIOCNOTTY, NULL);
1829 #endif /* TIOCNOTTY */
1831 /* Reinitialize the log (because of the fork above). */
1832 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1834 /* Avoid killing the process in high-pressure swapping environments. */
1835 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
1836 debug("madvise(): %.200s", strerror(errno));
1838 /* Initialize the random number generator. */
1841 /* Chdir to the root directory so that the current disk can be
1842 unmounted if desired. */
1845 /* ignore SIGPIPE */
1846 signal(SIGPIPE, SIG_IGN);
1848 /* Get a connection, either from inetd or a listening TCP socket */
1850 server_accept_inetd(&sock_in, &sock_out);
1852 platform_pre_listen();
1855 if (options.protocol & SSH_PROTO_1)
1856 generate_ephemeral_server_key();
1858 signal(SIGHUP, sighup_handler);
1859 signal(SIGCHLD, main_sigchld_handler);
1860 signal(SIGTERM, sigterm_handler);
1861 signal(SIGQUIT, sigterm_handler);
1864 * Write out the pid file after the sigterm handler
1865 * is setup and the listen sockets are bound
1868 FILE *f = fopen(options.pid_file, "w");
1871 error("Couldn't create pid file \"%s\": %s",
1872 options.pid_file, strerror(errno));
1874 fprintf(f, "%ld\n", (long) getpid());
1879 /* Accept a connection and return in a forked child */
1880 server_accept_loop(&sock_in, &sock_out,
1881 &newsock, config_s);
1884 /* This is the child processing a new connection. */
1885 setproctitle("%s", "[accepted]");
1888 * Create a new session and process group since the 4.4BSD
1889 * setlogin() affects the entire process group. We don't
1890 * want the child to be able to affect the parent.
1892 #if !defined(SSHD_ACQUIRES_CTTY)
1894 * If setsid is called, on some platforms sshd will later acquire a
1895 * controlling terminal which will result in "could not set
1896 * controlling tty" errors.
1898 if (!debug_flag && !inetd_flag && setsid() < 0)
1899 error("setsid: %.100s", strerror(errno));
1905 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1906 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1907 dup2(newsock, STDIN_FILENO);
1908 dup2(STDIN_FILENO, STDOUT_FILENO);
1909 if (startup_pipe == -1)
1910 close(REEXEC_STARTUP_PIPE_FD);
1912 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1914 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1916 if (startup_pipe != -1)
1917 close(startup_pipe);
1919 execv(rexec_argv[0], rexec_argv);
1921 /* Reexec has failed, fall back and continue */
1922 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1923 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1924 log_init(__progname, options.log_level,
1925 options.log_facility, log_stderr);
1928 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1930 close(REEXEC_CONFIG_PASS_FD);
1931 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1932 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1933 dup2(fd, STDIN_FILENO);
1934 dup2(fd, STDOUT_FILENO);
1935 if (fd > STDERR_FILENO)
1938 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1939 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1942 /* Executed child processes don't need these. */
1943 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1944 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1947 * Disable the key regeneration alarm. We will not regenerate the
1948 * key since we are no longer in a position to give it to anyone. We
1949 * will not restart on SIGHUP since it no longer makes sense.
1952 signal(SIGALRM, SIG_DFL);
1953 signal(SIGHUP, SIG_DFL);
1954 signal(SIGTERM, SIG_DFL);
1955 signal(SIGQUIT, SIG_DFL);
1956 signal(SIGCHLD, SIG_DFL);
1957 signal(SIGINT, SIG_DFL);
1961 * Initialize the resolver. This may not happen automatically
1962 * before privsep chroot().
1964 if ((_res.options & RES_INIT) == 0) {
1965 debug("res_init()");
1970 * Force GSS-API to parse its configuration and load any
1971 * mechanism plugins.
1975 OM_uint32 minor_status;
1976 gss_indicate_mechs(&minor_status, &mechs);
1977 gss_release_oid_set(&minor_status, &mechs);
1983 * Register our connection. This turns encryption off because we do
1986 packet_set_connection(sock_in, sock_out);
1987 packet_set_server();
1989 /* Set SO_KEEPALIVE if requested. */
1990 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1991 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1992 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1994 if ((remote_port = get_remote_port()) < 0) {
1995 debug("get_remote_port failed");
2000 * We use get_canonical_hostname with usedns = 0 instead of
2001 * get_remote_ipaddr here so IP options will be checked.
2003 (void) get_canonical_hostname(0);
2005 * The rest of the code depends on the fact that
2006 * get_remote_ipaddr() caches the remote ip, even if
2007 * the socket goes away.
2009 remote_ip = get_remote_ipaddr();
2011 #ifdef SSH_AUDIT_EVENTS
2012 audit_connection_from(remote_ip, remote_port);
2015 allow_severity = options.log_facility|LOG_INFO;
2016 deny_severity = options.log_facility|LOG_WARNING;
2017 /* Check whether logins are denied from this host. */
2018 if (packet_connection_is_on_socket()) {
2019 struct request_info req;
2021 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
2024 if (!hosts_access(&req)) {
2025 debug("Connection refused by tcp wrapper");
2028 fatal("libwrap refuse returns");
2031 #endif /* LIBWRAP */
2033 /* Log the connection. */
2034 verbose("Connection from %.500s port %d", remote_ip, remote_port);
2036 /* Set HPN options for the child. */
2037 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
2040 * We don't want to listen forever unless the other side
2041 * successfully authenticates itself. So we set up an alarm which is
2042 * cleared after successful authentication. A limit of zero
2043 * indicates no limit. Note that we don't set the alarm in debugging
2044 * mode; it is just annoying to have the server exit just when you
2045 * are about to discover the bug.
2047 signal(SIGALRM, grace_alarm_handler);
2049 alarm(options.login_grace_time);
2051 sshd_exchange_identification(sock_in, sock_out);
2053 /* In inetd mode, generate ephemeral key only for proto 1 connections */
2054 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2055 generate_ephemeral_server_key();
2057 packet_set_nonblocking();
2059 /* allocate authentication context */
2060 authctxt = xcalloc(1, sizeof(*authctxt));
2062 authctxt->loginmsg = &loginmsg;
2064 /* XXX global for cleanup, access from other modules */
2065 the_authctxt = authctxt;
2067 /* prepare buffer to collect messages to display to user after login */
2068 buffer_init(&loginmsg);
2072 if (privsep_preauth(authctxt) == 1)
2075 /* perform the key exchange */
2076 /* authenticate user and start session */
2079 do_authentication2(authctxt);
2082 do_authentication(authctxt);
2085 * If we use privilege separation, the unprivileged child transfers
2086 * the current keystate and exits
2089 mm_send_keystate(pmonitor);
2095 * Cancel the alarm we set to limit the time taken for
2099 signal(SIGALRM, SIG_DFL);
2100 authctxt->authenticated = 1;
2101 if (startup_pipe != -1) {
2102 close(startup_pipe);
2106 #ifdef SSH_AUDIT_EVENTS
2107 audit_event(SSH_AUTH_SUCCESS);
2111 if (options.gss_authentication) {
2112 temporarily_use_uid(authctxt->pw);
2113 ssh_gssapi_storecreds();
2118 if (options.use_pam) {
2125 * In privilege separation, we fork another child and prepare
2126 * file descriptor passing.
2129 privsep_postauth(authctxt);
2130 /* the monitor process [priv] will not return */
2132 destroy_sensitive_data();
2135 packet_set_timeout(options.client_alive_interval,
2136 options.client_alive_count_max);
2138 /* Start session. */
2139 do_authenticated(authctxt);
2141 /* The connection has been terminated. */
2142 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
2143 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
2144 verbose("Transferred: sent %llu, received %llu bytes",
2145 (unsigned long long)obytes, (unsigned long long)ibytes);
2147 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2150 if (options.use_pam)
2152 #endif /* USE_PAM */
2154 #ifdef SSH_AUDIT_EVENTS
2155 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2167 * Decrypt session_key_int using our private server key and private host key
2168 * (key with larger modulus first).
2171 ssh1_session_key(BIGNUM *session_key_int)
2175 if (BN_cmp(sensitive_data.server_key->rsa->n,
2176 sensitive_data.ssh1_host_key->rsa->n) > 0) {
2177 /* Server key has bigger modulus. */
2178 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2179 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2180 SSH_KEY_BITS_RESERVED) {
2181 fatal("do_connection: %s: "
2182 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2183 get_remote_ipaddr(),
2184 BN_num_bits(sensitive_data.server_key->rsa->n),
2185 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2186 SSH_KEY_BITS_RESERVED);
2188 if (rsa_private_decrypt(session_key_int, session_key_int,
2189 sensitive_data.server_key->rsa) <= 0)
2191 if (rsa_private_decrypt(session_key_int, session_key_int,
2192 sensitive_data.ssh1_host_key->rsa) <= 0)
2195 /* Host key has bigger modulus (or they are equal). */
2196 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2197 BN_num_bits(sensitive_data.server_key->rsa->n) +
2198 SSH_KEY_BITS_RESERVED) {
2199 fatal("do_connection: %s: "
2200 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2201 get_remote_ipaddr(),
2202 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2203 BN_num_bits(sensitive_data.server_key->rsa->n),
2204 SSH_KEY_BITS_RESERVED);
2206 if (rsa_private_decrypt(session_key_int, session_key_int,
2207 sensitive_data.ssh1_host_key->rsa) < 0)
2209 if (rsa_private_decrypt(session_key_int, session_key_int,
2210 sensitive_data.server_key->rsa) < 0)
2223 BIGNUM *session_key_int;
2224 u_char session_key[SSH_SESSION_KEY_LENGTH];
2226 u_int cipher_type, auth_mask, protocol_flags;
2229 * Generate check bytes that the client must send back in the user
2230 * packet in order for it to be accepted; this is used to defy ip
2231 * spoofing attacks. Note that this only works against somebody
2232 * doing IP spoofing from a remote machine; any machine on the local
2233 * network can still see outgoing packets and catch the random
2234 * cookie. This only affects rhosts authentication, and this is one
2235 * of the reasons why it is inherently insecure.
2237 arc4random_buf(cookie, sizeof(cookie));
2240 * Send our public key. We include in the packet 64 bits of random
2241 * data that must be matched in the reply in order to prevent IP
2244 packet_start(SSH_SMSG_PUBLIC_KEY);
2245 for (i = 0; i < 8; i++)
2246 packet_put_char(cookie[i]);
2248 /* Store our public server RSA key. */
2249 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2250 packet_put_bignum(sensitive_data.server_key->rsa->e);
2251 packet_put_bignum(sensitive_data.server_key->rsa->n);
2253 /* Store our public host RSA key. */
2254 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2255 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2256 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2258 /* Put protocol flags. */
2259 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2261 /* Declare which ciphers we support. */
2262 packet_put_int(cipher_mask_ssh1(0));
2264 /* Declare supported authentication types. */
2266 if (options.rhosts_rsa_authentication)
2267 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2268 if (options.rsa_authentication)
2269 auth_mask |= 1 << SSH_AUTH_RSA;
2270 if (options.challenge_response_authentication == 1)
2271 auth_mask |= 1 << SSH_AUTH_TIS;
2272 if (options.password_authentication)
2273 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2274 packet_put_int(auth_mask);
2276 /* Send the packet and wait for it to be sent. */
2278 packet_write_wait();
2280 debug("Sent %d bit server key and %d bit host key.",
2281 BN_num_bits(sensitive_data.server_key->rsa->n),
2282 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2284 /* Read clients reply (cipher type and session key). */
2285 packet_read_expect(SSH_CMSG_SESSION_KEY);
2287 /* Get cipher type and check whether we accept this. */
2288 cipher_type = packet_get_char();
2290 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2291 packet_disconnect("Warning: client selects unsupported cipher.");
2293 /* Get check bytes from the packet. These must match those we
2294 sent earlier with the public key packet. */
2295 for (i = 0; i < 8; i++)
2296 if (cookie[i] != packet_get_char())
2297 packet_disconnect("IP Spoofing check bytes do not match.");
2299 debug("Encryption type: %.200s", cipher_name(cipher_type));
2301 /* Get the encrypted integer. */
2302 if ((session_key_int = BN_new()) == NULL)
2303 fatal("do_ssh1_kex: BN_new failed");
2304 packet_get_bignum(session_key_int);
2306 protocol_flags = packet_get_int();
2307 packet_set_protocol_flags(protocol_flags);
2310 /* Decrypt session_key_int using host/server keys */
2311 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2314 * Extract session key from the decrypted integer. The key is in the
2315 * least significant 256 bits of the integer; the first byte of the
2316 * key is in the highest bits.
2319 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2320 len = BN_num_bytes(session_key_int);
2321 if (len < 0 || (u_int)len > sizeof(session_key)) {
2322 error("do_ssh1_kex: bad session key len from %s: "
2323 "session_key_int %d > sizeof(session_key) %lu",
2324 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2327 memset(session_key, 0, sizeof(session_key));
2328 BN_bn2bin(session_key_int,
2329 session_key + sizeof(session_key) - len);
2331 derive_ssh1_session_id(
2332 sensitive_data.ssh1_host_key->rsa->n,
2333 sensitive_data.server_key->rsa->n,
2334 cookie, session_id);
2336 * Xor the first 16 bytes of the session key with the
2339 for (i = 0; i < 16; i++)
2340 session_key[i] ^= session_id[i];
2344 int bytes = BN_num_bytes(session_key_int);
2345 u_char *buf = xmalloc(bytes);
2348 logit("do_connection: generating a fake encryption key");
2349 BN_bn2bin(session_key_int, buf);
2351 MD5_Update(&md, buf, bytes);
2352 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2353 MD5_Final(session_key, &md);
2355 MD5_Update(&md, session_key, 16);
2356 MD5_Update(&md, buf, bytes);
2357 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2358 MD5_Final(session_key + 16, &md);
2359 memset(buf, 0, bytes);
2361 for (i = 0; i < 16; i++)
2362 session_id[i] = session_key[i] ^ session_key[i + 16];
2364 /* Destroy the private and public keys. No longer. */
2365 destroy_sensitive_data();
2368 mm_ssh1_session_id(session_id);
2370 /* Destroy the decrypted integer. It is no longer needed. */
2371 BN_clear_free(session_key_int);
2373 /* Set the session key. From this on all communications will be encrypted. */
2374 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2376 /* Destroy our copy of the session key. It is no longer needed. */
2377 memset(session_key, 0, sizeof(session_key));
2379 debug("Received session key; encryption turned on.");
2381 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2382 packet_start(SSH_SMSG_SUCCESS);
2384 packet_write_wait();
2388 * SSH2 key exchange: diffie-hellman-group1-sha1
2395 if (options.ciphers != NULL) {
2396 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2397 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2398 #ifdef NONE_CIPHER_ENABLED
2399 } else if (options.none_enabled == 1) {
2400 debug ("WARNING: None cipher enabled");
2401 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2402 myproposal[PROPOSAL_ENC_ALGS_STOC] = KEX_ENCRYPT_INCLUDE_NONE;
2405 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2406 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2407 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2408 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2410 if (options.macs != NULL) {
2411 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2412 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2414 if (options.compression == COMP_NONE) {
2415 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2416 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2417 } else if (options.compression == COMP_DELAYED) {
2418 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2419 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2421 if (options.kex_algorithms != NULL)
2422 myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
2424 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2426 /* start key exchange */
2427 kex = kex_setup(myproposal);
2428 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2429 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2430 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2431 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2432 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2434 kex->client_version_string=client_version_string;
2435 kex->server_version_string=server_version_string;
2436 kex->load_host_public_key=&get_hostkey_public_by_type;
2437 kex->load_host_private_key=&get_hostkey_private_by_type;
2438 kex->host_key_index=&get_hostkey_index;
2442 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2444 session_id2 = kex->session_id;
2445 session_id2_len = kex->session_id_len;
2448 /* send 1st encrypted/maced/compressed message */
2449 packet_start(SSH2_MSG_IGNORE);
2450 packet_put_cstring("markus");
2452 packet_write_wait();
2457 /* server specific fatal cleanup */
2462 do_cleanup(the_authctxt);
2463 if (use_privsep && privsep_is_preauth && pmonitor->m_pid > 1) {
2464 debug("Killing privsep child %d", pmonitor->m_pid);
2465 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2467 error("%s: kill(%d): %s", __func__,
2468 pmonitor->m_pid, strerror(errno));
2471 #ifdef SSH_AUDIT_EVENTS
2472 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2473 if (!use_privsep || mm_is_monitor())
2474 audit_event(SSH_CONNECTION_ABANDON);