Annotation of src/usr.bin/ssh/sshd.c, Revision 1.138
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.138 ! markus 43: RCSID("$OpenBSD: sshd.c,v 1.137 2000/12/12 21:45:21 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 */
156: unsigned char session_id[16];
157:
1.108 markus 158: /* same for ssh2 */
159: unsigned char *session_id2 = NULL;
160: int session_id2_len = 0;
161:
1.125 markus 162: /* record remote hostname or ip */
163: unsigned int utmp_len = MAXHOSTNAMELEN;
164:
1.1 deraadt 165: /* Prototypes for various functions defined later in this file. */
1.96 markus 166: void do_ssh1_kex();
1.98 markus 167: void do_ssh2_kex();
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");
643: fprintf(stderr, " -q Quiet (no logging)\n");
644: fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
645: fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
646: fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
647: fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
648: fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
1.75 markus 649: HOST_KEY_FILE);
1.125 markus 650: fprintf(stderr, " -u len Maximum hostname length for utmp recording\n");
1.75 markus 651: fprintf(stderr, " -4 Use IPv4 only\n");
652: fprintf(stderr, " -6 Use IPv6 only\n");
1.64 markus 653: exit(1);
654: }
655: }
656:
1.75 markus 657: /*
658: * Force logging to stderr until we have loaded the private host
659: * key (unless started from inetd)
660: */
1.138 ! markus 661: log_init(__progname,
1.75 markus 662: options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
663: options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
1.110 markus 664: !silent && !inetd_flag);
1.75 markus 665:
1.64 markus 666: /* Read server configuration options from the configuration file. */
667: read_server_config(&options, config_file_name);
668:
669: /* Fill in default values for those options not explicitly set. */
670: fill_default_server_options(&options);
671:
672: /* Check that there are no remaining arguments. */
673: if (optind < ac) {
674: fprintf(stderr, "Extra argument %s.\n", av[optind]);
675: exit(1);
676: }
677:
678: debug("sshd version %.100s", SSH_VERSION);
679:
1.134 markus 680: /* load private host keys */
681: sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*));
682: sensitive_data.server_key = NULL;
683: sensitive_data.ssh1_host_key = NULL;
684: sensitive_data.have_ssh1_key = 0;
685: sensitive_data.have_ssh2_key = 0;
686:
687: for(i = 0; i < options.num_host_key_files; i++) {
688: Key *key = load_private_key_autodetect(options.host_key_files[i]);
689: if (key == NULL) {
690: error("Could not load host key: %.200s: %.100s",
691: options.host_key_files[i], strerror(errno));
692: continue;
693: }
694: switch(key->type){
695: case KEY_RSA1:
696: sensitive_data.ssh1_host_key = key;
697: sensitive_data.have_ssh1_key = 1;
698: break;
699: case KEY_RSA:
700: case KEY_DSA:
701: sensitive_data.have_ssh2_key = 1;
702: break;
703: }
704: sensitive_data.host_keys[i] = key;
705: }
706: if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
707: log("Disabling protocol version 1. Could not load host key");
1.108 markus 708: options.protocol &= ~SSH_PROTO_1;
709: }
1.134 markus 710: if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
711: log("Disabling protocol version 2. Could not load host key");
712: options.protocol &= ~SSH_PROTO_2;
1.108 markus 713: }
714: if (! options.protocol & (SSH_PROTO_1|SSH_PROTO_2)) {
1.110 markus 715: if (silent == 0)
716: fprintf(stderr, "sshd: no hostkeys available -- exiting.\n");
1.108 markus 717: log("sshd: no hostkeys available -- exiting.\n");
1.64 markus 718: exit(1);
719: }
720:
1.108 markus 721: /* Check certain values for sanity. */
722: if (options.protocol & SSH_PROTO_1) {
723: if (options.server_key_bits < 512 ||
724: options.server_key_bits > 32768) {
725: fprintf(stderr, "Bad server key size.\n");
726: exit(1);
727: }
728: /*
729: * Check that server and host key lengths differ sufficiently. This
730: * is necessary to make double encryption work with rsaref. Oh, I
731: * hate software patents. I dont know if this can go? Niels
732: */
733: if (options.server_key_bits >
1.134 markus 734: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - SSH_KEY_BITS_RESERVED &&
1.108 markus 735: options.server_key_bits <
1.134 markus 736: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1.108 markus 737: options.server_key_bits =
1.134 markus 738: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED;
1.108 markus 739: debug("Forcing server key to %d bits to make it differ from host key.",
740: options.server_key_bits);
741: }
742: }
743:
744: /* Initialize the log (it is reinitialized below in case we forked). */
1.64 markus 745: if (debug_flag && !inetd_flag)
746: log_stderr = 1;
1.138 ! markus 747: log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64 markus 748:
1.108 markus 749: /*
750: * If not in debugging mode, and not started from inetd, disconnect
751: * from the controlling terminal, and fork. The original process
752: * exits.
753: */
1.135 markus 754: if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1.1 deraadt 755: #ifdef TIOCNOTTY
1.64 markus 756: int fd;
1.1 deraadt 757: #endif /* TIOCNOTTY */
1.64 markus 758: if (daemon(0, 0) < 0)
759: fatal("daemon() failed: %.200s", strerror(errno));
760:
761: /* Disconnect from the controlling tty. */
1.1 deraadt 762: #ifdef TIOCNOTTY
1.64 markus 763: fd = open("/dev/tty", O_RDWR | O_NOCTTY);
764: if (fd >= 0) {
765: (void) ioctl(fd, TIOCNOTTY, NULL);
766: close(fd);
767: }
768: #endif /* TIOCNOTTY */
769: }
770: /* Reinitialize the log (because of the fork above). */
1.138 ! markus 771: log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64 markus 772:
773: /* Initialize the random number generator. */
774: arc4random_stir();
775:
776: /* Chdir to the root directory so that the current disk can be
777: unmounted if desired. */
778: chdir("/");
779:
780: /* Start listening for a socket, unless started from inetd. */
781: if (inetd_flag) {
782: int s1, s2;
783: s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
784: s2 = dup(s1);
785: sock_in = dup(0);
786: sock_out = dup(1);
1.123 djm 787: startup_pipe = -1;
1.108 markus 788: /*
789: * We intentionally do not close the descriptors 0, 1, and 2
790: * as our code for setting the descriptors won\'t work if
791: * ttyfd happens to be one of those.
792: */
1.64 markus 793: debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1.134 markus 794: if (options.protocol & SSH_PROTO_1)
795: generate_empheral_server_key();
1.64 markus 796: } else {
1.75 markus 797: for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
798: if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
799: continue;
800: if (num_listen_socks >= MAX_LISTEN_SOCKS)
801: fatal("Too many listen sockets. "
802: "Enlarge MAX_LISTEN_SOCKS");
803: if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
804: ntop, sizeof(ntop), strport, sizeof(strport),
805: NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
806: error("getnameinfo failed");
807: continue;
808: }
809: /* Create socket for listening. */
810: listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
811: if (listen_sock < 0) {
812: /* kernel may not support ipv6 */
813: verbose("socket: %.100s", strerror(errno));
814: continue;
815: }
816: if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
817: error("listen_sock O_NONBLOCK: %s", strerror(errno));
818: close(listen_sock);
819: continue;
820: }
821: /*
822: * Set socket options. We try to make the port
823: * reusable and have it close as fast as possible
824: * without waiting in unnecessary wait states on
825: * close.
826: */
827: setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
828: (void *) &on, sizeof(on));
829: linger.l_onoff = 1;
830: linger.l_linger = 5;
831: setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
832: (void *) &linger, sizeof(linger));
833:
834: debug("Bind to port %s on %s.", strport, ntop);
835:
836: /* Bind the socket to the desired port. */
837: if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
838: error("Bind to port %s on %s failed: %.200s.",
839: strport, ntop, strerror(errno));
840: close(listen_sock);
841: continue;
842: }
843: listen_socks[num_listen_socks] = listen_sock;
844: num_listen_socks++;
845:
846: /* Start listening on the port. */
847: log("Server listening on %s port %s.", ntop, strport);
848: if (listen(listen_sock, 5) < 0)
849: fatal("listen: %.100s", strerror(errno));
850:
1.64 markus 851: }
1.75 markus 852: freeaddrinfo(options.listen_addrs);
853:
854: if (!num_listen_socks)
855: fatal("Cannot bind any address.");
856:
1.64 markus 857: if (!debug_flag) {
1.66 markus 858: /*
1.136 todd 859: * Record our pid in /var/run/sshd.pid to make it
860: * easier to kill the correct sshd. We don't want to
861: * do this before the bind above because the bind will
1.66 markus 862: * fail if there already is a daemon, and this will
863: * overwrite any old pid in the file.
864: */
1.112 markus 865: f = fopen(options.pid_file, "w");
1.64 markus 866: if (f) {
867: fprintf(f, "%u\n", (unsigned int) getpid());
868: fclose(f);
869: }
870: }
1.108 markus 871: if (options.protocol & SSH_PROTO_1) {
1.134 markus 872: generate_empheral_server_key();
1.64 markus 873:
1.108 markus 874: /* Schedule server key regeneration alarm. */
875: signal(SIGALRM, key_regeneration_alarm);
876: alarm(options.key_regeneration_time);
877: }
1.64 markus 878:
879: /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
880: signal(SIGHUP, sighup_handler);
1.120 markus 881:
1.64 markus 882: signal(SIGTERM, sigterm_handler);
883: signal(SIGQUIT, sigterm_handler);
884:
885: /* Arrange SIGCHLD to be caught. */
886: signal(SIGCHLD, main_sigchld_handler);
887:
1.75 markus 888: /* setup fd set for listen */
1.120 markus 889: fdset = NULL;
1.75 markus 890: maxfd = 0;
891: for (i = 0; i < num_listen_socks; i++)
892: if (listen_socks[i] > maxfd)
893: maxfd = listen_socks[i];
1.120 markus 894: /* pipes connected to unauthenticated childs */
895: startup_pipes = xmalloc(options.max_startups * sizeof(int));
896: for (i = 0; i < options.max_startups; i++)
897: startup_pipes[i] = -1;
1.75 markus 898:
1.66 markus 899: /*
900: * Stay listening for connections until the system crashes or
901: * the daemon is killed with a signal.
902: */
1.64 markus 903: for (;;) {
904: if (received_sighup)
905: sighup_restart();
1.120 markus 906: if (fdset != NULL)
907: xfree(fdset);
908: fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
909: fdset = (fd_set *)xmalloc(fdsetsz);
1.75 markus 910: memset(fdset, 0, fdsetsz);
1.120 markus 911:
1.75 markus 912: for (i = 0; i < num_listen_socks; i++)
913: FD_SET(listen_socks[i], fdset);
1.120 markus 914: for (i = 0; i < options.max_startups; i++)
915: if (startup_pipes[i] != -1)
916: FD_SET(startup_pipes[i], fdset);
917:
918: /* Wait in select until there is a connection. */
1.75 markus 919: if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
920: if (errno != EINTR)
921: error("select: %.100s", strerror(errno));
922: continue;
923: }
1.120 markus 924: for (i = 0; i < options.max_startups; i++)
925: if (startup_pipes[i] != -1 &&
926: FD_ISSET(startup_pipes[i], fdset)) {
927: /*
928: * the read end of the pipe is ready
929: * if the child has closed the pipe
930: * after successfull authentication
931: * or if the child has died
932: */
933: close(startup_pipes[i]);
934: startup_pipes[i] = -1;
935: startups--;
936: }
1.75 markus 937: for (i = 0; i < num_listen_socks; i++) {
938: if (!FD_ISSET(listen_socks[i], fdset))
1.70 provos 939: continue;
1.120 markus 940: fromlen = sizeof(from);
941: newsock = accept(listen_socks[i], (struct sockaddr *)&from,
942: &fromlen);
943: if (newsock < 0) {
944: if (errno != EINTR && errno != EWOULDBLOCK)
945: error("accept: %.100s", strerror(errno));
946: continue;
947: }
948: if (fcntl(newsock, F_SETFL, 0) < 0) {
949: error("newsock del O_NONBLOCK: %s", strerror(errno));
950: continue;
951: }
1.124 markus 952: if (drop_connection(startups) == 1) {
953: debug("drop connection #%d", startups);
1.120 markus 954: close(newsock);
955: continue;
956: }
957: if (pipe(startup_p) == -1) {
958: close(newsock);
959: continue;
960: }
961:
962: for (j = 0; j < options.max_startups; j++)
963: if (startup_pipes[j] == -1) {
964: startup_pipes[j] = startup_p[0];
965: if (maxfd < startup_p[0])
966: maxfd = startup_p[0];
967: startups++;
968: break;
969: }
970:
1.66 markus 971: /*
1.120 markus 972: * Got connection. Fork a child to handle it, unless
973: * we are in debugging mode.
1.66 markus 974: */
1.120 markus 975: if (debug_flag) {
1.66 markus 976: /*
1.120 markus 977: * In debugging mode. Close the listening
978: * socket, and start processing the
979: * connection without forking.
1.66 markus 980: */
1.120 markus 981: debug("Server will not fork when running in debugging mode.");
1.75 markus 982: close_listen_socks();
1.64 markus 983: sock_in = newsock;
984: sock_out = newsock;
1.122 deraadt 985: startup_pipe = -1;
1.120 markus 986: pid = getpid();
1.64 markus 987: break;
1.120 markus 988: } else {
989: /*
990: * Normal production daemon. Fork, and have
991: * the child process the connection. The
992: * parent continues listening.
993: */
994: if ((pid = fork()) == 0) {
995: /*
996: * Child. Close the listening and max_startup
997: * sockets. Start using the accepted socket.
998: * Reinitialize logging (since our pid has
999: * changed). We break out of the loop to handle
1000: * the connection.
1001: */
1002: startup_pipe = startup_p[1];
1003: for (j = 0; j < options.max_startups; j++)
1004: if (startup_pipes[j] != -1)
1005: close(startup_pipes[j]);
1006: close_listen_socks();
1007: sock_in = newsock;
1008: sock_out = newsock;
1.138 ! markus 1009: log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.120 markus 1010: break;
1011: }
1.64 markus 1012: }
1013:
1.120 markus 1014: /* Parent. Stay in the loop. */
1015: if (pid < 0)
1016: error("fork: %.100s", strerror(errno));
1017: else
1018: debug("Forked child %d.", pid);
1019:
1020: close(startup_p[1]);
1.1 deraadt 1021:
1.120 markus 1022: /* Mark that the key has been used (it was "given" to the child). */
1023: key_used = 1;
1.1 deraadt 1024:
1.120 markus 1025: arc4random_stir();
1.1 deraadt 1026:
1.120 markus 1027: /* Close the new socket (the child is now taking care of it). */
1028: close(newsock);
1029: }
1.75 markus 1030: /* child process check (or debug mode) */
1031: if (num_listen_socks < 0)
1032: break;
1.64 markus 1033: }
1.1 deraadt 1034: }
1035:
1.64 markus 1036: /* This is the child processing a new connection. */
1037:
1.66 markus 1038: /*
1039: * Disable the key regeneration alarm. We will not regenerate the
1040: * key since we are no longer in a position to give it to anyone. We
1041: * will not restart on SIGHUP since it no longer makes sense.
1042: */
1.64 markus 1043: alarm(0);
1044: signal(SIGALRM, SIG_DFL);
1045: signal(SIGHUP, SIG_DFL);
1046: signal(SIGTERM, SIG_DFL);
1047: signal(SIGQUIT, SIG_DFL);
1048: signal(SIGCHLD, SIG_DFL);
1049:
1.66 markus 1050: /*
1051: * Set socket options for the connection. We want the socket to
1052: * close as fast as possible without waiting for anything. If the
1053: * connection is not a socket, these will do nothing.
1054: */
1055: /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1.64 markus 1056: linger.l_onoff = 1;
1057: linger.l_linger = 5;
1058: setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
1059:
1.66 markus 1060: /*
1061: * Register our connection. This turns encryption off because we do
1062: * not have a key.
1063: */
1.64 markus 1064: packet_set_connection(sock_in, sock_out);
1.1 deraadt 1065:
1.64 markus 1066: remote_port = get_remote_port();
1067: remote_ip = get_remote_ipaddr();
1.52 markus 1068:
1.64 markus 1069: /* Check whether logins are denied from this host. */
1.37 dugsong 1070: #ifdef LIBWRAP
1.75 markus 1071: /* XXX LIBWRAP noes not know about IPv6 */
1.64 markus 1072: {
1073: struct request_info req;
1.37 dugsong 1074:
1.138 ! markus 1075: request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, NULL);
1.64 markus 1076: fromhost(&req);
1.37 dugsong 1077:
1.64 markus 1078: if (!hosts_access(&req)) {
1079: close(sock_in);
1080: close(sock_out);
1081: refuse(&req);
1082: }
1.75 markus 1083: /*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
1.64 markus 1084: }
1.75 markus 1085: #endif /* LIBWRAP */
1.64 markus 1086: /* Log the connection. */
1087: verbose("Connection from %.500s port %d", remote_ip, remote_port);
1.1 deraadt 1088:
1.66 markus 1089: /*
1090: * We don\'t want to listen forever unless the other side
1091: * successfully authenticates itself. So we set up an alarm which is
1092: * cleared after successful authentication. A limit of zero
1093: * indicates no limit. Note that we don\'t set the alarm in debugging
1094: * mode; it is just annoying to have the server exit just when you
1095: * are about to discover the bug.
1096: */
1.64 markus 1097: signal(SIGALRM, grace_alarm_handler);
1098: if (!debug_flag)
1099: alarm(options.login_grace_time);
1100:
1.96 markus 1101: sshd_exchange_identification(sock_in, sock_out);
1.66 markus 1102: /*
1.137 markus 1103: * Check that the connection comes from a privileged port.
1104: * Rhosts-Authentication only makes sense from priviledged
1.66 markus 1105: * programs. Of course, if the intruder has root access on his local
1106: * machine, he can connect from any port. So do not use these
1107: * authentication methods from machines that you do not trust.
1108: */
1.64 markus 1109: if (remote_port >= IPPORT_RESERVED ||
1110: remote_port < IPPORT_RESERVED / 2) {
1.137 markus 1111: debug("Rhosts Authentication disabled, "
1.133 markus 1112: "originating port not trusted.");
1.64 markus 1113: options.rhosts_authentication = 0;
1114: }
1.76 markus 1115: #ifdef KRB4
1116: if (!packet_connection_is_ipv4() &&
1117: options.kerberos_authentication) {
1118: debug("Kerberos Authentication disabled, only available for IPv4.");
1119: options.kerberos_authentication = 0;
1120: }
1121: #endif /* KRB4 */
1122:
1.64 markus 1123: packet_set_nonblocking();
1.1 deraadt 1124:
1.77 markus 1125: /* perform the key exchange */
1126: /* authenticate user and start session */
1.98 markus 1127: if (compat20) {
1128: do_ssh2_kex();
1129: do_authentication2();
1130: } else {
1131: do_ssh1_kex();
1132: do_authentication();
1133: }
1.1 deraadt 1134:
1135: #ifdef KRB4
1.64 markus 1136: /* Cleanup user's ticket cache file. */
1137: if (options.kerberos_ticket_cleanup)
1138: (void) dest_tkt();
1.1 deraadt 1139: #endif /* KRB4 */
1140:
1.64 markus 1141: /* The connection has been terminated. */
1142: verbose("Closing connection to %.100s", remote_ip);
1143: packet_close();
1144: exit(0);
1.1 deraadt 1145: }
1146:
1.65 deraadt 1147: /*
1.77 markus 1148: * SSH1 key exchange
1.65 deraadt 1149: */
1.52 markus 1150: void
1.96 markus 1151: do_ssh1_kex()
1.1 deraadt 1152: {
1.64 markus 1153: int i, len;
1.77 markus 1154: int plen, slen;
1.64 markus 1155: BIGNUM *session_key_int;
1156: unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1.77 markus 1157: unsigned char cookie[8];
1.64 markus 1158: unsigned int cipher_type, auth_mask, protocol_flags;
1159: u_int32_t rand = 0;
1160:
1.66 markus 1161: /*
1162: * Generate check bytes that the client must send back in the user
1163: * packet in order for it to be accepted; this is used to defy ip
1164: * spoofing attacks. Note that this only works against somebody
1165: * doing IP spoofing from a remote machine; any machine on the local
1166: * network can still see outgoing packets and catch the random
1167: * cookie. This only affects rhosts authentication, and this is one
1168: * of the reasons why it is inherently insecure.
1169: */
1.64 markus 1170: for (i = 0; i < 8; i++) {
1171: if (i % 4 == 0)
1172: rand = arc4random();
1.77 markus 1173: cookie[i] = rand & 0xff;
1.64 markus 1174: rand >>= 8;
1175: }
1176:
1.66 markus 1177: /*
1178: * Send our public key. We include in the packet 64 bits of random
1179: * data that must be matched in the reply in order to prevent IP
1180: * spoofing.
1181: */
1.64 markus 1182: packet_start(SSH_SMSG_PUBLIC_KEY);
1183: for (i = 0; i < 8; i++)
1.77 markus 1184: packet_put_char(cookie[i]);
1.64 markus 1185:
1186: /* Store our public server RSA key. */
1.134 markus 1187: packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1188: packet_put_bignum(sensitive_data.server_key->rsa->e);
1189: packet_put_bignum(sensitive_data.server_key->rsa->n);
1.64 markus 1190:
1191: /* Store our public host RSA key. */
1.134 markus 1192: packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1193: packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1194: packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1.64 markus 1195:
1196: /* Put protocol flags. */
1197: packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1198:
1199: /* Declare which ciphers we support. */
1.131 markus 1200: packet_put_int(cipher_mask_ssh1(0));
1.64 markus 1201:
1202: /* Declare supported authentication types. */
1203: auth_mask = 0;
1204: if (options.rhosts_authentication)
1205: auth_mask |= 1 << SSH_AUTH_RHOSTS;
1206: if (options.rhosts_rsa_authentication)
1207: auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1208: if (options.rsa_authentication)
1209: auth_mask |= 1 << SSH_AUTH_RSA;
1.1 deraadt 1210: #ifdef KRB4
1.64 markus 1211: if (options.kerberos_authentication)
1212: auth_mask |= 1 << SSH_AUTH_KERBEROS;
1.1 deraadt 1213: #endif
1.5 dugsong 1214: #ifdef AFS
1.64 markus 1215: if (options.kerberos_tgt_passing)
1216: auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1217: if (options.afs_token_passing)
1218: auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1.1 deraadt 1219: #endif
1.63 markus 1220: #ifdef SKEY
1.64 markus 1221: if (options.skey_authentication == 1)
1222: auth_mask |= 1 << SSH_AUTH_TIS;
1.63 markus 1223: #endif
1.64 markus 1224: if (options.password_authentication)
1225: auth_mask |= 1 << SSH_AUTH_PASSWORD;
1226: packet_put_int(auth_mask);
1227:
1228: /* Send the packet and wait for it to be sent. */
1229: packet_send();
1230: packet_write_wait();
1231:
1.134 markus 1232: debug("Sent %d bit server key and %d bit host key.",
1233: BN_num_bits(sensitive_data.server_key->rsa->n),
1234: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1.64 markus 1235:
1236: /* Read clients reply (cipher type and session key). */
1237: packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
1238:
1.69 markus 1239: /* Get cipher type and check whether we accept this. */
1.64 markus 1240: cipher_type = packet_get_char();
1.69 markus 1241:
1.131 markus 1242: if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1.69 markus 1243: packet_disconnect("Warning: client selects unsupported cipher.");
1.64 markus 1244:
1245: /* Get check bytes from the packet. These must match those we
1246: sent earlier with the public key packet. */
1247: for (i = 0; i < 8; i++)
1.77 markus 1248: if (cookie[i] != packet_get_char())
1.64 markus 1249: packet_disconnect("IP Spoofing check bytes do not match.");
1250:
1251: debug("Encryption type: %.200s", cipher_name(cipher_type));
1252:
1253: /* Get the encrypted integer. */
1254: session_key_int = BN_new();
1255: packet_get_bignum(session_key_int, &slen);
1256:
1257: protocol_flags = packet_get_int();
1258: packet_set_protocol_flags(protocol_flags);
1259:
1260: packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1261:
1.66 markus 1262: /*
1263: * Decrypt it using our private server key and private host key (key
1264: * with larger modulus first).
1265: */
1.134 markus 1266: if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1.64 markus 1267: /* Private key has bigger modulus. */
1.134 markus 1268: if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1269: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1270: fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1271: get_remote_ipaddr(),
1272: BN_num_bits(sensitive_data.server_key->rsa->n),
1273: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1274: SSH_KEY_BITS_RESERVED);
1.64 markus 1275: }
1276: rsa_private_decrypt(session_key_int, session_key_int,
1.134 markus 1277: sensitive_data.server_key->rsa);
1.64 markus 1278: rsa_private_decrypt(session_key_int, session_key_int,
1.134 markus 1279: sensitive_data.ssh1_host_key->rsa);
1.64 markus 1280: } else {
1281: /* Host key has bigger modulus (or they are equal). */
1.134 markus 1282: if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1283: BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1284: fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1285: get_remote_ipaddr(),
1286: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1287: BN_num_bits(sensitive_data.server_key->rsa->n),
1288: SSH_KEY_BITS_RESERVED);
1.64 markus 1289: }
1290: rsa_private_decrypt(session_key_int, session_key_int,
1.134 markus 1291: sensitive_data.ssh1_host_key->rsa);
1.64 markus 1292: rsa_private_decrypt(session_key_int, session_key_int,
1.134 markus 1293: sensitive_data.server_key->rsa);
1.64 markus 1294: }
1295:
1.77 markus 1296: compute_session_id(session_id, cookie,
1.134 markus 1297: sensitive_data.ssh1_host_key->rsa->n,
1298: sensitive_data.server_key->rsa->n);
1.64 markus 1299:
1.77 markus 1300: /* Destroy the private and public keys. They will no longer be needed. */
1.108 markus 1301: destroy_sensitive_data();
1.77 markus 1302:
1.66 markus 1303: /*
1304: * Extract session key from the decrypted integer. The key is in the
1305: * least significant 256 bits of the integer; the first byte of the
1306: * key is in the highest bits.
1307: */
1.64 markus 1308: BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1309: len = BN_num_bytes(session_key_int);
1310: if (len < 0 || len > sizeof(session_key))
1311: fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1.134 markus 1312: get_remote_ipaddr(),
1313: len, sizeof(session_key));
1.64 markus 1314: memset(session_key, 0, sizeof(session_key));
1315: BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1316:
1.77 markus 1317: /* Destroy the decrypted integer. It is no longer needed. */
1318: BN_clear_free(session_key_int);
1319:
1.64 markus 1320: /* Xor the first 16 bytes of the session key with the session id. */
1321: for (i = 0; i < 16; i++)
1322: session_key[i] ^= session_id[i];
1323:
1324: /* Set the session key. From this on all communications will be encrypted. */
1325: packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1326:
1327: /* Destroy our copy of the session key. It is no longer needed. */
1328: memset(session_key, 0, sizeof(session_key));
1329:
1330: debug("Received session key; encryption turned on.");
1331:
1332: /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1333: packet_start(SSH_SMSG_SUCCESS);
1334: packet_send();
1335: packet_write_wait();
1.98 markus 1336: }
1337:
1338: /*
1339: * SSH2 key exchange: diffie-hellman-group1-sha1
1340: */
1341: void
1342: do_ssh2_kex()
1343: {
1344: Buffer *server_kexinit;
1345: Buffer *client_kexinit;
1.129 provos 1346: int payload_len;
1.98 markus 1347: int i;
1348: Kex *kex;
1349: char *cprop[PROPOSAL_MAX];
1350:
1351: /* KEXINIT */
1.102 markus 1352:
1353: if (options.ciphers != NULL) {
1.105 markus 1354: myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.102 markus 1355: myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1356: }
1.134 markus 1357: myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1358:
1.118 markus 1359: server_kexinit = kex_init(myproposal);
1.98 markus 1360: client_kexinit = xmalloc(sizeof(*client_kexinit));
1361: buffer_init(client_kexinit);
1362:
1.118 markus 1363: /* algorithm negotiation */
1364: kex_exchange_kexinit(server_kexinit, client_kexinit, cprop);
1365: kex = kex_choose_conf(cprop, myproposal, 1);
1366: for (i = 0; i < PROPOSAL_MAX; i++)
1367: xfree(cprop[i]);
1.98 markus 1368:
1.129 provos 1369: switch (kex->kex_type) {
1370: case DH_GRP1_SHA1:
1371: ssh_dh1_server(kex, client_kexinit, server_kexinit);
1372: break;
1373: case DH_GEX_SHA1:
1374: ssh_dhgex_server(kex, client_kexinit, server_kexinit);
1375: break;
1376: default:
1377: fatal("Unsupported key exchange %d", kex->kex_type);
1378: }
1379:
1380: debug("send SSH2_MSG_NEWKEYS.");
1381: packet_start(SSH2_MSG_NEWKEYS);
1382: packet_send();
1383: packet_write_wait();
1384: debug("done: send SSH2_MSG_NEWKEYS.");
1385:
1386: debug("Wait SSH2_MSG_NEWKEYS.");
1387: packet_read_expect(&payload_len, SSH2_MSG_NEWKEYS);
1388: debug("GOT SSH2_MSG_NEWKEYS.");
1389:
1390: #ifdef DEBUG_KEXDH
1391: /* send 1st encrypted/maced/compressed message */
1392: packet_start(SSH2_MSG_IGNORE);
1393: packet_put_cstring("markus");
1394: packet_send();
1395: packet_write_wait();
1396: #endif
1397:
1398: debug("done: KEX2.");
1399: }
1400:
1401: /*
1402: * SSH2 key exchange
1403: */
1404:
1405: /* diffie-hellman-group1-sha1 */
1406:
1407: void
1408: ssh_dh1_server(Kex *kex, Buffer *client_kexinit, Buffer *server_kexinit)
1409: {
1.130 markus 1410: #ifdef DEBUG_KEXDH
1411: int i;
1412: #endif
1.129 provos 1413: int payload_len, dlen;
1414: int slen;
1415: unsigned char *signature = NULL;
1416: unsigned char *server_host_key_blob = NULL;
1417: unsigned int sbloblen;
1418: unsigned int klen, kout;
1419: unsigned char *kbuf;
1420: unsigned char *hash;
1421: BIGNUM *shared_secret = 0;
1422: DH *dh;
1423: BIGNUM *dh_client_pub = 0;
1.134 markus 1424: Key *hostkey;
1425:
1426: hostkey = get_hostkey_by_type(kex->hostkey_type);
1427: if (hostkey == NULL)
1428: fatal("Unsupported hostkey type %d", kex->hostkey_type);
1.129 provos 1429:
1.98 markus 1430: /* KEXDH */
1431: debug("Wait SSH2_MSG_KEXDH_INIT.");
1432: packet_read_expect(&payload_len, SSH2_MSG_KEXDH_INIT);
1433:
1434: /* key, cert */
1435: dh_client_pub = BN_new();
1436: if (dh_client_pub == NULL)
1437: fatal("dh_client_pub == NULL");
1438: packet_get_bignum2(dh_client_pub, &dlen);
1439:
1440: #ifdef DEBUG_KEXDH
1441: fprintf(stderr, "\ndh_client_pub= ");
1.128 markus 1442: BN_print_fp(stderr, dh_client_pub);
1.98 markus 1443: fprintf(stderr, "\n");
1444: debug("bits %d", BN_num_bits(dh_client_pub));
1445: #endif
1446:
1447: /* generate DH key */
1.101 markus 1448: dh = dh_new_group1(); /* XXX depends on 'kex' */
1.98 markus 1449:
1450: #ifdef DEBUG_KEXDH
1451: fprintf(stderr, "\np= ");
1.128 markus 1452: BN_print_fp(stderr, dh->p);
1.98 markus 1453: fprintf(stderr, "\ng= ");
1.128 markus 1454: bn_print(dh->g);
1.98 markus 1455: fprintf(stderr, "\npub= ");
1.128 markus 1456: BN_print_fp(stderr, dh->pub_key);
1.98 markus 1457: fprintf(stderr, "\n");
1.128 markus 1458: DHparams_print_fp(stderr, dh);
1.98 markus 1459: #endif
1.101 markus 1460: if (!dh_pub_is_valid(dh, dh_client_pub))
1461: packet_disconnect("bad client public DH value");
1.98 markus 1462:
1463: klen = DH_size(dh);
1464: kbuf = xmalloc(klen);
1465: kout = DH_compute_key(kbuf, dh_client_pub, dh);
1466:
1467: #ifdef DEBUG_KEXDH
1468: debug("shared secret: len %d/%d", klen, kout);
1469: fprintf(stderr, "shared secret == ");
1470: for (i = 0; i< kout; i++)
1471: fprintf(stderr, "%02x", (kbuf[i])&0xff);
1472: fprintf(stderr, "\n");
1473: #endif
1474: shared_secret = BN_new();
1475:
1476: BN_bin2bn(kbuf, kout, shared_secret);
1477: memset(kbuf, 0, klen);
1478: xfree(kbuf);
1479:
1.111 markus 1480: /* XXX precompute? */
1.134 markus 1481: key_to_blob(hostkey, &server_host_key_blob, &sbloblen);
1.98 markus 1482:
1483: /* calc H */ /* XXX depends on 'kex' */
1484: hash = kex_hash(
1485: client_version_string,
1486: server_version_string,
1487: buffer_ptr(client_kexinit), buffer_len(client_kexinit),
1488: buffer_ptr(server_kexinit), buffer_len(server_kexinit),
1489: (char *)server_host_key_blob, sbloblen,
1490: dh_client_pub,
1491: dh->pub_key,
1492: shared_secret
1493: );
1494: buffer_free(client_kexinit);
1495: buffer_free(server_kexinit);
1496: xfree(client_kexinit);
1497: xfree(server_kexinit);
1498: #ifdef DEBUG_KEXDH
1.105 markus 1499: fprintf(stderr, "hash == ");
1500: for (i = 0; i< 20; i++)
1501: fprintf(stderr, "%02x", (hash[i])&0xff);
1502: fprintf(stderr, "\n");
1.98 markus 1503: #endif
1.108 markus 1504: /* save session id := H */
1505: /* XXX hashlen depends on KEX */
1506: session_id2_len = 20;
1507: session_id2 = xmalloc(session_id2_len);
1508: memcpy(session_id2, hash, session_id2_len);
1509:
1.98 markus 1510: /* sign H */
1.108 markus 1511: /* XXX hashlen depends on KEX */
1.134 markus 1512: key_sign(hostkey, &signature, &slen, hash, 20);
1.108 markus 1513:
1514: destroy_sensitive_data();
1.98 markus 1515:
1516: /* send server hostkey, DH pubkey 'f' and singed H */
1517: packet_start(SSH2_MSG_KEXDH_REPLY);
1518: packet_put_string((char *)server_host_key_blob, sbloblen);
1.114 markus 1519: packet_put_bignum2(dh->pub_key); /* f */
1.98 markus 1520: packet_put_string((char *)signature, slen);
1521: packet_send();
1.106 markus 1522: xfree(signature);
1.111 markus 1523: xfree(server_host_key_blob);
1.98 markus 1524: packet_write_wait();
1525:
1526: kex_derive_keys(kex, hash, shared_secret);
1527: packet_set_kex(kex);
1528:
1529: /* have keys, free DH */
1530: DH_free(dh);
1.129 provos 1531: }
1532:
1533: /* diffie-hellman-group-exchange-sha1 */
1.98 markus 1534:
1.129 provos 1535: void
1536: ssh_dhgex_server(Kex *kex, Buffer *client_kexinit, Buffer *server_kexinit)
1537: {
1.130 markus 1538: #ifdef DEBUG_KEXDH
1539: int i;
1540: #endif
1.129 provos 1541: int payload_len, dlen;
1542: int slen, nbits;
1543: unsigned char *signature = NULL;
1544: unsigned char *server_host_key_blob = NULL;
1545: unsigned int sbloblen;
1546: unsigned int klen, kout;
1547: unsigned char *kbuf;
1548: unsigned char *hash;
1549: BIGNUM *shared_secret = 0;
1550: DH *dh;
1551: BIGNUM *dh_client_pub = 0;
1.134 markus 1552: Key *hostkey;
1553:
1554: hostkey = get_hostkey_by_type(kex->hostkey_type);
1555: if (hostkey == NULL)
1556: fatal("Unsupported hostkey type %d", kex->hostkey_type);
1.129 provos 1557:
1558: /* KEXDHGEX */
1559: debug("Wait SSH2_MSG_KEX_DH_GEX_REQUEST.");
1560: packet_read_expect(&payload_len, SSH2_MSG_KEX_DH_GEX_REQUEST);
1561: nbits = packet_get_int();
1562: dh = choose_dh(nbits);
1563:
1564: debug("Sending SSH2_MSG_KEX_DH_GEX_GROUP.");
1565: packet_start(SSH2_MSG_KEX_DH_GEX_GROUP);
1566: packet_put_bignum2(dh->p);
1567: packet_put_bignum2(dh->g);
1.98 markus 1568: packet_send();
1569: packet_write_wait();
1570:
1.129 provos 1571: debug("Wait SSH2_MSG_KEX_DH_GEX_INIT.");
1572: packet_read_expect(&payload_len, SSH2_MSG_KEX_DH_GEX_INIT);
1573:
1574: /* key, cert */
1575: dh_client_pub = BN_new();
1576: if (dh_client_pub == NULL)
1577: fatal("dh_client_pub == NULL");
1578: packet_get_bignum2(dh_client_pub, &dlen);
1579:
1580: #ifdef DEBUG_KEXDH
1581: fprintf(stderr, "\ndh_client_pub= ");
1582: BN_print_fp(stderr, dh_client_pub);
1583: fprintf(stderr, "\n");
1584: debug("bits %d", BN_num_bits(dh_client_pub));
1585: #endif
1586:
1587: #ifdef DEBUG_KEXDH
1588: fprintf(stderr, "\np= ");
1589: BN_print_fp(stderr, dh->p);
1590: fprintf(stderr, "\ng= ");
1591: bn_print(dh->g);
1592: fprintf(stderr, "\npub= ");
1593: BN_print_fp(stderr, dh->pub_key);
1594: fprintf(stderr, "\n");
1595: DHparams_print_fp(stderr, dh);
1596: #endif
1597: if (!dh_pub_is_valid(dh, dh_client_pub))
1598: packet_disconnect("bad client public DH value");
1599:
1600: klen = DH_size(dh);
1601: kbuf = xmalloc(klen);
1602: kout = DH_compute_key(kbuf, dh_client_pub, dh);
1603:
1604: #ifdef DEBUG_KEXDH
1605: debug("shared secret: len %d/%d", klen, kout);
1606: fprintf(stderr, "shared secret == ");
1607: for (i = 0; i< kout; i++)
1608: fprintf(stderr, "%02x", (kbuf[i])&0xff);
1609: fprintf(stderr, "\n");
1610: #endif
1611: shared_secret = BN_new();
1612:
1613: BN_bin2bn(kbuf, kout, shared_secret);
1614: memset(kbuf, 0, klen);
1615: xfree(kbuf);
1616:
1617: /* XXX precompute? */
1.134 markus 1618: key_to_blob(hostkey, &server_host_key_blob, &sbloblen);
1.98 markus 1619:
1.129 provos 1620: /* calc H */ /* XXX depends on 'kex' */
1621: hash = kex_hash_gex(
1622: client_version_string,
1623: server_version_string,
1624: buffer_ptr(client_kexinit), buffer_len(client_kexinit),
1625: buffer_ptr(server_kexinit), buffer_len(server_kexinit),
1626: (char *)server_host_key_blob, sbloblen,
1627: nbits, dh->p, dh->g,
1628: dh_client_pub,
1629: dh->pub_key,
1630: shared_secret
1631: );
1632: buffer_free(client_kexinit);
1633: buffer_free(server_kexinit);
1634: xfree(client_kexinit);
1635: xfree(server_kexinit);
1.100 markus 1636: #ifdef DEBUG_KEXDH
1.129 provos 1637: fprintf(stderr, "hash == ");
1638: for (i = 0; i< 20; i++)
1639: fprintf(stderr, "%02x", (hash[i])&0xff);
1640: fprintf(stderr, "\n");
1641: #endif
1642: /* save session id := H */
1643: /* XXX hashlen depends on KEX */
1644: session_id2_len = 20;
1645: session_id2 = xmalloc(session_id2_len);
1646: memcpy(session_id2, hash, session_id2_len);
1647:
1648: /* sign H */
1649: /* XXX hashlen depends on KEX */
1.134 markus 1650: key_sign(hostkey, &signature, &slen, hash, 20);
1.129 provos 1651:
1652: destroy_sensitive_data();
1653:
1654: /* send server hostkey, DH pubkey 'f' and singed H */
1655: packet_start(SSH2_MSG_KEX_DH_GEX_REPLY);
1656: packet_put_string((char *)server_host_key_blob, sbloblen);
1657: packet_put_bignum2(dh->pub_key); /* f */
1658: packet_put_string((char *)signature, slen);
1.98 markus 1659: packet_send();
1.129 provos 1660: xfree(signature);
1661: xfree(server_host_key_blob);
1.98 markus 1662: packet_write_wait();
1.129 provos 1663:
1664: kex_derive_keys(kex, hash, shared_secret);
1665: packet_set_kex(kex);
1666:
1667: /* have keys, free DH */
1668: DH_free(dh);
1.1 deraadt 1669: }