2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * This program is the ssh daemon. It listens for connections from clients,
6 * and performs authentication, executes use commands or shell, and forwards
7 * information to/from the application to the user client over an encrypted
8 * connection. This can also handle forwarding of X11, TCP/IP, and
9 * authentication agent connections.
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
17 * SSH2 implementation:
19 * Copyright (c) 2000 Markus Friedl. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 RCSID("$OpenBSD: sshd.c,v 1.228 2002/02/27 21:23:13 stevesk Exp $");
45 #include <openssl/dh.h>
46 #include <openssl/bn.h>
47 #include <openssl/md5.h>
66 #include "myproposal.h"
68 #include "pathnames.h"
82 #include <openssl/md5.h>
85 /*end of modification*/
90 int allow_severity = LOG_INFO;
91 int deny_severity = LOG_WARNING;
98 #ifdef HAVE___PROGNAME
99 extern char *__progname;
104 /* Server configuration options. */
105 ServerOptions options;
107 /* Name of the server configuration file. */
108 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
111 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
112 * Default value is AF_UNSPEC means both IPv4 and IPv6.
115 int IPv4or6 = AF_INET;
117 int IPv4or6 = AF_UNSPEC;
121 * Debug mode flag. This can be set on the command line. If debug
122 * mode is enabled, extra debugging output will be sent to the system
123 * log, the daemon will not go to background, and will exit after processing
124 * the first connection.
128 /* Flag indicating that the daemon should only test the configuration and keys. */
131 /* Flag indicating that the daemon is being started from inetd. */
134 /* Flag indicating that sshd should not detach and become a daemon. */
135 int no_daemon_flag = 0;
137 /* debug goes to stderr unless inetd_flag is set */
140 /* Saved arguments to main(). */
145 * The sockets that the server is listening; this is used in the SIGHUP
148 #define MAX_LISTEN_SOCKS 16
149 int listen_socks[MAX_LISTEN_SOCKS];
150 int num_listen_socks = 0;
153 * the client's version string, passed by sshd2 in compat mode. if != NULL,
154 * sshd will skip the version-number exchange
156 char *client_version_string = NULL;
157 char *server_version_string = NULL;
159 /* for rekeying XXX fixme */
163 * Any really sensitive data in the application is contained in this
164 * structure. The idea is that this structure could be locked into memory so
165 * that the pages do not get written into swap. However, there are some
166 * problems. The private key contains BIGNUMs, and we do not (in principle)
167 * have access to the internals of them, and locking just the structure is
168 * not very useful. Currently, memory locking is not implemented.
171 Key *server_key; /* ephemeral server key */
172 Key *ssh1_host_key; /* ssh1 host key */
173 Key **host_keys; /* all private host keys */
176 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
180 * Flag indicating whether the RSA server key needs to be regenerated.
181 * Is set in the SIGALRM handler and cleared when the key is regenerated.
183 static volatile sig_atomic_t key_do_regen = 0;
185 /* This is set to true when a signal is received. */
186 static volatile sig_atomic_t received_sighup = 0;
187 static volatile sig_atomic_t received_sigterm = 0;
189 /* session identifier, used by RSA-auth */
190 u_char session_id[16];
193 u_char *session_id2 = NULL;
194 int session_id2_len = 0;
196 /* record remote hostname or ip */
197 u_int utmp_len = MAXHOSTNAMELEN;
199 /* options.max_startup sized array of fd ints */
200 int *startup_pipes = NULL;
201 int startup_pipe; /* in child */
203 /* Prototypes for various functions defined later in this file. */
204 void destroy_sensitive_data(void);
206 static void do_ssh1_kex(void);
207 static void do_ssh2_kex(void);
210 * Close all listening sockets
213 close_listen_socks(void)
216 for (i = 0; i < num_listen_socks; i++)
217 close(listen_socks[i]);
218 num_listen_socks = -1;
222 close_startup_pipes(void)
226 for (i = 0; i < options.max_startups; i++)
227 if (startup_pipes[i] != -1)
228 close(startup_pipes[i]);
232 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
233 * the effect is to reread the configuration file (and to regenerate
237 sighup_handler(int sig)
239 int save_errno = errno;
242 signal(SIGHUP, sighup_handler);
247 * Called from the main program after receiving SIGHUP.
248 * Restarts the server.
253 log("Received SIGHUP; restarting.");
254 close_listen_socks();
255 close_startup_pipes();
256 execv(saved_argv[0], saved_argv);
257 log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], strerror(errno));
262 * Generic signal handler for terminating signals in the master daemon.
265 sigterm_handler(int sig)
267 received_sigterm = sig;
271 * SIGCHLD handler. This is called whenever a child dies. This will then
272 * reap any zombies left by exited children.
275 main_sigchld_handler(int sig)
277 int save_errno = errno;
280 while (waitpid(-1, &status, WNOHANG) > 0)
283 signal(SIGCHLD, main_sigchld_handler);
288 * Signal handler for the alarm after the login grace period has expired.
291 grace_alarm_handler(int sig)
293 /* XXX no idea how fix this signal handler */
295 /* Close the connection. */
298 /* Log error and exit. */
299 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
303 * Signal handler for the key regeneration alarm. Note that this
304 * alarm only occurs in the daemon waiting for connections, and it does not
305 * do anything with the private key or random state before forking.
306 * Thus there should be no concurrency control/asynchronous execution
310 generate_ephemeral_server_key(void)
315 verbose("Generating %s%d bit RSA key.",
316 sensitive_data.server_key ? "new " : "", options.server_key_bits);
317 if (sensitive_data.server_key != NULL)
318 key_free(sensitive_data.server_key);
319 sensitive_data.server_key = key_generate(KEY_RSA1,
320 options.server_key_bits);
321 verbose("RSA key generation complete.");
323 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
326 sensitive_data.ssh1_cookie[i] = rand & 0xff;
333 key_regeneration_alarm(int sig)
335 int save_errno = errno;
336 signal(SIGALRM, SIG_DFL);
342 sshd_exchange_identification(int sock_in, int sock_out)
345 int remote_major, remote_minor;
348 char buf[256]; /* Must not be larger than remote_version. */
349 char remote_version[256]; /* Must be at least as big as buf. */
351 if ((options.protocol & SSH_PROTO_1) &&
352 (options.protocol & SSH_PROTO_2)) {
353 major = PROTOCOL_MAJOR_1;
355 } else if (options.protocol & SSH_PROTO_2) {
356 major = PROTOCOL_MAJOR_2;
357 minor = PROTOCOL_MINOR_2;
359 major = PROTOCOL_MAJOR_1;
360 minor = PROTOCOL_MINOR_1;
362 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
363 server_version_string = xstrdup(buf);
365 if (client_version_string == NULL) {
366 /* Send our protocol version identification. */
367 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
368 != strlen(server_version_string)) {
369 log("Could not write ident string to %s", get_remote_ipaddr());
373 /* Read other side's version identification. */
374 memset(buf, 0, sizeof(buf));
375 for (i = 0; i < sizeof(buf) - 1; i++) {
376 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
377 log("Did not receive identification string from %s",
378 get_remote_ipaddr());
381 if (buf[i] == '\r') {
383 /* Kludge for F-Secure Macintosh < 1.0.2 */
385 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
389 if (buf[i] == '\n') {
394 buf[sizeof(buf) - 1] = 0;
395 client_version_string = xstrdup(buf);
399 * Check that the versions match. In future this might accept
400 * several versions and set appropriate flags to handle them.
402 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
403 &remote_major, &remote_minor, remote_version) != 3) {
404 s = "Protocol mismatch.\n";
405 (void) atomicio(write, sock_out, s, strlen(s));
408 log("Bad protocol version identification '%.100s' from %s",
409 client_version_string, get_remote_ipaddr());
412 debug("Client protocol version %d.%d; client software version %.100s",
413 remote_major, remote_minor, remote_version);
415 compat_datafellows(remote_version);
417 if (datafellows & SSH_BUG_SCANNER) {
418 log("scanned from %s with %s. Don't panic.",
419 get_remote_ipaddr(), client_version_string);
424 switch (remote_major) {
426 if (remote_minor == 99) {
427 if (options.protocol & SSH_PROTO_2)
433 if (!(options.protocol & SSH_PROTO_1)) {
437 if (remote_minor < 3) {
438 packet_disconnect("Your ssh version is too old and "
439 "is no longer supported. Please install a newer version.");
440 } else if (remote_minor == 3) {
441 /* note that this disables agent-forwarding */
446 if (options.protocol & SSH_PROTO_2) {
455 chop(server_version_string);
456 debug("Local version string %.200s", server_version_string);
459 s = "Protocol major versions differ.\n";
460 (void) atomicio(write, sock_out, s, strlen(s));
463 log("Protocol major versions differ for %s: %.200s vs. %.200s",
465 server_version_string, client_version_string);
471 /* Destroy the host and server keys. They will no longer be needed. */
473 destroy_sensitive_data(void)
477 if (sensitive_data.server_key) {
478 key_free(sensitive_data.server_key);
479 sensitive_data.server_key = NULL;
481 for (i = 0; i < options.num_host_key_files; i++) {
482 if (sensitive_data.host_keys[i]) {
483 key_free(sensitive_data.host_keys[i]);
484 sensitive_data.host_keys[i] = NULL;
487 sensitive_data.ssh1_host_key = NULL;
488 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
492 list_hostkey_types(void)
499 for (i = 0; i < options.num_host_key_files; i++) {
500 Key *key = sensitive_data.host_keys[i];
506 if (buffer_len(&b) > 0)
507 buffer_append(&b, ",", 1);
508 p = key_ssh_name(key);
509 buffer_append(&b, p, strlen(p));
513 buffer_append(&b, "\0", 1);
514 p = xstrdup(buffer_ptr(&b));
516 debug("list_hostkey_types: %s", p);
521 get_hostkey_by_type(int type)
524 for (i = 0; i < options.num_host_key_files; i++) {
525 Key *key = sensitive_data.host_keys[i];
526 if (key != NULL && key->type == type)
533 * returns 1 if connection should be dropped, 0 otherwise.
534 * dropping starts at connection #max_startups_begin with a probability
535 * of (max_startups_rate/100). the probability increases linearly until
536 * all connections are dropped for startups > max_startups
539 drop_connection(int startups)
543 if (startups < options.max_startups_begin)
545 if (startups >= options.max_startups)
547 if (options.max_startups_rate == 100)
550 p = 100 - options.max_startups_rate;
551 p *= startups - options.max_startups_begin;
552 p /= (double) (options.max_startups - options.max_startups_begin);
553 p += options.max_startups_rate;
555 r = arc4random() / (double) UINT_MAX;
557 debug("drop_connection: p %g, r %g", p, r);
558 return (r < p) ? 1 : 0;
564 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
565 fprintf(stderr, "Usage: %s [options]\n", __progname);
566 fprintf(stderr, "Options:\n");
567 fprintf(stderr, " -f file Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
568 fprintf(stderr, " -d Debugging mode (multiple -d means more debugging)\n");
569 fprintf(stderr, " -i Started from inetd\n");
570 fprintf(stderr, " -D Do not fork into daemon mode\n");
571 fprintf(stderr, " -t Only test configuration file and keys\n");
572 fprintf(stderr, " -q Quiet (no logging)\n");
573 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
574 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
575 fprintf(stderr, " -g seconds Grace period for authentication (default: 600)\n");
576 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
577 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
578 _PATH_HOST_KEY_FILE);
579 fprintf(stderr, " -u len Maximum hostname length for utmp recording\n");
580 fprintf(stderr, " -4 Use IPv4 only\n");
581 fprintf(stderr, " -6 Use IPv6 only\n");
582 fprintf(stderr, " -o option Process the option as if it was read from a configuration file.\n");
587 * Main program for the daemon.
590 main(int ac, char **av)
594 int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
598 struct sockaddr_storage from;
599 const char *remote_ip;
602 struct linger linger;
604 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
605 int listen_sock, maxfd;
609 int ret, key_used = 0;
611 __progname = get_progname(av[0]);
618 /* Initialize configuration options to their default values. */
619 initialize_server_options(&options);
621 /* Parse command-line arguments. */
622 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
631 config_file_name = optarg;
634 if (0 == debug_flag) {
636 options.log_level = SYSLOG_LEVEL_DEBUG1;
637 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
640 fprintf(stderr, "Too high debugging level.\n");
657 options.log_level = SYSLOG_LEVEL_QUIET;
660 options.server_key_bits = atoi(optarg);
663 options.ports_from_cmdline = 1;
664 if (options.num_ports >= MAX_PORTS) {
665 fprintf(stderr, "too many ports.\n");
668 options.ports[options.num_ports++] = a2port(optarg);
669 if (options.ports[options.num_ports-1] == 0) {
670 fprintf(stderr, "Bad port number.\n");
675 if ((options.login_grace_time = convtime(optarg)) == -1) {
676 fprintf(stderr, "Invalid login grace time.\n");
681 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
682 fprintf(stderr, "Invalid key regeneration interval.\n");
687 if (options.num_host_key_files >= MAX_HOSTKEYS) {
688 fprintf(stderr, "too many host keys.\n");
691 options.host_key_files[options.num_host_key_files++] = optarg;
694 client_version_string = optarg;
695 /* only makes sense with inetd_flag, i.e. no listen() */
702 utmp_len = atoi(optarg);
705 if (process_server_config_line(&options, optarg,
706 "command-line", 0) != 0)
715 SSLeay_add_all_algorithms();
716 channel_set_af(IPv4or6);
719 * Force logging to stderr until we have loaded the private host
720 * key (unless started from inetd)
723 options.log_level == SYSLOG_LEVEL_NOT_SET ?
724 SYSLOG_LEVEL_INFO : options.log_level,
725 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
726 SYSLOG_FACILITY_AUTH : options.log_facility,
730 /* Cray can define user privs drop all prives now!
731 * Not needed on PRIV_SU systems!
738 /* Read server configuration options from the configuration file. */
739 read_server_config(&options, config_file_name);
741 /* Fill in default values for those options not explicitly set. */
742 fill_default_server_options(&options);
744 /* Check that there are no remaining arguments. */
746 fprintf(stderr, "Extra argument %s.\n", av[optind]);
750 debug("sshd version %.100s", SSH_VERSION);
752 /* load private host keys */
753 sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*));
754 for (i = 0; i < options.num_host_key_files; i++)
755 sensitive_data.host_keys[i] = NULL;
756 sensitive_data.server_key = NULL;
757 sensitive_data.ssh1_host_key = NULL;
758 sensitive_data.have_ssh1_key = 0;
759 sensitive_data.have_ssh2_key = 0;
761 for (i = 0; i < options.num_host_key_files; i++) {
762 key = key_load_private(options.host_key_files[i], "", NULL);
763 sensitive_data.host_keys[i] = key;
765 error("Could not load host key: %s",
766 options.host_key_files[i]);
767 sensitive_data.host_keys[i] = NULL;
772 sensitive_data.ssh1_host_key = key;
773 sensitive_data.have_ssh1_key = 1;
777 sensitive_data.have_ssh2_key = 1;
780 debug("private host key: #%d type %d %s", i, key->type,
783 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
784 log("Disabling protocol version 1. Could not load host key");
785 options.protocol &= ~SSH_PROTO_1;
788 /* The GSSAPI key exchange can run without a host key */
789 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
790 log("Disabling protocol version 2. Could not load host key");
791 options.protocol &= ~SSH_PROTO_2;
794 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
795 log("sshd: no hostkeys available -- exiting.");
799 /* Check certain values for sanity. */
800 if (options.protocol & SSH_PROTO_1) {
801 if (options.server_key_bits < 512 ||
802 options.server_key_bits > 32768) {
803 fprintf(stderr, "Bad server key size.\n");
807 * Check that server and host key lengths differ sufficiently. This
808 * is necessary to make double encryption work with rsaref. Oh, I
809 * hate software patents. I dont know if this can go? Niels
811 if (options.server_key_bits >
812 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - SSH_KEY_BITS_RESERVED &&
813 options.server_key_bits <
814 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
815 options.server_key_bits =
816 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED;
817 debug("Forcing server key to %d bits to make it differ from host key.",
818 options.server_key_bits);
822 /* Configuration looks good, so exit if in test mode. */
826 /*modified by binhe*/
830 /*end of modification*/
832 #ifdef HAVE_SCO_PROTECTED_PW
833 (void) set_auth_parameters(ac, av);
836 /* Initialize the log (it is reinitialized below in case we forked). */
837 if (debug_flag && !inetd_flag)
839 log_init(__progname, options.log_level, options.log_facility, log_stderr);
842 * If not in debugging mode, and not started from inetd, disconnect
843 * from the controlling terminal, and fork. The original process
846 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
849 #endif /* TIOCNOTTY */
850 if (daemon(0, 0) < 0)
851 fatal("daemon() failed: %.200s", strerror(errno));
853 /* Disconnect from the controlling tty. */
855 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
857 (void) ioctl(fd, TIOCNOTTY, NULL);
860 #endif /* TIOCNOTTY */
862 /* Reinitialize the log (because of the fork above). */
863 log_init(__progname, options.log_level, options.log_facility, log_stderr);
865 /* Initialize the random number generator. */
868 /* Chdir to the root directory so that the current disk can be
869 unmounted if desired. */
873 signal(SIGPIPE, SIG_IGN);
875 /* Start listening for a socket, unless started from inetd. */
878 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
884 * We intentionally do not close the descriptors 0, 1, and 2
885 * as our code for setting the descriptors won\'t work if
886 * ttyfd happens to be one of those.
888 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
889 if (options.protocol & SSH_PROTO_1)
890 generate_ephemeral_server_key();
892 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
893 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
895 if (num_listen_socks >= MAX_LISTEN_SOCKS)
896 fatal("Too many listen sockets. "
897 "Enlarge MAX_LISTEN_SOCKS");
898 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
899 ntop, sizeof(ntop), strport, sizeof(strport),
900 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
901 error("getnameinfo failed");
904 /* Create socket for listening. */
905 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
906 if (listen_sock < 0) {
907 /* kernel may not support ipv6 */
908 verbose("socket: %.100s", strerror(errno));
911 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
912 error("listen_sock O_NONBLOCK: %s", strerror(errno));
917 * Set socket options. We try to make the port
918 * reusable and have it close as fast as possible
919 * without waiting in unnecessary wait states on
922 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
926 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
927 &linger, sizeof(linger));
929 debug("Bind to port %s on %s.", strport, ntop);
931 /* Bind the socket to the desired port. */
932 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
934 error("Bind to port %s on %s failed: %.200s.",
935 strport, ntop, strerror(errno));
939 listen_socks[num_listen_socks] = listen_sock;
942 /* Start listening on the port. */
943 log("Server listening on %s port %s.", ntop, strport);
944 if (listen(listen_sock, 5) < 0)
945 fatal("listen: %.100s", strerror(errno));
948 freeaddrinfo(options.listen_addrs);
950 if (!num_listen_socks)
951 fatal("Cannot bind any address.");
953 if (options.protocol & SSH_PROTO_1)
954 generate_ephemeral_server_key();
957 * Arrange to restart on SIGHUP. The handler needs
960 signal(SIGHUP, sighup_handler);
962 signal(SIGTERM, sigterm_handler);
963 signal(SIGQUIT, sigterm_handler);
965 /* Arrange SIGCHLD to be caught. */
966 signal(SIGCHLD, main_sigchld_handler);
968 /* Write out the pid file after the sigterm handler is setup */
971 * Record our pid in /var/run/sshd.pid to make it
972 * easier to kill the correct sshd. We don't want to
973 * do this before the bind above because the bind will
974 * fail if there already is a daemon, and this will
975 * overwrite any old pid in the file.
977 f = fopen(options.pid_file, "wb");
979 fprintf(f, "%u\n", (u_int) getpid());
984 /* setup fd set for listen */
987 for (i = 0; i < num_listen_socks; i++)
988 if (listen_socks[i] > maxfd)
989 maxfd = listen_socks[i];
990 /* pipes connected to unauthenticated childs */
991 startup_pipes = xmalloc(options.max_startups * sizeof(int));
992 for (i = 0; i < options.max_startups; i++)
993 startup_pipes[i] = -1;
996 * Stay listening for connections until the system crashes or
997 * the daemon is killed with a signal.
1000 if (received_sighup)
1004 fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1005 fdset = (fd_set *)xmalloc(fdsetsz);
1006 memset(fdset, 0, fdsetsz);
1008 for (i = 0; i < num_listen_socks; i++)
1009 FD_SET(listen_socks[i], fdset);
1010 for (i = 0; i < options.max_startups; i++)
1011 if (startup_pipes[i] != -1)
1012 FD_SET(startup_pipes[i], fdset);
1014 /* Wait in select until there is a connection. */
1015 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1016 if (ret < 0 && errno != EINTR)
1017 error("select: %.100s", strerror(errno));
1018 if (received_sigterm) {
1019 log("Received signal %d; terminating.",
1020 (int) received_sigterm);
1021 close_listen_socks();
1022 unlink(options.pid_file);
1025 if (key_used && key_do_regen) {
1026 generate_ephemeral_server_key();
1033 for (i = 0; i < options.max_startups; i++)
1034 if (startup_pipes[i] != -1 &&
1035 FD_ISSET(startup_pipes[i], fdset)) {
1037 * the read end of the pipe is ready
1038 * if the child has closed the pipe
1039 * after successful authentication
1040 * or if the child has died
1042 close(startup_pipes[i]);
1043 startup_pipes[i] = -1;
1046 for (i = 0; i < num_listen_socks; i++) {
1047 if (!FD_ISSET(listen_socks[i], fdset))
1049 fromlen = sizeof(from);
1050 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
1053 if (errno != EINTR && errno != EWOULDBLOCK)
1054 error("accept: %.100s", strerror(errno));
1057 if (fcntl(newsock, F_SETFL, 0) < 0) {
1058 error("newsock del O_NONBLOCK: %s", strerror(errno));
1062 if (drop_connection(startups) == 1) {
1063 debug("drop connection #%d", startups);
1067 if (pipe(startup_p) == -1) {
1072 for (j = 0; j < options.max_startups; j++)
1073 if (startup_pipes[j] == -1) {
1074 startup_pipes[j] = startup_p[0];
1075 if (maxfd < startup_p[0])
1076 maxfd = startup_p[0];
1082 * Got connection. Fork a child to handle it, unless
1083 * we are in debugging mode.
1087 * In debugging mode. Close the listening
1088 * socket, and start processing the
1089 * connection without forking.
1091 debug("Server will not fork when running in debugging mode.");
1092 close_listen_socks();
1100 * Normal production daemon. Fork, and have
1101 * the child process the connection. The
1102 * parent continues listening.
1104 if ((pid = fork()) == 0) {
1106 * Child. Close the listening and max_startup
1107 * sockets. Start using the accepted socket.
1108 * Reinitialize logging (since our pid has
1109 * changed). We break out of the loop to handle
1112 startup_pipe = startup_p[1];
1113 close_startup_pipes();
1114 close_listen_socks();
1117 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1122 /* Parent. Stay in the loop. */
1124 error("fork: %.100s", strerror(errno));
1126 debug("Forked child %d.", pid);
1128 close(startup_p[1]);
1130 /* Mark that the key has been used (it was "given" to the child). */
1131 if ((options.protocol & SSH_PROTO_1) &&
1133 /* Schedule server key regeneration alarm. */
1134 signal(SIGALRM, key_regeneration_alarm);
1135 alarm(options.key_regeneration_time);
1141 /* Close the new socket (the child is now taking care of it). */
1144 /* child process check (or debug mode) */
1145 if (num_listen_socks < 0)
1150 /* This is the child processing a new connection. */
1153 * Disable the key regeneration alarm. We will not regenerate the
1154 * key since we are no longer in a position to give it to anyone. We
1155 * will not restart on SIGHUP since it no longer makes sense.
1158 signal(SIGALRM, SIG_DFL);
1159 signal(SIGHUP, SIG_DFL);
1160 signal(SIGTERM, SIG_DFL);
1161 signal(SIGQUIT, SIG_DFL);
1162 signal(SIGCHLD, SIG_DFL);
1163 signal(SIGINT, SIG_DFL);
1166 * Set socket options for the connection. We want the socket to
1167 * close as fast as possible without waiting for anything. If the
1168 * connection is not a socket, these will do nothing.
1170 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1172 linger.l_linger = 5;
1173 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
1175 /* Set keepalives if requested. */
1176 if (options.keepalives &&
1177 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
1179 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1182 * Register our connection. This turns encryption off because we do
1185 packet_set_connection(sock_in, sock_out);
1187 remote_port = get_remote_port();
1188 remote_ip = get_remote_ipaddr();
1191 /* Check whether logins are denied from this host. */
1193 struct request_info req;
1195 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1198 if (!hosts_access(&req)) {
1199 debug("Connection refused by tcp wrapper");
1202 fatal("libwrap refuse returns");
1205 #endif /* LIBWRAP */
1207 /* Log the connection. */
1208 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1211 * We don\'t want to listen forever unless the other side
1212 * successfully authenticates itself. So we set up an alarm which is
1213 * cleared after successful authentication. A limit of zero
1214 * indicates no limit. Note that we don\'t set the alarm in debugging
1215 * mode; it is just annoying to have the server exit just when you
1216 * are about to discover the bug.
1218 signal(SIGALRM, grace_alarm_handler);
1220 alarm(options.login_grace_time);
1222 sshd_exchange_identification(sock_in, sock_out);
1224 * Check that the connection comes from a privileged port.
1225 * Rhosts-Authentication only makes sense from priviledged
1226 * programs. Of course, if the intruder has root access on his local
1227 * machine, he can connect from any port. So do not use these
1228 * authentication methods from machines that you do not trust.
1230 if (options.rhosts_authentication &&
1231 (remote_port >= IPPORT_RESERVED ||
1232 remote_port < IPPORT_RESERVED / 2)) {
1233 debug("Rhosts Authentication disabled, "
1234 "originating port %d not trusted.", remote_port);
1235 options.rhosts_authentication = 0;
1237 #if defined(KRB4) && !defined(KRB5)
1238 if (!packet_connection_is_ipv4() &&
1239 options.kerberos_authentication) {
1240 debug("Kerberos Authentication disabled, only available for IPv4.");
1241 options.kerberos_authentication = 0;
1243 #endif /* KRB4 && !KRB5 */
1245 /* If machine has AFS, set process authentication group. */
1252 packet_set_nonblocking();
1254 /* perform the key exchange */
1255 /* authenticate user and start session */
1258 do_authentication2();
1261 do_authentication();
1263 /* The connection has been terminated. */
1264 verbose("Closing connection to %.100s", remote_ip);
1268 #endif /* USE_PAM */
1282 BIGNUM *session_key_int;
1283 u_char session_key[SSH_SESSION_KEY_LENGTH];
1285 u_int cipher_type, auth_mask, protocol_flags;
1289 * Generate check bytes that the client must send back in the user
1290 * packet in order for it to be accepted; this is used to defy ip
1291 * spoofing attacks. Note that this only works against somebody
1292 * doing IP spoofing from a remote machine; any machine on the local
1293 * network can still see outgoing packets and catch the random
1294 * cookie. This only affects rhosts authentication, and this is one
1295 * of the reasons why it is inherently insecure.
1297 for (i = 0; i < 8; i++) {
1299 rand = arc4random();
1300 cookie[i] = rand & 0xff;
1305 * Send our public key. We include in the packet 64 bits of random
1306 * data that must be matched in the reply in order to prevent IP
1309 packet_start(SSH_SMSG_PUBLIC_KEY);
1310 for (i = 0; i < 8; i++)
1311 packet_put_char(cookie[i]);
1313 /* Store our public server RSA key. */
1314 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1315 packet_put_bignum(sensitive_data.server_key->rsa->e);
1316 packet_put_bignum(sensitive_data.server_key->rsa->n);
1318 /* Store our public host RSA key. */
1319 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1320 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1321 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1323 /* Put protocol flags. */
1324 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1326 /* Declare which ciphers we support. */
1327 packet_put_int(cipher_mask_ssh1(0));
1329 /* Declare supported authentication types. */
1331 if (options.rhosts_authentication)
1332 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1333 if (options.rhosts_rsa_authentication)
1334 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1335 if (options.rsa_authentication)
1336 auth_mask |= 1 << SSH_AUTH_RSA;
1337 #if defined(KRB4) || defined(KRB5)
1338 if (options.kerberos_authentication)
1339 auth_mask |= 1 << SSH_AUTH_KERBEROS;
1341 #if defined(AFS) || defined(KRB5)
1342 if (options.kerberos_tgt_passing)
1343 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1346 if (options.afs_token_passing)
1347 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1349 if (options.challenge_response_authentication == 1)
1350 auth_mask |= 1 << SSH_AUTH_TIS;
1352 /*modified by binhe*/
1354 if (options.gss_authentication)
1355 auth_mask |= 1 << SSH_AUTH_GSSAPI;
1357 /*end of modification*/
1359 if (options.password_authentication)
1360 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1361 packet_put_int(auth_mask);
1363 /* Send the packet and wait for it to be sent. */
1365 packet_write_wait();
1367 debug("Sent %d bit server key and %d bit host key.",
1368 BN_num_bits(sensitive_data.server_key->rsa->n),
1369 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1371 /* Read clients reply (cipher type and session key). */
1372 packet_read_expect(SSH_CMSG_SESSION_KEY);
1374 /* Get cipher type and check whether we accept this. */
1375 cipher_type = packet_get_char();
1377 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1378 packet_disconnect("Warning: client selects unsupported cipher.");
1380 /* Get check bytes from the packet. These must match those we
1381 sent earlier with the public key packet. */
1382 for (i = 0; i < 8; i++)
1383 if (cookie[i] != packet_get_char())
1384 packet_disconnect("IP Spoofing check bytes do not match.");
1386 debug("Encryption type: %.200s", cipher_name(cipher_type));
1388 /* Get the encrypted integer. */
1389 if ((session_key_int = BN_new()) == NULL)
1390 fatal("do_ssh1_kex: BN_new failed");
1391 packet_get_bignum(session_key_int);
1393 protocol_flags = packet_get_int();
1394 packet_set_protocol_flags(protocol_flags);
1398 * Decrypt it using our private server key and private host key (key
1399 * with larger modulus first).
1401 if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1402 /* Server key has bigger modulus. */
1403 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1404 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1405 fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1406 get_remote_ipaddr(),
1407 BN_num_bits(sensitive_data.server_key->rsa->n),
1408 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1409 SSH_KEY_BITS_RESERVED);
1411 if (rsa_private_decrypt(session_key_int, session_key_int,
1412 sensitive_data.server_key->rsa) <= 0)
1414 if (rsa_private_decrypt(session_key_int, session_key_int,
1415 sensitive_data.ssh1_host_key->rsa) <= 0)
1418 /* Host key has bigger modulus (or they are equal). */
1419 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1420 BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1421 fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1422 get_remote_ipaddr(),
1423 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1424 BN_num_bits(sensitive_data.server_key->rsa->n),
1425 SSH_KEY_BITS_RESERVED);
1427 if (rsa_private_decrypt(session_key_int, session_key_int,
1428 sensitive_data.ssh1_host_key->rsa) < 0)
1430 if (rsa_private_decrypt(session_key_int, session_key_int,
1431 sensitive_data.server_key->rsa) < 0)
1435 * Extract session key from the decrypted integer. The key is in the
1436 * least significant 256 bits of the integer; the first byte of the
1437 * key is in the highest bits.
1440 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1441 len = BN_num_bytes(session_key_int);
1442 if (len < 0 || len > sizeof(session_key)) {
1443 error("do_connection: bad session key len from %s: "
1444 "session_key_int %d > sizeof(session_key) %lu",
1445 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1448 memset(session_key, 0, sizeof(session_key));
1449 BN_bn2bin(session_key_int,
1450 session_key + sizeof(session_key) - len);
1452 compute_session_id(session_id, cookie,
1453 sensitive_data.ssh1_host_key->rsa->n,
1454 sensitive_data.server_key->rsa->n);
1456 * Xor the first 16 bytes of the session key with the
1459 for (i = 0; i < 16; i++)
1460 session_key[i] ^= session_id[i];
1464 int bytes = BN_num_bytes(session_key_int);
1465 u_char *buf = xmalloc(bytes);
1468 log("do_connection: generating a fake encryption key");
1469 BN_bn2bin(session_key_int, buf);
1471 MD5_Update(&md, buf, bytes);
1472 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1473 MD5_Final(session_key, &md);
1475 MD5_Update(&md, session_key, 16);
1476 MD5_Update(&md, buf, bytes);
1477 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1478 MD5_Final(session_key + 16, &md);
1479 memset(buf, 0, bytes);
1481 for (i = 0; i < 16; i++)
1482 session_id[i] = session_key[i] ^ session_key[i + 16];
1485 /*modified by binhe*/
1488 * Before we destroy the host and server keys, hash them so we can
1489 * send the hash over to the client via a secure channel so that it
1495 unsigned char *data;
1496 unsigned int data_len;
1497 extern unsigned char ssh1_key_digest[]; /* in gss-serv.c */
1500 debug("Calculating MD5 hash of server and host keys...");
1502 /* Write all the keys to a temporary buffer */
1506 buffer_put_bignum(&buf, sensitive_data.server_key->rsa->e);
1507 buffer_put_bignum(&buf, sensitive_data.server_key->rsa->n);
1510 buffer_put_bignum(&buf, sensitive_data.ssh1_host_key->rsa->e);
1511 buffer_put_bignum(&buf, sensitive_data.ssh1_host_key->rsa->n);
1513 /* Get the resulting data */
1514 data = (unsigned char *) buffer_ptr(&buf);
1515 data_len = buffer_len(&buf);
1518 MD5_Init(&md5context);
1519 MD5_Update(&md5context, data, data_len);
1520 MD5_Final(ssh1_key_digest, &md5context);
1527 /*end of modification*/
1529 /* Destroy the private and public keys. They will no longer be needed. */
1530 destroy_sensitive_data();
1532 /* Destroy the decrypted integer. It is no longer needed. */
1533 BN_clear_free(session_key_int);
1535 /* Set the session key. From this on all communications will be encrypted. */
1536 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1538 /* Destroy our copy of the session key. It is no longer needed. */
1539 memset(session_key, 0, sizeof(session_key));
1541 debug("Received session key; encryption turned on.");
1543 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1544 packet_start(SSH_SMSG_SUCCESS);
1546 packet_write_wait();
1550 * SSH2 key exchange: diffie-hellman-group1-sha1
1557 if (options.ciphers != NULL) {
1558 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1559 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1561 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1562 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1563 myproposal[PROPOSAL_ENC_ALGS_STOC] =
1564 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1566 if (options.macs != NULL) {
1567 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1568 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1570 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1576 char *newstr = NULL;
1577 orig = myproposal[PROPOSAL_KEX_ALGS];
1579 /* If we don't have a host key, then all of the algorithms
1580 * currently in myproposal are useless */
1581 if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])==0)
1584 if (options.gss_keyex)
1585 gss = ssh_gssapi_mechanisms(1,NULL);
1590 int len = strlen(orig) + strlen(gss) +2;
1591 newstr=xmalloc(len);
1592 snprintf(newstr,len,"%s,%s",gss,orig);
1598 /* If we've got GSSAPI mechanisms, then we've also got the 'null'
1599 host key algorithm, but we're not allowed to advertise it, unless
1600 its the only host key algorithm we're supporting */
1601 if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0) {
1602 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]="null";
1605 myproposal[PROPOSAL_KEX_ALGS]=newstr;
1607 fatal("No supported key exchange algorithms");
1611 /* start key exchange */
1612 kex = kex_setup(myproposal);
1614 kex->client_version_string=client_version_string;
1615 kex->server_version_string=server_version_string;
1616 kex->load_host_key=&get_hostkey_by_type;
1620 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1622 session_id2 = kex->session_id;
1623 session_id2_len = kex->session_id_len;
1626 /* send 1st encrypted/maced/compressed message */
1627 packet_start(SSH2_MSG_IGNORE);
1628 packet_put_cstring("markus");
1630 packet_write_wait();