1 /* $OpenBSD: sshd.c,v 1.480 2016/12/09 03:04:29 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This program is the ssh daemon. It listens for connections from clients,
7 * and performs authentication, executes use commands or shell, and forwards
8 * information to/from the application to the user client over an encrypted
9 * connection. This can also handle forwarding of X11, TCP/IP, and
10 * authentication agent connections.
12 * As far as I am concerned, the code I have written for this software
13 * can be used freely for any purpose. Any derived versions of this
14 * software must be clearly marked as such, and if the derived work is
15 * incompatible with the protocol description in the RFC file, it must be
16 * called by a name other than "ssh" or "Secure Shell".
18 * SSH2 implementation:
19 * Privilege Separation:
21 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
22 * Copyright (c) 2002 Niels Provos. All rights reserved.
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
27 * 1. Redistributions of source code must retain the above copyright
28 * notice, this list of conditions and the following disclaimer.
29 * 2. Redistributions in binary form must reproduce the above copyright
30 * notice, this list of conditions and the following disclaimer in the
31 * documentation and/or other materials provided with the distribution.
33 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48 #include <sys/types.h>
49 #include <sys/ioctl.h>
51 #include <sys/socket.h>
52 #ifdef HAVE_SYS_STAT_H
53 # include <sys/stat.h>
55 #ifdef HAVE_SYS_TIME_H
56 # include <sys/time.h>
58 #include "openbsd-compat/sys-tree.h"
59 #include "openbsd-compat/sys-queue.h"
79 #include <openssl/dh.h>
80 #include <openssl/bn.h>
81 #include <openssl/rand.h>
82 #include "openbsd-compat/openssl-compat.h"
85 #ifdef HAVE_SECUREWARE
86 #include <sys/security.h>
92 #if defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
93 #include <gssapi/gssapi.h>
94 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_H)
109 #include "servconf.h"
116 #include "myproposal.h"
117 #include "authfile.h"
118 #include "pathnames.h"
119 #include "atomicio.h"
120 #include "canohost.h"
121 #include "hostfile.h"
125 #include "dispatch.h"
126 #include "channels.h"
132 #include "monitor_wrap.h"
133 #include "ssh-sandbox.h"
136 #include "blacklist_client.h"
146 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
147 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
148 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
149 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
151 extern char *__progname;
153 /* Server configuration options. */
154 ServerOptions options;
156 /* Name of the server configuration file. */
157 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
160 * Debug mode flag. This can be set on the command line. If debug
161 * mode is enabled, extra debugging output will be sent to the system
162 * log, the daemon will not go to background, and will exit after processing
163 * the first connection.
167 /* Flag indicating that the daemon should only test the configuration and keys. */
170 /* Flag indicating that the daemon is being started from inetd. */
173 /* Flag indicating that sshd should not detach and become a daemon. */
174 int no_daemon_flag = 0;
176 /* debug goes to stderr unless inetd_flag is set */
179 /* Saved arguments to main(). */
184 int rexeced_flag = 0;
190 * The sockets that the server is listening; this is used in the SIGHUP
193 #define MAX_LISTEN_SOCKS 16
194 int listen_socks[MAX_LISTEN_SOCKS];
195 int num_listen_socks = 0;
198 * the client's version string, passed by sshd2 in compat mode. if != NULL,
199 * sshd will skip the version-number exchange
201 char *client_version_string = NULL;
202 char *server_version_string = NULL;
204 /* Daemon's agent connection */
209 * Any really sensitive data in the application is contained in this
210 * structure. The idea is that this structure could be locked into memory so
211 * that the pages do not get written into swap. However, there are some
212 * problems. The private key contains BIGNUMs, and we do not (in principle)
213 * have access to the internals of them, and locking just the structure is
214 * not very useful. Currently, memory locking is not implemented.
217 Key **host_keys; /* all private host keys */
218 Key **host_pubkeys; /* all public host keys */
219 Key **host_certificates; /* all public host certificates */
223 /* This is set to true when a signal is received. */
224 static volatile sig_atomic_t received_sighup = 0;
225 static volatile sig_atomic_t received_sigterm = 0;
227 /* session identifier, used by RSA-auth */
228 u_char session_id[16];
231 u_char *session_id2 = NULL;
232 u_int session_id2_len = 0;
234 /* record remote hostname or ip */
235 u_int utmp_len = HOST_NAME_MAX+1;
237 /* options.max_startup sized array of fd ints */
238 int *startup_pipes = NULL;
239 int startup_pipe; /* in child */
241 /* variables used for privilege separation */
242 int use_privsep = -1;
243 struct monitor *pmonitor = NULL;
244 int privsep_is_preauth = 1;
246 /* global authentication context */
247 Authctxt *the_authctxt = NULL;
249 /* sshd_config buffer */
252 /* message to be displayed after login */
255 /* Unprivileged user */
256 struct passwd *privsep_pw = NULL;
258 /* Prototypes for various functions defined later in this file. */
259 void destroy_sensitive_data(void);
260 void demote_sensitive_data(void);
261 static void do_ssh2_kex(void);
264 * Close all listening sockets
267 close_listen_socks(void)
271 for (i = 0; i < num_listen_socks; i++)
272 close(listen_socks[i]);
273 num_listen_socks = -1;
277 close_startup_pipes(void)
282 for (i = 0; i < options.max_startups; i++)
283 if (startup_pipes[i] != -1)
284 close(startup_pipes[i]);
288 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
289 * the effect is to reread the configuration file (and to regenerate
295 sighup_handler(int sig)
297 int save_errno = errno;
300 signal(SIGHUP, sighup_handler);
305 * Called from the main program after receiving SIGHUP.
306 * Restarts the server.
311 logit("Received SIGHUP; restarting.");
312 if (options.pid_file != NULL)
313 unlink(options.pid_file);
314 platform_pre_restart();
315 close_listen_socks();
316 close_startup_pipes();
317 alarm(0); /* alarm timer persists across exec */
318 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
319 execv(saved_argv[0], saved_argv);
320 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
326 * Generic signal handler for terminating signals in the master daemon.
330 sigterm_handler(int sig)
332 received_sigterm = sig;
336 * SIGCHLD handler. This is called whenever a child dies. This will then
337 * reap any zombies left by exited children.
341 main_sigchld_handler(int sig)
343 int save_errno = errno;
347 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
348 (pid < 0 && errno == EINTR))
351 signal(SIGCHLD, main_sigchld_handler);
356 * Signal handler for the alarm after the login grace period has expired.
360 grace_alarm_handler(int sig)
362 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
363 kill(pmonitor->m_pid, SIGALRM);
366 * Try to kill any processes that we have spawned, E.g. authorized
367 * keys command helpers.
369 if (getpgid(0) == getpid()) {
370 signal(SIGTERM, SIG_IGN);
374 BLACKLIST_NOTIFY(BLACKLIST_AUTH_FAIL, "ssh");
376 /* Log error and exit. */
377 sigdie("Timeout before authentication for %s port %d",
378 ssh_remote_ipaddr(active_state), ssh_remote_port(active_state));
382 sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out)
385 int remote_major, remote_minor;
386 char *s, *newline = "\n";
387 char buf[256]; /* Must not be larger than remote_version. */
388 char remote_version[256]; /* Must be at least as big as buf. */
390 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s",
391 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
392 *options.version_addendum == '\0' ? "" : " ",
393 options.version_addendum, newline);
395 /* Send our protocol version identification. */
396 if (atomicio(vwrite, sock_out, server_version_string,
397 strlen(server_version_string))
398 != strlen(server_version_string)) {
399 logit("Could not write ident string to %s port %d",
400 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
404 /* Read other sides version identification. */
405 memset(buf, 0, sizeof(buf));
406 for (i = 0; i < sizeof(buf) - 1; i++) {
407 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
408 logit("Did not receive identification string "
410 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
413 if (buf[i] == '\r') {
415 /* Kludge for F-Secure Macintosh < 1.0.2 */
417 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
421 if (buf[i] == '\n') {
426 buf[sizeof(buf) - 1] = 0;
427 client_version_string = xstrdup(buf);
430 * Check that the versions match. In future this might accept
431 * several versions and set appropriate flags to handle them.
433 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
434 &remote_major, &remote_minor, remote_version) != 3) {
435 s = "Protocol mismatch.\n";
436 (void) atomicio(vwrite, sock_out, s, strlen(s));
437 logit("Bad protocol version identification '%.100s' "
438 "from %s port %d", client_version_string,
439 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
444 debug("Client protocol version %d.%d; client software version %.100s",
445 remote_major, remote_minor, remote_version);
447 ssh->compat = compat_datafellows(remote_version);
449 if ((ssh->compat & SSH_BUG_PROBE) != 0) {
450 logit("probed from %s port %d with %s. Don't panic.",
451 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
452 client_version_string);
455 if ((ssh->compat & SSH_BUG_SCANNER) != 0) {
456 logit("scanned from %s port %d with %s. Don't panic.",
457 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
458 client_version_string);
461 if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
462 logit("Client version \"%.100s\" uses unsafe RSA signature "
463 "scheme; disabling use of RSA keys", remote_version);
465 if ((ssh->compat & SSH_BUG_DERIVEKEY) != 0) {
466 fatal("Client version \"%.100s\" uses unsafe key agreement; "
467 "refusing connection", remote_version);
470 chop(server_version_string);
471 debug("Local version string %.200s", server_version_string);
473 if (remote_major == 2 ||
474 (remote_major == 1 && remote_minor == 99)) {
477 s = "Protocol major versions differ.\n";
478 (void) atomicio(vwrite, sock_out, s, strlen(s));
481 logit("Protocol major versions differ for %s port %d: "
483 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
484 server_version_string, client_version_string);
489 /* Destroy the host and server keys. They will no longer be needed. */
491 destroy_sensitive_data(void)
495 for (i = 0; i < options.num_host_key_files; i++) {
496 if (sensitive_data.host_keys[i]) {
497 key_free(sensitive_data.host_keys[i]);
498 sensitive_data.host_keys[i] = NULL;
500 if (sensitive_data.host_certificates[i]) {
501 key_free(sensitive_data.host_certificates[i]);
502 sensitive_data.host_certificates[i] = NULL;
507 /* Demote private to public keys for network child */
509 demote_sensitive_data(void)
514 for (i = 0; i < options.num_host_key_files; i++) {
515 if (sensitive_data.host_keys[i]) {
516 tmp = key_demote(sensitive_data.host_keys[i]);
517 key_free(sensitive_data.host_keys[i]);
518 sensitive_data.host_keys[i] = tmp;
520 /* Certs do not need demotion */
532 arc4random_stir(); /* noop on recent arc4random() implementations */
533 arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
536 RAND_seed(rnd, sizeof(rnd));
537 /* give libcrypto a chance to notice the PID change */
538 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
539 fatal("%s: RAND_bytes failed", __func__);
542 explicit_bzero(rnd, sizeof(rnd));
546 privsep_preauth_child(void)
550 /* Enable challenge-response authentication for privilege separation */
551 privsep_challenge_enable();
554 /* Cache supported mechanism OIDs for later use */
555 if (options.gss_authentication)
556 ssh_gssapi_prepare_supported_oids();
561 /* Demote the private keys to public keys. */
562 demote_sensitive_data();
564 /* Demote the child */
565 if (getuid() == 0 || geteuid() == 0) {
566 /* Change our root directory */
567 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
568 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
570 if (chdir("/") == -1)
571 fatal("chdir(\"/\"): %s", strerror(errno));
573 /* Drop our privileges */
574 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
575 (u_int)privsep_pw->pw_gid);
576 gidset[0] = privsep_pw->pw_gid;
577 if (setgroups(1, gidset) < 0)
578 fatal("setgroups: %.100s", strerror(errno));
579 permanently_set_uid(privsep_pw);
584 privsep_preauth(Authctxt *authctxt)
588 struct ssh_sandbox *box = NULL;
590 /* Set up unprivileged child process to deal with network data */
591 pmonitor = monitor_init();
592 /* Store a pointer to the kex for later rekeying */
593 pmonitor->m_pkex = &active_state->kex;
595 if (use_privsep == PRIVSEP_ON)
596 box = ssh_sandbox_init(pmonitor);
599 fatal("fork of unprivileged child failed");
600 } else if (pid != 0) {
601 debug2("Network child is on pid %ld", (long)pid);
603 pmonitor->m_pid = pid;
605 r = ssh_get_authentication_socket(&auth_sock);
607 error("Could not get agent socket: %s",
613 ssh_sandbox_parent_preauth(box, pid);
614 monitor_child_preauth(authctxt, pmonitor);
616 /* Wait for the child's exit status */
617 while (waitpid(pid, &status, 0) < 0) {
620 pmonitor->m_pid = -1;
621 fatal("%s: waitpid: %s", __func__, strerror(errno));
623 privsep_is_preauth = 0;
624 pmonitor->m_pid = -1;
625 if (WIFEXITED(status)) {
626 if (WEXITSTATUS(status) != 0)
627 fatal("%s: preauth child exited with status %d",
628 __func__, WEXITSTATUS(status));
629 } else if (WIFSIGNALED(status))
630 fatal("%s: preauth child terminated by signal %d",
631 __func__, WTERMSIG(status));
633 ssh_sandbox_parent_finish(box);
637 close(pmonitor->m_sendfd);
638 close(pmonitor->m_log_recvfd);
640 /* Arrange for logging to be sent to the monitor */
641 set_log_handler(mm_log_handler, pmonitor);
643 privsep_preauth_child();
644 setproctitle("%s", "[net]");
646 ssh_sandbox_child(box);
653 privsep_postauth(Authctxt *authctxt)
655 #ifdef DISABLE_FD_PASSING
658 if (authctxt->pw->pw_uid == 0) {
660 /* File descriptor passing is broken or root login */
665 /* New socket pair */
666 monitor_reinit(pmonitor);
668 pmonitor->m_pid = fork();
669 if (pmonitor->m_pid == -1)
670 fatal("fork of unprivileged child failed");
671 else if (pmonitor->m_pid != 0) {
672 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
673 buffer_clear(&loginmsg);
674 monitor_child_postauth(pmonitor);
682 close(pmonitor->m_sendfd);
683 pmonitor->m_sendfd = -1;
685 /* Demote the private keys to public keys. */
686 demote_sensitive_data();
690 /* Drop privileges */
691 do_setusercontext(authctxt->pw);
694 /* It is safe now to apply the key state */
695 monitor_apply_keystate(pmonitor);
698 * Tell the packet layer that authentication was successful, since
699 * this information is not part of the key state.
701 packet_set_authenticated();
705 list_hostkey_types(void)
714 for (i = 0; i < options.num_host_key_files; i++) {
715 key = sensitive_data.host_keys[i];
717 key = sensitive_data.host_pubkeys[i];
720 /* Check that the key is accepted in HostkeyAlgorithms */
721 if (match_pattern_list(sshkey_ssh_name(key),
722 options.hostkeyalgorithms, 0) != 1) {
723 debug3("%s: %s key not permitted by HostkeyAlgorithms",
724 __func__, sshkey_ssh_name(key));
732 if (buffer_len(&b) > 0)
733 buffer_append(&b, ",", 1);
734 p = key_ssh_name(key);
735 buffer_append(&b, p, strlen(p));
737 /* for RSA we also support SHA2 signatures */
738 if (key->type == KEY_RSA) {
739 p = ",rsa-sha2-512,rsa-sha2-256";
740 buffer_append(&b, p, strlen(p));
744 /* If the private key has a cert peer, then list that too */
745 key = sensitive_data.host_certificates[i];
752 case KEY_ED25519_CERT:
753 if (buffer_len(&b) > 0)
754 buffer_append(&b, ",", 1);
755 p = key_ssh_name(key);
756 buffer_append(&b, p, strlen(p));
760 if ((ret = sshbuf_dup_string(&b)) == NULL)
761 fatal("%s: sshbuf_dup_string failed", __func__);
763 debug("list_hostkey_types: %s", ret);
768 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
773 for (i = 0; i < options.num_host_key_files; i++) {
778 case KEY_ED25519_CERT:
779 key = sensitive_data.host_certificates[i];
782 key = sensitive_data.host_keys[i];
783 if (key == NULL && !need_private)
784 key = sensitive_data.host_pubkeys[i];
787 if (key != NULL && key->type == type &&
788 (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
789 return need_private ?
790 sensitive_data.host_keys[i] : key;
796 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
798 return get_hostkey_by_type(type, nid, 0, ssh);
802 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
804 return get_hostkey_by_type(type, nid, 1, ssh);
808 get_hostkey_by_index(int ind)
810 if (ind < 0 || ind >= options.num_host_key_files)
812 return (sensitive_data.host_keys[ind]);
816 get_hostkey_public_by_index(int ind, struct ssh *ssh)
818 if (ind < 0 || ind >= options.num_host_key_files)
820 return (sensitive_data.host_pubkeys[ind]);
824 get_hostkey_index(Key *key, int compare, struct ssh *ssh)
828 for (i = 0; i < options.num_host_key_files; i++) {
829 if (key_is_cert(key)) {
830 if (key == sensitive_data.host_certificates[i] ||
831 (compare && sensitive_data.host_certificates[i] &&
833 sensitive_data.host_certificates[i])))
836 if (key == sensitive_data.host_keys[i] ||
837 (compare && sensitive_data.host_keys[i] &&
838 sshkey_equal(key, sensitive_data.host_keys[i])))
840 if (key == sensitive_data.host_pubkeys[i] ||
841 (compare && sensitive_data.host_pubkeys[i] &&
842 sshkey_equal(key, sensitive_data.host_pubkeys[i])))
849 /* Inform the client of all hostkeys */
851 notify_hostkeys(struct ssh *ssh)
858 /* Some clients cannot cope with the hostkeys message, skip those. */
859 if (datafellows & SSH_BUG_HOSTKEYS)
862 if ((buf = sshbuf_new()) == NULL)
863 fatal("%s: sshbuf_new", __func__);
864 for (i = nkeys = 0; i < options.num_host_key_files; i++) {
865 key = get_hostkey_public_by_index(i, ssh);
866 if (key == NULL || key->type == KEY_UNSPEC ||
869 fp = sshkey_fingerprint(key, options.fingerprint_hash,
871 debug3("%s: key %d: %s %s", __func__, i,
872 sshkey_ssh_name(key), fp);
875 packet_start(SSH2_MSG_GLOBAL_REQUEST);
876 packet_put_cstring("hostkeys-00@openssh.com");
877 packet_put_char(0); /* want-reply */
880 if ((r = sshkey_putb(key, buf)) != 0)
881 fatal("%s: couldn't put hostkey %d: %s",
882 __func__, i, ssh_err(r));
883 packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
886 debug3("%s: sent %d hostkeys", __func__, nkeys);
888 fatal("%s: no hostkeys", __func__);
894 * returns 1 if connection should be dropped, 0 otherwise.
895 * dropping starts at connection #max_startups_begin with a probability
896 * of (max_startups_rate/100). the probability increases linearly until
897 * all connections are dropped for startups > max_startups
900 drop_connection(int startups)
904 if (startups < options.max_startups_begin)
906 if (startups >= options.max_startups)
908 if (options.max_startups_rate == 100)
911 p = 100 - options.max_startups_rate;
912 p *= startups - options.max_startups_begin;
913 p /= options.max_startups - options.max_startups_begin;
914 p += options.max_startups_rate;
915 r = arc4random_uniform(100);
917 debug("drop_connection: p %d, r %d", p, r);
918 return (r < p) ? 1 : 0;
924 if (options.version_addendum && *options.version_addendum != '\0')
925 fprintf(stderr, "%s %s, %s\n",
927 options.version_addendum, OPENSSL_VERSION);
929 fprintf(stderr, "%s, %s\n",
930 SSH_RELEASE, OPENSSL_VERSION);
932 "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
933 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
934 " [-h host_key_file] [-o option] [-p port] [-u len]\n"
940 send_rexec_state(int fd, struct sshbuf *conf)
945 debug3("%s: entering fd = %d config len %zu", __func__, fd,
949 * Protocol from reexec master to child:
950 * string configuration
951 * string rngseed (only if OpenSSL is not self-seeded)
953 if ((m = sshbuf_new()) == NULL)
954 fatal("%s: sshbuf_new failed", __func__);
955 if ((r = sshbuf_put_stringb(m, conf)) != 0)
956 fatal("%s: buffer error: %s", __func__, ssh_err(r));
958 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
959 rexec_send_rng_seed(m);
962 if (ssh_msg_send(fd, 0, m) == -1)
963 fatal("%s: ssh_msg_send failed", __func__);
967 debug3("%s: done", __func__);
971 recv_rexec_state(int fd, Buffer *conf)
977 debug3("%s: entering fd = %d", __func__, fd);
981 if (ssh_msg_recv(fd, &m) == -1)
982 fatal("%s: ssh_msg_recv failed", __func__);
983 if (buffer_get_char(&m) != 0)
984 fatal("%s: rexec version mismatch", __func__);
986 cp = buffer_get_string(&m, &len);
988 buffer_append(conf, cp, len);
991 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
992 rexec_recv_rng_seed(&m);
997 debug3("%s: done", __func__);
1000 /* Accept a connection from inetd */
1002 server_accept_inetd(int *sock_in, int *sock_out)
1008 close(REEXEC_CONFIG_PASS_FD);
1009 *sock_in = *sock_out = dup(STDIN_FILENO);
1011 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1012 close(REEXEC_STARTUP_PIPE_FD);
1015 *sock_in = dup(STDIN_FILENO);
1016 *sock_out = dup(STDOUT_FILENO);
1019 * We intentionally do not close the descriptors 0, 1, and 2
1020 * as our code for setting the descriptors won't work if
1021 * ttyfd happens to be one of those.
1023 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1024 dup2(fd, STDIN_FILENO);
1025 dup2(fd, STDOUT_FILENO);
1027 dup2(fd, STDERR_FILENO);
1028 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1031 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1035 * Listen for TCP connections
1040 int ret, listen_sock, on = 1;
1041 struct addrinfo *ai;
1042 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1046 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1047 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1049 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1050 fatal("Too many listen sockets. "
1051 "Enlarge MAX_LISTEN_SOCKS");
1052 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1053 ntop, sizeof(ntop), strport, sizeof(strport),
1054 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1055 error("getnameinfo failed: %.100s",
1056 ssh_gai_strerror(ret));
1059 /* Create socket for listening. */
1060 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1062 if (listen_sock < 0) {
1063 /* kernel may not support ipv6 */
1064 verbose("socket: %.100s", strerror(errno));
1067 if (set_nonblock(listen_sock) == -1) {
1072 * Set socket options.
1073 * Allow local port reuse in TIME_WAIT.
1075 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1076 &on, sizeof(on)) == -1)
1077 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1079 /* Only communicate in IPv6 over AF_INET6 sockets. */
1080 if (ai->ai_family == AF_INET6)
1081 sock_set_v6only(listen_sock);
1083 debug("Bind to port %s on %s.", strport, ntop);
1085 len = sizeof(socksize);
1086 getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
1087 debug("Server TCP RWIN socket size: %d", socksize);
1089 /* Bind the socket to the desired port. */
1090 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1091 error("Bind to port %s on %s failed: %.200s.",
1092 strport, ntop, strerror(errno));
1096 listen_socks[num_listen_socks] = listen_sock;
1099 /* Start listening on the port. */
1100 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1101 fatal("listen on [%s]:%s: %.100s",
1102 ntop, strport, strerror(errno));
1103 logit("Server listening on %s port %s.", ntop, strport);
1105 freeaddrinfo(options.listen_addrs);
1107 if (!num_listen_socks)
1108 fatal("Cannot bind any address.");
1112 * The main TCP accept loop. Note that, for the non-debug case, returns
1113 * from this function are in a forked subprocess.
1116 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1119 int i, j, ret, maxfd;
1121 int startup_p[2] = { -1 , -1 };
1122 struct sockaddr_storage from;
1127 /* setup fd set for accept */
1130 for (i = 0; i < num_listen_socks; i++)
1131 if (listen_socks[i] > maxfd)
1132 maxfd = listen_socks[i];
1133 /* pipes connected to unauthenticated childs */
1134 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1135 for (i = 0; i < options.max_startups; i++)
1136 startup_pipes[i] = -1;
1139 * Stay listening for connections until the system crashes or
1140 * the daemon is killed with a signal.
1143 if (received_sighup)
1146 fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1149 for (i = 0; i < num_listen_socks; i++)
1150 FD_SET(listen_socks[i], fdset);
1151 for (i = 0; i < options.max_startups; i++)
1152 if (startup_pipes[i] != -1)
1153 FD_SET(startup_pipes[i], fdset);
1155 /* Wait in select until there is a connection. */
1156 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1157 if (ret < 0 && errno != EINTR)
1158 error("select: %.100s", strerror(errno));
1159 if (received_sigterm) {
1160 logit("Received signal %d; terminating.",
1161 (int) received_sigterm);
1162 close_listen_socks();
1163 if (options.pid_file != NULL)
1164 unlink(options.pid_file);
1165 exit(received_sigterm == SIGTERM ? 0 : 255);
1170 for (i = 0; i < options.max_startups; i++)
1171 if (startup_pipes[i] != -1 &&
1172 FD_ISSET(startup_pipes[i], fdset)) {
1174 * the read end of the pipe is ready
1175 * if the child has closed the pipe
1176 * after successful authentication
1177 * or if the child has died
1179 close(startup_pipes[i]);
1180 startup_pipes[i] = -1;
1183 for (i = 0; i < num_listen_socks; i++) {
1184 if (!FD_ISSET(listen_socks[i], fdset))
1186 fromlen = sizeof(from);
1187 *newsock = accept(listen_socks[i],
1188 (struct sockaddr *)&from, &fromlen);
1190 if (errno != EINTR && errno != EWOULDBLOCK &&
1191 errno != ECONNABORTED && errno != EAGAIN)
1192 error("accept: %.100s",
1194 if (errno == EMFILE || errno == ENFILE)
1198 if (unset_nonblock(*newsock) == -1) {
1202 if (drop_connection(startups) == 1) {
1203 char *laddr = get_local_ipaddr(*newsock);
1204 char *raddr = get_peer_ipaddr(*newsock);
1206 verbose("drop connection #%d from [%s]:%d "
1207 "on [%s]:%d past MaxStartups", startups,
1208 raddr, get_peer_port(*newsock),
1209 laddr, get_local_port(*newsock));
1215 if (pipe(startup_p) == -1) {
1220 if (rexec_flag && socketpair(AF_UNIX,
1221 SOCK_STREAM, 0, config_s) == -1) {
1222 error("reexec socketpair: %s",
1225 close(startup_p[0]);
1226 close(startup_p[1]);
1230 for (j = 0; j < options.max_startups; j++)
1231 if (startup_pipes[j] == -1) {
1232 startup_pipes[j] = startup_p[0];
1233 if (maxfd < startup_p[0])
1234 maxfd = startup_p[0];
1240 * Got connection. Fork a child to handle it, unless
1241 * we are in debugging mode.
1245 * In debugging mode. Close the listening
1246 * socket, and start processing the
1247 * connection without forking.
1249 debug("Server will not fork when running in debugging mode.");
1250 close_listen_socks();
1251 *sock_in = *newsock;
1252 *sock_out = *newsock;
1253 close(startup_p[0]);
1254 close(startup_p[1]);
1258 send_rexec_state(config_s[0],
1266 * Normal production daemon. Fork, and have
1267 * the child process the connection. The
1268 * parent continues listening.
1270 platform_pre_fork();
1271 if ((pid = fork()) == 0) {
1273 * Child. Close the listening and
1274 * max_startup sockets. Start using
1275 * the accepted socket. Reinitialize
1276 * logging (since our pid has changed).
1277 * We break out of the loop to handle
1280 platform_post_fork_child();
1281 startup_pipe = startup_p[1];
1282 close_startup_pipes();
1283 close_listen_socks();
1284 *sock_in = *newsock;
1285 *sock_out = *newsock;
1286 log_init(__progname,
1288 options.log_facility,
1295 /* Parent. Stay in the loop. */
1296 platform_post_fork_parent(pid);
1298 error("fork: %.100s", strerror(errno));
1300 debug("Forked child %ld.", (long)pid);
1302 close(startup_p[1]);
1305 send_rexec_state(config_s[0], &cfg);
1312 * Ensure that our random state differs
1313 * from that of the child
1316 arc4random_buf(rnd, sizeof(rnd));
1318 RAND_seed(rnd, sizeof(rnd));
1319 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1320 fatal("%s: RAND_bytes failed", __func__);
1322 explicit_bzero(rnd, sizeof(rnd));
1325 /* child process check (or debug mode) */
1326 if (num_listen_socks < 0)
1332 * If IP options are supported, make sure there are none (log and
1333 * return an error if any are found). Basically we are worried about
1334 * source routing; it can be used to pretend you are somebody
1335 * (ip-address) you are not. That itself may be "almost acceptable"
1336 * under certain circumstances, but rhosts autentication is useless
1337 * if source routing is accepted. Notice also that if we just dropped
1338 * source routing here, the other side could use IP spoofing to do
1339 * rest of the interaction and could still bypass security. So we
1340 * exit here if we detect any IP options.
1343 check_ip_options(struct ssh *ssh)
1346 int sock_in = ssh_packet_get_connection_in(ssh);
1347 struct sockaddr_storage from;
1349 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1350 char text[sizeof(opts) * 3 + 1];
1352 memset(&from, 0, sizeof(from));
1353 if (getpeername(sock_in, (struct sockaddr *)&from,
1356 if (from.ss_family != AF_INET)
1358 /* XXX IPv6 options? */
1360 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1361 &option_size) >= 0 && option_size != 0) {
1363 for (i = 0; i < option_size; i++)
1364 snprintf(text + i*3, sizeof(text) - i*3,
1366 fatal("Connection from %.100s port %d with IP opts: %.800s",
1367 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1370 #endif /* IP_OPTIONS */
1374 * Main program for the daemon.
1377 main(int ac, char **av)
1379 struct ssh *ssh = NULL;
1380 extern char *optarg;
1382 int r, opt, i, j, on = 1, already_daemon;
1383 int sock_in = -1, sock_out = -1, newsock = -1;
1384 const char *remote_ip;
1386 char *fp, *line, *laddr, *logfile = NULL;
1387 int config_s[2] = { -1 , -1 };
1389 u_int64_t ibytes, obytes;
1395 struct connection_info *connection_info = get_connection_info(0, 0);
1397 ssh_malloc_init(); /* must be called before any mallocs */
1399 #ifdef HAVE_SECUREWARE
1400 (void)set_auth_parameters(ac, av);
1402 __progname = ssh_get_progname(av[0]);
1404 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1407 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1408 for (i = 0; i < ac; i++)
1409 saved_argv[i] = xstrdup(av[i]);
1410 saved_argv[i] = NULL;
1412 #ifndef HAVE_SETPROCTITLE
1413 /* Prepare for later setproctitle emulation */
1414 compat_init_setproctitle(ac, av);
1418 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1419 debug("setgroups(): %.200s", strerror(errno));
1421 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1424 /* Initialize configuration options to their default values. */
1425 initialize_server_options(&options);
1427 /* Parse command-line arguments. */
1428 while ((opt = getopt(ac, av,
1429 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1432 options.address_family = AF_INET;
1435 options.address_family = AF_INET6;
1438 config_file_name = optarg;
1441 if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1442 fprintf(stderr, "too many host certificates.\n");
1445 options.host_cert_files[options.num_host_cert_files++] =
1446 derelativise_path(optarg);
1449 if (debug_flag == 0) {
1451 options.log_level = SYSLOG_LEVEL_DEBUG1;
1452 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1453 options.log_level++;
1478 options.log_level = SYSLOG_LEVEL_QUIET;
1481 /* protocol 1, ignored */
1484 options.ports_from_cmdline = 1;
1485 if (options.num_ports >= MAX_PORTS) {
1486 fprintf(stderr, "too many ports.\n");
1489 options.ports[options.num_ports++] = a2port(optarg);
1490 if (options.ports[options.num_ports-1] <= 0) {
1491 fprintf(stderr, "Bad port number.\n");
1496 if ((options.login_grace_time = convtime(optarg)) == -1) {
1497 fprintf(stderr, "Invalid login grace time.\n");
1502 /* protocol 1, ignored */
1505 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1506 fprintf(stderr, "too many host keys.\n");
1509 options.host_key_files[options.num_host_key_files++] =
1510 derelativise_path(optarg);
1519 if (parse_server_match_testspec(connection_info,
1524 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1525 if (utmp_len > HOST_NAME_MAX+1) {
1526 fprintf(stderr, "Invalid utmp length.\n");
1531 line = xstrdup(optarg);
1532 if (process_server_config_line(&options, line,
1533 "command-line", 0, NULL, NULL) != 0)
1543 if (rexeced_flag || inetd_flag)
1545 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1546 fatal("sshd re-exec requires execution with an absolute path");
1548 closefrom(REEXEC_MIN_FREE_FD);
1550 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1553 OpenSSL_add_all_algorithms();
1556 /* If requested, redirect the logs to the specified logfile. */
1557 if (logfile != NULL)
1558 log_redirect_stderr_to(logfile);
1560 * Force logging to stderr until we have loaded the private host
1561 * key (unless started from inetd)
1563 log_init(__progname,
1564 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1565 SYSLOG_LEVEL_INFO : options.log_level,
1566 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1567 SYSLOG_FACILITY_AUTH : options.log_facility,
1568 log_stderr || !inetd_flag);
1571 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1572 * root's environment
1574 if (getenv("KRB5CCNAME") != NULL)
1575 (void) unsetenv("KRB5CCNAME");
1578 /* Cray can define user privs drop all privs now!
1579 * Not needed on PRIV_SU systems!
1584 sensitive_data.have_ssh2_key = 0;
1587 * If we're doing an extended config test, make sure we have all of
1588 * the parameters we need. If we're not doing an extended test,
1589 * do not silently ignore connection test params.
1591 if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1592 fatal("user, host and addr are all required when testing "
1594 if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1595 fatal("Config test connection parameter (-C) provided without "
1598 /* Fetch our configuration */
1601 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1602 else if (strcasecmp(config_file_name, "none") != 0)
1603 load_server_config(config_file_name, &cfg);
1605 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1610 /* Fill in default values for those options not explicitly set. */
1611 fill_default_server_options(&options);
1613 /* challenge-response is implemented via keyboard interactive */
1614 if (options.challenge_response_authentication)
1615 options.kbd_interactive_authentication = 1;
1617 /* Check that options are sensible */
1618 if (options.authorized_keys_command_user == NULL &&
1619 (options.authorized_keys_command != NULL &&
1620 strcasecmp(options.authorized_keys_command, "none") != 0))
1621 fatal("AuthorizedKeysCommand set without "
1622 "AuthorizedKeysCommandUser");
1623 if (options.authorized_principals_command_user == NULL &&
1624 (options.authorized_principals_command != NULL &&
1625 strcasecmp(options.authorized_principals_command, "none") != 0))
1626 fatal("AuthorizedPrincipalsCommand set without "
1627 "AuthorizedPrincipalsCommandUser");
1630 * Check whether there is any path through configured auth methods.
1631 * Unfortunately it is not possible to verify this generally before
1632 * daemonisation in the presence of Match block, but this catches
1633 * and warns for trivial misconfigurations that could break login.
1635 if (options.num_auth_methods != 0) {
1636 for (n = 0; n < options.num_auth_methods; n++) {
1637 if (auth2_methods_valid(options.auth_methods[n],
1641 if (n >= options.num_auth_methods)
1642 fatal("AuthenticationMethods cannot be satisfied by "
1643 "enabled authentication methods");
1646 /* set default channel AF */
1647 channel_set_af(options.address_family);
1649 /* Check that there are no remaining arguments. */
1651 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1655 debug("sshd version %s, %s", SSH_VERSION,
1657 SSLeay_version(SSLEAY_VERSION)
1663 /* Store privilege separation user for later use if required. */
1664 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1665 if (use_privsep || options.kerberos_authentication)
1666 fatal("Privilege separation user %s does not exist",
1669 explicit_bzero(privsep_pw->pw_passwd,
1670 strlen(privsep_pw->pw_passwd));
1671 privsep_pw = pwcopy(privsep_pw);
1672 free(privsep_pw->pw_passwd);
1673 privsep_pw->pw_passwd = xstrdup("*");
1677 /* load host keys */
1678 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1680 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1683 if (options.host_key_agent) {
1684 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1685 setenv(SSH_AUTHSOCKET_ENV_NAME,
1686 options.host_key_agent, 1);
1687 if ((r = ssh_get_authentication_socket(NULL)) == 0)
1690 error("Could not connect to agent \"%s\": %s",
1691 options.host_key_agent, ssh_err(r));
1694 for (i = 0; i < options.num_host_key_files; i++) {
1695 if (options.host_key_files[i] == NULL)
1697 key = key_load_private(options.host_key_files[i], "", NULL);
1698 pubkey = key_load_public(options.host_key_files[i], NULL);
1699 if (pubkey == NULL && key != NULL)
1700 pubkey = key_demote(key);
1701 sensitive_data.host_keys[i] = key;
1702 sensitive_data.host_pubkeys[i] = pubkey;
1704 if (key == NULL && pubkey != NULL && have_agent) {
1705 debug("will rely on agent for hostkey %s",
1706 options.host_key_files[i]);
1707 keytype = pubkey->type;
1708 } else if (key != NULL) {
1709 keytype = key->type;
1711 error("Could not load host key: %s",
1712 options.host_key_files[i]);
1713 sensitive_data.host_keys[i] = NULL;
1714 sensitive_data.host_pubkeys[i] = NULL;
1723 if (have_agent || key != NULL)
1724 sensitive_data.have_ssh2_key = 1;
1727 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1728 SSH_FP_DEFAULT)) == NULL)
1729 fatal("sshkey_fingerprint failed");
1730 debug("%s host key #%d: %s %s",
1731 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1734 if (!sensitive_data.have_ssh2_key) {
1735 logit("sshd: no hostkeys available -- exiting.");
1740 * Load certificates. They are stored in an array at identical
1741 * indices to the public keys that they relate to.
1743 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1745 for (i = 0; i < options.num_host_key_files; i++)
1746 sensitive_data.host_certificates[i] = NULL;
1748 for (i = 0; i < options.num_host_cert_files; i++) {
1749 if (options.host_cert_files[i] == NULL)
1751 key = key_load_public(options.host_cert_files[i], NULL);
1753 error("Could not load host certificate: %s",
1754 options.host_cert_files[i]);
1757 if (!key_is_cert(key)) {
1758 error("Certificate file is not a certificate: %s",
1759 options.host_cert_files[i]);
1763 /* Find matching private key */
1764 for (j = 0; j < options.num_host_key_files; j++) {
1765 if (key_equal_public(key,
1766 sensitive_data.host_keys[j])) {
1767 sensitive_data.host_certificates[j] = key;
1771 if (j >= options.num_host_key_files) {
1772 error("No matching private key for certificate: %s",
1773 options.host_cert_files[i]);
1777 sensitive_data.host_certificates[j] = key;
1778 debug("host certificate: #%d type %d %s", j, key->type,
1785 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1786 (S_ISDIR(st.st_mode) == 0))
1787 fatal("Missing privilege separation directory: %s",
1788 _PATH_PRIVSEP_CHROOT_DIR);
1791 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1792 (st.st_uid != getuid () ||
1793 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1795 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1797 fatal("%s must be owned by root and not group or "
1798 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1801 if (test_flag > 1) {
1802 if (server_match_spec_complete(connection_info) == 1)
1803 parse_server_match_config(&options, connection_info);
1804 dump_config(&options);
1807 /* Configuration looks good, so exit if in test mode. */
1812 * Clear out any supplemental groups we may have inherited. This
1813 * prevents inadvertent creation of files with bad modes (in the
1814 * portable version at least, it's certainly possible for PAM
1815 * to create a file, and we can't control the code in every
1816 * module which might be used).
1818 if (setgroups(0, NULL) < 0)
1819 debug("setgroups() failed: %.200s", strerror(errno));
1822 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1823 for (i = 0; i < rexec_argc; i++) {
1824 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1825 rexec_argv[i] = saved_argv[i];
1827 rexec_argv[rexec_argc] = "-R";
1828 rexec_argv[rexec_argc + 1] = NULL;
1831 /* Ensure that umask disallows at least group and world write */
1832 new_umask = umask(0077) | 0022;
1833 (void) umask(new_umask);
1835 /* Initialize the log (it is reinitialized below in case we forked). */
1836 if (debug_flag && (!inetd_flag || rexeced_flag))
1838 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1841 * If not in debugging mode, not started from inetd and not already
1842 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1843 * terminal, and fork. The original process exits.
1845 already_daemon = daemonized();
1846 if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1848 if (daemon(0, 0) < 0)
1849 fatal("daemon() failed: %.200s", strerror(errno));
1851 disconnect_controlling_tty();
1853 /* Reinitialize the log (because of the fork above). */
1854 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1856 /* Avoid killing the process in high-pressure swapping environments. */
1857 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
1858 debug("madvise(): %.200s", strerror(errno));
1860 /* Chdir to the root directory so that the current disk can be
1861 unmounted if desired. */
1862 if (chdir("/") == -1)
1863 error("chdir(\"/\"): %s", strerror(errno));
1865 /* ignore SIGPIPE */
1866 signal(SIGPIPE, SIG_IGN);
1868 /* Get a connection, either from inetd or a listening TCP socket */
1870 server_accept_inetd(&sock_in, &sock_out);
1872 platform_pre_listen();
1875 signal(SIGHUP, sighup_handler);
1876 signal(SIGCHLD, main_sigchld_handler);
1877 signal(SIGTERM, sigterm_handler);
1878 signal(SIGQUIT, sigterm_handler);
1881 * Write out the pid file after the sigterm handler
1882 * is setup and the listen sockets are bound
1884 if (options.pid_file != NULL && !debug_flag) {
1885 FILE *f = fopen(options.pid_file, "w");
1888 error("Couldn't create pid file \"%s\": %s",
1889 options.pid_file, strerror(errno));
1891 fprintf(f, "%ld\n", (long) getpid());
1896 /* Accept a connection and return in a forked child */
1897 server_accept_loop(&sock_in, &sock_out,
1898 &newsock, config_s);
1901 /* This is the child processing a new connection. */
1902 setproctitle("%s", "[accepted]");
1905 * Create a new session and process group since the 4.4BSD
1906 * setlogin() affects the entire process group. We don't
1907 * want the child to be able to affect the parent.
1909 #if !defined(SSHD_ACQUIRES_CTTY)
1911 * If setsid is called, on some platforms sshd will later acquire a
1912 * controlling terminal which will result in "could not set
1913 * controlling tty" errors.
1915 if (!debug_flag && !inetd_flag && setsid() < 0)
1916 error("setsid: %.100s", strerror(errno));
1922 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1923 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1924 dup2(newsock, STDIN_FILENO);
1925 dup2(STDIN_FILENO, STDOUT_FILENO);
1926 if (startup_pipe == -1)
1927 close(REEXEC_STARTUP_PIPE_FD);
1928 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
1929 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1930 close(startup_pipe);
1931 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1934 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1937 execv(rexec_argv[0], rexec_argv);
1939 /* Reexec has failed, fall back and continue */
1940 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1941 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1942 log_init(__progname, options.log_level,
1943 options.log_facility, log_stderr);
1946 close(REEXEC_CONFIG_PASS_FD);
1947 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1948 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1949 dup2(fd, STDIN_FILENO);
1950 dup2(fd, STDOUT_FILENO);
1951 if (fd > STDERR_FILENO)
1954 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1955 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1958 /* Executed child processes don't need these. */
1959 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1960 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1963 * Disable the key regeneration alarm. We will not regenerate the
1964 * key since we are no longer in a position to give it to anyone. We
1965 * will not restart on SIGHUP since it no longer makes sense.
1968 signal(SIGALRM, SIG_DFL);
1969 signal(SIGHUP, SIG_DFL);
1970 signal(SIGTERM, SIG_DFL);
1971 signal(SIGQUIT, SIG_DFL);
1972 signal(SIGCHLD, SIG_DFL);
1973 signal(SIGINT, SIG_DFL);
1977 * Initialize the resolver. This may not happen automatically
1978 * before privsep chroot().
1980 if ((_res.options & RES_INIT) == 0) {
1981 debug("res_init()");
1986 * Force GSS-API to parse its configuration and load any
1987 * mechanism plugins.
1991 OM_uint32 minor_status;
1992 gss_indicate_mechs(&minor_status, &mechs);
1993 gss_release_oid_set(&minor_status, &mechs);
1999 * Register our connection. This turns encryption off because we do
2002 packet_set_connection(sock_in, sock_out);
2003 packet_set_server();
2004 ssh = active_state; /* XXX */
2005 check_ip_options(ssh);
2007 /* Set SO_KEEPALIVE if requested. */
2008 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2009 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2010 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2012 if ((remote_port = ssh_remote_port(ssh)) < 0) {
2013 debug("ssh_remote_port failed");
2018 * The rest of the code depends on the fact that
2019 * ssh_remote_ipaddr() caches the remote ip, even if
2020 * the socket goes away.
2022 remote_ip = ssh_remote_ipaddr(ssh);
2024 #ifdef SSH_AUDIT_EVENTS
2025 audit_connection_from(remote_ip, remote_port);
2028 allow_severity = options.log_facility|LOG_INFO;
2029 deny_severity = options.log_facility|LOG_WARNING;
2030 /* Check whether logins are denied from this host. */
2031 if (packet_connection_is_on_socket()) {
2032 struct request_info req;
2034 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
2037 if (!hosts_access(&req)) {
2038 debug("Connection refused by tcp wrapper");
2041 fatal("libwrap refuse returns");
2044 #endif /* LIBWRAP */
2046 /* Log the connection. */
2047 laddr = get_local_ipaddr(sock_in);
2048 verbose("Connection from %s port %d on %s port %d",
2049 remote_ip, remote_port, laddr, ssh_local_port(ssh));
2053 * We don't want to listen forever unless the other side
2054 * successfully authenticates itself. So we set up an alarm which is
2055 * cleared after successful authentication. A limit of zero
2056 * indicates no limit. Note that we don't set the alarm in debugging
2057 * mode; it is just annoying to have the server exit just when you
2058 * are about to discover the bug.
2060 signal(SIGALRM, grace_alarm_handler);
2062 alarm(options.login_grace_time);
2064 sshd_exchange_identification(ssh, sock_in, sock_out);
2065 packet_set_nonblocking();
2067 /* allocate authentication context */
2068 authctxt = xcalloc(1, sizeof(*authctxt));
2070 authctxt->loginmsg = &loginmsg;
2072 /* XXX global for cleanup, access from other modules */
2073 the_authctxt = authctxt;
2075 /* prepare buffer to collect messages to display to user after login */
2076 buffer_init(&loginmsg);
2082 if (privsep_preauth(authctxt) == 1)
2084 } else if (have_agent) {
2085 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2086 error("Unable to get agent socket: %s", ssh_err(r));
2091 /* perform the key exchange */
2092 /* authenticate user and start session */
2094 do_authentication2(authctxt);
2097 * If we use privilege separation, the unprivileged child transfers
2098 * the current keystate and exits
2101 mm_send_keystate(pmonitor);
2107 * Cancel the alarm we set to limit the time taken for
2111 signal(SIGALRM, SIG_DFL);
2112 authctxt->authenticated = 1;
2113 if (startup_pipe != -1) {
2114 close(startup_pipe);
2118 #ifdef SSH_AUDIT_EVENTS
2119 audit_event(SSH_AUTH_SUCCESS);
2123 if (options.gss_authentication) {
2124 temporarily_use_uid(authctxt->pw);
2125 ssh_gssapi_storecreds();
2130 if (options.use_pam) {
2137 * In privilege separation, we fork another child and prepare
2138 * file descriptor passing.
2141 privsep_postauth(authctxt);
2142 /* the monitor process [priv] will not return */
2145 packet_set_timeout(options.client_alive_interval,
2146 options.client_alive_count_max);
2148 /* Try to send all our hostkeys to the client */
2149 notify_hostkeys(active_state);
2151 /* Start session. */
2152 do_authenticated(authctxt);
2154 /* The connection has been terminated. */
2155 packet_get_bytes(&ibytes, &obytes);
2156 verbose("Transferred: sent %llu, received %llu bytes",
2157 (unsigned long long)obytes, (unsigned long long)ibytes);
2159 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2162 if (options.use_pam)
2164 #endif /* USE_PAM */
2166 #ifdef SSH_AUDIT_EVENTS
2167 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2179 sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen,
2180 const u_char *data, size_t dlen, const char *alg, u_int flag)
2183 u_int xxx_slen, xxx_dlen = dlen;
2186 if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen,
2188 fatal("%s: key_sign failed", __func__);
2191 } else if (use_privsep) {
2192 if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen,
2194 fatal("%s: pubkey_sign failed", __func__);
2198 if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen,
2199 data, dlen, alg, datafellows)) != 0)
2200 fatal("%s: ssh_agent_sign failed: %s",
2201 __func__, ssh_err(r));
2206 /* SSH2 key exchange */
2210 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2214 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2215 options.kex_algorithms);
2216 myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
2218 myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
2220 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2221 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2223 if (options.compression == COMP_NONE) {
2224 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2225 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2228 if (options.rekey_limit || options.rekey_interval)
2229 packet_set_rekey_limits(options.rekey_limit,
2230 (time_t)options.rekey_interval);
2232 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2233 list_hostkey_types());
2235 /* start key exchange */
2236 if ((r = kex_setup(active_state, myproposal)) != 0)
2237 fatal("kex_setup: %s", ssh_err(r));
2238 kex = active_state->kex;
2240 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2241 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2242 kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
2243 kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
2244 kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
2245 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2246 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2247 # ifdef OPENSSL_HAS_ECC
2248 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2251 kex->kex[KEX_C25519_SHA256] = kexc25519_server;
2253 kex->client_version_string=client_version_string;
2254 kex->server_version_string=server_version_string;
2255 kex->load_host_public_key=&get_hostkey_public_by_type;
2256 kex->load_host_private_key=&get_hostkey_private_by_type;
2257 kex->host_key_index=&get_hostkey_index;
2258 kex->sign = sshd_hostkey_sign;
2260 dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
2262 session_id2 = kex->session_id;
2263 session_id2_len = kex->session_id_len;
2266 /* send 1st encrypted/maced/compressed message */
2267 packet_start(SSH2_MSG_IGNORE);
2268 packet_put_cstring("markus");
2270 packet_write_wait();
2275 /* server specific fatal cleanup */
2280 do_cleanup(the_authctxt);
2281 if (use_privsep && privsep_is_preauth &&
2282 pmonitor != NULL && pmonitor->m_pid > 1) {
2283 debug("Killing privsep child %d", pmonitor->m_pid);
2284 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2286 error("%s: kill(%d): %s", __func__,
2287 pmonitor->m_pid, strerror(errno));
2290 #ifdef SSH_AUDIT_EVENTS
2291 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2292 if (!use_privsep || mm_is_monitor())
2293 audit_event(SSH_CONNECTION_ABANDON);