]> andersk Git - openssh.git/blame - sshd.c
- Only set define entropy collection macros if they are found
[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.
11 */
8efc0c15 12
13#include "includes.h"
8ce64345 14RCSID("$OpenBSD: sshd.c,v 1.97 2000/04/04 21:37:27 markus Exp $");
8efc0c15 15
16#include "xmalloc.h"
17#include "rsa.h"
18#include "ssh.h"
19#include "pty.h"
20#include "packet.h"
8efc0c15 21#include "cipher.h"
22#include "mpaux.h"
23#include "servconf.h"
24#include "uidswap.h"
25#include "compat.h"
7368a6c8 26#include "buffer.h"
27
28#ifdef HAVE_OPENSSL
29# include <openssl/dh.h>
30# include <openssl/bn.h>
31# include <openssl/hmac.h>
32# include <openssl/dsa.h>
33# include <openssl/rsa.h>
34#endif
35#ifdef HAVE_SSL
36# include <ssl/dh.h>
37# include <ssl/bn.h>
38# include <ssl/hmac.h>
39# include <ssl/dsa.h>
40# include <ssl/rsa.h>
41#endif
42#include "key.h"
43
44#include "auth.h"
8efc0c15 45
46#ifdef LIBWRAP
47#include <tcpd.h>
48#include <syslog.h>
49int allow_severity = LOG_INFO;
50int deny_severity = LOG_WARNING;
51#endif /* LIBWRAP */
52
53#ifndef O_NOCTTY
54#define O_NOCTTY 0
55#endif
56
8efc0c15 57/* Server configuration options. */
58ServerOptions options;
59
60/* Name of the server configuration file. */
61char *config_file_name = SERVER_CONFIG_FILE;
62
48e671d5 63/*
64 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
65 * Default value is AF_UNSPEC means both IPv4 and IPv6.
66 */
59e76f33 67#ifdef IPV4_DEFAULT
68int IPv4or6 = AF_INET;
69#else
48e671d5 70int IPv4or6 = AF_UNSPEC;
59e76f33 71#endif
48e671d5 72
5260325f 73/*
74 * Debug mode flag. This can be set on the command line. If debug
75 * mode is enabled, extra debugging output will be sent to the system
76 * log, the daemon will not go to background, and will exit after processing
77 * the first connection.
78 */
8efc0c15 79int debug_flag = 0;
80
81/* Flag indicating that the daemon is being started from inetd. */
82int inetd_flag = 0;
83
6a17f9c2 84/* debug goes to stderr unless inetd_flag is set */
85int log_stderr = 0;
86
8efc0c15 87/* argv[0] without path. */
88char *av0;
89
90/* Saved arguments to main(). */
91char **saved_argv;
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 {
117 RSA *private_key; /* Private part of server key. */
118 RSA *host_key; /* Private part of 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
7368a6c8 137/* Prototypes for various functions defined later in this file. */
138void do_ssh1_kex();
c8d54615 139
48e671d5 140/*
141 * Close all listening sockets
142 */
143void
144close_listen_socks(void)
145{
146 int i;
147 for (i = 0; i < num_listen_socks; i++)
148 close(listen_socks[i]);
149 num_listen_socks = -1;
150}
151
5260325f 152/*
153 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
154 * the effect is to reread the configuration file (and to regenerate
155 * the server key).
156 */
157void
158sighup_handler(int sig)
8efc0c15 159{
5260325f 160 received_sighup = 1;
161 signal(SIGHUP, sighup_handler);
8efc0c15 162}
163
5260325f 164/*
165 * Called from the main program after receiving SIGHUP.
166 * Restarts the server.
167 */
168void
169sighup_restart()
8efc0c15 170{
5260325f 171 log("Received SIGHUP; restarting.");
48e671d5 172 close_listen_socks();
5260325f 173 execv(saved_argv[0], saved_argv);
174 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
175 exit(1);
8efc0c15 176}
177
5260325f 178/*
179 * Generic signal handler for terminating signals in the master daemon.
180 * These close the listen socket; not closing it seems to cause "Address
181 * already in use" problems on some machines, which is inconvenient.
182 */
183void
184sigterm_handler(int sig)
8efc0c15 185{
5260325f 186 log("Received signal %d; terminating.", sig);
48e671d5 187 close_listen_socks();
5260325f 188 exit(255);
8efc0c15 189}
190
5260325f 191/*
192 * SIGCHLD handler. This is called whenever a child dies. This will then
193 * reap any zombies left by exited c.
194 */
195void
196main_sigchld_handler(int sig)
8efc0c15 197{
5260325f 198 int save_errno = errno;
199 int status;
5ad13cd7 200
5260325f 201 while (waitpid(-1, &status, WNOHANG) > 0)
202 ;
5ad13cd7 203
5260325f 204 signal(SIGCHLD, main_sigchld_handler);
205 errno = save_errno;
8efc0c15 206}
207
5260325f 208/*
209 * Signal handler for the alarm after the login grace period has expired.
210 */
211void
212grace_alarm_handler(int sig)
8efc0c15 213{
5260325f 214 /* Close the connection. */
215 packet_close();
8efc0c15 216
5260325f 217 /* Log error and exit. */
218 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
219}
8efc0c15 220
5260325f 221/*
222 * Signal handler for the key regeneration alarm. Note that this
223 * alarm only occurs in the daemon waiting for connections, and it does not
224 * do anything with the private key or random state before forking.
225 * Thus there should be no concurrency control/asynchronous execution
226 * problems.
227 */
228void
229key_regeneration_alarm(int sig)
230{
231 int save_errno = errno;
232
233 /* Check if we should generate a new key. */
234 if (key_used) {
235 /* This should really be done in the background. */
236 log("Generating new %d bit RSA key.", options.server_key_bits);
237
238 if (sensitive_data.private_key != NULL)
239 RSA_free(sensitive_data.private_key);
240 sensitive_data.private_key = RSA_new();
241
242 if (public_key != NULL)
243 RSA_free(public_key);
244 public_key = RSA_new();
245
246 rsa_generate_key(sensitive_data.private_key, public_key,
247 options.server_key_bits);
248 arc4random_stir();
249 key_used = 0;
250 log("RSA key generation complete.");
251 }
252 /* Reschedule the alarm. */
253 signal(SIGALRM, key_regeneration_alarm);
254 alarm(options.key_regeneration_time);
255 errno = save_errno;
256}
8efc0c15 257
7368a6c8 258void
259sshd_exchange_identification(int sock_in, int sock_out)
260{
261 int i;
262 int remote_major, remote_minor;
263 char *s;
264 char buf[256]; /* Must not be larger than remote_version. */
265 char remote_version[256]; /* Must be at least as big as buf. */
266
267 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
268 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
269 server_version_string = xstrdup(buf);
270
271 if (client_version_string == NULL) {
272 /* Send our protocol version identification. */
273 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
274 != strlen(server_version_string)) {
275 log("Could not write ident string to %s.", get_remote_ipaddr());
276 fatal_cleanup();
277 }
278
279 /* Read other side\'s version identification. */
280 for (i = 0; i < sizeof(buf) - 1; i++) {
281 if (read(sock_in, &buf[i], 1) != 1) {
282 log("Did not receive ident string from %s.", get_remote_ipaddr());
283 fatal_cleanup();
284 }
285 if (buf[i] == '\r') {
286 buf[i] = '\n';
287 buf[i + 1] = 0;
288 continue;
289 /*break; XXX eat \r */
290 }
291 if (buf[i] == '\n') {
292 /* buf[i] == '\n' */
293 buf[i + 1] = 0;
294 break;
295 }
296 }
297 buf[sizeof(buf) - 1] = 0;
298 client_version_string = xstrdup(buf);
299 }
300
301 /*
302 * Check that the versions match. In future this might accept
303 * several versions and set appropriate flags to handle them.
304 */
305 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
306 &remote_major, &remote_minor, remote_version) != 3) {
307 s = "Protocol mismatch.\n";
308 (void) atomicio(write, sock_out, s, strlen(s));
309 close(sock_in);
310 close(sock_out);
311 log("Bad protocol version identification '%.100s' from %s",
312 client_version_string, get_remote_ipaddr());
313 fatal_cleanup();
314 }
315 debug("Client protocol version %d.%d; client software version %.100s",
316 remote_major, remote_minor, remote_version);
317
318 switch(remote_major) {
319 case 1:
320 if (remote_minor < 3) {
321 packet_disconnect("Your ssh version is too old and"
322 "is no longer supported. Please install a newer version.");
323 } else if (remote_minor == 3) {
324 /* note that this disables agent-forwarding */
325 enable_compat13();
326 }
327 break;
328 default:
329 s = "Protocol major versions differ.\n";
330 (void) atomicio(write, sock_out, s, strlen(s));
331 close(sock_in);
332 close(sock_out);
333 log("Protocol major versions differ for %s: %d vs. %d",
334 get_remote_ipaddr(), PROTOCOL_MAJOR, remote_major);
335 fatal_cleanup();
336 break;
337 }
338}
339
5260325f 340/*
341 * Main program for the daemon.
342 */
8efc0c15 343int
344main(int ac, char **av)
345{
5260325f 346 extern char *optarg;
347 extern int optind;
48e671d5 348 int opt, sock_in = 0, sock_out = 0, newsock, i, fdsetsz, pid, on = 1;
349 socklen_t fromlen;
5260325f 350 int silentrsa = 0;
48e671d5 351 fd_set *fdset;
352 struct sockaddr_storage from;
5260325f 353 const char *remote_ip;
354 int remote_port;
355 char *comment;
356 FILE *f;
357 struct linger linger;
48e671d5 358 struct addrinfo *ai;
359 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
360 int listen_sock, maxfd;
5260325f 361
362 /* Save argv[0]. */
363 saved_argv = av;
364 if (strchr(av[0], '/'))
365 av0 = strrchr(av[0], '/') + 1;
366 else
367 av0 = av[0];
368
369 /* Initialize configuration options to their default values. */
370 initialize_server_options(&options);
371
372 /* Parse command-line arguments. */
48e671d5 373 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ46")) != EOF) {
5260325f 374 switch (opt) {
48e671d5 375 case '4':
376 IPv4or6 = AF_INET;
377 break;
378 case '6':
379 IPv4or6 = AF_INET6;
380 break;
5260325f 381 case 'f':
382 config_file_name = optarg;
383 break;
384 case 'd':
385 debug_flag = 1;
386 options.log_level = SYSLOG_LEVEL_DEBUG;
387 break;
388 case 'i':
389 inetd_flag = 1;
390 break;
391 case 'Q':
392 silentrsa = 1;
393 break;
394 case 'q':
395 options.log_level = SYSLOG_LEVEL_QUIET;
396 break;
397 case 'b':
398 options.server_key_bits = atoi(optarg);
399 break;
400 case 'p':
48e671d5 401 options.ports_from_cmdline = 1;
402 if (options.num_ports >= MAX_PORTS)
403 fatal("too many ports.\n");
404 options.ports[options.num_ports++] = atoi(optarg);
5260325f 405 break;
406 case 'g':
407 options.login_grace_time = atoi(optarg);
408 break;
409 case 'k':
410 options.key_regeneration_time = atoi(optarg);
411 break;
412 case 'h':
413 options.host_key_file = optarg;
414 break;
415 case 'V':
416 client_version_string = optarg;
417 /* only makes sense with inetd_flag, i.e. no listen() */
418 inetd_flag = 1;
419 break;
420 case '?':
421 default:
422 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
423 fprintf(stderr, "Usage: %s [options]\n", av0);
424 fprintf(stderr, "Options:\n");
aa3378df 425 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE);
5260325f 426 fprintf(stderr, " -d Debugging mode\n");
427 fprintf(stderr, " -i Started from inetd\n");
428 fprintf(stderr, " -q Quiet (no logging)\n");
429 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
430 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
431 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
432 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
433 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
48e671d5 434 HOST_KEY_FILE);
435 fprintf(stderr, " -4 Use IPv4 only\n");
436 fprintf(stderr, " -6 Use IPv6 only\n");
5260325f 437 exit(1);
438 }
439 }
440
48e671d5 441 /*
442 * Force logging to stderr until we have loaded the private host
443 * key (unless started from inetd)
444 */
445 log_init(av0,
446 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
447 options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
448 !inetd_flag);
449
5260325f 450 /* check if RSA support exists */
451 if (rsa_alive() == 0) {
452 if (silentrsa == 0)
453 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
454 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
455 exit(1);
456 }
457 /* Read server configuration options from the configuration file. */
458 read_server_config(&options, config_file_name);
459
460 /* Fill in default values for those options not explicitly set. */
461 fill_default_server_options(&options);
462
463 /* Check certain values for sanity. */
464 if (options.server_key_bits < 512 ||
465 options.server_key_bits > 32768) {
466 fprintf(stderr, "Bad server key size.\n");
467 exit(1);
468 }
5260325f 469 /* Check that there are no remaining arguments. */
470 if (optind < ac) {
471 fprintf(stderr, "Extra argument %s.\n", av[optind]);
472 exit(1);
8efc0c15 473 }
5260325f 474
475 debug("sshd version %.100s", SSH_VERSION);
476
477 sensitive_data.host_key = RSA_new();
478 errno = 0;
479 /* Load the host key. It must have empty passphrase. */
480 if (!load_private_key(options.host_key_file, "",
481 sensitive_data.host_key, &comment)) {
482 error("Could not load host key: %.200s: %.100s",
483 options.host_key_file, strerror(errno));
484 exit(1);
485 }
486 xfree(comment);
487
488 /* Initialize the log (it is reinitialized below in case we
489 forked). */
490 if (debug_flag && !inetd_flag)
491 log_stderr = 1;
492 log_init(av0, options.log_level, options.log_facility, log_stderr);
493
494 /* If not in debugging mode, and not started from inetd,
495 disconnect from the controlling terminal, and fork. The
496 original process exits. */
497 if (!debug_flag && !inetd_flag) {
8efc0c15 498#ifdef TIOCNOTTY
5260325f 499 int fd;
8efc0c15 500#endif /* TIOCNOTTY */
5260325f 501 if (daemon(0, 0) < 0)
502 fatal("daemon() failed: %.200s", strerror(errno));
503
504 /* Disconnect from the controlling tty. */
8efc0c15 505#ifdef TIOCNOTTY
5260325f 506 fd = open("/dev/tty", O_RDWR | O_NOCTTY);
507 if (fd >= 0) {
508 (void) ioctl(fd, TIOCNOTTY, NULL);
509 close(fd);
510 }
8efc0c15 511#endif /* TIOCNOTTY */
8efc0c15 512 }
5260325f 513 /* Reinitialize the log (because of the fork above). */
514 log_init(av0, options.log_level, options.log_facility, log_stderr);
515
516 /* Check that server and host key lengths differ sufficiently.
517 This is necessary to make double encryption work with rsaref.
518 Oh, I hate software patents. I dont know if this can go? Niels */
519 if (options.server_key_bits >
520 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
521 options.server_key_bits <
522 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
523 options.server_key_bits =
524 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
525 debug("Forcing server key to %d bits to make it differ from host key.",
526 options.server_key_bits);
8efc0c15 527 }
5260325f 528 /* Do not display messages to stdout in RSA code. */
529 rsa_set_verbose(0);
530
531 /* Initialize the random number generator. */
532 arc4random_stir();
533
534 /* Chdir to the root directory so that the current disk can be
535 unmounted if desired. */
536 chdir("/");
537
5260325f 538 /* Start listening for a socket, unless started from inetd. */
539 if (inetd_flag) {
540 int s1, s2;
541 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
542 s2 = dup(s1);
543 sock_in = dup(0);
544 sock_out = dup(1);
545 /* We intentionally do not close the descriptors 0, 1, and 2
546 as our code for setting the descriptors won\'t work
547 if ttyfd happens to be one of those. */
548 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
549
550 public_key = RSA_new();
551 sensitive_data.private_key = RSA_new();
552
553 log("Generating %d bit RSA key.", options.server_key_bits);
554 rsa_generate_key(sensitive_data.private_key, public_key,
555 options.server_key_bits);
556 arc4random_stir();
557 log("RSA key generation complete.");
558 } else {
48e671d5 559 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
560 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
561 continue;
562 if (num_listen_socks >= MAX_LISTEN_SOCKS)
563 fatal("Too many listen sockets. "
564 "Enlarge MAX_LISTEN_SOCKS");
565 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
566 ntop, sizeof(ntop), strport, sizeof(strport),
567 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
568 error("getnameinfo failed");
569 continue;
570 }
571 /* Create socket for listening. */
572 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
573 if (listen_sock < 0) {
574 /* kernel may not support ipv6 */
575 verbose("socket: %.100s", strerror(errno));
576 continue;
577 }
578 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
579 error("listen_sock O_NONBLOCK: %s", strerror(errno));
580 close(listen_sock);
581 continue;
582 }
583 /*
584 * Set socket options. We try to make the port
585 * reusable and have it close as fast as possible
586 * without waiting in unnecessary wait states on
587 * close.
588 */
589 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
590 (void *) &on, sizeof(on));
591 linger.l_onoff = 1;
592 linger.l_linger = 5;
593 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
594 (void *) &linger, sizeof(linger));
595
596 debug("Bind to port %s on %s.", strport, ntop);
597
598 /* Bind the socket to the desired port. */
16218745 599 if ((bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) &&
600 (!ai->ai_next)) {
48e671d5 601 error("Bind to port %s on %s failed: %.200s.",
602 strport, ntop, strerror(errno));
603 close(listen_sock);
604 continue;
605 }
606 listen_socks[num_listen_socks] = listen_sock;
607 num_listen_socks++;
608
609 /* Start listening on the port. */
610 log("Server listening on %s port %s.", ntop, strport);
611 if (listen(listen_sock, 5) < 0)
612 fatal("listen: %.100s", strerror(errno));
613
5260325f 614 }
48e671d5 615 freeaddrinfo(options.listen_addrs);
616
617 if (!num_listen_socks)
618 fatal("Cannot bind any address.");
619
5260325f 620 if (!debug_flag) {
aa3378df 621 /*
622 * Record our pid in /etc/sshd_pid to make it easier
623 * to kill the correct sshd. We don\'t want to do
624 * this before the bind above because the bind will
625 * fail if there already is a daemon, and this will
626 * overwrite any old pid in the file.
627 */
5260325f 628 f = fopen(SSH_DAEMON_PID_FILE, "w");
629 if (f) {
630 fprintf(f, "%u\n", (unsigned int) getpid());
631 fclose(f);
632 }
8efc0c15 633 }
8efc0c15 634
5260325f 635 public_key = RSA_new();
636 sensitive_data.private_key = RSA_new();
637
638 log("Generating %d bit RSA key.", options.server_key_bits);
639 rsa_generate_key(sensitive_data.private_key, public_key,
640 options.server_key_bits);
641 arc4random_stir();
642 log("RSA key generation complete.");
643
644 /* Schedule server key regeneration alarm. */
645 signal(SIGALRM, key_regeneration_alarm);
646 alarm(options.key_regeneration_time);
647
648 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
649 signal(SIGHUP, sighup_handler);
650 signal(SIGTERM, sigterm_handler);
651 signal(SIGQUIT, sigterm_handler);
652
653 /* Arrange SIGCHLD to be caught. */
654 signal(SIGCHLD, main_sigchld_handler);
655
48e671d5 656 /* setup fd set for listen */
657 maxfd = 0;
658 for (i = 0; i < num_listen_socks; i++)
659 if (listen_socks[i] > maxfd)
660 maxfd = listen_socks[i];
661 fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
662 fdset = (fd_set *)xmalloc(fdsetsz);
663
aa3378df 664 /*
665 * Stay listening for connections until the system crashes or
666 * the daemon is killed with a signal.
667 */
5260325f 668 for (;;) {
669 if (received_sighup)
670 sighup_restart();
48e671d5 671 /* Wait in select until there is a connection. */
672 memset(fdset, 0, fdsetsz);
673 for (i = 0; i < num_listen_socks; i++)
674 FD_SET(listen_socks[i], fdset);
675 if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
676 if (errno != EINTR)
677 error("select: %.100s", strerror(errno));
2d86a6cc 678 continue;
48e671d5 679 }
680 for (i = 0; i < num_listen_socks; i++) {
681 if (!FD_ISSET(listen_socks[i], fdset))
5260325f 682 continue;
48e671d5 683 fromlen = sizeof(from);
684 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
685 &fromlen);
686 if (newsock < 0) {
687 if (errno != EINTR && errno != EWOULDBLOCK)
688 error("accept: %.100s", strerror(errno));
689 continue;
690 }
691 if (fcntl(newsock, F_SETFL, 0) < 0) {
692 error("newsock del O_NONBLOCK: %s", strerror(errno));
5260325f 693 continue;
694 }
aa3378df 695 /*
696 * Got connection. Fork a child to handle it, unless
697 * we are in debugging mode.
698 */
5260325f 699 if (debug_flag) {
aa3378df 700 /*
701 * In debugging mode. Close the listening
702 * socket, and start processing the
703 * connection without forking.
704 */
5260325f 705 debug("Server will not fork when running in debugging mode.");
48e671d5 706 close_listen_socks();
5260325f 707 sock_in = newsock;
708 sock_out = newsock;
709 pid = getpid();
710 break;
711 } else {
aa3378df 712 /*
713 * Normal production daemon. Fork, and have
714 * the child process the connection. The
715 * parent continues listening.
716 */
5260325f 717 if ((pid = fork()) == 0) {
aa3378df 718 /*
719 * Child. Close the listening socket, and start using the
720 * accepted socket. Reinitialize logging (since our pid has
721 * changed). We break out of the loop to handle the connection.
722 */
48e671d5 723 close_listen_socks();
5260325f 724 sock_in = newsock;
725 sock_out = newsock;
726 log_init(av0, options.log_level, options.log_facility, log_stderr);
727 break;
728 }
729 }
730
731 /* Parent. Stay in the loop. */
732 if (pid < 0)
733 error("fork: %.100s", strerror(errno));
734 else
735 debug("Forked child %d.", pid);
736
737 /* Mark that the key has been used (it was "given" to the child). */
738 key_used = 1;
739
740 arc4random_stir();
741
742 /* Close the new socket (the child is now taking care of it). */
743 close(newsock);
48e671d5 744 } /* for (i = 0; i < num_listen_socks; i++) */
745 /* child process check (or debug mode) */
746 if (num_listen_socks < 0)
747 break;
5260325f 748 }
749 }
8efc0c15 750
5260325f 751 /* This is the child processing a new connection. */
752
aa3378df 753 /*
754 * Disable the key regeneration alarm. We will not regenerate the
755 * key since we are no longer in a position to give it to anyone. We
756 * will not restart on SIGHUP since it no longer makes sense.
757 */
5260325f 758 alarm(0);
759 signal(SIGALRM, SIG_DFL);
760 signal(SIGHUP, SIG_DFL);
761 signal(SIGTERM, SIG_DFL);
762 signal(SIGQUIT, SIG_DFL);
763 signal(SIGCHLD, SIG_DFL);
764
aa3378df 765 /*
766 * Set socket options for the connection. We want the socket to
767 * close as fast as possible without waiting for anything. If the
768 * connection is not a socket, these will do nothing.
769 */
770 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
5260325f 771 linger.l_onoff = 1;
772 linger.l_linger = 5;
773 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
774
aa3378df 775 /*
776 * Register our connection. This turns encryption off because we do
777 * not have a key.
778 */
5260325f 779 packet_set_connection(sock_in, sock_out);
780
781 remote_port = get_remote_port();
782 remote_ip = get_remote_ipaddr();
783
784 /* Check whether logins are denied from this host. */
785#ifdef LIBWRAP
48e671d5 786 /* XXX LIBWRAP noes not know about IPv6 */
5260325f 787 {
788 struct request_info req;
8efc0c15 789
5260325f 790 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
791 fromhost(&req);
8efc0c15 792
5260325f 793 if (!hosts_access(&req)) {
794 close(sock_in);
795 close(sock_out);
796 refuse(&req);
797 }
48e671d5 798/*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
8efc0c15 799 }
48e671d5 800#endif /* LIBWRAP */
5260325f 801 /* Log the connection. */
802 verbose("Connection from %.500s port %d", remote_ip, remote_port);
8efc0c15 803
aa3378df 804 /*
805 * We don\'t want to listen forever unless the other side
806 * successfully authenticates itself. So we set up an alarm which is
807 * cleared after successful authentication. A limit of zero
808 * indicates no limit. Note that we don\'t set the alarm in debugging
809 * mode; it is just annoying to have the server exit just when you
810 * are about to discover the bug.
811 */
5260325f 812 signal(SIGALRM, grace_alarm_handler);
813 if (!debug_flag)
814 alarm(options.login_grace_time);
815
7368a6c8 816 sshd_exchange_identification(sock_in, sock_out);
aa3378df 817 /*
818 * Check that the connection comes from a privileged port. Rhosts-
819 * and Rhosts-RSA-Authentication only make sense from priviledged
820 * programs. Of course, if the intruder has root access on his local
821 * machine, he can connect from any port. So do not use these
822 * authentication methods from machines that you do not trust.
823 */
5260325f 824 if (remote_port >= IPPORT_RESERVED ||
825 remote_port < IPPORT_RESERVED / 2) {
826 options.rhosts_authentication = 0;
827 options.rhosts_rsa_authentication = 0;
828 }
48e671d5 829#ifdef KRB4
830 if (!packet_connection_is_ipv4() &&
831 options.kerberos_authentication) {
832 debug("Kerberos Authentication disabled, only available for IPv4.");
833 options.kerberos_authentication = 0;
834 }
835#endif /* KRB4 */
836
5260325f 837 packet_set_nonblocking();
838
7b2ea3a1 839 /* perform the key exchange */
7368a6c8 840 do_ssh1_kex();
7b2ea3a1 841 /* authenticate user and start session */
842 do_authentication();
8efc0c15 843
844#ifdef KRB4
5260325f 845 /* Cleanup user's ticket cache file. */
846 if (options.kerberos_ticket_cleanup)
847 (void) dest_tkt();
8efc0c15 848#endif /* KRB4 */
849
5260325f 850 /* The connection has been terminated. */
851 verbose("Closing connection to %.100s", remote_ip);
8efc0c15 852
d94aa2ae 853#ifdef USE_PAM
a5c9cd31 854 finish_pam();
d94aa2ae 855#endif /* USE_PAM */
8efc0c15 856
5260325f 857 packet_close();
858 exit(0);
859}
8efc0c15 860
5260325f 861/*
7b2ea3a1 862 * SSH1 key exchange
5260325f 863 */
e7c0f9d5 864void
7368a6c8 865do_ssh1_kex()
8efc0c15 866{
5260325f 867 int i, len;
7b2ea3a1 868 int plen, slen;
5260325f 869 BIGNUM *session_key_int;
870 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
7b2ea3a1 871 unsigned char cookie[8];
5260325f 872 unsigned int cipher_type, auth_mask, protocol_flags;
5260325f 873 u_int32_t rand = 0;
874
aa3378df 875 /*
876 * Generate check bytes that the client must send back in the user
877 * packet in order for it to be accepted; this is used to defy ip
878 * spoofing attacks. Note that this only works against somebody
879 * doing IP spoofing from a remote machine; any machine on the local
880 * network can still see outgoing packets and catch the random
881 * cookie. This only affects rhosts authentication, and this is one
882 * of the reasons why it is inherently insecure.
883 */
5260325f 884 for (i = 0; i < 8; i++) {
885 if (i % 4 == 0)
886 rand = arc4random();
7b2ea3a1 887 cookie[i] = rand & 0xff;
5260325f 888 rand >>= 8;
889 }
890
aa3378df 891 /*
892 * Send our public key. We include in the packet 64 bits of random
893 * data that must be matched in the reply in order to prevent IP
894 * spoofing.
895 */
5260325f 896 packet_start(SSH_SMSG_PUBLIC_KEY);
897 for (i = 0; i < 8; i++)
7b2ea3a1 898 packet_put_char(cookie[i]);
5260325f 899
900 /* Store our public server RSA key. */
901 packet_put_int(BN_num_bits(public_key->n));
902 packet_put_bignum(public_key->e);
903 packet_put_bignum(public_key->n);
904
905 /* Store our public host RSA key. */
906 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
907 packet_put_bignum(sensitive_data.host_key->e);
908 packet_put_bignum(sensitive_data.host_key->n);
909
910 /* Put protocol flags. */
911 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
912
913 /* Declare which ciphers we support. */
8ce64345 914 packet_put_int(cipher_mask1());
5260325f 915
916 /* Declare supported authentication types. */
917 auth_mask = 0;
918 if (options.rhosts_authentication)
919 auth_mask |= 1 << SSH_AUTH_RHOSTS;
920 if (options.rhosts_rsa_authentication)
921 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
922 if (options.rsa_authentication)
923 auth_mask |= 1 << SSH_AUTH_RSA;
8efc0c15 924#ifdef KRB4
5260325f 925 if (options.kerberos_authentication)
926 auth_mask |= 1 << SSH_AUTH_KERBEROS;
8efc0c15 927#endif
928#ifdef AFS
5260325f 929 if (options.kerberos_tgt_passing)
930 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
931 if (options.afs_token_passing)
932 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
8efc0c15 933#endif
5260325f 934#ifdef SKEY
935 if (options.skey_authentication == 1)
936 auth_mask |= 1 << SSH_AUTH_TIS;
937#endif
938 if (options.password_authentication)
939 auth_mask |= 1 << SSH_AUTH_PASSWORD;
940 packet_put_int(auth_mask);
941
942 /* Send the packet and wait for it to be sent. */
943 packet_send();
944 packet_write_wait();
945
946 debug("Sent %d bit public key and %d bit host key.",
947 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
948
949 /* Read clients reply (cipher type and session key). */
950 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
951
2d86a6cc 952 /* Get cipher type and check whether we accept this. */
5260325f 953 cipher_type = packet_get_char();
954
2d86a6cc 955 if (!(cipher_mask() & (1 << cipher_type)))
956 packet_disconnect("Warning: client selects unsupported cipher.");
957
5260325f 958 /* Get check bytes from the packet. These must match those we
959 sent earlier with the public key packet. */
960 for (i = 0; i < 8; i++)
7b2ea3a1 961 if (cookie[i] != packet_get_char())
5260325f 962 packet_disconnect("IP Spoofing check bytes do not match.");
963
964 debug("Encryption type: %.200s", cipher_name(cipher_type));
965
966 /* Get the encrypted integer. */
967 session_key_int = BN_new();
968 packet_get_bignum(session_key_int, &slen);
969
5260325f 970 protocol_flags = packet_get_int();
971 packet_set_protocol_flags(protocol_flags);
972
973 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
974
aa3378df 975 /*
976 * Decrypt it using our private server key and private host key (key
977 * with larger modulus first).
978 */
5260325f 979 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
980 /* Private key has bigger modulus. */
981 if (BN_num_bits(sensitive_data.private_key->n) <
982 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
983 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
984 get_remote_ipaddr(),
985 BN_num_bits(sensitive_data.private_key->n),
986 BN_num_bits(sensitive_data.host_key->n),
987 SSH_KEY_BITS_RESERVED);
988 }
989 rsa_private_decrypt(session_key_int, session_key_int,
990 sensitive_data.private_key);
991 rsa_private_decrypt(session_key_int, session_key_int,
992 sensitive_data.host_key);
993 } else {
994 /* Host key has bigger modulus (or they are equal). */
995 if (BN_num_bits(sensitive_data.host_key->n) <
996 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
997 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
998 get_remote_ipaddr(),
999 BN_num_bits(sensitive_data.host_key->n),
1000 BN_num_bits(sensitive_data.private_key->n),
1001 SSH_KEY_BITS_RESERVED);
1002 }
1003 rsa_private_decrypt(session_key_int, session_key_int,
1004 sensitive_data.host_key);
1005 rsa_private_decrypt(session_key_int, session_key_int,
1006 sensitive_data.private_key);
1007 }
1008
7b2ea3a1 1009 compute_session_id(session_id, cookie,
5260325f 1010 sensitive_data.host_key->n,
1011 sensitive_data.private_key->n);
1012
7b2ea3a1 1013 /* Destroy the private and public keys. They will no longer be needed. */
1014 RSA_free(public_key);
1015 RSA_free(sensitive_data.private_key);
1016 RSA_free(sensitive_data.host_key);
1017
aa3378df 1018 /*
1019 * Extract session key from the decrypted integer. The key is in the
1020 * least significant 256 bits of the integer; the first byte of the
1021 * key is in the highest bits.
1022 */
5260325f 1023 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1024 len = BN_num_bytes(session_key_int);
1025 if (len < 0 || len > sizeof(session_key))
1026 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1027 get_remote_ipaddr(),
1028 len, sizeof(session_key));
1029 memset(session_key, 0, sizeof(session_key));
1030 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1031
7b2ea3a1 1032 /* Destroy the decrypted integer. It is no longer needed. */
1033 BN_clear_free(session_key_int);
1034
5260325f 1035 /* Xor the first 16 bytes of the session key with the session id. */
1036 for (i = 0; i < 16; i++)
1037 session_key[i] ^= session_id[i];
1038
5260325f 1039 /* Set the session key. From this on all communications will be encrypted. */
1040 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1041
1042 /* Destroy our copy of the session key. It is no longer needed. */
1043 memset(session_key, 0, sizeof(session_key));
1044
1045 debug("Received session key; encryption turned on.");
1046
1047 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1048 packet_start(SSH_SMSG_SUCCESS);
1049 packet_send();
1050 packet_write_wait();
5260325f 1051}
This page took 0.883635 seconds and 5 git commands to generate.