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