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