1 /* $OpenBSD: sshd.c,v 1.600 2023/03/08 04:43:12 guenther 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>
50 #include <sys/socket.h>
51 #ifdef HAVE_SYS_STAT_H
52 # include <sys/stat.h>
54 #ifdef HAVE_SYS_TIME_H
55 # include <sys/time.h>
57 #include "openbsd-compat/sys-tree.h"
58 #include "openbsd-compat/sys-queue.h"
81 #include <openssl/dh.h>
82 #include <openssl/bn.h>
83 #include <openssl/rand.h>
84 #include "openbsd-compat/openssl-compat.h"
87 #ifdef HAVE_SECUREWARE
88 #include <sys/security.h>
94 #if defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
95 #include <gssapi/gssapi.h>
96 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_H)
110 #include "servconf.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"
134 #include "auth-options.h"
138 #include "srclimit.h"
140 #include "blacklist_client.h"
145 extern int allow_severity;
146 extern int deny_severity;
150 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
151 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
152 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
153 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
155 extern char *__progname;
157 /* Server configuration options. */
158 ServerOptions options;
160 /* Name of the server configuration file. */
161 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
164 * Debug mode flag. This can be set on the command line. If debug
165 * mode is enabled, extra debugging output will be sent to the system
166 * log, the daemon will not go to background, and will exit after processing
167 * the first connection.
172 * Indicating that the daemon should only test the configuration and keys.
173 * If test_flag > 1 ("-T" flag), then sshd will also dump the effective
174 * configuration, optionally using connection information provided by the
177 static int test_flag = 0;
179 /* Flag indicating that the daemon is being started from inetd. */
180 static int inetd_flag = 0;
182 /* Flag indicating that sshd should not detach and become a daemon. */
183 static int no_daemon_flag = 0;
185 /* debug goes to stderr unless inetd_flag is set */
186 static int log_stderr = 0;
188 /* Saved arguments to main(). */
189 static char **saved_argv;
190 static int saved_argc;
193 static int rexeced_flag = 0;
194 static int rexec_flag = 1;
195 static int rexec_argc = 0;
196 static char **rexec_argv;
199 * The sockets that the server is listening; this is used in the SIGHUP
202 #define MAX_LISTEN_SOCKS 16
203 static int listen_socks[MAX_LISTEN_SOCKS];
204 static int num_listen_socks = 0;
206 /* Daemon's agent connection */
208 static int have_agent = 0;
211 * Any really sensitive data in the application is contained in this
212 * structure. The idea is that this structure could be locked into memory so
213 * that the pages do not get written into swap. However, there are some
214 * problems. The private key contains BIGNUMs, and we do not (in principle)
215 * have access to the internals of them, and locking just the structure is
216 * not very useful. Currently, memory locking is not implemented.
219 struct sshkey **host_keys; /* all private host keys */
220 struct sshkey **host_pubkeys; /* all public host keys */
221 struct sshkey **host_certificates; /* all public host certificates */
225 /* This is set to true when a signal is received. */
226 static volatile sig_atomic_t received_sighup = 0;
227 static volatile sig_atomic_t received_sigterm = 0;
229 /* record remote hostname or ip */
230 u_int utmp_len = HOST_NAME_MAX+1;
233 * startup_pipes/flags are used for tracking children of the listening sshd
234 * process early in their lifespans. This tracking is needed for three things:
236 * 1) Implementing the MaxStartups limit of concurrent unauthenticated
238 * 2) Avoiding a race condition for SIGHUP processing, where child processes
239 * may have listen_socks open that could collide with main listener process
241 * 3) Ensuring that rexec'd sshd processes have received their initial state
242 * from the parent listen process before handling SIGHUP.
244 * Child processes signal that they have completed closure of the listen_socks
245 * and (if applicable) received their rexec state by sending a char over their
246 * sock. Child processes signal that authentication has completed by closing
247 * the sock (or by exiting).
249 static int *startup_pipes = NULL;
250 static int *startup_flags = NULL; /* Indicates child closed listener */
251 static int startup_pipe = -1; /* in child */
253 /* variables used for privilege separation */
254 int use_privsep = -1;
255 struct monitor *pmonitor = NULL;
256 int privsep_is_preauth = 1;
257 static int privsep_chroot = 1;
259 /* global connection state and authentication contexts */
260 Authctxt *the_authctxt = NULL;
261 struct ssh *the_active_state;
263 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
264 struct sshauthopt *auth_opts = NULL;
266 /* sshd_config buffer */
269 /* Included files from the configuration file */
270 struct include_list includes = TAILQ_HEAD_INITIALIZER(includes);
272 /* message to be displayed after login */
273 struct sshbuf *loginmsg;
275 /* Unprivileged user */
276 struct passwd *privsep_pw = NULL;
278 /* Prototypes for various functions defined later in this file. */
279 void destroy_sensitive_data(void);
280 void demote_sensitive_data(void);
281 static void do_ssh2_kex(struct ssh *);
283 static char *listener_proctitle;
286 * Close all listening sockets
289 close_listen_socks(void)
293 for (i = 0; i < num_listen_socks; i++)
294 close(listen_socks[i]);
295 num_listen_socks = 0;
299 close_startup_pipes(void)
304 for (i = 0; i < options.max_startups; i++)
305 if (startup_pipes[i] != -1)
306 close(startup_pipes[i]);
310 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
311 * the effect is to reread the configuration file (and to regenerate
316 sighup_handler(int sig)
322 * Called from the main program after receiving SIGHUP.
323 * Restarts the server.
328 logit("Received SIGHUP; restarting.");
329 if (options.pid_file != NULL)
330 unlink(options.pid_file);
331 platform_pre_restart();
332 close_listen_socks();
333 close_startup_pipes();
334 ssh_signal(SIGHUP, SIG_IGN); /* will be restored after exec */
335 execv(saved_argv[0], saved_argv);
336 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
342 * Generic signal handler for terminating signals in the master daemon.
345 sigterm_handler(int sig)
347 received_sigterm = sig;
351 * SIGCHLD handler. This is called whenever a child dies. This will then
352 * reap any zombies left by exited children.
355 main_sigchld_handler(int sig)
357 int save_errno = errno;
361 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
362 (pid == -1 && errno == EINTR))
368 * Signal handler for the alarm after the login grace period has expired.
371 grace_alarm_handler(int sig)
374 * Try to kill any processes that we have spawned, E.g. authorized
375 * keys command helpers or privsep children.
377 if (getpgid(0) == getpid()) {
378 ssh_signal(SIGTERM, SIG_IGN);
382 BLACKLIST_NOTIFY(the_active_state, BLACKLIST_AUTH_FAIL, "ssh");
384 /* Log error and exit. */
385 sigdie("Timeout before authentication for %s port %d",
386 ssh_remote_ipaddr(the_active_state),
387 ssh_remote_port(the_active_state));
390 /* Destroy the host and server keys. They will no longer be needed. */
392 destroy_sensitive_data(void)
396 for (i = 0; i < options.num_host_key_files; i++) {
397 if (sensitive_data.host_keys[i]) {
398 sshkey_free(sensitive_data.host_keys[i]);
399 sensitive_data.host_keys[i] = NULL;
401 if (sensitive_data.host_certificates[i]) {
402 sshkey_free(sensitive_data.host_certificates[i]);
403 sensitive_data.host_certificates[i] = NULL;
408 /* Demote private to public keys for network child */
410 demote_sensitive_data(void)
416 for (i = 0; i < options.num_host_key_files; i++) {
417 if (sensitive_data.host_keys[i]) {
418 if ((r = sshkey_from_private(
419 sensitive_data.host_keys[i], &tmp)) != 0)
420 fatal_r(r, "could not demote host %s key",
421 sshkey_type(sensitive_data.host_keys[i]));
422 sshkey_free(sensitive_data.host_keys[i]);
423 sensitive_data.host_keys[i] = tmp;
425 /* Certs do not need demotion */
437 arc4random_stir(); /* noop on recent arc4random() implementations */
438 arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
441 RAND_seed(rnd, sizeof(rnd));
442 /* give libcrypto a chance to notice the PID change */
443 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
444 fatal("%s: RAND_bytes failed", __func__);
447 explicit_bzero(rnd, sizeof(rnd));
451 privsep_preauth_child(void)
455 /* Enable challenge-response authentication for privilege separation */
456 privsep_challenge_enable();
459 /* Cache supported mechanism OIDs for later use */
460 ssh_gssapi_prepare_supported_oids();
465 /* Demote the private keys to public keys. */
466 demote_sensitive_data();
468 /* Demote the child */
469 if (privsep_chroot) {
470 /* Change our root directory */
471 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
472 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
474 if (chdir("/") == -1)
475 fatal("chdir(\"/\"): %s", strerror(errno));
477 /* Drop our privileges */
478 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
479 (u_int)privsep_pw->pw_gid);
480 gidset[0] = privsep_pw->pw_gid;
481 if (setgroups(1, gidset) == -1)
482 fatal("setgroups: %.100s", strerror(errno));
483 permanently_set_uid(privsep_pw);
488 privsep_preauth(struct ssh *ssh)
492 struct ssh_sandbox *box = NULL;
494 /* Set up unprivileged child process to deal with network data */
495 pmonitor = monitor_init();
496 /* Store a pointer to the kex for later rekeying */
497 pmonitor->m_pkex = &ssh->kex;
499 if (use_privsep == PRIVSEP_ON)
500 box = ssh_sandbox_init(pmonitor);
503 fatal("fork of unprivileged child failed");
504 } else if (pid != 0) {
505 debug2("Network child is on pid %ld", (long)pid);
507 pmonitor->m_pid = pid;
509 r = ssh_get_authentication_socket(&auth_sock);
511 error_r(r, "Could not get agent socket");
516 ssh_sandbox_parent_preauth(box, pid);
517 monitor_child_preauth(ssh, pmonitor);
519 /* Wait for the child's exit status */
520 while (waitpid(pid, &status, 0) == -1) {
523 pmonitor->m_pid = -1;
524 fatal_f("waitpid: %s", strerror(errno));
526 privsep_is_preauth = 0;
527 pmonitor->m_pid = -1;
528 if (WIFEXITED(status)) {
529 if (WEXITSTATUS(status) != 0)
530 fatal_f("preauth child exited with status %d",
531 WEXITSTATUS(status));
532 } else if (WIFSIGNALED(status))
533 fatal_f("preauth child terminated by signal %d",
536 ssh_sandbox_parent_finish(box);
540 close(pmonitor->m_sendfd);
541 close(pmonitor->m_log_recvfd);
543 /* Arrange for logging to be sent to the monitor */
544 set_log_handler(mm_log_handler, pmonitor);
546 privsep_preauth_child();
547 setproctitle("%s", "[net]");
549 ssh_sandbox_child(box);
556 privsep_postauth(struct ssh *ssh, Authctxt *authctxt)
558 #ifdef DISABLE_FD_PASSING
561 if (authctxt->pw->pw_uid == 0) {
563 /* File descriptor passing is broken or root login */
568 /* New socket pair */
569 monitor_reinit(pmonitor);
571 pmonitor->m_pid = fork();
572 if (pmonitor->m_pid == -1)
573 fatal("fork of unprivileged child failed");
574 else if (pmonitor->m_pid != 0) {
575 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
576 sshbuf_reset(loginmsg);
577 monitor_clear_keystate(ssh, pmonitor);
578 monitor_child_postauth(ssh, pmonitor);
586 close(pmonitor->m_sendfd);
587 pmonitor->m_sendfd = -1;
589 /* Demote the private keys to public keys. */
590 demote_sensitive_data();
594 /* Drop privileges */
595 do_setusercontext(authctxt->pw);
598 /* It is safe now to apply the key state */
599 monitor_apply_keystate(ssh, pmonitor);
602 * Tell the packet layer that authentication was successful, since
603 * this information is not part of the key state.
605 ssh_packet_set_authenticated(ssh);
609 append_hostkey_type(struct sshbuf *b, const char *s)
613 if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
614 debug3_f("%s key not permitted by HostkeyAlgorithms", s);
617 if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
618 fatal_fr(r, "sshbuf_putf");
622 list_hostkey_types(void)
629 if ((b = sshbuf_new()) == NULL)
630 fatal_f("sshbuf_new failed");
631 for (i = 0; i < options.num_host_key_files; i++) {
632 key = sensitive_data.host_keys[i];
634 key = sensitive_data.host_pubkeys[i];
639 /* for RSA we also support SHA2 signatures */
640 append_hostkey_type(b, "rsa-sha2-512");
641 append_hostkey_type(b, "rsa-sha2-256");
649 append_hostkey_type(b, sshkey_ssh_name(key));
652 /* If the private key has a cert peer, then list that too */
653 key = sensitive_data.host_certificates[i];
658 /* for RSA we also support SHA2 signatures */
659 append_hostkey_type(b,
660 "rsa-sha2-512-cert-v01@openssh.com");
661 append_hostkey_type(b,
662 "rsa-sha2-256-cert-v01@openssh.com");
666 case KEY_ED25519_CERT:
667 case KEY_ECDSA_SK_CERT:
668 case KEY_ED25519_SK_CERT:
670 append_hostkey_type(b, sshkey_ssh_name(key));
674 if ((ret = sshbuf_dup_string(b)) == NULL)
675 fatal_f("sshbuf_dup_string failed");
681 static struct sshkey *
682 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
687 for (i = 0; i < options.num_host_key_files; i++) {
692 case KEY_ED25519_CERT:
693 case KEY_ECDSA_SK_CERT:
694 case KEY_ED25519_SK_CERT:
696 key = sensitive_data.host_certificates[i];
699 key = sensitive_data.host_keys[i];
700 if (key == NULL && !need_private)
701 key = sensitive_data.host_pubkeys[i];
704 if (key == NULL || key->type != type)
710 case KEY_ECDSA_SK_CERT:
711 if (key->ecdsa_nid != nid)
715 return need_private ?
716 sensitive_data.host_keys[i] : key;
723 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
725 return get_hostkey_by_type(type, nid, 0, ssh);
729 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
731 return get_hostkey_by_type(type, nid, 1, ssh);
735 get_hostkey_by_index(int ind)
737 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
739 return (sensitive_data.host_keys[ind]);
743 get_hostkey_public_by_index(int ind, struct ssh *ssh)
745 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
747 return (sensitive_data.host_pubkeys[ind]);
751 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
755 for (i = 0; i < options.num_host_key_files; i++) {
756 if (sshkey_is_cert(key)) {
757 if (key == sensitive_data.host_certificates[i] ||
758 (compare && sensitive_data.host_certificates[i] &&
760 sensitive_data.host_certificates[i])))
763 if (key == sensitive_data.host_keys[i] ||
764 (compare && sensitive_data.host_keys[i] &&
765 sshkey_equal(key, sensitive_data.host_keys[i])))
767 if (key == sensitive_data.host_pubkeys[i] ||
768 (compare && sensitive_data.host_pubkeys[i] &&
769 sshkey_equal(key, sensitive_data.host_pubkeys[i])))
776 /* Inform the client of all hostkeys */
778 notify_hostkeys(struct ssh *ssh)
786 /* Some clients cannot cope with the hostkeys message, skip those. */
787 if (ssh->compat & SSH_BUG_HOSTKEYS)
790 if ((buf = sshbuf_new()) == NULL)
791 fatal_f("sshbuf_new");
792 for (i = nkeys = 0; i < options.num_host_key_files; i++) {
793 key = get_hostkey_public_by_index(i, ssh);
794 if (key == NULL || key->type == KEY_UNSPEC ||
797 fp = sshkey_fingerprint(key, options.fingerprint_hash,
799 debug3_f("key %d: %s %s", i, sshkey_ssh_name(key), fp);
803 * Start building the request when we find the
806 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
807 (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 ||
808 (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */
809 sshpkt_fatal(ssh, r, "%s: start request", __func__);
811 /* Append the key to the request */
813 if ((r = sshkey_putb(key, buf)) != 0)
814 fatal_fr(r, "couldn't put hostkey %d", i);
815 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
816 sshpkt_fatal(ssh, r, "%s: append key", __func__);
819 debug3_f("sent %u hostkeys", nkeys);
821 fatal_f("no hostkeys");
822 if ((r = sshpkt_send(ssh)) != 0)
823 sshpkt_fatal(ssh, r, "%s: send", __func__);
828 * returns 1 if connection should be dropped, 0 otherwise.
829 * dropping starts at connection #max_startups_begin with a probability
830 * of (max_startups_rate/100). the probability increases linearly until
831 * all connections are dropped for startups > max_startups
834 should_drop_connection(int startups)
838 if (startups < options.max_startups_begin)
840 if (startups >= options.max_startups)
842 if (options.max_startups_rate == 100)
845 p = 100 - options.max_startups_rate;
846 p *= startups - options.max_startups_begin;
847 p /= options.max_startups - options.max_startups_begin;
848 p += options.max_startups_rate;
849 r = arc4random_uniform(100);
851 debug_f("p %d, r %d", p, r);
852 return (r < p) ? 1 : 0;
856 * Check whether connection should be accepted by MaxStartups.
857 * Returns 0 if the connection is accepted. If the connection is refused,
858 * returns 1 and attempts to send notification to client.
859 * Logs when the MaxStartups condition is entered or exited, and periodically
860 * while in that state.
863 drop_connection(int sock, int startups, int notify_pipe)
866 const char msg[] = "Exceeded MaxStartups\r\n";
867 static time_t last_drop, first_drop;
868 static u_int ndropped;
869 LogLevel drop_level = SYSLOG_LEVEL_VERBOSE;
873 if (!should_drop_connection(startups) &&
874 srclimit_check_allow(sock, notify_pipe) == 1) {
875 if (last_drop != 0 &&
876 startups < options.max_startups_begin - 1) {
877 /* XXX maybe need better hysteresis here */
878 logit("exited MaxStartups throttling after %s, "
879 "%u connections dropped",
880 fmt_timeframe(now - first_drop), ndropped);
886 #define SSHD_MAXSTARTUPS_LOG_INTERVAL (5 * 60)
887 if (last_drop == 0) {
888 error("beginning MaxStartups throttling");
889 drop_level = SYSLOG_LEVEL_INFO;
892 } else if (last_drop + SSHD_MAXSTARTUPS_LOG_INTERVAL < now) {
894 error("in MaxStartups throttling for %s, "
895 "%u connections dropped",
896 fmt_timeframe(now - first_drop), ndropped + 1);
897 drop_level = SYSLOG_LEVEL_INFO;
902 laddr = get_local_ipaddr(sock);
903 raddr = get_peer_ipaddr(sock);
904 do_log2(drop_level, "drop connection #%d from [%s]:%d on [%s]:%d "
905 "past MaxStartups", startups, raddr, get_peer_port(sock),
906 laddr, get_local_port(sock));
909 /* best-effort notification to client */
910 (void)write(sock, msg, sizeof(msg) - 1);
917 if (options.version_addendum != NULL &&
918 *options.version_addendum != '\0')
919 fprintf(stderr, "%s %s, %s\n",
921 options.version_addendum, SSH_OPENSSL_VERSION);
923 fprintf(stderr, "%s, %s\n",
924 SSH_RELEASE, SSH_OPENSSL_VERSION);
926 "usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n"
927 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
928 " [-h host_key_file] [-o option] [-p port] [-u len]\n"
934 send_rexec_state(int fd, struct sshbuf *conf)
936 struct sshbuf *m = NULL, *inc = NULL;
937 struct include_item *item = NULL;
940 debug3_f("entering fd = %d config len %zu", fd,
943 if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
944 fatal_f("sshbuf_new failed");
946 /* pack includes into a string */
947 TAILQ_FOREACH(item, &includes, entry) {
948 if ((r = sshbuf_put_cstring(inc, item->selector)) != 0 ||
949 (r = sshbuf_put_cstring(inc, item->filename)) != 0 ||
950 (r = sshbuf_put_stringb(inc, item->contents)) != 0)
951 fatal_fr(r, "compose includes");
955 * Protocol from reexec master to child:
956 * string configuration
957 * string included_files[] {
963 if ((r = sshbuf_put_stringb(m, conf)) != 0 ||
964 (r = sshbuf_put_stringb(m, inc)) != 0)
965 fatal_fr(r, "compose config");
966 if (ssh_msg_send(fd, 0, m) == -1)
967 error_f("ssh_msg_send failed");
976 recv_rexec_state(int fd, struct sshbuf *conf)
978 struct sshbuf *m, *inc;
982 struct include_item *item;
984 debug3_f("entering fd = %d", fd);
986 if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
987 fatal_f("sshbuf_new failed");
988 if (ssh_msg_recv(fd, m) == -1)
989 fatal_f("ssh_msg_recv failed");
990 if ((r = sshbuf_get_u8(m, &ver)) != 0)
991 fatal_fr(r, "parse version");
993 fatal_f("rexec version mismatch");
994 if ((r = sshbuf_get_string(m, &cp, &len)) != 0 ||
995 (r = sshbuf_get_stringb(m, inc)) != 0)
996 fatal_fr(r, "parse config");
998 if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
999 fatal_fr(r, "sshbuf_put");
1001 while (sshbuf_len(inc) != 0) {
1002 item = xcalloc(1, sizeof(*item));
1003 if ((item->contents = sshbuf_new()) == NULL)
1004 fatal_f("sshbuf_new failed");
1005 if ((r = sshbuf_get_cstring(inc, &item->selector, NULL)) != 0 ||
1006 (r = sshbuf_get_cstring(inc, &item->filename, NULL)) != 0 ||
1007 (r = sshbuf_get_stringb(inc, item->contents)) != 0)
1008 fatal_fr(r, "parse includes");
1009 TAILQ_INSERT_TAIL(&includes, item, entry);
1018 /* Accept a connection from inetd */
1020 server_accept_inetd(int *sock_in, int *sock_out)
1023 close(REEXEC_CONFIG_PASS_FD);
1024 *sock_in = *sock_out = dup(STDIN_FILENO);
1026 *sock_in = dup(STDIN_FILENO);
1027 *sock_out = dup(STDOUT_FILENO);
1030 * We intentionally do not close the descriptors 0, 1, and 2
1031 * as our code for setting the descriptors won't work if
1032 * ttyfd happens to be one of those.
1034 if (stdfd_devnull(1, 1, !log_stderr) == -1)
1035 error_f("stdfd_devnull failed");
1036 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1040 * Listen for TCP connections
1043 listen_on_addrs(struct listenaddr *la)
1045 int ret, listen_sock;
1046 struct addrinfo *ai;
1047 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1049 for (ai = la->addrs; ai; ai = ai->ai_next) {
1050 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1052 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1053 fatal("Too many listen sockets. "
1054 "Enlarge MAX_LISTEN_SOCKS");
1055 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1056 ntop, sizeof(ntop), strport, sizeof(strport),
1057 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1058 error("getnameinfo failed: %.100s",
1059 ssh_gai_strerror(ret));
1062 /* Create socket for listening. */
1063 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1065 if (listen_sock == -1) {
1066 /* kernel may not support ipv6 */
1067 verbose("socket: %.100s", strerror(errno));
1070 if (set_nonblock(listen_sock) == -1) {
1074 if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
1075 verbose("socket: CLOEXEC: %s", strerror(errno));
1079 /* Socket options */
1080 set_reuseaddr(listen_sock);
1081 if (la->rdomain != NULL &&
1082 set_rdomain(listen_sock, la->rdomain) == -1) {
1087 /* Only communicate in IPv6 over AF_INET6 sockets. */
1088 if (ai->ai_family == AF_INET6)
1089 sock_set_v6only(listen_sock);
1091 debug("Bind to port %s on %s.", strport, ntop);
1093 /* Bind the socket to the desired port. */
1094 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) {
1095 error("Bind to port %s on %s failed: %.200s.",
1096 strport, ntop, strerror(errno));
1100 listen_socks[num_listen_socks] = listen_sock;
1103 /* Start listening on the port. */
1104 if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1)
1105 fatal("listen on [%s]:%s: %.100s",
1106 ntop, strport, strerror(errno));
1107 logit("Server listening on %s port %s%s%s.",
1109 la->rdomain == NULL ? "" : " rdomain ",
1110 la->rdomain == NULL ? "" : la->rdomain);
1119 /* Initialise per-source limit tracking. */
1120 srclimit_init(options.max_startups, options.per_source_max_startups,
1121 options.per_source_masklen_ipv4, options.per_source_masklen_ipv6);
1123 for (i = 0; i < options.num_listen_addrs; i++) {
1124 listen_on_addrs(&options.listen_addrs[i]);
1125 freeaddrinfo(options.listen_addrs[i].addrs);
1126 free(options.listen_addrs[i].rdomain);
1127 memset(&options.listen_addrs[i], 0,
1128 sizeof(options.listen_addrs[i]));
1130 free(options.listen_addrs);
1131 options.listen_addrs = NULL;
1132 options.num_listen_addrs = 0;
1134 if (!num_listen_socks)
1135 fatal("Cannot bind any address.");
1139 * The main TCP accept loop. Note that, for the non-debug case, returns
1140 * from this function are in a forked subprocess.
1143 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1145 struct pollfd *pfd = NULL;
1146 int i, j, ret, npfd;
1147 int ostartups = -1, startups = 0, listening = 0, lameduck = 0;
1148 int startup_p[2] = { -1 , -1 }, *startup_pollfd;
1150 struct sockaddr_storage from;
1154 sigset_t nsigset, osigset;
1156 struct request_info req;
1158 request_init(&req, RQ_DAEMON, __progname, 0);
1161 /* pipes connected to unauthenticated child sshd processes */
1162 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1163 startup_flags = xcalloc(options.max_startups, sizeof(int));
1164 startup_pollfd = xcalloc(options.max_startups, sizeof(int));
1165 for (i = 0; i < options.max_startups; i++)
1166 startup_pipes[i] = -1;
1169 * Prepare signal mask that we use to block signals that might set
1170 * received_sigterm or received_sighup, so that we are guaranteed
1171 * to immediately wake up the ppoll if a signal is received after
1172 * the flag is checked.
1174 sigemptyset(&nsigset);
1175 sigaddset(&nsigset, SIGHUP);
1176 sigaddset(&nsigset, SIGCHLD);
1177 sigaddset(&nsigset, SIGTERM);
1178 sigaddset(&nsigset, SIGQUIT);
1180 /* sized for worst-case */
1181 pfd = xcalloc(num_listen_socks + options.max_startups,
1182 sizeof(struct pollfd));
1185 * Stay listening for connections until the system crashes or
1186 * the daemon is killed with a signal.
1189 sigprocmask(SIG_BLOCK, &nsigset, &osigset);
1190 if (received_sigterm) {
1191 logit("Received signal %d; terminating.",
1192 (int) received_sigterm);
1193 close_listen_socks();
1194 if (options.pid_file != NULL)
1195 unlink(options.pid_file);
1196 exit(received_sigterm == SIGTERM ? 0 : 255);
1198 if (ostartups != startups) {
1199 setproctitle("%s [listener] %d of %d-%d startups",
1200 listener_proctitle, startups,
1201 options.max_startups_begin, options.max_startups);
1202 ostartups = startups;
1204 if (received_sighup) {
1206 debug("Received SIGHUP; waiting for children");
1207 close_listen_socks();
1210 if (listening <= 0) {
1211 sigprocmask(SIG_SETMASK, &osigset, NULL);
1216 for (i = 0; i < num_listen_socks; i++) {
1217 pfd[i].fd = listen_socks[i];
1218 pfd[i].events = POLLIN;
1220 npfd = num_listen_socks;
1221 for (i = 0; i < options.max_startups; i++) {
1222 startup_pollfd[i] = -1;
1223 if (startup_pipes[i] != -1) {
1224 pfd[npfd].fd = startup_pipes[i];
1225 pfd[npfd].events = POLLIN;
1226 startup_pollfd[i] = npfd++;
1230 /* Wait until a connection arrives or a child exits. */
1231 ret = ppoll(pfd, npfd, NULL, &osigset);
1232 if (ret == -1 && errno != EINTR) {
1233 error("ppoll: %.100s", strerror(errno));
1234 if (errno == EINVAL)
1235 cleanup_exit(1); /* can't recover */
1237 sigprocmask(SIG_SETMASK, &osigset, NULL);
1241 for (i = 0; i < options.max_startups; i++) {
1242 if (startup_pipes[i] == -1 ||
1243 startup_pollfd[i] == -1 ||
1244 !(pfd[startup_pollfd[i]].revents & (POLLIN|POLLHUP)))
1246 switch (read(startup_pipes[i], &c, sizeof(c))) {
1248 if (errno == EINTR || errno == EAGAIN)
1250 if (errno != EPIPE) {
1251 error_f("startup pipe %d (fd=%d): "
1252 "read %s", i, startup_pipes[i],
1257 /* child exited or completed auth */
1258 close(startup_pipes[i]);
1259 srclimit_done(startup_pipes[i]);
1260 startup_pipes[i] = -1;
1262 if (startup_flags[i])
1266 /* child has finished preliminaries */
1267 if (startup_flags[i]) {
1269 startup_flags[i] = 0;
1274 for (i = 0; i < num_listen_socks; i++) {
1275 if (!(pfd[i].revents & POLLIN))
1277 fromlen = sizeof(from);
1278 *newsock = accept(listen_socks[i],
1279 (struct sockaddr *)&from, &fromlen);
1280 if (*newsock == -1) {
1281 if (errno != EINTR && errno != EWOULDBLOCK &&
1282 errno != ECONNABORTED && errno != EAGAIN)
1283 error("accept: %.100s",
1285 if (errno == EMFILE || errno == ENFILE)
1290 /* Check whether logins are denied from this host. */
1291 request_set(&req, RQ_FILE, *newsock,
1292 RQ_CLIENT_NAME, "", RQ_CLIENT_ADDR, "", 0);
1294 if (!hosts_access(&req)) {
1295 const struct linger l = { .l_onoff = 1,
1298 (void )setsockopt(*newsock, SOL_SOCKET,
1299 SO_LINGER, &l, sizeof(l));
1300 (void )close(*newsock);
1302 * Mimic message from libwrap's refuse()
1303 * exactly. sshguard, and supposedly lots
1304 * of custom made scripts rely on it.
1306 syslog(deny_severity,
1307 "refused connect from %s (%s)",
1309 eval_hostaddr(req.client));
1310 debug("Connection refused by tcp wrapper");
1313 #endif /* LIBWRAP */
1314 if (unset_nonblock(*newsock) == -1) {
1318 if (pipe(startup_p) == -1) {
1319 error_f("pipe(startup_p): %s", strerror(errno));
1323 if (drop_connection(*newsock, startups, startup_p[0])) {
1325 close(startup_p[0]);
1326 close(startup_p[1]);
1330 if (rexec_flag && socketpair(AF_UNIX,
1331 SOCK_STREAM, 0, config_s) == -1) {
1332 error("reexec socketpair: %s",
1335 close(startup_p[0]);
1336 close(startup_p[1]);
1340 for (j = 0; j < options.max_startups; j++)
1341 if (startup_pipes[j] == -1) {
1342 startup_pipes[j] = startup_p[0];
1344 startup_flags[j] = 1;
1349 * Got connection. Fork a child to handle it, unless
1350 * we are in debugging mode.
1354 * In debugging mode. Close the listening
1355 * socket, and start processing the
1356 * connection without forking.
1358 debug("Server will not fork when running in debugging mode.");
1359 close_listen_socks();
1360 *sock_in = *newsock;
1361 *sock_out = *newsock;
1362 close(startup_p[0]);
1363 close(startup_p[1]);
1367 send_rexec_state(config_s[0], cfg);
1375 * Normal production daemon. Fork, and have
1376 * the child process the connection. The
1377 * parent continues listening.
1379 platform_pre_fork();
1381 if ((pid = fork()) == 0) {
1383 * Child. Close the listening and
1384 * max_startup sockets. Start using
1385 * the accepted socket. Reinitialize
1386 * logging (since our pid has changed).
1387 * We return from this function to handle
1390 platform_post_fork_child();
1391 startup_pipe = startup_p[1];
1392 close_startup_pipes();
1393 close_listen_socks();
1394 *sock_in = *newsock;
1395 *sock_out = *newsock;
1396 log_init(__progname,
1398 options.log_facility,
1404 * Signal parent that the preliminaries
1405 * for this child are complete. For the
1406 * re-exec case, this happens after the
1407 * child has received the rexec state
1410 (void)atomicio(vwrite, startup_pipe,
1417 /* Parent. Stay in the loop. */
1418 platform_post_fork_parent(pid);
1420 error("fork: %.100s", strerror(errno));
1422 debug("Forked child %ld.", (long)pid);
1424 close(startup_p[1]);
1428 send_rexec_state(config_s[0], cfg);
1434 * Ensure that our random state differs
1435 * from that of the child
1438 arc4random_buf(rnd, sizeof(rnd));
1440 RAND_seed(rnd, sizeof(rnd));
1441 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1442 fatal("%s: RAND_bytes failed", __func__);
1444 explicit_bzero(rnd, sizeof(rnd));
1450 * If IP options are supported, make sure there are none (log and
1451 * return an error if any are found). Basically we are worried about
1452 * source routing; it can be used to pretend you are somebody
1453 * (ip-address) you are not. That itself may be "almost acceptable"
1454 * under certain circumstances, but rhosts authentication is useless
1455 * if source routing is accepted. Notice also that if we just dropped
1456 * source routing here, the other side could use IP spoofing to do
1457 * rest of the interaction and could still bypass security. So we
1458 * exit here if we detect any IP options.
1461 check_ip_options(struct ssh *ssh)
1464 int sock_in = ssh_packet_get_connection_in(ssh);
1465 struct sockaddr_storage from;
1467 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1468 char text[sizeof(opts) * 3 + 1];
1470 memset(&from, 0, sizeof(from));
1471 if (getpeername(sock_in, (struct sockaddr *)&from,
1474 if (from.ss_family != AF_INET)
1476 /* XXX IPv6 options? */
1478 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1479 &option_size) >= 0 && option_size != 0) {
1481 for (i = 0; i < option_size; i++)
1482 snprintf(text + i*3, sizeof(text) - i*3,
1484 fatal("Connection from %.100s port %d with IP opts: %.800s",
1485 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1488 #endif /* IP_OPTIONS */
1491 /* Set the routing domain for this process */
1493 set_process_rdomain(struct ssh *ssh, const char *name)
1495 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
1497 return; /* default */
1499 if (strcmp(name, "%D") == 0) {
1500 /* "expands" to routing domain of connection */
1501 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1504 /* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
1505 return sys_set_process_rdomain(name);
1506 #elif defined(__OpenBSD__)
1507 int rtable, ortable = getrtable();
1511 return; /* default */
1513 if (strcmp(name, "%D") == 0) {
1514 /* "expands" to routing domain of connection */
1515 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1519 rtable = (int)strtonum(name, 0, 255, &errstr);
1520 if (errstr != NULL) /* Shouldn't happen */
1521 fatal("Invalid routing domain \"%s\": %s", name, errstr);
1522 if (rtable != ortable && setrtable(rtable) != 0)
1523 fatal("Unable to set routing domain %d: %s",
1524 rtable, strerror(errno));
1525 debug_f("set routing domain %d (was %d)", rtable, ortable);
1526 #else /* defined(__OpenBSD__) */
1527 fatal("Unable to set routing domain: not supported in this platform");
1532 accumulate_host_timing_secret(struct sshbuf *server_cfg,
1535 static struct ssh_digest_ctx *ctx;
1541 if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
1542 fatal_f("ssh_digest_start");
1543 if (key == NULL) { /* finalize */
1544 /* add server config in case we are using agent for host keys */
1545 if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
1546 sshbuf_len(server_cfg)) != 0)
1547 fatal_f("ssh_digest_update");
1548 len = ssh_digest_bytes(SSH_DIGEST_SHA512);
1549 hash = xmalloc(len);
1550 if (ssh_digest_final(ctx, hash, len) != 0)
1551 fatal_f("ssh_digest_final");
1552 options.timing_secret = PEEK_U64(hash);
1553 freezero(hash, len);
1554 ssh_digest_free(ctx);
1558 if ((buf = sshbuf_new()) == NULL)
1559 fatal_f("could not allocate buffer");
1560 if ((r = sshkey_private_serialize(key, buf)) != 0)
1561 fatal_fr(r, "encode %s key", sshkey_ssh_name(key));
1562 if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
1563 fatal_f("ssh_digest_update");
1569 prepare_proctitle(int ac, char **av)
1574 for (i = 0; i < ac; i++)
1575 xextendf(&ret, " ", "%s", av[i]);
1580 print_config(struct ssh *ssh, struct connection_info *connection_info)
1583 * If no connection info was provided by -C then use
1584 * use a blank one that will cause no predicate to match.
1586 if (connection_info == NULL)
1587 connection_info = get_connection_info(ssh, 0, 0);
1588 connection_info->test = 1;
1589 parse_server_match_config(&options, &includes, connection_info);
1590 dump_config(&options);
1595 * Main program for the daemon.
1598 main(int ac, char **av)
1600 struct ssh *ssh = NULL;
1601 extern char *optarg;
1603 int r, opt, on = 1, do_dump_cfg = 0, already_daemon, remote_port;
1604 int sock_in = -1, sock_out = -1, newsock = -1;
1605 const char *remote_ip, *rdomain;
1606 char *fp, *line, *laddr, *logfile = NULL;
1607 int config_s[2] = { -1 , -1 };
1609 u_int64_t ibytes, obytes;
1612 struct sshkey *pubkey;
1615 struct connection_info *connection_info = NULL;
1618 #ifdef HAVE_SECUREWARE
1619 (void)set_auth_parameters(ac, av);
1621 __progname = ssh_get_progname(av[0]);
1623 sigemptyset(&sigmask);
1624 sigprocmask(SIG_SETMASK, &sigmask, NULL);
1626 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1629 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1630 for (i = 0; (int)i < ac; i++)
1631 saved_argv[i] = xstrdup(av[i]);
1632 saved_argv[i] = NULL;
1634 #ifndef HAVE_SETPROCTITLE
1635 /* Prepare for later setproctitle emulation */
1636 compat_init_setproctitle(ac, av);
1640 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1641 debug("setgroups(): %.200s", strerror(errno));
1643 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1646 /* Initialize configuration options to their default values. */
1647 initialize_server_options(&options);
1649 /* Parse command-line arguments. */
1650 while ((opt = getopt(ac, av,
1651 "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) {
1654 options.address_family = AF_INET;
1657 options.address_family = AF_INET6;
1660 config_file_name = optarg;
1663 servconf_add_hostcert("[command-line]", 0,
1667 if (debug_flag == 0) {
1669 options.log_level = SYSLOG_LEVEL_DEBUG1;
1670 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1671 options.log_level++;
1699 options.log_level = SYSLOG_LEVEL_QUIET;
1702 /* protocol 1, ignored */
1705 options.ports_from_cmdline = 1;
1706 if (options.num_ports >= MAX_PORTS) {
1707 fprintf(stderr, "too many ports.\n");
1710 options.ports[options.num_ports++] = a2port(optarg);
1711 if (options.ports[options.num_ports-1] <= 0) {
1712 fprintf(stderr, "Bad port number.\n");
1717 if ((options.login_grace_time = convtime(optarg)) == -1) {
1718 fprintf(stderr, "Invalid login grace time.\n");
1723 /* protocol 1, ignored */
1726 servconf_add_hostkey("[command-line]", 0,
1727 &options, optarg, 1);
1736 connection_info = get_connection_info(ssh, 0, 0);
1737 if (parse_server_match_testspec(connection_info,
1742 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1743 if (utmp_len > HOST_NAME_MAX+1) {
1744 fprintf(stderr, "Invalid utmp length.\n");
1749 line = xstrdup(optarg);
1750 if (process_server_config_line(&options, line,
1751 "command-line", 0, NULL, NULL, &includes) != 0)
1756 fprintf(stderr, "%s, %s\n",
1757 SSH_VERSION, SSH_OPENSSL_VERSION);
1764 if (rexeced_flag || inetd_flag)
1766 if (!test_flag && !do_dump_cfg && rexec_flag && !path_absolute(av[0]))
1767 fatal("sshd re-exec requires execution with an absolute path");
1769 closefrom(REEXEC_MIN_FREE_FD);
1771 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1775 /* If requested, redirect the logs to the specified logfile. */
1776 if (logfile != NULL)
1777 log_redirect_stderr_to(logfile);
1779 * Force logging to stderr until we have loaded the private host
1780 * key (unless started from inetd)
1782 log_init(__progname,
1783 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1784 SYSLOG_LEVEL_INFO : options.log_level,
1785 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1786 SYSLOG_FACILITY_AUTH : options.log_facility,
1787 log_stderr || !inetd_flag || debug_flag);
1790 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1791 * root's environment
1793 if (getenv("KRB5CCNAME") != NULL)
1794 (void) unsetenv("KRB5CCNAME");
1796 sensitive_data.have_ssh2_key = 0;
1799 * If we're not doing an extended test do not silently ignore connection
1802 if (test_flag < 2 && connection_info != NULL)
1803 fatal("Config test connection parameter (-C) provided without "
1806 /* Fetch our configuration */
1807 if ((cfg = sshbuf_new()) == NULL)
1808 fatal_f("sshbuf_new failed");
1810 setproctitle("%s", "[rexeced]");
1811 recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg);
1813 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1814 close(REEXEC_STARTUP_PIPE_FD);
1816 * Signal parent that this child is at a point where
1817 * they can go away if they have a SIGHUP pending.
1819 (void)atomicio(vwrite, startup_pipe, "\0", 1);
1821 } else if (strcasecmp(config_file_name, "none") != 0)
1822 load_server_config(config_file_name, cfg);
1824 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1825 cfg, &includes, NULL, rexeced_flag);
1828 if (options.moduli_file != NULL)
1829 dh_set_moduli_file(options.moduli_file);
1832 /* Fill in default values for those options not explicitly set. */
1833 fill_default_server_options(&options);
1835 /* Check that options are sensible */
1836 if (options.authorized_keys_command_user == NULL &&
1837 (options.authorized_keys_command != NULL &&
1838 strcasecmp(options.authorized_keys_command, "none") != 0))
1839 fatal("AuthorizedKeysCommand set without "
1840 "AuthorizedKeysCommandUser");
1841 if (options.authorized_principals_command_user == NULL &&
1842 (options.authorized_principals_command != NULL &&
1843 strcasecmp(options.authorized_principals_command, "none") != 0))
1844 fatal("AuthorizedPrincipalsCommand set without "
1845 "AuthorizedPrincipalsCommandUser");
1848 * Check whether there is any path through configured auth methods.
1849 * Unfortunately it is not possible to verify this generally before
1850 * daemonisation in the presence of Match block, but this catches
1851 * and warns for trivial misconfigurations that could break login.
1853 if (options.num_auth_methods != 0) {
1854 for (i = 0; i < options.num_auth_methods; i++) {
1855 if (auth2_methods_valid(options.auth_methods[i],
1859 if (i >= options.num_auth_methods)
1860 fatal("AuthenticationMethods cannot be satisfied by "
1861 "enabled authentication methods");
1864 /* Check that there are no remaining arguments. */
1866 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1870 debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1873 print_config(ssh, connection_info);
1875 /* Store privilege separation user for later use if required. */
1876 privsep_chroot = use_privsep && (getuid() == 0 || geteuid() == 0);
1877 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1878 if (privsep_chroot || options.kerberos_authentication)
1879 fatal("Privilege separation user %s does not exist",
1882 privsep_pw = pwcopy(privsep_pw);
1883 freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
1884 privsep_pw->pw_passwd = xstrdup("*");
1888 /* load host keys */
1889 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1890 sizeof(struct sshkey *));
1891 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1892 sizeof(struct sshkey *));
1894 if (options.host_key_agent) {
1895 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1896 setenv(SSH_AUTHSOCKET_ENV_NAME,
1897 options.host_key_agent, 1);
1898 if ((r = ssh_get_authentication_socket(NULL)) == 0)
1901 error_r(r, "Could not connect to agent \"%s\"",
1902 options.host_key_agent);
1905 for (i = 0; i < options.num_host_key_files; i++) {
1906 int ll = options.host_key_file_userprovided[i] ?
1907 SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
1909 if (options.host_key_files[i] == NULL)
1911 if ((r = sshkey_load_private(options.host_key_files[i], "",
1912 &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1913 do_log2_r(r, ll, "Unable to load host key \"%s\"",
1914 options.host_key_files[i]);
1915 if (sshkey_is_sk(key) &&
1916 key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
1917 debug("host key %s requires user presence, ignoring",
1918 options.host_key_files[i]);
1919 key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
1921 if (r == 0 && key != NULL &&
1922 (r = sshkey_shield_private(key)) != 0) {
1923 do_log2_r(r, ll, "Unable to shield host key \"%s\"",
1924 options.host_key_files[i]);
1928 if ((r = sshkey_load_public(options.host_key_files[i],
1929 &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1930 do_log2_r(r, ll, "Unable to load host key \"%s\"",
1931 options.host_key_files[i]);
1932 if (pubkey != NULL && key != NULL) {
1933 if (!sshkey_equal(pubkey, key)) {
1934 error("Public key for %s does not match "
1935 "private key", options.host_key_files[i]);
1936 sshkey_free(pubkey);
1940 if (pubkey == NULL && key != NULL) {
1941 if ((r = sshkey_from_private(key, &pubkey)) != 0)
1942 fatal_r(r, "Could not demote key: \"%s\"",
1943 options.host_key_files[i]);
1945 if (pubkey != NULL && (r = sshkey_check_rsa_length(pubkey,
1946 options.required_rsa_size)) != 0) {
1947 error_fr(r, "Host key %s", options.host_key_files[i]);
1948 sshkey_free(pubkey);
1952 sensitive_data.host_keys[i] = key;
1953 sensitive_data.host_pubkeys[i] = pubkey;
1955 if (key == NULL && pubkey != NULL && have_agent) {
1956 debug("will rely on agent for hostkey %s",
1957 options.host_key_files[i]);
1958 keytype = pubkey->type;
1959 } else if (key != NULL) {
1960 keytype = key->type;
1961 accumulate_host_timing_secret(cfg, key);
1963 do_log2(ll, "Unable to load host key: %s",
1964 options.host_key_files[i]);
1965 sensitive_data.host_keys[i] = NULL;
1966 sensitive_data.host_pubkeys[i] = NULL;
1976 case KEY_ED25519_SK:
1978 if (have_agent || key != NULL)
1979 sensitive_data.have_ssh2_key = 1;
1982 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1983 SSH_FP_DEFAULT)) == NULL)
1984 fatal("sshkey_fingerprint failed");
1985 debug("%s host key #%d: %s %s",
1986 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1989 accumulate_host_timing_secret(cfg, NULL);
1990 if (!sensitive_data.have_ssh2_key) {
1991 logit("sshd: no hostkeys available -- exiting.");
1996 * Load certificates. They are stored in an array at identical
1997 * indices to the public keys that they relate to.
1999 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
2000 sizeof(struct sshkey *));
2001 for (i = 0; i < options.num_host_key_files; i++)
2002 sensitive_data.host_certificates[i] = NULL;
2004 for (i = 0; i < options.num_host_cert_files; i++) {
2005 if (options.host_cert_files[i] == NULL)
2007 if ((r = sshkey_load_public(options.host_cert_files[i],
2008 &key, NULL)) != 0) {
2009 error_r(r, "Could not load host certificate \"%s\"",
2010 options.host_cert_files[i]);
2013 if (!sshkey_is_cert(key)) {
2014 error("Certificate file is not a certificate: %s",
2015 options.host_cert_files[i]);
2019 /* Find matching private key */
2020 for (j = 0; j < options.num_host_key_files; j++) {
2021 if (sshkey_equal_public(key,
2022 sensitive_data.host_pubkeys[j])) {
2023 sensitive_data.host_certificates[j] = key;
2027 if (j >= options.num_host_key_files) {
2028 error("No matching private key for certificate: %s",
2029 options.host_cert_files[i]);
2033 sensitive_data.host_certificates[j] = key;
2034 debug("host certificate: #%u type %d %s", j, key->type,
2038 if (privsep_chroot) {
2041 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
2042 (S_ISDIR(st.st_mode) == 0))
2043 fatal("Missing privilege separation directory: %s",
2044 _PATH_PRIVSEP_CHROOT_DIR);
2047 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
2048 (st.st_uid != getuid () ||
2049 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
2051 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
2053 fatal("%s must be owned by root and not group or "
2054 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
2058 print_config(ssh, connection_info);
2060 /* Configuration looks good, so exit if in test mode. */
2065 * Clear out any supplemental groups we may have inherited. This
2066 * prevents inadvertent creation of files with bad modes (in the
2067 * portable version at least, it's certainly possible for PAM
2068 * to create a file, and we can't control the code in every
2069 * module which might be used).
2071 if (setgroups(0, NULL) < 0)
2072 debug("setgroups() failed: %.200s", strerror(errno));
2076 fatal("rexec_argc %d < 0", rexec_argc);
2077 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
2078 for (i = 0; i < (u_int)rexec_argc; i++) {
2079 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
2080 rexec_argv[i] = saved_argv[i];
2082 rexec_argv[rexec_argc] = "-R";
2083 rexec_argv[rexec_argc + 1] = NULL;
2085 listener_proctitle = prepare_proctitle(ac, av);
2087 /* Ensure that umask disallows at least group and world write */
2088 new_umask = umask(0077) | 0022;
2089 (void) umask(new_umask);
2091 /* Initialize the log (it is reinitialized below in case we forked). */
2092 if (debug_flag && (!inetd_flag || rexeced_flag))
2094 log_init(__progname, options.log_level,
2095 options.log_facility, log_stderr);
2096 for (i = 0; i < options.num_log_verbose; i++)
2097 log_verbose_add(options.log_verbose[i]);
2100 * If not in debugging mode, not started from inetd and not already
2101 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
2102 * terminal, and fork. The original process exits.
2104 already_daemon = daemonized();
2105 if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
2107 if (daemon(0, 0) == -1)
2108 fatal("daemon() failed: %.200s", strerror(errno));
2110 disconnect_controlling_tty();
2112 /* Reinitialize the log (because of the fork above). */
2113 log_init(__progname, options.log_level, options.log_facility, log_stderr);
2117 * We log refusals ourselves. However, libwrap will report
2118 * syntax errors in hosts.allow via syslog(3).
2120 allow_severity = options.log_facility|LOG_INFO;
2121 deny_severity = options.log_facility|LOG_WARNING;
2123 /* Avoid killing the process in high-pressure swapping environments. */
2124 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
2125 debug("madvise(): %.200s", strerror(errno));
2128 * Chdir to the root directory so that the current disk can be
2129 * unmounted if desired.
2131 if (chdir("/") == -1)
2132 error("chdir(\"/\"): %s", strerror(errno));
2134 /* ignore SIGPIPE */
2135 ssh_signal(SIGPIPE, SIG_IGN);
2137 /* Get a connection, either from inetd or a listening TCP socket */
2139 server_accept_inetd(&sock_in, &sock_out);
2141 platform_pre_listen();
2144 ssh_signal(SIGHUP, sighup_handler);
2145 ssh_signal(SIGCHLD, main_sigchld_handler);
2146 ssh_signal(SIGTERM, sigterm_handler);
2147 ssh_signal(SIGQUIT, sigterm_handler);
2150 * Write out the pid file after the sigterm handler
2151 * is setup and the listen sockets are bound
2153 if (options.pid_file != NULL && !debug_flag) {
2154 FILE *f = fopen(options.pid_file, "w");
2157 error("Couldn't create pid file \"%s\": %s",
2158 options.pid_file, strerror(errno));
2160 fprintf(f, "%ld\n", (long) getpid());
2165 /* Accept a connection and return in a forked child */
2166 server_accept_loop(&sock_in, &sock_out,
2167 &newsock, config_s);
2170 /* This is the child processing a new connection. */
2171 setproctitle("%s", "[accepted]");
2174 * Create a new session and process group since the 4.4BSD
2175 * setlogin() affects the entire process group. We don't
2176 * want the child to be able to affect the parent.
2178 if (!debug_flag && !inetd_flag && setsid() == -1)
2179 error("setsid: %.100s", strerror(errno));
2182 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
2183 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2184 if (dup2(newsock, STDIN_FILENO) == -1)
2185 debug3_f("dup2 stdin: %s", strerror(errno));
2186 if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1)
2187 debug3_f("dup2 stdout: %s", strerror(errno));
2188 if (startup_pipe == -1)
2189 close(REEXEC_STARTUP_PIPE_FD);
2190 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
2191 if (dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD) == -1)
2192 debug3_f("dup2 startup_p: %s", strerror(errno));
2193 close(startup_pipe);
2194 startup_pipe = REEXEC_STARTUP_PIPE_FD;
2197 if (dup2(config_s[1], REEXEC_CONFIG_PASS_FD) == -1)
2198 debug3_f("dup2 config_s: %s", strerror(errno));
2201 ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */
2202 execv(rexec_argv[0], rexec_argv);
2204 /* Reexec has failed, fall back and continue */
2205 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
2206 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
2207 log_init(__progname, options.log_level,
2208 options.log_facility, log_stderr);
2211 close(REEXEC_CONFIG_PASS_FD);
2212 newsock = sock_out = sock_in = dup(STDIN_FILENO);
2213 if (stdfd_devnull(1, 1, 0) == -1)
2214 error_f("stdfd_devnull failed");
2215 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2216 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2219 /* Executed child processes don't need these. */
2220 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2221 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2223 /* We will not restart on SIGHUP since it no longer makes sense. */
2224 ssh_signal(SIGALRM, SIG_DFL);
2225 ssh_signal(SIGHUP, SIG_DFL);
2226 ssh_signal(SIGTERM, SIG_DFL);
2227 ssh_signal(SIGQUIT, SIG_DFL);
2228 ssh_signal(SIGCHLD, SIG_DFL);
2229 ssh_signal(SIGINT, SIG_DFL);
2233 * Initialize the resolver. This may not happen automatically
2234 * before privsep chroot().
2236 if ((_res.options & RES_INIT) == 0) {
2237 debug("res_init()");
2242 * Force GSS-API to parse its configuration and load any
2243 * mechanism plugins.
2247 OM_uint32 minor_status;
2248 gss_indicate_mechs(&minor_status, &mechs);
2249 gss_release_oid_set(&minor_status, &mechs);
2255 * Register our connection. This turns encryption off because we do
2258 if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
2259 fatal("Unable to create connection");
2260 the_active_state = ssh;
2261 ssh_packet_set_server(ssh);
2263 check_ip_options(ssh);
2265 /* Prepare the channels layer */
2266 channel_init_channels(ssh);
2267 channel_set_af(ssh, options.address_family);
2268 process_channel_timeouts(ssh, &options);
2269 process_permitopen(ssh, &options);
2271 /* Set SO_KEEPALIVE if requested. */
2272 if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) &&
2273 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1)
2274 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2276 if ((remote_port = ssh_remote_port(ssh)) < 0) {
2277 debug("ssh_remote_port failed");
2281 if (options.routing_domain != NULL)
2282 set_process_rdomain(ssh, options.routing_domain);
2285 * The rest of the code depends on the fact that
2286 * ssh_remote_ipaddr() caches the remote ip, even if
2287 * the socket goes away.
2289 remote_ip = ssh_remote_ipaddr(ssh);
2291 #ifdef HAVE_LOGIN_CAP
2292 /* Also caches remote hostname for sandboxed child. */
2293 auth_get_canonical_hostname(ssh, options.use_dns);
2296 #ifdef SSH_AUDIT_EVENTS
2297 audit_connection_from(remote_ip, remote_port);
2300 rdomain = ssh_packet_rdomain_in(ssh);
2302 /* Log the connection. */
2303 laddr = get_local_ipaddr(sock_in);
2304 verbose("Connection from %s port %d on %s port %d%s%s%s",
2305 remote_ip, remote_port, laddr, ssh_local_port(ssh),
2306 rdomain == NULL ? "" : " rdomain \"",
2307 rdomain == NULL ? "" : rdomain,
2308 rdomain == NULL ? "" : "\"");
2312 * We don't want to listen forever unless the other side
2313 * successfully authenticates itself. So we set up an alarm which is
2314 * cleared after successful authentication. A limit of zero
2315 * indicates no limit. Note that we don't set the alarm in debugging
2316 * mode; it is just annoying to have the server exit just when you
2317 * are about to discover the bug.
2319 ssh_signal(SIGALRM, grace_alarm_handler);
2321 alarm(options.login_grace_time);
2323 if ((r = kex_exchange_identification(ssh, -1,
2324 options.version_addendum)) != 0)
2325 sshpkt_fatal(ssh, r, "banner exchange");
2327 ssh_packet_set_nonblocking(ssh);
2329 /* allocate authentication context */
2330 authctxt = xcalloc(1, sizeof(*authctxt));
2331 ssh->authctxt = authctxt;
2333 authctxt->loginmsg = loginmsg;
2335 /* XXX global for cleanup, access from other modules */
2336 the_authctxt = authctxt;
2338 /* Set default key authentication options */
2339 if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
2340 fatal("allocation failed");
2342 /* prepare buffer to collect messages to display to user after login */
2343 if ((loginmsg = sshbuf_new()) == NULL)
2344 fatal_f("sshbuf_new failed");
2350 if (privsep_preauth(ssh) == 1)
2352 } else if (have_agent) {
2353 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2354 error_r(r, "Unable to get agent socket");
2359 /* perform the key exchange */
2360 /* authenticate user and start session */
2362 do_authentication2(ssh);
2365 * If we use privilege separation, the unprivileged child transfers
2366 * the current keystate and exits
2369 mm_send_keystate(ssh, pmonitor);
2370 ssh_packet_clear_keys(ssh);
2376 * Cancel the alarm we set to limit the time taken for
2380 ssh_signal(SIGALRM, SIG_DFL);
2381 authctxt->authenticated = 1;
2382 if (startup_pipe != -1) {
2383 close(startup_pipe);
2387 #ifdef SSH_AUDIT_EVENTS
2388 audit_event(ssh, SSH_AUTH_SUCCESS);
2392 if (options.gss_authentication) {
2393 temporarily_use_uid(authctxt->pw);
2394 ssh_gssapi_storecreds();
2399 if (options.use_pam) {
2401 do_pam_session(ssh);
2406 * In privilege separation, we fork another child and prepare
2407 * file descriptor passing.
2410 privsep_postauth(ssh, authctxt);
2411 /* the monitor process [priv] will not return */
2414 ssh_packet_set_timeout(ssh, options.client_alive_interval,
2415 options.client_alive_count_max);
2417 /* Try to send all our hostkeys to the client */
2418 notify_hostkeys(ssh);
2420 /* Start session. */
2421 do_authenticated(ssh, authctxt);
2423 /* The connection has been terminated. */
2424 ssh_packet_get_bytes(ssh, &ibytes, &obytes);
2425 verbose("Transferred: sent %llu, received %llu bytes",
2426 (unsigned long long)obytes, (unsigned long long)ibytes);
2428 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2431 if (options.use_pam)
2433 #endif /* USE_PAM */
2435 #ifdef SSH_AUDIT_EVENTS
2436 PRIVSEP(audit_event(ssh, SSH_CONNECTION_CLOSE));
2439 ssh_packet_close(ssh);
2448 sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
2449 struct sshkey *pubkey, u_char **signature, size_t *slenp,
2450 const u_char *data, size_t dlen, const char *alg)
2456 if (mm_sshkey_sign(ssh, privkey, signature, slenp,
2457 data, dlen, alg, options.sk_provider, NULL,
2459 fatal_f("privkey sign failed");
2461 if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
2462 data, dlen, alg, options.sk_provider, NULL,
2464 fatal_f("pubkey sign failed");
2468 if (sshkey_sign(privkey, signature, slenp, data, dlen,
2469 alg, options.sk_provider, NULL, ssh->compat) < 0)
2470 fatal_f("privkey sign failed");
2472 if ((r = ssh_agent_sign(auth_sock, pubkey,
2473 signature, slenp, data, dlen, alg,
2474 ssh->compat)) != 0) {
2475 fatal_fr(r, "agent sign failed");
2482 /* SSH2 key exchange */
2484 do_ssh2_kex(struct ssh *ssh)
2486 char *hkalgs = NULL, *myproposal[PROPOSAL_MAX];
2487 const char *compression = NULL;
2491 if (options.rekey_limit || options.rekey_interval)
2492 ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
2493 options.rekey_interval);
2495 if (options.compression == COMP_NONE)
2496 compression = "none";
2497 hkalgs = list_hostkey_types();
2499 kex_proposal_populate_entries(ssh, myproposal, options.kex_algorithms,
2500 options.ciphers, options.macs, compression, hkalgs);
2504 /* start key exchange */
2505 if ((r = kex_setup(ssh, myproposal)) != 0)
2506 fatal_r(r, "kex_setup");
2509 kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
2510 kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
2511 kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
2512 kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
2513 kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
2514 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2515 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2516 # ifdef OPENSSL_HAS_ECC
2517 kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
2520 kex->kex[KEX_C25519_SHA256] = kex_gen_server;
2521 kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
2522 kex->load_host_public_key=&get_hostkey_public_by_type;
2523 kex->load_host_private_key=&get_hostkey_private_by_type;
2524 kex->host_key_index=&get_hostkey_index;
2525 kex->sign = sshd_hostkey_sign;
2527 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
2530 /* send 1st encrypted/maced/compressed message */
2531 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2532 (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
2533 (r = sshpkt_send(ssh)) != 0 ||
2534 (r = ssh_packet_write_wait(ssh)) != 0)
2535 fatal_fr(r, "send test");
2537 kex_proposal_free_entries(myproposal);
2541 /* server specific fatal cleanup */
2545 if (the_active_state != NULL && the_authctxt != NULL) {
2546 do_cleanup(the_active_state, the_authctxt);
2547 if (use_privsep && privsep_is_preauth &&
2548 pmonitor != NULL && pmonitor->m_pid > 1) {
2549 debug("Killing privsep child %d", pmonitor->m_pid);
2550 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2552 error_f("kill(%d): %s", pmonitor->m_pid,
2557 #ifdef SSH_AUDIT_EVENTS
2558 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2559 if (the_active_state != NULL && (!use_privsep || mm_is_monitor()))
2560 audit_event(the_active_state, SSH_CONNECTION_ABANDON);