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