Annotation of src/usr.bin/ssh/sshd.c, Revision 1.221
1.86 markus 1: /*
1.65 deraadt 2: * Author: Tatu Ylonen <ylo@cs.hut.fi>
3: * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4: * All rights reserved
1.126 deraadt 5: * This program is the ssh daemon. It listens for connections from clients,
6: * and performs authentication, executes use commands or shell, and forwards
1.65 deraadt 7: * information to/from the application to the user client over an encrypted
1.126 deraadt 8: * connection. This can also handle forwarding of X11, TCP/IP, and
9: * authentication agent connections.
1.98 markus 10: *
1.126 deraadt 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".
16: *
17: * SSH2 implementation:
18: *
19: * Copyright (c) 2000 Markus Friedl. All rights reserved.
20: *
21: * Redistribution and use in source and binary forms, with or without
22: * modification, are permitted provided that the following conditions
23: * are met:
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.
29: *
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.
1.65 deraadt 40: */
1.1 deraadt 41:
42: #include "includes.h"
1.221 ! markus 43: RCSID("$OpenBSD: sshd.c,v 1.220 2001/12/28 12:14:27 markus Exp $");
1.1 deraadt 44:
1.155 markus 45: #include <openssl/dh.h>
46: #include <openssl/bn.h>
47: #include <openssl/hmac.h>
48:
49: #include "ssh.h"
50: #include "ssh1.h"
51: #include "ssh2.h"
1.1 deraadt 52: #include "xmalloc.h"
53: #include "rsa.h"
1.171 djm 54: #include "sshpty.h"
1.1 deraadt 55: #include "packet.h"
56: #include "mpaux.h"
1.155 markus 57: #include "log.h"
1.1 deraadt 58: #include "servconf.h"
59: #include "uidswap.h"
1.33 markus 60: #include "compat.h"
1.96 markus 61: #include "buffer.h"
1.155 markus 62: #include "cipher.h"
1.98 markus 63: #include "kex.h"
1.96 markus 64: #include "key.h"
1.129 provos 65: #include "dh.h"
1.98 markus 66: #include "myproposal.h"
1.108 markus 67: #include "authfile.h"
1.154 markus 68: #include "pathnames.h"
1.155 markus 69: #include "atomicio.h"
70: #include "canohost.h"
71: #include "auth.h"
72: #include "misc.h"
1.186 markus 73: #include "dispatch.h"
1.206 stevesk 74: #include "channels.h"
1.1 deraadt 75:
76: #ifdef LIBWRAP
77: #include <tcpd.h>
78: #include <syslog.h>
79: int allow_severity = LOG_INFO;
80: int deny_severity = LOG_WARNING;
81: #endif /* LIBWRAP */
82:
83: #ifndef O_NOCTTY
84: #define O_NOCTTY 0
85: #endif
86:
1.138 markus 87: extern char *__progname;
88:
1.1 deraadt 89: /* Server configuration options. */
90: ServerOptions options;
91:
92: /* Name of the server configuration file. */
1.154 markus 93: char *config_file_name = _PATH_SERVER_CONFIG_FILE;
1.1 deraadt 94:
1.105 markus 95: /*
1.75 markus 96: * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
97: * Default value is AF_UNSPEC means both IPv4 and IPv6.
98: */
99: int IPv4or6 = AF_UNSPEC;
100:
1.65 deraadt 101: /*
102: * Debug mode flag. This can be set on the command line. If debug
103: * mode is enabled, extra debugging output will be sent to the system
104: * log, the daemon will not go to background, and will exit after processing
105: * the first connection.
106: */
1.1 deraadt 107: int debug_flag = 0;
108:
1.203 stevesk 109: /* Flag indicating that the daemon should only test the configuration and keys. */
110: int test_flag = 0;
111:
1.1 deraadt 112: /* Flag indicating that the daemon is being started from inetd. */
113: int inetd_flag = 0;
114:
1.135 markus 115: /* Flag indicating that sshd should not detach and become a daemon. */
116: int no_daemon_flag = 0;
117:
1.47 markus 118: /* debug goes to stderr unless inetd_flag is set */
119: int log_stderr = 0;
120:
1.1 deraadt 121: /* Saved arguments to main(). */
122: char **saved_argv;
123:
1.66 markus 124: /*
1.75 markus 125: * The sockets that the server is listening; this is used in the SIGHUP
126: * signal handler.
1.66 markus 127: */
1.75 markus 128: #define MAX_LISTEN_SOCKS 16
129: int listen_socks[MAX_LISTEN_SOCKS];
130: int num_listen_socks = 0;
1.1 deraadt 131:
1.66 markus 132: /*
133: * the client's version string, passed by sshd2 in compat mode. if != NULL,
134: * sshd will skip the version-number exchange
135: */
1.61 markus 136: char *client_version_string = NULL;
1.96 markus 137: char *server_version_string = NULL;
1.1 deraadt 138:
1.189 markus 139: /* for rekeying XXX fixme */
140: Kex *xxx_kex;
141:
1.66 markus 142: /*
143: * Any really sensitive data in the application is contained in this
144: * structure. The idea is that this structure could be locked into memory so
145: * that the pages do not get written into swap. However, there are some
146: * problems. The private key contains BIGNUMs, and we do not (in principle)
147: * have access to the internals of them, and locking just the structure is
148: * not very useful. Currently, memory locking is not implemented.
149: */
1.64 markus 150: struct {
1.174 deraadt 151: Key *server_key; /* ephemeral server key */
1.134 markus 152: Key *ssh1_host_key; /* ssh1 host key */
153: Key **host_keys; /* all private host keys */
154: int have_ssh1_key;
155: int have_ssh2_key;
1.169 markus 156: u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
1.1 deraadt 157: } sensitive_data;
158:
1.66 markus 159: /*
1.151 markus 160: * Flag indicating whether the RSA server key needs to be regenerated.
161: * Is set in the SIGALRM handler and cleared when the key is regenerated.
1.66 markus 162: */
1.212 markus 163: static volatile sig_atomic_t key_do_regen = 0;
1.1 deraadt 164:
1.199 markus 165: /* This is set to true when a signal is received. */
1.212 markus 166: static volatile sig_atomic_t received_sighup = 0;
167: static volatile sig_atomic_t received_sigterm = 0;
1.1 deraadt 168:
1.96 markus 169: /* session identifier, used by RSA-auth */
1.140 markus 170: u_char session_id[16];
1.96 markus 171:
1.108 markus 172: /* same for ssh2 */
1.140 markus 173: u_char *session_id2 = NULL;
1.108 markus 174: int session_id2_len = 0;
175:
1.125 markus 176: /* record remote hostname or ip */
1.140 markus 177: u_int utmp_len = MAXHOSTNAMELEN;
1.125 markus 178:
1.211 markus 179: /* options.max_startup sized array of fd ints */
180: int *startup_pipes = NULL;
181: int startup_pipe; /* in child */
182:
1.1 deraadt 183: /* Prototypes for various functions defined later in this file. */
1.200 itojun 184: void destroy_sensitive_data(void);
1.87 markus 185:
1.200 itojun 186: static void do_ssh1_kex(void);
187: static void do_ssh2_kex(void);
1.129 provos 188:
1.87 markus 189: /*
1.75 markus 190: * Close all listening sockets
191: */
1.200 itojun 192: static void
1.75 markus 193: close_listen_socks(void)
194: {
195: int i;
196: for (i = 0; i < num_listen_socks; i++)
197: close(listen_socks[i]);
198: num_listen_socks = -1;
199: }
200:
1.211 markus 201: static void
202: close_startup_pipes(void)
203: {
204: int i;
205: if (startup_pipes)
206: for (i = 0; i < options.max_startups; i++)
207: if (startup_pipes[i] != -1)
208: close(startup_pipes[i]);
209: }
210:
1.75 markus 211: /*
1.65 deraadt 212: * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
213: * the effect is to reread the configuration file (and to regenerate
214: * the server key).
215: */
1.200 itojun 216: static void
1.64 markus 217: sighup_handler(int sig)
1.1 deraadt 218: {
1.210 deraadt 219: int save_errno = errno;
220:
1.64 markus 221: received_sighup = 1;
222: signal(SIGHUP, sighup_handler);
1.210 deraadt 223: errno = save_errno;
1.1 deraadt 224: }
225:
1.65 deraadt 226: /*
227: * Called from the main program after receiving SIGHUP.
228: * Restarts the server.
229: */
1.200 itojun 230: static void
1.165 itojun 231: sighup_restart(void)
1.1 deraadt 232: {
1.64 markus 233: log("Received SIGHUP; restarting.");
1.75 markus 234: close_listen_socks();
1.211 markus 235: close_startup_pipes();
1.64 markus 236: execv(saved_argv[0], saved_argv);
1.138 markus 237: log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], strerror(errno));
1.64 markus 238: exit(1);
1.1 deraadt 239: }
240:
1.65 deraadt 241: /*
242: * Generic signal handler for terminating signals in the master daemon.
243: */
1.200 itojun 244: static void
1.64 markus 245: sigterm_handler(int sig)
1.1 deraadt 246: {
1.199 markus 247: received_sigterm = sig;
1.1 deraadt 248: }
249:
1.65 deraadt 250: /*
251: * SIGCHLD handler. This is called whenever a child dies. This will then
1.199 markus 252: * reap any zombies left by exited children.
1.65 deraadt 253: */
1.200 itojun 254: static void
1.64 markus 255: main_sigchld_handler(int sig)
1.1 deraadt 256: {
1.64 markus 257: int save_errno = errno;
258: int status;
1.60 deraadt 259:
1.64 markus 260: while (waitpid(-1, &status, WNOHANG) > 0)
261: ;
1.60 deraadt 262:
1.64 markus 263: signal(SIGCHLD, main_sigchld_handler);
264: errno = save_errno;
1.1 deraadt 265: }
266:
1.65 deraadt 267: /*
268: * Signal handler for the alarm after the login grace period has expired.
269: */
1.200 itojun 270: static void
1.64 markus 271: grace_alarm_handler(int sig)
1.1 deraadt 272: {
1.199 markus 273: /* XXX no idea how fix this signal handler */
274:
1.64 markus 275: /* Close the connection. */
276: packet_close();
277:
278: /* Log error and exit. */
279: fatal("Timeout before authentication for %s.", get_remote_ipaddr());
1.62 markus 280: }
281:
1.65 deraadt 282: /*
283: * Signal handler for the key regeneration alarm. Note that this
284: * alarm only occurs in the daemon waiting for connections, and it does not
285: * do anything with the private key or random state before forking.
286: * Thus there should be no concurrency control/asynchronous execution
287: * problems.
288: */
1.200 itojun 289: static void
1.174 deraadt 290: generate_ephemeral_server_key(void)
1.134 markus 291: {
1.169 markus 292: u_int32_t rand = 0;
293: int i;
294:
1.191 markus 295: verbose("Generating %s%d bit RSA key.",
1.185 djm 296: sensitive_data.server_key ? "new " : "", options.server_key_bits);
1.134 markus 297: if (sensitive_data.server_key != NULL)
298: key_free(sensitive_data.server_key);
1.191 markus 299: sensitive_data.server_key = key_generate(KEY_RSA1,
1.185 djm 300: options.server_key_bits);
301: verbose("RSA key generation complete.");
1.169 markus 302:
303: for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
304: if (i % 4 == 0)
305: rand = arc4random();
306: sensitive_data.ssh1_cookie[i] = rand & 0xff;
307: rand >>= 8;
308: }
1.134 markus 309: arc4random_stir();
310: }
1.147 deraadt 311:
1.200 itojun 312: static void
1.64 markus 313: key_regeneration_alarm(int sig)
1.1 deraadt 314: {
1.64 markus 315: int save_errno = errno;
1.151 markus 316: signal(SIGALRM, SIG_DFL);
1.64 markus 317: errno = save_errno;
1.151 markus 318: key_do_regen = 1;
1.98 markus 319: }
320:
1.200 itojun 321: static void
1.96 markus 322: sshd_exchange_identification(int sock_in, int sock_out)
323: {
1.102 markus 324: int i, mismatch;
1.96 markus 325: int remote_major, remote_minor;
1.102 markus 326: int major, minor;
1.96 markus 327: char *s;
328: char buf[256]; /* Must not be larger than remote_version. */
329: char remote_version[256]; /* Must be at least as big as buf. */
330:
1.103 markus 331: if ((options.protocol & SSH_PROTO_1) &&
332: (options.protocol & SSH_PROTO_2)) {
1.102 markus 333: major = PROTOCOL_MAJOR_1;
334: minor = 99;
335: } else if (options.protocol & SSH_PROTO_2) {
336: major = PROTOCOL_MAJOR_2;
337: minor = PROTOCOL_MINOR_2;
338: } else {
339: major = PROTOCOL_MAJOR_1;
340: minor = PROTOCOL_MINOR_1;
341: }
342: snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
1.96 markus 343: server_version_string = xstrdup(buf);
344:
345: if (client_version_string == NULL) {
346: /* Send our protocol version identification. */
347: if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
348: != strlen(server_version_string)) {
1.208 markus 349: log("Could not write ident string to %s", get_remote_ipaddr());
1.96 markus 350: fatal_cleanup();
351: }
352:
1.167 markus 353: /* Read other side's version identification. */
1.191 markus 354: memset(buf, 0, sizeof(buf));
1.96 markus 355: for (i = 0; i < sizeof(buf) - 1; i++) {
1.119 markus 356: if (atomicio(read, sock_in, &buf[i], 1) != 1) {
1.208 markus 357: log("Did not receive identification string from %s",
1.168 deraadt 358: get_remote_ipaddr());
1.96 markus 359: fatal_cleanup();
360: }
361: if (buf[i] == '\r') {
1.176 deraadt 362: buf[i] = 0;
1.132 markus 363: /* Kludge for F-Secure Macintosh < 1.0.2 */
364: if (i == 12 &&
365: strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
366: break;
1.96 markus 367: continue;
368: }
369: if (buf[i] == '\n') {
1.176 deraadt 370: buf[i] = 0;
1.96 markus 371: break;
372: }
373: }
374: buf[sizeof(buf) - 1] = 0;
375: client_version_string = xstrdup(buf);
376: }
377:
378: /*
379: * Check that the versions match. In future this might accept
380: * several versions and set appropriate flags to handle them.
381: */
382: if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
383: &remote_major, &remote_minor, remote_version) != 3) {
1.105 markus 384: s = "Protocol mismatch.\n";
1.96 markus 385: (void) atomicio(write, sock_out, s, strlen(s));
386: close(sock_in);
387: close(sock_out);
388: log("Bad protocol version identification '%.100s' from %s",
389: client_version_string, get_remote_ipaddr());
390: fatal_cleanup();
391: }
392: debug("Client protocol version %d.%d; client software version %.100s",
1.217 deraadt 393: remote_major, remote_minor, remote_version);
1.96 markus 394:
1.98 markus 395: compat_datafellows(remote_version);
1.175 deraadt 396:
397: if (datafellows & SSH_BUG_SCANNER) {
398: log("scanned from %s with %s. Don't panic.",
399: get_remote_ipaddr(), client_version_string);
400: fatal_cleanup();
401: }
1.98 markus 402:
1.102 markus 403: mismatch = 0;
1.214 deraadt 404: switch (remote_major) {
1.96 markus 405: case 1:
1.108 markus 406: if (remote_minor == 99) {
407: if (options.protocol & SSH_PROTO_2)
408: enable_compat20();
409: else
410: mismatch = 1;
411: break;
412: }
1.102 markus 413: if (!(options.protocol & SSH_PROTO_1)) {
414: mismatch = 1;
415: break;
416: }
1.96 markus 417: if (remote_minor < 3) {
1.121 provos 418: packet_disconnect("Your ssh version is too old and "
1.96 markus 419: "is no longer supported. Please install a newer version.");
420: } else if (remote_minor == 3) {
421: /* note that this disables agent-forwarding */
422: enable_compat13();
423: }
1.102 markus 424: break;
1.98 markus 425: case 2:
1.102 markus 426: if (options.protocol & SSH_PROTO_2) {
1.98 markus 427: enable_compat20();
428: break;
429: }
1.99 markus 430: /* FALLTHROUGH */
1.105 markus 431: default:
1.102 markus 432: mismatch = 1;
433: break;
434: }
435: chop(server_version_string);
436: debug("Local version string %.200s", server_version_string);
437:
438: if (mismatch) {
1.96 markus 439: s = "Protocol major versions differ.\n";
440: (void) atomicio(write, sock_out, s, strlen(s));
441: close(sock_in);
442: close(sock_out);
1.102 markus 443: log("Protocol major versions differ for %s: %.200s vs. %.200s",
444: get_remote_ipaddr(),
445: server_version_string, client_version_string);
1.96 markus 446: fatal_cleanup();
447: }
1.108 markus 448: }
449:
450:
1.134 markus 451: /* Destroy the host and server keys. They will no longer be needed. */
1.108 markus 452: void
453: destroy_sensitive_data(void)
454: {
1.134 markus 455: int i;
456:
457: if (sensitive_data.server_key) {
458: key_free(sensitive_data.server_key);
459: sensitive_data.server_key = NULL;
460: }
1.217 deraadt 461: for (i = 0; i < options.num_host_key_files; i++) {
1.134 markus 462: if (sensitive_data.host_keys[i]) {
463: key_free(sensitive_data.host_keys[i]);
464: sensitive_data.host_keys[i] = NULL;
465: }
466: }
467: sensitive_data.ssh1_host_key = NULL;
1.169 markus 468: memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
1.134 markus 469: }
470:
1.200 itojun 471: static char *
1.134 markus 472: list_hostkey_types(void)
473: {
474: static char buf[1024];
475: int i;
476: buf[0] = '\0';
1.217 deraadt 477: for (i = 0; i < options.num_host_key_files; i++) {
1.134 markus 478: Key *key = sensitive_data.host_keys[i];
479: if (key == NULL)
480: continue;
1.214 deraadt 481: switch (key->type) {
1.134 markus 482: case KEY_RSA:
483: case KEY_DSA:
484: strlcat(buf, key_ssh_name(key), sizeof buf);
485: strlcat(buf, ",", sizeof buf);
486: break;
487: }
488: }
489: i = strlen(buf);
490: if (i > 0 && buf[i-1] == ',')
491: buf[i-1] = '\0';
492: debug("list_hostkey_types: %s", buf);
493: return buf;
494: }
495:
1.200 itojun 496: static Key *
1.134 markus 497: get_hostkey_by_type(int type)
498: {
499: int i;
1.217 deraadt 500: for (i = 0; i < options.num_host_key_files; i++) {
1.134 markus 501: Key *key = sensitive_data.host_keys[i];
502: if (key != NULL && key->type == type)
503: return key;
504: }
505: return NULL;
1.96 markus 506: }
507:
1.124 markus 508: /*
509: * returns 1 if connection should be dropped, 0 otherwise.
510: * dropping starts at connection #max_startups_begin with a probability
511: * of (max_startups_rate/100). the probability increases linearly until
512: * all connections are dropped for startups > max_startups
513: */
1.200 itojun 514: static int
1.124 markus 515: drop_connection(int startups)
516: {
517: double p, r;
518:
519: if (startups < options.max_startups_begin)
520: return 0;
521: if (startups >= options.max_startups)
522: return 1;
523: if (options.max_startups_rate == 100)
524: return 1;
525:
526: p = 100 - options.max_startups_rate;
527: p *= startups - options.max_startups_begin;
528: p /= (double) (options.max_startups - options.max_startups_begin);
529: p += options.max_startups_rate;
530: p /= 100.0;
531: r = arc4random() / (double) UINT_MAX;
532:
533: debug("drop_connection: p %g, r %g", p, r);
534: return (r < p) ? 1 : 0;
535: }
536:
1.215 markus 537: static void
538: usage(void)
539: {
540: fprintf(stderr, "sshd version %s\n", SSH_VERSION);
541: fprintf(stderr, "Usage: %s [options]\n", __progname);
542: fprintf(stderr, "Options:\n");
543: fprintf(stderr, " -f file Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
544: fprintf(stderr, " -d Debugging mode (multiple -d means more debugging)\n");
545: fprintf(stderr, " -i Started from inetd\n");
546: fprintf(stderr, " -D Do not fork into daemon mode\n");
547: fprintf(stderr, " -t Only test configuration file and keys\n");
548: fprintf(stderr, " -q Quiet (no logging)\n");
549: fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
550: fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
551: fprintf(stderr, " -g seconds Grace period for authentication (default: 600)\n");
552: fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
553: fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
554: _PATH_HOST_KEY_FILE);
555: fprintf(stderr, " -u len Maximum hostname length for utmp recording\n");
556: fprintf(stderr, " -4 Use IPv4 only\n");
557: fprintf(stderr, " -6 Use IPv6 only\n");
558: fprintf(stderr, " -o option Process the option as if it was read from a configuration file.\n");
559: exit(1);
560: }
561:
1.65 deraadt 562: /*
563: * Main program for the daemon.
564: */
1.2 provos 565: int
566: main(int ac, char **av)
1.1 deraadt 567: {
1.64 markus 568: extern char *optarg;
569: extern int optind;
1.120 markus 570: int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
1.107 deraadt 571: pid_t pid;
1.75 markus 572: socklen_t fromlen;
573: fd_set *fdset;
574: struct sockaddr_storage from;
1.64 markus 575: const char *remote_ip;
576: int remote_port;
577: FILE *f;
578: struct linger linger;
1.75 markus 579: struct addrinfo *ai;
580: char ntop[NI_MAXHOST], strport[NI_MAXSERV];
581: int listen_sock, maxfd;
1.120 markus 582: int startup_p[2];
583: int startups = 0;
1.179 markus 584: Key *key;
1.151 markus 585: int ret, key_used = 0;
1.64 markus 586:
1.138 markus 587: /* Save argv. */
1.64 markus 588: saved_argv = av;
589:
590: /* Initialize configuration options to their default values. */
591: initialize_server_options(&options);
592:
593: /* Parse command-line arguments. */
1.215 markus 594: while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
1.64 markus 595: switch (opt) {
1.75 markus 596: case '4':
597: IPv4or6 = AF_INET;
598: break;
599: case '6':
600: IPv4or6 = AF_INET6;
601: break;
1.64 markus 602: case 'f':
603: config_file_name = optarg;
604: break;
605: case 'd':
1.127 markus 606: if (0 == debug_flag) {
607: debug_flag = 1;
608: options.log_level = SYSLOG_LEVEL_DEBUG1;
609: } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
610: options.log_level++;
611: } else {
612: fprintf(stderr, "Too high debugging level.\n");
613: exit(1);
614: }
1.64 markus 615: break;
1.135 markus 616: case 'D':
617: no_daemon_flag = 1;
1.192 lebel 618: break;
619: case 'e':
620: log_stderr = 1;
1.135 markus 621: break;
1.64 markus 622: case 'i':
623: inetd_flag = 1;
624: break;
625: case 'Q':
1.158 markus 626: /* ignored */
1.64 markus 627: break;
628: case 'q':
629: options.log_level = SYSLOG_LEVEL_QUIET;
630: break;
631: case 'b':
632: options.server_key_bits = atoi(optarg);
633: break;
634: case 'p':
1.75 markus 635: options.ports_from_cmdline = 1;
1.127 markus 636: if (options.num_ports >= MAX_PORTS) {
637: fprintf(stderr, "too many ports.\n");
638: exit(1);
639: }
1.193 stevesk 640: options.ports[options.num_ports++] = a2port(optarg);
641: if (options.ports[options.num_ports-1] == 0) {
642: fprintf(stderr, "Bad port number.\n");
643: exit(1);
644: }
1.64 markus 645: break;
646: case 'g':
1.197 stevesk 647: if ((options.login_grace_time = convtime(optarg)) == -1) {
648: fprintf(stderr, "Invalid login grace time.\n");
649: exit(1);
650: }
1.64 markus 651: break;
652: case 'k':
1.197 stevesk 653: if ((options.key_regeneration_time = convtime(optarg)) == -1) {
654: fprintf(stderr, "Invalid key regeneration interval.\n");
655: exit(1);
656: }
1.64 markus 657: break;
658: case 'h':
1.134 markus 659: if (options.num_host_key_files >= MAX_HOSTKEYS) {
660: fprintf(stderr, "too many host keys.\n");
661: exit(1);
662: }
663: options.host_key_files[options.num_host_key_files++] = optarg;
1.64 markus 664: break;
665: case 'V':
666: client_version_string = optarg;
667: /* only makes sense with inetd_flag, i.e. no listen() */
668: inetd_flag = 1;
669: break;
1.203 stevesk 670: case 't':
671: test_flag = 1;
672: break;
1.125 markus 673: case 'u':
674: utmp_len = atoi(optarg);
675: break;
1.215 markus 676: case 'o':
1.217 deraadt 677: if (process_server_config_line(&options, optarg,
1.215 markus 678: "command-line", 0) != 0)
1.217 deraadt 679: exit(1);
1.215 markus 680: break;
1.64 markus 681: case '?':
682: default:
1.215 markus 683: usage();
684: break;
1.64 markus 685: }
686: }
1.180 markus 687: SSLeay_add_all_algorithms();
1.205 markus 688: channel_set_af(IPv4or6);
1.64 markus 689:
1.75 markus 690: /*
691: * Force logging to stderr until we have loaded the private host
692: * key (unless started from inetd)
693: */
1.138 markus 694: log_init(__progname,
1.152 markus 695: options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
1.75 markus 696: options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
1.158 markus 697: !inetd_flag);
1.75 markus 698:
1.64 markus 699: /* Read server configuration options from the configuration file. */
700: read_server_config(&options, config_file_name);
701:
702: /* Fill in default values for those options not explicitly set. */
703: fill_default_server_options(&options);
704:
705: /* Check that there are no remaining arguments. */
706: if (optind < ac) {
707: fprintf(stderr, "Extra argument %s.\n", av[optind]);
708: exit(1);
709: }
710:
711: debug("sshd version %.100s", SSH_VERSION);
712:
1.134 markus 713: /* load private host keys */
714: sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*));
1.217 deraadt 715: for (i = 0; i < options.num_host_key_files; i++)
1.141 markus 716: sensitive_data.host_keys[i] = NULL;
1.134 markus 717: sensitive_data.server_key = NULL;
718: sensitive_data.ssh1_host_key = NULL;
719: sensitive_data.have_ssh1_key = 0;
720: sensitive_data.have_ssh2_key = 0;
721:
1.217 deraadt 722: for (i = 0; i < options.num_host_key_files; i++) {
1.179 markus 723: key = key_load_private(options.host_key_files[i], "", NULL);
724: sensitive_data.host_keys[i] = key;
1.134 markus 725: if (key == NULL) {
1.195 markus 726: error("Could not load host key: %s",
727: options.host_key_files[i]);
1.179 markus 728: sensitive_data.host_keys[i] = NULL;
1.134 markus 729: continue;
730: }
1.214 deraadt 731: switch (key->type) {
1.134 markus 732: case KEY_RSA1:
733: sensitive_data.ssh1_host_key = key;
734: sensitive_data.have_ssh1_key = 1;
735: break;
736: case KEY_RSA:
737: case KEY_DSA:
738: sensitive_data.have_ssh2_key = 1;
739: break;
740: }
1.179 markus 741: debug("private host key: #%d type %d %s", i, key->type,
742: key_type(key));
1.134 markus 743: }
744: if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
745: log("Disabling protocol version 1. Could not load host key");
1.108 markus 746: options.protocol &= ~SSH_PROTO_1;
747: }
1.134 markus 748: if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
749: log("Disabling protocol version 2. Could not load host key");
750: options.protocol &= ~SSH_PROTO_2;
1.108 markus 751: }
1.162 stevesk 752: if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1.172 millert 753: log("sshd: no hostkeys available -- exiting.");
1.64 markus 754: exit(1);
755: }
756:
1.108 markus 757: /* Check certain values for sanity. */
758: if (options.protocol & SSH_PROTO_1) {
759: if (options.server_key_bits < 512 ||
760: options.server_key_bits > 32768) {
761: fprintf(stderr, "Bad server key size.\n");
762: exit(1);
763: }
764: /*
765: * Check that server and host key lengths differ sufficiently. This
766: * is necessary to make double encryption work with rsaref. Oh, I
767: * hate software patents. I dont know if this can go? Niels
768: */
769: if (options.server_key_bits >
1.134 markus 770: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - SSH_KEY_BITS_RESERVED &&
1.108 markus 771: options.server_key_bits <
1.134 markus 772: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1.108 markus 773: options.server_key_bits =
1.134 markus 774: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED;
1.108 markus 775: debug("Forcing server key to %d bits to make it differ from host key.",
776: options.server_key_bits);
777: }
778: }
1.203 stevesk 779:
780: /* Configuration looks good, so exit if in test mode. */
781: if (test_flag)
782: exit(0);
1.108 markus 783:
784: /* Initialize the log (it is reinitialized below in case we forked). */
1.64 markus 785: if (debug_flag && !inetd_flag)
786: log_stderr = 1;
1.138 markus 787: log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64 markus 788:
1.108 markus 789: /*
790: * If not in debugging mode, and not started from inetd, disconnect
791: * from the controlling terminal, and fork. The original process
792: * exits.
793: */
1.135 markus 794: if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1.1 deraadt 795: #ifdef TIOCNOTTY
1.64 markus 796: int fd;
1.1 deraadt 797: #endif /* TIOCNOTTY */
1.64 markus 798: if (daemon(0, 0) < 0)
799: fatal("daemon() failed: %.200s", strerror(errno));
800:
801: /* Disconnect from the controlling tty. */
1.1 deraadt 802: #ifdef TIOCNOTTY
1.165 itojun 803: fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1.64 markus 804: if (fd >= 0) {
805: (void) ioctl(fd, TIOCNOTTY, NULL);
806: close(fd);
807: }
808: #endif /* TIOCNOTTY */
809: }
810: /* Reinitialize the log (because of the fork above). */
1.138 markus 811: log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64 markus 812:
813: /* Initialize the random number generator. */
814: arc4random_stir();
815:
816: /* Chdir to the root directory so that the current disk can be
817: unmounted if desired. */
818: chdir("/");
1.217 deraadt 819:
1.178 markus 820: /* ignore SIGPIPE */
821: signal(SIGPIPE, SIG_IGN);
1.64 markus 822:
823: /* Start listening for a socket, unless started from inetd. */
824: if (inetd_flag) {
1.194 markus 825: int s1;
1.64 markus 826: s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
1.194 markus 827: dup(s1);
1.64 markus 828: sock_in = dup(0);
829: sock_out = dup(1);
1.123 djm 830: startup_pipe = -1;
1.108 markus 831: /*
832: * We intentionally do not close the descriptors 0, 1, and 2
833: * as our code for setting the descriptors won\'t work if
834: * ttyfd happens to be one of those.
835: */
1.64 markus 836: debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1.134 markus 837: if (options.protocol & SSH_PROTO_1)
1.174 deraadt 838: generate_ephemeral_server_key();
1.64 markus 839: } else {
1.75 markus 840: for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
841: if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
842: continue;
843: if (num_listen_socks >= MAX_LISTEN_SOCKS)
844: fatal("Too many listen sockets. "
845: "Enlarge MAX_LISTEN_SOCKS");
846: if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
847: ntop, sizeof(ntop), strport, sizeof(strport),
848: NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
849: error("getnameinfo failed");
850: continue;
851: }
852: /* Create socket for listening. */
853: listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
854: if (listen_sock < 0) {
855: /* kernel may not support ipv6 */
856: verbose("socket: %.100s", strerror(errno));
857: continue;
858: }
859: if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
860: error("listen_sock O_NONBLOCK: %s", strerror(errno));
861: close(listen_sock);
862: continue;
863: }
864: /*
865: * Set socket options. We try to make the port
866: * reusable and have it close as fast as possible
867: * without waiting in unnecessary wait states on
868: * close.
869: */
870: setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
871: (void *) &on, sizeof(on));
872: linger.l_onoff = 1;
873: linger.l_linger = 5;
874: setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
875: (void *) &linger, sizeof(linger));
876:
877: debug("Bind to port %s on %s.", strport, ntop);
878:
879: /* Bind the socket to the desired port. */
880: if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
881: error("Bind to port %s on %s failed: %.200s.",
882: strport, ntop, strerror(errno));
883: close(listen_sock);
884: continue;
885: }
886: listen_socks[num_listen_socks] = listen_sock;
887: num_listen_socks++;
888:
889: /* Start listening on the port. */
890: log("Server listening on %s port %s.", ntop, strport);
891: if (listen(listen_sock, 5) < 0)
892: fatal("listen: %.100s", strerror(errno));
893:
1.64 markus 894: }
1.75 markus 895: freeaddrinfo(options.listen_addrs);
896:
897: if (!num_listen_socks)
898: fatal("Cannot bind any address.");
899:
1.201 markus 900: if (options.protocol & SSH_PROTO_1)
901: generate_ephemeral_server_key();
902:
903: /*
904: * Arrange to restart on SIGHUP. The handler needs
905: * listen_sock.
906: */
907: signal(SIGHUP, sighup_handler);
908:
909: signal(SIGTERM, sigterm_handler);
910: signal(SIGQUIT, sigterm_handler);
911:
912: /* Arrange SIGCHLD to be caught. */
913: signal(SIGCHLD, main_sigchld_handler);
914:
915: /* Write out the pid file after the sigterm handler is setup */
1.64 markus 916: if (!debug_flag) {
1.66 markus 917: /*
1.136 todd 918: * Record our pid in /var/run/sshd.pid to make it
919: * easier to kill the correct sshd. We don't want to
920: * do this before the bind above because the bind will
1.66 markus 921: * fail if there already is a daemon, and this will
922: * overwrite any old pid in the file.
923: */
1.112 markus 924: f = fopen(options.pid_file, "w");
1.64 markus 925: if (f) {
1.140 markus 926: fprintf(f, "%u\n", (u_int) getpid());
1.64 markus 927: fclose(f);
928: }
929: }
930:
1.75 markus 931: /* setup fd set for listen */
1.120 markus 932: fdset = NULL;
1.75 markus 933: maxfd = 0;
934: for (i = 0; i < num_listen_socks; i++)
935: if (listen_socks[i] > maxfd)
936: maxfd = listen_socks[i];
1.120 markus 937: /* pipes connected to unauthenticated childs */
938: startup_pipes = xmalloc(options.max_startups * sizeof(int));
939: for (i = 0; i < options.max_startups; i++)
940: startup_pipes[i] = -1;
1.75 markus 941:
1.66 markus 942: /*
943: * Stay listening for connections until the system crashes or
944: * the daemon is killed with a signal.
945: */
1.64 markus 946: for (;;) {
947: if (received_sighup)
948: sighup_restart();
1.120 markus 949: if (fdset != NULL)
950: xfree(fdset);
1.148 markus 951: fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1.120 markus 952: fdset = (fd_set *)xmalloc(fdsetsz);
1.75 markus 953: memset(fdset, 0, fdsetsz);
1.120 markus 954:
1.75 markus 955: for (i = 0; i < num_listen_socks; i++)
956: FD_SET(listen_socks[i], fdset);
1.120 markus 957: for (i = 0; i < options.max_startups; i++)
958: if (startup_pipes[i] != -1)
959: FD_SET(startup_pipes[i], fdset);
960:
961: /* Wait in select until there is a connection. */
1.151 markus 962: ret = select(maxfd+1, fdset, NULL, NULL, NULL);
963: if (ret < 0 && errno != EINTR)
964: error("select: %.100s", strerror(errno));
1.199 markus 965: if (received_sigterm) {
966: log("Received signal %d; terminating.",
1.213 itojun 967: (int) received_sigterm);
1.199 markus 968: close_listen_socks();
969: unlink(options.pid_file);
970: exit(255);
971: }
1.151 markus 972: if (key_used && key_do_regen) {
1.174 deraadt 973: generate_ephemeral_server_key();
1.151 markus 974: key_used = 0;
975: key_do_regen = 0;
976: }
977: if (ret < 0)
1.75 markus 978: continue;
1.151 markus 979:
1.120 markus 980: for (i = 0; i < options.max_startups; i++)
981: if (startup_pipes[i] != -1 &&
982: FD_ISSET(startup_pipes[i], fdset)) {
983: /*
984: * the read end of the pipe is ready
985: * if the child has closed the pipe
1.143 markus 986: * after successful authentication
1.120 markus 987: * or if the child has died
988: */
989: close(startup_pipes[i]);
990: startup_pipes[i] = -1;
991: startups--;
992: }
1.75 markus 993: for (i = 0; i < num_listen_socks; i++) {
994: if (!FD_ISSET(listen_socks[i], fdset))
1.70 provos 995: continue;
1.120 markus 996: fromlen = sizeof(from);
997: newsock = accept(listen_socks[i], (struct sockaddr *)&from,
998: &fromlen);
999: if (newsock < 0) {
1000: if (errno != EINTR && errno != EWOULDBLOCK)
1001: error("accept: %.100s", strerror(errno));
1002: continue;
1003: }
1004: if (fcntl(newsock, F_SETFL, 0) < 0) {
1005: error("newsock del O_NONBLOCK: %s", strerror(errno));
1.216 stevesk 1006: close(newsock);
1.120 markus 1007: continue;
1008: }
1.124 markus 1009: if (drop_connection(startups) == 1) {
1010: debug("drop connection #%d", startups);
1.120 markus 1011: close(newsock);
1012: continue;
1013: }
1014: if (pipe(startup_p) == -1) {
1015: close(newsock);
1016: continue;
1017: }
1018:
1019: for (j = 0; j < options.max_startups; j++)
1020: if (startup_pipes[j] == -1) {
1021: startup_pipes[j] = startup_p[0];
1022: if (maxfd < startup_p[0])
1023: maxfd = startup_p[0];
1024: startups++;
1025: break;
1026: }
1.161 stevesk 1027:
1.66 markus 1028: /*
1.120 markus 1029: * Got connection. Fork a child to handle it, unless
1030: * we are in debugging mode.
1.66 markus 1031: */
1.120 markus 1032: if (debug_flag) {
1.66 markus 1033: /*
1.120 markus 1034: * In debugging mode. Close the listening
1035: * socket, and start processing the
1036: * connection without forking.
1.66 markus 1037: */
1.120 markus 1038: debug("Server will not fork when running in debugging mode.");
1.75 markus 1039: close_listen_socks();
1.64 markus 1040: sock_in = newsock;
1041: sock_out = newsock;
1.122 deraadt 1042: startup_pipe = -1;
1.120 markus 1043: pid = getpid();
1.64 markus 1044: break;
1.120 markus 1045: } else {
1046: /*
1047: * Normal production daemon. Fork, and have
1048: * the child process the connection. The
1049: * parent continues listening.
1050: */
1051: if ((pid = fork()) == 0) {
1052: /*
1053: * Child. Close the listening and max_startup
1054: * sockets. Start using the accepted socket.
1055: * Reinitialize logging (since our pid has
1056: * changed). We break out of the loop to handle
1057: * the connection.
1058: */
1059: startup_pipe = startup_p[1];
1.211 markus 1060: close_startup_pipes();
1.120 markus 1061: close_listen_socks();
1062: sock_in = newsock;
1063: sock_out = newsock;
1.138 markus 1064: log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.120 markus 1065: break;
1066: }
1.64 markus 1067: }
1068:
1.120 markus 1069: /* Parent. Stay in the loop. */
1070: if (pid < 0)
1071: error("fork: %.100s", strerror(errno));
1072: else
1073: debug("Forked child %d.", pid);
1074:
1075: close(startup_p[1]);
1.1 deraadt 1076:
1.120 markus 1077: /* Mark that the key has been used (it was "given" to the child). */
1.151 markus 1078: if ((options.protocol & SSH_PROTO_1) &&
1079: key_used == 0) {
1080: /* Schedule server key regeneration alarm. */
1081: signal(SIGALRM, key_regeneration_alarm);
1082: alarm(options.key_regeneration_time);
1083: key_used = 1;
1084: }
1.1 deraadt 1085:
1.120 markus 1086: arc4random_stir();
1.1 deraadt 1087:
1.120 markus 1088: /* Close the new socket (the child is now taking care of it). */
1089: close(newsock);
1090: }
1.75 markus 1091: /* child process check (or debug mode) */
1092: if (num_listen_socks < 0)
1093: break;
1.64 markus 1094: }
1.1 deraadt 1095: }
1096:
1.64 markus 1097: /* This is the child processing a new connection. */
1098:
1.66 markus 1099: /*
1100: * Disable the key regeneration alarm. We will not regenerate the
1101: * key since we are no longer in a position to give it to anyone. We
1102: * will not restart on SIGHUP since it no longer makes sense.
1103: */
1.64 markus 1104: alarm(0);
1105: signal(SIGALRM, SIG_DFL);
1106: signal(SIGHUP, SIG_DFL);
1107: signal(SIGTERM, SIG_DFL);
1108: signal(SIGQUIT, SIG_DFL);
1109: signal(SIGCHLD, SIG_DFL);
1110:
1.66 markus 1111: /*
1112: * Set socket options for the connection. We want the socket to
1113: * close as fast as possible without waiting for anything. If the
1114: * connection is not a socket, these will do nothing.
1115: */
1116: /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1.64 markus 1117: linger.l_onoff = 1;
1118: linger.l_linger = 5;
1119: setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
1.150 markus 1120:
1121: /* Set keepalives if requested. */
1122: if (options.keepalives &&
1123: setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
1124: sizeof(on)) < 0)
1125: error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1.64 markus 1126:
1.66 markus 1127: /*
1128: * Register our connection. This turns encryption off because we do
1129: * not have a key.
1130: */
1.64 markus 1131: packet_set_connection(sock_in, sock_out);
1.1 deraadt 1132:
1.64 markus 1133: remote_port = get_remote_port();
1134: remote_ip = get_remote_ipaddr();
1.52 markus 1135:
1.209 markus 1136: #ifdef LIBWRAP
1.64 markus 1137: /* Check whether logins are denied from this host. */
1138: {
1139: struct request_info req;
1.37 dugsong 1140:
1.204 camield 1141: request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1.64 markus 1142: fromhost(&req);
1.37 dugsong 1143:
1.64 markus 1144: if (!hosts_access(&req)) {
1.209 markus 1145: debug("Connection refused by tcp wrapper");
1.182 markus 1146: refuse(&req);
1.209 markus 1147: /* NOTREACHED */
1148: fatal("libwrap refuse returns");
1.64 markus 1149: }
1150: }
1.75 markus 1151: #endif /* LIBWRAP */
1.209 markus 1152:
1.64 markus 1153: /* Log the connection. */
1154: verbose("Connection from %.500s port %d", remote_ip, remote_port);
1.1 deraadt 1155:
1.66 markus 1156: /*
1157: * We don\'t want to listen forever unless the other side
1158: * successfully authenticates itself. So we set up an alarm which is
1159: * cleared after successful authentication. A limit of zero
1160: * indicates no limit. Note that we don\'t set the alarm in debugging
1161: * mode; it is just annoying to have the server exit just when you
1162: * are about to discover the bug.
1163: */
1.64 markus 1164: signal(SIGALRM, grace_alarm_handler);
1165: if (!debug_flag)
1166: alarm(options.login_grace_time);
1167:
1.96 markus 1168: sshd_exchange_identification(sock_in, sock_out);
1.66 markus 1169: /*
1.137 markus 1170: * Check that the connection comes from a privileged port.
1171: * Rhosts-Authentication only makes sense from priviledged
1.66 markus 1172: * programs. Of course, if the intruder has root access on his local
1173: * machine, he can connect from any port. So do not use these
1174: * authentication methods from machines that you do not trust.
1175: */
1.64 markus 1176: if (remote_port >= IPPORT_RESERVED ||
1177: remote_port < IPPORT_RESERVED / 2) {
1.137 markus 1178: debug("Rhosts Authentication disabled, "
1.207 markus 1179: "originating port %d not trusted.", remote_port);
1.64 markus 1180: options.rhosts_authentication = 0;
1181: }
1.202 dugsong 1182: #if defined(KRB4) && !defined(KRB5)
1.76 markus 1183: if (!packet_connection_is_ipv4() &&
1184: options.kerberos_authentication) {
1185: debug("Kerberos Authentication disabled, only available for IPv4.");
1186: options.kerberos_authentication = 0;
1187: }
1.202 dugsong 1188: #endif /* KRB4 && !KRB5 */
1.164 markus 1189: #ifdef AFS
1190: /* If machine has AFS, set process authentication group. */
1191: if (k_hasafs()) {
1192: k_setpag();
1193: k_unlog();
1194: }
1195: #endif /* AFS */
1.76 markus 1196:
1.64 markus 1197: packet_set_nonblocking();
1.1 deraadt 1198:
1.77 markus 1199: /* perform the key exchange */
1200: /* authenticate user and start session */
1.98 markus 1201: if (compat20) {
1202: do_ssh2_kex();
1203: do_authentication2();
1204: } else {
1205: do_ssh1_kex();
1206: do_authentication();
1207: }
1.64 markus 1208: /* The connection has been terminated. */
1209: verbose("Closing connection to %.100s", remote_ip);
1210: packet_close();
1211: exit(0);
1.1 deraadt 1212: }
1213:
1.65 deraadt 1214: /*
1.77 markus 1215: * SSH1 key exchange
1.65 deraadt 1216: */
1.200 itojun 1217: static void
1.142 markus 1218: do_ssh1_kex(void)
1.1 deraadt 1219: {
1.64 markus 1220: int i, len;
1.221 ! markus 1221: int plen;
1.159 markus 1222: int rsafail = 0;
1.64 markus 1223: BIGNUM *session_key_int;
1.140 markus 1224: u_char session_key[SSH_SESSION_KEY_LENGTH];
1225: u_char cookie[8];
1226: u_int cipher_type, auth_mask, protocol_flags;
1.64 markus 1227: u_int32_t rand = 0;
1228:
1.66 markus 1229: /*
1230: * Generate check bytes that the client must send back in the user
1231: * packet in order for it to be accepted; this is used to defy ip
1232: * spoofing attacks. Note that this only works against somebody
1233: * doing IP spoofing from a remote machine; any machine on the local
1234: * network can still see outgoing packets and catch the random
1235: * cookie. This only affects rhosts authentication, and this is one
1236: * of the reasons why it is inherently insecure.
1237: */
1.64 markus 1238: for (i = 0; i < 8; i++) {
1239: if (i % 4 == 0)
1240: rand = arc4random();
1.77 markus 1241: cookie[i] = rand & 0xff;
1.64 markus 1242: rand >>= 8;
1243: }
1244:
1.66 markus 1245: /*
1246: * Send our public key. We include in the packet 64 bits of random
1247: * data that must be matched in the reply in order to prevent IP
1248: * spoofing.
1249: */
1.64 markus 1250: packet_start(SSH_SMSG_PUBLIC_KEY);
1251: for (i = 0; i < 8; i++)
1.77 markus 1252: packet_put_char(cookie[i]);
1.64 markus 1253:
1254: /* Store our public server RSA key. */
1.134 markus 1255: packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1256: packet_put_bignum(sensitive_data.server_key->rsa->e);
1257: packet_put_bignum(sensitive_data.server_key->rsa->n);
1.64 markus 1258:
1259: /* Store our public host RSA key. */
1.134 markus 1260: packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1261: packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1262: packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1.64 markus 1263:
1264: /* Put protocol flags. */
1265: packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1266:
1267: /* Declare which ciphers we support. */
1.131 markus 1268: packet_put_int(cipher_mask_ssh1(0));
1.64 markus 1269:
1270: /* Declare supported authentication types. */
1271: auth_mask = 0;
1272: if (options.rhosts_authentication)
1273: auth_mask |= 1 << SSH_AUTH_RHOSTS;
1274: if (options.rhosts_rsa_authentication)
1275: auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1276: if (options.rsa_authentication)
1277: auth_mask |= 1 << SSH_AUTH_RSA;
1.202 dugsong 1278: #if defined(KRB4) || defined(KRB5)
1.64 markus 1279: if (options.kerberos_authentication)
1280: auth_mask |= 1 << SSH_AUTH_KERBEROS;
1.1 deraadt 1281: #endif
1.202 dugsong 1282: #if defined(AFS) || defined(KRB5)
1.64 markus 1283: if (options.kerberos_tgt_passing)
1284: auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1.202 dugsong 1285: #endif
1286: #ifdef AFS
1.64 markus 1287: if (options.afs_token_passing)
1288: auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1.1 deraadt 1289: #endif
1.196 markus 1290: if (options.challenge_response_authentication == 1)
1.64 markus 1291: auth_mask |= 1 << SSH_AUTH_TIS;
1292: if (options.password_authentication)
1293: auth_mask |= 1 << SSH_AUTH_PASSWORD;
1294: packet_put_int(auth_mask);
1295:
1296: /* Send the packet and wait for it to be sent. */
1297: packet_send();
1298: packet_write_wait();
1299:
1.134 markus 1300: debug("Sent %d bit server key and %d bit host key.",
1301: BN_num_bits(sensitive_data.server_key->rsa->n),
1302: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1.64 markus 1303:
1304: /* Read clients reply (cipher type and session key). */
1305: packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
1306:
1.69 markus 1307: /* Get cipher type and check whether we accept this. */
1.64 markus 1308: cipher_type = packet_get_char();
1.69 markus 1309:
1.131 markus 1310: if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1.69 markus 1311: packet_disconnect("Warning: client selects unsupported cipher.");
1.64 markus 1312:
1313: /* Get check bytes from the packet. These must match those we
1314: sent earlier with the public key packet. */
1315: for (i = 0; i < 8; i++)
1.77 markus 1316: if (cookie[i] != packet_get_char())
1.64 markus 1317: packet_disconnect("IP Spoofing check bytes do not match.");
1318:
1319: debug("Encryption type: %.200s", cipher_name(cipher_type));
1320:
1321: /* Get the encrypted integer. */
1.218 markus 1322: if ((session_key_int = BN_new()) == NULL)
1323: fatal("do_ssh1_kex: BN_new failed");
1.221 ! markus 1324: packet_get_bignum(session_key_int);
1.64 markus 1325:
1326: protocol_flags = packet_get_int();
1327: packet_set_protocol_flags(protocol_flags);
1.220 markus 1328: packet_check_eom();
1.64 markus 1329:
1.66 markus 1330: /*
1331: * Decrypt it using our private server key and private host key (key
1332: * with larger modulus first).
1333: */
1.134 markus 1334: if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1.159 markus 1335: /* Server key has bigger modulus. */
1.134 markus 1336: if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1337: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1338: fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1339: get_remote_ipaddr(),
1340: BN_num_bits(sensitive_data.server_key->rsa->n),
1341: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1342: SSH_KEY_BITS_RESERVED);
1.64 markus 1343: }
1.159 markus 1344: if (rsa_private_decrypt(session_key_int, session_key_int,
1345: sensitive_data.server_key->rsa) <= 0)
1346: rsafail++;
1347: if (rsa_private_decrypt(session_key_int, session_key_int,
1348: sensitive_data.ssh1_host_key->rsa) <= 0)
1349: rsafail++;
1.64 markus 1350: } else {
1351: /* Host key has bigger modulus (or they are equal). */
1.134 markus 1352: if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1353: BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1354: fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1355: get_remote_ipaddr(),
1356: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1357: BN_num_bits(sensitive_data.server_key->rsa->n),
1358: SSH_KEY_BITS_RESERVED);
1.64 markus 1359: }
1.159 markus 1360: if (rsa_private_decrypt(session_key_int, session_key_int,
1361: sensitive_data.ssh1_host_key->rsa) < 0)
1362: rsafail++;
1363: if (rsa_private_decrypt(session_key_int, session_key_int,
1364: sensitive_data.server_key->rsa) < 0)
1365: rsafail++;
1.64 markus 1366: }
1.66 markus 1367: /*
1368: * Extract session key from the decrypted integer. The key is in the
1369: * least significant 256 bits of the integer; the first byte of the
1370: * key is in the highest bits.
1371: */
1.159 markus 1372: if (!rsafail) {
1373: BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1374: len = BN_num_bytes(session_key_int);
1375: if (len < 0 || len > sizeof(session_key)) {
1376: error("do_connection: bad session key len from %s: "
1.165 itojun 1377: "session_key_int %d > sizeof(session_key) %lu",
1378: get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1.159 markus 1379: rsafail++;
1380: } else {
1381: memset(session_key, 0, sizeof(session_key));
1382: BN_bn2bin(session_key_int,
1383: session_key + sizeof(session_key) - len);
1.169 markus 1384:
1385: compute_session_id(session_id, cookie,
1386: sensitive_data.ssh1_host_key->rsa->n,
1387: sensitive_data.server_key->rsa->n);
1388: /*
1389: * Xor the first 16 bytes of the session key with the
1390: * session id.
1391: */
1392: for (i = 0; i < 16; i++)
1393: session_key[i] ^= session_id[i];
1.159 markus 1394: }
1395: }
1396: if (rsafail) {
1.169 markus 1397: int bytes = BN_num_bytes(session_key_int);
1398: char *buf = xmalloc(bytes);
1399: MD5_CTX md;
1400:
1.159 markus 1401: log("do_connection: generating a fake encryption key");
1.169 markus 1402: BN_bn2bin(session_key_int, buf);
1403: MD5_Init(&md);
1404: MD5_Update(&md, buf, bytes);
1405: MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1406: MD5_Final(session_key, &md);
1407: MD5_Init(&md);
1408: MD5_Update(&md, session_key, 16);
1409: MD5_Update(&md, buf, bytes);
1410: MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1411: MD5_Final(session_key + 16, &md);
1412: memset(buf, 0, bytes);
1413: xfree(buf);
1.170 markus 1414: for (i = 0; i < 16; i++)
1415: session_id[i] = session_key[i] ^ session_key[i + 16];
1.159 markus 1416: }
1.169 markus 1417: /* Destroy the private and public keys. They will no longer be needed. */
1418: destroy_sensitive_data();
1419:
1.77 markus 1420: /* Destroy the decrypted integer. It is no longer needed. */
1421: BN_clear_free(session_key_int);
1.64 markus 1422:
1423: /* Set the session key. From this on all communications will be encrypted. */
1424: packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1425:
1426: /* Destroy our copy of the session key. It is no longer needed. */
1427: memset(session_key, 0, sizeof(session_key));
1428:
1429: debug("Received session key; encryption turned on.");
1430:
1431: /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1432: packet_start(SSH_SMSG_SUCCESS);
1433: packet_send();
1434: packet_write_wait();
1.98 markus 1435: }
1436:
1437: /*
1438: * SSH2 key exchange: diffie-hellman-group1-sha1
1439: */
1.200 itojun 1440: static void
1.142 markus 1441: do_ssh2_kex(void)
1.98 markus 1442: {
1443: Kex *kex;
1.102 markus 1444:
1445: if (options.ciphers != NULL) {
1.105 markus 1446: myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.102 markus 1447: myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1.166 markus 1448: }
1.184 stevesk 1449: myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1450: compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1451: myproposal[PROPOSAL_ENC_ALGS_STOC] =
1452: compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1453:
1.166 markus 1454: if (options.macs != NULL) {
1455: myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1456: myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1.102 markus 1457: }
1.134 markus 1458: myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1459:
1.189 markus 1460: /* start key exchange */
1.188 markus 1461: kex = kex_setup(myproposal);
1.186 markus 1462: kex->server = 1;
1463: kex->client_version_string=client_version_string;
1464: kex->server_version_string=server_version_string;
1465: kex->load_host_key=&get_hostkey_by_type;
1.129 provos 1466:
1.189 markus 1467: xxx_kex = kex;
1468:
1.190 markus 1469: dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1.187 markus 1470:
1471: session_id2 = kex->session_id;
1472: session_id2_len = kex->session_id_len;
1.129 provos 1473:
1474: #ifdef DEBUG_KEXDH
1475: /* send 1st encrypted/maced/compressed message */
1476: packet_start(SSH2_MSG_IGNORE);
1477: packet_put_cstring("markus");
1478: packet_send();
1479: packet_write_wait();
1480: #endif
1.186 markus 1481: debug("KEX done");
1.1 deraadt 1482: }