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