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