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