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