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"
148 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
149 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
150 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
151 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
153 extern char *__progname;
155 /* Server configuration options. */
156 ServerOptions options;
158 /* Name of the server configuration file. */
159 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
162 * Debug mode flag. This can be set on the command line. If debug
163 * mode is enabled, extra debugging output will be sent to the system
164 * log, the daemon will not go to background, and will exit after processing
165 * the first connection.
170 * Indicating that the daemon should only test the configuration and keys.
171 * If test_flag > 1 ("-T" flag), then sshd will also dump the effective
172 * configuration, optionally using connection information provided by the
175 static int test_flag = 0;
177 /* Flag indicating that the daemon is being started from inetd. */
178 static int inetd_flag = 0;
180 /* Flag indicating that sshd should not detach and become a daemon. */
181 static int no_daemon_flag = 0;
183 /* debug goes to stderr unless inetd_flag is set */
184 static int log_stderr = 0;
186 /* Saved arguments to main(). */
187 static char **saved_argv;
188 static int saved_argc;
191 static int rexeced_flag = 0;
192 static int rexec_flag = 1;
193 static int rexec_argc = 0;
194 static char **rexec_argv;
197 * The sockets that the server is listening; this is used in the SIGHUP
200 #define MAX_LISTEN_SOCKS 16
201 static int listen_socks[MAX_LISTEN_SOCKS];
202 static int num_listen_socks = 0;
204 /* Daemon's agent connection */
206 static int have_agent = 0;
209 * Any really sensitive data in the application is contained in this
210 * structure. The idea is that this structure could be locked into memory so
211 * that the pages do not get written into swap. However, there are some
212 * problems. The private key contains BIGNUMs, and we do not (in principle)
213 * have access to the internals of them, and locking just the structure is
214 * not very useful. Currently, memory locking is not implemented.
217 struct sshkey **host_keys; /* all private host keys */
218 struct sshkey **host_pubkeys; /* all public host keys */
219 struct sshkey **host_certificates; /* all public host certificates */
223 /* This is set to true when a signal is received. */
224 static volatile sig_atomic_t received_sighup = 0;
225 static volatile sig_atomic_t received_sigterm = 0;
227 /* record remote hostname or ip */
228 u_int utmp_len = HOST_NAME_MAX+1;
231 * startup_pipes/flags are used for tracking children of the listening sshd
232 * process early in their lifespans. This tracking is needed for three things:
234 * 1) Implementing the MaxStartups limit of concurrent unauthenticated
236 * 2) Avoiding a race condition for SIGHUP processing, where child processes
237 * may have listen_socks open that could collide with main listener process
239 * 3) Ensuring that rexec'd sshd processes have received their initial state
240 * from the parent listen process before handling SIGHUP.
242 * Child processes signal that they have completed closure of the listen_socks
243 * and (if applicable) received their rexec state by sending a char over their
244 * sock. Child processes signal that authentication has completed by closing
245 * the sock (or by exiting).
247 static int *startup_pipes = NULL;
248 static int *startup_flags = NULL; /* Indicates child closed listener */
249 static int startup_pipe = -1; /* in child */
251 /* variables used for privilege separation */
252 int use_privsep = -1;
253 struct monitor *pmonitor = NULL;
254 int privsep_is_preauth = 1;
255 static int privsep_chroot = 1;
257 /* global connection state and authentication contexts */
258 Authctxt *the_authctxt = NULL;
259 struct ssh *the_active_state;
261 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
262 struct sshauthopt *auth_opts = NULL;
264 /* sshd_config buffer */
267 /* Included files from the configuration file */
268 struct include_list includes = TAILQ_HEAD_INITIALIZER(includes);
270 /* message to be displayed after login */
271 struct sshbuf *loginmsg;
273 /* Unprivileged user */
274 struct passwd *privsep_pw = NULL;
276 /* Prototypes for various functions defined later in this file. */
277 void destroy_sensitive_data(void);
278 void demote_sensitive_data(void);
279 static void do_ssh2_kex(struct ssh *);
281 static char *listener_proctitle;
284 * Close all listening sockets
287 close_listen_socks(void)
291 for (i = 0; i < num_listen_socks; i++)
292 close(listen_socks[i]);
293 num_listen_socks = 0;
297 close_startup_pipes(void)
302 for (i = 0; i < options.max_startups; i++)
303 if (startup_pipes[i] != -1)
304 close(startup_pipes[i]);
308 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
309 * the effect is to reread the configuration file (and to regenerate
314 sighup_handler(int sig)
320 * Called from the main program after receiving SIGHUP.
321 * Restarts the server.
326 logit("Received SIGHUP; restarting.");
327 if (options.pid_file != NULL)
328 unlink(options.pid_file);
329 platform_pre_restart();
330 close_listen_socks();
331 close_startup_pipes();
332 ssh_signal(SIGHUP, SIG_IGN); /* will be restored after exec */
333 execv(saved_argv[0], saved_argv);
334 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
340 * Generic signal handler for terminating signals in the master daemon.
343 sigterm_handler(int sig)
345 received_sigterm = sig;
349 * SIGCHLD handler. This is called whenever a child dies. This will then
350 * reap any zombies left by exited children.
353 main_sigchld_handler(int sig)
355 int save_errno = errno;
359 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
360 (pid == -1 && errno == EINTR))
366 * Signal handler for the alarm after the login grace period has expired.
369 grace_alarm_handler(int sig)
372 * Try to kill any processes that we have spawned, E.g. authorized
373 * keys command helpers or privsep children.
375 if (getpgid(0) == getpid()) {
376 ssh_signal(SIGTERM, SIG_IGN);
380 BLACKLIST_NOTIFY(the_active_state, BLACKLIST_AUTH_FAIL, "ssh");
382 /* Log error and exit. */
383 sigdie("Timeout before authentication for %s port %d",
384 ssh_remote_ipaddr(the_active_state),
385 ssh_remote_port(the_active_state));
388 /* Destroy the host and server keys. They will no longer be needed. */
390 destroy_sensitive_data(void)
394 for (i = 0; i < options.num_host_key_files; i++) {
395 if (sensitive_data.host_keys[i]) {
396 sshkey_free(sensitive_data.host_keys[i]);
397 sensitive_data.host_keys[i] = NULL;
399 if (sensitive_data.host_certificates[i]) {
400 sshkey_free(sensitive_data.host_certificates[i]);
401 sensitive_data.host_certificates[i] = NULL;
406 /* Demote private to public keys for network child */
408 demote_sensitive_data(void)
414 for (i = 0; i < options.num_host_key_files; i++) {
415 if (sensitive_data.host_keys[i]) {
416 if ((r = sshkey_from_private(
417 sensitive_data.host_keys[i], &tmp)) != 0)
418 fatal_r(r, "could not demote host %s key",
419 sshkey_type(sensitive_data.host_keys[i]));
420 sshkey_free(sensitive_data.host_keys[i]);
421 sensitive_data.host_keys[i] = tmp;
423 /* Certs do not need demotion */
435 arc4random_stir(); /* noop on recent arc4random() implementations */
436 arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
439 RAND_seed(rnd, sizeof(rnd));
440 /* give libcrypto a chance to notice the PID change */
441 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
442 fatal("%s: RAND_bytes failed", __func__);
445 explicit_bzero(rnd, sizeof(rnd));
449 privsep_preauth_child(void)
453 /* Enable challenge-response authentication for privilege separation */
454 privsep_challenge_enable();
457 /* Cache supported mechanism OIDs for later use */
458 ssh_gssapi_prepare_supported_oids();
463 /* Demote the private keys to public keys. */
464 demote_sensitive_data();
466 /* Demote the child */
467 if (privsep_chroot) {
468 /* Change our root directory */
469 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
470 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
472 if (chdir("/") == -1)
473 fatal("chdir(\"/\"): %s", strerror(errno));
475 /* Drop our privileges */
476 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
477 (u_int)privsep_pw->pw_gid);
478 gidset[0] = privsep_pw->pw_gid;
479 if (setgroups(1, gidset) == -1)
480 fatal("setgroups: %.100s", strerror(errno));
481 permanently_set_uid(privsep_pw);
486 privsep_preauth(struct ssh *ssh)
490 struct ssh_sandbox *box = NULL;
492 /* Set up unprivileged child process to deal with network data */
493 pmonitor = monitor_init();
494 /* Store a pointer to the kex for later rekeying */
495 pmonitor->m_pkex = &ssh->kex;
497 if (use_privsep == PRIVSEP_ON)
498 box = ssh_sandbox_init(pmonitor);
501 fatal("fork of unprivileged child failed");
502 } else if (pid != 0) {
503 debug2("Network child is on pid %ld", (long)pid);
505 pmonitor->m_pid = pid;
507 r = ssh_get_authentication_socket(&auth_sock);
509 error_r(r, "Could not get agent socket");
514 ssh_sandbox_parent_preauth(box, pid);
515 monitor_child_preauth(ssh, pmonitor);
517 /* Wait for the child's exit status */
518 while (waitpid(pid, &status, 0) == -1) {
521 pmonitor->m_pid = -1;
522 fatal_f("waitpid: %s", strerror(errno));
524 privsep_is_preauth = 0;
525 pmonitor->m_pid = -1;
526 if (WIFEXITED(status)) {
527 if (WEXITSTATUS(status) != 0)
528 fatal_f("preauth child exited with status %d",
529 WEXITSTATUS(status));
530 } else if (WIFSIGNALED(status))
531 fatal_f("preauth child terminated by signal %d",
534 ssh_sandbox_parent_finish(box);
538 close(pmonitor->m_sendfd);
539 close(pmonitor->m_log_recvfd);
541 /* Arrange for logging to be sent to the monitor */
542 set_log_handler(mm_log_handler, pmonitor);
544 privsep_preauth_child();
545 setproctitle("%s", "[net]");
547 ssh_sandbox_child(box);
554 privsep_postauth(struct ssh *ssh, Authctxt *authctxt)
556 #ifdef DISABLE_FD_PASSING
559 if (authctxt->pw->pw_uid == 0) {
561 /* File descriptor passing is broken or root login */
566 /* New socket pair */
567 monitor_reinit(pmonitor);
569 pmonitor->m_pid = fork();
570 if (pmonitor->m_pid == -1)
571 fatal("fork of unprivileged child failed");
572 else if (pmonitor->m_pid != 0) {
573 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
574 sshbuf_reset(loginmsg);
575 monitor_clear_keystate(ssh, pmonitor);
576 monitor_child_postauth(ssh, pmonitor);
584 close(pmonitor->m_sendfd);
585 pmonitor->m_sendfd = -1;
587 /* Demote the private keys to public keys. */
588 demote_sensitive_data();
592 /* Drop privileges */
593 do_setusercontext(authctxt->pw);
596 /* It is safe now to apply the key state */
597 monitor_apply_keystate(ssh, pmonitor);
600 * Tell the packet layer that authentication was successful, since
601 * this information is not part of the key state.
603 ssh_packet_set_authenticated(ssh);
607 append_hostkey_type(struct sshbuf *b, const char *s)
611 if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
612 debug3_f("%s key not permitted by HostkeyAlgorithms", s);
615 if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
616 fatal_fr(r, "sshbuf_putf");
620 list_hostkey_types(void)
627 if ((b = sshbuf_new()) == NULL)
628 fatal_f("sshbuf_new failed");
629 for (i = 0; i < options.num_host_key_files; i++) {
630 key = sensitive_data.host_keys[i];
632 key = sensitive_data.host_pubkeys[i];
637 /* for RSA we also support SHA2 signatures */
638 append_hostkey_type(b, "rsa-sha2-512");
639 append_hostkey_type(b, "rsa-sha2-256");
647 append_hostkey_type(b, sshkey_ssh_name(key));
650 /* If the private key has a cert peer, then list that too */
651 key = sensitive_data.host_certificates[i];
656 /* for RSA we also support SHA2 signatures */
657 append_hostkey_type(b,
658 "rsa-sha2-512-cert-v01@openssh.com");
659 append_hostkey_type(b,
660 "rsa-sha2-256-cert-v01@openssh.com");
664 case KEY_ED25519_CERT:
665 case KEY_ECDSA_SK_CERT:
666 case KEY_ED25519_SK_CERT:
668 append_hostkey_type(b, sshkey_ssh_name(key));
672 if ((ret = sshbuf_dup_string(b)) == NULL)
673 fatal_f("sshbuf_dup_string failed");
679 static struct sshkey *
680 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
685 for (i = 0; i < options.num_host_key_files; i++) {
690 case KEY_ED25519_CERT:
691 case KEY_ECDSA_SK_CERT:
692 case KEY_ED25519_SK_CERT:
694 key = sensitive_data.host_certificates[i];
697 key = sensitive_data.host_keys[i];
698 if (key == NULL && !need_private)
699 key = sensitive_data.host_pubkeys[i];
702 if (key == NULL || key->type != type)
708 case KEY_ECDSA_SK_CERT:
709 if (key->ecdsa_nid != nid)
713 return need_private ?
714 sensitive_data.host_keys[i] : key;
721 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
723 return get_hostkey_by_type(type, nid, 0, ssh);
727 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
729 return get_hostkey_by_type(type, nid, 1, ssh);
733 get_hostkey_by_index(int ind)
735 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
737 return (sensitive_data.host_keys[ind]);
741 get_hostkey_public_by_index(int ind, struct ssh *ssh)
743 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
745 return (sensitive_data.host_pubkeys[ind]);
749 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
753 for (i = 0; i < options.num_host_key_files; i++) {
754 if (sshkey_is_cert(key)) {
755 if (key == sensitive_data.host_certificates[i] ||
756 (compare && sensitive_data.host_certificates[i] &&
758 sensitive_data.host_certificates[i])))
761 if (key == sensitive_data.host_keys[i] ||
762 (compare && sensitive_data.host_keys[i] &&
763 sshkey_equal(key, sensitive_data.host_keys[i])))
765 if (key == sensitive_data.host_pubkeys[i] ||
766 (compare && sensitive_data.host_pubkeys[i] &&
767 sshkey_equal(key, sensitive_data.host_pubkeys[i])))
774 /* Inform the client of all hostkeys */
776 notify_hostkeys(struct ssh *ssh)
784 /* Some clients cannot cope with the hostkeys message, skip those. */
785 if (ssh->compat & SSH_BUG_HOSTKEYS)
788 if ((buf = sshbuf_new()) == NULL)
789 fatal_f("sshbuf_new");
790 for (i = nkeys = 0; i < options.num_host_key_files; i++) {
791 key = get_hostkey_public_by_index(i, ssh);
792 if (key == NULL || key->type == KEY_UNSPEC ||
795 fp = sshkey_fingerprint(key, options.fingerprint_hash,
797 debug3_f("key %d: %s %s", i, sshkey_ssh_name(key), fp);
801 * Start building the request when we find the
804 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
805 (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 ||
806 (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */
807 sshpkt_fatal(ssh, r, "%s: start request", __func__);
809 /* Append the key to the request */
811 if ((r = sshkey_putb(key, buf)) != 0)
812 fatal_fr(r, "couldn't put hostkey %d", i);
813 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
814 sshpkt_fatal(ssh, r, "%s: append key", __func__);
817 debug3_f("sent %u hostkeys", nkeys);
819 fatal_f("no hostkeys");
820 if ((r = sshpkt_send(ssh)) != 0)
821 sshpkt_fatal(ssh, r, "%s: send", __func__);
826 * returns 1 if connection should be dropped, 0 otherwise.
827 * dropping starts at connection #max_startups_begin with a probability
828 * of (max_startups_rate/100). the probability increases linearly until
829 * all connections are dropped for startups > max_startups
832 should_drop_connection(int startups)
836 if (startups < options.max_startups_begin)
838 if (startups >= options.max_startups)
840 if (options.max_startups_rate == 100)
843 p = 100 - options.max_startups_rate;
844 p *= startups - options.max_startups_begin;
845 p /= options.max_startups - options.max_startups_begin;
846 p += options.max_startups_rate;
847 r = arc4random_uniform(100);
849 debug_f("p %d, r %d", p, r);
850 return (r < p) ? 1 : 0;
854 * Check whether connection should be accepted by MaxStartups.
855 * Returns 0 if the connection is accepted. If the connection is refused,
856 * returns 1 and attempts to send notification to client.
857 * Logs when the MaxStartups condition is entered or exited, and periodically
858 * while in that state.
861 drop_connection(int sock, int startups, int notify_pipe)
864 const char msg[] = "Exceeded MaxStartups\r\n";
865 static time_t last_drop, first_drop;
866 static u_int ndropped;
867 LogLevel drop_level = SYSLOG_LEVEL_VERBOSE;
871 if (!should_drop_connection(startups) &&
872 srclimit_check_allow(sock, notify_pipe) == 1) {
873 if (last_drop != 0 &&
874 startups < options.max_startups_begin - 1) {
875 /* XXX maybe need better hysteresis here */
876 logit("exited MaxStartups throttling after %s, "
877 "%u connections dropped",
878 fmt_timeframe(now - first_drop), ndropped);
884 #define SSHD_MAXSTARTUPS_LOG_INTERVAL (5 * 60)
885 if (last_drop == 0) {
886 error("beginning MaxStartups throttling");
887 drop_level = SYSLOG_LEVEL_INFO;
890 } else if (last_drop + SSHD_MAXSTARTUPS_LOG_INTERVAL < now) {
892 error("in MaxStartups throttling for %s, "
893 "%u connections dropped",
894 fmt_timeframe(now - first_drop), ndropped + 1);
895 drop_level = SYSLOG_LEVEL_INFO;
900 laddr = get_local_ipaddr(sock);
901 raddr = get_peer_ipaddr(sock);
902 do_log2(drop_level, "drop connection #%d from [%s]:%d on [%s]:%d "
903 "past MaxStartups", startups, raddr, get_peer_port(sock),
904 laddr, get_local_port(sock));
907 /* best-effort notification to client */
908 (void)write(sock, msg, sizeof(msg) - 1);
915 if (options.version_addendum != NULL &&
916 *options.version_addendum != '\0')
917 fprintf(stderr, "%s %s, %s\n",
919 options.version_addendum, SSH_OPENSSL_VERSION);
921 fprintf(stderr, "%s, %s\n",
922 SSH_RELEASE, SSH_OPENSSL_VERSION);
924 "usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n"
925 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
926 " [-h host_key_file] [-o option] [-p port] [-u len]\n"
932 send_rexec_state(int fd, struct sshbuf *conf)
934 struct sshbuf *m = NULL, *inc = NULL;
935 struct include_item *item = NULL;
938 debug3_f("entering fd = %d config len %zu", fd,
941 if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
942 fatal_f("sshbuf_new failed");
944 /* pack includes into a string */
945 TAILQ_FOREACH(item, &includes, entry) {
946 if ((r = sshbuf_put_cstring(inc, item->selector)) != 0 ||
947 (r = sshbuf_put_cstring(inc, item->filename)) != 0 ||
948 (r = sshbuf_put_stringb(inc, item->contents)) != 0)
949 fatal_fr(r, "compose includes");
953 * Protocol from reexec master to child:
954 * string configuration
955 * string included_files[] {
961 if ((r = sshbuf_put_stringb(m, conf)) != 0 ||
962 (r = sshbuf_put_stringb(m, inc)) != 0)
963 fatal_fr(r, "compose config");
964 if (ssh_msg_send(fd, 0, m) == -1)
965 error_f("ssh_msg_send failed");
974 recv_rexec_state(int fd, struct sshbuf *conf)
976 struct sshbuf *m, *inc;
980 struct include_item *item;
982 debug3_f("entering fd = %d", fd);
984 if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
985 fatal_f("sshbuf_new failed");
986 if (ssh_msg_recv(fd, m) == -1)
987 fatal_f("ssh_msg_recv failed");
988 if ((r = sshbuf_get_u8(m, &ver)) != 0)
989 fatal_fr(r, "parse version");
991 fatal_f("rexec version mismatch");
992 if ((r = sshbuf_get_string(m, &cp, &len)) != 0 ||
993 (r = sshbuf_get_stringb(m, inc)) != 0)
994 fatal_fr(r, "parse config");
996 if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
997 fatal_fr(r, "sshbuf_put");
999 while (sshbuf_len(inc) != 0) {
1000 item = xcalloc(1, sizeof(*item));
1001 if ((item->contents = sshbuf_new()) == NULL)
1002 fatal_f("sshbuf_new failed");
1003 if ((r = sshbuf_get_cstring(inc, &item->selector, NULL)) != 0 ||
1004 (r = sshbuf_get_cstring(inc, &item->filename, NULL)) != 0 ||
1005 (r = sshbuf_get_stringb(inc, item->contents)) != 0)
1006 fatal_fr(r, "parse includes");
1007 TAILQ_INSERT_TAIL(&includes, item, entry);
1016 /* Accept a connection from inetd */
1018 server_accept_inetd(int *sock_in, int *sock_out)
1021 close(REEXEC_CONFIG_PASS_FD);
1022 *sock_in = *sock_out = dup(STDIN_FILENO);
1024 *sock_in = dup(STDIN_FILENO);
1025 *sock_out = dup(STDOUT_FILENO);
1028 * We intentionally do not close the descriptors 0, 1, and 2
1029 * as our code for setting the descriptors won't work if
1030 * ttyfd happens to be one of those.
1032 if (stdfd_devnull(1, 1, !log_stderr) == -1)
1033 error_f("stdfd_devnull failed");
1034 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1038 * Listen for TCP connections
1041 listen_on_addrs(struct listenaddr *la)
1043 int ret, listen_sock;
1044 struct addrinfo *ai;
1045 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1047 for (ai = la->addrs; ai; ai = ai->ai_next) {
1048 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1050 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1051 fatal("Too many listen sockets. "
1052 "Enlarge MAX_LISTEN_SOCKS");
1053 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1054 ntop, sizeof(ntop), strport, sizeof(strport),
1055 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1056 error("getnameinfo failed: %.100s",
1057 ssh_gai_strerror(ret));
1060 /* Create socket for listening. */
1061 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1063 if (listen_sock == -1) {
1064 /* kernel may not support ipv6 */
1065 verbose("socket: %.100s", strerror(errno));
1068 if (set_nonblock(listen_sock) == -1) {
1072 if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
1073 verbose("socket: CLOEXEC: %s", strerror(errno));
1077 /* Socket options */
1078 set_reuseaddr(listen_sock);
1079 if (la->rdomain != NULL &&
1080 set_rdomain(listen_sock, la->rdomain) == -1) {
1085 /* Only communicate in IPv6 over AF_INET6 sockets. */
1086 if (ai->ai_family == AF_INET6)
1087 sock_set_v6only(listen_sock);
1089 debug("Bind to port %s on %s.", strport, ntop);
1091 /* Bind the socket to the desired port. */
1092 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) {
1093 error("Bind to port %s on %s failed: %.200s.",
1094 strport, ntop, strerror(errno));
1098 listen_socks[num_listen_socks] = listen_sock;
1101 /* Start listening on the port. */
1102 if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1)
1103 fatal("listen on [%s]:%s: %.100s",
1104 ntop, strport, strerror(errno));
1105 logit("Server listening on %s port %s%s%s.",
1107 la->rdomain == NULL ? "" : " rdomain ",
1108 la->rdomain == NULL ? "" : la->rdomain);
1117 /* Initialise per-source limit tracking. */
1118 srclimit_init(options.max_startups, options.per_source_max_startups,
1119 options.per_source_masklen_ipv4, options.per_source_masklen_ipv6);
1121 for (i = 0; i < options.num_listen_addrs; i++) {
1122 listen_on_addrs(&options.listen_addrs[i]);
1123 freeaddrinfo(options.listen_addrs[i].addrs);
1124 free(options.listen_addrs[i].rdomain);
1125 memset(&options.listen_addrs[i], 0,
1126 sizeof(options.listen_addrs[i]));
1128 free(options.listen_addrs);
1129 options.listen_addrs = NULL;
1130 options.num_listen_addrs = 0;
1132 if (!num_listen_socks)
1133 fatal("Cannot bind any address.");
1137 * The main TCP accept loop. Note that, for the non-debug case, returns
1138 * from this function are in a forked subprocess.
1141 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1143 struct pollfd *pfd = NULL;
1144 int i, j, ret, npfd;
1145 int ostartups = -1, startups = 0, listening = 0, lameduck = 0;
1146 int startup_p[2] = { -1 , -1 }, *startup_pollfd;
1148 struct sockaddr_storage from;
1152 sigset_t nsigset, osigset;
1154 struct request_info req;
1156 request_init(&req, RQ_DAEMON, __progname, 0);
1159 /* pipes connected to unauthenticated child sshd processes */
1160 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1161 startup_flags = xcalloc(options.max_startups, sizeof(int));
1162 startup_pollfd = xcalloc(options.max_startups, sizeof(int));
1163 for (i = 0; i < options.max_startups; i++)
1164 startup_pipes[i] = -1;
1167 * Prepare signal mask that we use to block signals that might set
1168 * received_sigterm or received_sighup, so that we are guaranteed
1169 * to immediately wake up the ppoll if a signal is received after
1170 * the flag is checked.
1172 sigemptyset(&nsigset);
1173 sigaddset(&nsigset, SIGHUP);
1174 sigaddset(&nsigset, SIGCHLD);
1175 sigaddset(&nsigset, SIGTERM);
1176 sigaddset(&nsigset, SIGQUIT);
1178 /* sized for worst-case */
1179 pfd = xcalloc(num_listen_socks + options.max_startups,
1180 sizeof(struct pollfd));
1183 * Stay listening for connections until the system crashes or
1184 * the daemon is killed with a signal.
1187 sigprocmask(SIG_BLOCK, &nsigset, &osigset);
1188 if (received_sigterm) {
1189 logit("Received signal %d; terminating.",
1190 (int) received_sigterm);
1191 close_listen_socks();
1192 if (options.pid_file != NULL)
1193 unlink(options.pid_file);
1194 exit(received_sigterm == SIGTERM ? 0 : 255);
1196 if (ostartups != startups) {
1197 setproctitle("%s [listener] %d of %d-%d startups",
1198 listener_proctitle, startups,
1199 options.max_startups_begin, options.max_startups);
1200 ostartups = startups;
1202 if (received_sighup) {
1204 debug("Received SIGHUP; waiting for children");
1205 close_listen_socks();
1208 if (listening <= 0) {
1209 sigprocmask(SIG_SETMASK, &osigset, NULL);
1214 for (i = 0; i < num_listen_socks; i++) {
1215 pfd[i].fd = listen_socks[i];
1216 pfd[i].events = POLLIN;
1218 npfd = num_listen_socks;
1219 for (i = 0; i < options.max_startups; i++) {
1220 startup_pollfd[i] = -1;
1221 if (startup_pipes[i] != -1) {
1222 pfd[npfd].fd = startup_pipes[i];
1223 pfd[npfd].events = POLLIN;
1224 startup_pollfd[i] = npfd++;
1228 /* Wait until a connection arrives or a child exits. */
1229 ret = ppoll(pfd, npfd, NULL, &osigset);
1230 if (ret == -1 && errno != EINTR) {
1231 error("ppoll: %.100s", strerror(errno));
1232 if (errno == EINVAL)
1233 cleanup_exit(1); /* can't recover */
1235 sigprocmask(SIG_SETMASK, &osigset, NULL);
1239 for (i = 0; i < options.max_startups; i++) {
1240 if (startup_pipes[i] == -1 ||
1241 startup_pollfd[i] == -1 ||
1242 !(pfd[startup_pollfd[i]].revents & (POLLIN|POLLHUP)))
1244 switch (read(startup_pipes[i], &c, sizeof(c))) {
1246 if (errno == EINTR || errno == EAGAIN)
1248 if (errno != EPIPE) {
1249 error_f("startup pipe %d (fd=%d): "
1250 "read %s", i, startup_pipes[i],
1255 /* child exited or completed auth */
1256 close(startup_pipes[i]);
1257 srclimit_done(startup_pipes[i]);
1258 startup_pipes[i] = -1;
1260 if (startup_flags[i])
1264 /* child has finished preliminaries */
1265 if (startup_flags[i]) {
1267 startup_flags[i] = 0;
1272 for (i = 0; i < num_listen_socks; i++) {
1273 if (!(pfd[i].revents & POLLIN))
1275 fromlen = sizeof(from);
1276 *newsock = accept(listen_socks[i],
1277 (struct sockaddr *)&from, &fromlen);
1278 if (*newsock == -1) {
1279 if (errno != EINTR && errno != EWOULDBLOCK &&
1280 errno != ECONNABORTED && errno != EAGAIN)
1281 error("accept: %.100s",
1283 if (errno == EMFILE || errno == ENFILE)
1288 /* Check whether logins are denied from this host. */
1289 request_set(&req, RQ_FILE, *newsock,
1290 RQ_CLIENT_NAME, "", RQ_CLIENT_ADDR, "", 0);
1292 if (!hosts_access(&req)) {
1293 const struct linger l = { .l_onoff = 1,
1296 (void )setsockopt(*newsock, SOL_SOCKET,
1297 SO_LINGER, &l, sizeof(l));
1298 (void )close(*newsock);
1300 * Mimic message from libwrap's refuse() as
1301 * precisely as we can afford. The authentic
1302 * message prints the IP address and the
1303 * hostname it resolves to in parentheses. If
1304 * the IP address cannot be resolved to a
1305 * hostname, the IP address will be repeated
1306 * in parentheses. As name resolution in the
1307 * main server loop could stall, and logging
1308 * resolved names adds little or no value to
1309 * incident investigation, this implementation
1310 * only repeats the IP address in parentheses.
1311 * This should resemble librwap's refuse()
1312 * closely enough not to break auditing
1313 * software like sshguard or custom scripts.
1316 "refused connect from %s (%s)",
1317 eval_hostaddr(req.client),
1318 eval_hostaddr(req.client));
1319 debug("Connection refused by tcp wrapper");
1322 #endif /* LIBWRAP */
1323 if (unset_nonblock(*newsock) == -1) {
1327 if (pipe(startup_p) == -1) {
1328 error_f("pipe(startup_p): %s", strerror(errno));
1332 if (drop_connection(*newsock, startups, startup_p[0])) {
1334 close(startup_p[0]);
1335 close(startup_p[1]);
1339 if (rexec_flag && socketpair(AF_UNIX,
1340 SOCK_STREAM, 0, config_s) == -1) {
1341 error("reexec socketpair: %s",
1344 close(startup_p[0]);
1345 close(startup_p[1]);
1349 for (j = 0; j < options.max_startups; j++)
1350 if (startup_pipes[j] == -1) {
1351 startup_pipes[j] = startup_p[0];
1353 startup_flags[j] = 1;
1358 * Got connection. Fork a child to handle it, unless
1359 * we are in debugging mode.
1363 * In debugging mode. Close the listening
1364 * socket, and start processing the
1365 * connection without forking.
1367 debug("Server will not fork when running in debugging mode.");
1368 close_listen_socks();
1369 *sock_in = *newsock;
1370 *sock_out = *newsock;
1371 close(startup_p[0]);
1372 close(startup_p[1]);
1376 send_rexec_state(config_s[0], cfg);
1384 * Normal production daemon. Fork, and have
1385 * the child process the connection. The
1386 * parent continues listening.
1388 platform_pre_fork();
1390 if ((pid = fork()) == 0) {
1392 * Child. Close the listening and
1393 * max_startup sockets. Start using
1394 * the accepted socket. Reinitialize
1395 * logging (since our pid has changed).
1396 * We return from this function to handle
1399 platform_post_fork_child();
1400 startup_pipe = startup_p[1];
1401 close_startup_pipes();
1402 close_listen_socks();
1403 *sock_in = *newsock;
1404 *sock_out = *newsock;
1405 log_init(__progname,
1407 options.log_facility,
1413 * Signal parent that the preliminaries
1414 * for this child are complete. For the
1415 * re-exec case, this happens after the
1416 * child has received the rexec state
1419 (void)atomicio(vwrite, startup_pipe,
1426 /* Parent. Stay in the loop. */
1427 platform_post_fork_parent(pid);
1429 error("fork: %.100s", strerror(errno));
1431 debug("Forked child %ld.", (long)pid);
1433 close(startup_p[1]);
1437 send_rexec_state(config_s[0], cfg);
1443 * Ensure that our random state differs
1444 * from that of the child
1447 arc4random_buf(rnd, sizeof(rnd));
1449 RAND_seed(rnd, sizeof(rnd));
1450 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1451 fatal("%s: RAND_bytes failed", __func__);
1453 explicit_bzero(rnd, sizeof(rnd));
1459 * If IP options are supported, make sure there are none (log and
1460 * return an error if any are found). Basically we are worried about
1461 * source routing; it can be used to pretend you are somebody
1462 * (ip-address) you are not. That itself may be "almost acceptable"
1463 * under certain circumstances, but rhosts authentication is useless
1464 * if source routing is accepted. Notice also that if we just dropped
1465 * source routing here, the other side could use IP spoofing to do
1466 * rest of the interaction and could still bypass security. So we
1467 * exit here if we detect any IP options.
1470 check_ip_options(struct ssh *ssh)
1473 int sock_in = ssh_packet_get_connection_in(ssh);
1474 struct sockaddr_storage from;
1476 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1477 char text[sizeof(opts) * 3 + 1];
1479 memset(&from, 0, sizeof(from));
1480 if (getpeername(sock_in, (struct sockaddr *)&from,
1483 if (from.ss_family != AF_INET)
1485 /* XXX IPv6 options? */
1487 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1488 &option_size) >= 0 && option_size != 0) {
1490 for (i = 0; i < option_size; i++)
1491 snprintf(text + i*3, sizeof(text) - i*3,
1493 fatal("Connection from %.100s port %d with IP opts: %.800s",
1494 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1497 #endif /* IP_OPTIONS */
1500 /* Set the routing domain for this process */
1502 set_process_rdomain(struct ssh *ssh, const char *name)
1504 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
1506 return; /* default */
1508 if (strcmp(name, "%D") == 0) {
1509 /* "expands" to routing domain of connection */
1510 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1513 /* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
1514 return sys_set_process_rdomain(name);
1515 #elif defined(__OpenBSD__)
1516 int rtable, ortable = getrtable();
1520 return; /* default */
1522 if (strcmp(name, "%D") == 0) {
1523 /* "expands" to routing domain of connection */
1524 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1528 rtable = (int)strtonum(name, 0, 255, &errstr);
1529 if (errstr != NULL) /* Shouldn't happen */
1530 fatal("Invalid routing domain \"%s\": %s", name, errstr);
1531 if (rtable != ortable && setrtable(rtable) != 0)
1532 fatal("Unable to set routing domain %d: %s",
1533 rtable, strerror(errno));
1534 debug_f("set routing domain %d (was %d)", rtable, ortable);
1535 #else /* defined(__OpenBSD__) */
1536 fatal("Unable to set routing domain: not supported in this platform");
1541 accumulate_host_timing_secret(struct sshbuf *server_cfg,
1544 static struct ssh_digest_ctx *ctx;
1550 if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
1551 fatal_f("ssh_digest_start");
1552 if (key == NULL) { /* finalize */
1553 /* add server config in case we are using agent for host keys */
1554 if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
1555 sshbuf_len(server_cfg)) != 0)
1556 fatal_f("ssh_digest_update");
1557 len = ssh_digest_bytes(SSH_DIGEST_SHA512);
1558 hash = xmalloc(len);
1559 if (ssh_digest_final(ctx, hash, len) != 0)
1560 fatal_f("ssh_digest_final");
1561 options.timing_secret = PEEK_U64(hash);
1562 freezero(hash, len);
1563 ssh_digest_free(ctx);
1567 if ((buf = sshbuf_new()) == NULL)
1568 fatal_f("could not allocate buffer");
1569 if ((r = sshkey_private_serialize(key, buf)) != 0)
1570 fatal_fr(r, "encode %s key", sshkey_ssh_name(key));
1571 if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
1572 fatal_f("ssh_digest_update");
1578 prepare_proctitle(int ac, char **av)
1583 for (i = 0; i < ac; i++)
1584 xextendf(&ret, " ", "%s", av[i]);
1589 print_config(struct ssh *ssh, struct connection_info *connection_info)
1592 * If no connection info was provided by -C then use
1593 * use a blank one that will cause no predicate to match.
1595 if (connection_info == NULL)
1596 connection_info = get_connection_info(ssh, 0, 0);
1597 connection_info->test = 1;
1598 parse_server_match_config(&options, &includes, connection_info);
1599 dump_config(&options);
1604 * Main program for the daemon.
1607 main(int ac, char **av)
1609 struct ssh *ssh = NULL;
1610 extern char *optarg;
1612 int r, opt, on = 1, do_dump_cfg = 0, already_daemon, remote_port;
1613 int sock_in = -1, sock_out = -1, newsock = -1;
1614 const char *remote_ip, *rdomain;
1615 char *fp, *line, *laddr, *logfile = NULL;
1616 int config_s[2] = { -1 , -1 };
1618 u_int64_t ibytes, obytes;
1621 struct sshkey *pubkey;
1624 struct connection_info *connection_info = NULL;
1627 #ifdef HAVE_SECUREWARE
1628 (void)set_auth_parameters(ac, av);
1630 __progname = ssh_get_progname(av[0]);
1632 sigemptyset(&sigmask);
1633 sigprocmask(SIG_SETMASK, &sigmask, NULL);
1635 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1638 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1639 for (i = 0; (int)i < ac; i++)
1640 saved_argv[i] = xstrdup(av[i]);
1641 saved_argv[i] = NULL;
1643 #ifndef HAVE_SETPROCTITLE
1644 /* Prepare for later setproctitle emulation */
1645 compat_init_setproctitle(ac, av);
1649 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1650 debug("setgroups(): %.200s", strerror(errno));
1652 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1655 /* Initialize configuration options to their default values. */
1656 initialize_server_options(&options);
1658 /* Parse command-line arguments. */
1659 while ((opt = getopt(ac, av,
1660 "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) {
1663 options.address_family = AF_INET;
1666 options.address_family = AF_INET6;
1669 config_file_name = optarg;
1672 servconf_add_hostcert("[command-line]", 0,
1676 if (debug_flag == 0) {
1678 options.log_level = SYSLOG_LEVEL_DEBUG1;
1679 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1680 options.log_level++;
1708 options.log_level = SYSLOG_LEVEL_QUIET;
1711 /* protocol 1, ignored */
1714 options.ports_from_cmdline = 1;
1715 if (options.num_ports >= MAX_PORTS) {
1716 fprintf(stderr, "too many ports.\n");
1719 options.ports[options.num_ports++] = a2port(optarg);
1720 if (options.ports[options.num_ports-1] <= 0) {
1721 fprintf(stderr, "Bad port number.\n");
1726 if ((options.login_grace_time = convtime(optarg)) == -1) {
1727 fprintf(stderr, "Invalid login grace time.\n");
1732 /* protocol 1, ignored */
1735 servconf_add_hostkey("[command-line]", 0,
1736 &options, optarg, 1);
1745 connection_info = get_connection_info(ssh, 0, 0);
1746 if (parse_server_match_testspec(connection_info,
1751 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1752 if (utmp_len > HOST_NAME_MAX+1) {
1753 fprintf(stderr, "Invalid utmp length.\n");
1758 line = xstrdup(optarg);
1759 if (process_server_config_line(&options, line,
1760 "command-line", 0, NULL, NULL, &includes) != 0)
1765 fprintf(stderr, "%s, %s\n",
1766 SSH_VERSION, SSH_OPENSSL_VERSION);
1773 if (rexeced_flag || inetd_flag)
1775 if (!test_flag && !do_dump_cfg && rexec_flag && !path_absolute(av[0]))
1776 fatal("sshd re-exec requires execution with an absolute path");
1778 closefrom(REEXEC_MIN_FREE_FD);
1780 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1784 /* If requested, redirect the logs to the specified logfile. */
1785 if (logfile != NULL)
1786 log_redirect_stderr_to(logfile);
1788 * Force logging to stderr until we have loaded the private host
1789 * key (unless started from inetd)
1791 log_init(__progname,
1792 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1793 SYSLOG_LEVEL_INFO : options.log_level,
1794 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1795 SYSLOG_FACILITY_AUTH : options.log_facility,
1796 log_stderr || !inetd_flag || debug_flag);
1799 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1800 * root's environment
1802 if (getenv("KRB5CCNAME") != NULL)
1803 (void) unsetenv("KRB5CCNAME");
1805 sensitive_data.have_ssh2_key = 0;
1808 * If we're not doing an extended test do not silently ignore connection
1811 if (test_flag < 2 && connection_info != NULL)
1812 fatal("Config test connection parameter (-C) provided without "
1815 /* Fetch our configuration */
1816 if ((cfg = sshbuf_new()) == NULL)
1817 fatal_f("sshbuf_new failed");
1819 setproctitle("%s", "[rexeced]");
1820 recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg);
1822 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1823 close(REEXEC_STARTUP_PIPE_FD);
1825 * Signal parent that this child is at a point where
1826 * they can go away if they have a SIGHUP pending.
1828 (void)atomicio(vwrite, startup_pipe, "\0", 1);
1830 } else if (strcasecmp(config_file_name, "none") != 0)
1831 load_server_config(config_file_name, cfg);
1833 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1834 cfg, &includes, NULL, rexeced_flag);
1837 if (options.moduli_file != NULL)
1838 dh_set_moduli_file(options.moduli_file);
1841 /* Fill in default values for those options not explicitly set. */
1842 fill_default_server_options(&options);
1844 /* Check that options are sensible */
1845 if (options.authorized_keys_command_user == NULL &&
1846 (options.authorized_keys_command != NULL &&
1847 strcasecmp(options.authorized_keys_command, "none") != 0))
1848 fatal("AuthorizedKeysCommand set without "
1849 "AuthorizedKeysCommandUser");
1850 if (options.authorized_principals_command_user == NULL &&
1851 (options.authorized_principals_command != NULL &&
1852 strcasecmp(options.authorized_principals_command, "none") != 0))
1853 fatal("AuthorizedPrincipalsCommand set without "
1854 "AuthorizedPrincipalsCommandUser");
1857 * Check whether there is any path through configured auth methods.
1858 * Unfortunately it is not possible to verify this generally before
1859 * daemonisation in the presence of Match block, but this catches
1860 * and warns for trivial misconfigurations that could break login.
1862 if (options.num_auth_methods != 0) {
1863 for (i = 0; i < options.num_auth_methods; i++) {
1864 if (auth2_methods_valid(options.auth_methods[i],
1868 if (i >= options.num_auth_methods)
1869 fatal("AuthenticationMethods cannot be satisfied by "
1870 "enabled authentication methods");
1873 /* Check that there are no remaining arguments. */
1875 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1879 debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1882 print_config(ssh, connection_info);
1884 /* Store privilege separation user for later use if required. */
1885 privsep_chroot = use_privsep && (getuid() == 0 || geteuid() == 0);
1886 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1887 if (privsep_chroot || options.kerberos_authentication)
1888 fatal("Privilege separation user %s does not exist",
1891 privsep_pw = pwcopy(privsep_pw);
1892 freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
1893 privsep_pw->pw_passwd = xstrdup("*");
1897 /* load host keys */
1898 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1899 sizeof(struct sshkey *));
1900 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1901 sizeof(struct sshkey *));
1903 if (options.host_key_agent) {
1904 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1905 setenv(SSH_AUTHSOCKET_ENV_NAME,
1906 options.host_key_agent, 1);
1907 if ((r = ssh_get_authentication_socket(NULL)) == 0)
1910 error_r(r, "Could not connect to agent \"%s\"",
1911 options.host_key_agent);
1914 for (i = 0; i < options.num_host_key_files; i++) {
1915 int ll = options.host_key_file_userprovided[i] ?
1916 SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
1918 if (options.host_key_files[i] == NULL)
1920 if ((r = sshkey_load_private(options.host_key_files[i], "",
1921 &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1922 do_log2_r(r, ll, "Unable to load host key \"%s\"",
1923 options.host_key_files[i]);
1924 if (sshkey_is_sk(key) &&
1925 key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
1926 debug("host key %s requires user presence, ignoring",
1927 options.host_key_files[i]);
1928 key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
1930 if (r == 0 && key != NULL &&
1931 (r = sshkey_shield_private(key)) != 0) {
1932 do_log2_r(r, ll, "Unable to shield host key \"%s\"",
1933 options.host_key_files[i]);
1937 if ((r = sshkey_load_public(options.host_key_files[i],
1938 &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1939 do_log2_r(r, ll, "Unable to load host key \"%s\"",
1940 options.host_key_files[i]);
1941 if (pubkey != NULL && key != NULL) {
1942 if (!sshkey_equal(pubkey, key)) {
1943 error("Public key for %s does not match "
1944 "private key", options.host_key_files[i]);
1945 sshkey_free(pubkey);
1949 if (pubkey == NULL && key != NULL) {
1950 if ((r = sshkey_from_private(key, &pubkey)) != 0)
1951 fatal_r(r, "Could not demote key: \"%s\"",
1952 options.host_key_files[i]);
1954 if (pubkey != NULL && (r = sshkey_check_rsa_length(pubkey,
1955 options.required_rsa_size)) != 0) {
1956 error_fr(r, "Host key %s", options.host_key_files[i]);
1957 sshkey_free(pubkey);
1961 sensitive_data.host_keys[i] = key;
1962 sensitive_data.host_pubkeys[i] = pubkey;
1964 if (key == NULL && pubkey != NULL && have_agent) {
1965 debug("will rely on agent for hostkey %s",
1966 options.host_key_files[i]);
1967 keytype = pubkey->type;
1968 } else if (key != NULL) {
1969 keytype = key->type;
1970 accumulate_host_timing_secret(cfg, key);
1972 do_log2(ll, "Unable to load host key: %s",
1973 options.host_key_files[i]);
1974 sensitive_data.host_keys[i] = NULL;
1975 sensitive_data.host_pubkeys[i] = NULL;
1985 case KEY_ED25519_SK:
1987 if (have_agent || key != NULL)
1988 sensitive_data.have_ssh2_key = 1;
1991 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1992 SSH_FP_DEFAULT)) == NULL)
1993 fatal("sshkey_fingerprint failed");
1994 debug("%s host key #%d: %s %s",
1995 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1998 accumulate_host_timing_secret(cfg, NULL);
1999 if (!sensitive_data.have_ssh2_key) {
2000 logit("sshd: no hostkeys available -- exiting.");
2005 * Load certificates. They are stored in an array at identical
2006 * indices to the public keys that they relate to.
2008 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
2009 sizeof(struct sshkey *));
2010 for (i = 0; i < options.num_host_key_files; i++)
2011 sensitive_data.host_certificates[i] = NULL;
2013 for (i = 0; i < options.num_host_cert_files; i++) {
2014 if (options.host_cert_files[i] == NULL)
2016 if ((r = sshkey_load_public(options.host_cert_files[i],
2017 &key, NULL)) != 0) {
2018 error_r(r, "Could not load host certificate \"%s\"",
2019 options.host_cert_files[i]);
2022 if (!sshkey_is_cert(key)) {
2023 error("Certificate file is not a certificate: %s",
2024 options.host_cert_files[i]);
2028 /* Find matching private key */
2029 for (j = 0; j < options.num_host_key_files; j++) {
2030 if (sshkey_equal_public(key,
2031 sensitive_data.host_pubkeys[j])) {
2032 sensitive_data.host_certificates[j] = key;
2036 if (j >= options.num_host_key_files) {
2037 error("No matching private key for certificate: %s",
2038 options.host_cert_files[i]);
2042 sensitive_data.host_certificates[j] = key;
2043 debug("host certificate: #%u type %d %s", j, key->type,
2047 if (privsep_chroot) {
2050 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
2051 (S_ISDIR(st.st_mode) == 0))
2052 fatal("Missing privilege separation directory: %s",
2053 _PATH_PRIVSEP_CHROOT_DIR);
2056 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
2057 (st.st_uid != getuid () ||
2058 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
2060 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
2062 fatal("%s must be owned by root and not group or "
2063 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
2067 print_config(ssh, connection_info);
2069 /* Configuration looks good, so exit if in test mode. */
2074 * Clear out any supplemental groups we may have inherited. This
2075 * prevents inadvertent creation of files with bad modes (in the
2076 * portable version at least, it's certainly possible for PAM
2077 * to create a file, and we can't control the code in every
2078 * module which might be used).
2080 if (setgroups(0, NULL) < 0)
2081 debug("setgroups() failed: %.200s", strerror(errno));
2085 fatal("rexec_argc %d < 0", rexec_argc);
2086 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
2087 for (i = 0; i < (u_int)rexec_argc; i++) {
2088 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
2089 rexec_argv[i] = saved_argv[i];
2091 rexec_argv[rexec_argc] = "-R";
2092 rexec_argv[rexec_argc + 1] = NULL;
2094 listener_proctitle = prepare_proctitle(ac, av);
2096 /* Ensure that umask disallows at least group and world write */
2097 new_umask = umask(0077) | 0022;
2098 (void) umask(new_umask);
2100 /* Initialize the log (it is reinitialized below in case we forked). */
2101 if (debug_flag && (!inetd_flag || rexeced_flag))
2103 log_init(__progname, options.log_level,
2104 options.log_facility, log_stderr);
2105 for (i = 0; i < options.num_log_verbose; i++)
2106 log_verbose_add(options.log_verbose[i]);
2109 * If not in debugging mode, not started from inetd and not already
2110 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
2111 * terminal, and fork. The original process exits.
2113 already_daemon = daemonized();
2114 if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
2116 if (daemon(0, 0) == -1)
2117 fatal("daemon() failed: %.200s", strerror(errno));
2119 disconnect_controlling_tty();
2121 /* Reinitialize the log (because of the fork above). */
2122 log_init(__progname, options.log_level, options.log_facility, log_stderr);
2124 /* Avoid killing the process in high-pressure swapping environments. */
2125 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
2126 debug("madvise(): %.200s", strerror(errno));
2129 * Chdir to the root directory so that the current disk can be
2130 * unmounted if desired.
2132 if (chdir("/") == -1)
2133 error("chdir(\"/\"): %s", strerror(errno));
2135 /* ignore SIGPIPE */
2136 ssh_signal(SIGPIPE, SIG_IGN);
2138 /* Get a connection, either from inetd or a listening TCP socket */
2140 server_accept_inetd(&sock_in, &sock_out);
2142 platform_pre_listen();
2145 ssh_signal(SIGHUP, sighup_handler);
2146 ssh_signal(SIGCHLD, main_sigchld_handler);
2147 ssh_signal(SIGTERM, sigterm_handler);
2148 ssh_signal(SIGQUIT, sigterm_handler);
2151 * Write out the pid file after the sigterm handler
2152 * is setup and the listen sockets are bound
2154 if (options.pid_file != NULL && !debug_flag) {
2155 FILE *f = fopen(options.pid_file, "w");
2158 error("Couldn't create pid file \"%s\": %s",
2159 options.pid_file, strerror(errno));
2161 fprintf(f, "%ld\n", (long) getpid());
2166 /* Accept a connection and return in a forked child */
2167 server_accept_loop(&sock_in, &sock_out,
2168 &newsock, config_s);
2171 /* This is the child processing a new connection. */
2172 setproctitle("%s", "[accepted]");
2175 * Create a new session and process group since the 4.4BSD
2176 * setlogin() affects the entire process group. We don't
2177 * want the child to be able to affect the parent.
2179 if (!debug_flag && !inetd_flag && setsid() == -1)
2180 error("setsid: %.100s", strerror(errno));
2183 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
2184 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2185 if (dup2(newsock, STDIN_FILENO) == -1)
2186 debug3_f("dup2 stdin: %s", strerror(errno));
2187 if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1)
2188 debug3_f("dup2 stdout: %s", strerror(errno));
2189 if (startup_pipe == -1)
2190 close(REEXEC_STARTUP_PIPE_FD);
2191 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
2192 if (dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD) == -1)
2193 debug3_f("dup2 startup_p: %s", strerror(errno));
2194 close(startup_pipe);
2195 startup_pipe = REEXEC_STARTUP_PIPE_FD;
2198 if (dup2(config_s[1], REEXEC_CONFIG_PASS_FD) == -1)
2199 debug3_f("dup2 config_s: %s", strerror(errno));
2202 ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */
2203 execv(rexec_argv[0], rexec_argv);
2205 /* Reexec has failed, fall back and continue */
2206 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
2207 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
2208 log_init(__progname, options.log_level,
2209 options.log_facility, log_stderr);
2212 close(REEXEC_CONFIG_PASS_FD);
2213 newsock = sock_out = sock_in = dup(STDIN_FILENO);
2214 if (stdfd_devnull(1, 1, 0) == -1)
2215 error_f("stdfd_devnull failed");
2216 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2217 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2220 /* Executed child processes don't need these. */
2221 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2222 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2224 /* We will not restart on SIGHUP since it no longer makes sense. */
2225 ssh_signal(SIGALRM, SIG_DFL);
2226 ssh_signal(SIGHUP, SIG_DFL);
2227 ssh_signal(SIGTERM, SIG_DFL);
2228 ssh_signal(SIGQUIT, SIG_DFL);
2229 ssh_signal(SIGCHLD, SIG_DFL);
2230 ssh_signal(SIGINT, SIG_DFL);
2234 * Initialize the resolver. This may not happen automatically
2235 * before privsep chroot().
2237 if ((_res.options & RES_INIT) == 0) {
2238 debug("res_init()");
2243 * Force GSS-API to parse its configuration and load any
2244 * mechanism plugins.
2248 OM_uint32 minor_status;
2249 gss_indicate_mechs(&minor_status, &mechs);
2250 gss_release_oid_set(&minor_status, &mechs);
2256 * Register our connection. This turns encryption off because we do
2259 if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
2260 fatal("Unable to create connection");
2261 the_active_state = ssh;
2262 ssh_packet_set_server(ssh);
2264 check_ip_options(ssh);
2266 /* Prepare the channels layer */
2267 channel_init_channels(ssh);
2268 channel_set_af(ssh, options.address_family);
2269 process_channel_timeouts(ssh, &options);
2270 process_permitopen(ssh, &options);
2272 /* Set SO_KEEPALIVE if requested. */
2273 if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) &&
2274 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1)
2275 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2277 if ((remote_port = ssh_remote_port(ssh)) < 0) {
2278 debug("ssh_remote_port failed");
2282 if (options.routing_domain != NULL)
2283 set_process_rdomain(ssh, options.routing_domain);
2286 * The rest of the code depends on the fact that
2287 * ssh_remote_ipaddr() caches the remote ip, even if
2288 * the socket goes away.
2290 remote_ip = ssh_remote_ipaddr(ssh);
2292 #ifdef HAVE_LOGIN_CAP
2293 /* Also caches remote hostname for sandboxed child. */
2294 auth_get_canonical_hostname(ssh, options.use_dns);
2297 #ifdef SSH_AUDIT_EVENTS
2298 audit_connection_from(remote_ip, remote_port);
2301 rdomain = ssh_packet_rdomain_in(ssh);
2303 /* Log the connection. */
2304 laddr = get_local_ipaddr(sock_in);
2305 verbose("Connection from %s port %d on %s port %d%s%s%s",
2306 remote_ip, remote_port, laddr, ssh_local_port(ssh),
2307 rdomain == NULL ? "" : " rdomain \"",
2308 rdomain == NULL ? "" : rdomain,
2309 rdomain == NULL ? "" : "\"");
2313 * We don't want to listen forever unless the other side
2314 * successfully authenticates itself. So we set up an alarm which is
2315 * cleared after successful authentication. A limit of zero
2316 * indicates no limit. Note that we don't set the alarm in debugging
2317 * mode; it is just annoying to have the server exit just when you
2318 * are about to discover the bug.
2320 ssh_signal(SIGALRM, grace_alarm_handler);
2322 alarm(options.login_grace_time);
2324 if ((r = kex_exchange_identification(ssh, -1,
2325 options.version_addendum)) != 0)
2326 sshpkt_fatal(ssh, r, "banner exchange");
2328 ssh_packet_set_nonblocking(ssh);
2330 /* allocate authentication context */
2331 authctxt = xcalloc(1, sizeof(*authctxt));
2332 ssh->authctxt = authctxt;
2334 authctxt->loginmsg = loginmsg;
2336 /* XXX global for cleanup, access from other modules */
2337 the_authctxt = authctxt;
2339 /* Set default key authentication options */
2340 if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
2341 fatal("allocation failed");
2343 /* prepare buffer to collect messages to display to user after login */
2344 if ((loginmsg = sshbuf_new()) == NULL)
2345 fatal_f("sshbuf_new failed");
2351 if (privsep_preauth(ssh) == 1)
2353 } else if (have_agent) {
2354 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2355 error_r(r, "Unable to get agent socket");
2360 /* perform the key exchange */
2361 /* authenticate user and start session */
2363 do_authentication2(ssh);
2366 * If we use privilege separation, the unprivileged child transfers
2367 * the current keystate and exits
2370 mm_send_keystate(ssh, pmonitor);
2371 ssh_packet_clear_keys(ssh);
2377 * Cancel the alarm we set to limit the time taken for
2381 ssh_signal(SIGALRM, SIG_DFL);
2382 authctxt->authenticated = 1;
2383 if (startup_pipe != -1) {
2384 close(startup_pipe);
2388 #ifdef SSH_AUDIT_EVENTS
2389 audit_event(ssh, SSH_AUTH_SUCCESS);
2393 if (options.gss_authentication) {
2394 temporarily_use_uid(authctxt->pw);
2395 ssh_gssapi_storecreds();
2400 if (options.use_pam) {
2402 do_pam_session(ssh);
2407 * In privilege separation, we fork another child and prepare
2408 * file descriptor passing.
2411 privsep_postauth(ssh, authctxt);
2412 /* the monitor process [priv] will not return */
2415 ssh_packet_set_timeout(ssh, options.client_alive_interval,
2416 options.client_alive_count_max);
2418 /* Try to send all our hostkeys to the client */
2419 notify_hostkeys(ssh);
2421 /* Start session. */
2422 do_authenticated(ssh, authctxt);
2424 /* The connection has been terminated. */
2425 ssh_packet_get_bytes(ssh, &ibytes, &obytes);
2426 verbose("Transferred: sent %llu, received %llu bytes",
2427 (unsigned long long)obytes, (unsigned long long)ibytes);
2429 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2432 if (options.use_pam)
2434 #endif /* USE_PAM */
2436 #ifdef SSH_AUDIT_EVENTS
2437 PRIVSEP(audit_event(ssh, SSH_CONNECTION_CLOSE));
2440 ssh_packet_close(ssh);
2449 sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
2450 struct sshkey *pubkey, u_char **signature, size_t *slenp,
2451 const u_char *data, size_t dlen, const char *alg)
2457 if (mm_sshkey_sign(ssh, privkey, signature, slenp,
2458 data, dlen, alg, options.sk_provider, NULL,
2460 fatal_f("privkey sign failed");
2462 if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
2463 data, dlen, alg, options.sk_provider, NULL,
2465 fatal_f("pubkey sign failed");
2469 if (sshkey_sign(privkey, signature, slenp, data, dlen,
2470 alg, options.sk_provider, NULL, ssh->compat) < 0)
2471 fatal_f("privkey sign failed");
2473 if ((r = ssh_agent_sign(auth_sock, pubkey,
2474 signature, slenp, data, dlen, alg,
2475 ssh->compat)) != 0) {
2476 fatal_fr(r, "agent sign failed");
2483 /* SSH2 key exchange */
2485 do_ssh2_kex(struct ssh *ssh)
2487 char *hkalgs = NULL, *myproposal[PROPOSAL_MAX];
2488 const char *compression = NULL;
2492 if (options.rekey_limit || options.rekey_interval)
2493 ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
2494 options.rekey_interval);
2496 if (options.compression == COMP_NONE)
2497 compression = "none";
2498 hkalgs = list_hostkey_types();
2500 kex_proposal_populate_entries(ssh, myproposal, options.kex_algorithms,
2501 options.ciphers, options.macs, compression, hkalgs);
2505 /* start key exchange */
2506 if ((r = kex_setup(ssh, myproposal)) != 0)
2507 fatal_r(r, "kex_setup");
2510 kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
2511 kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
2512 kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
2513 kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
2514 kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
2515 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2516 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2517 # ifdef OPENSSL_HAS_ECC
2518 kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
2521 kex->kex[KEX_C25519_SHA256] = kex_gen_server;
2522 kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
2523 kex->load_host_public_key=&get_hostkey_public_by_type;
2524 kex->load_host_private_key=&get_hostkey_private_by_type;
2525 kex->host_key_index=&get_hostkey_index;
2526 kex->sign = sshd_hostkey_sign;
2528 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
2531 /* send 1st encrypted/maced/compressed message */
2532 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2533 (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
2534 (r = sshpkt_send(ssh)) != 0 ||
2535 (r = ssh_packet_write_wait(ssh)) != 0)
2536 fatal_fr(r, "send test");
2538 kex_proposal_free_entries(myproposal);
2542 /* server specific fatal cleanup */
2546 if (the_active_state != NULL && the_authctxt != NULL) {
2547 do_cleanup(the_active_state, the_authctxt);
2548 if (use_privsep && privsep_is_preauth &&
2549 pmonitor != NULL && pmonitor->m_pid > 1) {
2550 debug("Killing privsep child %d", pmonitor->m_pid);
2551 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2553 error_f("kill(%d): %s", pmonitor->m_pid,
2558 #ifdef SSH_AUDIT_EVENTS
2559 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2560 if (the_active_state != NULL && (!use_privsep || mm_is_monitor()))
2561 audit_event(the_active_state, SSH_CONNECTION_ABANDON);