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