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