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