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