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