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