1 /* $OpenBSD: sshd.c,v 1.428 2014/07/15 15:54:14 millert Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This program is the ssh daemon. It listens for connections from clients,
7 * and performs authentication, executes use commands or shell, and forwards
8 * information to/from the application to the user client over an encrypted
9 * connection. This can also handle forwarding of X11, TCP/IP, and
10 * authentication agent connections.
12 * As far as I am concerned, the code I have written for this software
13 * can be used freely for any purpose. Any derived versions of this
14 * software must be clearly marked as such, and if the derived work is
15 * incompatible with the protocol description in the RFC file, it must be
16 * called by a name other than "ssh" or "Secure Shell".
18 * SSH2 implementation:
19 * Privilege Separation:
21 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
22 * Copyright (c) 2002 Niels Provos. All rights reserved.
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
27 * 1. Redistributions of source code must retain the above copyright
28 * notice, this list of conditions and the following disclaimer.
29 * 2. Redistributions in binary form must reproduce the above copyright
30 * notice, this list of conditions and the following disclaimer in the
31 * documentation and/or other materials provided with the distribution.
33 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47 #include <sys/types.h>
48 #include <sys/ioctl.h>
49 #include <sys/socket.h>
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
53 #ifdef HAVE_SYS_TIME_H
54 # include <sys/time.h>
56 #include "openbsd-compat/sys-tree.h"
57 #include "openbsd-compat/sys-queue.h"
76 #include <openssl/dh.h>
77 #include <openssl/bn.h>
78 #include <openssl/rand.h>
79 #include "openbsd-compat/openssl-compat.h"
82 #ifdef HAVE_SECUREWARE
83 #include <sys/security.h>
105 #include "myproposal.h"
106 #include "authfile.h"
107 #include "pathnames.h"
108 #include "atomicio.h"
109 #include "canohost.h"
110 #include "hostfile.h"
114 #include "dispatch.h"
115 #include "channels.h"
117 #include "monitor_mm.h"
122 #include "monitor_wrap.h"
124 #include "ssh-sandbox.h"
132 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
133 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
134 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
135 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
140 extern char *__progname;
142 /* Server configuration options. */
143 ServerOptions options;
145 /* Name of the server configuration file. */
146 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
149 * Debug mode flag. This can be set on the command line. If debug
150 * mode is enabled, extra debugging output will be sent to the system
151 * log, the daemon will not go to background, and will exit after processing
152 * the first connection.
156 /* Flag indicating that the daemon should only test the configuration and keys. */
159 /* Flag indicating that the daemon is being started from inetd. */
162 /* Flag indicating that sshd should not detach and become a daemon. */
163 int no_daemon_flag = 0;
165 /* debug goes to stderr unless inetd_flag is set */
168 /* Saved arguments to main(). */
173 int rexeced_flag = 0;
179 * The sockets that the server is listening; this is used in the SIGHUP
182 #define MAX_LISTEN_SOCKS 16
183 int listen_socks[MAX_LISTEN_SOCKS];
184 int num_listen_socks = 0;
187 * the client's version string, passed by sshd2 in compat mode. if != NULL,
188 * sshd will skip the version-number exchange
190 char *client_version_string = NULL;
191 char *server_version_string = NULL;
193 /* for rekeying XXX fixme */
196 /* Daemon's agent connection */
197 AuthenticationConnection *auth_conn = NULL;
201 * Any really sensitive data in the application is contained in this
202 * structure. The idea is that this structure could be locked into memory so
203 * that the pages do not get written into swap. However, there are some
204 * problems. The private key contains BIGNUMs, and we do not (in principle)
205 * have access to the internals of them, and locking just the structure is
206 * not very useful. Currently, memory locking is not implemented.
209 Key *server_key; /* ephemeral server key */
210 Key *ssh1_host_key; /* ssh1 host key */
211 Key **host_keys; /* all private host keys */
212 Key **host_pubkeys; /* all public host keys */
213 Key **host_certificates; /* all public host certificates */
216 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
220 * Flag indicating whether the RSA server key needs to be regenerated.
221 * Is set in the SIGALRM handler and cleared when the key is regenerated.
223 static volatile sig_atomic_t key_do_regen = 0;
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 /* session identifier, used by RSA-auth */
230 u_char session_id[16];
233 u_char *session_id2 = NULL;
234 u_int session_id2_len = 0;
236 /* record remote hostname or ip */
237 u_int utmp_len = MAXHOSTNAMELEN;
239 /* options.max_startup sized array of fd ints */
240 int *startup_pipes = NULL;
241 int startup_pipe; /* in child */
243 /* variables used for privilege separation */
244 int use_privsep = -1;
245 struct monitor *pmonitor = NULL;
246 int privsep_is_preauth = 1;
248 /* global authentication context */
249 Authctxt *the_authctxt = NULL;
251 /* sshd_config buffer */
254 /* message to be displayed after login */
257 /* Unprivileged user */
258 struct passwd *privsep_pw = NULL;
260 /* Prototypes for various functions defined later in this file. */
261 void destroy_sensitive_data(void);
262 void demote_sensitive_data(void);
265 static void do_ssh1_kex(void);
267 static void do_ssh2_kex(void);
270 * Close all listening sockets
273 close_listen_socks(void)
277 for (i = 0; i < num_listen_socks; i++)
278 close(listen_socks[i]);
279 num_listen_socks = -1;
283 close_startup_pipes(void)
288 for (i = 0; i < options.max_startups; i++)
289 if (startup_pipes[i] != -1)
290 close(startup_pipes[i]);
294 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
295 * the effect is to reread the configuration file (and to regenerate
301 sighup_handler(int sig)
303 int save_errno = errno;
306 signal(SIGHUP, sighup_handler);
311 * Called from the main program after receiving SIGHUP.
312 * Restarts the server.
317 logit("Received SIGHUP; restarting.");
318 platform_pre_restart();
319 close_listen_socks();
320 close_startup_pipes();
321 alarm(0); /* alarm timer persists across exec */
322 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
323 execv(saved_argv[0], saved_argv);
324 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
330 * Generic signal handler for terminating signals in the master daemon.
334 sigterm_handler(int sig)
336 received_sigterm = sig;
340 * SIGCHLD handler. This is called whenever a child dies. This will then
341 * reap any zombies left by exited children.
345 main_sigchld_handler(int sig)
347 int save_errno = errno;
351 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
352 (pid < 0 && errno == EINTR))
355 signal(SIGCHLD, main_sigchld_handler);
360 * Signal handler for the alarm after the login grace period has expired.
364 grace_alarm_handler(int sig)
366 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
367 kill(pmonitor->m_pid, SIGALRM);
370 * Try to kill any processes that we have spawned, E.g. authorized
371 * keys command helpers.
373 if (getpgid(0) == getpid()) {
374 signal(SIGTERM, SIG_IGN);
378 /* Log error and exit. */
379 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
383 * Signal handler for the key regeneration alarm. Note that this
384 * alarm only occurs in the daemon waiting for connections, and it does not
385 * do anything with the private key or random state before forking.
386 * Thus there should be no concurrency control/asynchronous execution
390 generate_ephemeral_server_key(void)
392 verbose("Generating %s%d bit RSA key.",
393 sensitive_data.server_key ? "new " : "", options.server_key_bits);
394 if (sensitive_data.server_key != NULL)
395 key_free(sensitive_data.server_key);
396 sensitive_data.server_key = key_generate(KEY_RSA1,
397 options.server_key_bits);
398 verbose("RSA key generation complete.");
400 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
405 key_regeneration_alarm(int sig)
407 int save_errno = errno;
409 signal(SIGALRM, SIG_DFL);
415 sshd_exchange_identification(int sock_in, int sock_out)
419 int remote_major, remote_minor;
421 char *s, *newline = "\n";
422 char buf[256]; /* Must not be larger than remote_version. */
423 char remote_version[256]; /* Must be at least as big as buf. */
425 if ((options.protocol & SSH_PROTO_1) &&
426 (options.protocol & SSH_PROTO_2)) {
427 major = PROTOCOL_MAJOR_1;
429 } else if (options.protocol & SSH_PROTO_2) {
430 major = PROTOCOL_MAJOR_2;
431 minor = PROTOCOL_MINOR_2;
434 major = PROTOCOL_MAJOR_1;
435 minor = PROTOCOL_MINOR_1;
438 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s",
439 major, minor, SSH_RELEASE,
440 *options.version_addendum == '\0' ? "" : " ",
441 options.version_addendum, newline);
443 /* Send our protocol version identification. */
444 if (roaming_atomicio(vwrite, sock_out, server_version_string,
445 strlen(server_version_string))
446 != strlen(server_version_string)) {
447 logit("Could not write ident string to %s", get_remote_ipaddr());
451 /* Read other sides version identification. */
452 memset(buf, 0, sizeof(buf));
453 for (i = 0; i < sizeof(buf) - 1; i++) {
454 if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
455 logit("Did not receive identification string from %s",
456 get_remote_ipaddr());
459 if (buf[i] == '\r') {
461 /* Kludge for F-Secure Macintosh < 1.0.2 */
463 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
467 if (buf[i] == '\n') {
472 buf[sizeof(buf) - 1] = 0;
473 client_version_string = xstrdup(buf);
476 * Check that the versions match. In future this might accept
477 * several versions and set appropriate flags to handle them.
479 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
480 &remote_major, &remote_minor, remote_version) != 3) {
481 s = "Protocol mismatch.\n";
482 (void) atomicio(vwrite, sock_out, s, strlen(s));
483 logit("Bad protocol version identification '%.100s' "
484 "from %s port %d", client_version_string,
485 get_remote_ipaddr(), get_remote_port());
490 debug("Client protocol version %d.%d; client software version %.100s",
491 remote_major, remote_minor, remote_version);
492 logit("SSH: Server;Ltype: Version;Remote: %s-%d;Protocol: %d.%d;Client: %.100s",
493 get_remote_ipaddr(), get_remote_port(),
494 remote_major, remote_minor, remote_version);
496 compat_datafellows(remote_version);
498 if ((datafellows & SSH_BUG_PROBE) != 0) {
499 logit("probed from %s with %s. Don't panic.",
500 get_remote_ipaddr(), client_version_string);
503 if ((datafellows & SSH_BUG_SCANNER) != 0) {
504 logit("scanned from %s with %s. Don't panic.",
505 get_remote_ipaddr(), client_version_string);
508 if ((datafellows & SSH_BUG_RSASIGMD5) != 0) {
509 logit("Client version \"%.100s\" uses unsafe RSA signature "
510 "scheme; disabling use of RSA keys", remote_version);
512 if ((datafellows & SSH_BUG_DERIVEKEY) != 0) {
513 fatal("Client version \"%.100s\" uses unsafe key agreement; "
514 "refusing connection", remote_version);
518 switch (remote_major) {
520 if (remote_minor == 99) {
521 if (options.protocol & SSH_PROTO_2)
527 if (!(options.protocol & SSH_PROTO_1)) {
531 if (remote_minor < 3) {
532 packet_disconnect("Your ssh version is too old and "
533 "is no longer supported. Please install a newer version.");
534 } else if (remote_minor == 3) {
535 /* note that this disables agent-forwarding */
540 if (options.protocol & SSH_PROTO_2) {
549 chop(server_version_string);
550 debug("Local version string %.200s", server_version_string);
553 s = "Protocol major versions differ.\n";
554 (void) atomicio(vwrite, sock_out, s, strlen(s));
557 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
559 server_version_string, client_version_string);
564 /* Destroy the host and server keys. They will no longer be needed. */
566 destroy_sensitive_data(void)
570 if (sensitive_data.server_key) {
571 key_free(sensitive_data.server_key);
572 sensitive_data.server_key = NULL;
574 for (i = 0; i < options.num_host_key_files; i++) {
575 if (sensitive_data.host_keys[i]) {
576 key_free(sensitive_data.host_keys[i]);
577 sensitive_data.host_keys[i] = NULL;
579 if (sensitive_data.host_certificates[i]) {
580 key_free(sensitive_data.host_certificates[i]);
581 sensitive_data.host_certificates[i] = NULL;
584 sensitive_data.ssh1_host_key = NULL;
585 explicit_bzero(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
588 /* Demote private to public keys for network child */
590 demote_sensitive_data(void)
595 if (sensitive_data.server_key) {
596 tmp = key_demote(sensitive_data.server_key);
597 key_free(sensitive_data.server_key);
598 sensitive_data.server_key = tmp;
601 for (i = 0; i < options.num_host_key_files; i++) {
602 if (sensitive_data.host_keys[i]) {
603 tmp = key_demote(sensitive_data.host_keys[i]);
604 key_free(sensitive_data.host_keys[i]);
605 sensitive_data.host_keys[i] = tmp;
606 if (tmp->type == KEY_RSA1)
607 sensitive_data.ssh1_host_key = tmp;
609 /* Certs do not need demotion */
612 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
616 privsep_preauth_child(void)
621 /* Enable challenge-response authentication for privilege separation */
622 privsep_challenge_enable();
625 /* Cache supported mechanism OIDs for later use */
626 if (options.gss_authentication)
627 ssh_gssapi_prepare_supported_oids();
631 arc4random_buf(rnd, sizeof(rnd));
632 RAND_seed(rnd, sizeof(rnd));
633 explicit_bzero(rnd, sizeof(rnd));
635 /* Demote the private keys to public keys. */
636 demote_sensitive_data();
638 /* Change our root directory */
639 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
640 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
642 if (chdir("/") == -1)
643 fatal("chdir(\"/\"): %s", strerror(errno));
645 /* Drop our privileges */
646 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
647 (u_int)privsep_pw->pw_gid);
649 /* XXX not ready, too heavy after chroot */
650 do_setusercontext(privsep_pw);
652 gidset[0] = privsep_pw->pw_gid;
653 if (setgroups(1, gidset) < 0)
654 fatal("setgroups: %.100s", strerror(errno));
655 permanently_set_uid(privsep_pw);
660 privsep_preauth(Authctxt *authctxt)
664 struct ssh_sandbox *box = NULL;
666 /* Set up unprivileged child process to deal with network data */
667 pmonitor = monitor_init();
668 /* Store a pointer to the kex for later rekeying */
669 pmonitor->m_pkex = &xxx_kex;
671 if (use_privsep == PRIVSEP_ON)
672 box = ssh_sandbox_init(pmonitor);
675 fatal("fork of unprivileged child failed");
676 } else if (pid != 0) {
677 debug2("Network child is on pid %ld", (long)pid);
679 pmonitor->m_pid = pid;
681 auth_conn = ssh_get_authentication_connection();
683 ssh_sandbox_parent_preauth(box, pid);
684 monitor_child_preauth(authctxt, pmonitor);
687 monitor_sync(pmonitor);
689 /* Wait for the child's exit status */
690 while (waitpid(pid, &status, 0) < 0) {
693 pmonitor->m_pid = -1;
694 fatal("%s: waitpid: %s", __func__, strerror(errno));
696 privsep_is_preauth = 0;
697 pmonitor->m_pid = -1;
698 if (WIFEXITED(status)) {
699 if (WEXITSTATUS(status) != 0)
700 fatal("%s: preauth child exited with status %d",
701 __func__, WEXITSTATUS(status));
702 } else if (WIFSIGNALED(status))
703 fatal("%s: preauth child terminated by signal %d",
704 __func__, WTERMSIG(status));
706 ssh_sandbox_parent_finish(box);
710 close(pmonitor->m_sendfd);
711 close(pmonitor->m_log_recvfd);
713 /* Arrange for logging to be sent to the monitor */
714 set_log_handler(mm_log_handler, pmonitor);
716 /* Demote the child */
717 if (getuid() == 0 || geteuid() == 0)
718 privsep_preauth_child();
719 setproctitle("%s", "[net]");
721 ssh_sandbox_child(box);
728 privsep_postauth(Authctxt *authctxt)
732 #ifdef DISABLE_FD_PASSING
735 if (authctxt->pw->pw_uid == 0 || options.use_login) {
737 /* File descriptor passing is broken or root login */
742 /* New socket pair */
743 monitor_reinit(pmonitor);
745 pmonitor->m_pid = fork();
746 if (pmonitor->m_pid == -1)
747 fatal("fork of unprivileged child failed");
748 else if (pmonitor->m_pid != 0) {
749 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
750 buffer_clear(&loginmsg);
751 monitor_child_postauth(pmonitor);
759 close(pmonitor->m_sendfd);
760 pmonitor->m_sendfd = -1;
762 /* Demote the private keys to public keys. */
763 demote_sensitive_data();
766 arc4random_buf(rnd, sizeof(rnd));
767 RAND_seed(rnd, sizeof(rnd));
768 explicit_bzero(rnd, sizeof(rnd));
770 /* Drop privileges */
771 do_setusercontext(authctxt->pw);
774 /* It is safe now to apply the key state */
775 monitor_apply_keystate(pmonitor);
778 * Tell the packet layer that authentication was successful, since
779 * this information is not part of the key state.
781 packet_set_authenticated();
785 list_hostkey_types(void)
794 for (i = 0; i < options.num_host_key_files; i++) {
795 key = sensitive_data.host_keys[i];
797 key = sensitive_data.host_pubkeys[i];
805 if (buffer_len(&b) > 0)
806 buffer_append(&b, ",", 1);
807 p = key_ssh_name(key);
808 buffer_append(&b, p, strlen(p));
811 /* If the private key has a cert peer, then list that too */
812 key = sensitive_data.host_certificates[i];
816 case KEY_RSA_CERT_V00:
817 case KEY_DSA_CERT_V00:
821 case KEY_ED25519_CERT:
822 if (buffer_len(&b) > 0)
823 buffer_append(&b, ",", 1);
824 p = key_ssh_name(key);
825 buffer_append(&b, p, strlen(p));
829 buffer_append(&b, "\0", 1);
830 ret = xstrdup(buffer_ptr(&b));
832 debug("list_hostkey_types: %s", ret);
837 get_hostkey_by_type(int type, int need_private)
842 for (i = 0; i < options.num_host_key_files; i++) {
844 case KEY_RSA_CERT_V00:
845 case KEY_DSA_CERT_V00:
849 case KEY_ED25519_CERT:
850 key = sensitive_data.host_certificates[i];
853 key = sensitive_data.host_keys[i];
854 if (key == NULL && !need_private)
855 key = sensitive_data.host_pubkeys[i];
858 if (key != NULL && key->type == type)
859 return need_private ?
860 sensitive_data.host_keys[i] : key;
866 get_hostkey_public_by_type(int type)
868 return get_hostkey_by_type(type, 0);
872 get_hostkey_private_by_type(int type)
874 return get_hostkey_by_type(type, 1);
878 get_hostkey_by_index(int ind)
880 if (ind < 0 || ind >= options.num_host_key_files)
882 return (sensitive_data.host_keys[ind]);
886 get_hostkey_public_by_index(int ind)
888 if (ind < 0 || ind >= options.num_host_key_files)
890 return (sensitive_data.host_pubkeys[ind]);
894 get_hostkey_index(Key *key)
898 for (i = 0; i < options.num_host_key_files; i++) {
899 if (key_is_cert(key)) {
900 if (key == sensitive_data.host_certificates[i])
903 if (key == sensitive_data.host_keys[i])
905 if (key == sensitive_data.host_pubkeys[i])
913 * returns 1 if connection should be dropped, 0 otherwise.
914 * dropping starts at connection #max_startups_begin with a probability
915 * of (max_startups_rate/100). the probability increases linearly until
916 * all connections are dropped for startups > max_startups
919 drop_connection(int startups)
923 if (startups < options.max_startups_begin)
925 if (startups >= options.max_startups)
927 if (options.max_startups_rate == 100)
930 p = 100 - options.max_startups_rate;
931 p *= startups - options.max_startups_begin;
932 p /= options.max_startups - options.max_startups_begin;
933 p += options.max_startups_rate;
934 r = arc4random_uniform(100);
936 debug("drop_connection: p %d, r %d", p, r);
937 return (r < p) ? 1 : 0;
943 fprintf(stderr, "%s, %s\n",
946 SSLeay_version(SSLEAY_VERSION)
952 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
953 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
954 " [-h host_key_file] [-k key_gen_time] [-o option] [-p port]\n"
961 send_rexec_state(int fd, Buffer *conf)
965 debug3("%s: entering fd = %d config len %d", __func__, fd,
969 * Protocol from reexec master to child:
970 * string configuration
971 * u_int ephemeral_key_follows
972 * bignum e (only if ephemeral_key_follows == 1)
978 * string rngseed (only if OpenSSL is not self-seeded)
981 buffer_put_cstring(&m, buffer_ptr(conf));
984 if (sensitive_data.server_key != NULL &&
985 sensitive_data.server_key->type == KEY_RSA1) {
986 buffer_put_int(&m, 1);
987 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
988 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
989 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
990 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
991 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
992 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
995 buffer_put_int(&m, 0);
997 #ifndef OPENSSL_PRNG_ONLY
998 rexec_send_rng_seed(&m);
1001 if (ssh_msg_send(fd, 0, &m) == -1)
1002 fatal("%s: ssh_msg_send failed", __func__);
1006 debug3("%s: done", __func__);
1010 recv_rexec_state(int fd, Buffer *conf)
1016 debug3("%s: entering fd = %d", __func__, fd);
1020 if (ssh_msg_recv(fd, &m) == -1)
1021 fatal("%s: ssh_msg_recv failed", __func__);
1022 if (buffer_get_char(&m) != 0)
1023 fatal("%s: rexec version mismatch", __func__);
1025 cp = buffer_get_string(&m, &len);
1027 buffer_append(conf, cp, len + 1);
1030 if (buffer_get_int(&m)) {
1032 if (sensitive_data.server_key != NULL)
1033 key_free(sensitive_data.server_key);
1034 sensitive_data.server_key = key_new_private(KEY_RSA1);
1035 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
1036 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
1037 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
1038 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1039 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
1040 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
1041 if (rsa_generate_additional_parameters(
1042 sensitive_data.server_key->rsa) != 0)
1043 fatal("%s: rsa_generate_additional_parameters "
1046 fatal("ssh1 not supported");
1050 #ifndef OPENSSL_PRNG_ONLY
1051 rexec_recv_rng_seed(&m);
1056 debug3("%s: done", __func__);
1059 /* Accept a connection from inetd */
1061 server_accept_inetd(int *sock_in, int *sock_out)
1067 close(REEXEC_CONFIG_PASS_FD);
1068 *sock_in = *sock_out = dup(STDIN_FILENO);
1070 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1071 close(REEXEC_STARTUP_PIPE_FD);
1074 *sock_in = dup(STDIN_FILENO);
1075 *sock_out = dup(STDOUT_FILENO);
1078 * We intentionally do not close the descriptors 0, 1, and 2
1079 * as our code for setting the descriptors won't work if
1080 * ttyfd happens to be one of those.
1082 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1083 dup2(fd, STDIN_FILENO);
1084 dup2(fd, STDOUT_FILENO);
1086 dup2(fd, STDERR_FILENO);
1087 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1090 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1094 * Listen for TCP connections
1099 int ret, listen_sock, on = 1;
1100 struct addrinfo *ai;
1101 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1103 int socksizelen = sizeof(int);
1105 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1106 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1108 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1109 fatal("Too many listen sockets. "
1110 "Enlarge MAX_LISTEN_SOCKS");
1111 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1112 ntop, sizeof(ntop), strport, sizeof(strport),
1113 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1114 error("getnameinfo failed: %.100s",
1115 ssh_gai_strerror(ret));
1118 /* Create socket for listening. */
1119 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1121 if (listen_sock < 0) {
1122 /* kernel may not support ipv6 */
1123 verbose("socket: %.100s", strerror(errno));
1126 if (set_nonblock(listen_sock) == -1) {
1131 * Set socket options.
1132 * Allow local port reuse in TIME_WAIT.
1134 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1135 &on, sizeof(on)) == -1)
1136 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1138 /* Only communicate in IPv6 over AF_INET6 sockets. */
1139 if (ai->ai_family == AF_INET6)
1140 sock_set_v6only(listen_sock);
1142 debug("Bind to port %s on %s.", strport, ntop);
1144 getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF,
1145 &socksize, &socksizelen);
1146 debug("Server TCP RWIN socket size: %d", socksize);
1147 debug("HPN Buffer Size: %d", options.hpn_buffer_size);
1149 /* Bind the socket to the desired port. */
1150 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1151 error("Bind to port %s on %s failed: %.200s.",
1152 strport, ntop, strerror(errno));
1156 listen_socks[num_listen_socks] = listen_sock;
1159 /* Start listening on the port. */
1160 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1161 fatal("listen on [%s]:%s: %.100s",
1162 ntop, strport, strerror(errno));
1163 logit("Server listening on %s port %s.", ntop, strport);
1165 freeaddrinfo(options.listen_addrs);
1167 if (!num_listen_socks)
1168 fatal("Cannot bind any address.");
1172 * The main TCP accept loop. Note that, for the non-debug case, returns
1173 * from this function are in a forked subprocess.
1176 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1179 int i, j, ret, maxfd;
1180 int key_used = 0, startups = 0;
1181 int startup_p[2] = { -1 , -1 };
1182 struct sockaddr_storage from;
1187 /* setup fd set for accept */
1190 for (i = 0; i < num_listen_socks; i++)
1191 if (listen_socks[i] > maxfd)
1192 maxfd = listen_socks[i];
1193 /* pipes connected to unauthenticated childs */
1194 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1195 for (i = 0; i < options.max_startups; i++)
1196 startup_pipes[i] = -1;
1199 * Stay listening for connections until the system crashes or
1200 * the daemon is killed with a signal.
1203 if (received_sighup)
1207 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1210 for (i = 0; i < num_listen_socks; i++)
1211 FD_SET(listen_socks[i], fdset);
1212 for (i = 0; i < options.max_startups; i++)
1213 if (startup_pipes[i] != -1)
1214 FD_SET(startup_pipes[i], fdset);
1216 /* Wait in select until there is a connection. */
1217 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1218 if (ret < 0 && errno != EINTR)
1219 error("select: %.100s", strerror(errno));
1220 if (received_sigterm) {
1221 logit("Received signal %d; terminating.",
1222 (int) received_sigterm);
1223 close_listen_socks();
1224 unlink(options.pid_file);
1225 exit(received_sigterm == SIGTERM ? 0 : 255);
1227 if (key_used && key_do_regen) {
1228 generate_ephemeral_server_key();
1235 for (i = 0; i < options.max_startups; i++)
1236 if (startup_pipes[i] != -1 &&
1237 FD_ISSET(startup_pipes[i], fdset)) {
1239 * the read end of the pipe is ready
1240 * if the child has closed the pipe
1241 * after successful authentication
1242 * or if the child has died
1244 close(startup_pipes[i]);
1245 startup_pipes[i] = -1;
1248 for (i = 0; i < num_listen_socks; i++) {
1249 if (!FD_ISSET(listen_socks[i], fdset))
1251 fromlen = sizeof(from);
1252 *newsock = accept(listen_socks[i],
1253 (struct sockaddr *)&from, &fromlen);
1255 if (errno != EINTR && errno != EWOULDBLOCK &&
1256 errno != ECONNABORTED && errno != EAGAIN)
1257 error("accept: %.100s",
1259 if (errno == EMFILE || errno == ENFILE)
1263 if (unset_nonblock(*newsock) == -1) {
1267 if (drop_connection(startups) == 1) {
1268 debug("drop connection #%d", startups);
1272 if (pipe(startup_p) == -1) {
1277 if (rexec_flag && socketpair(AF_UNIX,
1278 SOCK_STREAM, 0, config_s) == -1) {
1279 error("reexec socketpair: %s",
1282 close(startup_p[0]);
1283 close(startup_p[1]);
1287 for (j = 0; j < options.max_startups; j++)
1288 if (startup_pipes[j] == -1) {
1289 startup_pipes[j] = startup_p[0];
1290 if (maxfd < startup_p[0])
1291 maxfd = startup_p[0];
1297 * Got connection. Fork a child to handle it, unless
1298 * we are in debugging mode.
1302 * In debugging mode. Close the listening
1303 * socket, and start processing the
1304 * connection without forking.
1306 debug("Server will not fork when running in debugging mode.");
1307 close_listen_socks();
1308 *sock_in = *newsock;
1309 *sock_out = *newsock;
1310 close(startup_p[0]);
1311 close(startup_p[1]);
1315 send_rexec_state(config_s[0],
1323 * Normal production daemon. Fork, and have
1324 * the child process the connection. The
1325 * parent continues listening.
1327 platform_pre_fork();
1328 if ((pid = fork()) == 0) {
1330 * Child. Close the listening and
1331 * max_startup sockets. Start using
1332 * the accepted socket. Reinitialize
1333 * logging (since our pid has changed).
1334 * We break out of the loop to handle
1337 platform_post_fork_child();
1338 startup_pipe = startup_p[1];
1339 close_startup_pipes();
1340 close_listen_socks();
1341 *sock_in = *newsock;
1342 *sock_out = *newsock;
1343 log_init(__progname,
1345 options.log_facility,
1352 /* Parent. Stay in the loop. */
1353 platform_post_fork_parent(pid);
1355 error("fork: %.100s", strerror(errno));
1357 debug("Forked child %ld.", (long)pid);
1359 close(startup_p[1]);
1362 send_rexec_state(config_s[0], &cfg);
1368 * Mark that the key has been used (it
1369 * was "given" to the child).
1371 if ((options.protocol & SSH_PROTO_1) &&
1373 /* Schedule server key regeneration alarm. */
1374 signal(SIGALRM, key_regeneration_alarm);
1375 alarm(options.key_regeneration_time);
1382 * Ensure that our random state differs
1383 * from that of the child
1386 arc4random_buf(rnd, sizeof(rnd));
1387 RAND_seed(rnd, sizeof(rnd));
1388 explicit_bzero(rnd, sizeof(rnd));
1391 /* child process check (or debug mode) */
1392 if (num_listen_socks < 0)
1399 * Main program for the daemon.
1402 main(int ac, char **av)
1404 extern char *optarg;
1406 int opt, i, j, on = 1;
1407 int sock_in = -1, sock_out = -1, newsock = -1;
1408 const char *remote_ip;
1410 char *line, *logfile = NULL;
1411 int config_s[2] = { -1 , -1 };
1413 u_int64_t ibytes, obytes;
1419 struct connection_info *connection_info = get_connection_info(0, 0);
1421 #ifdef HAVE_SECUREWARE
1422 (void)set_auth_parameters(ac, av);
1424 __progname = ssh_get_progname(av[0]);
1426 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1429 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1430 for (i = 0; i < ac; i++)
1431 saved_argv[i] = xstrdup(av[i]);
1432 saved_argv[i] = NULL;
1434 #ifndef HAVE_SETPROCTITLE
1435 /* Prepare for later setproctitle emulation */
1436 compat_init_setproctitle(ac, av);
1440 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1441 debug("setgroups(): %.200s", strerror(errno));
1443 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1446 /* Initialize configuration options to their default values. */
1447 initialize_server_options(&options);
1449 /* Parse command-line arguments. */
1450 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeE:iqrtQRT46")) != -1) {
1453 options.address_family = AF_INET;
1456 options.address_family = AF_INET6;
1459 config_file_name = optarg;
1462 if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1463 fprintf(stderr, "too many host certificates.\n");
1466 options.host_cert_files[options.num_host_cert_files++] =
1467 derelativise_path(optarg);
1470 if (debug_flag == 0) {
1472 options.log_level = SYSLOG_LEVEL_DEBUG1;
1473 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1474 options.log_level++;
1480 logfile = xstrdup(optarg);
1499 options.log_level = SYSLOG_LEVEL_QUIET;
1502 options.server_key_bits = (int)strtonum(optarg, 256,
1506 options.ports_from_cmdline = 1;
1507 if (options.num_ports >= MAX_PORTS) {
1508 fprintf(stderr, "too many ports.\n");
1511 options.ports[options.num_ports++] = a2port(optarg);
1512 if (options.ports[options.num_ports-1] <= 0) {
1513 fprintf(stderr, "Bad port number.\n");
1518 if ((options.login_grace_time = convtime(optarg)) == -1) {
1519 fprintf(stderr, "Invalid login grace time.\n");
1524 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1525 fprintf(stderr, "Invalid key regeneration interval.\n");
1530 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1531 fprintf(stderr, "too many host keys.\n");
1534 options.host_key_files[options.num_host_key_files++] =
1535 derelativise_path(optarg);
1544 if (parse_server_match_testspec(connection_info,
1549 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1550 if (utmp_len > MAXHOSTNAMELEN) {
1551 fprintf(stderr, "Invalid utmp length.\n");
1556 line = xstrdup(optarg);
1557 if (process_server_config_line(&options, line,
1558 "command-line", 0, NULL, NULL) != 0)
1568 if (rexeced_flag || inetd_flag)
1570 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1571 fatal("sshd re-exec requires execution with an absolute path");
1573 closefrom(REEXEC_MIN_FREE_FD);
1575 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1578 OpenSSL_add_all_algorithms();
1581 /* If requested, redirect the logs to the specified logfile. */
1582 if (logfile != NULL) {
1583 log_redirect_stderr_to(logfile);
1587 * Force logging to stderr until we have loaded the private host
1588 * key (unless started from inetd)
1590 log_init(__progname,
1591 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1592 SYSLOG_LEVEL_INFO : options.log_level,
1593 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1594 SYSLOG_FACILITY_AUTH : options.log_facility,
1595 log_stderr || !inetd_flag);
1598 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1599 * root's environment
1601 if (getenv("KRB5CCNAME") != NULL)
1602 (void) unsetenv("KRB5CCNAME");
1605 /* Cray can define user privs drop all privs now!
1606 * Not needed on PRIV_SU systems!
1611 sensitive_data.server_key = NULL;
1612 sensitive_data.ssh1_host_key = NULL;
1613 sensitive_data.have_ssh1_key = 0;
1614 sensitive_data.have_ssh2_key = 0;
1617 * If we're doing an extended config test, make sure we have all of
1618 * the parameters we need. If we're not doing an extended test,
1619 * do not silently ignore connection test params.
1621 if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1622 fatal("user, host and addr are all required when testing "
1624 if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1625 fatal("Config test connection parameter (-C) provided without "
1628 /* Fetch our configuration */
1631 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1633 load_server_config(config_file_name, &cfg);
1635 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1640 /* Fill in default values for those options not explicitly set. */
1641 fill_default_server_options(&options);
1643 /* challenge-response is implemented via keyboard interactive */
1644 if (options.challenge_response_authentication)
1645 options.kbd_interactive_authentication = 1;
1647 /* Check that options are sensible */
1648 if (options.authorized_keys_command_user == NULL &&
1649 (options.authorized_keys_command != NULL &&
1650 strcasecmp(options.authorized_keys_command, "none") != 0))
1651 fatal("AuthorizedKeysCommand set without "
1652 "AuthorizedKeysCommandUser");
1655 * Check whether there is any path through configured auth methods.
1656 * Unfortunately it is not possible to verify this generally before
1657 * daemonisation in the presence of Match block, but this catches
1658 * and warns for trivial misconfigurations that could break login.
1660 if (options.num_auth_methods != 0) {
1661 if ((options.protocol & SSH_PROTO_1))
1662 fatal("AuthenticationMethods is not supported with "
1664 for (n = 0; n < options.num_auth_methods; n++) {
1665 if (auth2_methods_valid(options.auth_methods[n],
1669 if (n >= options.num_auth_methods)
1670 fatal("AuthenticationMethods cannot be satisfied by "
1671 "enabled authentication methods");
1674 /* set default channel AF */
1675 channel_set_af(options.address_family);
1677 /* Check that there are no remaining arguments. */
1679 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1683 debug("sshd version %s, %s", SSH_VERSION,
1685 SSLeay_version(SSLEAY_VERSION)
1691 /* Store privilege separation user for later use if required. */
1692 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1693 if (use_privsep || options.kerberos_authentication)
1694 fatal("Privilege separation user %s does not exist",
1697 explicit_bzero(privsep_pw->pw_passwd,
1698 strlen(privsep_pw->pw_passwd));
1699 privsep_pw = pwcopy(privsep_pw);
1700 free(privsep_pw->pw_passwd);
1701 privsep_pw->pw_passwd = xstrdup("*");
1705 /* load host keys */
1706 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1708 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1710 for (i = 0; i < options.num_host_key_files; i++) {
1711 sensitive_data.host_keys[i] = NULL;
1712 sensitive_data.host_pubkeys[i] = NULL;
1715 if (options.host_key_agent) {
1716 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1717 setenv(SSH_AUTHSOCKET_ENV_NAME,
1718 options.host_key_agent, 1);
1719 have_agent = ssh_agent_present();
1722 for (i = 0; i < options.num_host_key_files; i++) {
1723 key = key_load_private(options.host_key_files[i], "", NULL);
1724 pubkey = key_load_public(options.host_key_files[i], NULL);
1725 sensitive_data.host_keys[i] = key;
1726 sensitive_data.host_pubkeys[i] = pubkey;
1728 if (key == NULL && pubkey != NULL && pubkey->type != KEY_RSA1 &&
1730 debug("will rely on agent for hostkey %s",
1731 options.host_key_files[i]);
1732 keytype = pubkey->type;
1733 } else if (key != NULL) {
1734 keytype = key->type;
1736 error("Could not load host key: %s",
1737 options.host_key_files[i]);
1738 sensitive_data.host_keys[i] = NULL;
1739 sensitive_data.host_pubkeys[i] = NULL;
1745 sensitive_data.ssh1_host_key = key;
1746 sensitive_data.have_ssh1_key = 1;
1752 sensitive_data.have_ssh2_key = 1;
1755 debug("private host key: #%d type %d %s", i, keytype,
1756 key_type(key ? key : pubkey));
1758 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1759 logit("Disabling protocol version 1. Could not load host key");
1760 options.protocol &= ~SSH_PROTO_1;
1762 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1763 logit("Disabling protocol version 2. Could not load host key");
1764 options.protocol &= ~SSH_PROTO_2;
1766 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1767 logit("sshd: no hostkeys available -- exiting.");
1772 * Load certificates. They are stored in an array at identical
1773 * indices to the public keys that they relate to.
1775 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1777 for (i = 0; i < options.num_host_key_files; i++)
1778 sensitive_data.host_certificates[i] = NULL;
1780 for (i = 0; i < options.num_host_cert_files; i++) {
1781 key = key_load_public(options.host_cert_files[i], NULL);
1783 error("Could not load host certificate: %s",
1784 options.host_cert_files[i]);
1787 if (!key_is_cert(key)) {
1788 error("Certificate file is not a certificate: %s",
1789 options.host_cert_files[i]);
1793 /* Find matching private key */
1794 for (j = 0; j < options.num_host_key_files; j++) {
1795 if (key_equal_public(key,
1796 sensitive_data.host_keys[j])) {
1797 sensitive_data.host_certificates[j] = key;
1801 if (j >= options.num_host_key_files) {
1802 error("No matching private key for certificate: %s",
1803 options.host_cert_files[i]);
1807 sensitive_data.host_certificates[j] = key;
1808 debug("host certificate: #%d type %d %s", j, key->type,
1813 /* Check certain values for sanity. */
1814 if (options.protocol & SSH_PROTO_1) {
1815 if (options.server_key_bits < 512 ||
1816 options.server_key_bits > 32768) {
1817 fprintf(stderr, "Bad server key size.\n");
1821 * Check that server and host key lengths differ sufficiently. This
1822 * is necessary to make double encryption work with rsaref. Oh, I
1823 * hate software patents. I dont know if this can go? Niels
1825 if (options.server_key_bits >
1826 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1827 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1828 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1829 SSH_KEY_BITS_RESERVED) {
1830 options.server_key_bits =
1831 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1832 SSH_KEY_BITS_RESERVED;
1833 debug("Forcing server key to %d bits to make it differ from host key.",
1834 options.server_key_bits);
1842 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1843 (S_ISDIR(st.st_mode) == 0))
1844 fatal("Missing privilege separation directory: %s",
1845 _PATH_PRIVSEP_CHROOT_DIR);
1848 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1849 (st.st_uid != getuid () ||
1850 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1852 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1854 fatal("%s must be owned by root and not group or "
1855 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1858 if (test_flag > 1) {
1859 if (server_match_spec_complete(connection_info) == 1)
1860 parse_server_match_config(&options, connection_info);
1861 dump_config(&options);
1864 /* Configuration looks good, so exit if in test mode. */
1869 * Clear out any supplemental groups we may have inherited. This
1870 * prevents inadvertent creation of files with bad modes (in the
1871 * portable version at least, it's certainly possible for PAM
1872 * to create a file, and we can't control the code in every
1873 * module which might be used).
1875 if (setgroups(0, NULL) < 0)
1876 debug("setgroups() failed: %.200s", strerror(errno));
1879 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1880 for (i = 0; i < rexec_argc; i++) {
1881 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1882 rexec_argv[i] = saved_argv[i];
1884 rexec_argv[rexec_argc] = "-R";
1885 rexec_argv[rexec_argc + 1] = NULL;
1888 /* Ensure that umask disallows at least group and world write */
1889 new_umask = umask(0077) | 0022;
1890 (void) umask(new_umask);
1892 /* Initialize the log (it is reinitialized below in case we forked). */
1893 if (debug_flag && (!inetd_flag || rexeced_flag))
1895 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1898 * If not in debugging mode, and not started from inetd, disconnect
1899 * from the controlling terminal, and fork. The original process
1902 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1905 #endif /* TIOCNOTTY */
1906 if (daemon(0, 0) < 0)
1907 fatal("daemon() failed: %.200s", strerror(errno));
1909 /* Disconnect from the controlling tty. */
1911 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1913 (void) ioctl(fd, TIOCNOTTY, NULL);
1916 #endif /* TIOCNOTTY */
1918 /* Reinitialize the log (because of the fork above). */
1919 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1921 /* Chdir to the root directory so that the current disk can be
1922 unmounted if desired. */
1923 if (chdir("/") == -1)
1924 error("chdir(\"/\"): %s", strerror(errno));
1926 /* ignore SIGPIPE */
1927 signal(SIGPIPE, SIG_IGN);
1929 /* Get a connection, either from inetd or a listening TCP socket */
1931 server_accept_inetd(&sock_in, &sock_out);
1933 platform_pre_listen();
1936 if (options.protocol & SSH_PROTO_1)
1937 generate_ephemeral_server_key();
1939 signal(SIGHUP, sighup_handler);
1940 signal(SIGCHLD, main_sigchld_handler);
1941 signal(SIGTERM, sigterm_handler);
1942 signal(SIGQUIT, sigterm_handler);
1945 * Write out the pid file after the sigterm handler
1946 * is setup and the listen sockets are bound
1949 FILE *f = fopen(options.pid_file, "w");
1952 error("Couldn't create pid file \"%s\": %s",
1953 options.pid_file, strerror(errno));
1955 fprintf(f, "%ld\n", (long) getpid());
1960 /* Accept a connection and return in a forked child */
1961 server_accept_loop(&sock_in, &sock_out,
1962 &newsock, config_s);
1965 /* This is the child processing a new connection. */
1966 setproctitle("%s", "[accepted]");
1969 * Initialize the resolver. This may not happen automatically
1970 * before privsep chroot().
1972 if ((_res.options & RES_INIT) == 0) {
1973 debug("res_init()");
1978 * Create a new session and process group since the 4.4BSD
1979 * setlogin() affects the entire process group. We don't
1980 * want the child to be able to affect the parent.
1982 #if !defined(SSHD_ACQUIRES_CTTY)
1984 * If setsid is called, on some platforms sshd will later acquire a
1985 * controlling terminal which will result in "could not set
1986 * controlling tty" errors.
1988 if (!debug_flag && !inetd_flag && setsid() < 0)
1989 error("setsid: %.100s", strerror(errno));
1995 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1996 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1997 dup2(newsock, STDIN_FILENO);
1998 dup2(STDIN_FILENO, STDOUT_FILENO);
1999 if (startup_pipe == -1)
2000 close(REEXEC_STARTUP_PIPE_FD);
2001 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
2002 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
2003 close(startup_pipe);
2004 startup_pipe = REEXEC_STARTUP_PIPE_FD;
2007 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
2010 execv(rexec_argv[0], rexec_argv);
2012 /* Reexec has failed, fall back and continue */
2013 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
2014 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
2015 log_init(__progname, options.log_level,
2016 options.log_facility, log_stderr);
2019 close(REEXEC_CONFIG_PASS_FD);
2020 newsock = sock_out = sock_in = dup(STDIN_FILENO);
2021 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2022 dup2(fd, STDIN_FILENO);
2023 dup2(fd, STDOUT_FILENO);
2024 if (fd > STDERR_FILENO)
2027 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2028 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2031 /* Executed child processes don't need these. */
2032 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2033 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2036 * Disable the key regeneration alarm. We will not regenerate the
2037 * key since we are no longer in a position to give it to anyone. We
2038 * will not restart on SIGHUP since it no longer makes sense.
2041 signal(SIGALRM, SIG_DFL);
2042 signal(SIGHUP, SIG_DFL);
2043 signal(SIGTERM, SIG_DFL);
2044 signal(SIGQUIT, SIG_DFL);
2045 signal(SIGCHLD, SIG_DFL);
2046 signal(SIGINT, SIG_DFL);
2049 * Register our connection. This turns encryption off because we do
2052 packet_set_connection(sock_in, sock_out);
2053 packet_set_server();
2055 /* Set SO_KEEPALIVE if requested. */
2056 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2057 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2058 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2060 if ((remote_port = get_remote_port()) < 0) {
2061 debug("get_remote_port failed");
2066 * We use get_canonical_hostname with usedns = 0 instead of
2067 * get_remote_ipaddr here so IP options will be checked.
2069 (void) get_canonical_hostname(0);
2071 * The rest of the code depends on the fact that
2072 * get_remote_ipaddr() caches the remote ip, even if
2073 * the socket goes away.
2075 remote_ip = get_remote_ipaddr();
2077 #ifdef SSH_AUDIT_EVENTS
2078 audit_connection_from(remote_ip, remote_port);
2081 /* Log the connection. */
2082 verbose("Connection from %s port %d on %s port %d",
2083 remote_ip, remote_port,
2084 get_local_ipaddr(sock_in), get_local_port());
2086 /* set the HPN options for the child */
2087 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
2090 * We don't want to listen forever unless the other side
2091 * successfully authenticates itself. So we set up an alarm which is
2092 * cleared after successful authentication. A limit of zero
2093 * indicates no limit. Note that we don't set the alarm in debugging
2094 * mode; it is just annoying to have the server exit just when you
2095 * are about to discover the bug.
2097 signal(SIGALRM, grace_alarm_handler);
2099 alarm(options.login_grace_time);
2101 sshd_exchange_identification(sock_in, sock_out);
2103 /* In inetd mode, generate ephemeral key only for proto 1 connections */
2104 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2105 generate_ephemeral_server_key();
2107 packet_set_nonblocking();
2109 /* allocate authentication context */
2110 authctxt = xcalloc(1, sizeof(*authctxt));
2112 authctxt->loginmsg = &loginmsg;
2114 /* XXX global for cleanup, access from other modules */
2115 the_authctxt = authctxt;
2117 /* prepare buffer to collect messages to display to user after login */
2118 buffer_init(&loginmsg);
2122 if (privsep_preauth(authctxt) == 1)
2124 } else if (compat20 && have_agent)
2125 auth_conn = ssh_get_authentication_connection();
2127 /* perform the key exchange */
2128 /* authenticate user and start session */
2131 do_authentication2(authctxt);
2135 do_authentication(authctxt);
2137 fatal("ssh1 not supported");
2141 * If we use privilege separation, the unprivileged child transfers
2142 * the current keystate and exits
2145 mm_send_keystate(pmonitor);
2151 * Cancel the alarm we set to limit the time taken for
2155 signal(SIGALRM, SIG_DFL);
2156 authctxt->authenticated = 1;
2157 if (startup_pipe != -1) {
2158 close(startup_pipe);
2162 #ifdef SSH_AUDIT_EVENTS
2163 audit_event(SSH_AUTH_SUCCESS);
2167 if (options.gss_authentication) {
2168 temporarily_use_uid(authctxt->pw);
2169 ssh_gssapi_storecreds();
2174 if (options.use_pam) {
2181 * In privilege separation, we fork another child and prepare
2182 * file descriptor passing.
2185 privsep_postauth(authctxt);
2186 /* the monitor process [priv] will not return */
2188 destroy_sensitive_data();
2191 packet_set_timeout(options.client_alive_interval,
2192 options.client_alive_count_max);
2194 /* Start session. */
2196 /* if we are using aes-ctr there can be issues in either a fork or sandbox
2197 * so the initial aes-ctr is defined to point ot the original single process
2198 * evp. After authentication we'll be past the fork and the sandboxed privsep
2199 * so we repoint the define to the multithreaded evp. To start the threads we
2200 * then force a rekey
2202 CipherContext *ccsend;
2203 ccsend = (CipherContext*)packet_get_send_context();
2205 /* only rekey if necessary. If we don't do this gcm mode cipher breaks */
2206 if (strstr(cipher_return_name((Cipher*)ccsend->cipher), "ctr")) {
2207 debug ("Single to Multithreaded CTR cipher swap - server request");
2208 cipher_reset_multithreaded();
2209 packet_request_rekeying();
2212 do_authenticated(authctxt);
2214 /* The connection has been terminated. */
2215 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
2216 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
2217 verbose("Transferred: sent %llu, received %llu bytes",
2218 (unsigned long long)obytes, (unsigned long long)ibytes);
2220 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2223 if (options.use_pam)
2225 #endif /* USE_PAM */
2227 #ifdef SSH_AUDIT_EVENTS
2228 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2241 * Decrypt session_key_int using our private server key and private host key
2242 * (key with larger modulus first).
2245 ssh1_session_key(BIGNUM *session_key_int)
2249 if (BN_cmp(sensitive_data.server_key->rsa->n,
2250 sensitive_data.ssh1_host_key->rsa->n) > 0) {
2251 /* Server key has bigger modulus. */
2252 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2253 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2254 SSH_KEY_BITS_RESERVED) {
2255 fatal("do_connection: %s: "
2256 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2257 get_remote_ipaddr(),
2258 BN_num_bits(sensitive_data.server_key->rsa->n),
2259 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2260 SSH_KEY_BITS_RESERVED);
2262 if (rsa_private_decrypt(session_key_int, session_key_int,
2263 sensitive_data.server_key->rsa) != 0)
2265 if (rsa_private_decrypt(session_key_int, session_key_int,
2266 sensitive_data.ssh1_host_key->rsa) != 0)
2269 /* Host key has bigger modulus (or they are equal). */
2270 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2271 BN_num_bits(sensitive_data.server_key->rsa->n) +
2272 SSH_KEY_BITS_RESERVED) {
2273 fatal("do_connection: %s: "
2274 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2275 get_remote_ipaddr(),
2276 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2277 BN_num_bits(sensitive_data.server_key->rsa->n),
2278 SSH_KEY_BITS_RESERVED);
2280 if (rsa_private_decrypt(session_key_int, session_key_int,
2281 sensitive_data.ssh1_host_key->rsa) != 0)
2283 if (rsa_private_decrypt(session_key_int, session_key_int,
2284 sensitive_data.server_key->rsa) != 0)
2298 BIGNUM *session_key_int;
2299 u_char session_key[SSH_SESSION_KEY_LENGTH];
2301 u_int cipher_type, auth_mask, protocol_flags;
2304 * Generate check bytes that the client must send back in the user
2305 * packet in order for it to be accepted; this is used to defy ip
2306 * spoofing attacks. Note that this only works against somebody
2307 * doing IP spoofing from a remote machine; any machine on the local
2308 * network can still see outgoing packets and catch the random
2309 * cookie. This only affects rhosts authentication, and this is one
2310 * of the reasons why it is inherently insecure.
2312 arc4random_buf(cookie, sizeof(cookie));
2315 * Send our public key. We include in the packet 64 bits of random
2316 * data that must be matched in the reply in order to prevent IP
2319 packet_start(SSH_SMSG_PUBLIC_KEY);
2320 for (i = 0; i < 8; i++)
2321 packet_put_char(cookie[i]);
2323 /* Store our public server RSA key. */
2324 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2325 packet_put_bignum(sensitive_data.server_key->rsa->e);
2326 packet_put_bignum(sensitive_data.server_key->rsa->n);
2328 /* Store our public host RSA key. */
2329 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2330 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2331 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2333 /* Put protocol flags. */
2334 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2336 /* Declare which ciphers we support. */
2337 packet_put_int(cipher_mask_ssh1(0));
2339 /* Declare supported authentication types. */
2341 if (options.rhosts_rsa_authentication)
2342 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2343 if (options.rsa_authentication)
2344 auth_mask |= 1 << SSH_AUTH_RSA;
2345 if (options.challenge_response_authentication == 1)
2346 auth_mask |= 1 << SSH_AUTH_TIS;
2347 if (options.password_authentication)
2348 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2349 packet_put_int(auth_mask);
2351 /* Send the packet and wait for it to be sent. */
2353 packet_write_wait();
2355 debug("Sent %d bit server key and %d bit host key.",
2356 BN_num_bits(sensitive_data.server_key->rsa->n),
2357 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2359 /* Read clients reply (cipher type and session key). */
2360 packet_read_expect(SSH_CMSG_SESSION_KEY);
2362 /* Get cipher type and check whether we accept this. */
2363 cipher_type = packet_get_char();
2365 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2366 packet_disconnect("Warning: client selects unsupported cipher.");
2368 /* Get check bytes from the packet. These must match those we
2369 sent earlier with the public key packet. */
2370 for (i = 0; i < 8; i++)
2371 if (cookie[i] != packet_get_char())
2372 packet_disconnect("IP Spoofing check bytes do not match.");
2374 debug("Encryption type: %.200s", cipher_name(cipher_type));
2376 /* Get the encrypted integer. */
2377 if ((session_key_int = BN_new()) == NULL)
2378 fatal("do_ssh1_kex: BN_new failed");
2379 packet_get_bignum(session_key_int);
2381 protocol_flags = packet_get_int();
2382 packet_set_protocol_flags(protocol_flags);
2385 /* Decrypt session_key_int using host/server keys */
2386 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2389 * Extract session key from the decrypted integer. The key is in the
2390 * least significant 256 bits of the integer; the first byte of the
2391 * key is in the highest bits.
2394 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2395 len = BN_num_bytes(session_key_int);
2396 if (len < 0 || (u_int)len > sizeof(session_key)) {
2397 error("do_ssh1_kex: bad session key len from %s: "
2398 "session_key_int %d > sizeof(session_key) %lu",
2399 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2402 explicit_bzero(session_key, sizeof(session_key));
2403 BN_bn2bin(session_key_int,
2404 session_key + sizeof(session_key) - len);
2406 derive_ssh1_session_id(
2407 sensitive_data.ssh1_host_key->rsa->n,
2408 sensitive_data.server_key->rsa->n,
2409 cookie, session_id);
2411 * Xor the first 16 bytes of the session key with the
2414 for (i = 0; i < 16; i++)
2415 session_key[i] ^= session_id[i];
2419 int bytes = BN_num_bytes(session_key_int);
2420 u_char *buf = xmalloc(bytes);
2421 struct ssh_digest_ctx *md;
2423 logit("do_connection: generating a fake encryption key");
2424 BN_bn2bin(session_key_int, buf);
2425 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
2426 ssh_digest_update(md, buf, bytes) < 0 ||
2427 ssh_digest_update(md, sensitive_data.ssh1_cookie,
2428 SSH_SESSION_KEY_LENGTH) < 0 ||
2429 ssh_digest_final(md, session_key, sizeof(session_key)) < 0)
2430 fatal("%s: md5 failed", __func__);
2431 ssh_digest_free(md);
2432 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
2433 ssh_digest_update(md, session_key, 16) < 0 ||
2434 ssh_digest_update(md, sensitive_data.ssh1_cookie,
2435 SSH_SESSION_KEY_LENGTH) < 0 ||
2436 ssh_digest_final(md, session_key + 16,
2437 sizeof(session_key) - 16) < 0)
2438 fatal("%s: md5 failed", __func__);
2439 ssh_digest_free(md);
2440 explicit_bzero(buf, bytes);
2442 for (i = 0; i < 16; i++)
2443 session_id[i] = session_key[i] ^ session_key[i + 16];
2445 /* Destroy the private and public keys. No longer. */
2446 destroy_sensitive_data();
2449 mm_ssh1_session_id(session_id);
2451 /* Destroy the decrypted integer. It is no longer needed. */
2452 BN_clear_free(session_key_int);
2454 /* Set the session key. From this on all communications will be encrypted. */
2455 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2457 /* Destroy our copy of the session key. It is no longer needed. */
2458 explicit_bzero(session_key, sizeof(session_key));
2460 debug("Received session key; encryption turned on.");
2462 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2463 packet_start(SSH_SMSG_SUCCESS);
2465 packet_write_wait();
2470 sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, u_int *slen,
2471 u_char *data, u_int dlen)
2474 if (PRIVSEP(key_sign(privkey, signature, slen, data, dlen) < 0))
2475 fatal("%s: key_sign failed", __func__);
2476 } else if (use_privsep) {
2477 if (mm_key_sign(pubkey, signature, slen, data, dlen) < 0)
2478 fatal("%s: pubkey_sign failed", __func__);
2480 if (ssh_agent_sign(auth_conn, pubkey, signature, slen, data,
2482 fatal("%s: ssh_agent_sign failed", __func__);
2487 * SSH2 key exchange: diffie-hellman-group1-sha1
2492 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2496 debug ("MYFLAG IS %d", myflag);
2497 if (options.ciphers != NULL) {
2498 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2499 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2500 } else if (options.none_enabled == 1) {
2501 debug ("WARNING: None cipher enabled");
2502 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2503 myproposal[PROPOSAL_ENC_ALGS_STOC] = KEX_ENCRYPT_INCLUDE_NONE;
2505 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2506 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2507 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2508 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2510 if (options.macs != NULL) {
2511 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2512 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2514 if (options.compression == COMP_NONE) {
2515 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2516 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2517 } else if (options.compression == COMP_DELAYED) {
2518 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2519 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2521 if (options.kex_algorithms != NULL)
2522 myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
2524 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2525 myproposal[PROPOSAL_KEX_ALGS]);
2527 if (options.rekey_limit || options.rekey_interval)
2528 packet_set_rekey_limits((u_int32_t)options.rekey_limit,
2529 (time_t)options.rekey_interval);
2531 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2532 list_hostkey_types());
2534 /* start key exchange */
2535 kex = kex_setup(myproposal);
2537 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2538 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2539 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2540 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2541 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2543 kex->kex[KEX_C25519_SHA256] = kexc25519_server;
2545 kex->client_version_string=client_version_string;
2546 kex->server_version_string=server_version_string;
2547 kex->load_host_public_key=&get_hostkey_public_by_type;
2548 kex->load_host_private_key=&get_hostkey_private_by_type;
2549 kex->host_key_index=&get_hostkey_index;
2550 kex->sign = sshd_hostkey_sign;
2554 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2556 session_id2 = kex->session_id;
2557 session_id2_len = kex->session_id_len;
2560 /* send 1st encrypted/maced/compressed message */
2561 packet_start(SSH2_MSG_IGNORE);
2562 packet_put_cstring("markus");
2564 packet_write_wait();
2569 /* server specific fatal cleanup */
2574 do_cleanup(the_authctxt);
2575 if (use_privsep && privsep_is_preauth &&
2576 pmonitor != NULL && pmonitor->m_pid > 1) {
2577 debug("Killing privsep child %d", pmonitor->m_pid);
2578 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2580 error("%s: kill(%d): %s", __func__,
2581 pmonitor->m_pid, strerror(errno));
2584 #ifdef SSH_AUDIT_EVENTS
2585 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2586 if (!use_privsep || mm_is_monitor())
2587 audit_event(SSH_CONNECTION_ABANDON);