]> andersk Git - gssapi-openssh.git/blob - openssh/sshd.c
resolving conflicts from import of OpenSSH 3.1p1
[gssapi-openssh.git] / openssh / 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  * This program is the ssh daemon.  It listens for connections from clients,
6  * and performs authentication, executes use commands or shell, and forwards
7  * information to/from the application to the user client over an encrypted
8  * connection.  This can also handle forwarding of X11, TCP/IP, and
9  * authentication agent connections.
10  *
11  * As far as I am concerned, the code I have written for this software
12  * can be used freely for any purpose.  Any derived versions of this
13  * software must be clearly marked as such, and if the derived work is
14  * incompatible with the protocol description in the RFC file, it must be
15  * called by a name other than "ssh" or "Secure Shell".
16  *
17  * SSH2 implementation:
18  *
19  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  */
41
42 #include "includes.h"
43 RCSID("$OpenBSD: sshd.c,v 1.228 2002/02/27 21:23:13 stevesk Exp $");
44
45 #include <openssl/dh.h>
46 #include <openssl/bn.h>
47 #include <openssl/md5.h>
48
49 #include "ssh.h"
50 #include "ssh1.h"
51 #include "ssh2.h"
52 #include "xmalloc.h"
53 #include "rsa.h"
54 #include "sshpty.h"
55 #include "packet.h"
56 #include "mpaux.h"
57 #include "log.h"
58 #include "servconf.h"
59 #include "uidswap.h"
60 #include "compat.h"
61 #include "buffer.h"
62 #include "cipher.h"
63 #include "kex.h"
64 #include "key.h"
65 #include "dh.h"
66 #include "myproposal.h"
67 #include "authfile.h"
68 #include "pathnames.h"
69 #include "atomicio.h"
70 #include "canohost.h"
71 #include "auth.h"
72 #include "misc.h"
73 #include "dispatch.h"
74 #include "channels.h"
75
76 #ifdef GSSAPI
77 #include "ssh-gss.h"
78 #endif
79
80 #ifdef LIBWRAP
81 #include <tcpd.h>
82 #include <syslog.h>
83 int allow_severity = LOG_INFO;
84 int deny_severity = LOG_WARNING;
85 #endif /* LIBWRAP */
86
87 #ifndef O_NOCTTY
88 #define O_NOCTTY        0
89 #endif
90
91 #ifdef HAVE___PROGNAME
92 extern char *__progname;
93 #else
94 char *__progname;
95 #endif
96
97 /* Server configuration options. */
98 ServerOptions options;
99
100 /* Name of the server configuration file. */
101 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
102
103 /*
104  * Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
105  * Default value is AF_UNSPEC means both IPv4 and IPv6.
106  */
107 #ifdef IPV4_DEFAULT
108 int IPv4or6 = AF_INET;
109 #else
110 int IPv4or6 = AF_UNSPEC;
111 #endif
112
113 /*
114  * Debug mode flag.  This can be set on the command line.  If debug
115  * mode is enabled, extra debugging output will be sent to the system
116  * log, the daemon will not go to background, and will exit after processing
117  * the first connection.
118  */
119 int debug_flag = 0;
120
121 /* Flag indicating that the daemon should only test the configuration and keys. */
122 int test_flag = 0;
123
124 /* Flag indicating that the daemon is being started from inetd. */
125 int inetd_flag = 0;
126
127 /* Flag indicating that sshd should not detach and become a daemon. */
128 int no_daemon_flag = 0;
129
130 /* debug goes to stderr unless inetd_flag is set */
131 int log_stderr = 0;
132
133 /* Saved arguments to main(). */
134 char **saved_argv;
135 int saved_argc;
136
137 /*
138  * The sockets that the server is listening; this is used in the SIGHUP
139  * signal handler.
140  */
141 #define MAX_LISTEN_SOCKS        16
142 int listen_socks[MAX_LISTEN_SOCKS];
143 int num_listen_socks = 0;
144
145 /*
146  * the client's version string, passed by sshd2 in compat mode. if != NULL,
147  * sshd will skip the version-number exchange
148  */
149 char *client_version_string = NULL;
150 char *server_version_string = NULL;
151
152 /* for rekeying XXX fixme */
153 Kex *xxx_kex;
154
155 /*
156  * Any really sensitive data in the application is contained in this
157  * structure. The idea is that this structure could be locked into memory so
158  * that the pages do not get written into swap.  However, there are some
159  * problems. The private key contains BIGNUMs, and we do not (in principle)
160  * have access to the internals of them, and locking just the structure is
161  * not very useful.  Currently, memory locking is not implemented.
162  */
163 struct {
164         Key     *server_key;            /* ephemeral server key */
165         Key     *ssh1_host_key;         /* ssh1 host key */
166         Key     **host_keys;            /* all private host keys */
167         int     have_ssh1_key;
168         int     have_ssh2_key;
169         u_char  ssh1_cookie[SSH_SESSION_KEY_LENGTH];
170 } sensitive_data;
171
172 /*
173  * Flag indicating whether the RSA server key needs to be regenerated.
174  * Is set in the SIGALRM handler and cleared when the key is regenerated.
175  */
176 static volatile sig_atomic_t key_do_regen = 0;
177
178 /* This is set to true when a signal is received. */
179 static volatile sig_atomic_t received_sighup = 0;
180 static volatile sig_atomic_t received_sigterm = 0;
181
182 /* session identifier, used by RSA-auth */
183 u_char session_id[16];
184
185 /* same for ssh2 */
186 u_char *session_id2 = NULL;
187 int session_id2_len = 0;
188
189 /* record remote hostname or ip */
190 u_int utmp_len = MAXHOSTNAMELEN;
191
192 /* options.max_startup sized array of fd ints */
193 int *startup_pipes = NULL;
194 int startup_pipe;               /* in child */
195
196 /* Prototypes for various functions defined later in this file. */
197 void destroy_sensitive_data(void);
198
199 static void do_ssh1_kex(void);
200 static void do_ssh2_kex(void);
201
202 /*
203  * Close all listening sockets
204  */
205 static void
206 close_listen_socks(void)
207 {
208         int i;
209         for (i = 0; i < num_listen_socks; i++)
210                 close(listen_socks[i]);
211         num_listen_socks = -1;
212 }
213
214 static void
215 close_startup_pipes(void)
216 {
217         int i;
218         if (startup_pipes)
219                 for (i = 0; i < options.max_startups; i++)
220                         if (startup_pipes[i] != -1)
221                                 close(startup_pipes[i]);
222 }
223
224 /*
225  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
226  * the effect is to reread the configuration file (and to regenerate
227  * the server key).
228  */
229 static void
230 sighup_handler(int sig)
231 {
232         int save_errno = errno;
233
234         received_sighup = 1;
235         signal(SIGHUP, sighup_handler);
236         errno = save_errno;
237 }
238
239 /*
240  * Called from the main program after receiving SIGHUP.
241  * Restarts the server.
242  */
243 static void
244 sighup_restart(void)
245 {
246         log("Received SIGHUP; restarting.");
247         close_listen_socks();
248         close_startup_pipes();
249         execv(saved_argv[0], saved_argv);
250         log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], strerror(errno));
251         exit(1);
252 }
253
254 /*
255  * Generic signal handler for terminating signals in the master daemon.
256  */
257 static void
258 sigterm_handler(int sig)
259 {
260         received_sigterm = sig;
261 }
262
263 /*
264  * SIGCHLD handler.  This is called whenever a child dies.  This will then
265  * reap any zombies left by exited children.
266  */
267 static void
268 main_sigchld_handler(int sig)
269 {
270         int save_errno = errno;
271         int status;
272
273         while (waitpid(-1, &status, WNOHANG) > 0)
274                 ;
275
276         signal(SIGCHLD, main_sigchld_handler);
277         errno = save_errno;
278 }
279
280 /*
281  * Signal handler for the alarm after the login grace period has expired.
282  */
283 static void
284 grace_alarm_handler(int sig)
285 {
286         /* XXX no idea how fix this signal handler */
287
288         /* Close the connection. */
289         packet_close();
290
291         /* Log error and exit. */
292         fatal("Timeout before authentication for %s.", get_remote_ipaddr());
293 }
294
295 /*
296  * Signal handler for the key regeneration alarm.  Note that this
297  * alarm only occurs in the daemon waiting for connections, and it does not
298  * do anything with the private key or random state before forking.
299  * Thus there should be no concurrency control/asynchronous execution
300  * problems.
301  */
302 static void
303 generate_ephemeral_server_key(void)
304 {
305         u_int32_t rand = 0;
306         int i;
307
308         verbose("Generating %s%d bit RSA key.",
309             sensitive_data.server_key ? "new " : "", options.server_key_bits);
310         if (sensitive_data.server_key != NULL)
311                 key_free(sensitive_data.server_key);
312         sensitive_data.server_key = key_generate(KEY_RSA1,
313             options.server_key_bits);
314         verbose("RSA key generation complete.");
315
316         for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
317                 if (i % 4 == 0)
318                         rand = arc4random();
319                 sensitive_data.ssh1_cookie[i] = rand & 0xff;
320                 rand >>= 8;
321         }
322         arc4random_stir();
323 }
324
325 static void
326 key_regeneration_alarm(int sig)
327 {
328         int save_errno = errno;
329         signal(SIGALRM, SIG_DFL);
330         errno = save_errno;
331         key_do_regen = 1;
332 }
333
334 static void
335 sshd_exchange_identification(int sock_in, int sock_out)
336 {
337         int i, mismatch;
338         int remote_major, remote_minor;
339         int major, minor;
340         char *s;
341         char buf[256];                  /* Must not be larger than remote_version. */
342         char remote_version[256];       /* Must be at least as big as buf. */
343
344         if ((options.protocol & SSH_PROTO_1) &&
345             (options.protocol & SSH_PROTO_2)) {
346                 major = PROTOCOL_MAJOR_1;
347                 minor = 99;
348         } else if (options.protocol & SSH_PROTO_2) {
349                 major = PROTOCOL_MAJOR_2;
350                 minor = PROTOCOL_MINOR_2;
351         } else {
352                 major = PROTOCOL_MAJOR_1;
353                 minor = PROTOCOL_MINOR_1;
354         }
355         snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
356         server_version_string = xstrdup(buf);
357
358         if (client_version_string == NULL) {
359                 /* Send our protocol version identification. */
360                 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
361                     != strlen(server_version_string)) {
362                         log("Could not write ident string to %s", get_remote_ipaddr());
363                         fatal_cleanup();
364                 }
365
366                 /* Read other side's version identification. */
367                 memset(buf, 0, sizeof(buf));
368                 for (i = 0; i < sizeof(buf) - 1; i++) {
369                         if (atomicio(read, sock_in, &buf[i], 1) != 1) {
370                                 log("Did not receive identification string from %s",
371                                     get_remote_ipaddr());
372                                 fatal_cleanup();
373                         }
374                         if (buf[i] == '\r') {
375                                 buf[i] = 0;
376                                 /* Kludge for F-Secure Macintosh < 1.0.2 */
377                                 if (i == 12 &&
378                                     strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
379                                         break;
380                                 continue;
381                         }
382                         if (buf[i] == '\n') {
383                                 buf[i] = 0;
384                                 break;
385                         }
386                 }
387                 buf[sizeof(buf) - 1] = 0;
388                 client_version_string = xstrdup(buf);
389         }
390
391         /*
392          * Check that the versions match.  In future this might accept
393          * several versions and set appropriate flags to handle them.
394          */
395         if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
396             &remote_major, &remote_minor, remote_version) != 3) {
397                 s = "Protocol mismatch.\n";
398                 (void) atomicio(write, sock_out, s, strlen(s));
399                 close(sock_in);
400                 close(sock_out);
401                 log("Bad protocol version identification '%.100s' from %s",
402                     client_version_string, get_remote_ipaddr());
403                 fatal_cleanup();
404         }
405         debug("Client protocol version %d.%d; client software version %.100s",
406             remote_major, remote_minor, remote_version);
407
408         compat_datafellows(remote_version);
409
410         if (datafellows & SSH_BUG_SCANNER) {
411                 log("scanned from %s with %s.  Don't panic.",
412                     get_remote_ipaddr(), client_version_string);
413                 fatal_cleanup();
414         }
415
416         mismatch = 0;
417         switch (remote_major) {
418         case 1:
419                 if (remote_minor == 99) {
420                         if (options.protocol & SSH_PROTO_2)
421                                 enable_compat20();
422                         else
423                                 mismatch = 1;
424                         break;
425                 }
426                 if (!(options.protocol & SSH_PROTO_1)) {
427                         mismatch = 1;
428                         break;
429                 }
430                 if (remote_minor < 3) {
431                         packet_disconnect("Your ssh version is too old and "
432                             "is no longer supported.  Please install a newer version.");
433                 } else if (remote_minor == 3) {
434                         /* note that this disables agent-forwarding */
435                         enable_compat13();
436                 }
437                 break;
438         case 2:
439                 if (options.protocol & SSH_PROTO_2) {
440                         enable_compat20();
441                         break;
442                 }
443                 /* FALLTHROUGH */
444         default:
445                 mismatch = 1;
446                 break;
447         }
448         chop(server_version_string);
449         debug("Local version string %.200s", server_version_string);
450
451         if (mismatch) {
452                 s = "Protocol major versions differ.\n";
453                 (void) atomicio(write, sock_out, s, strlen(s));
454                 close(sock_in);
455                 close(sock_out);
456                 log("Protocol major versions differ for %s: %.200s vs. %.200s",
457                     get_remote_ipaddr(),
458                     server_version_string, client_version_string);
459                 fatal_cleanup();
460         }
461 }
462
463
464 /* Destroy the host and server keys.  They will no longer be needed. */
465 void
466 destroy_sensitive_data(void)
467 {
468         int i;
469
470         if (sensitive_data.server_key) {
471                 key_free(sensitive_data.server_key);
472                 sensitive_data.server_key = NULL;
473         }
474         for (i = 0; i < options.num_host_key_files; i++) {
475                 if (sensitive_data.host_keys[i]) {
476                         key_free(sensitive_data.host_keys[i]);
477                         sensitive_data.host_keys[i] = NULL;
478                 }
479         }
480         sensitive_data.ssh1_host_key = NULL;
481         memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
482 }
483
484 static char *
485 list_hostkey_types(void)
486 {
487         Buffer b;
488         char *p;
489         int i;
490
491         buffer_init(&b);
492         for (i = 0; i < options.num_host_key_files; i++) {
493                 Key *key = sensitive_data.host_keys[i];
494                 if (key == NULL)
495                         continue;
496                 switch (key->type) {
497                 case KEY_RSA:
498                 case KEY_DSA:
499                         if (buffer_len(&b) > 0)
500                                 buffer_append(&b, ",", 1);
501                         p = key_ssh_name(key);
502                         buffer_append(&b, p, strlen(p));
503                         break;
504                 }
505         }
506         buffer_append(&b, "\0", 1);
507         p = xstrdup(buffer_ptr(&b));
508         buffer_free(&b);
509         debug("list_hostkey_types: %s", p);
510         return p;
511 }
512
513 static Key *
514 get_hostkey_by_type(int type)
515 {
516         int i;
517         for (i = 0; i < options.num_host_key_files; i++) {
518                 Key *key = sensitive_data.host_keys[i];
519                 if (key != NULL && key->type == type)
520                         return key;
521         }
522         return NULL;
523 }
524
525 /*
526  * returns 1 if connection should be dropped, 0 otherwise.
527  * dropping starts at connection #max_startups_begin with a probability
528  * of (max_startups_rate/100). the probability increases linearly until
529  * all connections are dropped for startups > max_startups
530  */
531 static int
532 drop_connection(int startups)
533 {
534         double p, r;
535
536         if (startups < options.max_startups_begin)
537                 return 0;
538         if (startups >= options.max_startups)
539                 return 1;
540         if (options.max_startups_rate == 100)
541                 return 1;
542
543         p  = 100 - options.max_startups_rate;
544         p *= startups - options.max_startups_begin;
545         p /= (double) (options.max_startups - options.max_startups_begin);
546         p += options.max_startups_rate;
547         p /= 100.0;
548         r = arc4random() / (double) UINT_MAX;
549
550         debug("drop_connection: p %g, r %g", p, r);
551         return (r < p) ? 1 : 0;
552 }
553
554 static void
555 usage(void)
556 {
557         fprintf(stderr, "sshd version %s\n", SSH_VERSION);
558         fprintf(stderr, "Usage: %s [options]\n", __progname);
559         fprintf(stderr, "Options:\n");
560         fprintf(stderr, "  -f file    Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
561         fprintf(stderr, "  -d         Debugging mode (multiple -d means more debugging)\n");
562         fprintf(stderr, "  -i         Started from inetd\n");
563         fprintf(stderr, "  -D         Do not fork into daemon mode\n");
564         fprintf(stderr, "  -t         Only test configuration file and keys\n");
565         fprintf(stderr, "  -q         Quiet (no logging)\n");
566         fprintf(stderr, "  -p port    Listen on the specified port (default: 22)\n");
567         fprintf(stderr, "  -k seconds Regenerate server key every this many seconds (default: 3600)\n");
568         fprintf(stderr, "  -g seconds Grace period for authentication (default: 600)\n");
569         fprintf(stderr, "  -b bits    Size of server RSA key (default: 768 bits)\n");
570         fprintf(stderr, "  -h file    File from which to read host key (default: %s)\n",
571             _PATH_HOST_KEY_FILE);
572         fprintf(stderr, "  -u len     Maximum hostname length for utmp recording\n");
573         fprintf(stderr, "  -4         Use IPv4 only\n");
574         fprintf(stderr, "  -6         Use IPv6 only\n");
575         fprintf(stderr, "  -o option  Process the option as if it was read from a configuration file.\n");
576         exit(1);
577 }
578
579 /*
580  * Main program for the daemon.
581  */
582 int
583 main(int ac, char **av)
584 {
585         extern char *optarg;
586         extern int optind;
587         int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
588         pid_t pid;
589         socklen_t fromlen;
590         fd_set *fdset;
591         struct sockaddr_storage from;
592         const char *remote_ip;
593         int remote_port;
594         FILE *f;
595         struct linger linger;
596         struct addrinfo *ai;
597         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
598         int listen_sock, maxfd;
599         int startup_p[2];
600         int startups = 0;
601         Key *key;
602         int ret, key_used = 0;
603
604         __progname = get_progname(av[0]);
605         init_rng();
606
607         /* Save argv. */
608         saved_argc = ac;
609         saved_argv = av;
610
611         /* Initialize configuration options to their default values. */
612         initialize_server_options(&options);
613
614         /* Parse command-line arguments. */
615         while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
616                 switch (opt) {
617                 case '4':
618                         IPv4or6 = AF_INET;
619                         break;
620                 case '6':
621                         IPv4or6 = AF_INET6;
622                         break;
623                 case 'f':
624                         config_file_name = optarg;
625                         break;
626                 case 'd':
627                         if (0 == debug_flag) {
628                                 debug_flag = 1;
629                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
630                         } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
631                                 options.log_level++;
632                         } else {
633                                 fprintf(stderr, "Too high debugging level.\n");
634                                 exit(1);
635                         }
636                         break;
637                 case 'D':
638                         no_daemon_flag = 1;
639                         break;
640                 case 'e':
641                         log_stderr = 1;
642                         break;
643                 case 'i':
644                         inetd_flag = 1;
645                         break;
646                 case 'Q':
647                         /* ignored */
648                         break;
649                 case 'q':
650                         options.log_level = SYSLOG_LEVEL_QUIET;
651                         break;
652                 case 'b':
653                         options.server_key_bits = atoi(optarg);
654                         break;
655                 case 'p':
656                         options.ports_from_cmdline = 1;
657                         if (options.num_ports >= MAX_PORTS) {
658                                 fprintf(stderr, "too many ports.\n");
659                                 exit(1);
660                         }
661                         options.ports[options.num_ports++] = a2port(optarg);
662                         if (options.ports[options.num_ports-1] == 0) {
663                                 fprintf(stderr, "Bad port number.\n");
664                                 exit(1);
665                         }
666                         break;
667                 case 'g':
668                         if ((options.login_grace_time = convtime(optarg)) == -1) {
669                                 fprintf(stderr, "Invalid login grace time.\n");
670                                 exit(1);
671                         }
672                         break;
673                 case 'k':
674                         if ((options.key_regeneration_time = convtime(optarg)) == -1) {
675                                 fprintf(stderr, "Invalid key regeneration interval.\n");
676                                 exit(1);
677                         }
678                         break;
679                 case 'h':
680                         if (options.num_host_key_files >= MAX_HOSTKEYS) {
681                                 fprintf(stderr, "too many host keys.\n");
682                                 exit(1);
683                         }
684                         options.host_key_files[options.num_host_key_files++] = optarg;
685                         break;
686                 case 'V':
687                         client_version_string = optarg;
688                         /* only makes sense with inetd_flag, i.e. no listen() */
689                         inetd_flag = 1;
690                         break;
691                 case 't':
692                         test_flag = 1;
693                         break;
694                 case 'u':
695                         utmp_len = atoi(optarg);
696                         break;
697                 case 'o':
698                         if (process_server_config_line(&options, optarg,
699                             "command-line", 0) != 0)
700                                 exit(1);
701                         break;
702                 case '?':
703                 default:
704                         usage();
705                         break;
706                 }
707         }
708         SSLeay_add_all_algorithms();
709         channel_set_af(IPv4or6);
710
711         /*
712          * Force logging to stderr until we have loaded the private host
713          * key (unless started from inetd)
714          */
715         log_init(__progname,
716             options.log_level == SYSLOG_LEVEL_NOT_SET ?
717             SYSLOG_LEVEL_INFO : options.log_level,
718             options.log_facility == SYSLOG_FACILITY_NOT_SET ?
719             SYSLOG_FACILITY_AUTH : options.log_facility,
720             !inetd_flag);
721
722 #ifdef _CRAY
723         /* Cray can define user privs drop all prives now!
724          * Not needed on PRIV_SU systems!
725          */
726         drop_cray_privs();
727 #endif
728
729         seed_rng();
730
731         /* Read server configuration options from the configuration file. */
732         read_server_config(&options, config_file_name);
733
734         /* Fill in default values for those options not explicitly set. */
735         fill_default_server_options(&options);
736
737         /* Check that there are no remaining arguments. */
738         if (optind < ac) {
739                 fprintf(stderr, "Extra argument %s.\n", av[optind]);
740                 exit(1);
741         }
742
743         debug("sshd version %.100s", SSH_VERSION);
744
745         /* load private host keys */
746         sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*));
747         for (i = 0; i < options.num_host_key_files; i++)
748                 sensitive_data.host_keys[i] = NULL;
749         sensitive_data.server_key = NULL;
750         sensitive_data.ssh1_host_key = NULL;
751         sensitive_data.have_ssh1_key = 0;
752         sensitive_data.have_ssh2_key = 0;
753
754         for (i = 0; i < options.num_host_key_files; i++) {
755                 key = key_load_private(options.host_key_files[i], "", NULL);
756                 sensitive_data.host_keys[i] = key;
757                 if (key == NULL) {
758                         error("Could not load host key: %s",
759                             options.host_key_files[i]);
760                         sensitive_data.host_keys[i] = NULL;
761                         continue;
762                 }
763                 switch (key->type) {
764                 case KEY_RSA1:
765                         sensitive_data.ssh1_host_key = key;
766                         sensitive_data.have_ssh1_key = 1;
767                         break;
768                 case KEY_RSA:
769                 case KEY_DSA:
770                         sensitive_data.have_ssh2_key = 1;
771                         break;
772                 }
773                 debug("private host key: #%d type %d %s", i, key->type,
774                     key_type(key));
775         }
776         if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
777                 log("Disabling protocol version 1. Could not load host key");
778                 options.protocol &= ~SSH_PROTO_1;
779         }
780 #ifndef GSSAPI
781         /* The GSSAPI key exchange can run without a host key */
782         if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
783                 log("Disabling protocol version 2. Could not load host key");
784                 options.protocol &= ~SSH_PROTO_2;
785         }
786 #endif
787         if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
788                 log("sshd: no hostkeys available -- exiting.");
789                 exit(1);
790         }
791
792         /* Check certain values for sanity. */
793         if (options.protocol & SSH_PROTO_1) {
794                 if (options.server_key_bits < 512 ||
795                     options.server_key_bits > 32768) {
796                         fprintf(stderr, "Bad server key size.\n");
797                         exit(1);
798                 }
799                 /*
800                  * Check that server and host key lengths differ sufficiently. This
801                  * is necessary to make double encryption work with rsaref. Oh, I
802                  * hate software patents. I dont know if this can go? Niels
803                  */
804                 if (options.server_key_bits >
805                     BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - SSH_KEY_BITS_RESERVED &&
806                     options.server_key_bits <
807                     BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
808                         options.server_key_bits =
809                             BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED;
810                         debug("Forcing server key to %d bits to make it differ from host key.",
811                             options.server_key_bits);
812                 }
813         }
814
815         /* Configuration looks good, so exit if in test mode. */
816         if (test_flag)
817                 exit(0);
818
819 #ifdef HAVE_SCO_PROTECTED_PW
820         (void) set_auth_parameters(ac, av);
821 #endif
822
823         /* Initialize the log (it is reinitialized below in case we forked). */
824         if (debug_flag && !inetd_flag)
825                 log_stderr = 1;
826         log_init(__progname, options.log_level, options.log_facility, log_stderr);
827
828         /*
829          * If not in debugging mode, and not started from inetd, disconnect
830          * from the controlling terminal, and fork.  The original process
831          * exits.
832          */
833         if (!(debug_flag || inetd_flag || no_daemon_flag)) {
834 #ifdef TIOCNOTTY
835                 int fd;
836 #endif /* TIOCNOTTY */
837                 if (daemon(0, 0) < 0)
838                         fatal("daemon() failed: %.200s", strerror(errno));
839
840                 /* Disconnect from the controlling tty. */
841 #ifdef TIOCNOTTY
842                 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
843                 if (fd >= 0) {
844                         (void) ioctl(fd, TIOCNOTTY, NULL);
845                         close(fd);
846                 }
847 #endif /* TIOCNOTTY */
848         }
849         /* Reinitialize the log (because of the fork above). */
850         log_init(__progname, options.log_level, options.log_facility, log_stderr);
851
852         /* Initialize the random number generator. */
853         arc4random_stir();
854
855         /* Chdir to the root directory so that the current disk can be
856            unmounted if desired. */
857         chdir("/");
858
859         /* ignore SIGPIPE */
860         signal(SIGPIPE, SIG_IGN);
861
862         /* Start listening for a socket, unless started from inetd. */
863         if (inetd_flag) {
864                 int s1;
865                 s1 = dup(0);    /* Make sure descriptors 0, 1, and 2 are in use. */
866                 dup(s1);
867                 sock_in = dup(0);
868                 sock_out = dup(1);
869                 startup_pipe = -1;
870                 /*
871                  * We intentionally do not close the descriptors 0, 1, and 2
872                  * as our code for setting the descriptors won\'t work if
873                  * ttyfd happens to be one of those.
874                  */
875                 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
876                 if (options.protocol & SSH_PROTO_1)
877                         generate_ephemeral_server_key();
878         } else {
879                 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
880                         if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
881                                 continue;
882                         if (num_listen_socks >= MAX_LISTEN_SOCKS)
883                                 fatal("Too many listen sockets. "
884                                     "Enlarge MAX_LISTEN_SOCKS");
885                         if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
886                             ntop, sizeof(ntop), strport, sizeof(strport),
887                             NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
888                                 error("getnameinfo failed");
889                                 continue;
890                         }
891                         /* Create socket for listening. */
892                         listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
893                         if (listen_sock < 0) {
894                                 /* kernel may not support ipv6 */
895                                 verbose("socket: %.100s", strerror(errno));
896                                 continue;
897                         }
898                         if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
899                                 error("listen_sock O_NONBLOCK: %s", strerror(errno));
900                                 close(listen_sock);
901                                 continue;
902                         }
903                         /*
904                          * Set socket options.  We try to make the port
905                          * reusable and have it close as fast as possible
906                          * without waiting in unnecessary wait states on
907                          * close.
908                          */
909                         setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
910                             &on, sizeof(on));
911                         linger.l_onoff = 1;
912                         linger.l_linger = 5;
913                         setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
914                             &linger, sizeof(linger));
915
916                         debug("Bind to port %s on %s.", strport, ntop);
917
918                         /* Bind the socket to the desired port. */
919                         if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
920                                 if (!ai->ai_next)
921                                     error("Bind to port %s on %s failed: %.200s.",
922                                             strport, ntop, strerror(errno));
923                                 close(listen_sock);
924                                 continue;
925                         }
926                         listen_socks[num_listen_socks] = listen_sock;
927                         num_listen_socks++;
928
929                         /* Start listening on the port. */
930                         log("Server listening on %s port %s.", ntop, strport);
931                         if (listen(listen_sock, 5) < 0)
932                                 fatal("listen: %.100s", strerror(errno));
933
934                 }
935                 freeaddrinfo(options.listen_addrs);
936
937                 if (!num_listen_socks)
938                         fatal("Cannot bind any address.");
939
940                 if (options.protocol & SSH_PROTO_1)
941                         generate_ephemeral_server_key();
942
943                 /*
944                  * Arrange to restart on SIGHUP.  The handler needs
945                  * listen_sock.
946                  */
947                 signal(SIGHUP, sighup_handler);
948
949                 signal(SIGTERM, sigterm_handler);
950                 signal(SIGQUIT, sigterm_handler);
951
952                 /* Arrange SIGCHLD to be caught. */
953                 signal(SIGCHLD, main_sigchld_handler);
954
955                 /* Write out the pid file after the sigterm handler is setup */
956                 if (!debug_flag) {
957                         /*
958                          * Record our pid in /var/run/sshd.pid to make it
959                          * easier to kill the correct sshd.  We don't want to
960                          * do this before the bind above because the bind will
961                          * fail if there already is a daemon, and this will
962                          * overwrite any old pid in the file.
963                          */
964                         f = fopen(options.pid_file, "wb");
965                         if (f) {
966                                 fprintf(f, "%u\n", (u_int) getpid());
967                                 fclose(f);
968                         }
969                 }
970
971                 /* setup fd set for listen */
972                 fdset = NULL;
973                 maxfd = 0;
974                 for (i = 0; i < num_listen_socks; i++)
975                         if (listen_socks[i] > maxfd)
976                                 maxfd = listen_socks[i];
977                 /* pipes connected to unauthenticated childs */
978                 startup_pipes = xmalloc(options.max_startups * sizeof(int));
979                 for (i = 0; i < options.max_startups; i++)
980                         startup_pipes[i] = -1;
981
982                 /*
983                  * Stay listening for connections until the system crashes or
984                  * the daemon is killed with a signal.
985                  */
986                 for (;;) {
987                         if (received_sighup)
988                                 sighup_restart();
989                         if (fdset != NULL)
990                                 xfree(fdset);
991                         fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
992                         fdset = (fd_set *)xmalloc(fdsetsz);
993                         memset(fdset, 0, fdsetsz);
994
995                         for (i = 0; i < num_listen_socks; i++)
996                                 FD_SET(listen_socks[i], fdset);
997                         for (i = 0; i < options.max_startups; i++)
998                                 if (startup_pipes[i] != -1)
999                                         FD_SET(startup_pipes[i], fdset);
1000
1001                         /* Wait in select until there is a connection. */
1002                         ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1003                         if (ret < 0 && errno != EINTR)
1004                                 error("select: %.100s", strerror(errno));
1005                         if (received_sigterm) {
1006                                 log("Received signal %d; terminating.",
1007                                     (int) received_sigterm);
1008                                 close_listen_socks();
1009                                 unlink(options.pid_file);
1010                                 exit(255);
1011                         }
1012                         if (key_used && key_do_regen) {
1013                                 generate_ephemeral_server_key();
1014                                 key_used = 0;
1015                                 key_do_regen = 0;
1016                         }
1017                         if (ret < 0)
1018                                 continue;
1019
1020                         for (i = 0; i < options.max_startups; i++)
1021                                 if (startup_pipes[i] != -1 &&
1022                                     FD_ISSET(startup_pipes[i], fdset)) {
1023                                         /*
1024                                          * the read end of the pipe is ready
1025                                          * if the child has closed the pipe
1026                                          * after successful authentication
1027                                          * or if the child has died
1028                                          */
1029                                         close(startup_pipes[i]);
1030                                         startup_pipes[i] = -1;
1031                                         startups--;
1032                                 }
1033                         for (i = 0; i < num_listen_socks; i++) {
1034                                 if (!FD_ISSET(listen_socks[i], fdset))
1035                                         continue;
1036                                 fromlen = sizeof(from);
1037                                 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
1038                                     &fromlen);
1039                                 if (newsock < 0) {
1040                                         if (errno != EINTR && errno != EWOULDBLOCK)
1041                                                 error("accept: %.100s", strerror(errno));
1042                                         continue;
1043                                 }
1044                                 if (fcntl(newsock, F_SETFL, 0) < 0) {
1045                                         error("newsock del O_NONBLOCK: %s", strerror(errno));
1046                                         close(newsock);
1047                                         continue;
1048                                 }
1049                                 if (drop_connection(startups) == 1) {
1050                                         debug("drop connection #%d", startups);
1051                                         close(newsock);
1052                                         continue;
1053                                 }
1054                                 if (pipe(startup_p) == -1) {
1055                                         close(newsock);
1056                                         continue;
1057                                 }
1058
1059                                 for (j = 0; j < options.max_startups; j++)
1060                                         if (startup_pipes[j] == -1) {
1061                                                 startup_pipes[j] = startup_p[0];
1062                                                 if (maxfd < startup_p[0])
1063                                                         maxfd = startup_p[0];
1064                                                 startups++;
1065                                                 break;
1066                                         }
1067
1068                                 /*
1069                                  * Got connection.  Fork a child to handle it, unless
1070                                  * we are in debugging mode.
1071                                  */
1072                                 if (debug_flag) {
1073                                         /*
1074                                          * In debugging mode.  Close the listening
1075                                          * socket, and start processing the
1076                                          * connection without forking.
1077                                          */
1078                                         debug("Server will not fork when running in debugging mode.");
1079                                         close_listen_socks();
1080                                         sock_in = newsock;
1081                                         sock_out = newsock;
1082                                         startup_pipe = -1;
1083                                         pid = getpid();
1084                                         break;
1085                                 } else {
1086                                         /*
1087                                          * Normal production daemon.  Fork, and have
1088                                          * the child process the connection. The
1089                                          * parent continues listening.
1090                                          */
1091                                         if ((pid = fork()) == 0) {
1092                                                 /*
1093                                                  * Child.  Close the listening and max_startup
1094                                                  * sockets.  Start using the accepted socket.
1095                                                  * Reinitialize logging (since our pid has
1096                                                  * changed).  We break out of the loop to handle
1097                                                  * the connection.
1098                                                  */
1099                                                 startup_pipe = startup_p[1];
1100                                                 close_startup_pipes();
1101                                                 close_listen_socks();
1102                                                 sock_in = newsock;
1103                                                 sock_out = newsock;
1104                                                 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1105                                                 break;
1106                                         }
1107                                 }
1108
1109                                 /* Parent.  Stay in the loop. */
1110                                 if (pid < 0)
1111                                         error("fork: %.100s", strerror(errno));
1112                                 else
1113                                         debug("Forked child %d.", pid);
1114
1115                                 close(startup_p[1]);
1116
1117                                 /* Mark that the key has been used (it was "given" to the child). */
1118                                 if ((options.protocol & SSH_PROTO_1) &&
1119                                     key_used == 0) {
1120                                         /* Schedule server key regeneration alarm. */
1121                                         signal(SIGALRM, key_regeneration_alarm);
1122                                         alarm(options.key_regeneration_time);
1123                                         key_used = 1;
1124                                 }
1125
1126                                 arc4random_stir();
1127
1128                                 /* Close the new socket (the child is now taking care of it). */
1129                                 close(newsock);
1130                         }
1131                         /* child process check (or debug mode) */
1132                         if (num_listen_socks < 0)
1133                                 break;
1134                 }
1135         }
1136
1137         /* This is the child processing a new connection. */
1138
1139         /*
1140          * Disable the key regeneration alarm.  We will not regenerate the
1141          * key since we are no longer in a position to give it to anyone. We
1142          * will not restart on SIGHUP since it no longer makes sense.
1143          */
1144         alarm(0);
1145         signal(SIGALRM, SIG_DFL);
1146         signal(SIGHUP, SIG_DFL);
1147         signal(SIGTERM, SIG_DFL);
1148         signal(SIGQUIT, SIG_DFL);
1149         signal(SIGCHLD, SIG_DFL);
1150         signal(SIGINT, SIG_DFL);
1151
1152         /*
1153          * Set socket options for the connection.  We want the socket to
1154          * close as fast as possible without waiting for anything.  If the
1155          * connection is not a socket, these will do nothing.
1156          */
1157         /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1158         linger.l_onoff = 1;
1159         linger.l_linger = 5;
1160         setsockopt(sock_in, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
1161
1162         /* Set keepalives if requested. */
1163         if (options.keepalives &&
1164             setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
1165             sizeof(on)) < 0)
1166                 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1167
1168         /*
1169          * Register our connection.  This turns encryption off because we do
1170          * not have a key.
1171          */
1172         packet_set_connection(sock_in, sock_out);
1173
1174         remote_port = get_remote_port();
1175         remote_ip = get_remote_ipaddr();
1176
1177 #ifdef LIBWRAP
1178         /* Check whether logins are denied from this host. */
1179         {
1180                 struct request_info req;
1181
1182                 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1183                 fromhost(&req);
1184
1185                 if (!hosts_access(&req)) {
1186                         debug("Connection refused by tcp wrapper");
1187                         refuse(&req);
1188                         /* NOTREACHED */
1189                         fatal("libwrap refuse returns");
1190                 }
1191         }
1192 #endif /* LIBWRAP */
1193
1194         /* Log the connection. */
1195         verbose("Connection from %.500s port %d", remote_ip, remote_port);
1196
1197         /*
1198          * We don\'t want to listen forever unless the other side
1199          * successfully authenticates itself.  So we set up an alarm which is
1200          * cleared after successful authentication.  A limit of zero
1201          * indicates no limit. Note that we don\'t set the alarm in debugging
1202          * mode; it is just annoying to have the server exit just when you
1203          * are about to discover the bug.
1204          */
1205         signal(SIGALRM, grace_alarm_handler);
1206         if (!debug_flag)
1207                 alarm(options.login_grace_time);
1208
1209         sshd_exchange_identification(sock_in, sock_out);
1210         /*
1211          * Check that the connection comes from a privileged port.
1212          * Rhosts-Authentication only makes sense from priviledged
1213          * programs.  Of course, if the intruder has root access on his local
1214          * machine, he can connect from any port.  So do not use these
1215          * authentication methods from machines that you do not trust.
1216          */
1217         if (options.rhosts_authentication &&
1218             (remote_port >= IPPORT_RESERVED ||
1219             remote_port < IPPORT_RESERVED / 2)) {
1220                 debug("Rhosts Authentication disabled, "
1221                     "originating port %d not trusted.", remote_port);
1222                 options.rhosts_authentication = 0;
1223         }
1224 #if defined(KRB4) && !defined(KRB5)
1225         if (!packet_connection_is_ipv4() &&
1226             options.kerberos_authentication) {
1227                 debug("Kerberos Authentication disabled, only available for IPv4.");
1228                 options.kerberos_authentication = 0;
1229         }
1230 #endif /* KRB4 && !KRB5 */
1231 #ifdef AFS
1232         /* If machine has AFS, set process authentication group. */
1233         if (k_hasafs()) {
1234                 k_setpag();
1235                 k_unlog();
1236         }
1237 #endif /* AFS */
1238
1239         packet_set_nonblocking();
1240
1241         /* perform the key exchange */
1242         /* authenticate user and start session */
1243         if (compat20) {
1244                 do_ssh2_kex();
1245                 do_authentication2();
1246         } else {
1247                 do_ssh1_kex();
1248                 do_authentication();
1249         }
1250         /* The connection has been terminated. */
1251         verbose("Closing connection to %.100s", remote_ip);
1252
1253 #ifdef USE_PAM
1254         finish_pam();
1255 #endif /* USE_PAM */
1256
1257         packet_close();
1258         exit(0);
1259 }
1260
1261 /*
1262  * SSH1 key exchange
1263  */
1264 static void
1265 do_ssh1_kex(void)
1266 {
1267         int i, len;
1268         int rsafail = 0;
1269         BIGNUM *session_key_int;
1270         u_char session_key[SSH_SESSION_KEY_LENGTH];
1271         u_char cookie[8];
1272         u_int cipher_type, auth_mask, protocol_flags;
1273         u_int32_t rand = 0;
1274
1275         /*
1276          * Generate check bytes that the client must send back in the user
1277          * packet in order for it to be accepted; this is used to defy ip
1278          * spoofing attacks.  Note that this only works against somebody
1279          * doing IP spoofing from a remote machine; any machine on the local
1280          * network can still see outgoing packets and catch the random
1281          * cookie.  This only affects rhosts authentication, and this is one
1282          * of the reasons why it is inherently insecure.
1283          */
1284         for (i = 0; i < 8; i++) {
1285                 if (i % 4 == 0)
1286                         rand = arc4random();
1287                 cookie[i] = rand & 0xff;
1288                 rand >>= 8;
1289         }
1290
1291         /*
1292          * Send our public key.  We include in the packet 64 bits of random
1293          * data that must be matched in the reply in order to prevent IP
1294          * spoofing.
1295          */
1296         packet_start(SSH_SMSG_PUBLIC_KEY);
1297         for (i = 0; i < 8; i++)
1298                 packet_put_char(cookie[i]);
1299
1300         /* Store our public server RSA key. */
1301         packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1302         packet_put_bignum(sensitive_data.server_key->rsa->e);
1303         packet_put_bignum(sensitive_data.server_key->rsa->n);
1304
1305         /* Store our public host RSA key. */
1306         packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1307         packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1308         packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1309
1310         /* Put protocol flags. */
1311         packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1312
1313         /* Declare which ciphers we support. */
1314         packet_put_int(cipher_mask_ssh1(0));
1315
1316         /* Declare supported authentication types. */
1317         auth_mask = 0;
1318         if (options.rhosts_authentication)
1319                 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1320         if (options.rhosts_rsa_authentication)
1321                 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1322         if (options.rsa_authentication)
1323                 auth_mask |= 1 << SSH_AUTH_RSA;
1324 #if defined(KRB4) || defined(KRB5)
1325         if (options.kerberos_authentication)
1326                 auth_mask |= 1 << SSH_AUTH_KERBEROS;
1327 #endif
1328 #if defined(AFS) || defined(KRB5)
1329         if (options.kerberos_tgt_passing)
1330                 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1331 #endif
1332 #ifdef AFS
1333         if (options.afs_token_passing)
1334                 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1335 #endif
1336         if (options.challenge_response_authentication == 1)
1337                 auth_mask |= 1 << SSH_AUTH_TIS;
1338         if (options.password_authentication)
1339                 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1340         packet_put_int(auth_mask);
1341
1342         /* Send the packet and wait for it to be sent. */
1343         packet_send();
1344         packet_write_wait();
1345
1346         debug("Sent %d bit server key and %d bit host key.",
1347             BN_num_bits(sensitive_data.server_key->rsa->n),
1348             BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1349
1350         /* Read clients reply (cipher type and session key). */
1351         packet_read_expect(SSH_CMSG_SESSION_KEY);
1352
1353         /* Get cipher type and check whether we accept this. */
1354         cipher_type = packet_get_char();
1355
1356         if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1357                 packet_disconnect("Warning: client selects unsupported cipher.");
1358
1359         /* Get check bytes from the packet.  These must match those we
1360            sent earlier with the public key packet. */
1361         for (i = 0; i < 8; i++)
1362                 if (cookie[i] != packet_get_char())
1363                         packet_disconnect("IP Spoofing check bytes do not match.");
1364
1365         debug("Encryption type: %.200s", cipher_name(cipher_type));
1366
1367         /* Get the encrypted integer. */
1368         if ((session_key_int = BN_new()) == NULL)
1369                 fatal("do_ssh1_kex: BN_new failed");
1370         packet_get_bignum(session_key_int);
1371
1372         protocol_flags = packet_get_int();
1373         packet_set_protocol_flags(protocol_flags);
1374         packet_check_eom();
1375
1376         packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1377
1378         /*
1379          * Decrypt it using our private server key and private host key (key
1380          * with larger modulus first).
1381          */
1382         if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1383                 /* Server key has bigger modulus. */
1384                 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1385                     BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1386                         fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1387                             get_remote_ipaddr(),
1388                             BN_num_bits(sensitive_data.server_key->rsa->n),
1389                             BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1390                             SSH_KEY_BITS_RESERVED);
1391                 }
1392                 if (rsa_private_decrypt(session_key_int, session_key_int,
1393                     sensitive_data.server_key->rsa) <= 0)
1394                         rsafail++;
1395                 if (rsa_private_decrypt(session_key_int, session_key_int,
1396                     sensitive_data.ssh1_host_key->rsa) <= 0)
1397                         rsafail++;
1398         } else {
1399                 /* Host key has bigger modulus (or they are equal). */
1400                 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1401                     BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1402                         fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1403                             get_remote_ipaddr(),
1404                             BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1405                             BN_num_bits(sensitive_data.server_key->rsa->n),
1406                             SSH_KEY_BITS_RESERVED);
1407                 }
1408                 if (rsa_private_decrypt(session_key_int, session_key_int,
1409                     sensitive_data.ssh1_host_key->rsa) < 0)
1410                         rsafail++;
1411                 if (rsa_private_decrypt(session_key_int, session_key_int,
1412                     sensitive_data.server_key->rsa) < 0)
1413                         rsafail++;
1414         }
1415         /*
1416          * Extract session key from the decrypted integer.  The key is in the
1417          * least significant 256 bits of the integer; the first byte of the
1418          * key is in the highest bits.
1419          */
1420         if (!rsafail) {
1421                 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1422                 len = BN_num_bytes(session_key_int);
1423                 if (len < 0 || len > sizeof(session_key)) {
1424                         error("do_connection: bad session key len from %s: "
1425                             "session_key_int %d > sizeof(session_key) %lu",
1426                             get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1427                         rsafail++;
1428                 } else {
1429                         memset(session_key, 0, sizeof(session_key));
1430                         BN_bn2bin(session_key_int,
1431                             session_key + sizeof(session_key) - len);
1432
1433                         compute_session_id(session_id, cookie,
1434                             sensitive_data.ssh1_host_key->rsa->n,
1435                             sensitive_data.server_key->rsa->n);
1436                         /*
1437                          * Xor the first 16 bytes of the session key with the
1438                          * session id.
1439                          */
1440                         for (i = 0; i < 16; i++)
1441                                 session_key[i] ^= session_id[i];
1442                 }
1443         }
1444         if (rsafail) {
1445                 int bytes = BN_num_bytes(session_key_int);
1446                 u_char *buf = xmalloc(bytes);
1447                 MD5_CTX md;
1448
1449                 log("do_connection: generating a fake encryption key");
1450                 BN_bn2bin(session_key_int, buf);
1451                 MD5_Init(&md);
1452                 MD5_Update(&md, buf, bytes);
1453                 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1454                 MD5_Final(session_key, &md);
1455                 MD5_Init(&md);
1456                 MD5_Update(&md, session_key, 16);
1457                 MD5_Update(&md, buf, bytes);
1458                 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1459                 MD5_Final(session_key + 16, &md);
1460                 memset(buf, 0, bytes);
1461                 xfree(buf);
1462                 for (i = 0; i < 16; i++)
1463                         session_id[i] = session_key[i] ^ session_key[i + 16];
1464         }
1465         /* Destroy the private and public keys.  They will no longer be needed. */
1466         destroy_sensitive_data();
1467
1468         /* Destroy the decrypted integer.  It is no longer needed. */
1469         BN_clear_free(session_key_int);
1470
1471         /* Set the session key.  From this on all communications will be encrypted. */
1472         packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1473
1474         /* Destroy our copy of the session key.  It is no longer needed. */
1475         memset(session_key, 0, sizeof(session_key));
1476
1477         debug("Received session key; encryption turned on.");
1478
1479         /* Send an acknowledgement packet.  Note that this packet is sent encrypted. */
1480         packet_start(SSH_SMSG_SUCCESS);
1481         packet_send();
1482         packet_write_wait();
1483 }
1484
1485 /*
1486  * SSH2 key exchange: diffie-hellman-group1-sha1
1487  */
1488 static void
1489 do_ssh2_kex(void)
1490 {
1491         Kex *kex;
1492
1493         if (options.ciphers != NULL) {
1494                 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1495                 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1496         }
1497         myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1498             compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1499         myproposal[PROPOSAL_ENC_ALGS_STOC] =
1500             compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1501
1502         if (options.macs != NULL) {
1503                 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1504                 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1505         }
1506         myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1507
1508 #ifdef GSSAPI
1509         { 
1510         char *orig;
1511         char *gss = NULL;
1512         char *newstr = NULL;
1513         orig = myproposal[PROPOSAL_KEX_ALGS];
1514
1515         /* If we don't have a host key, then all of the algorithms
1516          * currently in myproposal are useless */
1517         if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])==0)
1518                 orig= NULL;
1519                 
1520         if (options.gss_keyex)
1521                 gss = ssh_gssapi_mechanisms(1,NULL);
1522         else
1523                 gss = NULL;
1524         
1525         if (gss && orig) {
1526                 int len = strlen(orig) + strlen(gss) +2;
1527                 newstr=xmalloc(len);
1528                 snprintf(newstr,len,"%s,%s",gss,orig);
1529         } else if (gss) {
1530                 newstr=gss;
1531         } else if (orig) {
1532                 newstr=orig;
1533         }
1534         /* If we've got GSSAPI mechanisms, then we've also got the 'null'
1535            host key algorithm, but we're not allowed to advertise it, unless
1536            its the only host key algorithm we're supporting */
1537         if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0) {
1538                 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]="null";
1539         }
1540         if (newstr)
1541                 myproposal[PROPOSAL_KEX_ALGS]=newstr;
1542         else
1543                 fatal("No supported key exchange algorithms");
1544         }
1545 #endif
1546
1547         /* start key exchange */
1548         kex = kex_setup(myproposal);
1549         kex->server = 1;
1550         kex->client_version_string=client_version_string;
1551         kex->server_version_string=server_version_string;
1552         kex->load_host_key=&get_hostkey_by_type;
1553
1554         xxx_kex = kex;
1555
1556         dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1557
1558         session_id2 = kex->session_id;
1559         session_id2_len = kex->session_id_len;
1560
1561 #ifdef DEBUG_KEXDH
1562         /* send 1st encrypted/maced/compressed message */
1563         packet_start(SSH2_MSG_IGNORE);
1564         packet_put_cstring("markus");
1565         packet_send();
1566         packet_write_wait();
1567 #endif
1568         debug("KEX done");
1569 }
This page took 2.438938 seconds and 5 git commands to generate.