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