]> andersk Git - gssapi-openssh.git/blame - openssh/sshd.c
Merge from OPENSSH_3_8_1P1_GSSAPI_20040713 to OPENSSH_3_9P1_GSSAPI_20040818.
[gssapi-openssh.git] / openssh / sshd.c
CommitLineData
3c0ef626 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:
2980ea68 18 * Privilege Separation:
3c0ef626 19 *
2980ea68 20 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
21 * Copyright (c) 2002 Niels Provos. All rights reserved.
3c0ef626 22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 *
32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 */
43
44#include "includes.h"
1b56ff3d 45RCSID("$OpenBSD: sshd.c,v 1.301 2004/08/11 11:50:09 dtucker Exp $");
3c0ef626 46
47#include <openssl/dh.h>
48#include <openssl/bn.h>
1e608e42 49#include <openssl/md5.h>
2980ea68 50#include <openssl/rand.h>
51#ifdef HAVE_SECUREWARE
52#include <sys/security.h>
53#include <prot.h>
54#endif
3c0ef626 55
56#include "ssh.h"
57#include "ssh1.h"
58#include "ssh2.h"
59#include "xmalloc.h"
60#include "rsa.h"
61#include "sshpty.h"
62#include "packet.h"
3c0ef626 63#include "log.h"
64#include "servconf.h"
65#include "uidswap.h"
66#include "compat.h"
67#include "buffer.h"
1b56ff3d 68#include "bufaux.h"
3c0ef626 69#include "cipher.h"
70#include "kex.h"
71#include "key.h"
72#include "dh.h"
73#include "myproposal.h"
74#include "authfile.h"
75#include "pathnames.h"
76#include "atomicio.h"
77#include "canohost.h"
78#include "auth.h"
79#include "misc.h"
1b56ff3d 80#include "msg.h"
3c0ef626 81#include "dispatch.h"
82#include "channels.h"
2980ea68 83#include "session.h"
84#include "monitor_mm.h"
85#include "monitor.h"
86#include "monitor_wrap.h"
87#include "monitor_fdpass.h"
3c0ef626 88
5598e598 89#ifdef GSSAPI
90#include "ssh-gss.h"
91#endif
92
0b582e46 93#ifdef GSSAPI
94#include <openssl/md5.h>
95#include "bufaux.h"
96#endif /* GSSAPI */
0b582e46 97
3c0ef626 98#ifdef LIBWRAP
99#include <tcpd.h>
100#include <syslog.h>
101int allow_severity = LOG_INFO;
102int deny_severity = LOG_WARNING;
103#endif /* LIBWRAP */
104
105#ifndef O_NOCTTY
106#define O_NOCTTY 0
107#endif
108
1b56ff3d 109/* Re-exec fds */
110#define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
111#define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
112#define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
113#define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
114
3c0ef626 115extern char *__progname;
3c0ef626 116
117/* Server configuration options. */
118ServerOptions options;
119
120/* Name of the server configuration file. */
ae43c103 121char *config_file_name;
3c0ef626 122
123/*
124 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
125 * Default value is AF_UNSPEC means both IPv4 and IPv6.
126 */
3c0ef626 127int IPv4or6 = AF_UNSPEC;
3c0ef626 128
129/*
130 * Debug mode flag. This can be set on the command line. If debug
131 * mode is enabled, extra debugging output will be sent to the system
132 * log, the daemon will not go to background, and will exit after processing
133 * the first connection.
134 */
135int debug_flag = 0;
136
137/* Flag indicating that the daemon should only test the configuration and keys. */
138int test_flag = 0;
139
140/* Flag indicating that the daemon is being started from inetd. */
141int inetd_flag = 0;
142
143/* Flag indicating that sshd should not detach and become a daemon. */
144int no_daemon_flag = 0;
145
146/* debug goes to stderr unless inetd_flag is set */
147int log_stderr = 0;
148
149/* Saved arguments to main(). */
150char **saved_argv;
151int saved_argc;
152
1b56ff3d 153/* re-exec */
154int rexeced_flag = 0;
155int rexec_flag = 1;
156int rexec_argc = 0;
157char **rexec_argv;
158
3c0ef626 159/*
160 * The sockets that the server is listening; this is used in the SIGHUP
161 * signal handler.
162 */
163#define MAX_LISTEN_SOCKS 16
164int listen_socks[MAX_LISTEN_SOCKS];
165int num_listen_socks = 0;
166
167/*
168 * the client's version string, passed by sshd2 in compat mode. if != NULL,
169 * sshd will skip the version-number exchange
170 */
171char *client_version_string = NULL;
172char *server_version_string = NULL;
173
174/* for rekeying XXX fixme */
175Kex *xxx_kex;
176
177/*
178 * Any really sensitive data in the application is contained in this
179 * structure. The idea is that this structure could be locked into memory so
180 * that the pages do not get written into swap. However, there are some
181 * problems. The private key contains BIGNUMs, and we do not (in principle)
182 * have access to the internals of them, and locking just the structure is
183 * not very useful. Currently, memory locking is not implemented.
184 */
185struct {
186 Key *server_key; /* ephemeral server key */
187 Key *ssh1_host_key; /* ssh1 host key */
188 Key **host_keys; /* all private host keys */
189 int have_ssh1_key;
190 int have_ssh2_key;
191 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
192} sensitive_data;
193
194/*
195 * Flag indicating whether the RSA server key needs to be regenerated.
196 * Is set in the SIGALRM handler and cleared when the key is regenerated.
197 */
1e608e42 198static volatile sig_atomic_t key_do_regen = 0;
3c0ef626 199
200/* This is set to true when a signal is received. */
1e608e42 201static volatile sig_atomic_t received_sighup = 0;
202static volatile sig_atomic_t received_sigterm = 0;
3c0ef626 203
204/* session identifier, used by RSA-auth */
205u_char session_id[16];
206
207/* same for ssh2 */
208u_char *session_id2 = NULL;
70791e56 209u_int session_id2_len = 0;
3c0ef626 210
211/* record remote hostname or ip */
212u_int utmp_len = MAXHOSTNAMELEN;
213
1e608e42 214/* options.max_startup sized array of fd ints */
215int *startup_pipes = NULL;
216int startup_pipe; /* in child */
217
2980ea68 218/* variables used for privilege separation */
1c14df9e 219int use_privsep;
416fd2a8 220struct monitor *pmonitor = NULL;
2980ea68 221
416fd2a8 222/* global authentication context */
223Authctxt *the_authctxt = NULL;
224
1b56ff3d 225/* message to be displayed after login */
226Buffer loginmsg;
227
3c0ef626 228/* Prototypes for various functions defined later in this file. */
229void destroy_sensitive_data(void);
2980ea68 230void demote_sensitive_data(void);
3c0ef626 231
232static void do_ssh1_kex(void);
233static void do_ssh2_kex(void);
234
235/*
236 * Close all listening sockets
237 */
238static void
239close_listen_socks(void)
240{
241 int i;
ff2d7a98 242
3c0ef626 243 for (i = 0; i < num_listen_socks; i++)
244 close(listen_socks[i]);
245 num_listen_socks = -1;
246}
247
1e608e42 248static void
249close_startup_pipes(void)
250{
251 int i;
ff2d7a98 252
1e608e42 253 if (startup_pipes)
254 for (i = 0; i < options.max_startups; i++)
255 if (startup_pipes[i] != -1)
256 close(startup_pipes[i]);
257}
258
3c0ef626 259/*
260 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
261 * the effect is to reread the configuration file (and to regenerate
262 * the server key).
263 */
264static void
265sighup_handler(int sig)
266{
1e608e42 267 int save_errno = errno;
268
3c0ef626 269 received_sighup = 1;
270 signal(SIGHUP, sighup_handler);
1e608e42 271 errno = save_errno;
3c0ef626 272}
273
274/*
275 * Called from the main program after receiving SIGHUP.
276 * Restarts the server.
277 */
278static void
279sighup_restart(void)
280{
70791e56 281 logit("Received SIGHUP; restarting.");
3c0ef626 282 close_listen_socks();
1e608e42 283 close_startup_pipes();
3c0ef626 284 execv(saved_argv[0], saved_argv);
70791e56 285 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
ff2d7a98 286 strerror(errno));
3c0ef626 287 exit(1);
288}
289
290/*
291 * Generic signal handler for terminating signals in the master daemon.
292 */
293static void
294sigterm_handler(int sig)
295{
296 received_sigterm = sig;
297}
298
299/*
300 * SIGCHLD handler. This is called whenever a child dies. This will then
301 * reap any zombies left by exited children.
302 */
303static void
304main_sigchld_handler(int sig)
305{
306 int save_errno = errno;
ff2d7a98 307 pid_t pid;
3c0ef626 308 int status;
309
2980ea68 310 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
311 (pid < 0 && errno == EINTR))
3c0ef626 312 ;
313
314 signal(SIGCHLD, main_sigchld_handler);
315 errno = save_errno;
316}
317
318/*
319 * Signal handler for the alarm after the login grace period has expired.
320 */
321static void
322grace_alarm_handler(int sig)
323{
324 /* XXX no idea how fix this signal handler */
325
416fd2a8 326 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
327 kill(pmonitor->m_pid, SIGALRM);
328
3c0ef626 329 /* Log error and exit. */
e54b3d7c 330 fatal("Timeout before authentication for %s", get_remote_ipaddr());
3c0ef626 331}
332
333/*
334 * Signal handler for the key regeneration alarm. Note that this
335 * alarm only occurs in the daemon waiting for connections, and it does not
336 * do anything with the private key or random state before forking.
337 * Thus there should be no concurrency control/asynchronous execution
338 * problems.
339 */
340static void
341generate_ephemeral_server_key(void)
342{
e54b3d7c 343 u_int32_t rnd = 0;
3c0ef626 344 int i;
345
346 verbose("Generating %s%d bit RSA key.",
347 sensitive_data.server_key ? "new " : "", options.server_key_bits);
348 if (sensitive_data.server_key != NULL)
349 key_free(sensitive_data.server_key);
350 sensitive_data.server_key = key_generate(KEY_RSA1,
351 options.server_key_bits);
352 verbose("RSA key generation complete.");
353
354 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
355 if (i % 4 == 0)
e54b3d7c 356 rnd = arc4random();
357 sensitive_data.ssh1_cookie[i] = rnd & 0xff;
358 rnd >>= 8;
3c0ef626 359 }
360 arc4random_stir();
361}
362
363static void
364key_regeneration_alarm(int sig)
365{
366 int save_errno = errno;
ff2d7a98 367
3c0ef626 368 signal(SIGALRM, SIG_DFL);
369 errno = save_errno;
370 key_do_regen = 1;
371}
372
373static void
374sshd_exchange_identification(int sock_in, int sock_out)
375{
376 int i, mismatch;
377 int remote_major, remote_minor;
378 int major, minor;
379 char *s;
380 char buf[256]; /* Must not be larger than remote_version. */
381 char remote_version[256]; /* Must be at least as big as buf. */
382
383 if ((options.protocol & SSH_PROTO_1) &&
384 (options.protocol & SSH_PROTO_2)) {
385 major = PROTOCOL_MAJOR_1;
386 minor = 99;
387 } else if (options.protocol & SSH_PROTO_2) {
388 major = PROTOCOL_MAJOR_2;
389 minor = PROTOCOL_MINOR_2;
390 } else {
391 major = PROTOCOL_MAJOR_1;
392 minor = PROTOCOL_MINOR_1;
393 }
394 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
395 server_version_string = xstrdup(buf);
396
70791e56 397 /* Send our protocol version identification. */
398 if (atomicio(vwrite, sock_out, server_version_string,
399 strlen(server_version_string))
400 != strlen(server_version_string)) {
401 logit("Could not write ident string to %s", get_remote_ipaddr());
416fd2a8 402 cleanup_exit(255);
70791e56 403 }
404
405 /* Read other sides version identification. */
406 memset(buf, 0, sizeof(buf));
407 for (i = 0; i < sizeof(buf) - 1; i++) {
408 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
409 logit("Did not receive identification string from %s",
410 get_remote_ipaddr());
416fd2a8 411 cleanup_exit(255);
3c0ef626 412 }
70791e56 413 if (buf[i] == '\r') {
414 buf[i] = 0;
415 /* Kludge for F-Secure Macintosh < 1.0.2 */
416 if (i == 12 &&
417 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
3c0ef626 418 break;
70791e56 419 continue;
420 }
421 if (buf[i] == '\n') {
422 buf[i] = 0;
423 break;
3c0ef626 424 }
3c0ef626 425 }
70791e56 426 buf[sizeof(buf) - 1] = 0;
427 client_version_string = xstrdup(buf);
3c0ef626 428
429 /*
430 * Check that the versions match. In future this might accept
431 * several versions and set appropriate flags to handle them.
432 */
433 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
434 &remote_major, &remote_minor, remote_version) != 3) {
435 s = "Protocol mismatch.\n";
70791e56 436 (void) atomicio(vwrite, sock_out, s, strlen(s));
3c0ef626 437 close(sock_in);
438 close(sock_out);
70791e56 439 logit("Bad protocol version identification '%.100s' from %s",
3c0ef626 440 client_version_string, get_remote_ipaddr());
416fd2a8 441 cleanup_exit(255);
3c0ef626 442 }
443 debug("Client protocol version %d.%d; client software version %.100s",
1e608e42 444 remote_major, remote_minor, remote_version);
3c0ef626 445
446 compat_datafellows(remote_version);
447
e54b3d7c 448 if (datafellows & SSH_BUG_PROBE) {
70791e56 449 logit("probed from %s with %s. Don't panic.",
e54b3d7c 450 get_remote_ipaddr(), client_version_string);
416fd2a8 451 cleanup_exit(255);
e54b3d7c 452 }
453
3c0ef626 454 if (datafellows & SSH_BUG_SCANNER) {
70791e56 455 logit("scanned from %s with %s. Don't panic.",
3c0ef626 456 get_remote_ipaddr(), client_version_string);
416fd2a8 457 cleanup_exit(255);
3c0ef626 458 }
459
460 mismatch = 0;
1e608e42 461 switch (remote_major) {
3c0ef626 462 case 1:
463 if (remote_minor == 99) {
464 if (options.protocol & SSH_PROTO_2)
465 enable_compat20();
466 else
467 mismatch = 1;
468 break;
469 }
470 if (!(options.protocol & SSH_PROTO_1)) {
471 mismatch = 1;
472 break;
473 }
474 if (remote_minor < 3) {
475 packet_disconnect("Your ssh version is too old and "
476 "is no longer supported. Please install a newer version.");
477 } else if (remote_minor == 3) {
478 /* note that this disables agent-forwarding */
479 enable_compat13();
480 }
481 break;
482 case 2:
483 if (options.protocol & SSH_PROTO_2) {
484 enable_compat20();
485 break;
486 }
487 /* FALLTHROUGH */
488 default:
489 mismatch = 1;
490 break;
491 }
492 chop(server_version_string);
493 debug("Local version string %.200s", server_version_string);
494
495 if (mismatch) {
496 s = "Protocol major versions differ.\n";
70791e56 497 (void) atomicio(vwrite, sock_out, s, strlen(s));
3c0ef626 498 close(sock_in);
499 close(sock_out);
70791e56 500 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
3c0ef626 501 get_remote_ipaddr(),
502 server_version_string, client_version_string);
416fd2a8 503 cleanup_exit(255);
3c0ef626 504 }
505}
506
3c0ef626 507/* Destroy the host and server keys. They will no longer be needed. */
508void
509destroy_sensitive_data(void)
510{
511 int i;
512
513 if (sensitive_data.server_key) {
514 key_free(sensitive_data.server_key);
515 sensitive_data.server_key = NULL;
516 }
1e608e42 517 for (i = 0; i < options.num_host_key_files; i++) {
3c0ef626 518 if (sensitive_data.host_keys[i]) {
519 key_free(sensitive_data.host_keys[i]);
520 sensitive_data.host_keys[i] = NULL;
521 }
522 }
523 sensitive_data.ssh1_host_key = NULL;
524 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
525}
526
2980ea68 527/* Demote private to public keys for network child */
528void
529demote_sensitive_data(void)
530{
531 Key *tmp;
532 int i;
533
534 if (sensitive_data.server_key) {
535 tmp = key_demote(sensitive_data.server_key);
536 key_free(sensitive_data.server_key);
537 sensitive_data.server_key = tmp;
538 }
539
540 for (i = 0; i < options.num_host_key_files; i++) {
541 if (sensitive_data.host_keys[i]) {
542 tmp = key_demote(sensitive_data.host_keys[i]);
543 key_free(sensitive_data.host_keys[i]);
544 sensitive_data.host_keys[i] = tmp;
545 if (tmp->type == KEY_RSA1)
546 sensitive_data.ssh1_host_key = tmp;
547 }
548 }
549
550 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
551}
552
553static void
554privsep_preauth_child(void)
555{
e54b3d7c 556 u_int32_t rnd[256];
557 gid_t gidset[1];
2980ea68 558 struct passwd *pw;
ff2d7a98 559 int i;
2980ea68 560
561 /* Enable challenge-response authentication for privilege separation */
562 privsep_challenge_enable();
563
564 for (i = 0; i < 256; i++)
e54b3d7c 565 rnd[i] = arc4random();
566 RAND_seed(rnd, sizeof(rnd));
2980ea68 567
568 /* Demote the private keys to public keys. */
569 demote_sensitive_data();
570
571 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
572 fatal("Privilege separation user %s does not exist",
573 SSH_PRIVSEP_USER);
574 memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
575 endpwent();
576
e54b3d7c 577 /* Change our root directory */
2980ea68 578 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
579 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
580 strerror(errno));
581 if (chdir("/") == -1)
582 fatal("chdir(\"/\"): %s", strerror(errno));
583
584 /* Drop our privileges */
585 debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
586 (u_int)pw->pw_gid);
ff2d7a98 587#if 0
2a304a95 588 /* XXX not ready, too heavy after chroot */
2980ea68 589 do_setusercontext(pw);
ff2d7a98 590#else
591 gidset[0] = pw->pw_gid;
ff2d7a98 592 if (setgroups(1, gidset) < 0)
593 fatal("setgroups: %.100s", strerror(errno));
594 permanently_set_uid(pw);
595#endif
2980ea68 596}
597
416fd2a8 598static int
599privsep_preauth(Authctxt *authctxt)
2980ea68 600{
2980ea68 601 int status;
602 pid_t pid;
603
604 /* Set up unprivileged child process to deal with network data */
605 pmonitor = monitor_init();
606 /* Store a pointer to the kex for later rekeying */
607 pmonitor->m_pkex = &xxx_kex;
608
609 pid = fork();
610 if (pid == -1) {
611 fatal("fork of unprivileged child failed");
612 } else if (pid != 0) {
ff2d7a98 613 debug2("Network child is on pid %ld", (long)pid);
2980ea68 614
615 close(pmonitor->m_recvfd);
416fd2a8 616 pmonitor->m_pid = pid;
617 monitor_child_preauth(authctxt, pmonitor);
2980ea68 618 close(pmonitor->m_sendfd);
619
620 /* Sync memory */
621 monitor_sync(pmonitor);
622
623 /* Wait for the child's exit status */
624 while (waitpid(pid, &status, 0) < 0)
625 if (errno != EINTR)
626 break;
416fd2a8 627 return (1);
2980ea68 628 } else {
629 /* child */
630
631 close(pmonitor->m_sendfd);
632
633 /* Demote the child */
634 if (getuid() == 0 || geteuid() == 0)
635 privsep_preauth_child();
636 setproctitle("%s", "[net]");
637 }
416fd2a8 638 return (0);
2980ea68 639}
640
641static void
642privsep_postauth(Authctxt *authctxt)
643{
e54b3d7c 644#ifdef DISABLE_FD_PASSING
ff2d7a98 645 if (1) {
646#else
2980ea68 647 if (authctxt->pw->pw_uid == 0 || options.use_login) {
ff2d7a98 648#endif
2980ea68 649 /* File descriptor passing is broken or root login */
650 monitor_apply_keystate(pmonitor);
651 use_privsep = 0;
652 return;
653 }
654
655 /* Authentication complete */
656 alarm(0);
657 if (startup_pipe != -1) {
658 close(startup_pipe);
659 startup_pipe = -1;
660 }
661
662 /* New socket pair */
663 monitor_reinit(pmonitor);
664
665 pmonitor->m_pid = fork();
666 if (pmonitor->m_pid == -1)
667 fatal("fork of unprivileged child failed");
668 else if (pmonitor->m_pid != 0) {
ff2d7a98 669 debug2("User child is on pid %ld", (long)pmonitor->m_pid);
2980ea68 670 close(pmonitor->m_recvfd);
1b56ff3d 671 buffer_clear(&loginmsg);
2980ea68 672 monitor_child_postauth(pmonitor);
673
674 /* NEVERREACHED */
675 exit(0);
676 }
677
678 close(pmonitor->m_sendfd);
679
680 /* Demote the private keys to public keys. */
681 demote_sensitive_data();
682
683 /* Drop privileges */
684 do_setusercontext(authctxt->pw);
685
686 /* It is safe now to apply the key state */
687 monitor_apply_keystate(pmonitor);
688}
689
3c0ef626 690static char *
691list_hostkey_types(void)
692{
1e608e42 693 Buffer b;
416fd2a8 694 const char *p;
695 char *ret;
3c0ef626 696 int i;
1e608e42 697
698 buffer_init(&b);
699 for (i = 0; i < options.num_host_key_files; i++) {
3c0ef626 700 Key *key = sensitive_data.host_keys[i];
701 if (key == NULL)
702 continue;
1e608e42 703 switch (key->type) {
3c0ef626 704 case KEY_RSA:
705 case KEY_DSA:
1e608e42 706 if (buffer_len(&b) > 0)
707 buffer_append(&b, ",", 1);
708 p = key_ssh_name(key);
709 buffer_append(&b, p, strlen(p));
3c0ef626 710 break;
711 }
712 }
1e608e42 713 buffer_append(&b, "\0", 1);
416fd2a8 714 ret = xstrdup(buffer_ptr(&b));
1e608e42 715 buffer_free(&b);
416fd2a8 716 debug("list_hostkey_types: %s", ret);
717 return ret;
3c0ef626 718}
719
2980ea68 720Key *
3c0ef626 721get_hostkey_by_type(int type)
722{
723 int i;
ff2d7a98 724
1e608e42 725 for (i = 0; i < options.num_host_key_files; i++) {
3c0ef626 726 Key *key = sensitive_data.host_keys[i];
727 if (key != NULL && key->type == type)
728 return key;
729 }
730 return NULL;
731}
732
2980ea68 733Key *
734get_hostkey_by_index(int ind)
735{
736 if (ind < 0 || ind >= options.num_host_key_files)
737 return (NULL);
738 return (sensitive_data.host_keys[ind]);
739}
740
741int
742get_hostkey_index(Key *key)
743{
744 int i;
ff2d7a98 745
2980ea68 746 for (i = 0; i < options.num_host_key_files; i++) {
747 if (key == sensitive_data.host_keys[i])
748 return (i);
749 }
750 return (-1);
751}
752
3c0ef626 753/*
754 * returns 1 if connection should be dropped, 0 otherwise.
755 * dropping starts at connection #max_startups_begin with a probability
756 * of (max_startups_rate/100). the probability increases linearly until
757 * all connections are dropped for startups > max_startups
758 */
759static int
760drop_connection(int startups)
761{
762 double p, r;
763
764 if (startups < options.max_startups_begin)
765 return 0;
766 if (startups >= options.max_startups)
767 return 1;
768 if (options.max_startups_rate == 100)
769 return 1;
770
771 p = 100 - options.max_startups_rate;
772 p *= startups - options.max_startups_begin;
773 p /= (double) (options.max_startups - options.max_startups_begin);
774 p += options.max_startups_rate;
775 p /= 100.0;
776 r = arc4random() / (double) UINT_MAX;
777
778 debug("drop_connection: p %g, r %g", p, r);
779 return (r < p) ? 1 : 0;
780}
781
1e608e42 782static void
783usage(void)
784{
2a304a95 785 fprintf(stderr, "%s, %s\n",
416fd2a8 786 SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
2a304a95 787 fprintf(stderr,
788"usage: sshd [-46Ddeiqt] [-b bits] [-f config_file] [-g login_grace_time]\n"
789" [-h host_key_file] [-k key_gen_time] [-o option] [-p port] [-u len]\n"
790 );
1e608e42 791 exit(1);
792}
3c0ef626 793
1b56ff3d 794static void
795send_rexec_state(int fd, Buffer *conf)
796{
797 Buffer m;
798
799 debug3("%s: entering fd = %d config len %d", __func__, fd,
800 buffer_len(conf));
801
802 /*
803 * Protocol from reexec master to child:
804 * string configuration
805 * u_int ephemeral_key_follows
806 * bignum e (only if ephemeral_key_follows == 1)
807 * bignum n "
808 * bignum d "
809 * bignum iqmp "
810 * bignum p "
811 * bignum q "
812 */
813 buffer_init(&m);
814 buffer_put_cstring(&m, buffer_ptr(conf));
815
816 if (sensitive_data.server_key != NULL &&
817 sensitive_data.server_key->type == KEY_RSA1) {
818 buffer_put_int(&m, 1);
819 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
820 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
821 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
822 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
823 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
824 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
825 } else
826 buffer_put_int(&m, 0);
827
828 if (ssh_msg_send(fd, 0, &m) == -1)
829 fatal("%s: ssh_msg_send failed", __func__);
830
831 buffer_free(&m);
832
833 debug3("%s: done", __func__);
834}
835
836static void
837recv_rexec_state(int fd, Buffer *conf)
838{
839 Buffer m;
840 char *cp;
841 u_int len;
842
843 debug3("%s: entering fd = %d", __func__, fd);
844
845 buffer_init(&m);
846
847 if (ssh_msg_recv(fd, &m) == -1)
848 fatal("%s: ssh_msg_recv failed", __func__);
849 if (buffer_get_char(&m) != 0)
850 fatal("%s: rexec version mismatch", __func__);
851
852 cp = buffer_get_string(&m, &len);
853 if (conf != NULL)
854 buffer_append(conf, cp, len + 1);
855 xfree(cp);
856
857 if (buffer_get_int(&m)) {
858 if (sensitive_data.server_key != NULL)
859 key_free(sensitive_data.server_key);
860 sensitive_data.server_key = key_new_private(KEY_RSA1);
861 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
862 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
863 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
864 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
865 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
866 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
867 rsa_generate_additional_parameters(
868 sensitive_data.server_key->rsa);
869 }
870 buffer_free(&m);
871
872 debug3("%s: done", __func__);
873}
874
3c0ef626 875/*
876 * Main program for the daemon.
877 */
878int
879main(int ac, char **av)
880{
881 extern char *optarg;
882 extern int optind;
1b56ff3d 883 int opt, j, i, fdsetsz, on = 1;
884 int sock_in = -1, sock_out = -1, newsock = -1;
3c0ef626 885 pid_t pid;
886 socklen_t fromlen;
887 fd_set *fdset;
888 struct sockaddr_storage from;
889 const char *remote_ip;
890 int remote_port;
891 FILE *f;
3c0ef626 892 struct addrinfo *ai;
893 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
416fd2a8 894 char *line;
3c0ef626 895 int listen_sock, maxfd;
1b56ff3d 896 int startup_p[2], config_s[2];
3c0ef626 897 int startups = 0;
898 Key *key;
416fd2a8 899 Authctxt *authctxt;
3c0ef626 900 int ret, key_used = 0;
1b56ff3d 901 Buffer cfg;
3c0ef626 902
2980ea68 903#ifdef HAVE_SECUREWARE
904 (void)set_auth_parameters(ac, av);
905#endif
70791e56 906 __progname = ssh_get_progname(av[0]);
ae43c103 907 init_pathnames();
004706ea 908 config_file_name = _PATH_SERVER_CONFIG_FILE;
3c0ef626 909 init_rng();
910
1c14df9e 911 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
3c0ef626 912 saved_argc = ac;
1b56ff3d 913 rexec_argc = ac;
70791e56 914 saved_argv = xmalloc(sizeof(*saved_argv) * (ac + 1));
1c14df9e 915 for (i = 0; i < ac; i++)
916 saved_argv[i] = xstrdup(av[i]);
70791e56 917 saved_argv[i] = NULL;
1c14df9e 918
919#ifndef HAVE_SETPROCTITLE
920 /* Prepare for later setproctitle emulation */
921 compat_init_setproctitle(ac, av);
70791e56 922 av = saved_argv;
1c14df9e 923#endif
3c0ef626 924
2a304a95 925 if (geteuid() == 0 && setgroups(0, NULL) == -1)
926 debug("setgroups(): %.200s", strerror(errno));
927
3c0ef626 928 /* Initialize configuration options to their default values. */
929 initialize_server_options(&options);
930
931 /* Parse command-line arguments. */
1b56ff3d 932 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:dDeiqrtQR46")) != -1) {
3c0ef626 933 switch (opt) {
934 case '4':
935 IPv4or6 = AF_INET;
936 break;
937 case '6':
938 IPv4or6 = AF_INET6;
939 break;
940 case 'f':
941 config_file_name = optarg;
942 break;
943 case 'd':
70791e56 944 if (debug_flag == 0) {
3c0ef626 945 debug_flag = 1;
946 options.log_level = SYSLOG_LEVEL_DEBUG1;
70791e56 947 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
3c0ef626 948 options.log_level++;
3c0ef626 949 break;
950 case 'D':
951 no_daemon_flag = 1;
952 break;
953 case 'e':
954 log_stderr = 1;
955 break;
956 case 'i':
957 inetd_flag = 1;
958 break;
1b56ff3d 959 case 'r':
960 rexec_flag = 0;
961 break;
962 case 'R':
963 rexeced_flag = 1;
964 inetd_flag = 1;
965 break;
3c0ef626 966 case 'Q':
967 /* ignored */
968 break;
969 case 'q':
970 options.log_level = SYSLOG_LEVEL_QUIET;
971 break;
972 case 'b':
973 options.server_key_bits = atoi(optarg);
974 break;
975 case 'p':
976 options.ports_from_cmdline = 1;
977 if (options.num_ports >= MAX_PORTS) {
978 fprintf(stderr, "too many ports.\n");
979 exit(1);
980 }
981 options.ports[options.num_ports++] = a2port(optarg);
982 if (options.ports[options.num_ports-1] == 0) {
983 fprintf(stderr, "Bad port number.\n");
984 exit(1);
985 }
986 break;
987 case 'g':
988 if ((options.login_grace_time = convtime(optarg)) == -1) {
989 fprintf(stderr, "Invalid login grace time.\n");
990 exit(1);
991 }
992 break;
993 case 'k':
994 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
995 fprintf(stderr, "Invalid key regeneration interval.\n");
996 exit(1);
997 }
998 break;
999 case 'h':
1000 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1001 fprintf(stderr, "too many host keys.\n");
1002 exit(1);
1003 }
1004 options.host_key_files[options.num_host_key_files++] = optarg;
1005 break;
3c0ef626 1006 case 't':
1007 test_flag = 1;
1008 break;
1009 case 'u':
1010 utmp_len = atoi(optarg);
e54b3d7c 1011 if (utmp_len > MAXHOSTNAMELEN) {
1012 fprintf(stderr, "Invalid utmp length.\n");
1013 exit(1);
1014 }
3c0ef626 1015 break;
1e608e42 1016 case 'o':
416fd2a8 1017 line = xstrdup(optarg);
1018 if (process_server_config_line(&options, line,
1e608e42 1019 "command-line", 0) != 0)
1020 exit(1);
416fd2a8 1021 xfree(line);
1e608e42 1022 break;
3c0ef626 1023 case '?':
1024 default:
1e608e42 1025 usage();
1026 break;
3c0ef626 1027 }
1028 }
1b56ff3d 1029 if (rexeced_flag || inetd_flag)
1030 rexec_flag = 0;
1031 if (rexec_flag && (av[0] == NULL || *av[0] != '/'))
1032 fatal("sshd re-exec requires execution with an absolute path");
1033 if (rexeced_flag)
1034 closefrom(REEXEC_MIN_FREE_FD);
1035 else
1036 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1037
3c0ef626 1038 SSLeay_add_all_algorithms();
1039 channel_set_af(IPv4or6);
1040
1041 /*
1042 * Force logging to stderr until we have loaded the private host
1043 * key (unless started from inetd)
1044 */
1045 log_init(__progname,
1e608e42 1046 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1047 SYSLOG_LEVEL_INFO : options.log_level,
1048 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1049 SYSLOG_FACILITY_AUTH : options.log_facility,
1c14df9e 1050 log_stderr || !inetd_flag);
3c0ef626 1051
2a304a95 1052#ifdef _AIX
1053 /*
1054 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1055 * root's environment
1056 */
1057 unsetenv("KRB5CCNAME");
1058#endif /* _AIX */
e54b3d7c 1059#ifdef _UNICOS
1b56ff3d 1060 /* Cray can define user privs drop all privs now!
3c0ef626 1061 * Not needed on PRIV_SU systems!
1062 */
1063 drop_cray_privs();
1064#endif
1065
1066 seed_rng();
1067
1b56ff3d 1068 sensitive_data.server_key = NULL;
1069 sensitive_data.ssh1_host_key = NULL;
1070 sensitive_data.have_ssh1_key = 0;
1071 sensitive_data.have_ssh2_key = 0;
1072
1073 /* Fetch our configuration */
1074 buffer_init(&cfg);
1075 if (rexeced_flag)
1076 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1077 else
1078 load_server_config(config_file_name, &cfg);
1079
1080 parse_server_config(&options,
1081 rexeced_flag ? "rexec" : config_file_name, &cfg);
1082
1083 if (!rexec_flag)
1084 buffer_free(&cfg);
3c0ef626 1085
1086 /* Fill in default values for those options not explicitly set. */
1087 fill_default_server_options(&options);
1088
1089 /* Check that there are no remaining arguments. */
1090 if (optind < ac) {
1091 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1092 exit(1);
1093 }
1094
1095 debug("sshd version %.100s", SSH_VERSION);
1096
1097 /* load private host keys */
e54b3d7c 1098 sensitive_data.host_keys = xmalloc(options.num_host_key_files *
1099 sizeof(Key *));
1e608e42 1100 for (i = 0; i < options.num_host_key_files; i++)
3c0ef626 1101 sensitive_data.host_keys[i] = NULL;
3c0ef626 1102
1e608e42 1103 for (i = 0; i < options.num_host_key_files; i++) {
3c0ef626 1104 key = key_load_private(options.host_key_files[i], "", NULL);
1105 sensitive_data.host_keys[i] = key;
1106 if (key == NULL) {
1107 error("Could not load host key: %s",
1108 options.host_key_files[i]);
1109 sensitive_data.host_keys[i] = NULL;
1110 continue;
1111 }
1e608e42 1112 switch (key->type) {
3c0ef626 1113 case KEY_RSA1:
1114 sensitive_data.ssh1_host_key = key;
1115 sensitive_data.have_ssh1_key = 1;
1116 break;
1117 case KEY_RSA:
1118 case KEY_DSA:
1119 sensitive_data.have_ssh2_key = 1;
1120 break;
1121 }
1122 debug("private host key: #%d type %d %s", i, key->type,
1123 key_type(key));
1124 }
1125 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
70791e56 1126 logit("Disabling protocol version 1. Could not load host key");
3c0ef626 1127 options.protocol &= ~SSH_PROTO_1;
1128 }
5598e598 1129#ifndef GSSAPI
1130 /* The GSSAPI key exchange can run without a host key */
3c0ef626 1131 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
70791e56 1132 logit("Disabling protocol version 2. Could not load host key");
3c0ef626 1133 options.protocol &= ~SSH_PROTO_2;
1134 }
5598e598 1135#endif
3c0ef626 1136 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
70791e56 1137 logit("sshd: no hostkeys available -- exiting.");
3c0ef626 1138 exit(1);
1139 }
1140
1141 /* Check certain values for sanity. */
1142 if (options.protocol & SSH_PROTO_1) {
1143 if (options.server_key_bits < 512 ||
1144 options.server_key_bits > 32768) {
1145 fprintf(stderr, "Bad server key size.\n");
1146 exit(1);
1147 }
1148 /*
1149 * Check that server and host key lengths differ sufficiently. This
1150 * is necessary to make double encryption work with rsaref. Oh, I
1151 * hate software patents. I dont know if this can go? Niels
1152 */
1153 if (options.server_key_bits >
ff2d7a98 1154 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1155 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1156 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1157 SSH_KEY_BITS_RESERVED) {
3c0ef626 1158 options.server_key_bits =
ff2d7a98 1159 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1160 SSH_KEY_BITS_RESERVED;
3c0ef626 1161 debug("Forcing server key to %d bits to make it differ from host key.",
1162 options.server_key_bits);
1163 }
1164 }
1165
ff2d7a98 1166 if (use_privsep) {
1167 struct passwd *pw;
1168 struct stat st;
1169
1170 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
1171 fatal("Privilege separation user %s does not exist",
1172 SSH_PRIVSEP_USER);
1173 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1174 (S_ISDIR(st.st_mode) == 0))
1175 fatal("Missing privilege separation directory: %s",
1176 _PATH_PRIVSEP_CHROOT_DIR);
e54b3d7c 1177
1178#ifdef HAVE_CYGWIN
1179 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1180 (st.st_uid != getuid () ||
1181 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1182#else
ff2d7a98 1183 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
e54b3d7c 1184#endif
1c14df9e 1185 fatal("%s must be owned by root and not group or "
1186 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
ff2d7a98 1187 }
1188
3c0ef626 1189 /* Configuration looks good, so exit if in test mode. */
1190 if (test_flag)
1191 exit(0);
1192
2980ea68 1193 /*
1194 * Clear out any supplemental groups we may have inherited. This
1195 * prevents inadvertent creation of files with bad modes (in the
416fd2a8 1196 * portable version at least, it's certainly possible for PAM
1197 * to create a file, and we can't control the code in every
2980ea68 1198 * module which might be used).
1199 */
1200 if (setgroups(0, NULL) < 0)
1201 debug("setgroups() failed: %.200s", strerror(errno));
3c0ef626 1202
1b56ff3d 1203 if (rexec_flag) {
1204 rexec_argv = xmalloc(sizeof(char *) * (rexec_argc + 2));
1205 for (i = 0; i < rexec_argc; i++) {
1206 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1207 rexec_argv[i] = saved_argv[i];
1208 }
1209 rexec_argv[rexec_argc] = "-R";
1210 rexec_argv[rexec_argc + 1] = NULL;
1211 }
1212
3c0ef626 1213 /* Initialize the log (it is reinitialized below in case we forked). */
1214 if (debug_flag && !inetd_flag)
1215 log_stderr = 1;
1216 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1217
1218 /*
1219 * If not in debugging mode, and not started from inetd, disconnect
1220 * from the controlling terminal, and fork. The original process
1221 * exits.
1222 */
1223 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1224#ifdef TIOCNOTTY
1225 int fd;
1226#endif /* TIOCNOTTY */
1227 if (daemon(0, 0) < 0)
1228 fatal("daemon() failed: %.200s", strerror(errno));
1229
1230 /* Disconnect from the controlling tty. */
1231#ifdef TIOCNOTTY
1232 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1233 if (fd >= 0) {
1234 (void) ioctl(fd, TIOCNOTTY, NULL);
1235 close(fd);
1236 }
1237#endif /* TIOCNOTTY */
1238 }
1239 /* Reinitialize the log (because of the fork above). */
1240 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1241
1242 /* Initialize the random number generator. */
1243 arc4random_stir();
1244
1245 /* Chdir to the root directory so that the current disk can be
1246 unmounted if desired. */
1247 chdir("/");
1e608e42 1248
3c0ef626 1249 /* ignore SIGPIPE */
1250 signal(SIGPIPE, SIG_IGN);
1251
1252 /* Start listening for a socket, unless started from inetd. */
1253 if (inetd_flag) {
1b56ff3d 1254 int fd;
1255
3c0ef626 1256 startup_pipe = -1;
1b56ff3d 1257 if (rexeced_flag) {
1258 close(REEXEC_CONFIG_PASS_FD);
1259 sock_in = sock_out = dup(STDIN_FILENO);
1260 if (!debug_flag) {
1261 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1262 close(REEXEC_STARTUP_PIPE_FD);
1263 }
1264 } else {
1265 sock_in = dup(STDIN_FILENO);
1266 sock_out = dup(STDOUT_FILENO);
1267 }
3c0ef626 1268 /*
1269 * We intentionally do not close the descriptors 0, 1, and 2
1b56ff3d 1270 * as our code for setting the descriptors won't work if
3c0ef626 1271 * ttyfd happens to be one of those.
1272 */
1b56ff3d 1273 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1274 dup2(fd, STDIN_FILENO);
1275 dup2(fd, STDOUT_FILENO);
1276 if (fd > STDOUT_FILENO)
1277 close(fd);
1278 }
3c0ef626 1279 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1b56ff3d 1280 if ((options.protocol & SSH_PROTO_1) &&
1281 sensitive_data.server_key == NULL)
3c0ef626 1282 generate_ephemeral_server_key();
1283 } else {
1284 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1285 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1286 continue;
1287 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1288 fatal("Too many listen sockets. "
1289 "Enlarge MAX_LISTEN_SOCKS");
1290 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
1291 ntop, sizeof(ntop), strport, sizeof(strport),
1292 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1293 error("getnameinfo failed");
1294 continue;
1295 }
1296 /* Create socket for listening. */
70791e56 1297 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1298 ai->ai_protocol);
3c0ef626 1299 if (listen_sock < 0) {
1300 /* kernel may not support ipv6 */
1301 verbose("socket: %.100s", strerror(errno));
1302 continue;
1303 }
1b56ff3d 1304 if (set_nonblock(listen_sock) == -1) {
3c0ef626 1305 close(listen_sock);
1306 continue;
1307 }
1308 /*
e54b3d7c 1309 * Set socket options.
1310 * Allow local port reuse in TIME_WAIT.
3c0ef626 1311 */
e54b3d7c 1312 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1313 &on, sizeof(on)) == -1)
1314 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
3c0ef626 1315
1316 debug("Bind to port %s on %s.", strport, ntop);
1317
1318 /* Bind the socket to the desired port. */
1319 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1320 if (!ai->ai_next)
1321 error("Bind to port %s on %s failed: %.200s.",
1322 strport, ntop, strerror(errno));
1323 close(listen_sock);
1324 continue;
1325 }
1326 listen_socks[num_listen_socks] = listen_sock;
1327 num_listen_socks++;
1328
1329 /* Start listening on the port. */
70791e56 1330 logit("Server listening on %s port %s.", ntop, strport);
416fd2a8 1331 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
3c0ef626 1332 fatal("listen: %.100s", strerror(errno));
1333
1334 }
1335 freeaddrinfo(options.listen_addrs);
1336
1337 if (!num_listen_socks)
1338 fatal("Cannot bind any address.");
1339
1340 if (options.protocol & SSH_PROTO_1)
1341 generate_ephemeral_server_key();
1342
1343 /*
1344 * Arrange to restart on SIGHUP. The handler needs
1345 * listen_sock.
1346 */
1347 signal(SIGHUP, sighup_handler);
1348
1349 signal(SIGTERM, sigterm_handler);
1350 signal(SIGQUIT, sigterm_handler);
1351
1352 /* Arrange SIGCHLD to be caught. */
1353 signal(SIGCHLD, main_sigchld_handler);
1354
1355 /* Write out the pid file after the sigterm handler is setup */
1356 if (!debug_flag) {
1357 /*
1358 * Record our pid in /var/run/sshd.pid to make it
1359 * easier to kill the correct sshd. We don't want to
1360 * do this before the bind above because the bind will
1361 * fail if there already is a daemon, and this will
1362 * overwrite any old pid in the file.
1363 */
1364 f = fopen(options.pid_file, "wb");
70791e56 1365 if (f == NULL) {
1366 error("Couldn't create pid file \"%s\": %s",
1367 options.pid_file, strerror(errno));
1368 } else {
ff2d7a98 1369 fprintf(f, "%ld\n", (long) getpid());
3c0ef626 1370 fclose(f);
1371 }
1372 }
1373
1374 /* setup fd set for listen */
1375 fdset = NULL;
1376 maxfd = 0;
1377 for (i = 0; i < num_listen_socks; i++)
1378 if (listen_socks[i] > maxfd)
1379 maxfd = listen_socks[i];
1380 /* pipes connected to unauthenticated childs */
1381 startup_pipes = xmalloc(options.max_startups * sizeof(int));
1382 for (i = 0; i < options.max_startups; i++)
1383 startup_pipes[i] = -1;
1384
1385 /*
1386 * Stay listening for connections until the system crashes or
1387 * the daemon is killed with a signal.
1388 */
1389 for (;;) {
1390 if (received_sighup)
1391 sighup_restart();
1392 if (fdset != NULL)
1393 xfree(fdset);
1394 fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1395 fdset = (fd_set *)xmalloc(fdsetsz);
1396 memset(fdset, 0, fdsetsz);
1397
1398 for (i = 0; i < num_listen_socks; i++)
1399 FD_SET(listen_socks[i], fdset);
1400 for (i = 0; i < options.max_startups; i++)
1401 if (startup_pipes[i] != -1)
1402 FD_SET(startup_pipes[i], fdset);
1403
1404 /* Wait in select until there is a connection. */
1405 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1406 if (ret < 0 && errno != EINTR)
1407 error("select: %.100s", strerror(errno));
1408 if (received_sigterm) {
70791e56 1409 logit("Received signal %d; terminating.",
1e608e42 1410 (int) received_sigterm);
3c0ef626 1411 close_listen_socks();
1412 unlink(options.pid_file);
1413 exit(255);
1414 }
1415 if (key_used && key_do_regen) {
1416 generate_ephemeral_server_key();
1417 key_used = 0;
1418 key_do_regen = 0;
1419 }
1420 if (ret < 0)
1421 continue;
1422
1423 for (i = 0; i < options.max_startups; i++)
1424 if (startup_pipes[i] != -1 &&
1425 FD_ISSET(startup_pipes[i], fdset)) {
1426 /*
1427 * the read end of the pipe is ready
1428 * if the child has closed the pipe
1429 * after successful authentication
1430 * or if the child has died
1431 */
1432 close(startup_pipes[i]);
1433 startup_pipes[i] = -1;
1434 startups--;
1435 }
1436 for (i = 0; i < num_listen_socks; i++) {
1437 if (!FD_ISSET(listen_socks[i], fdset))
1438 continue;
1439 fromlen = sizeof(from);
1440 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
1441 &fromlen);
1442 if (newsock < 0) {
1443 if (errno != EINTR && errno != EWOULDBLOCK)
1444 error("accept: %.100s", strerror(errno));
1445 continue;
1446 }
1b56ff3d 1447 if (unset_nonblock(newsock) == -1) {
1e608e42 1448 close(newsock);
3c0ef626 1449 continue;
1450 }
1451 if (drop_connection(startups) == 1) {
1452 debug("drop connection #%d", startups);
1453 close(newsock);
1454 continue;
1455 }
1456 if (pipe(startup_p) == -1) {
1457 close(newsock);
1458 continue;
1459 }
1460
1b56ff3d 1461 if (rexec_flag && socketpair(AF_UNIX,
1462 SOCK_STREAM, 0, config_s) == -1) {
1463 error("reexec socketpair: %s",
1464 strerror(errno));
1465 close(newsock);
1466 close(startup_p[0]);
1467 close(startup_p[1]);
1468 continue;
1469 }
1470
3c0ef626 1471 for (j = 0; j < options.max_startups; j++)
1472 if (startup_pipes[j] == -1) {
1473 startup_pipes[j] = startup_p[0];
1474 if (maxfd < startup_p[0])
1475 maxfd = startup_p[0];
1476 startups++;
1477 break;
1478 }
1479
1480 /*
1481 * Got connection. Fork a child to handle it, unless
1482 * we are in debugging mode.
1483 */
1484 if (debug_flag) {
1485 /*
1486 * In debugging mode. Close the listening
1487 * socket, and start processing the
1488 * connection without forking.
1489 */
1490 debug("Server will not fork when running in debugging mode.");
1491 close_listen_socks();
1492 sock_in = newsock;
1493 sock_out = newsock;
1b56ff3d 1494 close(startup_p[0]);
1495 close(startup_p[1]);
3c0ef626 1496 startup_pipe = -1;
1497 pid = getpid();
1b56ff3d 1498 if (rexec_flag) {
1499 send_rexec_state(config_s[0],
1500 &cfg);
1501 close(config_s[0]);
1502 }
3c0ef626 1503 break;
1504 } else {
1505 /*
1506 * Normal production daemon. Fork, and have
1507 * the child process the connection. The
1508 * parent continues listening.
1509 */
1510 if ((pid = fork()) == 0) {
1511 /*
1512 * Child. Close the listening and max_startup
1513 * sockets. Start using the accepted socket.
1514 * Reinitialize logging (since our pid has
1515 * changed). We break out of the loop to handle
1516 * the connection.
1517 */
1518 startup_pipe = startup_p[1];
1e608e42 1519 close_startup_pipes();
3c0ef626 1520 close_listen_socks();
1521 sock_in = newsock;
1522 sock_out = newsock;
1523 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1b56ff3d 1524 close(config_s[0]);
3c0ef626 1525 break;
1526 }
1527 }
1528
1529 /* Parent. Stay in the loop. */
1530 if (pid < 0)
1531 error("fork: %.100s", strerror(errno));
1532 else
ff2d7a98 1533 debug("Forked child %ld.", (long)pid);
3c0ef626 1534
1535 close(startup_p[1]);
1536
1b56ff3d 1537 if (rexec_flag) {
1538 send_rexec_state(config_s[0], &cfg);
1539 close(config_s[0]);
1540 close(config_s[1]);
1541 }
1542
3c0ef626 1543 /* Mark that the key has been used (it was "given" to the child). */
1544 if ((options.protocol & SSH_PROTO_1) &&
1545 key_used == 0) {
1546 /* Schedule server key regeneration alarm. */
1547 signal(SIGALRM, key_regeneration_alarm);
1548 alarm(options.key_regeneration_time);
1549 key_used = 1;
1550 }
1551
1552 arc4random_stir();
1553
1554 /* Close the new socket (the child is now taking care of it). */
1555 close(newsock);
1556 }
1557 /* child process check (or debug mode) */
1558 if (num_listen_socks < 0)
1559 break;
1560 }
1561 }
1562
1563 /* This is the child processing a new connection. */
2a304a95 1564 setproctitle("%s", "[accepted]");
3c0ef626 1565
2980ea68 1566 /*
1567 * Create a new session and process group since the 4.4BSD
1568 * setlogin() affects the entire process group. We don't
1569 * want the child to be able to affect the parent.
1570 */
70791e56 1571#if !defined(SSHD_ACQUIRES_CTTY)
1c14df9e 1572 /*
70791e56 1573 * If setsid is called, on some platforms sshd will later acquire a
1574 * controlling terminal which will result in "could not set
1575 * controlling tty" errors.
1c14df9e 1576 */
ff2d7a98 1577 if (!debug_flag && !inetd_flag && setsid() < 0)
2980ea68 1578 error("setsid: %.100s", strerror(errno));
1579#endif
1580
1b56ff3d 1581 if (rexec_flag) {
1582 int fd;
1583
1584 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1585 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1586 dup2(newsock, STDIN_FILENO);
1587 dup2(STDIN_FILENO, STDOUT_FILENO);
1588 if (startup_pipe == -1)
1589 close(REEXEC_STARTUP_PIPE_FD);
1590 else
1591 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1592
1593 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1594 close(config_s[1]);
1595 if (startup_pipe != -1)
1596 close(startup_pipe);
1597
1598 execv(rexec_argv[0], rexec_argv);
1599
1600 /* Reexec has failed, fall back and continue */
1601 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1602 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1603 log_init(__progname, options.log_level,
1604 options.log_facility, log_stderr);
1605
1606 /* Clean up fds */
1607 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1608 close(config_s[1]);
1609 close(REEXEC_CONFIG_PASS_FD);
1610 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1611 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1612 dup2(fd, STDIN_FILENO);
1613 dup2(fd, STDOUT_FILENO);
1614 if (fd > STDERR_FILENO)
1615 close(fd);
1616 }
1617 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1618 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1619 }
1620
3c0ef626 1621 /*
1622 * Disable the key regeneration alarm. We will not regenerate the
1623 * key since we are no longer in a position to give it to anyone. We
1624 * will not restart on SIGHUP since it no longer makes sense.
1625 */
1626 alarm(0);
1627 signal(SIGALRM, SIG_DFL);
1628 signal(SIGHUP, SIG_DFL);
1629 signal(SIGTERM, SIG_DFL);
1630 signal(SIGQUIT, SIG_DFL);
1631 signal(SIGCHLD, SIG_DFL);
1632 signal(SIGINT, SIG_DFL);
1633
416fd2a8 1634 /* Set SO_KEEPALIVE if requested. */
1635 if (options.tcp_keep_alive &&
1e608e42 1636 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
3c0ef626 1637 sizeof(on)) < 0)
1638 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1639
1640 /*
1641 * Register our connection. This turns encryption off because we do
1642 * not have a key.
1643 */
1644 packet_set_connection(sock_in, sock_out);
1645
1646 remote_port = get_remote_port();
1647 remote_ip = get_remote_ipaddr();
1648
1649#ifdef LIBWRAP
1650 /* Check whether logins are denied from this host. */
1b56ff3d 1651 if (packet_connection_is_on_socket()) {
3c0ef626 1652 struct request_info req;
1653
1654 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1655 fromhost(&req);
1656
1657 if (!hosts_access(&req)) {
1658 debug("Connection refused by tcp wrapper");
1659 refuse(&req);
1660 /* NOTREACHED */
1661 fatal("libwrap refuse returns");
1662 }
1663 }
1664#endif /* LIBWRAP */
1665
1666 /* Log the connection. */
1667 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1668
1669 /*
1670 * We don\'t want to listen forever unless the other side
1671 * successfully authenticates itself. So we set up an alarm which is
1672 * cleared after successful authentication. A limit of zero
1673 * indicates no limit. Note that we don\'t set the alarm in debugging
1674 * mode; it is just annoying to have the server exit just when you
1675 * are about to discover the bug.
1676 */
1677 signal(SIGALRM, grace_alarm_handler);
1678 if (!debug_flag)
1679 alarm(options.login_grace_time);
1680
1681 sshd_exchange_identification(sock_in, sock_out);
70791e56 1682#if defined(AFS_KRB5)
3c0ef626 1683 /* If machine has AFS, set process authentication group. */
1684 if (k_hasafs()) {
1685 k_setpag();
1686 k_unlog();
1687 }
f2fd21a2 1688#endif /* AFS || AFS_KRB5 */
3c0ef626 1689
1690 packet_set_nonblocking();
1691
416fd2a8 1692 /* prepare buffers to collect authentication messages */
70791e56 1693 buffer_init(&loginmsg);
1694
416fd2a8 1695 /* allocate authentication context */
1696 authctxt = xmalloc(sizeof(*authctxt));
1697 memset(authctxt, 0, sizeof(*authctxt));
1698
1699 /* XXX global for cleanup, access from other modules */
1700 the_authctxt = authctxt;
1701
2980ea68 1702 if (use_privsep)
416fd2a8 1703 if (privsep_preauth(authctxt) == 1)
2980ea68 1704 goto authenticated;
1705
1b56ff3d 1706 /* prepare buffer to collect messages to display to user after login */
1707 buffer_init(&loginmsg);
1708
3c0ef626 1709 /* perform the key exchange */
1710 /* authenticate user and start session */
1711 if (compat20) {
1712 do_ssh2_kex();
416fd2a8 1713 do_authentication2(authctxt);
3c0ef626 1714 } else {
1715 do_ssh1_kex();
416fd2a8 1716 do_authentication(authctxt);
2980ea68 1717 }
1718 /*
1719 * If we use privilege separation, the unprivileged child transfers
1720 * the current keystate and exits
1721 */
1722 if (use_privsep) {
1723 mm_send_keystate(pmonitor);
1724 exit(0);
3c0ef626 1725 }
2980ea68 1726
1727 authenticated:
1728 /*
1729 * In privilege separation, we fork another child and prepare
1730 * file descriptor passing.
1731 */
1732 if (use_privsep) {
1733 privsep_postauth(authctxt);
1734 /* the monitor process [priv] will not return */
1735 if (!compat20)
1736 destroy_sensitive_data();
1737 }
1738
416fd2a8 1739 /* Start session. */
2980ea68 1740 do_authenticated(authctxt);
1741
3c0ef626 1742 /* The connection has been terminated. */
1743 verbose("Closing connection to %.100s", remote_ip);
1744
1745#ifdef USE_PAM
70791e56 1746 if (options.use_pam)
1747 finish_pam();
3c0ef626 1748#endif /* USE_PAM */
1749
1750 packet_close();
2980ea68 1751
1752 if (use_privsep)
1753 mm_terminate();
1754
3c0ef626 1755 exit(0);
1756}
1757
2980ea68 1758/*
1759 * Decrypt session_key_int using our private server key and private host key
1760 * (key with larger modulus first).
1761 */
1762int
1763ssh1_session_key(BIGNUM *session_key_int)
1764{
1765 int rsafail = 0;
1766
1767 if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1768 /* Server key has bigger modulus. */
1769 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1770 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1771 fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1772 get_remote_ipaddr(),
1773 BN_num_bits(sensitive_data.server_key->rsa->n),
1774 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1775 SSH_KEY_BITS_RESERVED);
1776 }
1777 if (rsa_private_decrypt(session_key_int, session_key_int,
1778 sensitive_data.server_key->rsa) <= 0)
1779 rsafail++;
1780 if (rsa_private_decrypt(session_key_int, session_key_int,
1781 sensitive_data.ssh1_host_key->rsa) <= 0)
1782 rsafail++;
1783 } else {
1784 /* Host key has bigger modulus (or they are equal). */
1785 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1786 BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1787 fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1788 get_remote_ipaddr(),
1789 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1790 BN_num_bits(sensitive_data.server_key->rsa->n),
1791 SSH_KEY_BITS_RESERVED);
1792 }
1793 if (rsa_private_decrypt(session_key_int, session_key_int,
1794 sensitive_data.ssh1_host_key->rsa) < 0)
1795 rsafail++;
1796 if (rsa_private_decrypt(session_key_int, session_key_int,
1797 sensitive_data.server_key->rsa) < 0)
1798 rsafail++;
1799 }
1800 return (rsafail);
1801}
3c0ef626 1802/*
1803 * SSH1 key exchange
1804 */
1805static void
1806do_ssh1_kex(void)
1807{
1808 int i, len;
3c0ef626 1809 int rsafail = 0;
1810 BIGNUM *session_key_int;
1811 u_char session_key[SSH_SESSION_KEY_LENGTH];
1812 u_char cookie[8];
1813 u_int cipher_type, auth_mask, protocol_flags;
e54b3d7c 1814 u_int32_t rnd = 0;
3c0ef626 1815
1816 /*
1817 * Generate check bytes that the client must send back in the user
1818 * packet in order for it to be accepted; this is used to defy ip
1819 * spoofing attacks. Note that this only works against somebody
1820 * doing IP spoofing from a remote machine; any machine on the local
1821 * network can still see outgoing packets and catch the random
1822 * cookie. This only affects rhosts authentication, and this is one
1823 * of the reasons why it is inherently insecure.
1824 */
1825 for (i = 0; i < 8; i++) {
1826 if (i % 4 == 0)
e54b3d7c 1827 rnd = arc4random();
1828 cookie[i] = rnd & 0xff;
1829 rnd >>= 8;
3c0ef626 1830 }
1831
1832 /*
1833 * Send our public key. We include in the packet 64 bits of random
1834 * data that must be matched in the reply in order to prevent IP
1835 * spoofing.
1836 */
1837 packet_start(SSH_SMSG_PUBLIC_KEY);
1838 for (i = 0; i < 8; i++)
1839 packet_put_char(cookie[i]);
1840
1841 /* Store our public server RSA key. */
1842 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1843 packet_put_bignum(sensitive_data.server_key->rsa->e);
1844 packet_put_bignum(sensitive_data.server_key->rsa->n);
1845
1846 /* Store our public host RSA key. */
1847 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1848 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1849 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1850
1851 /* Put protocol flags. */
1852 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1853
1854 /* Declare which ciphers we support. */
1855 packet_put_int(cipher_mask_ssh1(0));
1856
1857 /* Declare supported authentication types. */
1858 auth_mask = 0;
3c0ef626 1859 if (options.rhosts_rsa_authentication)
1860 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1861 if (options.rsa_authentication)
1862 auth_mask |= 1 << SSH_AUTH_RSA;
ff2d7a98 1863 if (options.challenge_response_authentication == 1)
1864 auth_mask |= 1 << SSH_AUTH_TIS;
3c0ef626 1865 if (options.password_authentication)
1866 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1867 packet_put_int(auth_mask);
1868
1869 /* Send the packet and wait for it to be sent. */
1870 packet_send();
1871 packet_write_wait();
1872
1873 debug("Sent %d bit server key and %d bit host key.",
1874 BN_num_bits(sensitive_data.server_key->rsa->n),
1875 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1876
1877 /* Read clients reply (cipher type and session key). */
1e608e42 1878 packet_read_expect(SSH_CMSG_SESSION_KEY);
3c0ef626 1879
1880 /* Get cipher type and check whether we accept this. */
1881 cipher_type = packet_get_char();
1882
1883 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1884 packet_disconnect("Warning: client selects unsupported cipher.");
1885
1886 /* Get check bytes from the packet. These must match those we
1887 sent earlier with the public key packet. */
1888 for (i = 0; i < 8; i++)
1889 if (cookie[i] != packet_get_char())
1890 packet_disconnect("IP Spoofing check bytes do not match.");
1891
1892 debug("Encryption type: %.200s", cipher_name(cipher_type));
1893
1894 /* Get the encrypted integer. */
1e608e42 1895 if ((session_key_int = BN_new()) == NULL)
1896 fatal("do_ssh1_kex: BN_new failed");
1897 packet_get_bignum(session_key_int);
3c0ef626 1898
1899 protocol_flags = packet_get_int();
1900 packet_set_protocol_flags(protocol_flags);
1e608e42 1901 packet_check_eom();
3c0ef626 1902
2980ea68 1903 /* Decrypt session_key_int using host/server keys */
1904 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
1905
3c0ef626 1906 /*
1907 * Extract session key from the decrypted integer. The key is in the
1908 * least significant 256 bits of the integer; the first byte of the
1909 * key is in the highest bits.
1910 */
1911 if (!rsafail) {
1912 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1913 len = BN_num_bytes(session_key_int);
1914 if (len < 0 || len > sizeof(session_key)) {
1915 error("do_connection: bad session key len from %s: "
1916 "session_key_int %d > sizeof(session_key) %lu",
1917 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1918 rsafail++;
1919 } else {
1920 memset(session_key, 0, sizeof(session_key));
1921 BN_bn2bin(session_key_int,
1922 session_key + sizeof(session_key) - len);
1923
1b56ff3d 1924 derive_ssh1_session_id(
3c0ef626 1925 sensitive_data.ssh1_host_key->rsa->n,
1b56ff3d 1926 sensitive_data.server_key->rsa->n,
1927 cookie, session_id);
3c0ef626 1928 /*
1929 * Xor the first 16 bytes of the session key with the
1930 * session id.
1931 */
1932 for (i = 0; i < 16; i++)
1933 session_key[i] ^= session_id[i];
1934 }
1935 }
1936 if (rsafail) {
1937 int bytes = BN_num_bytes(session_key_int);
1e608e42 1938 u_char *buf = xmalloc(bytes);
3c0ef626 1939 MD5_CTX md;
1940
70791e56 1941 logit("do_connection: generating a fake encryption key");
3c0ef626 1942 BN_bn2bin(session_key_int, buf);
1943 MD5_Init(&md);
1944 MD5_Update(&md, buf, bytes);
1945 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1946 MD5_Final(session_key, &md);
1947 MD5_Init(&md);
1948 MD5_Update(&md, session_key, 16);
1949 MD5_Update(&md, buf, bytes);
1950 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1951 MD5_Final(session_key + 16, &md);
1952 memset(buf, 0, bytes);
1953 xfree(buf);
1954 for (i = 0; i < 16; i++)
1955 session_id[i] = session_key[i] ^ session_key[i + 16];
1956 }
2980ea68 1957 /* Destroy the private and public keys. No longer. */
3c0ef626 1958 destroy_sensitive_data();
1959
2980ea68 1960 if (use_privsep)
1961 mm_ssh1_session_id(session_id);
1962
3c0ef626 1963 /* Destroy the decrypted integer. It is no longer needed. */
1964 BN_clear_free(session_key_int);
1965
1966 /* Set the session key. From this on all communications will be encrypted. */
1967 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1968
1969 /* Destroy our copy of the session key. It is no longer needed. */
1970 memset(session_key, 0, sizeof(session_key));
1971
1972 debug("Received session key; encryption turned on.");
1973
ff2d7a98 1974 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
3c0ef626 1975 packet_start(SSH_SMSG_SUCCESS);
1976 packet_send();
1977 packet_write_wait();
1978}
1979
1980/*
1981 * SSH2 key exchange: diffie-hellman-group1-sha1
1982 */
1983static void
1984do_ssh2_kex(void)
1985{
1986 Kex *kex;
1987
1988 if (options.ciphers != NULL) {
1989 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1990 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1991 }
1992 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1993 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1994 myproposal[PROPOSAL_ENC_ALGS_STOC] =
1995 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1996
1997 if (options.macs != NULL) {
1998 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1999 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2000 }
ff2d7a98 2001 if (!options.compression) {
2002 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2003 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2004 }
3c0ef626 2005 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2006
5598e598 2007#ifdef GSSAPI
2008 {
2009 char *orig;
2010 char *gss = NULL;
2011 char *newstr = NULL;
2012 orig = myproposal[PROPOSAL_KEX_ALGS];
2013
2014 /* If we don't have a host key, then all of the algorithms
2015 * currently in myproposal are useless */
2016 if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])==0)
2017 orig= NULL;
2018
2019 if (options.gss_keyex)
88928908 2020 gss = ssh_gssapi_server_mechanisms();
5598e598 2021 else
2022 gss = NULL;
2023
2024 if (gss && orig) {
2025 int len = strlen(orig) + strlen(gss) +2;
2026 newstr=xmalloc(len);
2027 snprintf(newstr,len,"%s,%s",gss,orig);
2028 } else if (gss) {
2029 newstr=gss;
2030 } else if (orig) {
2031 newstr=orig;
2032 }
2033 /* If we've got GSSAPI mechanisms, then we've also got the 'null'
2034 host key algorithm, but we're not allowed to advertise it, unless
2035 its the only host key algorithm we're supporting */
2036 if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0) {
2037 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]="null";
2038 }
2039 if (newstr)
2040 myproposal[PROPOSAL_KEX_ALGS]=newstr;
2041 else
2042 fatal("No supported key exchange algorithms");
2043 }
2044#endif
2045
3c0ef626 2046 /* start key exchange */
2047 kex = kex_setup(myproposal);
1c14df9e 2048 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1b56ff3d 2049 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1c14df9e 2050 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2051#ifdef GSSAPI
2052 kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
2053#endif
3c0ef626 2054 kex->server = 1;
2055 kex->client_version_string=client_version_string;
2056 kex->server_version_string=server_version_string;
2057 kex->load_host_key=&get_hostkey_by_type;
2980ea68 2058 kex->host_key_index=&get_hostkey_index;
3c0ef626 2059
2060 xxx_kex = kex;
2061
2062 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2063
2064 session_id2 = kex->session_id;
2065 session_id2_len = kex->session_id_len;
2066
2067#ifdef DEBUG_KEXDH
2068 /* send 1st encrypted/maced/compressed message */
2069 packet_start(SSH2_MSG_IGNORE);
2070 packet_put_cstring("markus");
2071 packet_send();
2072 packet_write_wait();
2073#endif
2074 debug("KEX done");
2075}
416fd2a8 2076
2077/* server specific fatal cleanup */
2078void
2079cleanup_exit(int i)
2080{
2081 if (the_authctxt)
2082 do_cleanup(the_authctxt);
2083 _exit(i);
2084}
This page took 0.373492 seconds and 5 git commands to generate.