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