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