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