1 /* $OpenBSD: sshd.c,v 1.404 2013/07/19 07:37:48 markus Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * This program is the ssh daemon. It listens for connections from clients,
8 * and performs authentication, executes use commands or shell, and forwards
9 * information to/from the application to the user client over an encrypted
10 * connection. This can also handle forwarding of X11, TCP/IP, and
11 * authentication agent connections.
13 * As far as I am concerned, the code I have written for this software
14 * can be used freely for any purpose. Any derived versions of this
15 * software must be clearly marked as such, and if the derived work is
16 * incompatible with the protocol description in the RFC file, it must be
17 * called by a name other than "ssh" or "Secure Shell".
19 * SSH2 implementation:
20 * Privilege Separation:
22 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
23 * Copyright (c) 2002 Niels Provos. All rights reserved.
25 * Redistribution and use in source and binary forms, with or without
26 * modification, are permitted provided that the following conditions
28 * 1. Redistributions of source code must retain the above copyright
29 * notice, this list of conditions and the following disclaimer.
30 * 2. Redistributions in binary form must reproduce the above copyright
31 * notice, this list of conditions and the following disclaimer in the
32 * documentation and/or other materials provided with the distribution.
34 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
35 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
36 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
37 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
38 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
39 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
40 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
41 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
49 #include <sys/types.h>
50 #include <sys/ioctl.h>
52 #include <sys/socket.h>
53 #ifdef HAVE_SYS_STAT_H
54 # include <sys/stat.h>
56 #ifdef HAVE_SYS_TIME_H
57 # include <sys/time.h>
59 #include "openbsd-compat/sys-tree.h"
60 #include "openbsd-compat/sys-queue.h"
78 #include <openssl/dh.h>
79 #include <openssl/bn.h>
80 #include <openssl/md5.h>
81 #include <openssl/rand.h>
82 #include "openbsd-compat/openssl-compat.h"
84 #ifdef HAVE_SECUREWARE
85 #include <sys/security.h>
91 #if defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
92 #include <gssapi/gssapi.h>
93 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_H)
107 #include "servconf.h"
114 #include "myproposal.h"
115 #include "authfile.h"
116 #include "pathnames.h"
117 #include "atomicio.h"
118 #include "canohost.h"
119 #include "hostfile.h"
124 #include "dispatch.h"
125 #include "channels.h"
127 #include "monitor_mm.h"
132 #include "monitor_wrap.h"
134 #include "ssh-sandbox.h"
149 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
150 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
151 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
152 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
154 extern char *__progname;
156 /* Server configuration options. */
157 ServerOptions options;
159 /* Name of the server configuration file. */
160 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
163 * Debug mode flag. This can be set on the command line. If debug
164 * mode is enabled, extra debugging output will be sent to the system
165 * log, the daemon will not go to background, and will exit after processing
166 * the first connection.
170 /* Flag indicating that the daemon should only test the configuration and keys. */
173 /* Flag indicating that the daemon is being started from inetd. */
176 /* Flag indicating that sshd should not detach and become a daemon. */
177 int no_daemon_flag = 0;
179 /* debug goes to stderr unless inetd_flag is set */
182 /* Saved arguments to main(). */
187 int rexeced_flag = 0;
193 * The sockets that the server is listening; this is used in the SIGHUP
196 #define MAX_LISTEN_SOCKS 16
197 int listen_socks[MAX_LISTEN_SOCKS];
198 int num_listen_socks = 0;
201 * the client's version string, passed by sshd2 in compat mode. if != NULL,
202 * sshd will skip the version-number exchange
204 char *client_version_string = NULL;
205 char *server_version_string = NULL;
207 /* for rekeying XXX fixme */
210 /* Daemon's agent connection */
211 AuthenticationConnection *auth_conn = NULL;
215 * Any really sensitive data in the application is contained in this
216 * structure. The idea is that this structure could be locked into memory so
217 * that the pages do not get written into swap. However, there are some
218 * problems. The private key contains BIGNUMs, and we do not (in principle)
219 * have access to the internals of them, and locking just the structure is
220 * not very useful. Currently, memory locking is not implemented.
223 Key *server_key; /* ephemeral server key */
224 Key *ssh1_host_key; /* ssh1 host key */
225 Key **host_keys; /* all private host keys */
226 Key **host_pubkeys; /* all public host keys */
227 Key **host_certificates; /* all public host certificates */
230 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
234 * Flag indicating whether the RSA server key needs to be regenerated.
235 * Is set in the SIGALRM handler and cleared when the key is regenerated.
237 static volatile sig_atomic_t key_do_regen = 0;
239 /* This is set to true when a signal is received. */
240 static volatile sig_atomic_t received_sighup = 0;
241 static volatile sig_atomic_t received_sigterm = 0;
243 /* session identifier, used by RSA-auth */
244 u_char session_id[16];
247 u_char *session_id2 = NULL;
248 u_int session_id2_len = 0;
250 /* record remote hostname or ip */
251 u_int utmp_len = MAXHOSTNAMELEN;
253 /* options.max_startup sized array of fd ints */
254 int *startup_pipes = NULL;
255 int startup_pipe; /* in child */
257 /* variables used for privilege separation */
258 int use_privsep = -1;
259 struct monitor *pmonitor = NULL;
260 int privsep_is_preauth = 1;
262 /* global authentication context */
263 Authctxt *the_authctxt = NULL;
265 /* sshd_config buffer */
268 /* message to be displayed after login */
271 /* Unprivileged user */
272 struct passwd *privsep_pw = NULL;
274 /* Prototypes for various functions defined later in this file. */
275 void destroy_sensitive_data(void);
276 void demote_sensitive_data(void);
278 static void do_ssh1_kex(void);
279 static void do_ssh2_kex(void);
282 * Close all listening sockets
285 close_listen_socks(void)
289 for (i = 0; i < num_listen_socks; i++)
290 close(listen_socks[i]);
291 num_listen_socks = -1;
295 close_startup_pipes(void)
300 for (i = 0; i < options.max_startups; i++)
301 if (startup_pipes[i] != -1)
302 close(startup_pipes[i]);
306 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
307 * the effect is to reread the configuration file (and to regenerate
313 sighup_handler(int sig)
315 int save_errno = errno;
318 signal(SIGHUP, sighup_handler);
323 * Called from the main program after receiving SIGHUP.
324 * Restarts the server.
329 logit("Received SIGHUP; restarting.");
330 close_listen_socks();
331 close_startup_pipes();
332 alarm(0); /* alarm timer persists across exec */
333 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
334 execv(saved_argv[0], saved_argv);
335 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
341 * Generic signal handler for terminating signals in the master daemon.
345 sigterm_handler(int sig)
347 received_sigterm = sig;
351 * SIGCHLD handler. This is called whenever a child dies. This will then
352 * reap any zombies left by exited children.
356 main_sigchld_handler(int sig)
358 int save_errno = errno;
362 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
363 (pid < 0 && errno == EINTR))
366 signal(SIGCHLD, main_sigchld_handler);
371 * Signal handler for the alarm after the login grace period has expired.
375 grace_alarm_handler(int sig)
377 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
378 kill(pmonitor->m_pid, SIGALRM);
381 * Try to kill any processes that we have spawned, E.g. authorized
382 * keys command helpers.
384 if (getpgid(0) == getpid()) {
385 signal(SIGTERM, SIG_IGN);
389 /* Log error and exit. */
390 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
394 * Signal handler for the key regeneration alarm. Note that this
395 * alarm only occurs in the daemon waiting for connections, and it does not
396 * do anything with the private key or random state before forking.
397 * Thus there should be no concurrency control/asynchronous execution
401 generate_ephemeral_server_key(void)
403 verbose("Generating %s%d bit RSA key.",
404 sensitive_data.server_key ? "new " : "", options.server_key_bits);
405 if (sensitive_data.server_key != NULL)
406 key_free(sensitive_data.server_key);
407 sensitive_data.server_key = key_generate(KEY_RSA1,
408 options.server_key_bits);
409 verbose("RSA key generation complete.");
411 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
417 key_regeneration_alarm(int sig)
419 int save_errno = errno;
421 signal(SIGALRM, SIG_DFL);
427 sshd_exchange_identification(int sock_in, int sock_out)
431 int remote_major, remote_minor;
433 char *s, *newline = "\n";
434 char buf[256]; /* Must not be larger than remote_version. */
435 char remote_version[256]; /* Must be at least as big as buf. */
437 if ((options.protocol & SSH_PROTO_1) &&
438 (options.protocol & SSH_PROTO_2)) {
439 major = PROTOCOL_MAJOR_1;
441 } else if (options.protocol & SSH_PROTO_2) {
442 major = PROTOCOL_MAJOR_2;
443 minor = PROTOCOL_MINOR_2;
446 major = PROTOCOL_MAJOR_1;
447 minor = PROTOCOL_MINOR_1;
450 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s%s",
451 major, minor, SSH_VERSION,
452 options.hpn_disabled ? "" : SSH_VERSION_HPN,
453 *options.version_addendum == '\0' ? "" : " ",
454 options.version_addendum, newline);
456 /* Send our protocol version identification. */
457 if (roaming_atomicio(vwrite, sock_out, server_version_string,
458 strlen(server_version_string))
459 != strlen(server_version_string)) {
460 logit("Could not write ident string to %s", get_remote_ipaddr());
464 /* Read other sides version identification. */
465 memset(buf, 0, sizeof(buf));
466 for (i = 0; i < sizeof(buf) - 1; i++) {
467 if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
468 logit("Did not receive identification string from %s",
469 get_remote_ipaddr());
472 if (buf[i] == '\r') {
474 /* Kludge for F-Secure Macintosh < 1.0.2 */
476 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
480 if (buf[i] == '\n') {
485 buf[sizeof(buf) - 1] = 0;
486 client_version_string = xstrdup(buf);
489 * Check that the versions match. In future this might accept
490 * several versions and set appropriate flags to handle them.
492 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
493 &remote_major, &remote_minor, remote_version) != 3) {
494 s = "Protocol mismatch.\n";
495 (void) atomicio(vwrite, sock_out, s, strlen(s));
498 logit("Bad protocol version identification '%.100s' from %s",
499 client_version_string, get_remote_ipaddr());
502 debug("Client protocol version %d.%d; client software version %.100s",
503 remote_major, remote_minor, remote_version);
505 compat_datafellows(remote_version);
507 if (datafellows & SSH_BUG_PROBE) {
508 logit("probed from %s with %s. Don't panic.",
509 get_remote_ipaddr(), client_version_string);
513 if (datafellows & SSH_BUG_SCANNER) {
514 logit("scanned from %s with %s. Don't panic.",
515 get_remote_ipaddr(), client_version_string);
520 switch (remote_major) {
522 if (remote_minor == 99) {
523 if (options.protocol & SSH_PROTO_2)
529 if (!(options.protocol & SSH_PROTO_1)) {
533 if (remote_minor < 3) {
534 packet_disconnect("Your ssh version is too old and "
535 "is no longer supported. Please install a newer version.");
536 } else if (remote_minor == 3) {
537 /* note that this disables agent-forwarding */
542 if (options.protocol & SSH_PROTO_2) {
551 chop(server_version_string);
552 debug("Local version string %.200s", server_version_string);
555 s = "Protocol major versions differ.\n";
556 (void) atomicio(vwrite, sock_out, s, strlen(s));
559 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
561 server_version_string, client_version_string);
566 /* Destroy the host and server keys. They will no longer be needed. */
568 destroy_sensitive_data(void)
572 if (sensitive_data.server_key) {
573 key_free(sensitive_data.server_key);
574 sensitive_data.server_key = NULL;
576 for (i = 0; i < options.num_host_key_files; i++) {
577 if (sensitive_data.host_keys[i]) {
578 key_free(sensitive_data.host_keys[i]);
579 sensitive_data.host_keys[i] = NULL;
581 if (sensitive_data.host_certificates[i]) {
582 key_free(sensitive_data.host_certificates[i]);
583 sensitive_data.host_certificates[i] = NULL;
586 sensitive_data.ssh1_host_key = NULL;
587 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
590 /* Demote private to public keys for network child */
592 demote_sensitive_data(void)
597 if (sensitive_data.server_key) {
598 tmp = key_demote(sensitive_data.server_key);
599 key_free(sensitive_data.server_key);
600 sensitive_data.server_key = tmp;
603 for (i = 0; i < options.num_host_key_files; i++) {
604 if (sensitive_data.host_keys[i]) {
605 tmp = key_demote(sensitive_data.host_keys[i]);
606 key_free(sensitive_data.host_keys[i]);
607 sensitive_data.host_keys[i] = tmp;
608 if (tmp->type == KEY_RSA1)
609 sensitive_data.ssh1_host_key = tmp;
611 /* Certs do not need demotion */
614 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
618 privsep_preauth_child(void)
623 /* Enable challenge-response authentication for privilege separation */
624 privsep_challenge_enable();
627 arc4random_buf(rnd, sizeof(rnd));
628 RAND_seed(rnd, sizeof(rnd));
630 /* Demote the private keys to public keys. */
631 demote_sensitive_data();
633 /* Change our root directory */
634 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
635 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
637 if (chdir("/") == -1)
638 fatal("chdir(\"/\"): %s", strerror(errno));
640 /* Drop our privileges */
641 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
642 (u_int)privsep_pw->pw_gid);
644 /* XXX not ready, too heavy after chroot */
645 do_setusercontext(privsep_pw);
647 gidset[0] = privsep_pw->pw_gid;
648 if (setgroups(1, gidset) < 0)
649 fatal("setgroups: %.100s", strerror(errno));
650 permanently_set_uid(privsep_pw);
655 privsep_preauth(Authctxt *authctxt)
659 struct ssh_sandbox *box = NULL;
661 /* Set up unprivileged child process to deal with network data */
662 pmonitor = monitor_init();
663 /* Store a pointer to the kex for later rekeying */
664 pmonitor->m_pkex = &xxx_kex;
666 if (use_privsep == PRIVSEP_ON)
667 box = ssh_sandbox_init();
670 fatal("fork of unprivileged child failed");
671 } else if (pid != 0) {
672 debug2("Network child is on pid %ld", (long)pid);
674 pmonitor->m_pid = pid;
676 auth_conn = ssh_get_authentication_connection();
678 ssh_sandbox_parent_preauth(box, pid);
679 monitor_child_preauth(authctxt, pmonitor);
682 monitor_sync(pmonitor);
684 /* Wait for the child's exit status */
685 while (waitpid(pid, &status, 0) < 0) {
688 pmonitor->m_pid = -1;
689 fatal("%s: waitpid: %s", __func__, strerror(errno));
691 privsep_is_preauth = 0;
692 pmonitor->m_pid = -1;
693 if (WIFEXITED(status)) {
694 if (WEXITSTATUS(status) != 0)
695 fatal("%s: preauth child exited with status %d",
696 __func__, WEXITSTATUS(status));
697 } else if (WIFSIGNALED(status))
698 fatal("%s: preauth child terminated by signal %d",
699 __func__, WTERMSIG(status));
701 ssh_sandbox_parent_finish(box);
705 close(pmonitor->m_sendfd);
706 close(pmonitor->m_log_recvfd);
708 /* Arrange for logging to be sent to the monitor */
709 set_log_handler(mm_log_handler, pmonitor);
711 /* Demote the child */
712 if (getuid() == 0 || geteuid() == 0)
713 privsep_preauth_child();
714 setproctitle("%s", "[net]");
716 ssh_sandbox_child(box);
723 privsep_postauth(Authctxt *authctxt)
727 #ifdef DISABLE_FD_PASSING
730 if (authctxt->pw->pw_uid == 0 || options.use_login) {
732 /* File descriptor passing is broken or root login */
737 /* New socket pair */
738 monitor_reinit(pmonitor);
740 pmonitor->m_pid = fork();
741 if (pmonitor->m_pid == -1)
742 fatal("fork of unprivileged child failed");
743 else if (pmonitor->m_pid != 0) {
744 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
745 buffer_clear(&loginmsg);
746 monitor_child_postauth(pmonitor);
754 close(pmonitor->m_sendfd);
755 pmonitor->m_sendfd = -1;
757 /* Demote the private keys to public keys. */
758 demote_sensitive_data();
761 arc4random_buf(rnd, sizeof(rnd));
762 RAND_seed(rnd, sizeof(rnd));
764 /* Drop privileges */
765 do_setusercontext(authctxt->pw);
768 /* It is safe now to apply the key state */
769 monitor_apply_keystate(pmonitor);
772 * Tell the packet layer that authentication was successful, since
773 * this information is not part of the key state.
775 packet_set_authenticated();
779 list_hostkey_types(void)
788 for (i = 0; i < options.num_host_key_files; i++) {
789 key = sensitive_data.host_keys[i];
791 key = sensitive_data.host_pubkeys[i];
798 if (buffer_len(&b) > 0)
799 buffer_append(&b, ",", 1);
800 p = key_ssh_name(key);
801 buffer_append(&b, p, strlen(p));
804 /* If the private key has a cert peer, then list that too */
805 key = sensitive_data.host_certificates[i];
809 case KEY_RSA_CERT_V00:
810 case KEY_DSA_CERT_V00:
814 if (buffer_len(&b) > 0)
815 buffer_append(&b, ",", 1);
816 p = key_ssh_name(key);
817 buffer_append(&b, p, strlen(p));
821 buffer_append(&b, "\0", 1);
822 ret = xstrdup(buffer_ptr(&b));
824 debug("list_hostkey_types: %s", ret);
829 get_hostkey_by_type(int type, int need_private)
834 for (i = 0; i < options.num_host_key_files; i++) {
836 case KEY_RSA_CERT_V00:
837 case KEY_DSA_CERT_V00:
841 key = sensitive_data.host_certificates[i];
844 key = sensitive_data.host_keys[i];
845 if (key == NULL && !need_private)
846 key = sensitive_data.host_pubkeys[i];
849 if (key != NULL && key->type == type)
850 return need_private ?
851 sensitive_data.host_keys[i] : key;
857 get_hostkey_public_by_type(int type)
859 return get_hostkey_by_type(type, 0);
863 get_hostkey_private_by_type(int type)
865 return get_hostkey_by_type(type, 1);
869 get_hostkey_by_index(int ind)
871 if (ind < 0 || ind >= options.num_host_key_files)
873 return (sensitive_data.host_keys[ind]);
877 get_hostkey_public_by_index(int ind)
879 if (ind < 0 || ind >= options.num_host_key_files)
881 return (sensitive_data.host_pubkeys[ind]);
885 get_hostkey_index(Key *key)
889 for (i = 0; i < options.num_host_key_files; i++) {
890 if (key_is_cert(key)) {
891 if (key == sensitive_data.host_certificates[i])
894 if (key == sensitive_data.host_keys[i])
896 if (key == sensitive_data.host_pubkeys[i])
904 * returns 1 if connection should be dropped, 0 otherwise.
905 * dropping starts at connection #max_startups_begin with a probability
906 * of (max_startups_rate/100). the probability increases linearly until
907 * all connections are dropped for startups > max_startups
910 drop_connection(int startups)
914 if (startups < options.max_startups_begin)
916 if (startups >= options.max_startups)
918 if (options.max_startups_rate == 100)
921 p = 100 - options.max_startups_rate;
922 p *= startups - options.max_startups_begin;
923 p /= options.max_startups - options.max_startups_begin;
924 p += options.max_startups_rate;
925 r = arc4random_uniform(100);
927 debug("drop_connection: p %d, r %d", p, r);
928 return (r < p) ? 1 : 0;
934 if (options.version_addendum && *options.version_addendum != '\0')
935 fprintf(stderr, "%s%s %s, %s\n",
936 SSH_RELEASE, options.hpn_disabled ? "" : SSH_VERSION_HPN,
937 options.version_addendum, SSLeay_version(SSLEAY_VERSION));
939 fprintf(stderr, "%s%s, %s\n",
940 SSH_RELEASE, options.hpn_disabled ? "" : SSH_VERSION_HPN,
941 SSLeay_version(SSLEAY_VERSION));
943 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
944 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
945 " [-h host_key_file] [-k key_gen_time] [-o option] [-p port]\n"
952 send_rexec_state(int fd, Buffer *conf)
956 debug3("%s: entering fd = %d config len %d", __func__, fd,
960 * Protocol from reexec master to child:
961 * string configuration
962 * u_int ephemeral_key_follows
963 * bignum e (only if ephemeral_key_follows == 1)
969 * string rngseed (only if OpenSSL is not self-seeded)
972 buffer_put_cstring(&m, buffer_ptr(conf));
974 if (sensitive_data.server_key != NULL &&
975 sensitive_data.server_key->type == KEY_RSA1) {
976 buffer_put_int(&m, 1);
977 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
978 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
979 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
980 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
981 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
982 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
984 buffer_put_int(&m, 0);
986 #ifndef OPENSSL_PRNG_ONLY
987 rexec_send_rng_seed(&m);
990 if (ssh_msg_send(fd, 0, &m) == -1)
991 fatal("%s: ssh_msg_send failed", __func__);
995 debug3("%s: done", __func__);
999 recv_rexec_state(int fd, Buffer *conf)
1005 debug3("%s: entering fd = %d", __func__, fd);
1009 if (ssh_msg_recv(fd, &m) == -1)
1010 fatal("%s: ssh_msg_recv failed", __func__);
1011 if (buffer_get_char(&m) != 0)
1012 fatal("%s: rexec version mismatch", __func__);
1014 cp = buffer_get_string(&m, &len);
1016 buffer_append(conf, cp, len + 1);
1019 if (buffer_get_int(&m)) {
1020 if (sensitive_data.server_key != NULL)
1021 key_free(sensitive_data.server_key);
1022 sensitive_data.server_key = key_new_private(KEY_RSA1);
1023 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
1024 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
1025 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
1026 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1027 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
1028 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
1029 rsa_generate_additional_parameters(
1030 sensitive_data.server_key->rsa);
1033 #ifndef OPENSSL_PRNG_ONLY
1034 rexec_recv_rng_seed(&m);
1039 debug3("%s: done", __func__);
1042 /* Accept a connection from inetd */
1044 server_accept_inetd(int *sock_in, int *sock_out)
1050 close(REEXEC_CONFIG_PASS_FD);
1051 *sock_in = *sock_out = dup(STDIN_FILENO);
1053 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1054 close(REEXEC_STARTUP_PIPE_FD);
1057 *sock_in = dup(STDIN_FILENO);
1058 *sock_out = dup(STDOUT_FILENO);
1061 * We intentionally do not close the descriptors 0, 1, and 2
1062 * as our code for setting the descriptors won't work if
1063 * ttyfd happens to be one of those.
1065 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1066 dup2(fd, STDIN_FILENO);
1067 dup2(fd, STDOUT_FILENO);
1069 dup2(fd, STDERR_FILENO);
1070 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1073 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1077 * Listen for TCP connections
1082 int ret, listen_sock, on = 1;
1083 struct addrinfo *ai;
1084 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1088 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1089 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1091 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1092 fatal("Too many listen sockets. "
1093 "Enlarge MAX_LISTEN_SOCKS");
1094 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1095 ntop, sizeof(ntop), strport, sizeof(strport),
1096 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1097 error("getnameinfo failed: %.100s",
1098 ssh_gai_strerror(ret));
1101 /* Create socket for listening. */
1102 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1104 if (listen_sock < 0) {
1105 /* kernel may not support ipv6 */
1106 verbose("socket: %.100s", strerror(errno));
1109 if (set_nonblock(listen_sock) == -1) {
1114 * Set socket options.
1115 * Allow local port reuse in TIME_WAIT.
1117 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1118 &on, sizeof(on)) == -1)
1119 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1121 /* Only communicate in IPv6 over AF_INET6 sockets. */
1122 if (ai->ai_family == AF_INET6)
1123 sock_set_v6only(listen_sock);
1125 debug("Bind to port %s on %s.", strport, ntop);
1127 len = sizeof(socksize);
1128 getsockopt(listen_sock, SOL_SOCKET, SO_RCVBUF, &socksize, &len);
1129 debug("Server TCP RWIN socket size: %d", socksize);
1130 debug("HPN Buffer Size: %d", options.hpn_buffer_size);
1132 /* Bind the socket to the desired port. */
1133 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1134 error("Bind to port %s on %s failed: %.200s.",
1135 strport, ntop, strerror(errno));
1139 listen_socks[num_listen_socks] = listen_sock;
1142 /* Start listening on the port. */
1143 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1144 fatal("listen on [%s]:%s: %.100s",
1145 ntop, strport, strerror(errno));
1146 logit("Server listening on %s port %s.", ntop, strport);
1148 freeaddrinfo(options.listen_addrs);
1150 if (!num_listen_socks)
1151 fatal("Cannot bind any address.");
1155 * The main TCP accept loop. Note that, for the non-debug case, returns
1156 * from this function are in a forked subprocess.
1159 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1162 int i, j, ret, maxfd;
1163 int key_used = 0, startups = 0;
1164 int startup_p[2] = { -1 , -1 };
1165 struct sockaddr_storage from;
1169 /* setup fd set for accept */
1172 for (i = 0; i < num_listen_socks; i++)
1173 if (listen_socks[i] > maxfd)
1174 maxfd = listen_socks[i];
1175 /* pipes connected to unauthenticated childs */
1176 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1177 for (i = 0; i < options.max_startups; i++)
1178 startup_pipes[i] = -1;
1181 * Stay listening for connections until the system crashes or
1182 * the daemon is killed with a signal.
1185 if (received_sighup)
1189 fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1192 for (i = 0; i < num_listen_socks; i++)
1193 FD_SET(listen_socks[i], fdset);
1194 for (i = 0; i < options.max_startups; i++)
1195 if (startup_pipes[i] != -1)
1196 FD_SET(startup_pipes[i], fdset);
1198 /* Wait in select until there is a connection. */
1199 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1200 if (ret < 0 && errno != EINTR)
1201 error("select: %.100s", strerror(errno));
1202 if (received_sigterm) {
1203 logit("Received signal %d; terminating.",
1204 (int) received_sigterm);
1205 close_listen_socks();
1206 unlink(options.pid_file);
1207 exit(received_sigterm == SIGTERM ? 0 : 255);
1209 if (key_used && key_do_regen) {
1210 generate_ephemeral_server_key();
1217 for (i = 0; i < options.max_startups; i++)
1218 if (startup_pipes[i] != -1 &&
1219 FD_ISSET(startup_pipes[i], fdset)) {
1221 * the read end of the pipe is ready
1222 * if the child has closed the pipe
1223 * after successful authentication
1224 * or if the child has died
1226 close(startup_pipes[i]);
1227 startup_pipes[i] = -1;
1230 for (i = 0; i < num_listen_socks; i++) {
1231 if (!FD_ISSET(listen_socks[i], fdset))
1233 fromlen = sizeof(from);
1234 *newsock = accept(listen_socks[i],
1235 (struct sockaddr *)&from, &fromlen);
1237 if (errno != EINTR && errno != EWOULDBLOCK &&
1238 errno != ECONNABORTED && errno != EAGAIN)
1239 error("accept: %.100s",
1241 if (errno == EMFILE || errno == ENFILE)
1245 if (unset_nonblock(*newsock) == -1) {
1249 if (drop_connection(startups) == 1) {
1250 debug("drop connection #%d", startups);
1254 if (pipe(startup_p) == -1) {
1259 if (rexec_flag && socketpair(AF_UNIX,
1260 SOCK_STREAM, 0, config_s) == -1) {
1261 error("reexec socketpair: %s",
1264 close(startup_p[0]);
1265 close(startup_p[1]);
1269 for (j = 0; j < options.max_startups; j++)
1270 if (startup_pipes[j] == -1) {
1271 startup_pipes[j] = startup_p[0];
1272 if (maxfd < startup_p[0])
1273 maxfd = startup_p[0];
1279 * Got connection. Fork a child to handle it, unless
1280 * we are in debugging mode.
1284 * In debugging mode. Close the listening
1285 * socket, and start processing the
1286 * connection without forking.
1288 debug("Server will not fork when running in debugging mode.");
1289 close_listen_socks();
1290 *sock_in = *newsock;
1291 *sock_out = *newsock;
1292 close(startup_p[0]);
1293 close(startup_p[1]);
1297 send_rexec_state(config_s[0],
1305 * Normal production daemon. Fork, and have
1306 * the child process the connection. The
1307 * parent continues listening.
1309 platform_pre_fork();
1310 if ((pid = fork()) == 0) {
1312 * Child. Close the listening and
1313 * max_startup sockets. Start using
1314 * the accepted socket. Reinitialize
1315 * logging (since our pid has changed).
1316 * We break out of the loop to handle
1319 platform_post_fork_child();
1320 startup_pipe = startup_p[1];
1321 close_startup_pipes();
1322 close_listen_socks();
1323 *sock_in = *newsock;
1324 *sock_out = *newsock;
1325 log_init(__progname,
1327 options.log_facility,
1334 /* Parent. Stay in the loop. */
1335 platform_post_fork_parent(pid);
1337 error("fork: %.100s", strerror(errno));
1339 debug("Forked child %ld.", (long)pid);
1341 close(startup_p[1]);
1344 send_rexec_state(config_s[0], &cfg);
1350 * Mark that the key has been used (it
1351 * was "given" to the child).
1353 if ((options.protocol & SSH_PROTO_1) &&
1355 /* Schedule server key regeneration alarm. */
1356 signal(SIGALRM, key_regeneration_alarm);
1357 alarm(options.key_regeneration_time);
1364 * Ensure that our random state differs
1365 * from that of the child
1370 /* child process check (or debug mode) */
1371 if (num_listen_socks < 0)
1378 * Main program for the daemon.
1381 main(int ac, char **av)
1383 extern char *optarg;
1385 int opt, i, j, on = 1;
1386 int sock_in = -1, sock_out = -1, newsock = -1;
1387 const char *remote_ip;
1389 char *line, *logfile = NULL;
1390 int config_s[2] = { -1 , -1 };
1392 u_int64_t ibytes, obytes;
1398 struct connection_info *connection_info = get_connection_info(0, 0);
1400 #ifdef HAVE_SECUREWARE
1401 (void)set_auth_parameters(ac, av);
1403 __progname = ssh_get_progname(av[0]);
1405 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1408 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1409 for (i = 0; i < ac; i++)
1410 saved_argv[i] = xstrdup(av[i]);
1411 saved_argv[i] = NULL;
1413 #ifndef HAVE_SETPROCTITLE
1414 /* Prepare for later setproctitle emulation */
1415 compat_init_setproctitle(ac, av);
1419 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1420 debug("setgroups(): %.200s", strerror(errno));
1422 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1425 /* Initialize configuration options to their default values. */
1426 initialize_server_options(&options);
1428 /* Parse command-line arguments. */
1429 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeE:iqrtQRT46")) != -1) {
1432 options.address_family = AF_INET;
1435 options.address_family = AF_INET6;
1438 config_file_name = optarg;
1441 if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1442 fprintf(stderr, "too many host certificates.\n");
1445 options.host_cert_files[options.num_host_cert_files++] =
1446 derelativise_path(optarg);
1449 if (debug_flag == 0) {
1451 options.log_level = SYSLOG_LEVEL_DEBUG1;
1452 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1453 options.log_level++;
1459 logfile = xstrdup(optarg);
1478 options.log_level = SYSLOG_LEVEL_QUIET;
1481 options.server_key_bits = (int)strtonum(optarg, 256,
1485 options.ports_from_cmdline = 1;
1486 if (options.num_ports >= MAX_PORTS) {
1487 fprintf(stderr, "too many ports.\n");
1490 options.ports[options.num_ports++] = a2port(optarg);
1491 if (options.ports[options.num_ports-1] <= 0) {
1492 fprintf(stderr, "Bad port number.\n");
1497 if ((options.login_grace_time = convtime(optarg)) == -1) {
1498 fprintf(stderr, "Invalid login grace time.\n");
1503 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1504 fprintf(stderr, "Invalid key regeneration interval.\n");
1509 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1510 fprintf(stderr, "too many host keys.\n");
1513 options.host_key_files[options.num_host_key_files++] =
1514 derelativise_path(optarg);
1523 if (parse_server_match_testspec(connection_info,
1528 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1529 if (utmp_len > MAXHOSTNAMELEN) {
1530 fprintf(stderr, "Invalid utmp length.\n");
1535 line = xstrdup(optarg);
1536 if (process_server_config_line(&options, line,
1537 "command-line", 0, NULL, NULL) != 0)
1547 if (rexeced_flag || inetd_flag)
1549 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1550 fatal("sshd re-exec requires execution with an absolute path");
1552 closefrom(REEXEC_MIN_FREE_FD);
1554 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1556 OpenSSL_add_all_algorithms();
1558 /* If requested, redirect the logs to the specified logfile. */
1559 if (logfile != NULL) {
1560 log_redirect_stderr_to(logfile);
1564 * Force logging to stderr until we have loaded the private host
1565 * key (unless started from inetd)
1567 log_init(__progname,
1568 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1569 SYSLOG_LEVEL_INFO : options.log_level,
1570 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1571 SYSLOG_FACILITY_AUTH : options.log_facility,
1572 log_stderr || !inetd_flag);
1575 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1576 * root's environment
1578 if (getenv("KRB5CCNAME") != NULL)
1579 (void) unsetenv("KRB5CCNAME");
1582 /* Cray can define user privs drop all privs now!
1583 * Not needed on PRIV_SU systems!
1588 sensitive_data.server_key = NULL;
1589 sensitive_data.ssh1_host_key = NULL;
1590 sensitive_data.have_ssh1_key = 0;
1591 sensitive_data.have_ssh2_key = 0;
1594 * If we're doing an extended config test, make sure we have all of
1595 * the parameters we need. If we're not doing an extended test,
1596 * do not silently ignore connection test params.
1598 if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1599 fatal("user, host and addr are all required when testing "
1601 if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1602 fatal("Config test connection parameter (-C) provided without "
1605 /* Fetch our configuration */
1608 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1610 load_server_config(config_file_name, &cfg);
1612 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1617 /* Fill in default values for those options not explicitly set. */
1618 fill_default_server_options(&options);
1620 /* challenge-response is implemented via keyboard interactive */
1621 if (options.challenge_response_authentication)
1622 options.kbd_interactive_authentication = 1;
1624 /* Check that options are sensible */
1625 if (options.authorized_keys_command_user == NULL &&
1626 (options.authorized_keys_command != NULL &&
1627 strcasecmp(options.authorized_keys_command, "none") != 0))
1628 fatal("AuthorizedKeysCommand set without "
1629 "AuthorizedKeysCommandUser");
1632 * Check whether there is any path through configured auth methods.
1633 * Unfortunately it is not possible to verify this generally before
1634 * daemonisation in the presence of Match block, but this catches
1635 * and warns for trivial misconfigurations that could break login.
1637 if (options.num_auth_methods != 0) {
1638 if ((options.protocol & SSH_PROTO_1))
1639 fatal("AuthenticationMethods is not supported with "
1641 for (n = 0; n < options.num_auth_methods; n++) {
1642 if (auth2_methods_valid(options.auth_methods[n],
1646 if (n >= options.num_auth_methods)
1647 fatal("AuthenticationMethods cannot be satisfied by "
1648 "enabled authentication methods");
1651 /* set default channel AF */
1652 channel_set_af(options.address_family);
1654 /* Check that there are no remaining arguments. */
1656 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1660 debug("sshd version %.100s%.100s%s%.100s, %.100s",
1662 options.hpn_disabled ? "" : SSH_VERSION_HPN,
1663 *options.version_addendum == '\0' ? "" : " ",
1664 options.version_addendum,
1665 SSLeay_version(SSLEAY_VERSION));
1667 /* Store privilege separation user for later use if required. */
1668 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1669 if (use_privsep || options.kerberos_authentication)
1670 fatal("Privilege separation user %s does not exist",
1673 memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1674 privsep_pw = pwcopy(privsep_pw);
1675 free(privsep_pw->pw_passwd);
1676 privsep_pw->pw_passwd = xstrdup("*");
1680 /* load host keys */
1681 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1683 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1685 for (i = 0; i < options.num_host_key_files; i++) {
1686 sensitive_data.host_keys[i] = NULL;
1687 sensitive_data.host_pubkeys[i] = NULL;
1690 if (options.host_key_agent) {
1691 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1692 setenv(SSH_AUTHSOCKET_ENV_NAME,
1693 options.host_key_agent, 1);
1694 have_agent = ssh_agent_present();
1697 for (i = 0; i < options.num_host_key_files; i++) {
1698 key = key_load_private(options.host_key_files[i], "", NULL);
1699 pubkey = key_load_public(options.host_key_files[i], NULL);
1700 sensitive_data.host_keys[i] = key;
1701 sensitive_data.host_pubkeys[i] = pubkey;
1703 if (key == NULL && pubkey != NULL && pubkey->type != KEY_RSA1 &&
1705 debug("will rely on agent for hostkey %s",
1706 options.host_key_files[i]);
1707 keytype = pubkey->type;
1708 } else if (key != NULL) {
1709 keytype = key->type;
1711 error("Could not load host key: %s",
1712 options.host_key_files[i]);
1713 sensitive_data.host_keys[i] = NULL;
1714 sensitive_data.host_pubkeys[i] = NULL;
1720 sensitive_data.ssh1_host_key = key;
1721 sensitive_data.have_ssh1_key = 1;
1726 sensitive_data.have_ssh2_key = 1;
1729 debug("private host key: #%d type %d %s", i, keytype,
1730 key_type(key ? key : pubkey));
1732 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1733 logit("Disabling protocol version 1. Could not load host key");
1734 options.protocol &= ~SSH_PROTO_1;
1736 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1737 logit("Disabling protocol version 2. Could not load host key");
1738 options.protocol &= ~SSH_PROTO_2;
1740 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1741 logit("sshd: no hostkeys available -- exiting.");
1746 * Load certificates. They are stored in an array at identical
1747 * indices to the public keys that they relate to.
1749 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1751 for (i = 0; i < options.num_host_key_files; i++)
1752 sensitive_data.host_certificates[i] = NULL;
1754 for (i = 0; i < options.num_host_cert_files; i++) {
1755 key = key_load_public(options.host_cert_files[i], NULL);
1757 error("Could not load host certificate: %s",
1758 options.host_cert_files[i]);
1761 if (!key_is_cert(key)) {
1762 error("Certificate file is not a certificate: %s",
1763 options.host_cert_files[i]);
1767 /* Find matching private key */
1768 for (j = 0; j < options.num_host_key_files; j++) {
1769 if (key_equal_public(key,
1770 sensitive_data.host_keys[j])) {
1771 sensitive_data.host_certificates[j] = key;
1775 if (j >= options.num_host_key_files) {
1776 error("No matching private key for certificate: %s",
1777 options.host_cert_files[i]);
1781 sensitive_data.host_certificates[j] = key;
1782 debug("host certificate: #%d type %d %s", j, key->type,
1785 /* Check certain values for sanity. */
1786 if (options.protocol & SSH_PROTO_1) {
1787 if (options.server_key_bits < 512 ||
1788 options.server_key_bits > 32768) {
1789 fprintf(stderr, "Bad server key size.\n");
1793 * Check that server and host key lengths differ sufficiently. This
1794 * is necessary to make double encryption work with rsaref. Oh, I
1795 * hate software patents. I dont know if this can go? Niels
1797 if (options.server_key_bits >
1798 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1799 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1800 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1801 SSH_KEY_BITS_RESERVED) {
1802 options.server_key_bits =
1803 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1804 SSH_KEY_BITS_RESERVED;
1805 debug("Forcing server key to %d bits to make it differ from host key.",
1806 options.server_key_bits);
1813 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1814 (S_ISDIR(st.st_mode) == 0))
1815 fatal("Missing privilege separation directory: %s",
1816 _PATH_PRIVSEP_CHROOT_DIR);
1819 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1820 (st.st_uid != getuid () ||
1821 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1823 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1825 fatal("%s must be owned by root and not group or "
1826 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1829 if (test_flag > 1) {
1830 if (server_match_spec_complete(connection_info) == 1)
1831 parse_server_match_config(&options, connection_info);
1832 dump_config(&options);
1835 /* Configuration looks good, so exit if in test mode. */
1840 * Clear out any supplemental groups we may have inherited. This
1841 * prevents inadvertent creation of files with bad modes (in the
1842 * portable version at least, it's certainly possible for PAM
1843 * to create a file, and we can't control the code in every
1844 * module which might be used).
1846 if (setgroups(0, NULL) < 0)
1847 debug("setgroups() failed: %.200s", strerror(errno));
1850 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1851 for (i = 0; i < rexec_argc; i++) {
1852 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1853 rexec_argv[i] = saved_argv[i];
1855 rexec_argv[rexec_argc] = "-R";
1856 rexec_argv[rexec_argc + 1] = NULL;
1859 /* Ensure that umask disallows at least group and world write */
1860 new_umask = umask(0077) | 0022;
1861 (void) umask(new_umask);
1863 /* Initialize the log (it is reinitialized below in case we forked). */
1864 if (debug_flag && (!inetd_flag || rexeced_flag))
1866 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1869 * If not in debugging mode, and not started from inetd, disconnect
1870 * from the controlling terminal, and fork. The original process
1873 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1876 #endif /* TIOCNOTTY */
1877 if (daemon(0, 0) < 0)
1878 fatal("daemon() failed: %.200s", strerror(errno));
1880 /* Disconnect from the controlling tty. */
1882 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1884 (void) ioctl(fd, TIOCNOTTY, NULL);
1887 #endif /* TIOCNOTTY */
1889 /* Reinitialize the log (because of the fork above). */
1890 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1892 /* Avoid killing the process in high-pressure swapping environments. */
1893 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
1894 debug("madvise(): %.200s", strerror(errno));
1896 /* Initialize the random number generator. */
1899 /* Chdir to the root directory so that the current disk can be
1900 unmounted if desired. */
1901 if (chdir("/") == -1)
1902 error("chdir(\"/\"): %s", strerror(errno));
1904 /* ignore SIGPIPE */
1905 signal(SIGPIPE, SIG_IGN);
1907 /* Get a connection, either from inetd or a listening TCP socket */
1909 server_accept_inetd(&sock_in, &sock_out);
1911 platform_pre_listen();
1914 if (options.protocol & SSH_PROTO_1)
1915 generate_ephemeral_server_key();
1917 signal(SIGHUP, sighup_handler);
1918 signal(SIGCHLD, main_sigchld_handler);
1919 signal(SIGTERM, sigterm_handler);
1920 signal(SIGQUIT, sigterm_handler);
1923 * Write out the pid file after the sigterm handler
1924 * is setup and the listen sockets are bound
1927 FILE *f = fopen(options.pid_file, "w");
1930 error("Couldn't create pid file \"%s\": %s",
1931 options.pid_file, strerror(errno));
1933 fprintf(f, "%ld\n", (long) getpid());
1938 /* Accept a connection and return in a forked child */
1939 server_accept_loop(&sock_in, &sock_out,
1940 &newsock, config_s);
1943 /* This is the child processing a new connection. */
1944 setproctitle("%s", "[accepted]");
1947 * Create a new session and process group since the 4.4BSD
1948 * setlogin() affects the entire process group. We don't
1949 * want the child to be able to affect the parent.
1951 #if !defined(SSHD_ACQUIRES_CTTY)
1953 * If setsid is called, on some platforms sshd will later acquire a
1954 * controlling terminal which will result in "could not set
1955 * controlling tty" errors.
1957 if (!debug_flag && !inetd_flag && setsid() < 0)
1958 error("setsid: %.100s", strerror(errno));
1964 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1965 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1966 dup2(newsock, STDIN_FILENO);
1967 dup2(STDIN_FILENO, STDOUT_FILENO);
1968 if (startup_pipe == -1)
1969 close(REEXEC_STARTUP_PIPE_FD);
1971 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1973 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1975 if (startup_pipe != -1)
1976 close(startup_pipe);
1978 execv(rexec_argv[0], rexec_argv);
1980 /* Reexec has failed, fall back and continue */
1981 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1982 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1983 log_init(__progname, options.log_level,
1984 options.log_facility, log_stderr);
1987 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1989 close(REEXEC_CONFIG_PASS_FD);
1990 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1991 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1992 dup2(fd, STDIN_FILENO);
1993 dup2(fd, STDOUT_FILENO);
1994 if (fd > STDERR_FILENO)
1997 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1998 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2001 /* Executed child processes don't need these. */
2002 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2003 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2006 * Disable the key regeneration alarm. We will not regenerate the
2007 * key since we are no longer in a position to give it to anyone. We
2008 * will not restart on SIGHUP since it no longer makes sense.
2011 signal(SIGALRM, SIG_DFL);
2012 signal(SIGHUP, SIG_DFL);
2013 signal(SIGTERM, SIG_DFL);
2014 signal(SIGQUIT, SIG_DFL);
2015 signal(SIGCHLD, SIG_DFL);
2016 signal(SIGINT, SIG_DFL);
2020 * Initialize the resolver. This may not happen automatically
2021 * before privsep chroot().
2023 if ((_res.options & RES_INIT) == 0) {
2024 debug("res_init()");
2029 * Force GSS-API to parse its configuration and load any
2030 * mechanism plugins.
2034 OM_uint32 minor_status;
2035 gss_indicate_mechs(&minor_status, &mechs);
2036 gss_release_oid_set(&minor_status, &mechs);
2042 * Register our connection. This turns encryption off because we do
2045 packet_set_connection(sock_in, sock_out);
2046 packet_set_server();
2048 /* Set SO_KEEPALIVE if requested. */
2049 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2050 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2051 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2053 if ((remote_port = get_remote_port()) < 0) {
2054 debug("get_remote_port failed");
2059 * We use get_canonical_hostname with usedns = 0 instead of
2060 * get_remote_ipaddr here so IP options will be checked.
2062 (void) get_canonical_hostname(0);
2064 * The rest of the code depends on the fact that
2065 * get_remote_ipaddr() caches the remote ip, even if
2066 * the socket goes away.
2068 remote_ip = get_remote_ipaddr();
2070 #ifdef SSH_AUDIT_EVENTS
2071 audit_connection_from(remote_ip, remote_port);
2074 allow_severity = options.log_facility|LOG_INFO;
2075 deny_severity = options.log_facility|LOG_WARNING;
2076 /* Check whether logins are denied from this host. */
2077 if (packet_connection_is_on_socket()) {
2078 struct request_info req;
2080 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
2083 if (!hosts_access(&req)) {
2084 debug("Connection refused by tcp wrapper");
2087 fatal("libwrap refuse returns");
2090 #endif /* LIBWRAP */
2092 /* Log the connection. */
2093 verbose("Connection from %.500s port %d", remote_ip, remote_port);
2095 /* Set HPN options for the child. */
2096 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
2099 * We don't want to listen forever unless the other side
2100 * successfully authenticates itself. So we set up an alarm which is
2101 * cleared after successful authentication. A limit of zero
2102 * indicates no limit. Note that we don't set the alarm in debugging
2103 * mode; it is just annoying to have the server exit just when you
2104 * are about to discover the bug.
2106 signal(SIGALRM, grace_alarm_handler);
2108 alarm(options.login_grace_time);
2110 sshd_exchange_identification(sock_in, sock_out);
2112 /* In inetd mode, generate ephemeral key only for proto 1 connections */
2113 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2114 generate_ephemeral_server_key();
2116 packet_set_nonblocking();
2118 /* allocate authentication context */
2119 authctxt = xcalloc(1, sizeof(*authctxt));
2121 authctxt->loginmsg = &loginmsg;
2123 /* XXX global for cleanup, access from other modules */
2124 the_authctxt = authctxt;
2126 /* prepare buffer to collect messages to display to user after login */
2127 buffer_init(&loginmsg);
2131 if (privsep_preauth(authctxt) == 1)
2133 } else if (compat20 && have_agent)
2134 auth_conn = ssh_get_authentication_connection();
2136 /* perform the key exchange */
2137 /* authenticate user and start session */
2140 do_authentication2(authctxt);
2143 do_authentication(authctxt);
2146 * If we use privilege separation, the unprivileged child transfers
2147 * the current keystate and exits
2150 mm_send_keystate(pmonitor);
2156 * Cancel the alarm we set to limit the time taken for
2160 signal(SIGALRM, SIG_DFL);
2161 authctxt->authenticated = 1;
2162 if (startup_pipe != -1) {
2163 close(startup_pipe);
2167 #ifdef SSH_AUDIT_EVENTS
2168 audit_event(SSH_AUTH_SUCCESS);
2172 if (options.gss_authentication) {
2173 temporarily_use_uid(authctxt->pw);
2174 ssh_gssapi_storecreds();
2179 if (options.use_pam) {
2186 * In privilege separation, we fork another child and prepare
2187 * file descriptor passing.
2190 privsep_postauth(authctxt);
2191 /* the monitor process [priv] will not return */
2193 destroy_sensitive_data();
2196 packet_set_timeout(options.client_alive_interval,
2197 options.client_alive_count_max);
2199 /* Start session. */
2200 do_authenticated(authctxt);
2202 /* The connection has been terminated. */
2203 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
2204 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
2205 verbose("Transferred: sent %llu, received %llu bytes",
2206 (unsigned long long)obytes, (unsigned long long)ibytes);
2208 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2211 if (options.use_pam)
2213 #endif /* USE_PAM */
2215 #ifdef SSH_AUDIT_EVENTS
2216 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2228 * Decrypt session_key_int using our private server key and private host key
2229 * (key with larger modulus first).
2232 ssh1_session_key(BIGNUM *session_key_int)
2236 if (BN_cmp(sensitive_data.server_key->rsa->n,
2237 sensitive_data.ssh1_host_key->rsa->n) > 0) {
2238 /* Server key has bigger modulus. */
2239 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2240 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2241 SSH_KEY_BITS_RESERVED) {
2242 fatal("do_connection: %s: "
2243 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2244 get_remote_ipaddr(),
2245 BN_num_bits(sensitive_data.server_key->rsa->n),
2246 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2247 SSH_KEY_BITS_RESERVED);
2249 if (rsa_private_decrypt(session_key_int, session_key_int,
2250 sensitive_data.server_key->rsa) <= 0)
2252 if (rsa_private_decrypt(session_key_int, session_key_int,
2253 sensitive_data.ssh1_host_key->rsa) <= 0)
2256 /* Host key has bigger modulus (or they are equal). */
2257 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2258 BN_num_bits(sensitive_data.server_key->rsa->n) +
2259 SSH_KEY_BITS_RESERVED) {
2260 fatal("do_connection: %s: "
2261 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2262 get_remote_ipaddr(),
2263 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2264 BN_num_bits(sensitive_data.server_key->rsa->n),
2265 SSH_KEY_BITS_RESERVED);
2267 if (rsa_private_decrypt(session_key_int, session_key_int,
2268 sensitive_data.ssh1_host_key->rsa) < 0)
2270 if (rsa_private_decrypt(session_key_int, session_key_int,
2271 sensitive_data.server_key->rsa) < 0)
2284 BIGNUM *session_key_int;
2285 u_char session_key[SSH_SESSION_KEY_LENGTH];
2287 u_int cipher_type, auth_mask, protocol_flags;
2290 * Generate check bytes that the client must send back in the user
2291 * packet in order for it to be accepted; this is used to defy ip
2292 * spoofing attacks. Note that this only works against somebody
2293 * doing IP spoofing from a remote machine; any machine on the local
2294 * network can still see outgoing packets and catch the random
2295 * cookie. This only affects rhosts authentication, and this is one
2296 * of the reasons why it is inherently insecure.
2298 arc4random_buf(cookie, sizeof(cookie));
2301 * Send our public key. We include in the packet 64 bits of random
2302 * data that must be matched in the reply in order to prevent IP
2305 packet_start(SSH_SMSG_PUBLIC_KEY);
2306 for (i = 0; i < 8; i++)
2307 packet_put_char(cookie[i]);
2309 /* Store our public server RSA key. */
2310 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2311 packet_put_bignum(sensitive_data.server_key->rsa->e);
2312 packet_put_bignum(sensitive_data.server_key->rsa->n);
2314 /* Store our public host RSA key. */
2315 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2316 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2317 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2319 /* Put protocol flags. */
2320 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2322 /* Declare which ciphers we support. */
2323 packet_put_int(cipher_mask_ssh1(0));
2325 /* Declare supported authentication types. */
2327 if (options.rhosts_rsa_authentication)
2328 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2329 if (options.rsa_authentication)
2330 auth_mask |= 1 << SSH_AUTH_RSA;
2331 if (options.challenge_response_authentication == 1)
2332 auth_mask |= 1 << SSH_AUTH_TIS;
2333 if (options.password_authentication)
2334 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2335 packet_put_int(auth_mask);
2337 /* Send the packet and wait for it to be sent. */
2339 packet_write_wait();
2341 debug("Sent %d bit server key and %d bit host key.",
2342 BN_num_bits(sensitive_data.server_key->rsa->n),
2343 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2345 /* Read clients reply (cipher type and session key). */
2346 packet_read_expect(SSH_CMSG_SESSION_KEY);
2348 /* Get cipher type and check whether we accept this. */
2349 cipher_type = packet_get_char();
2351 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2352 packet_disconnect("Warning: client selects unsupported cipher.");
2354 /* Get check bytes from the packet. These must match those we
2355 sent earlier with the public key packet. */
2356 for (i = 0; i < 8; i++)
2357 if (cookie[i] != packet_get_char())
2358 packet_disconnect("IP Spoofing check bytes do not match.");
2360 debug("Encryption type: %.200s", cipher_name(cipher_type));
2362 /* Get the encrypted integer. */
2363 if ((session_key_int = BN_new()) == NULL)
2364 fatal("do_ssh1_kex: BN_new failed");
2365 packet_get_bignum(session_key_int);
2367 protocol_flags = packet_get_int();
2368 packet_set_protocol_flags(protocol_flags);
2371 /* Decrypt session_key_int using host/server keys */
2372 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2375 * Extract session key from the decrypted integer. The key is in the
2376 * least significant 256 bits of the integer; the first byte of the
2377 * key is in the highest bits.
2380 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2381 len = BN_num_bytes(session_key_int);
2382 if (len < 0 || (u_int)len > sizeof(session_key)) {
2383 error("do_ssh1_kex: bad session key len from %s: "
2384 "session_key_int %d > sizeof(session_key) %lu",
2385 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2388 memset(session_key, 0, sizeof(session_key));
2389 BN_bn2bin(session_key_int,
2390 session_key + sizeof(session_key) - len);
2392 derive_ssh1_session_id(
2393 sensitive_data.ssh1_host_key->rsa->n,
2394 sensitive_data.server_key->rsa->n,
2395 cookie, session_id);
2397 * Xor the first 16 bytes of the session key with the
2400 for (i = 0; i < 16; i++)
2401 session_key[i] ^= session_id[i];
2405 int bytes = BN_num_bytes(session_key_int);
2406 u_char *buf = xmalloc(bytes);
2409 logit("do_connection: generating a fake encryption key");
2410 BN_bn2bin(session_key_int, buf);
2412 MD5_Update(&md, buf, bytes);
2413 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2414 MD5_Final(session_key, &md);
2416 MD5_Update(&md, session_key, 16);
2417 MD5_Update(&md, buf, bytes);
2418 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2419 MD5_Final(session_key + 16, &md);
2420 memset(buf, 0, bytes);
2422 for (i = 0; i < 16; i++)
2423 session_id[i] = session_key[i] ^ session_key[i + 16];
2425 /* Destroy the private and public keys. No longer. */
2426 destroy_sensitive_data();
2429 mm_ssh1_session_id(session_id);
2431 /* Destroy the decrypted integer. It is no longer needed. */
2432 BN_clear_free(session_key_int);
2434 /* Set the session key. From this on all communications will be encrypted. */
2435 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2437 /* Destroy our copy of the session key. It is no longer needed. */
2438 memset(session_key, 0, sizeof(session_key));
2440 debug("Received session key; encryption turned on.");
2442 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2443 packet_start(SSH_SMSG_SUCCESS);
2445 packet_write_wait();
2449 sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, u_int *slen,
2450 u_char *data, u_int dlen)
2453 if (PRIVSEP(key_sign(privkey, signature, slen, data, dlen) < 0))
2454 fatal("%s: key_sign failed", __func__);
2455 } else if (use_privsep) {
2456 if (mm_key_sign(pubkey, signature, slen, data, dlen) < 0)
2457 fatal("%s: pubkey_sign failed", __func__);
2459 if (ssh_agent_sign(auth_conn, pubkey, signature, slen, data,
2461 fatal("%s: ssh_agent_sign failed", __func__);
2466 * SSH2 key exchange: diffie-hellman-group1-sha1
2473 if (options.ciphers != NULL) {
2474 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2475 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
2476 #ifdef NONE_CIPHER_ENABLED
2477 } else if (options.none_enabled == 1) {
2478 debug ("WARNING: None cipher enabled");
2479 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2480 myproposal[PROPOSAL_ENC_ALGS_STOC] = KEX_ENCRYPT_INCLUDE_NONE;
2483 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2484 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2485 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2486 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2488 if (options.macs != NULL) {
2489 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2490 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2492 if (options.compression == COMP_NONE) {
2493 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2494 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2495 } else if (options.compression == COMP_DELAYED) {
2496 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2497 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2499 if (options.kex_algorithms != NULL)
2500 myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
2502 if (options.rekey_limit || options.rekey_interval)
2503 packet_set_rekey_limits((u_int32_t)options.rekey_limit,
2504 (time_t)options.rekey_interval);
2506 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2508 /* start key exchange */
2509 kex = kex_setup(myproposal);
2510 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2511 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2512 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2513 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2514 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2516 kex->client_version_string=client_version_string;
2517 kex->server_version_string=server_version_string;
2518 kex->load_host_public_key=&get_hostkey_public_by_type;
2519 kex->load_host_private_key=&get_hostkey_private_by_type;
2520 kex->host_key_index=&get_hostkey_index;
2521 kex->sign = sshd_hostkey_sign;
2525 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2527 session_id2 = kex->session_id;
2528 session_id2_len = kex->session_id_len;
2531 /* send 1st encrypted/maced/compressed message */
2532 packet_start(SSH2_MSG_IGNORE);
2533 packet_put_cstring("markus");
2535 packet_write_wait();
2540 /* server specific fatal cleanup */
2545 do_cleanup(the_authctxt);
2546 if (use_privsep && privsep_is_preauth && pmonitor->m_pid > 1) {
2547 debug("Killing privsep child %d", pmonitor->m_pid);
2548 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2550 error("%s: kill(%d): %s", __func__,
2551 pmonitor->m_pid, strerror(errno));
2554 #ifdef SSH_AUDIT_EVENTS
2555 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2556 if (!use_privsep || mm_is_monitor())
2557 audit_event(SSH_CONNECTION_ABANDON);