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