1 /* $OpenBSD: sshd.c,v 1.506 2018/03/03 03:15:51 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This program is the ssh daemon. It listens for connections from clients,
7 * and performs authentication, executes use commands or shell, and forwards
8 * information to/from the application to the user client over an encrypted
9 * connection. This can also handle forwarding of X11, TCP/IP, and
10 * authentication agent connections.
12 * As far as I am concerned, the code I have written for this software
13 * can be used freely for any purpose. Any derived versions of this
14 * software must be clearly marked as such, and if the derived work is
15 * incompatible with the protocol description in the RFC file, it must be
16 * called by a name other than "ssh" or "Secure Shell".
18 * SSH2 implementation:
19 * Privilege Separation:
21 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
22 * Copyright (c) 2002 Niels Provos. All rights reserved.
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
27 * 1. Redistributions of source code must retain the above copyright
28 * notice, this list of conditions and the following disclaimer.
29 * 2. Redistributions in binary form must reproduce the above copyright
30 * notice, this list of conditions and the following disclaimer in the
31 * documentation and/or other materials provided with the distribution.
33 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47 #include <sys/types.h>
48 #include <sys/ioctl.h>
49 #include <sys/socket.h>
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
53 #ifdef HAVE_SYS_TIME_H
54 # include <sys/time.h>
56 #include "openbsd-compat/sys-tree.h"
57 #include "openbsd-compat/sys-queue.h"
77 #include <openssl/dh.h>
78 #include <openssl/bn.h>
79 #include <openssl/rand.h>
80 #include "openbsd-compat/openssl-compat.h"
83 #ifdef HAVE_SECUREWARE
84 #include <sys/security.h>
104 #include "myproposal.h"
105 #include "authfile.h"
106 #include "pathnames.h"
107 #include "atomicio.h"
108 #include "canohost.h"
109 #include "hostfile.h"
113 #include "dispatch.h"
114 #include "channels.h"
120 #include "monitor_wrap.h"
121 #include "ssh-sandbox.h"
122 #include "auth-options.h"
127 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
128 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
129 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
130 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
132 extern char *__progname;
134 /* Server configuration options. */
135 ServerOptions options;
137 /* Name of the server configuration file. */
138 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
141 * Debug mode flag. This can be set on the command line. If debug
142 * mode is enabled, extra debugging output will be sent to the system
143 * log, the daemon will not go to background, and will exit after processing
144 * the first connection.
149 * Indicating that the daemon should only test the configuration and keys.
150 * If test_flag > 1 ("-T" flag), then sshd will also dump the effective
151 * configuration, optionally using connection information provided by the
156 /* Flag indicating that the daemon is being started from inetd. */
159 /* Flag indicating that sshd should not detach and become a daemon. */
160 int no_daemon_flag = 0;
162 /* debug goes to stderr unless inetd_flag is set */
165 /* Saved arguments to main(). */
170 int rexeced_flag = 0;
176 * The sockets that the server is listening; this is used in the SIGHUP
179 #define MAX_LISTEN_SOCKS 16
180 int listen_socks[MAX_LISTEN_SOCKS];
181 int num_listen_socks = 0;
184 * the client's version string, passed by sshd2 in compat mode. if != NULL,
185 * sshd will skip the version-number exchange
187 char *client_version_string = NULL;
188 char *server_version_string = NULL;
190 /* Daemon's agent connection */
195 * Any really sensitive data in the application is contained in this
196 * structure. The idea is that this structure could be locked into memory so
197 * that the pages do not get written into swap. However, there are some
198 * problems. The private key contains BIGNUMs, and we do not (in principle)
199 * have access to the internals of them, and locking just the structure is
200 * not very useful. Currently, memory locking is not implemented.
203 struct sshkey **host_keys; /* all private host keys */
204 struct sshkey **host_pubkeys; /* all public host keys */
205 struct sshkey **host_certificates; /* all public host certificates */
209 /* This is set to true when a signal is received. */
210 static volatile sig_atomic_t received_sighup = 0;
211 static volatile sig_atomic_t received_sigterm = 0;
213 /* session identifier, used by RSA-auth */
214 u_char session_id[16];
217 u_char *session_id2 = NULL;
218 u_int session_id2_len = 0;
220 /* record remote hostname or ip */
221 u_int utmp_len = HOST_NAME_MAX+1;
223 /* options.max_startup sized array of fd ints */
224 int *startup_pipes = NULL;
225 int startup_pipe; /* in child */
227 /* variables used for privilege separation */
228 int use_privsep = -1;
229 struct monitor *pmonitor = NULL;
230 int privsep_is_preauth = 1;
231 static int privsep_chroot = 1;
233 /* global authentication context */
234 Authctxt *the_authctxt = NULL;
236 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
237 struct sshauthopt *auth_opts = NULL;
239 /* sshd_config buffer */
242 /* message to be displayed after login */
245 /* Unprivileged user */
246 struct passwd *privsep_pw = NULL;
248 /* Prototypes for various functions defined later in this file. */
249 void destroy_sensitive_data(void);
250 void demote_sensitive_data(void);
251 static void do_ssh2_kex(void);
254 * Close all listening sockets
257 close_listen_socks(void)
261 for (i = 0; i < num_listen_socks; i++)
262 close(listen_socks[i]);
263 num_listen_socks = -1;
267 close_startup_pipes(void)
272 for (i = 0; i < options.max_startups; i++)
273 if (startup_pipes[i] != -1)
274 close(startup_pipes[i]);
278 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
279 * the effect is to reread the configuration file (and to regenerate
285 sighup_handler(int sig)
287 int save_errno = errno;
294 * Called from the main program after receiving SIGHUP.
295 * Restarts the server.
300 logit("Received SIGHUP; restarting.");
301 if (options.pid_file != NULL)
302 unlink(options.pid_file);
303 platform_pre_restart();
304 close_listen_socks();
305 close_startup_pipes();
306 alarm(0); /* alarm timer persists across exec */
307 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
308 execv(saved_argv[0], saved_argv);
309 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
315 * Generic signal handler for terminating signals in the master daemon.
319 sigterm_handler(int sig)
321 received_sigterm = sig;
325 * SIGCHLD handler. This is called whenever a child dies. This will then
326 * reap any zombies left by exited children.
330 main_sigchld_handler(int sig)
332 int save_errno = errno;
336 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
337 (pid < 0 && errno == EINTR))
343 * Signal handler for the alarm after the login grace period has expired.
347 grace_alarm_handler(int sig)
349 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
350 kill(pmonitor->m_pid, SIGALRM);
353 * Try to kill any processes that we have spawned, E.g. authorized
354 * keys command helpers.
356 if (getpgid(0) == getpid()) {
357 signal(SIGTERM, SIG_IGN);
361 /* Log error and exit. */
362 sigdie("Timeout before authentication for %s port %d",
363 ssh_remote_ipaddr(active_state), ssh_remote_port(active_state));
367 sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out)
370 int remote_major, remote_minor;
372 char buf[256]; /* Must not be larger than remote_version. */
373 char remote_version[256]; /* Must be at least as big as buf. */
375 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s\r\n",
376 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
377 *options.version_addendum == '\0' ? "" : " ",
378 options.version_addendum);
380 /* Send our protocol version identification. */
381 if (atomicio(vwrite, sock_out, server_version_string,
382 strlen(server_version_string))
383 != strlen(server_version_string)) {
384 logit("Could not write ident string to %s port %d",
385 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
389 /* Read other sides version identification. */
390 memset(buf, 0, sizeof(buf));
391 for (i = 0; i < sizeof(buf) - 1; i++) {
392 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
393 logit("Did not receive identification string "
395 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
398 if (buf[i] == '\r') {
400 /* Kludge for F-Secure Macintosh < 1.0.2 */
402 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
406 if (buf[i] == '\n') {
411 buf[sizeof(buf) - 1] = 0;
412 client_version_string = xstrdup(buf);
415 * Check that the versions match. In future this might accept
416 * several versions and set appropriate flags to handle them.
418 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
419 &remote_major, &remote_minor, remote_version) != 3) {
420 s = "Protocol mismatch.\n";
421 (void) atomicio(vwrite, sock_out, s, strlen(s));
422 logit("Bad protocol version identification '%.100s' "
423 "from %s port %d", client_version_string,
424 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
429 debug("Client protocol version %d.%d; client software version %.100s",
430 remote_major, remote_minor, remote_version);
432 ssh->compat = compat_datafellows(remote_version);
434 if ((ssh->compat & SSH_BUG_PROBE) != 0) {
435 logit("probed from %s port %d with %s. Don't panic.",
436 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
437 client_version_string);
440 if ((ssh->compat & SSH_BUG_SCANNER) != 0) {
441 logit("scanned from %s port %d with %s. Don't panic.",
442 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
443 client_version_string);
446 if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
447 logit("Client version \"%.100s\" uses unsafe RSA signature "
448 "scheme; disabling use of RSA keys", remote_version);
451 chop(server_version_string);
452 debug("Local version string %.200s", server_version_string);
454 if (remote_major != 2 &&
455 !(remote_major == 1 && remote_minor == 99)) {
456 s = "Protocol major versions differ.\n";
457 (void) atomicio(vwrite, sock_out, s, strlen(s));
460 logit("Protocol major versions differ for %s port %d: "
462 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
463 server_version_string, client_version_string);
468 /* Destroy the host and server keys. They will no longer be needed. */
470 destroy_sensitive_data(void)
474 for (i = 0; i < options.num_host_key_files; i++) {
475 if (sensitive_data.host_keys[i]) {
476 key_free(sensitive_data.host_keys[i]);
477 sensitive_data.host_keys[i] = NULL;
479 if (sensitive_data.host_certificates[i]) {
480 key_free(sensitive_data.host_certificates[i]);
481 sensitive_data.host_certificates[i] = NULL;
486 /* Demote private to public keys for network child */
488 demote_sensitive_data(void)
493 for (i = 0; i < options.num_host_key_files; i++) {
494 if (sensitive_data.host_keys[i]) {
495 tmp = key_demote(sensitive_data.host_keys[i]);
496 key_free(sensitive_data.host_keys[i]);
497 sensitive_data.host_keys[i] = tmp;
499 /* Certs do not need demotion */
511 arc4random_stir(); /* noop on recent arc4random() implementations */
512 arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
515 RAND_seed(rnd, sizeof(rnd));
516 /* give libcrypto a chance to notice the PID change */
517 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
518 fatal("%s: RAND_bytes failed", __func__);
521 explicit_bzero(rnd, sizeof(rnd));
525 privsep_preauth_child(void)
529 /* Enable challenge-response authentication for privilege separation */
530 privsep_challenge_enable();
533 /* Cache supported mechanism OIDs for later use */
534 if (options.gss_authentication)
535 ssh_gssapi_prepare_supported_oids();
540 /* Demote the private keys to public keys. */
541 demote_sensitive_data();
543 /* Demote the child */
544 if (privsep_chroot) {
545 /* Change our root directory */
546 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
547 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
549 if (chdir("/") == -1)
550 fatal("chdir(\"/\"): %s", strerror(errno));
552 /* Drop our privileges */
553 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
554 (u_int)privsep_pw->pw_gid);
555 gidset[0] = privsep_pw->pw_gid;
556 if (setgroups(1, gidset) < 0)
557 fatal("setgroups: %.100s", strerror(errno));
558 permanently_set_uid(privsep_pw);
563 privsep_preauth(Authctxt *authctxt)
567 struct ssh_sandbox *box = NULL;
569 /* Set up unprivileged child process to deal with network data */
570 pmonitor = monitor_init();
571 /* Store a pointer to the kex for later rekeying */
572 pmonitor->m_pkex = &active_state->kex;
574 if (use_privsep == PRIVSEP_ON)
575 box = ssh_sandbox_init(pmonitor);
578 fatal("fork of unprivileged child failed");
579 } else if (pid != 0) {
580 debug2("Network child is on pid %ld", (long)pid);
582 pmonitor->m_pid = pid;
584 r = ssh_get_authentication_socket(&auth_sock);
586 error("Could not get agent socket: %s",
592 ssh_sandbox_parent_preauth(box, pid);
593 monitor_child_preauth(authctxt, pmonitor);
595 /* Wait for the child's exit status */
596 while (waitpid(pid, &status, 0) < 0) {
599 pmonitor->m_pid = -1;
600 fatal("%s: waitpid: %s", __func__, strerror(errno));
602 privsep_is_preauth = 0;
603 pmonitor->m_pid = -1;
604 if (WIFEXITED(status)) {
605 if (WEXITSTATUS(status) != 0)
606 fatal("%s: preauth child exited with status %d",
607 __func__, WEXITSTATUS(status));
608 } else if (WIFSIGNALED(status))
609 fatal("%s: preauth child terminated by signal %d",
610 __func__, WTERMSIG(status));
612 ssh_sandbox_parent_finish(box);
616 close(pmonitor->m_sendfd);
617 close(pmonitor->m_log_recvfd);
619 /* Arrange for logging to be sent to the monitor */
620 set_log_handler(mm_log_handler, pmonitor);
622 privsep_preauth_child();
623 setproctitle("%s", "[net]");
625 ssh_sandbox_child(box);
632 privsep_postauth(Authctxt *authctxt)
634 #ifdef DISABLE_FD_PASSING
637 if (authctxt->pw->pw_uid == 0) {
639 /* File descriptor passing is broken or root login */
644 /* New socket pair */
645 monitor_reinit(pmonitor);
647 pmonitor->m_pid = fork();
648 if (pmonitor->m_pid == -1)
649 fatal("fork of unprivileged child failed");
650 else if (pmonitor->m_pid != 0) {
651 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
652 buffer_clear(&loginmsg);
653 monitor_clear_keystate(pmonitor);
654 monitor_child_postauth(pmonitor);
662 close(pmonitor->m_sendfd);
663 pmonitor->m_sendfd = -1;
665 /* Demote the private keys to public keys. */
666 demote_sensitive_data();
670 /* Drop privileges */
671 do_setusercontext(authctxt->pw);
674 /* It is safe now to apply the key state */
675 monitor_apply_keystate(pmonitor);
678 * Tell the packet layer that authentication was successful, since
679 * this information is not part of the key state.
681 packet_set_authenticated();
685 list_hostkey_types(void)
694 for (i = 0; i < options.num_host_key_files; i++) {
695 key = sensitive_data.host_keys[i];
697 key = sensitive_data.host_pubkeys[i];
700 /* Check that the key is accepted in HostkeyAlgorithms */
701 if (match_pattern_list(sshkey_ssh_name(key),
702 options.hostkeyalgorithms, 0) != 1) {
703 debug3("%s: %s key not permitted by HostkeyAlgorithms",
704 __func__, sshkey_ssh_name(key));
713 if (buffer_len(&b) > 0)
714 buffer_append(&b, ",", 1);
715 p = key_ssh_name(key);
716 buffer_append(&b, p, strlen(p));
718 /* for RSA we also support SHA2 signatures */
719 if (key->type == KEY_RSA) {
720 p = ",rsa-sha2-512,rsa-sha2-256";
721 buffer_append(&b, p, strlen(p));
725 /* If the private key has a cert peer, then list that too */
726 key = sensitive_data.host_certificates[i];
733 case KEY_ED25519_CERT:
735 if (buffer_len(&b) > 0)
736 buffer_append(&b, ",", 1);
737 p = key_ssh_name(key);
738 buffer_append(&b, p, strlen(p));
742 if ((ret = sshbuf_dup_string(&b)) == NULL)
743 fatal("%s: sshbuf_dup_string failed", __func__);
745 debug("list_hostkey_types: %s", ret);
749 static struct sshkey *
750 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
755 for (i = 0; i < options.num_host_key_files; i++) {
760 case KEY_ED25519_CERT:
762 key = sensitive_data.host_certificates[i];
765 key = sensitive_data.host_keys[i];
766 if (key == NULL && !need_private)
767 key = sensitive_data.host_pubkeys[i];
770 if (key != NULL && key->type == type &&
771 (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
772 return need_private ?
773 sensitive_data.host_keys[i] : key;
779 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
781 return get_hostkey_by_type(type, nid, 0, ssh);
785 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
787 return get_hostkey_by_type(type, nid, 1, ssh);
791 get_hostkey_by_index(int ind)
793 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
795 return (sensitive_data.host_keys[ind]);
799 get_hostkey_public_by_index(int ind, struct ssh *ssh)
801 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
803 return (sensitive_data.host_pubkeys[ind]);
807 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
811 for (i = 0; i < options.num_host_key_files; i++) {
812 if (key_is_cert(key)) {
813 if (key == sensitive_data.host_certificates[i] ||
814 (compare && sensitive_data.host_certificates[i] &&
816 sensitive_data.host_certificates[i])))
819 if (key == sensitive_data.host_keys[i] ||
820 (compare && sensitive_data.host_keys[i] &&
821 sshkey_equal(key, sensitive_data.host_keys[i])))
823 if (key == sensitive_data.host_pubkeys[i] ||
824 (compare && sensitive_data.host_pubkeys[i] &&
825 sshkey_equal(key, sensitive_data.host_pubkeys[i])))
832 /* Inform the client of all hostkeys */
834 notify_hostkeys(struct ssh *ssh)
842 /* Some clients cannot cope with the hostkeys message, skip those. */
843 if (datafellows & SSH_BUG_HOSTKEYS)
846 if ((buf = sshbuf_new()) == NULL)
847 fatal("%s: sshbuf_new", __func__);
848 for (i = nkeys = 0; i < options.num_host_key_files; i++) {
849 key = get_hostkey_public_by_index(i, ssh);
850 if (key == NULL || key->type == KEY_UNSPEC ||
853 fp = sshkey_fingerprint(key, options.fingerprint_hash,
855 debug3("%s: key %d: %s %s", __func__, i,
856 sshkey_ssh_name(key), fp);
859 packet_start(SSH2_MSG_GLOBAL_REQUEST);
860 packet_put_cstring("hostkeys-00@openssh.com");
861 packet_put_char(0); /* want-reply */
864 if ((r = sshkey_putb(key, buf)) != 0)
865 fatal("%s: couldn't put hostkey %d: %s",
866 __func__, i, ssh_err(r));
867 packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
870 debug3("%s: sent %u hostkeys", __func__, nkeys);
872 fatal("%s: no hostkeys", __func__);
878 * returns 1 if connection should be dropped, 0 otherwise.
879 * dropping starts at connection #max_startups_begin with a probability
880 * of (max_startups_rate/100). the probability increases linearly until
881 * all connections are dropped for startups > max_startups
884 drop_connection(int startups)
888 if (startups < options.max_startups_begin)
890 if (startups >= options.max_startups)
892 if (options.max_startups_rate == 100)
895 p = 100 - options.max_startups_rate;
896 p *= startups - options.max_startups_begin;
897 p /= options.max_startups - options.max_startups_begin;
898 p += options.max_startups_rate;
899 r = arc4random_uniform(100);
901 debug("drop_connection: p %d, r %d", p, r);
902 return (r < p) ? 1 : 0;
908 fprintf(stderr, "%s, %s\n",
911 SSLeay_version(SSLEAY_VERSION)
917 "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
918 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
919 " [-h host_key_file] [-o option] [-p port] [-u len]\n"
925 send_rexec_state(int fd, struct sshbuf *conf)
930 debug3("%s: entering fd = %d config len %zu", __func__, fd,
934 * Protocol from reexec master to child:
935 * string configuration
936 * string rngseed (only if OpenSSL is not self-seeded)
938 if ((m = sshbuf_new()) == NULL)
939 fatal("%s: sshbuf_new failed", __func__);
940 if ((r = sshbuf_put_stringb(m, conf)) != 0)
941 fatal("%s: buffer error: %s", __func__, ssh_err(r));
943 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
944 rexec_send_rng_seed(m);
947 if (ssh_msg_send(fd, 0, m) == -1)
948 fatal("%s: ssh_msg_send failed", __func__);
952 debug3("%s: done", __func__);
956 recv_rexec_state(int fd, Buffer *conf)
962 debug3("%s: entering fd = %d", __func__, fd);
966 if (ssh_msg_recv(fd, &m) == -1)
967 fatal("%s: ssh_msg_recv failed", __func__);
968 if (buffer_get_char(&m) != 0)
969 fatal("%s: rexec version mismatch", __func__);
971 cp = buffer_get_string(&m, &len);
973 buffer_append(conf, cp, len);
976 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
977 rexec_recv_rng_seed(&m);
982 debug3("%s: done", __func__);
985 /* Accept a connection from inetd */
987 server_accept_inetd(int *sock_in, int *sock_out)
993 close(REEXEC_CONFIG_PASS_FD);
994 *sock_in = *sock_out = dup(STDIN_FILENO);
996 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
997 close(REEXEC_STARTUP_PIPE_FD);
1000 *sock_in = dup(STDIN_FILENO);
1001 *sock_out = dup(STDOUT_FILENO);
1004 * We intentionally do not close the descriptors 0, 1, and 2
1005 * as our code for setting the descriptors won't work if
1006 * ttyfd happens to be one of those.
1008 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1009 dup2(fd, STDIN_FILENO);
1010 dup2(fd, STDOUT_FILENO);
1012 dup2(fd, STDERR_FILENO);
1013 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1016 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1020 * Listen for TCP connections
1023 listen_on_addrs(struct listenaddr *la)
1025 int ret, listen_sock;
1026 struct addrinfo *ai;
1027 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1029 for (ai = la->addrs; ai; ai = ai->ai_next) {
1030 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1032 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1033 fatal("Too many listen sockets. "
1034 "Enlarge MAX_LISTEN_SOCKS");
1035 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1036 ntop, sizeof(ntop), strport, sizeof(strport),
1037 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1038 error("getnameinfo failed: %.100s",
1039 ssh_gai_strerror(ret));
1042 /* Create socket for listening. */
1043 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1045 if (listen_sock < 0) {
1046 /* kernel may not support ipv6 */
1047 verbose("socket: %.100s", strerror(errno));
1050 if (set_nonblock(listen_sock) == -1) {
1054 if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
1055 verbose("socket: CLOEXEC: %s", strerror(errno));
1059 /* Socket options */
1060 set_reuseaddr(listen_sock);
1061 if (la->rdomain != NULL &&
1062 set_rdomain(listen_sock, la->rdomain) == -1) {
1067 /* Only communicate in IPv6 over AF_INET6 sockets. */
1068 if (ai->ai_family == AF_INET6)
1069 sock_set_v6only(listen_sock);
1071 debug("Bind to port %s on %s.", strport, ntop);
1073 /* Bind the socket to the desired port. */
1074 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1075 error("Bind to port %s on %s failed: %.200s.",
1076 strport, ntop, strerror(errno));
1080 listen_socks[num_listen_socks] = listen_sock;
1083 /* Start listening on the port. */
1084 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1085 fatal("listen on [%s]:%s: %.100s",
1086 ntop, strport, strerror(errno));
1087 logit("Server listening on %s port %s%s%s.",
1089 la->rdomain == NULL ? "" : " rdomain ",
1090 la->rdomain == NULL ? "" : la->rdomain);
1099 for (i = 0; i < options.num_listen_addrs; i++) {
1100 listen_on_addrs(&options.listen_addrs[i]);
1101 freeaddrinfo(options.listen_addrs[i].addrs);
1102 free(options.listen_addrs[i].rdomain);
1103 memset(&options.listen_addrs[i], 0,
1104 sizeof(options.listen_addrs[i]));
1106 free(options.listen_addrs);
1107 options.listen_addrs = NULL;
1108 options.num_listen_addrs = 0;
1110 if (!num_listen_socks)
1111 fatal("Cannot bind any address.");
1115 * The main TCP accept loop. Note that, for the non-debug case, returns
1116 * from this function are in a forked subprocess.
1119 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1122 int i, j, ret, maxfd;
1124 int startup_p[2] = { -1 , -1 };
1125 struct sockaddr_storage from;
1130 /* setup fd set for accept */
1133 for (i = 0; i < num_listen_socks; i++)
1134 if (listen_socks[i] > maxfd)
1135 maxfd = listen_socks[i];
1136 /* pipes connected to unauthenticated childs */
1137 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1138 for (i = 0; i < options.max_startups; i++)
1139 startup_pipes[i] = -1;
1142 * Stay listening for connections until the system crashes or
1143 * the daemon is killed with a signal.
1146 if (received_sighup)
1149 fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1152 for (i = 0; i < num_listen_socks; i++)
1153 FD_SET(listen_socks[i], fdset);
1154 for (i = 0; i < options.max_startups; i++)
1155 if (startup_pipes[i] != -1)
1156 FD_SET(startup_pipes[i], fdset);
1158 /* Wait in select until there is a connection. */
1159 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1160 if (ret < 0 && errno != EINTR)
1161 error("select: %.100s", strerror(errno));
1162 if (received_sigterm) {
1163 logit("Received signal %d; terminating.",
1164 (int) received_sigterm);
1165 close_listen_socks();
1166 if (options.pid_file != NULL)
1167 unlink(options.pid_file);
1168 exit(received_sigterm == SIGTERM ? 0 : 255);
1173 for (i = 0; i < options.max_startups; i++)
1174 if (startup_pipes[i] != -1 &&
1175 FD_ISSET(startup_pipes[i], fdset)) {
1177 * the read end of the pipe is ready
1178 * if the child has closed the pipe
1179 * after successful authentication
1180 * or if the child has died
1182 close(startup_pipes[i]);
1183 startup_pipes[i] = -1;
1186 for (i = 0; i < num_listen_socks; i++) {
1187 if (!FD_ISSET(listen_socks[i], fdset))
1189 fromlen = sizeof(from);
1190 *newsock = accept(listen_socks[i],
1191 (struct sockaddr *)&from, &fromlen);
1193 if (errno != EINTR && errno != EWOULDBLOCK &&
1194 errno != ECONNABORTED && errno != EAGAIN)
1195 error("accept: %.100s",
1197 if (errno == EMFILE || errno == ENFILE)
1201 if (unset_nonblock(*newsock) == -1) {
1205 if (drop_connection(startups) == 1) {
1206 char *laddr = get_local_ipaddr(*newsock);
1207 char *raddr = get_peer_ipaddr(*newsock);
1209 verbose("drop connection #%d from [%s]:%d "
1210 "on [%s]:%d past MaxStartups", startups,
1211 raddr, get_peer_port(*newsock),
1212 laddr, get_local_port(*newsock));
1218 if (pipe(startup_p) == -1) {
1223 if (rexec_flag && socketpair(AF_UNIX,
1224 SOCK_STREAM, 0, config_s) == -1) {
1225 error("reexec socketpair: %s",
1228 close(startup_p[0]);
1229 close(startup_p[1]);
1233 for (j = 0; j < options.max_startups; j++)
1234 if (startup_pipes[j] == -1) {
1235 startup_pipes[j] = startup_p[0];
1236 if (maxfd < startup_p[0])
1237 maxfd = startup_p[0];
1243 * Got connection. Fork a child to handle it, unless
1244 * we are in debugging mode.
1248 * In debugging mode. Close the listening
1249 * socket, and start processing the
1250 * connection without forking.
1252 debug("Server will not fork when running in debugging mode.");
1253 close_listen_socks();
1254 *sock_in = *newsock;
1255 *sock_out = *newsock;
1256 close(startup_p[0]);
1257 close(startup_p[1]);
1261 send_rexec_state(config_s[0],
1269 * Normal production daemon. Fork, and have
1270 * the child process the connection. The
1271 * parent continues listening.
1273 platform_pre_fork();
1274 if ((pid = fork()) == 0) {
1276 * Child. Close the listening and
1277 * max_startup sockets. Start using
1278 * the accepted socket. Reinitialize
1279 * logging (since our pid has changed).
1280 * We break out of the loop to handle
1283 platform_post_fork_child();
1284 startup_pipe = startup_p[1];
1285 close_startup_pipes();
1286 close_listen_socks();
1287 *sock_in = *newsock;
1288 *sock_out = *newsock;
1289 log_init(__progname,
1291 options.log_facility,
1298 /* Parent. Stay in the loop. */
1299 platform_post_fork_parent(pid);
1301 error("fork: %.100s", strerror(errno));
1303 debug("Forked child %ld.", (long)pid);
1305 close(startup_p[1]);
1308 send_rexec_state(config_s[0], &cfg);
1315 * Ensure that our random state differs
1316 * from that of the child
1319 arc4random_buf(rnd, sizeof(rnd));
1321 RAND_seed(rnd, sizeof(rnd));
1322 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1323 fatal("%s: RAND_bytes failed", __func__);
1325 explicit_bzero(rnd, sizeof(rnd));
1328 /* child process check (or debug mode) */
1329 if (num_listen_socks < 0)
1335 * If IP options are supported, make sure there are none (log and
1336 * return an error if any are found). Basically we are worried about
1337 * source routing; it can be used to pretend you are somebody
1338 * (ip-address) you are not. That itself may be "almost acceptable"
1339 * under certain circumstances, but rhosts autentication is useless
1340 * if source routing is accepted. Notice also that if we just dropped
1341 * source routing here, the other side could use IP spoofing to do
1342 * rest of the interaction and could still bypass security. So we
1343 * exit here if we detect any IP options.
1346 check_ip_options(struct ssh *ssh)
1349 int sock_in = ssh_packet_get_connection_in(ssh);
1350 struct sockaddr_storage from;
1352 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1353 char text[sizeof(opts) * 3 + 1];
1355 memset(&from, 0, sizeof(from));
1356 if (getpeername(sock_in, (struct sockaddr *)&from,
1359 if (from.ss_family != AF_INET)
1361 /* XXX IPv6 options? */
1363 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1364 &option_size) >= 0 && option_size != 0) {
1366 for (i = 0; i < option_size; i++)
1367 snprintf(text + i*3, sizeof(text) - i*3,
1369 fatal("Connection from %.100s port %d with IP opts: %.800s",
1370 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1373 #endif /* IP_OPTIONS */
1376 /* Set the routing domain for this process */
1378 set_process_rdomain(struct ssh *ssh, const char *name)
1380 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
1382 return; /* default */
1384 if (strcmp(name, "%D") == 0) {
1385 /* "expands" to routing domain of connection */
1386 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1389 /* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
1390 return sys_set_process_rdomain(name);
1391 #elif defined(__OpenBSD__)
1392 int rtable, ortable = getrtable();
1396 return; /* default */
1398 if (strcmp(name, "%D") == 0) {
1399 /* "expands" to routing domain of connection */
1400 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1404 rtable = (int)strtonum(name, 0, 255, &errstr);
1405 if (errstr != NULL) /* Shouldn't happen */
1406 fatal("Invalid routing domain \"%s\": %s", name, errstr);
1407 if (rtable != ortable && setrtable(rtable) != 0)
1408 fatal("Unable to set routing domain %d: %s",
1409 rtable, strerror(errno));
1410 debug("%s: set routing domain %d (was %d)", __func__, rtable, ortable);
1411 #else /* defined(__OpenBSD__) */
1412 fatal("Unable to set routing domain: not supported in this platform");
1417 * Main program for the daemon.
1420 main(int ac, char **av)
1422 struct ssh *ssh = NULL;
1423 extern char *optarg;
1425 int r, opt, on = 1, already_daemon, remote_port;
1426 int sock_in = -1, sock_out = -1, newsock = -1;
1427 const char *remote_ip, *rdomain;
1428 char *fp, *line, *laddr, *logfile = NULL;
1429 int config_s[2] = { -1 , -1 };
1431 u_int64_t ibytes, obytes;
1434 struct sshkey *pubkey;
1437 struct connection_info *connection_info = NULL;
1439 ssh_malloc_init(); /* must be called before any mallocs */
1441 #ifdef HAVE_SECUREWARE
1442 (void)set_auth_parameters(ac, av);
1444 __progname = ssh_get_progname(av[0]);
1446 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1449 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1450 for (i = 0; (int)i < ac; i++)
1451 saved_argv[i] = xstrdup(av[i]);
1452 saved_argv[i] = NULL;
1454 #ifndef HAVE_SETPROCTITLE
1455 /* Prepare for later setproctitle emulation */
1456 compat_init_setproctitle(ac, av);
1460 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1461 debug("setgroups(): %.200s", strerror(errno));
1463 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1466 /* Initialize configuration options to their default values. */
1467 initialize_server_options(&options);
1469 /* Parse command-line arguments. */
1470 while ((opt = getopt(ac, av,
1471 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1474 options.address_family = AF_INET;
1477 options.address_family = AF_INET6;
1480 config_file_name = optarg;
1483 servconf_add_hostcert("[command-line]", 0,
1487 if (debug_flag == 0) {
1489 options.log_level = SYSLOG_LEVEL_DEBUG1;
1490 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1491 options.log_level++;
1516 options.log_level = SYSLOG_LEVEL_QUIET;
1519 /* protocol 1, ignored */
1522 options.ports_from_cmdline = 1;
1523 if (options.num_ports >= MAX_PORTS) {
1524 fprintf(stderr, "too many ports.\n");
1527 options.ports[options.num_ports++] = a2port(optarg);
1528 if (options.ports[options.num_ports-1] <= 0) {
1529 fprintf(stderr, "Bad port number.\n");
1534 if ((options.login_grace_time = convtime(optarg)) == -1) {
1535 fprintf(stderr, "Invalid login grace time.\n");
1540 /* protocol 1, ignored */
1543 servconf_add_hostkey("[command-line]", 0,
1553 connection_info = get_connection_info(0, 0);
1554 if (parse_server_match_testspec(connection_info,
1559 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1560 if (utmp_len > HOST_NAME_MAX+1) {
1561 fprintf(stderr, "Invalid utmp length.\n");
1566 line = xstrdup(optarg);
1567 if (process_server_config_line(&options, line,
1568 "command-line", 0, NULL, NULL) != 0)
1578 if (rexeced_flag || inetd_flag)
1580 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1581 fatal("sshd re-exec requires execution with an absolute path");
1583 closefrom(REEXEC_MIN_FREE_FD);
1585 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1588 OpenSSL_add_all_algorithms();
1591 /* If requested, redirect the logs to the specified logfile. */
1592 if (logfile != NULL)
1593 log_redirect_stderr_to(logfile);
1595 * Force logging to stderr until we have loaded the private host
1596 * key (unless started from inetd)
1598 log_init(__progname,
1599 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1600 SYSLOG_LEVEL_INFO : options.log_level,
1601 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1602 SYSLOG_FACILITY_AUTH : options.log_facility,
1603 log_stderr || !inetd_flag);
1606 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1607 * root's environment
1609 if (getenv("KRB5CCNAME") != NULL)
1610 (void) unsetenv("KRB5CCNAME");
1612 sensitive_data.have_ssh2_key = 0;
1615 * If we're not doing an extended test do not silently ignore connection
1618 if (test_flag < 2 && connection_info != NULL)
1619 fatal("Config test connection parameter (-C) provided without "
1622 /* Fetch our configuration */
1625 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1626 else if (strcasecmp(config_file_name, "none") != 0)
1627 load_server_config(config_file_name, &cfg);
1629 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1634 /* Fill in default values for those options not explicitly set. */
1635 fill_default_server_options(&options);
1637 /* challenge-response is implemented via keyboard interactive */
1638 if (options.challenge_response_authentication)
1639 options.kbd_interactive_authentication = 1;
1641 /* Check that options are sensible */
1642 if (options.authorized_keys_command_user == NULL &&
1643 (options.authorized_keys_command != NULL &&
1644 strcasecmp(options.authorized_keys_command, "none") != 0))
1645 fatal("AuthorizedKeysCommand set without "
1646 "AuthorizedKeysCommandUser");
1647 if (options.authorized_principals_command_user == NULL &&
1648 (options.authorized_principals_command != NULL &&
1649 strcasecmp(options.authorized_principals_command, "none") != 0))
1650 fatal("AuthorizedPrincipalsCommand set without "
1651 "AuthorizedPrincipalsCommandUser");
1654 * Check whether there is any path through configured auth methods.
1655 * Unfortunately it is not possible to verify this generally before
1656 * daemonisation in the presence of Match block, but this catches
1657 * and warns for trivial misconfigurations that could break login.
1659 if (options.num_auth_methods != 0) {
1660 for (i = 0; i < options.num_auth_methods; i++) {
1661 if (auth2_methods_valid(options.auth_methods[i],
1665 if (i >= options.num_auth_methods)
1666 fatal("AuthenticationMethods cannot be satisfied by "
1667 "enabled authentication methods");
1670 /* Check that there are no remaining arguments. */
1672 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1676 debug("sshd version %s, %s", SSH_VERSION,
1678 SSLeay_version(SSLEAY_VERSION)
1684 /* Store privilege separation user for later use if required. */
1685 privsep_chroot = use_privsep && (getuid() == 0 || geteuid() == 0);
1686 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1687 if (privsep_chroot || options.kerberos_authentication)
1688 fatal("Privilege separation user %s does not exist",
1691 privsep_pw = pwcopy(privsep_pw);
1692 freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
1693 privsep_pw->pw_passwd = xstrdup("*");
1697 /* load host keys */
1698 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1699 sizeof(struct sshkey *));
1700 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1701 sizeof(struct sshkey *));
1703 if (options.host_key_agent) {
1704 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1705 setenv(SSH_AUTHSOCKET_ENV_NAME,
1706 options.host_key_agent, 1);
1707 if ((r = ssh_get_authentication_socket(NULL)) == 0)
1710 error("Could not connect to agent \"%s\": %s",
1711 options.host_key_agent, ssh_err(r));
1714 for (i = 0; i < options.num_host_key_files; i++) {
1715 if (options.host_key_files[i] == NULL)
1717 key = key_load_private(options.host_key_files[i], "", NULL);
1718 pubkey = key_load_public(options.host_key_files[i], NULL);
1720 if (pubkey == NULL && key != NULL)
1721 pubkey = key_demote(key);
1722 sensitive_data.host_keys[i] = key;
1723 sensitive_data.host_pubkeys[i] = pubkey;
1725 if (key == NULL && pubkey != NULL && have_agent) {
1726 debug("will rely on agent for hostkey %s",
1727 options.host_key_files[i]);
1728 keytype = pubkey->type;
1729 } else if (key != NULL) {
1730 keytype = key->type;
1732 error("Could not load host key: %s",
1733 options.host_key_files[i]);
1734 sensitive_data.host_keys[i] = NULL;
1735 sensitive_data.host_pubkeys[i] = NULL;
1745 if (have_agent || key != NULL)
1746 sensitive_data.have_ssh2_key = 1;
1749 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1750 SSH_FP_DEFAULT)) == NULL)
1751 fatal("sshkey_fingerprint failed");
1752 debug("%s host key #%d: %s %s",
1753 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1756 if (!sensitive_data.have_ssh2_key) {
1757 logit("sshd: no hostkeys available -- exiting.");
1762 * Load certificates. They are stored in an array at identical
1763 * indices to the public keys that they relate to.
1765 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1766 sizeof(struct sshkey *));
1767 for (i = 0; i < options.num_host_key_files; i++)
1768 sensitive_data.host_certificates[i] = NULL;
1770 for (i = 0; i < options.num_host_cert_files; i++) {
1771 if (options.host_cert_files[i] == NULL)
1773 key = key_load_public(options.host_cert_files[i], NULL);
1775 error("Could not load host certificate: %s",
1776 options.host_cert_files[i]);
1779 if (!key_is_cert(key)) {
1780 error("Certificate file is not a certificate: %s",
1781 options.host_cert_files[i]);
1785 /* Find matching private key */
1786 for (j = 0; j < options.num_host_key_files; j++) {
1787 if (key_equal_public(key,
1788 sensitive_data.host_keys[j])) {
1789 sensitive_data.host_certificates[j] = key;
1793 if (j >= options.num_host_key_files) {
1794 error("No matching private key for certificate: %s",
1795 options.host_cert_files[i]);
1799 sensitive_data.host_certificates[j] = key;
1800 debug("host certificate: #%u type %d %s", j, key->type,
1804 if (privsep_chroot) {
1807 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1808 (S_ISDIR(st.st_mode) == 0))
1809 fatal("Missing privilege separation directory: %s",
1810 _PATH_PRIVSEP_CHROOT_DIR);
1813 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1814 (st.st_uid != getuid () ||
1815 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1817 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1819 fatal("%s must be owned by root and not group or "
1820 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1823 if (test_flag > 1) {
1825 * If no connection info was provided by -C then use
1826 * use a blank one that will cause no predicate to match.
1828 if (connection_info == NULL)
1829 connection_info = get_connection_info(0, 0);
1830 parse_server_match_config(&options, connection_info);
1831 dump_config(&options);
1834 /* Configuration looks good, so exit if in test mode. */
1839 * Clear out any supplemental groups we may have inherited. This
1840 * prevents inadvertent creation of files with bad modes (in the
1841 * portable version at least, it's certainly possible for PAM
1842 * to create a file, and we can't control the code in every
1843 * module which might be used).
1845 if (setgroups(0, NULL) < 0)
1846 debug("setgroups() failed: %.200s", strerror(errno));
1850 fatal("rexec_argc %d < 0", rexec_argc);
1851 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1852 for (i = 0; i < (u_int)rexec_argc; i++) {
1853 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1854 rexec_argv[i] = saved_argv[i];
1856 rexec_argv[rexec_argc] = "-R";
1857 rexec_argv[rexec_argc + 1] = NULL;
1860 /* Ensure that umask disallows at least group and world write */
1861 new_umask = umask(0077) | 0022;
1862 (void) umask(new_umask);
1864 /* Initialize the log (it is reinitialized below in case we forked). */
1865 if (debug_flag && (!inetd_flag || rexeced_flag))
1867 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1870 * If not in debugging mode, not started from inetd and not already
1871 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1872 * terminal, and fork. The original process exits.
1874 already_daemon = daemonized();
1875 if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1877 if (daemon(0, 0) < 0)
1878 fatal("daemon() failed: %.200s", strerror(errno));
1880 disconnect_controlling_tty();
1882 /* Reinitialize the log (because of the fork above). */
1883 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1885 /* Chdir to the root directory so that the current disk can be
1886 unmounted if desired. */
1887 if (chdir("/") == -1)
1888 error("chdir(\"/\"): %s", strerror(errno));
1890 /* ignore SIGPIPE */
1891 signal(SIGPIPE, SIG_IGN);
1893 /* Get a connection, either from inetd or a listening TCP socket */
1895 server_accept_inetd(&sock_in, &sock_out);
1897 platform_pre_listen();
1900 signal(SIGHUP, sighup_handler);
1901 signal(SIGCHLD, main_sigchld_handler);
1902 signal(SIGTERM, sigterm_handler);
1903 signal(SIGQUIT, sigterm_handler);
1906 * Write out the pid file after the sigterm handler
1907 * is setup and the listen sockets are bound
1909 if (options.pid_file != NULL && !debug_flag) {
1910 FILE *f = fopen(options.pid_file, "w");
1913 error("Couldn't create pid file \"%s\": %s",
1914 options.pid_file, strerror(errno));
1916 fprintf(f, "%ld\n", (long) getpid());
1921 /* Accept a connection and return in a forked child */
1922 server_accept_loop(&sock_in, &sock_out,
1923 &newsock, config_s);
1926 /* This is the child processing a new connection. */
1927 setproctitle("%s", "[accepted]");
1930 * Create a new session and process group since the 4.4BSD
1931 * setlogin() affects the entire process group. We don't
1932 * want the child to be able to affect the parent.
1934 #if !defined(SSHD_ACQUIRES_CTTY)
1936 * If setsid is called, on some platforms sshd will later acquire a
1937 * controlling terminal which will result in "could not set
1938 * controlling tty" errors.
1940 if (!debug_flag && !inetd_flag && setsid() < 0)
1941 error("setsid: %.100s", strerror(errno));
1947 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1948 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1949 dup2(newsock, STDIN_FILENO);
1950 dup2(STDIN_FILENO, STDOUT_FILENO);
1951 if (startup_pipe == -1)
1952 close(REEXEC_STARTUP_PIPE_FD);
1953 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
1954 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1955 close(startup_pipe);
1956 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1959 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1962 execv(rexec_argv[0], rexec_argv);
1964 /* Reexec has failed, fall back and continue */
1965 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1966 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1967 log_init(__progname, options.log_level,
1968 options.log_facility, log_stderr);
1971 close(REEXEC_CONFIG_PASS_FD);
1972 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1973 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1974 dup2(fd, STDIN_FILENO);
1975 dup2(fd, STDOUT_FILENO);
1976 if (fd > STDERR_FILENO)
1979 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1980 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1983 /* Executed child processes don't need these. */
1984 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1985 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1988 * Disable the key regeneration alarm. We will not regenerate the
1989 * key since we are no longer in a position to give it to anyone. We
1990 * will not restart on SIGHUP since it no longer makes sense.
1993 signal(SIGALRM, SIG_DFL);
1994 signal(SIGHUP, SIG_DFL);
1995 signal(SIGTERM, SIG_DFL);
1996 signal(SIGQUIT, SIG_DFL);
1997 signal(SIGCHLD, SIG_DFL);
1998 signal(SIGINT, SIG_DFL);
2001 * Register our connection. This turns encryption off because we do
2004 packet_set_connection(sock_in, sock_out);
2005 packet_set_server();
2006 ssh = active_state; /* XXX */
2008 check_ip_options(ssh);
2010 /* Prepare the channels layer */
2011 channel_init_channels(ssh);
2012 channel_set_af(ssh, options.address_family);
2013 process_permitopen(ssh, &options);
2015 /* Set SO_KEEPALIVE if requested. */
2016 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2017 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2018 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2020 if ((remote_port = ssh_remote_port(ssh)) < 0) {
2021 debug("ssh_remote_port failed");
2025 if (options.routing_domain != NULL)
2026 set_process_rdomain(ssh, options.routing_domain);
2029 * The rest of the code depends on the fact that
2030 * ssh_remote_ipaddr() caches the remote ip, even if
2031 * the socket goes away.
2033 remote_ip = ssh_remote_ipaddr(ssh);
2035 #ifdef SSH_AUDIT_EVENTS
2036 audit_connection_from(remote_ip, remote_port);
2039 rdomain = ssh_packet_rdomain_in(ssh);
2041 /* Log the connection. */
2042 laddr = get_local_ipaddr(sock_in);
2043 verbose("Connection from %s port %d on %s port %d%s%s%s",
2044 remote_ip, remote_port, laddr, ssh_local_port(ssh),
2045 rdomain == NULL ? "" : " rdomain \"",
2046 rdomain == NULL ? "" : rdomain,
2047 rdomain == NULL ? "" : "\"");
2051 * We don't want to listen forever unless the other side
2052 * successfully authenticates itself. So we set up an alarm which is
2053 * cleared after successful authentication. A limit of zero
2054 * indicates no limit. Note that we don't set the alarm in debugging
2055 * mode; it is just annoying to have the server exit just when you
2056 * are about to discover the bug.
2058 signal(SIGALRM, grace_alarm_handler);
2060 alarm(options.login_grace_time);
2062 sshd_exchange_identification(ssh, sock_in, sock_out);
2063 packet_set_nonblocking();
2065 /* allocate authentication context */
2066 authctxt = xcalloc(1, sizeof(*authctxt));
2068 authctxt->loginmsg = &loginmsg;
2070 /* XXX global for cleanup, access from other modules */
2071 the_authctxt = authctxt;
2073 /* Set default key authentication options */
2074 if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
2075 fatal("allocation failed");
2077 /* prepare buffer to collect messages to display to user after login */
2078 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);
2102 packet_clear_keys();
2108 * Cancel the alarm we set to limit the time taken for
2112 signal(SIGALRM, SIG_DFL);
2113 authctxt->authenticated = 1;
2114 if (startup_pipe != -1) {
2115 close(startup_pipe);
2119 #ifdef SSH_AUDIT_EVENTS
2120 audit_event(SSH_AUTH_SUCCESS);
2124 if (options.gss_authentication) {
2125 temporarily_use_uid(authctxt->pw);
2126 ssh_gssapi_storecreds();
2131 if (options.use_pam) {
2133 do_pam_session(ssh);
2138 * In privilege separation, we fork another child and prepare
2139 * file descriptor passing.
2142 privsep_postauth(authctxt);
2143 /* the monitor process [priv] will not return */
2146 packet_set_timeout(options.client_alive_interval,
2147 options.client_alive_count_max);
2149 /* Try to send all our hostkeys to the client */
2150 notify_hostkeys(ssh);
2152 /* Start session. */
2153 do_authenticated(ssh, authctxt);
2155 /* The connection has been terminated. */
2156 packet_get_bytes(&ibytes, &obytes);
2157 verbose("Transferred: sent %llu, received %llu bytes",
2158 (unsigned long long)obytes, (unsigned long long)ibytes);
2160 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2163 if (options.use_pam)
2165 #endif /* USE_PAM */
2167 #ifdef SSH_AUDIT_EVENTS
2168 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2180 sshd_hostkey_sign(struct sshkey *privkey, struct sshkey *pubkey,
2181 u_char **signature, size_t *slen, const u_char *data, size_t dlen,
2182 const char *alg, u_int flag)
2185 u_int xxx_slen, xxx_dlen = dlen;
2188 if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen,
2190 fatal("%s: key_sign failed", __func__);
2193 } else if (use_privsep) {
2194 if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen,
2196 fatal("%s: pubkey_sign failed", __func__);
2200 if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen,
2201 data, dlen, alg, datafellows)) != 0)
2202 fatal("%s: ssh_agent_sign failed: %s",
2203 __func__, ssh_err(r));
2208 /* SSH2 key exchange */
2212 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2216 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2217 options.kex_algorithms);
2218 myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
2220 myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
2222 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2223 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2225 if (options.compression == COMP_NONE) {
2226 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2227 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2230 if (options.rekey_limit || options.rekey_interval)
2231 packet_set_rekey_limits(options.rekey_limit,
2232 options.rekey_interval);
2234 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2235 list_hostkey_types());
2237 /* start key exchange */
2238 if ((r = kex_setup(active_state, myproposal)) != 0)
2239 fatal("kex_setup: %s", ssh_err(r));
2240 kex = active_state->kex;
2242 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2243 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2244 kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
2245 kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
2246 kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
2247 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2248 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2249 # ifdef OPENSSL_HAS_ECC
2250 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2253 kex->kex[KEX_C25519_SHA256] = kexc25519_server;
2255 kex->client_version_string=client_version_string;
2256 kex->server_version_string=server_version_string;
2257 kex->load_host_public_key=&get_hostkey_public_by_type;
2258 kex->load_host_private_key=&get_hostkey_private_by_type;
2259 kex->host_key_index=&get_hostkey_index;
2260 kex->sign = sshd_hostkey_sign;
2262 ssh_dispatch_run_fatal(active_state, DISPATCH_BLOCK, &kex->done);
2264 session_id2 = kex->session_id;
2265 session_id2_len = kex->session_id_len;
2268 /* send 1st encrypted/maced/compressed message */
2269 packet_start(SSH2_MSG_IGNORE);
2270 packet_put_cstring("markus");
2272 packet_write_wait();
2277 /* server specific fatal cleanup */
2281 struct ssh *ssh = active_state; /* XXX */
2284 do_cleanup(ssh, the_authctxt);
2285 if (use_privsep && privsep_is_preauth &&
2286 pmonitor != NULL && pmonitor->m_pid > 1) {
2287 debug("Killing privsep child %d", pmonitor->m_pid);
2288 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2290 error("%s: kill(%d): %s", __func__,
2291 pmonitor->m_pid, strerror(errno));
2294 #ifdef SSH_AUDIT_EVENTS
2295 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2296 if (!use_privsep || mm_is_monitor())
2297 audit_event(SSH_CONNECTION_ABANDON);