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