1 /* $OpenBSD: sshd.c,v 1.465 2016/02/15 09:47:49 dtucker Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This program is the ssh daemon. It listens for connections from clients,
7 * and performs authentication, executes use commands or shell, and forwards
8 * information to/from the application to the user client over an encrypted
9 * connection. This can also handle forwarding of X11, TCP/IP, and
10 * authentication agent connections.
12 * As far as I am concerned, the code I have written for this software
13 * can be used freely for any purpose. Any derived versions of this
14 * software must be clearly marked as such, and if the derived work is
15 * incompatible with the protocol description in the RFC file, it must be
16 * called by a name other than "ssh" or "Secure Shell".
18 * SSH2 implementation:
19 * Privilege Separation:
21 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
22 * Copyright (c) 2002 Niels Provos. All rights reserved.
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
27 * 1. Redistributions of source code must retain the above copyright
28 * notice, this list of conditions and the following disclaimer.
29 * 2. Redistributions in binary form must reproduce the above copyright
30 * notice, this list of conditions and the following disclaimer in the
31 * documentation and/or other materials provided with the distribution.
33 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48 #include <sys/types.h>
49 #include <sys/ioctl.h>
51 #include <sys/socket.h>
52 #ifdef HAVE_SYS_STAT_H
53 # include <sys/stat.h>
55 #ifdef HAVE_SYS_TIME_H
56 # include <sys/time.h>
58 #include "openbsd-compat/sys-tree.h"
59 #include "openbsd-compat/sys-queue.h"
79 #include <openssl/dh.h>
80 #include <openssl/bn.h>
81 #include <openssl/rand.h>
82 #include "openbsd-compat/openssl-compat.h"
85 #ifdef HAVE_SECUREWARE
86 #include <sys/security.h>
92 #if defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
93 #include <gssapi/gssapi.h>
94 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_H)
110 #include "servconf.h"
117 #include "myproposal.h"
118 #include "authfile.h"
119 #include "pathnames.h"
120 #include "atomicio.h"
121 #include "canohost.h"
122 #include "hostfile.h"
126 #include "dispatch.h"
127 #include "channels.h"
129 #include "monitor_mm.h"
134 #include "monitor_wrap.h"
135 #include "ssh-sandbox.h"
139 #include "blacklist_client.h"
154 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
155 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
156 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
157 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
159 extern char *__progname;
161 /* Server configuration options. */
162 ServerOptions options;
164 /* Name of the server configuration file. */
165 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
168 * Debug mode flag. This can be set on the command line. If debug
169 * mode is enabled, extra debugging output will be sent to the system
170 * log, the daemon will not go to background, and will exit after processing
171 * the first connection.
175 /* Flag indicating that the daemon should only test the configuration and keys. */
178 /* Flag indicating that the daemon is being started from inetd. */
181 /* Flag indicating that sshd should not detach and become a daemon. */
182 int no_daemon_flag = 0;
184 /* debug goes to stderr unless inetd_flag is set */
187 /* Saved arguments to main(). */
192 int rexeced_flag = 0;
198 * The sockets that the server is listening; this is used in the SIGHUP
201 #define MAX_LISTEN_SOCKS 16
202 int listen_socks[MAX_LISTEN_SOCKS];
203 int num_listen_socks = 0;
206 * the client's version string, passed by sshd2 in compat mode. if != NULL,
207 * sshd will skip the version-number exchange
209 char *client_version_string = NULL;
210 char *server_version_string = NULL;
212 /* Daemon's agent connection */
217 * Any really sensitive data in the application is contained in this
218 * structure. The idea is that this structure could be locked into memory so
219 * that the pages do not get written into swap. However, there are some
220 * problems. The private key contains BIGNUMs, and we do not (in principle)
221 * have access to the internals of them, and locking just the structure is
222 * not very useful. Currently, memory locking is not implemented.
225 Key *server_key; /* ephemeral server key */
226 Key *ssh1_host_key; /* ssh1 host key */
227 Key **host_keys; /* all private host keys */
228 Key **host_pubkeys; /* all public host keys */
229 Key **host_certificates; /* all public host certificates */
232 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
236 * Flag indicating whether the RSA server key needs to be regenerated.
237 * Is set in the SIGALRM handler and cleared when the key is regenerated.
239 static volatile sig_atomic_t key_do_regen = 0;
241 /* This is set to true when a signal is received. */
242 static volatile sig_atomic_t received_sighup = 0;
243 static volatile sig_atomic_t received_sigterm = 0;
245 /* session identifier, used by RSA-auth */
246 u_char session_id[16];
249 u_char *session_id2 = NULL;
250 u_int session_id2_len = 0;
252 /* record remote hostname or ip */
253 u_int utmp_len = HOST_NAME_MAX+1;
255 /* options.max_startup sized array of fd ints */
256 int *startup_pipes = NULL;
257 int startup_pipe; /* in child */
259 /* variables used for privilege separation */
260 int use_privsep = -1;
261 struct monitor *pmonitor = NULL;
262 int privsep_is_preauth = 1;
264 /* global authentication context */
265 Authctxt *the_authctxt = NULL;
267 /* sshd_config buffer */
270 /* message to be displayed after login */
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);
281 static void do_ssh1_kex(void);
283 static void do_ssh2_kex(void);
286 * Close all listening sockets
289 close_listen_socks(void)
293 for (i = 0; i < num_listen_socks; i++)
294 close(listen_socks[i]);
295 num_listen_socks = -1;
299 close_startup_pipes(void)
304 for (i = 0; i < options.max_startups; i++)
305 if (startup_pipes[i] != -1)
306 close(startup_pipes[i]);
310 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
311 * the effect is to reread the configuration file (and to regenerate
317 sighup_handler(int sig)
319 int save_errno = errno;
322 signal(SIGHUP, sighup_handler);
327 * Called from the main program after receiving SIGHUP.
328 * Restarts the server.
333 logit("Received SIGHUP; restarting.");
334 platform_pre_restart();
335 close_listen_socks();
336 close_startup_pipes();
337 alarm(0); /* alarm timer persists across exec */
338 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
339 execv(saved_argv[0], saved_argv);
340 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
346 * Generic signal handler for terminating signals in the master daemon.
350 sigterm_handler(int sig)
352 received_sigterm = sig;
356 * SIGCHLD handler. This is called whenever a child dies. This will then
357 * reap any zombies left by exited children.
361 main_sigchld_handler(int sig)
363 int save_errno = errno;
367 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
368 (pid < 0 && errno == EINTR))
371 signal(SIGCHLD, main_sigchld_handler);
376 * Signal handler for the alarm after the login grace period has expired.
380 grace_alarm_handler(int sig)
382 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
383 kill(pmonitor->m_pid, SIGALRM);
386 * Try to kill any processes that we have spawned, E.g. authorized
387 * keys command helpers.
389 if (getpgid(0) == getpid()) {
390 signal(SIGTERM, SIG_IGN);
397 /* Log error and exit. */
398 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
402 * Signal handler for the key regeneration alarm. Note that this
403 * alarm only occurs in the daemon waiting for connections, and it does not
404 * do anything with the private key or random state before forking.
405 * Thus there should be no concurrency control/asynchronous execution
409 generate_ephemeral_server_key(void)
411 verbose("Generating %s%d bit RSA key.",
412 sensitive_data.server_key ? "new " : "", options.server_key_bits);
413 if (sensitive_data.server_key != NULL)
414 key_free(sensitive_data.server_key);
415 sensitive_data.server_key = key_generate(KEY_RSA1,
416 options.server_key_bits);
417 verbose("RSA key generation complete.");
419 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
424 key_regeneration_alarm(int sig)
426 int save_errno = errno;
428 signal(SIGALRM, SIG_DFL);
434 sshd_exchange_identification(int sock_in, int sock_out)
438 int remote_major, remote_minor;
440 char *s, *newline = "\n";
441 char buf[256]; /* Must not be larger than remote_version. */
442 char remote_version[256]; /* Must be at least as big as buf. */
444 if ((options.protocol & SSH_PROTO_1) &&
445 (options.protocol & SSH_PROTO_2)) {
446 major = PROTOCOL_MAJOR_1;
448 } else if (options.protocol & SSH_PROTO_2) {
449 major = PROTOCOL_MAJOR_2;
450 minor = PROTOCOL_MINOR_2;
453 major = PROTOCOL_MAJOR_1;
454 minor = PROTOCOL_MINOR_1;
457 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s",
458 major, minor, SSH_VERSION,
459 *options.version_addendum == '\0' ? "" : " ",
460 options.version_addendum, newline);
462 /* Send our protocol version identification. */
463 if (atomicio(vwrite, sock_out, server_version_string,
464 strlen(server_version_string))
465 != strlen(server_version_string)) {
466 logit("Could not write ident string to %s", get_remote_ipaddr());
470 /* Read other sides version identification. */
471 memset(buf, 0, sizeof(buf));
472 for (i = 0; i < sizeof(buf) - 1; i++) {
473 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
474 logit("Did not receive identification string from %s",
475 get_remote_ipaddr());
478 if (buf[i] == '\r') {
480 /* Kludge for F-Secure Macintosh < 1.0.2 */
482 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
486 if (buf[i] == '\n') {
491 buf[sizeof(buf) - 1] = 0;
492 client_version_string = xstrdup(buf);
495 * Check that the versions match. In future this might accept
496 * several versions and set appropriate flags to handle them.
498 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
499 &remote_major, &remote_minor, remote_version) != 3) {
500 s = "Protocol mismatch.\n";
501 (void) atomicio(vwrite, sock_out, s, strlen(s));
502 logit("Bad protocol version identification '%.100s' "
503 "from %s port %d", client_version_string,
504 get_remote_ipaddr(), get_remote_port());
509 debug("Client protocol version %d.%d; client software version %.100s",
510 remote_major, remote_minor, remote_version);
512 active_state->compat = compat_datafellows(remote_version);
514 if ((datafellows & SSH_BUG_PROBE) != 0) {
515 logit("probed from %s with %s. Don't panic.",
516 get_remote_ipaddr(), client_version_string);
519 if ((datafellows & SSH_BUG_SCANNER) != 0) {
520 logit("scanned from %s with %s. Don't panic.",
521 get_remote_ipaddr(), client_version_string);
524 if ((datafellows & SSH_BUG_RSASIGMD5) != 0) {
525 logit("Client version \"%.100s\" uses unsafe RSA signature "
526 "scheme; disabling use of RSA keys", remote_version);
528 if ((datafellows & SSH_BUG_DERIVEKEY) != 0) {
529 fatal("Client version \"%.100s\" uses unsafe key agreement; "
530 "refusing connection", remote_version);
534 switch (remote_major) {
536 if (remote_minor == 99) {
537 if (options.protocol & SSH_PROTO_2)
543 if (!(options.protocol & SSH_PROTO_1)) {
547 if (remote_minor < 3) {
548 packet_disconnect("Your ssh version is too old and "
549 "is no longer supported. Please install a newer version.");
550 } else if (remote_minor == 3) {
551 /* note that this disables agent-forwarding */
556 if (options.protocol & SSH_PROTO_2) {
565 chop(server_version_string);
566 debug("Local version string %.200s", server_version_string);
569 s = "Protocol major versions differ.\n";
570 (void) atomicio(vwrite, sock_out, s, strlen(s));
573 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
575 server_version_string, client_version_string);
580 /* Destroy the host and server keys. They will no longer be needed. */
582 destroy_sensitive_data(void)
586 if (sensitive_data.server_key) {
587 key_free(sensitive_data.server_key);
588 sensitive_data.server_key = NULL;
590 for (i = 0; i < options.num_host_key_files; i++) {
591 if (sensitive_data.host_keys[i]) {
592 key_free(sensitive_data.host_keys[i]);
593 sensitive_data.host_keys[i] = NULL;
595 if (sensitive_data.host_certificates[i]) {
596 key_free(sensitive_data.host_certificates[i]);
597 sensitive_data.host_certificates[i] = NULL;
600 sensitive_data.ssh1_host_key = NULL;
601 explicit_bzero(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
604 /* Demote private to public keys for network child */
606 demote_sensitive_data(void)
611 if (sensitive_data.server_key) {
612 tmp = key_demote(sensitive_data.server_key);
613 key_free(sensitive_data.server_key);
614 sensitive_data.server_key = tmp;
617 for (i = 0; i < options.num_host_key_files; i++) {
618 if (sensitive_data.host_keys[i]) {
619 tmp = key_demote(sensitive_data.host_keys[i]);
620 key_free(sensitive_data.host_keys[i]);
621 sensitive_data.host_keys[i] = tmp;
622 if (tmp->type == KEY_RSA1)
623 sensitive_data.ssh1_host_key = tmp;
625 /* Certs do not need demotion */
628 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
632 privsep_preauth_child(void)
637 /* Enable challenge-response authentication for privilege separation */
638 privsep_challenge_enable();
641 /* Cache supported mechanism OIDs for later use */
642 if (options.gss_authentication)
643 ssh_gssapi_prepare_supported_oids();
647 arc4random_buf(rnd, sizeof(rnd));
649 RAND_seed(rnd, sizeof(rnd));
650 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
651 fatal("%s: RAND_bytes failed", __func__);
653 explicit_bzero(rnd, sizeof(rnd));
655 /* Demote the private keys to public keys. */
656 demote_sensitive_data();
662 /* Demote the child */
663 if (getuid() == 0 || geteuid() == 0) {
664 /* Change our root directory */
665 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
666 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
668 if (chdir("/") == -1)
669 fatal("chdir(\"/\"): %s", strerror(errno));
671 /* Drop our privileges */
672 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
673 (u_int)privsep_pw->pw_gid);
674 gidset[0] = privsep_pw->pw_gid;
675 if (setgroups(1, gidset) < 0)
676 fatal("setgroups: %.100s", strerror(errno));
677 permanently_set_uid(privsep_pw);
682 privsep_preauth(Authctxt *authctxt)
686 struct ssh_sandbox *box = NULL;
688 /* Set up unprivileged child process to deal with network data */
689 pmonitor = monitor_init();
690 /* Store a pointer to the kex for later rekeying */
691 pmonitor->m_pkex = &active_state->kex;
693 if (use_privsep == PRIVSEP_ON)
694 box = ssh_sandbox_init(pmonitor);
697 fatal("fork of unprivileged child failed");
698 } else if (pid != 0) {
699 debug2("Network child is on pid %ld", (long)pid);
701 pmonitor->m_pid = pid;
703 r = ssh_get_authentication_socket(&auth_sock);
705 error("Could not get agent socket: %s",
711 ssh_sandbox_parent_preauth(box, pid);
712 monitor_child_preauth(authctxt, pmonitor);
715 monitor_sync(pmonitor);
717 /* Wait for the child's exit status */
718 while (waitpid(pid, &status, 0) < 0) {
721 pmonitor->m_pid = -1;
722 fatal("%s: waitpid: %s", __func__, strerror(errno));
724 privsep_is_preauth = 0;
725 pmonitor->m_pid = -1;
726 if (WIFEXITED(status)) {
727 if (WEXITSTATUS(status) != 0)
728 fatal("%s: preauth child exited with status %d",
729 __func__, WEXITSTATUS(status));
730 } else if (WIFSIGNALED(status))
731 fatal("%s: preauth child terminated by signal %d",
732 __func__, WTERMSIG(status));
734 ssh_sandbox_parent_finish(box);
738 close(pmonitor->m_sendfd);
739 close(pmonitor->m_log_recvfd);
741 /* Arrange for logging to be sent to the monitor */
742 set_log_handler(mm_log_handler, pmonitor);
744 privsep_preauth_child();
745 setproctitle("%s", "[net]");
747 ssh_sandbox_child(box);
754 privsep_postauth(Authctxt *authctxt)
758 #ifdef DISABLE_FD_PASSING
761 if (authctxt->pw->pw_uid == 0 || options.use_login) {
763 /* File descriptor passing is broken or root login */
768 /* New socket pair */
769 monitor_reinit(pmonitor);
771 pmonitor->m_pid = fork();
772 if (pmonitor->m_pid == -1)
773 fatal("fork of unprivileged child failed");
774 else if (pmonitor->m_pid != 0) {
775 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
776 buffer_clear(&loginmsg);
777 monitor_child_postauth(pmonitor);
785 close(pmonitor->m_sendfd);
786 pmonitor->m_sendfd = -1;
788 /* Demote the private keys to public keys. */
789 demote_sensitive_data();
792 arc4random_buf(rnd, sizeof(rnd));
794 RAND_seed(rnd, sizeof(rnd));
795 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
796 fatal("%s: RAND_bytes failed", __func__);
798 explicit_bzero(rnd, sizeof(rnd));
800 /* Drop privileges */
801 do_setusercontext(authctxt->pw);
804 /* It is safe now to apply the key state */
805 monitor_apply_keystate(pmonitor);
808 * Tell the packet layer that authentication was successful, since
809 * this information is not part of the key state.
811 packet_set_authenticated();
815 list_hostkey_types(void)
824 for (i = 0; i < options.num_host_key_files; i++) {
825 key = sensitive_data.host_keys[i];
827 key = sensitive_data.host_pubkeys[i];
828 if (key == NULL || key->type == KEY_RSA1)
830 /* Check that the key is accepted in HostkeyAlgorithms */
831 if (match_pattern_list(sshkey_ssh_name(key),
832 options.hostkeyalgorithms, 0) != 1) {
833 debug3("%s: %s key not permitted by HostkeyAlgorithms",
834 __func__, sshkey_ssh_name(key));
842 if (buffer_len(&b) > 0)
843 buffer_append(&b, ",", 1);
844 p = key_ssh_name(key);
845 buffer_append(&b, p, strlen(p));
847 /* for RSA we also support SHA2 signatures */
848 if (key->type == KEY_RSA) {
849 p = ",rsa-sha2-512,rsa-sha2-256";
850 buffer_append(&b, p, strlen(p));
854 /* If the private key has a cert peer, then list that too */
855 key = sensitive_data.host_certificates[i];
862 case KEY_ED25519_CERT:
863 if (buffer_len(&b) > 0)
864 buffer_append(&b, ",", 1);
865 p = key_ssh_name(key);
866 buffer_append(&b, p, strlen(p));
870 buffer_append(&b, "\0", 1);
871 ret = xstrdup(buffer_ptr(&b));
873 debug("list_hostkey_types: %s", ret);
878 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
883 for (i = 0; i < options.num_host_key_files; i++) {
888 case KEY_ED25519_CERT:
889 key = sensitive_data.host_certificates[i];
892 key = sensitive_data.host_keys[i];
893 if (key == NULL && !need_private)
894 key = sensitive_data.host_pubkeys[i];
897 if (key != NULL && key->type == type &&
898 (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
899 return need_private ?
900 sensitive_data.host_keys[i] : key;
906 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
908 return get_hostkey_by_type(type, nid, 0, ssh);
912 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
914 return get_hostkey_by_type(type, nid, 1, ssh);
918 get_hostkey_by_index(int ind)
920 if (ind < 0 || ind >= options.num_host_key_files)
922 return (sensitive_data.host_keys[ind]);
926 get_hostkey_public_by_index(int ind, struct ssh *ssh)
928 if (ind < 0 || ind >= options.num_host_key_files)
930 return (sensitive_data.host_pubkeys[ind]);
934 get_hostkey_index(Key *key, int compare, struct ssh *ssh)
938 for (i = 0; i < options.num_host_key_files; i++) {
939 if (key_is_cert(key)) {
940 if (key == sensitive_data.host_certificates[i] ||
941 (compare && sensitive_data.host_certificates[i] &&
943 sensitive_data.host_certificates[i])))
946 if (key == sensitive_data.host_keys[i] ||
947 (compare && sensitive_data.host_keys[i] &&
948 sshkey_equal(key, sensitive_data.host_keys[i])))
950 if (key == sensitive_data.host_pubkeys[i] ||
951 (compare && sensitive_data.host_pubkeys[i] &&
952 sshkey_equal(key, sensitive_data.host_pubkeys[i])))
959 /* Inform the client of all hostkeys */
961 notify_hostkeys(struct ssh *ssh)
968 /* Some clients cannot cope with the hostkeys message, skip those. */
969 if (datafellows & SSH_BUG_HOSTKEYS)
972 if ((buf = sshbuf_new()) == NULL)
973 fatal("%s: sshbuf_new", __func__);
974 for (i = nkeys = 0; i < options.num_host_key_files; i++) {
975 key = get_hostkey_public_by_index(i, ssh);
976 if (key == NULL || key->type == KEY_UNSPEC ||
977 key->type == KEY_RSA1 || sshkey_is_cert(key))
979 fp = sshkey_fingerprint(key, options.fingerprint_hash,
981 debug3("%s: key %d: %s %s", __func__, i,
982 sshkey_ssh_name(key), fp);
985 packet_start(SSH2_MSG_GLOBAL_REQUEST);
986 packet_put_cstring("hostkeys-00@openssh.com");
987 packet_put_char(0); /* want-reply */
990 if ((r = sshkey_putb(key, buf)) != 0)
991 fatal("%s: couldn't put hostkey %d: %s",
992 __func__, i, ssh_err(r));
993 packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
996 debug3("%s: sent %d hostkeys", __func__, nkeys);
998 fatal("%s: no hostkeys", __func__);
1004 * returns 1 if connection should be dropped, 0 otherwise.
1005 * dropping starts at connection #max_startups_begin with a probability
1006 * of (max_startups_rate/100). the probability increases linearly until
1007 * all connections are dropped for startups > max_startups
1010 drop_connection(int startups)
1014 if (startups < options.max_startups_begin)
1016 if (startups >= options.max_startups)
1018 if (options.max_startups_rate == 100)
1021 p = 100 - options.max_startups_rate;
1022 p *= startups - options.max_startups_begin;
1023 p /= options.max_startups - options.max_startups_begin;
1024 p += options.max_startups_rate;
1025 r = arc4random_uniform(100);
1027 debug("drop_connection: p %d, r %d", p, r);
1028 return (r < p) ? 1 : 0;
1034 if (options.version_addendum && *options.version_addendum != '\0')
1035 fprintf(stderr, "%s %s, %s\n",
1037 options.version_addendum, OPENSSL_VERSION);
1039 fprintf(stderr, "%s, %s\n",
1040 SSH_RELEASE, OPENSSL_VERSION);
1042 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
1043 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
1044 " [-h host_key_file] [-k key_gen_time] [-o option] [-p port]\n"
1051 send_rexec_state(int fd, Buffer *conf)
1055 debug3("%s: entering fd = %d config len %d", __func__, fd,
1059 * Protocol from reexec master to child:
1060 * string configuration
1061 * u_int ephemeral_key_follows
1062 * bignum e (only if ephemeral_key_follows == 1)
1068 * string rngseed (only if OpenSSL is not self-seeded)
1071 buffer_put_cstring(&m, buffer_ptr(conf));
1074 if (sensitive_data.server_key != NULL &&
1075 sensitive_data.server_key->type == KEY_RSA1) {
1076 buffer_put_int(&m, 1);
1077 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
1078 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
1079 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
1080 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1081 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
1082 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
1085 buffer_put_int(&m, 0);
1087 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1088 rexec_send_rng_seed(&m);
1091 if (ssh_msg_send(fd, 0, &m) == -1)
1092 fatal("%s: ssh_msg_send failed", __func__);
1096 debug3("%s: done", __func__);
1100 recv_rexec_state(int fd, Buffer *conf)
1106 debug3("%s: entering fd = %d", __func__, fd);
1110 if (ssh_msg_recv(fd, &m) == -1)
1111 fatal("%s: ssh_msg_recv failed", __func__);
1112 if (buffer_get_char(&m) != 0)
1113 fatal("%s: rexec version mismatch", __func__);
1115 cp = buffer_get_string(&m, &len);
1117 buffer_append(conf, cp, len + 1);
1120 if (buffer_get_int(&m)) {
1122 if (sensitive_data.server_key != NULL)
1123 key_free(sensitive_data.server_key);
1124 sensitive_data.server_key = key_new_private(KEY_RSA1);
1125 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
1126 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
1127 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
1128 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1129 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
1130 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
1131 if (rsa_generate_additional_parameters(
1132 sensitive_data.server_key->rsa) != 0)
1133 fatal("%s: rsa_generate_additional_parameters "
1138 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1139 rexec_recv_rng_seed(&m);
1144 debug3("%s: done", __func__);
1147 /* Accept a connection from inetd */
1149 server_accept_inetd(int *sock_in, int *sock_out)
1155 close(REEXEC_CONFIG_PASS_FD);
1156 *sock_in = *sock_out = dup(STDIN_FILENO);
1158 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1159 close(REEXEC_STARTUP_PIPE_FD);
1162 *sock_in = dup(STDIN_FILENO);
1163 *sock_out = dup(STDOUT_FILENO);
1166 * We intentionally do not close the descriptors 0, 1, and 2
1167 * as our code for setting the descriptors won't work if
1168 * ttyfd happens to be one of those.
1170 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1171 dup2(fd, STDIN_FILENO);
1172 dup2(fd, STDOUT_FILENO);
1174 dup2(fd, STDERR_FILENO);
1175 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1178 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1182 * Listen for TCP connections
1187 int ret, listen_sock, on = 1;
1188 struct addrinfo *ai;
1189 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1193 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1194 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1196 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1197 fatal("Too many listen sockets. "
1198 "Enlarge MAX_LISTEN_SOCKS");
1199 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1200 ntop, sizeof(ntop), strport, sizeof(strport),
1201 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1202 error("getnameinfo failed: %.100s",
1203 ssh_gai_strerror(ret));
1206 /* Create socket for listening. */
1207 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1209 if (listen_sock < 0) {
1210 /* kernel may not support ipv6 */
1211 verbose("socket: %.100s", strerror(errno));
1214 if (set_nonblock(listen_sock) == -1) {
1219 * Set socket options.
1220 * Allow local port reuse in TIME_WAIT.
1222 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1223 &on, sizeof(on)) == -1)
1224 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1226 /* Only communicate in IPv6 over AF_INET6 sockets. */
1227 if (ai->ai_family == AF_INET6)
1228 sock_set_v6only(listen_sock);
1230 debug("Bind to port %s on %s.", strport, ntop);
1232 len = sizeof(socksize);
1233 getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
1234 debug("Server TCP RWIN socket size: %d", socksize);
1236 /* Bind the socket to the desired port. */
1237 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1238 error("Bind to port %s on %s failed: %.200s.",
1239 strport, ntop, strerror(errno));
1243 listen_socks[num_listen_socks] = listen_sock;
1246 /* Start listening on the port. */
1247 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1248 fatal("listen on [%s]:%s: %.100s",
1249 ntop, strport, strerror(errno));
1250 logit("Server listening on %s port %s.", ntop, strport);
1252 freeaddrinfo(options.listen_addrs);
1254 if (!num_listen_socks)
1255 fatal("Cannot bind any address.");
1259 * The main TCP accept loop. Note that, for the non-debug case, returns
1260 * from this function are in a forked subprocess.
1263 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1266 int i, j, ret, maxfd;
1267 int key_used = 0, startups = 0;
1268 int startup_p[2] = { -1 , -1 };
1269 struct sockaddr_storage from;
1274 /* setup fd set for accept */
1277 for (i = 0; i < num_listen_socks; i++)
1278 if (listen_socks[i] > maxfd)
1279 maxfd = listen_socks[i];
1280 /* pipes connected to unauthenticated childs */
1281 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1282 for (i = 0; i < options.max_startups; i++)
1283 startup_pipes[i] = -1;
1285 #ifdef USE_BLACKLIST
1289 * Stay listening for connections until the system crashes or
1290 * the daemon is killed with a signal.
1293 if (received_sighup)
1296 fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1299 for (i = 0; i < num_listen_socks; i++)
1300 FD_SET(listen_socks[i], fdset);
1301 for (i = 0; i < options.max_startups; i++)
1302 if (startup_pipes[i] != -1)
1303 FD_SET(startup_pipes[i], fdset);
1305 /* Wait in select until there is a connection. */
1306 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1307 if (ret < 0 && errno != EINTR)
1308 error("select: %.100s", strerror(errno));
1309 if (received_sigterm) {
1310 logit("Received signal %d; terminating.",
1311 (int) received_sigterm);
1312 close_listen_socks();
1313 if (options.pid_file != NULL)
1314 unlink(options.pid_file);
1315 exit(received_sigterm == SIGTERM ? 0 : 255);
1317 if (key_used && key_do_regen) {
1318 generate_ephemeral_server_key();
1325 for (i = 0; i < options.max_startups; i++)
1326 if (startup_pipes[i] != -1 &&
1327 FD_ISSET(startup_pipes[i], fdset)) {
1329 * the read end of the pipe is ready
1330 * if the child has closed the pipe
1331 * after successful authentication
1332 * or if the child has died
1334 close(startup_pipes[i]);
1335 startup_pipes[i] = -1;
1338 for (i = 0; i < num_listen_socks; i++) {
1339 if (!FD_ISSET(listen_socks[i], fdset))
1341 fromlen = sizeof(from);
1342 *newsock = accept(listen_socks[i],
1343 (struct sockaddr *)&from, &fromlen);
1345 if (errno != EINTR && errno != EWOULDBLOCK &&
1346 errno != ECONNABORTED && errno != EAGAIN)
1347 error("accept: %.100s",
1349 if (errno == EMFILE || errno == ENFILE)
1353 if (unset_nonblock(*newsock) == -1) {
1357 if (drop_connection(startups) == 1) {
1358 debug("drop connection #%d", startups);
1362 if (pipe(startup_p) == -1) {
1367 if (rexec_flag && socketpair(AF_UNIX,
1368 SOCK_STREAM, 0, config_s) == -1) {
1369 error("reexec socketpair: %s",
1372 close(startup_p[0]);
1373 close(startup_p[1]);
1377 for (j = 0; j < options.max_startups; j++)
1378 if (startup_pipes[j] == -1) {
1379 startup_pipes[j] = startup_p[0];
1380 if (maxfd < startup_p[0])
1381 maxfd = startup_p[0];
1387 * Got connection. Fork a child to handle it, unless
1388 * we are in debugging mode.
1392 * In debugging mode. Close the listening
1393 * socket, and start processing the
1394 * connection without forking.
1396 debug("Server will not fork when running in debugging mode.");
1397 close_listen_socks();
1398 *sock_in = *newsock;
1399 *sock_out = *newsock;
1400 close(startup_p[0]);
1401 close(startup_p[1]);
1405 send_rexec_state(config_s[0],
1413 * Normal production daemon. Fork, and have
1414 * the child process the connection. The
1415 * parent continues listening.
1417 platform_pre_fork();
1418 if ((pid = fork()) == 0) {
1420 * Child. Close the listening and
1421 * max_startup sockets. Start using
1422 * the accepted socket. Reinitialize
1423 * logging (since our pid has changed).
1424 * We break out of the loop to handle
1427 platform_post_fork_child();
1428 startup_pipe = startup_p[1];
1429 close_startup_pipes();
1430 close_listen_socks();
1431 *sock_in = *newsock;
1432 *sock_out = *newsock;
1433 log_init(__progname,
1435 options.log_facility,
1442 /* Parent. Stay in the loop. */
1443 platform_post_fork_parent(pid);
1445 error("fork: %.100s", strerror(errno));
1447 debug("Forked child %ld.", (long)pid);
1449 close(startup_p[1]);
1452 send_rexec_state(config_s[0], &cfg);
1458 * Mark that the key has been used (it
1459 * was "given" to the child).
1461 if ((options.protocol & SSH_PROTO_1) &&
1463 /* Schedule server key regeneration alarm. */
1464 signal(SIGALRM, key_regeneration_alarm);
1465 alarm(options.key_regeneration_time);
1472 * Ensure that our random state differs
1473 * from that of the child
1476 arc4random_buf(rnd, sizeof(rnd));
1478 RAND_seed(rnd, sizeof(rnd));
1479 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1480 fatal("%s: RAND_bytes failed", __func__);
1482 explicit_bzero(rnd, sizeof(rnd));
1485 /* child process check (or debug mode) */
1486 if (num_listen_socks < 0)
1493 * Main program for the daemon.
1496 main(int ac, char **av)
1498 extern char *optarg;
1500 int r, opt, i, j, on = 1;
1501 int sock_in = -1, sock_out = -1, newsock = -1;
1502 const char *remote_ip;
1504 char *fp, *line, *laddr, *logfile = NULL;
1505 int config_s[2] = { -1 , -1 };
1507 u_int64_t ibytes, obytes;
1513 struct connection_info *connection_info = get_connection_info(0, 0);
1515 ssh_malloc_init(); /* must be called before any mallocs */
1517 #ifdef HAVE_SECUREWARE
1518 (void)set_auth_parameters(ac, av);
1520 __progname = ssh_get_progname(av[0]);
1522 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1525 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1526 for (i = 0; i < ac; i++)
1527 saved_argv[i] = xstrdup(av[i]);
1528 saved_argv[i] = NULL;
1530 #ifndef HAVE_SETPROCTITLE
1531 /* Prepare for later setproctitle emulation */
1532 compat_init_setproctitle(ac, av);
1536 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1537 debug("setgroups(): %.200s", strerror(errno));
1539 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1542 /* Initialize configuration options to their default values. */
1543 initialize_server_options(&options);
1545 /* Parse command-line arguments. */
1546 while ((opt = getopt(ac, av,
1547 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1550 options.address_family = AF_INET;
1553 options.address_family = AF_INET6;
1556 config_file_name = optarg;
1559 if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1560 fprintf(stderr, "too many host certificates.\n");
1563 options.host_cert_files[options.num_host_cert_files++] =
1564 derelativise_path(optarg);
1567 if (debug_flag == 0) {
1569 options.log_level = SYSLOG_LEVEL_DEBUG1;
1570 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1571 options.log_level++;
1596 options.log_level = SYSLOG_LEVEL_QUIET;
1599 options.server_key_bits = (int)strtonum(optarg, 256,
1603 options.ports_from_cmdline = 1;
1604 if (options.num_ports >= MAX_PORTS) {
1605 fprintf(stderr, "too many ports.\n");
1608 options.ports[options.num_ports++] = a2port(optarg);
1609 if (options.ports[options.num_ports-1] <= 0) {
1610 fprintf(stderr, "Bad port number.\n");
1615 if ((options.login_grace_time = convtime(optarg)) == -1) {
1616 fprintf(stderr, "Invalid login grace time.\n");
1621 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1622 fprintf(stderr, "Invalid key regeneration interval.\n");
1627 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1628 fprintf(stderr, "too many host keys.\n");
1631 options.host_key_files[options.num_host_key_files++] =
1632 derelativise_path(optarg);
1641 if (parse_server_match_testspec(connection_info,
1646 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1647 if (utmp_len > HOST_NAME_MAX+1) {
1648 fprintf(stderr, "Invalid utmp length.\n");
1653 line = xstrdup(optarg);
1654 if (process_server_config_line(&options, line,
1655 "command-line", 0, NULL, NULL) != 0)
1665 if (rexeced_flag || inetd_flag)
1667 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1668 fatal("sshd re-exec requires execution with an absolute path");
1670 closefrom(REEXEC_MIN_FREE_FD);
1672 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1675 OpenSSL_add_all_algorithms();
1678 /* If requested, redirect the logs to the specified logfile. */
1679 if (logfile != NULL)
1680 log_redirect_stderr_to(logfile);
1682 * Force logging to stderr until we have loaded the private host
1683 * key (unless started from inetd)
1685 log_init(__progname,
1686 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1687 SYSLOG_LEVEL_INFO : options.log_level,
1688 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1689 SYSLOG_FACILITY_AUTH : options.log_facility,
1690 log_stderr || !inetd_flag);
1693 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1694 * root's environment
1696 if (getenv("KRB5CCNAME") != NULL)
1697 (void) unsetenv("KRB5CCNAME");
1700 /* Cray can define user privs drop all privs now!
1701 * Not needed on PRIV_SU systems!
1706 sensitive_data.server_key = NULL;
1707 sensitive_data.ssh1_host_key = NULL;
1708 sensitive_data.have_ssh1_key = 0;
1709 sensitive_data.have_ssh2_key = 0;
1712 * If we're doing an extended config test, make sure we have all of
1713 * the parameters we need. If we're not doing an extended test,
1714 * do not silently ignore connection test params.
1716 if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1717 fatal("user, host and addr are all required when testing "
1719 if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1720 fatal("Config test connection parameter (-C) provided without "
1723 /* Fetch our configuration */
1726 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1727 else if (strcasecmp(config_file_name, "none") != 0)
1728 load_server_config(config_file_name, &cfg);
1730 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1735 /* Fill in default values for those options not explicitly set. */
1736 fill_default_server_options(&options);
1738 /* challenge-response is implemented via keyboard interactive */
1739 if (options.challenge_response_authentication)
1740 options.kbd_interactive_authentication = 1;
1742 /* Check that options are sensible */
1743 if (options.authorized_keys_command_user == NULL &&
1744 (options.authorized_keys_command != NULL &&
1745 strcasecmp(options.authorized_keys_command, "none") != 0))
1746 fatal("AuthorizedKeysCommand set without "
1747 "AuthorizedKeysCommandUser");
1748 if (options.authorized_principals_command_user == NULL &&
1749 (options.authorized_principals_command != NULL &&
1750 strcasecmp(options.authorized_principals_command, "none") != 0))
1751 fatal("AuthorizedPrincipalsCommand set without "
1752 "AuthorizedPrincipalsCommandUser");
1755 * Check whether there is any path through configured auth methods.
1756 * Unfortunately it is not possible to verify this generally before
1757 * daemonisation in the presence of Match block, but this catches
1758 * and warns for trivial misconfigurations that could break login.
1760 if (options.num_auth_methods != 0) {
1761 if ((options.protocol & SSH_PROTO_1))
1762 fatal("AuthenticationMethods is not supported with "
1764 for (n = 0; n < options.num_auth_methods; n++) {
1765 if (auth2_methods_valid(options.auth_methods[n],
1769 if (n >= options.num_auth_methods)
1770 fatal("AuthenticationMethods cannot be satisfied by "
1771 "enabled authentication methods");
1774 /* set default channel AF */
1775 channel_set_af(options.address_family);
1777 /* Check that there are no remaining arguments. */
1779 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1783 debug("sshd version %s, %s", SSH_VERSION,
1785 SSLeay_version(SSLEAY_VERSION)
1791 /* Store privilege separation user for later use if required. */
1792 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1793 if (use_privsep || options.kerberos_authentication)
1794 fatal("Privilege separation user %s does not exist",
1797 explicit_bzero(privsep_pw->pw_passwd,
1798 strlen(privsep_pw->pw_passwd));
1799 privsep_pw = pwcopy(privsep_pw);
1800 free(privsep_pw->pw_passwd);
1801 privsep_pw->pw_passwd = xstrdup("*");
1805 /* load host keys */
1806 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1808 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1811 if (options.host_key_agent) {
1812 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1813 setenv(SSH_AUTHSOCKET_ENV_NAME,
1814 options.host_key_agent, 1);
1815 if ((r = ssh_get_authentication_socket(NULL)) == 0)
1818 error("Could not connect to agent \"%s\": %s",
1819 options.host_key_agent, ssh_err(r));
1822 for (i = 0; i < options.num_host_key_files; i++) {
1823 if (options.host_key_files[i] == NULL)
1825 key = key_load_private(options.host_key_files[i], "", NULL);
1826 pubkey = key_load_public(options.host_key_files[i], NULL);
1827 if (pubkey == NULL && key != NULL)
1828 pubkey = key_demote(key);
1829 sensitive_data.host_keys[i] = key;
1830 sensitive_data.host_pubkeys[i] = pubkey;
1832 if (key == NULL && pubkey != NULL && pubkey->type != KEY_RSA1 &&
1834 debug("will rely on agent for hostkey %s",
1835 options.host_key_files[i]);
1836 keytype = pubkey->type;
1837 } else if (key != NULL) {
1838 keytype = key->type;
1840 error("Could not load host key: %s",
1841 options.host_key_files[i]);
1842 sensitive_data.host_keys[i] = NULL;
1843 sensitive_data.host_pubkeys[i] = NULL;
1849 sensitive_data.ssh1_host_key = key;
1850 sensitive_data.have_ssh1_key = 1;
1856 if (have_agent || key != NULL)
1857 sensitive_data.have_ssh2_key = 1;
1860 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1861 SSH_FP_DEFAULT)) == NULL)
1862 fatal("sshkey_fingerprint failed");
1863 debug("%s host key #%d: %s %s",
1864 key ? "private" : "agent", i, keytype == KEY_RSA1 ?
1865 sshkey_type(pubkey) : sshkey_ssh_name(pubkey), fp);
1868 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1869 logit("Disabling protocol version 1. Could not load host key");
1870 options.protocol &= ~SSH_PROTO_1;
1872 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1873 logit("Disabling protocol version 2. Could not load host key");
1874 options.protocol &= ~SSH_PROTO_2;
1876 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1877 logit("sshd: no hostkeys available -- exiting.");
1882 * Load certificates. They are stored in an array at identical
1883 * indices to the public keys that they relate to.
1885 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1887 for (i = 0; i < options.num_host_key_files; i++)
1888 sensitive_data.host_certificates[i] = NULL;
1890 for (i = 0; i < options.num_host_cert_files; i++) {
1891 if (options.host_cert_files[i] == NULL)
1893 key = key_load_public(options.host_cert_files[i], NULL);
1895 error("Could not load host certificate: %s",
1896 options.host_cert_files[i]);
1899 if (!key_is_cert(key)) {
1900 error("Certificate file is not a certificate: %s",
1901 options.host_cert_files[i]);
1905 /* Find matching private key */
1906 for (j = 0; j < options.num_host_key_files; j++) {
1907 if (key_equal_public(key,
1908 sensitive_data.host_keys[j])) {
1909 sensitive_data.host_certificates[j] = key;
1913 if (j >= options.num_host_key_files) {
1914 error("No matching private key for certificate: %s",
1915 options.host_cert_files[i]);
1919 sensitive_data.host_certificates[j] = key;
1920 debug("host certificate: #%d type %d %s", j, key->type,
1925 /* Check certain values for sanity. */
1926 if (options.protocol & SSH_PROTO_1) {
1927 if (options.server_key_bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1928 options.server_key_bits > OPENSSL_RSA_MAX_MODULUS_BITS) {
1929 fprintf(stderr, "Bad server key size.\n");
1933 * Check that server and host key lengths differ sufficiently. This
1934 * is necessary to make double encryption work with rsaref. Oh, I
1935 * hate software patents. I dont know if this can go? Niels
1937 if (options.server_key_bits >
1938 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1939 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1940 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1941 SSH_KEY_BITS_RESERVED) {
1942 options.server_key_bits =
1943 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1944 SSH_KEY_BITS_RESERVED;
1945 debug("Forcing server key to %d bits to make it differ from host key.",
1946 options.server_key_bits);
1954 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1955 (S_ISDIR(st.st_mode) == 0))
1956 fatal("Missing privilege separation directory: %s",
1957 _PATH_PRIVSEP_CHROOT_DIR);
1960 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1961 (st.st_uid != getuid () ||
1962 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1964 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1966 fatal("%s must be owned by root and not group or "
1967 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1970 if (test_flag > 1) {
1971 if (server_match_spec_complete(connection_info) == 1)
1972 parse_server_match_config(&options, connection_info);
1973 dump_config(&options);
1976 /* Configuration looks good, so exit if in test mode. */
1981 * Clear out any supplemental groups we may have inherited. This
1982 * prevents inadvertent creation of files with bad modes (in the
1983 * portable version at least, it's certainly possible for PAM
1984 * to create a file, and we can't control the code in every
1985 * module which might be used).
1987 if (setgroups(0, NULL) < 0)
1988 debug("setgroups() failed: %.200s", strerror(errno));
1991 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1992 for (i = 0; i < rexec_argc; i++) {
1993 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1994 rexec_argv[i] = saved_argv[i];
1996 rexec_argv[rexec_argc] = "-R";
1997 rexec_argv[rexec_argc + 1] = NULL;
2000 /* Ensure that umask disallows at least group and world write */
2001 new_umask = umask(0077) | 0022;
2002 (void) umask(new_umask);
2004 /* Initialize the log (it is reinitialized below in case we forked). */
2005 if (debug_flag && (!inetd_flag || rexeced_flag))
2007 log_init(__progname, options.log_level, options.log_facility, log_stderr);
2010 * If not in debugging mode, and not started from inetd, disconnect
2011 * from the controlling terminal, and fork. The original process
2014 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
2017 #endif /* TIOCNOTTY */
2018 if (daemon(0, 0) < 0)
2019 fatal("daemon() failed: %.200s", strerror(errno));
2021 /* Disconnect from the controlling tty. */
2023 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
2025 (void) ioctl(fd, TIOCNOTTY, NULL);
2028 #endif /* TIOCNOTTY */
2030 /* Reinitialize the log (because of the fork above). */
2031 log_init(__progname, options.log_level, options.log_facility, log_stderr);
2033 /* Avoid killing the process in high-pressure swapping environments. */
2034 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
2035 debug("madvise(): %.200s", strerror(errno));
2037 /* Chdir to the root directory so that the current disk can be
2038 unmounted if desired. */
2039 if (chdir("/") == -1)
2040 error("chdir(\"/\"): %s", strerror(errno));
2042 /* ignore SIGPIPE */
2043 signal(SIGPIPE, SIG_IGN);
2045 /* Get a connection, either from inetd or a listening TCP socket */
2047 server_accept_inetd(&sock_in, &sock_out);
2049 platform_pre_listen();
2052 if (options.protocol & SSH_PROTO_1)
2053 generate_ephemeral_server_key();
2055 signal(SIGHUP, sighup_handler);
2056 signal(SIGCHLD, main_sigchld_handler);
2057 signal(SIGTERM, sigterm_handler);
2058 signal(SIGQUIT, sigterm_handler);
2061 * Write out the pid file after the sigterm handler
2062 * is setup and the listen sockets are bound
2064 if (options.pid_file != NULL && !debug_flag) {
2065 FILE *f = fopen(options.pid_file, "w");
2068 error("Couldn't create pid file \"%s\": %s",
2069 options.pid_file, strerror(errno));
2071 fprintf(f, "%ld\n", (long) getpid());
2076 /* Accept a connection and return in a forked child */
2077 server_accept_loop(&sock_in, &sock_out,
2078 &newsock, config_s);
2081 /* This is the child processing a new connection. */
2082 setproctitle("%s", "[accepted]");
2085 * Create a new session and process group since the 4.4BSD
2086 * setlogin() affects the entire process group. We don't
2087 * want the child to be able to affect the parent.
2089 #if !defined(SSHD_ACQUIRES_CTTY)
2091 * If setsid is called, on some platforms sshd will later acquire a
2092 * controlling terminal which will result in "could not set
2093 * controlling tty" errors.
2095 if (!debug_flag && !inetd_flag && setsid() < 0)
2096 error("setsid: %.100s", strerror(errno));
2102 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
2103 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2104 dup2(newsock, STDIN_FILENO);
2105 dup2(STDIN_FILENO, STDOUT_FILENO);
2106 if (startup_pipe == -1)
2107 close(REEXEC_STARTUP_PIPE_FD);
2108 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
2109 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
2110 close(startup_pipe);
2111 startup_pipe = REEXEC_STARTUP_PIPE_FD;
2114 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
2117 execv(rexec_argv[0], rexec_argv);
2119 /* Reexec has failed, fall back and continue */
2120 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
2121 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
2122 log_init(__progname, options.log_level,
2123 options.log_facility, log_stderr);
2126 close(REEXEC_CONFIG_PASS_FD);
2127 newsock = sock_out = sock_in = dup(STDIN_FILENO);
2128 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2129 dup2(fd, STDIN_FILENO);
2130 dup2(fd, STDOUT_FILENO);
2131 if (fd > STDERR_FILENO)
2134 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2135 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2138 /* Executed child processes don't need these. */
2139 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2140 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2143 * Disable the key regeneration alarm. We will not regenerate the
2144 * key since we are no longer in a position to give it to anyone. We
2145 * will not restart on SIGHUP since it no longer makes sense.
2148 signal(SIGALRM, SIG_DFL);
2149 signal(SIGHUP, SIG_DFL);
2150 signal(SIGTERM, SIG_DFL);
2151 signal(SIGQUIT, SIG_DFL);
2152 signal(SIGCHLD, SIG_DFL);
2153 signal(SIGINT, SIG_DFL);
2157 * Initialize the resolver. This may not happen automatically
2158 * before privsep chroot().
2160 if ((_res.options & RES_INIT) == 0) {
2161 debug("res_init()");
2166 * Force GSS-API to parse its configuration and load any
2167 * mechanism plugins.
2171 OM_uint32 minor_status;
2172 gss_indicate_mechs(&minor_status, &mechs);
2173 gss_release_oid_set(&minor_status, &mechs);
2179 * Register our connection. This turns encryption off because we do
2182 packet_set_connection(sock_in, sock_out);
2183 packet_set_server();
2185 /* Set SO_KEEPALIVE if requested. */
2186 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2187 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2188 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2190 if ((remote_port = get_remote_port()) < 0) {
2191 debug("get_remote_port failed");
2196 * We use get_canonical_hostname with usedns = 0 instead of
2197 * get_remote_ipaddr here so IP options will be checked.
2199 (void) get_canonical_hostname(0);
2201 * The rest of the code depends on the fact that
2202 * get_remote_ipaddr() caches the remote ip, even if
2203 * the socket goes away.
2205 remote_ip = get_remote_ipaddr();
2207 #ifdef SSH_AUDIT_EVENTS
2208 audit_connection_from(remote_ip, remote_port);
2211 allow_severity = options.log_facility|LOG_INFO;
2212 deny_severity = options.log_facility|LOG_WARNING;
2213 /* Check whether logins are denied from this host. */
2214 if (packet_connection_is_on_socket()) {
2215 struct request_info req;
2217 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
2220 if (!hosts_access(&req)) {
2221 debug("Connection refused by tcp wrapper");
2224 fatal("libwrap refuse returns");
2227 #endif /* LIBWRAP */
2229 /* Log the connection. */
2230 laddr = get_local_ipaddr(sock_in);
2231 verbose("Connection from %s port %d on %s port %d",
2232 remote_ip, remote_port, laddr, get_local_port());
2236 * We don't want to listen forever unless the other side
2237 * successfully authenticates itself. So we set up an alarm which is
2238 * cleared after successful authentication. A limit of zero
2239 * indicates no limit. Note that we don't set the alarm in debugging
2240 * mode; it is just annoying to have the server exit just when you
2241 * are about to discover the bug.
2243 signal(SIGALRM, grace_alarm_handler);
2245 alarm(options.login_grace_time);
2247 sshd_exchange_identification(sock_in, sock_out);
2249 /* In inetd mode, generate ephemeral key only for proto 1 connections */
2250 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2251 generate_ephemeral_server_key();
2253 packet_set_nonblocking();
2255 /* allocate authentication context */
2256 authctxt = xcalloc(1, sizeof(*authctxt));
2258 authctxt->loginmsg = &loginmsg;
2260 /* XXX global for cleanup, access from other modules */
2261 the_authctxt = authctxt;
2263 /* prepare buffer to collect messages to display to user after login */
2264 buffer_init(&loginmsg);
2268 if (privsep_preauth(authctxt) == 1)
2270 } else if (compat20 && have_agent) {
2271 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2272 error("Unable to get agent socket: %s", ssh_err(r));
2277 /* perform the key exchange */
2278 /* authenticate user and start session */
2281 do_authentication2(authctxt);
2285 do_authentication(authctxt);
2287 fatal("ssh1 not supported");
2291 * If we use privilege separation, the unprivileged child transfers
2292 * the current keystate and exits
2295 mm_send_keystate(pmonitor);
2301 * Cancel the alarm we set to limit the time taken for
2305 signal(SIGALRM, SIG_DFL);
2306 authctxt->authenticated = 1;
2307 if (startup_pipe != -1) {
2308 close(startup_pipe);
2312 #ifdef SSH_AUDIT_EVENTS
2313 audit_event(SSH_AUTH_SUCCESS);
2317 if (options.gss_authentication) {
2318 temporarily_use_uid(authctxt->pw);
2319 ssh_gssapi_storecreds();
2324 if (options.use_pam) {
2331 * In privilege separation, we fork another child and prepare
2332 * file descriptor passing.
2335 privsep_postauth(authctxt);
2336 /* the monitor process [priv] will not return */
2338 destroy_sensitive_data();
2341 packet_set_timeout(options.client_alive_interval,
2342 options.client_alive_count_max);
2344 /* Try to send all our hostkeys to the client */
2346 notify_hostkeys(active_state);
2348 /* Start session. */
2349 do_authenticated(authctxt);
2351 /* The connection has been terminated. */
2352 packet_get_bytes(&ibytes, &obytes);
2353 verbose("Transferred: sent %llu, received %llu bytes",
2354 (unsigned long long)obytes, (unsigned long long)ibytes);
2356 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2359 if (options.use_pam)
2361 #endif /* USE_PAM */
2363 #ifdef SSH_AUDIT_EVENTS
2364 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2377 * Decrypt session_key_int using our private server key and private host key
2378 * (key with larger modulus first).
2381 ssh1_session_key(BIGNUM *session_key_int)
2385 if (BN_cmp(sensitive_data.server_key->rsa->n,
2386 sensitive_data.ssh1_host_key->rsa->n) > 0) {
2387 /* Server key has bigger modulus. */
2388 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2389 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2390 SSH_KEY_BITS_RESERVED) {
2391 fatal("do_connection: %s: "
2392 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2393 get_remote_ipaddr(),
2394 BN_num_bits(sensitive_data.server_key->rsa->n),
2395 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2396 SSH_KEY_BITS_RESERVED);
2398 if (rsa_private_decrypt(session_key_int, session_key_int,
2399 sensitive_data.server_key->rsa) != 0)
2401 if (rsa_private_decrypt(session_key_int, session_key_int,
2402 sensitive_data.ssh1_host_key->rsa) != 0)
2405 /* Host key has bigger modulus (or they are equal). */
2406 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2407 BN_num_bits(sensitive_data.server_key->rsa->n) +
2408 SSH_KEY_BITS_RESERVED) {
2409 fatal("do_connection: %s: "
2410 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2411 get_remote_ipaddr(),
2412 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2413 BN_num_bits(sensitive_data.server_key->rsa->n),
2414 SSH_KEY_BITS_RESERVED);
2416 if (rsa_private_decrypt(session_key_int, session_key_int,
2417 sensitive_data.ssh1_host_key->rsa) != 0)
2419 if (rsa_private_decrypt(session_key_int, session_key_int,
2420 sensitive_data.server_key->rsa) != 0)
2434 BIGNUM *session_key_int, *fake_key_int, *real_key_int;
2435 u_char session_key[SSH_SESSION_KEY_LENGTH];
2436 u_char fake_key_bytes[4096 / 8];
2437 size_t fake_key_len;
2439 u_int cipher_type, auth_mask, protocol_flags;
2442 * Generate check bytes that the client must send back in the user
2443 * packet in order for it to be accepted; this is used to defy ip
2444 * spoofing attacks. Note that this only works against somebody
2445 * doing IP spoofing from a remote machine; any machine on the local
2446 * network can still see outgoing packets and catch the random
2447 * cookie. This only affects rhosts authentication, and this is one
2448 * of the reasons why it is inherently insecure.
2450 arc4random_buf(cookie, sizeof(cookie));
2453 * Send our public key. We include in the packet 64 bits of random
2454 * data that must be matched in the reply in order to prevent IP
2457 packet_start(SSH_SMSG_PUBLIC_KEY);
2458 for (i = 0; i < 8; i++)
2459 packet_put_char(cookie[i]);
2461 /* Store our public server RSA key. */
2462 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2463 packet_put_bignum(sensitive_data.server_key->rsa->e);
2464 packet_put_bignum(sensitive_data.server_key->rsa->n);
2466 /* Store our public host RSA key. */
2467 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2468 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2469 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2471 /* Put protocol flags. */
2472 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2474 /* Declare which ciphers we support. */
2475 packet_put_int(cipher_mask_ssh1(0));
2477 /* Declare supported authentication types. */
2479 if (options.rhosts_rsa_authentication)
2480 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2481 if (options.rsa_authentication)
2482 auth_mask |= 1 << SSH_AUTH_RSA;
2483 if (options.challenge_response_authentication == 1)
2484 auth_mask |= 1 << SSH_AUTH_TIS;
2485 if (options.password_authentication)
2486 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2487 packet_put_int(auth_mask);
2489 /* Send the packet and wait for it to be sent. */
2491 packet_write_wait();
2493 debug("Sent %d bit server key and %d bit host key.",
2494 BN_num_bits(sensitive_data.server_key->rsa->n),
2495 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2497 /* Read clients reply (cipher type and session key). */
2498 packet_read_expect(SSH_CMSG_SESSION_KEY);
2500 /* Get cipher type and check whether we accept this. */
2501 cipher_type = packet_get_char();
2503 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2504 packet_disconnect("Warning: client selects unsupported cipher.");
2506 /* Get check bytes from the packet. These must match those we
2507 sent earlier with the public key packet. */
2508 for (i = 0; i < 8; i++)
2509 if (cookie[i] != packet_get_char())
2510 packet_disconnect("IP Spoofing check bytes do not match.");
2512 debug("Encryption type: %.200s", cipher_name(cipher_type));
2514 /* Get the encrypted integer. */
2515 if ((real_key_int = BN_new()) == NULL)
2516 fatal("do_ssh1_kex: BN_new failed");
2517 packet_get_bignum(real_key_int);
2519 protocol_flags = packet_get_int();
2520 packet_set_protocol_flags(protocol_flags);
2523 /* Setup a fake key in case RSA decryption fails */
2524 if ((fake_key_int = BN_new()) == NULL)
2525 fatal("do_ssh1_kex: BN_new failed");
2526 fake_key_len = BN_num_bytes(real_key_int);
2527 if (fake_key_len > sizeof(fake_key_bytes))
2528 fake_key_len = sizeof(fake_key_bytes);
2529 arc4random_buf(fake_key_bytes, fake_key_len);
2530 if (BN_bin2bn(fake_key_bytes, fake_key_len, fake_key_int) == NULL)
2531 fatal("do_ssh1_kex: BN_bin2bn failed");
2533 /* Decrypt real_key_int using host/server keys */
2534 rsafail = PRIVSEP(ssh1_session_key(real_key_int));
2535 /* If decryption failed, use the fake key. Else, the real key. */
2537 session_key_int = fake_key_int;
2539 session_key_int = real_key_int;
2542 * Extract session key from the decrypted integer. The key is in the
2543 * least significant 256 bits of the integer; the first byte of the
2544 * key is in the highest bits.
2546 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2547 len = BN_num_bytes(session_key_int);
2548 if (len < 0 || (u_int)len > sizeof(session_key)) {
2549 error("do_ssh1_kex: bad session key len from %s: "
2550 "session_key_int %d > sizeof(session_key) %lu",
2551 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2554 explicit_bzero(session_key, sizeof(session_key));
2555 BN_bn2bin(session_key_int,
2556 session_key + sizeof(session_key) - len);
2558 derive_ssh1_session_id(
2559 sensitive_data.ssh1_host_key->rsa->n,
2560 sensitive_data.server_key->rsa->n,
2561 cookie, session_id);
2563 * Xor the first 16 bytes of the session key with the
2566 for (i = 0; i < 16; i++)
2567 session_key[i] ^= session_id[i];
2570 /* Destroy the private and public keys. No longer. */
2571 destroy_sensitive_data();
2574 mm_ssh1_session_id(session_id);
2576 /* Destroy the decrypted integer. It is no longer needed. */
2577 BN_clear_free(real_key_int);
2578 BN_clear_free(fake_key_int);
2580 /* Set the session key. From this on all communications will be encrypted. */
2581 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2583 /* Destroy our copy of the session key. It is no longer needed. */
2584 explicit_bzero(session_key, sizeof(session_key));
2586 debug("Received session key; encryption turned on.");
2588 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2589 packet_start(SSH_SMSG_SUCCESS);
2591 packet_write_wait();
2596 sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen,
2597 const u_char *data, size_t dlen, const char *alg, u_int flag)
2600 u_int xxx_slen, xxx_dlen = dlen;
2603 if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen,
2605 fatal("%s: key_sign failed", __func__);
2608 } else if (use_privsep) {
2609 if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen,
2611 fatal("%s: pubkey_sign failed", __func__);
2615 if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen,
2616 data, dlen, alg, datafellows)) != 0)
2617 fatal("%s: ssh_agent_sign failed: %s",
2618 __func__, ssh_err(r));
2623 /* SSH2 key exchange */
2627 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2631 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2632 options.kex_algorithms);
2633 myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
2635 myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
2637 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2638 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2640 if (options.compression == COMP_NONE) {
2641 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2642 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2643 } else if (options.compression == COMP_DELAYED) {
2644 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2645 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2648 if (options.rekey_limit || options.rekey_interval)
2649 packet_set_rekey_limits(options.rekey_limit,
2650 (time_t)options.rekey_interval);
2652 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2653 list_hostkey_types());
2655 /* start key exchange */
2656 if ((r = kex_setup(active_state, myproposal)) != 0)
2657 fatal("kex_setup: %s", ssh_err(r));
2658 kex = active_state->kex;
2660 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2661 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2662 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2663 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2664 # ifdef OPENSSL_HAS_ECC
2665 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2668 kex->kex[KEX_C25519_SHA256] = kexc25519_server;
2670 kex->client_version_string=client_version_string;
2671 kex->server_version_string=server_version_string;
2672 kex->load_host_public_key=&get_hostkey_public_by_type;
2673 kex->load_host_private_key=&get_hostkey_private_by_type;
2674 kex->host_key_index=&get_hostkey_index;
2675 kex->sign = sshd_hostkey_sign;
2677 dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
2679 session_id2 = kex->session_id;
2680 session_id2_len = kex->session_id_len;
2683 /* send 1st encrypted/maced/compressed message */
2684 packet_start(SSH2_MSG_IGNORE);
2685 packet_put_cstring("markus");
2687 packet_write_wait();
2692 /* server specific fatal cleanup */
2697 do_cleanup(the_authctxt);
2698 if (use_privsep && privsep_is_preauth &&
2699 pmonitor != NULL && pmonitor->m_pid > 1) {
2700 debug("Killing privsep child %d", pmonitor->m_pid);
2701 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2703 error("%s: kill(%d): %s", __func__,
2704 pmonitor->m_pid, strerror(errno));
2707 #ifdef SSH_AUDIT_EVENTS
2708 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2709 if (!use_privsep || mm_is_monitor())
2710 audit_event(SSH_CONNECTION_ABANDON);