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