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