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