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