]> andersk Git - openssh.git/blame - sshd.c
- (djm) OpenBSD CVS Sync
[openssh.git] / sshd.c
CommitLineData
8efc0c15 1/*
5260325f 2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 * All rights reserved
bcbf86ec 5 * This program is the ssh daemon. It listens for connections from clients,
6 * and performs authentication, executes use commands or shell, and forwards
5260325f 7 * information to/from the application to the user client over an encrypted
bcbf86ec 8 * connection. This can also handle forwarding of X11, TCP/IP, and
9 * authentication agent connections.
e78a59f5 10 *
bcbf86ec 11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
16 *
17 * SSH2 implementation:
1853d1ef 18 * Privilege Separation:
bcbf86ec 19 *
1853d1ef 20 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
21 * Copyright (c) 2002 Niels Provos. All rights reserved.
bcbf86ec 22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 *
32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5260325f 42 */
8efc0c15 43
44#include "includes.h"
8c38e88b 45RCSID("$OpenBSD: sshd.c,v 1.239 2002/03/30 18:51:15 markus Exp $");
8efc0c15 46
42f11eb2 47#include <openssl/dh.h>
48#include <openssl/bn.h>
436c347c 49#include <openssl/md5.h>
1853d1ef 50#include <openssl/rand.h>
42f11eb2 51
52#include "ssh.h"
53#include "ssh1.h"
54#include "ssh2.h"
8efc0c15 55#include "xmalloc.h"
56#include "rsa.h"
1729c161 57#include "sshpty.h"
8efc0c15 58#include "packet.h"
8efc0c15 59#include "mpaux.h"
42f11eb2 60#include "log.h"
8efc0c15 61#include "servconf.h"
62#include "uidswap.h"
63#include "compat.h"
7368a6c8 64#include "buffer.h"
42f11eb2 65#include "cipher.h"
e78a59f5 66#include "kex.h"
7368a6c8 67#include "key.h"
94ec8c6b 68#include "dh.h"
e78a59f5 69#include "myproposal.h"
a306f2dd 70#include "authfile.h"
42f11eb2 71#include "pathnames.h"
72#include "atomicio.h"
73#include "canohost.h"
74#include "auth.h"
75#include "misc.h"
a5c9ffdb 76#include "dispatch.h"
e4d7f734 77#include "channels.h"
1b34c1b3 78#include "session.h"
1853d1ef 79#include "monitor_mm.h"
80#include "monitor.h"
81#include "monitor_wrap.h"
82#include "monitor_fdpass.h"
8efc0c15 83
84#ifdef LIBWRAP
85#include <tcpd.h>
86#include <syslog.h>
87int allow_severity = LOG_INFO;
88int deny_severity = LOG_WARNING;
89#endif /* LIBWRAP */
90
91#ifndef O_NOCTTY
92#define O_NOCTTY 0
93#endif
94
260d427b 95#ifdef HAVE___PROGNAME
96extern char *__progname;
97#else
98char *__progname;
99#endif
100
8efc0c15 101/* Server configuration options. */
102ServerOptions options;
103
104/* Name of the server configuration file. */
42f11eb2 105char *config_file_name = _PATH_SERVER_CONFIG_FILE;
8efc0c15 106
6ae2364d 107/*
48e671d5 108 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
109 * Default value is AF_UNSPEC means both IPv4 and IPv6.
110 */
59e76f33 111#ifdef IPV4_DEFAULT
112int IPv4or6 = AF_INET;
113#else
48e671d5 114int IPv4or6 = AF_UNSPEC;
59e76f33 115#endif
48e671d5 116
5260325f 117/*
118 * Debug mode flag. This can be set on the command line. If debug
119 * mode is enabled, extra debugging output will be sent to the system
120 * log, the daemon will not go to background, and will exit after processing
121 * the first connection.
122 */
8efc0c15 123int debug_flag = 0;
124
f87f09aa 125/* Flag indicating that the daemon should only test the configuration and keys. */
126int test_flag = 0;
127
8efc0c15 128/* Flag indicating that the daemon is being started from inetd. */
129int inetd_flag = 0;
130
0b6fbf03 131/* Flag indicating that sshd should not detach and become a daemon. */
132int no_daemon_flag = 0;
133
6a17f9c2 134/* debug goes to stderr unless inetd_flag is set */
135int log_stderr = 0;
136
8efc0c15 137/* Saved arguments to main(). */
138char **saved_argv;
4d33e531 139int saved_argc;
8efc0c15 140
aa3378df 141/*
48e671d5 142 * The sockets that the server is listening; this is used in the SIGHUP
143 * signal handler.
aa3378df 144 */
48e671d5 145#define MAX_LISTEN_SOCKS 16
146int listen_socks[MAX_LISTEN_SOCKS];
147int num_listen_socks = 0;
8efc0c15 148
aa3378df 149/*
150 * the client's version string, passed by sshd2 in compat mode. if != NULL,
151 * sshd will skip the version-number exchange
152 */
5260325f 153char *client_version_string = NULL;
7368a6c8 154char *server_version_string = NULL;
8efc0c15 155
7a37c112 156/* for rekeying XXX fixme */
157Kex *xxx_kex;
158
aa3378df 159/*
160 * Any really sensitive data in the application is contained in this
161 * structure. The idea is that this structure could be locked into memory so
162 * that the pages do not get written into swap. However, there are some
163 * problems. The private key contains BIGNUMs, and we do not (in principle)
164 * have access to the internals of them, and locking just the structure is
165 * not very useful. Currently, memory locking is not implemented.
166 */
5260325f 167struct {
cb7bd922 168 Key *server_key; /* ephemeral server key */
fa08c86b 169 Key *ssh1_host_key; /* ssh1 host key */
170 Key **host_keys; /* all private host keys */
171 int have_ssh1_key;
172 int have_ssh2_key;
00be5382 173 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
8efc0c15 174} sensitive_data;
175
aa3378df 176/*
59c97189 177 * Flag indicating whether the RSA server key needs to be regenerated.
178 * Is set in the SIGALRM handler and cleared when the key is regenerated.
aa3378df 179 */
7a934d1b 180static volatile sig_atomic_t key_do_regen = 0;
8efc0c15 181
c9130033 182/* This is set to true when a signal is received. */
7a934d1b 183static volatile sig_atomic_t received_sighup = 0;
184static volatile sig_atomic_t received_sigterm = 0;
8efc0c15 185
7368a6c8 186/* session identifier, used by RSA-auth */
1e3b8b07 187u_char session_id[16];
e7c0f9d5 188
a306f2dd 189/* same for ssh2 */
1e3b8b07 190u_char *session_id2 = NULL;
a306f2dd 191int session_id2_len = 0;
192
c345cf9d 193/* record remote hostname or ip */
1e3b8b07 194u_int utmp_len = MAXHOSTNAMELEN;
c345cf9d 195
7ace8c3b 196/* options.max_startup sized array of fd ints */
197int *startup_pipes = NULL;
198int startup_pipe; /* in child */
199
1853d1ef 200/* variables used for privilege separation */
201extern struct monitor *monitor;
202extern int use_privsep;
203
7368a6c8 204/* Prototypes for various functions defined later in this file. */
396c147e 205void destroy_sensitive_data(void);
1853d1ef 206void demote_sensitive_data(void);
c8d54615 207
396c147e 208static void do_ssh1_kex(void);
209static void do_ssh2_kex(void);
94ec8c6b 210
48e671d5 211/*
212 * Close all listening sockets
213 */
396c147e 214static void
48e671d5 215close_listen_socks(void)
216{
217 int i;
218 for (i = 0; i < num_listen_socks; i++)
219 close(listen_socks[i]);
220 num_listen_socks = -1;
221}
222
7ace8c3b 223static void
224close_startup_pipes(void)
225{
226 int i;
227 if (startup_pipes)
228 for (i = 0; i < options.max_startups; i++)
229 if (startup_pipes[i] != -1)
230 close(startup_pipes[i]);
231}
232
5260325f 233/*
234 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
235 * the effect is to reread the configuration file (and to regenerate
236 * the server key).
237 */
396c147e 238static void
5260325f 239sighup_handler(int sig)
8efc0c15 240{
6056eb35 241 int save_errno = errno;
242
5260325f 243 received_sighup = 1;
244 signal(SIGHUP, sighup_handler);
6056eb35 245 errno = save_errno;
8efc0c15 246}
247
5260325f 248/*
249 * Called from the main program after receiving SIGHUP.
250 * Restarts the server.
251 */
396c147e 252static void
5ca51e19 253sighup_restart(void)
8efc0c15 254{
5260325f 255 log("Received SIGHUP; restarting.");
48e671d5 256 close_listen_socks();
7ace8c3b 257 close_startup_pipes();
5260325f 258 execv(saved_argv[0], saved_argv);
1fe6a48f 259 log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], strerror(errno));
5260325f 260 exit(1);
8efc0c15 261}
262
5260325f 263/*
264 * Generic signal handler for terminating signals in the master daemon.
5260325f 265 */
396c147e 266static void
5260325f 267sigterm_handler(int sig)
8efc0c15 268{
c9130033 269 received_sigterm = sig;
8efc0c15 270}
271
5260325f 272/*
273 * SIGCHLD handler. This is called whenever a child dies. This will then
c9130033 274 * reap any zombies left by exited children.
5260325f 275 */
396c147e 276static void
5260325f 277main_sigchld_handler(int sig)
8efc0c15 278{
8c38e88b 279 pid_t pid;
5260325f 280 int save_errno = errno;
281 int status;
5ad13cd7 282
8c38e88b 283 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
284 (pid < 0 && errno == EINTR))
5260325f 285 ;
5ad13cd7 286
5260325f 287 signal(SIGCHLD, main_sigchld_handler);
288 errno = save_errno;
8efc0c15 289}
290
5260325f 291/*
292 * Signal handler for the alarm after the login grace period has expired.
293 */
396c147e 294static void
5260325f 295grace_alarm_handler(int sig)
8efc0c15 296{
c9130033 297 /* XXX no idea how fix this signal handler */
298
5260325f 299 /* Close the connection. */
300 packet_close();
8efc0c15 301
5260325f 302 /* Log error and exit. */
303 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
304}
8efc0c15 305
5260325f 306/*
307 * Signal handler for the key regeneration alarm. Note that this
308 * alarm only occurs in the daemon waiting for connections, and it does not
309 * do anything with the private key or random state before forking.
310 * Thus there should be no concurrency control/asynchronous execution
311 * problems.
312 */
396c147e 313static void
cb7bd922 314generate_ephemeral_server_key(void)
fa08c86b 315{
00be5382 316 u_int32_t rand = 0;
317 int i;
318
cd332296 319 verbose("Generating %s%d bit RSA key.",
76ca7b01 320 sensitive_data.server_key ? "new " : "", options.server_key_bits);
fa08c86b 321 if (sensitive_data.server_key != NULL)
322 key_free(sensitive_data.server_key);
cd332296 323 sensitive_data.server_key = key_generate(KEY_RSA1,
76ca7b01 324 options.server_key_bits);
325 verbose("RSA key generation complete.");
00be5382 326
327 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
328 if (i % 4 == 0)
329 rand = arc4random();
330 sensitive_data.ssh1_cookie[i] = rand & 0xff;
331 rand >>= 8;
332 }
333 arc4random_stir();
fa08c86b 334}
f546c780 335
396c147e 336static void
5260325f 337key_regeneration_alarm(int sig)
338{
339 int save_errno = errno;
59c97189 340 signal(SIGALRM, SIG_DFL);
5260325f 341 errno = save_errno;
59c97189 342 key_do_regen = 1;
5260325f 343}
8efc0c15 344
396c147e 345static void
7368a6c8 346sshd_exchange_identification(int sock_in, int sock_out)
347{
a8be9f80 348 int i, mismatch;
7368a6c8 349 int remote_major, remote_minor;
a8be9f80 350 int major, minor;
7368a6c8 351 char *s;
352 char buf[256]; /* Must not be larger than remote_version. */
353 char remote_version[256]; /* Must be at least as big as buf. */
354
a8be9f80 355 if ((options.protocol & SSH_PROTO_1) &&
356 (options.protocol & SSH_PROTO_2)) {
357 major = PROTOCOL_MAJOR_1;
358 minor = 99;
359 } else if (options.protocol & SSH_PROTO_2) {
360 major = PROTOCOL_MAJOR_2;
361 minor = PROTOCOL_MINOR_2;
362 } else {
363 major = PROTOCOL_MAJOR_1;
364 minor = PROTOCOL_MINOR_1;
365 }
366 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
7368a6c8 367 server_version_string = xstrdup(buf);
368
369 if (client_version_string == NULL) {
370 /* Send our protocol version identification. */
371 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
372 != strlen(server_version_string)) {
30f60c34 373 log("Could not write ident string to %s", get_remote_ipaddr());
7368a6c8 374 fatal_cleanup();
375 }
376
2ce1adf9 377 /* Read other side's version identification. */
cd332296 378 memset(buf, 0, sizeof(buf));
7368a6c8 379 for (i = 0; i < sizeof(buf) - 1; i++) {
e5a0294f 380 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
30f60c34 381 log("Did not receive identification string from %s",
c2b544a5 382 get_remote_ipaddr());
7368a6c8 383 fatal_cleanup();
384 }
385 if (buf[i] == '\r') {
8a169574 386 buf[i] = 0;
94ec8c6b 387 /* Kludge for F-Secure Macintosh < 1.0.2 */
388 if (i == 12 &&
389 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
390 break;
7368a6c8 391 continue;
7368a6c8 392 }
393 if (buf[i] == '\n') {
8a169574 394 buf[i] = 0;
7368a6c8 395 break;
396 }
397 }
398 buf[sizeof(buf) - 1] = 0;
399 client_version_string = xstrdup(buf);
400 }
401
402 /*
403 * Check that the versions match. In future this might accept
404 * several versions and set appropriate flags to handle them.
405 */
406 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
407 &remote_major, &remote_minor, remote_version) != 3) {
6ae2364d 408 s = "Protocol mismatch.\n";
7368a6c8 409 (void) atomicio(write, sock_out, s, strlen(s));
410 close(sock_in);
411 close(sock_out);
412 log("Bad protocol version identification '%.100s' from %s",
413 client_version_string, get_remote_ipaddr());
414 fatal_cleanup();
415 }
416 debug("Client protocol version %d.%d; client software version %.100s",
184eed6a 417 remote_major, remote_minor, remote_version);
7368a6c8 418
e78a59f5 419 compat_datafellows(remote_version);
420
3a1c54d4 421 if (datafellows & SSH_BUG_SCANNER) {
422 log("scanned from %s with %s. Don't panic.",
423 get_remote_ipaddr(), client_version_string);
424 fatal_cleanup();
425 }
426
a8be9f80 427 mismatch = 0;
6aacefa7 428 switch (remote_major) {
7368a6c8 429 case 1:
a306f2dd 430 if (remote_minor == 99) {
431 if (options.protocol & SSH_PROTO_2)
432 enable_compat20();
433 else
434 mismatch = 1;
435 break;
436 }
a8be9f80 437 if (!(options.protocol & SSH_PROTO_1)) {
438 mismatch = 1;
439 break;
440 }
7368a6c8 441 if (remote_minor < 3) {
089fbbd2 442 packet_disconnect("Your ssh version is too old and "
7368a6c8 443 "is no longer supported. Please install a newer version.");
444 } else if (remote_minor == 3) {
445 /* note that this disables agent-forwarding */
446 enable_compat13();
447 }
a8be9f80 448 break;
e78a59f5 449 case 2:
a8be9f80 450 if (options.protocol & SSH_PROTO_2) {
e78a59f5 451 enable_compat20();
452 break;
453 }
454 /* FALLTHROUGH */
6ae2364d 455 default:
a8be9f80 456 mismatch = 1;
457 break;
458 }
459 chop(server_version_string);
a8be9f80 460 debug("Local version string %.200s", server_version_string);
461
462 if (mismatch) {
7368a6c8 463 s = "Protocol major versions differ.\n";
464 (void) atomicio(write, sock_out, s, strlen(s));
465 close(sock_in);
466 close(sock_out);
a8be9f80 467 log("Protocol major versions differ for %s: %.200s vs. %.200s",
468 get_remote_ipaddr(),
469 server_version_string, client_version_string);
7368a6c8 470 fatal_cleanup();
7368a6c8 471 }
a306f2dd 472}
473
474
fa08c86b 475/* Destroy the host and server keys. They will no longer be needed. */
a306f2dd 476void
477destroy_sensitive_data(void)
478{
fa08c86b 479 int i;
480
481 if (sensitive_data.server_key) {
482 key_free(sensitive_data.server_key);
483 sensitive_data.server_key = NULL;
484 }
184eed6a 485 for (i = 0; i < options.num_host_key_files; i++) {
fa08c86b 486 if (sensitive_data.host_keys[i]) {
487 key_free(sensitive_data.host_keys[i]);
488 sensitive_data.host_keys[i] = NULL;
489 }
490 }
491 sensitive_data.ssh1_host_key = NULL;
00be5382 492 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
fa08c86b 493}
fa08c86b 494
1853d1ef 495/* Demote private to public keys for network child */
496void
497demote_sensitive_data(void)
498{
499 Key *tmp;
500 int i;
501
502 if (sensitive_data.server_key) {
503 tmp = key_demote(sensitive_data.server_key);
504 key_free(sensitive_data.server_key);
505 sensitive_data.server_key = tmp;
506 }
507
508 for (i = 0; i < options.num_host_key_files; i++) {
509 if (sensitive_data.host_keys[i]) {
510 tmp = key_demote(sensitive_data.host_keys[i]);
511 key_free(sensitive_data.host_keys[i]);
512 sensitive_data.host_keys[i] = tmp;
513 if (tmp->type == KEY_RSA1)
514 sensitive_data.ssh1_host_key = tmp;
515 }
516 }
517
518 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
519}
520
51aeb639 521static void
1853d1ef 522privsep_preauth_child(void)
523{
524 u_int32_t rand[256];
525 int i;
2ea6de2b 526 struct passwd *pw;
1853d1ef 527
528 /* Enable challenge-response authentication for privilege separation */
529 privsep_challenge_enable();
530
531 for (i = 0; i < 256; i++)
532 rand[i] = arc4random();
533 RAND_seed(rand, sizeof(rand));
534
535 /* Demote the private keys to public keys. */
536 demote_sensitive_data();
537
2ea6de2b 538 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
539 fatal("%s: no user", SSH_PRIVSEP_USER);
540 memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
541 endpwent();
542
1853d1ef 543 /* Change our root directory*/
1c352e97 544 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
545 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
546 strerror(errno));
1853d1ef 547 if (chdir("/") == -1)
edfb66cb 548 fatal("chdir(\"/\"): %s", strerror(errno));
762715ce 549
1853d1ef 550 /* Drop our privileges */
2ea6de2b 551 debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
552 (u_int)pw->pw_gid);
553 do_setusercontext(pw);
1853d1ef 554}
555
324bf712 556static Authctxt*
557privsep_preauth(void)
1853d1ef 558{
324bf712 559 Authctxt *authctxt = NULL;
1853d1ef 560 int status;
324bf712 561 pid_t pid;
1853d1ef 562
324bf712 563 /* Set up unprivileged child process to deal with network data */
564 monitor = monitor_init();
565 /* Store a pointer to the kex for later rekeying */
566 monitor->m_pkex = &xxx_kex;
567
568 pid = fork();
569 if (pid == -1) {
570 fatal("fork of unprivileged child failed");
571 } else if (pid != 0) {
572 debug2("Network child is on pid %d", pid);
573
574 close(monitor->m_recvfd);
575 authctxt = monitor_child_preauth(monitor);
576 close(monitor->m_sendfd);
577
578 /* Sync memory */
579 monitor_sync(monitor);
580
581 /* Wait for the child's exit status */
8c38e88b 582 while (waitpid(pid, &status, 0) < 0)
583 if (errno != EINTR)
584 break;
324bf712 585 return (authctxt);
586 } else {
587 /* child */
588
589 close(monitor->m_sendfd);
590
591 /* Demote the child */
592 if (getuid() == 0 || geteuid() == 0)
593 privsep_preauth_child();
47c36e5b 594 setproctitle("%s", "[net]");
324bf712 595 }
596 return (NULL);
597}
598
599static void
600privsep_postauth(Authctxt *authctxt)
601{
602 extern Authctxt *x_authctxt;
1853d1ef 603
604 /* XXX - Remote port forwarding */
605 x_authctxt = authctxt;
606
607 if (authctxt->pw->pw_uid == 0 || options.use_login) {
608 /* File descriptor passing is broken or root login */
609 monitor_apply_keystate(monitor);
610 use_privsep = 0;
611 return;
612 }
762715ce 613
1853d1ef 614 /* Authentication complete */
615 alarm(0);
616 if (startup_pipe != -1) {
617 close(startup_pipe);
618 startup_pipe = -1;
619 }
620
621 /* New socket pair */
622 monitor_reinit(monitor);
623
624 monitor->m_pid = fork();
625 if (monitor->m_pid == -1)
626 fatal("fork of unprivileged child failed");
627 else if (monitor->m_pid != 0) {
324bf712 628 debug2("User child is on pid %d", monitor->m_pid);
1853d1ef 629 close(monitor->m_recvfd);
630 monitor_child_postauth(monitor);
631
632 /* NEVERREACHED */
633 exit(0);
634 }
635
636 close(monitor->m_sendfd);
637
638 /* Demote the private keys to public keys. */
639 demote_sensitive_data();
640
641 /* Drop privileges */
642 do_setusercontext(authctxt->pw);
643
644 /* It is safe now to apply the key state */
645 monitor_apply_keystate(monitor);
646}
647
396c147e 648static char *
fa08c86b 649list_hostkey_types(void)
650{
3469eac4 651 Buffer b;
652 char *p;
fa08c86b 653 int i;
3469eac4 654
655 buffer_init(&b);
184eed6a 656 for (i = 0; i < options.num_host_key_files; i++) {
fa08c86b 657 Key *key = sensitive_data.host_keys[i];
658 if (key == NULL)
659 continue;
6aacefa7 660 switch (key->type) {
fa08c86b 661 case KEY_RSA:
662 case KEY_DSA:
3469eac4 663 if (buffer_len(&b) > 0)
664 buffer_append(&b, ",", 1);
665 p = key_ssh_name(key);
666 buffer_append(&b, p, strlen(p));
fa08c86b 667 break;
668 }
669 }
3469eac4 670 buffer_append(&b, "\0", 1);
671 p = xstrdup(buffer_ptr(&b));
672 buffer_free(&b);
673 debug("list_hostkey_types: %s", p);
674 return p;
fa08c86b 675}
676
1853d1ef 677Key *
fa08c86b 678get_hostkey_by_type(int type)
679{
680 int i;
184eed6a 681 for (i = 0; i < options.num_host_key_files; i++) {
fa08c86b 682 Key *key = sensitive_data.host_keys[i];
683 if (key != NULL && key->type == type)
684 return key;
685 }
686 return NULL;
7368a6c8 687}
688
1853d1ef 689Key *
690get_hostkey_by_index(int ind)
691{
692 if (ind < 0 || ind >= options.num_host_key_files)
693 return (NULL);
694 return (sensitive_data.host_keys[ind]);
695}
696
697int
698get_hostkey_index(Key *key)
699{
700 int i;
701 for (i = 0; i < options.num_host_key_files; i++) {
702 if (key == sensitive_data.host_keys[i])
703 return (i);
704 }
705 return (-1);
706}
707
c345cf9d 708/*
709 * returns 1 if connection should be dropped, 0 otherwise.
710 * dropping starts at connection #max_startups_begin with a probability
711 * of (max_startups_rate/100). the probability increases linearly until
712 * all connections are dropped for startups > max_startups
713 */
396c147e 714static int
c345cf9d 715drop_connection(int startups)
716{
717 double p, r;
718
719 if (startups < options.max_startups_begin)
720 return 0;
721 if (startups >= options.max_startups)
722 return 1;
723 if (options.max_startups_rate == 100)
724 return 1;
725
726 p = 100 - options.max_startups_rate;
727 p *= startups - options.max_startups_begin;
728 p /= (double) (options.max_startups - options.max_startups_begin);
729 p += options.max_startups_rate;
730 p /= 100.0;
731 r = arc4random() / (double) UINT_MAX;
732
733 debug("drop_connection: p %g, r %g", p, r);
734 return (r < p) ? 1 : 0;
735}
736
2717fa0f 737static void
738usage(void)
739{
740 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
741 fprintf(stderr, "Usage: %s [options]\n", __progname);
742 fprintf(stderr, "Options:\n");
743 fprintf(stderr, " -f file Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
744 fprintf(stderr, " -d Debugging mode (multiple -d means more debugging)\n");
745 fprintf(stderr, " -i Started from inetd\n");
746 fprintf(stderr, " -D Do not fork into daemon mode\n");
747 fprintf(stderr, " -t Only test configuration file and keys\n");
748 fprintf(stderr, " -q Quiet (no logging)\n");
749 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
750 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
751 fprintf(stderr, " -g seconds Grace period for authentication (default: 600)\n");
752 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
753 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
754 _PATH_HOST_KEY_FILE);
755 fprintf(stderr, " -u len Maximum hostname length for utmp recording\n");
756 fprintf(stderr, " -4 Use IPv4 only\n");
757 fprintf(stderr, " -6 Use IPv6 only\n");
758 fprintf(stderr, " -o option Process the option as if it was read from a configuration file.\n");
759 exit(1);
760}
761
5260325f 762/*
763 * Main program for the daemon.
764 */
8efc0c15 765int
766main(int ac, char **av)
767{
5260325f 768 extern char *optarg;
769 extern int optind;
089fbbd2 770 int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
9da5c3c9 771 pid_t pid;
48e671d5 772 socklen_t fromlen;
48e671d5 773 fd_set *fdset;
774 struct sockaddr_storage from;
5260325f 775 const char *remote_ip;
776 int remote_port;
5260325f 777 FILE *f;
778 struct linger linger;
48e671d5 779 struct addrinfo *ai;
780 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
781 int listen_sock, maxfd;
089fbbd2 782 int startup_p[2];
783 int startups = 0;
1b34c1b3 784 Authctxt *authctxt;
aeaa3d9e 785 Key *key;
59c97189 786 int ret, key_used = 0;
5260325f 787
260d427b 788 __progname = get_progname(av[0]);
264dce47 789 init_rng();
790
1fe6a48f 791 /* Save argv. */
4d33e531 792 saved_argc = ac;
5260325f 793 saved_argv = av;
5260325f 794
795 /* Initialize configuration options to their default values. */
796 initialize_server_options(&options);
797
798 /* Parse command-line arguments. */
2717fa0f 799 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
5260325f 800 switch (opt) {
48e671d5 801 case '4':
802 IPv4or6 = AF_INET;
803 break;
804 case '6':
805 IPv4or6 = AF_INET6;
806 break;
5260325f 807 case 'f':
808 config_file_name = optarg;
809 break;
810 case 'd':
bcbf86ec 811 if (0 == debug_flag) {
812 debug_flag = 1;
813 options.log_level = SYSLOG_LEVEL_DEBUG1;
814 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
815 options.log_level++;
816 } else {
817 fprintf(stderr, "Too high debugging level.\n");
818 exit(1);
819 }
5260325f 820 break;
0b6fbf03 821 case 'D':
822 no_daemon_flag = 1;
823 break;
ff14faf1 824 case 'e':
825 log_stderr = 1;
826 break;
5260325f 827 case 'i':
828 inetd_flag = 1;
829 break;
830 case 'Q':
9bd5b720 831 /* ignored */
5260325f 832 break;
833 case 'q':
834 options.log_level = SYSLOG_LEVEL_QUIET;
835 break;
836 case 'b':
837 options.server_key_bits = atoi(optarg);
838 break;
839 case 'p':
48e671d5 840 options.ports_from_cmdline = 1;
bcbf86ec 841 if (options.num_ports >= MAX_PORTS) {
842 fprintf(stderr, "too many ports.\n");
843 exit(1);
844 }
2d2a2c65 845 options.ports[options.num_ports++] = a2port(optarg);
846 if (options.ports[options.num_ports-1] == 0) {
847 fprintf(stderr, "Bad port number.\n");
848 exit(1);
849 }
5260325f 850 break;
851 case 'g':
e2b1fb42 852 if ((options.login_grace_time = convtime(optarg)) == -1) {
853 fprintf(stderr, "Invalid login grace time.\n");
854 exit(1);
855 }
5260325f 856 break;
857 case 'k':
e2b1fb42 858 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
859 fprintf(stderr, "Invalid key regeneration interval.\n");
860 exit(1);
861 }
5260325f 862 break;
863 case 'h':
fa08c86b 864 if (options.num_host_key_files >= MAX_HOSTKEYS) {
865 fprintf(stderr, "too many host keys.\n");
866 exit(1);
867 }
868 options.host_key_files[options.num_host_key_files++] = optarg;
5260325f 869 break;
870 case 'V':
871 client_version_string = optarg;
872 /* only makes sense with inetd_flag, i.e. no listen() */
873 inetd_flag = 1;
874 break;
f87f09aa 875 case 't':
876 test_flag = 1;
877 break;
c345cf9d 878 case 'u':
879 utmp_len = atoi(optarg);
880 break;
2717fa0f 881 case 'o':
184eed6a 882 if (process_server_config_line(&options, optarg,
2717fa0f 883 "command-line", 0) != 0)
184eed6a 884 exit(1);
2717fa0f 885 break;
5260325f 886 case '?':
887 default:
2717fa0f 888 usage();
889 break;
5260325f 890 }
891 }
1a92bd7e 892 SSLeay_add_all_algorithms();
5e4a7219 893 channel_set_af(IPv4or6);
5260325f 894
48e671d5 895 /*
896 * Force logging to stderr until we have loaded the private host
897 * key (unless started from inetd)
898 */
1fe6a48f 899 log_init(__progname,
980c9344 900 options.log_level == SYSLOG_LEVEL_NOT_SET ?
901 SYSLOG_LEVEL_INFO : options.log_level,
902 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
903 SYSLOG_FACILITY_AUTH : options.log_facility,
9bd5b720 904 !inetd_flag);
48e671d5 905
1a23ac2c 906#ifdef _CRAY
907 /* Cray can define user privs drop all prives now!
908 * Not needed on PRIV_SU systems!
909 */
910 drop_cray_privs();
911#endif
912
e339aa53 913 seed_rng();
914
5260325f 915 /* Read server configuration options from the configuration file. */
916 read_server_config(&options, config_file_name);
917
918 /* Fill in default values for those options not explicitly set. */
919 fill_default_server_options(&options);
920
5260325f 921 /* Check that there are no remaining arguments. */
922 if (optind < ac) {
923 fprintf(stderr, "Extra argument %s.\n", av[optind]);
924 exit(1);
8efc0c15 925 }
5260325f 926
927 debug("sshd version %.100s", SSH_VERSION);
928
fa08c86b 929 /* load private host keys */
930 sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*));
184eed6a 931 for (i = 0; i < options.num_host_key_files; i++)
1e3b8b07 932 sensitive_data.host_keys[i] = NULL;
fa08c86b 933 sensitive_data.server_key = NULL;
934 sensitive_data.ssh1_host_key = NULL;
935 sensitive_data.have_ssh1_key = 0;
936 sensitive_data.have_ssh2_key = 0;
a306f2dd 937
184eed6a 938 for (i = 0; i < options.num_host_key_files; i++) {
aeaa3d9e 939 key = key_load_private(options.host_key_files[i], "", NULL);
940 sensitive_data.host_keys[i] = key;
fa08c86b 941 if (key == NULL) {
58cfa257 942 error("Could not load host key: %s",
943 options.host_key_files[i]);
aeaa3d9e 944 sensitive_data.host_keys[i] = NULL;
fa08c86b 945 continue;
a306f2dd 946 }
6aacefa7 947 switch (key->type) {
fa08c86b 948 case KEY_RSA1:
949 sensitive_data.ssh1_host_key = key;
950 sensitive_data.have_ssh1_key = 1;
951 break;
952 case KEY_RSA:
953 case KEY_DSA:
954 sensitive_data.have_ssh2_key = 1;
955 break;
a306f2dd 956 }
aeaa3d9e 957 debug("private host key: #%d type %d %s", i, key->type,
958 key_type(key));
fa08c86b 959 }
960 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
961 log("Disabling protocol version 1. Could not load host key");
962 options.protocol &= ~SSH_PROTO_1;
963 }
964 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
965 log("Disabling protocol version 2. Could not load host key");
966 options.protocol &= ~SSH_PROTO_2;
a306f2dd 967 }
6a416424 968 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
54b974dc 969 log("sshd: no hostkeys available -- exiting.");
5260325f 970 exit(1);
971 }
5260325f 972
a306f2dd 973 /* Check certain values for sanity. */
974 if (options.protocol & SSH_PROTO_1) {
975 if (options.server_key_bits < 512 ||
976 options.server_key_bits > 32768) {
977 fprintf(stderr, "Bad server key size.\n");
978 exit(1);
979 }
980 /*
981 * Check that server and host key lengths differ sufficiently. This
982 * is necessary to make double encryption work with rsaref. Oh, I
983 * hate software patents. I dont know if this can go? Niels
984 */
985 if (options.server_key_bits >
fa08c86b 986 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - SSH_KEY_BITS_RESERVED &&
a306f2dd 987 options.server_key_bits <
fa08c86b 988 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
a306f2dd 989 options.server_key_bits =
fa08c86b 990 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED;
a306f2dd 991 debug("Forcing server key to %d bits to make it differ from host key.",
992 options.server_key_bits);
993 }
994 }
995
f87f09aa 996 /* Configuration looks good, so exit if in test mode. */
997 if (test_flag)
998 exit(0);
999
77bb0bca 1000#ifdef HAVE_SCO_PROTECTED_PW
1001 (void) set_auth_parameters(ac, av);
1002#endif
1003
a306f2dd 1004 /* Initialize the log (it is reinitialized below in case we forked). */
5260325f 1005 if (debug_flag && !inetd_flag)
1006 log_stderr = 1;
1fe6a48f 1007 log_init(__progname, options.log_level, options.log_facility, log_stderr);
5260325f 1008
a306f2dd 1009 /*
1010 * If not in debugging mode, and not started from inetd, disconnect
1011 * from the controlling terminal, and fork. The original process
1012 * exits.
1013 */
0b6fbf03 1014 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
8efc0c15 1015#ifdef TIOCNOTTY
5260325f 1016 int fd;
8efc0c15 1017#endif /* TIOCNOTTY */
5260325f 1018 if (daemon(0, 0) < 0)
1019 fatal("daemon() failed: %.200s", strerror(errno));
1020
1021 /* Disconnect from the controlling tty. */
8efc0c15 1022#ifdef TIOCNOTTY
5ca51e19 1023 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
5260325f 1024 if (fd >= 0) {
1025 (void) ioctl(fd, TIOCNOTTY, NULL);
1026 close(fd);
1027 }
8efc0c15 1028#endif /* TIOCNOTTY */
8efc0c15 1029 }
5260325f 1030 /* Reinitialize the log (because of the fork above). */
1fe6a48f 1031 log_init(__progname, options.log_level, options.log_facility, log_stderr);
5260325f 1032
5260325f 1033 /* Initialize the random number generator. */
1034 arc4random_stir();
1035
1036 /* Chdir to the root directory so that the current disk can be
1037 unmounted if desired. */
1038 chdir("/");
184eed6a 1039
1d3c30db 1040 /* ignore SIGPIPE */
1041 signal(SIGPIPE, SIG_IGN);
5260325f 1042
5260325f 1043 /* Start listening for a socket, unless started from inetd. */
1044 if (inetd_flag) {
ec1f12d3 1045 int s1;
5260325f 1046 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
ec1f12d3 1047 dup(s1);
5260325f 1048 sock_in = dup(0);
1049 sock_out = dup(1);
4c8722d9 1050 startup_pipe = -1;
a306f2dd 1051 /*
1052 * We intentionally do not close the descriptors 0, 1, and 2
1053 * as our code for setting the descriptors won\'t work if
1054 * ttyfd happens to be one of those.
1055 */
5260325f 1056 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
fa08c86b 1057 if (options.protocol & SSH_PROTO_1)
cb7bd922 1058 generate_ephemeral_server_key();
5260325f 1059 } else {
48e671d5 1060 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1061 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1062 continue;
1063 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1064 fatal("Too many listen sockets. "
1065 "Enlarge MAX_LISTEN_SOCKS");
1066 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
1067 ntop, sizeof(ntop), strport, sizeof(strport),
1068 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1069 error("getnameinfo failed");
1070 continue;
1071 }
1072 /* Create socket for listening. */
1073 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
1074 if (listen_sock < 0) {
1075 /* kernel may not support ipv6 */
1076 verbose("socket: %.100s", strerror(errno));
1077 continue;
1078 }
1079 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
1080 error("listen_sock O_NONBLOCK: %s", strerror(errno));
1081 close(listen_sock);
1082 continue;
1083 }
1084 /*
1085 * Set socket options. We try to make the port
1086 * reusable and have it close as fast as possible
1087 * without waiting in unnecessary wait states on
1088 * close.
1089 */
1090 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
db518d9b 1091 &on, sizeof(on));
48e671d5 1092 linger.l_onoff = 1;
1093 linger.l_linger = 5;
1094 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
db518d9b 1095 &linger, sizeof(linger));
48e671d5 1096
1097 debug("Bind to port %s on %s.", strport, ntop);
1098
1099 /* Bind the socket to the desired port. */
32ced054 1100 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1101 if (!ai->ai_next)
1102 error("Bind to port %s on %s failed: %.200s.",
1103 strport, ntop, strerror(errno));
48e671d5 1104 close(listen_sock);
1105 continue;
1106 }
1107 listen_socks[num_listen_socks] = listen_sock;
1108 num_listen_socks++;
1109
1110 /* Start listening on the port. */
1111 log("Server listening on %s port %s.", ntop, strport);
1112 if (listen(listen_sock, 5) < 0)
1113 fatal("listen: %.100s", strerror(errno));
1114
5260325f 1115 }
48e671d5 1116 freeaddrinfo(options.listen_addrs);
1117
1118 if (!num_listen_socks)
1119 fatal("Cannot bind any address.");
1120
3aca00a3 1121 if (options.protocol & SSH_PROTO_1)
1122 generate_ephemeral_server_key();
1123
1124 /*
1125 * Arrange to restart on SIGHUP. The handler needs
1126 * listen_sock.
1127 */
1128 signal(SIGHUP, sighup_handler);
1129
1130 signal(SIGTERM, sigterm_handler);
1131 signal(SIGQUIT, sigterm_handler);
1132
1133 /* Arrange SIGCHLD to be caught. */
1134 signal(SIGCHLD, main_sigchld_handler);
1135
1136 /* Write out the pid file after the sigterm handler is setup */
5260325f 1137 if (!debug_flag) {
aa3378df 1138 /*
97fb6912 1139 * Record our pid in /var/run/sshd.pid to make it
1140 * easier to kill the correct sshd. We don't want to
1141 * do this before the bind above because the bind will
aa3378df 1142 * fail if there already is a daemon, and this will
1143 * overwrite any old pid in the file.
1144 */
3c62e7eb 1145 f = fopen(options.pid_file, "wb");
5260325f 1146 if (f) {
1e3b8b07 1147 fprintf(f, "%u\n", (u_int) getpid());
5260325f 1148 fclose(f);
1149 }
8efc0c15 1150 }
5260325f 1151
48e671d5 1152 /* setup fd set for listen */
089fbbd2 1153 fdset = NULL;
48e671d5 1154 maxfd = 0;
1155 for (i = 0; i < num_listen_socks; i++)
1156 if (listen_socks[i] > maxfd)
1157 maxfd = listen_socks[i];
089fbbd2 1158 /* pipes connected to unauthenticated childs */
1159 startup_pipes = xmalloc(options.max_startups * sizeof(int));
1160 for (i = 0; i < options.max_startups; i++)
1161 startup_pipes[i] = -1;
48e671d5 1162
aa3378df 1163 /*
1164 * Stay listening for connections until the system crashes or
1165 * the daemon is killed with a signal.
1166 */
5260325f 1167 for (;;) {
1168 if (received_sighup)
1169 sighup_restart();
089fbbd2 1170 if (fdset != NULL)
1171 xfree(fdset);
b5c334cc 1172 fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
089fbbd2 1173 fdset = (fd_set *)xmalloc(fdsetsz);
48e671d5 1174 memset(fdset, 0, fdsetsz);
089fbbd2 1175
48e671d5 1176 for (i = 0; i < num_listen_socks; i++)
1177 FD_SET(listen_socks[i], fdset);
089fbbd2 1178 for (i = 0; i < options.max_startups; i++)
1179 if (startup_pipes[i] != -1)
1180 FD_SET(startup_pipes[i], fdset);
1181
1182 /* Wait in select until there is a connection. */
59c97189 1183 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1184 if (ret < 0 && errno != EINTR)
1185 error("select: %.100s", strerror(errno));
c9130033 1186 if (received_sigterm) {
1187 log("Received signal %d; terminating.",
010f9726 1188 (int) received_sigterm);
c9130033 1189 close_listen_socks();
1190 unlink(options.pid_file);
1191 exit(255);
1192 }
59c97189 1193 if (key_used && key_do_regen) {
cb7bd922 1194 generate_ephemeral_server_key();
59c97189 1195 key_used = 0;
1196 key_do_regen = 0;
48e671d5 1197 }
59c97189 1198 if (ret < 0)
1199 continue;
1200
089fbbd2 1201 for (i = 0; i < options.max_startups; i++)
1202 if (startup_pipes[i] != -1 &&
1203 FD_ISSET(startup_pipes[i], fdset)) {
1204 /*
1205 * the read end of the pipe is ready
1206 * if the child has closed the pipe
8abcdba4 1207 * after successful authentication
089fbbd2 1208 * or if the child has died
1209 */
1210 close(startup_pipes[i]);
1211 startup_pipes[i] = -1;
1212 startups--;
1213 }
48e671d5 1214 for (i = 0; i < num_listen_socks; i++) {
1215 if (!FD_ISSET(listen_socks[i], fdset))
5260325f 1216 continue;
089fbbd2 1217 fromlen = sizeof(from);
1218 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
1219 &fromlen);
1220 if (newsock < 0) {
1221 if (errno != EINTR && errno != EWOULDBLOCK)
1222 error("accept: %.100s", strerror(errno));
1223 continue;
1224 }
1225 if (fcntl(newsock, F_SETFL, 0) < 0) {
1226 error("newsock del O_NONBLOCK: %s", strerror(errno));
5e8948af 1227 close(newsock);
089fbbd2 1228 continue;
1229 }
c345cf9d 1230 if (drop_connection(startups) == 1) {
1231 debug("drop connection #%d", startups);
089fbbd2 1232 close(newsock);
1233 continue;
1234 }
1235 if (pipe(startup_p) == -1) {
1236 close(newsock);
1237 continue;
1238 }
1239
1240 for (j = 0; j < options.max_startups; j++)
1241 if (startup_pipes[j] == -1) {
1242 startup_pipes[j] = startup_p[0];
1243 if (maxfd < startup_p[0])
1244 maxfd = startup_p[0];
1245 startups++;
1246 break;
1247 }
2b87da3b 1248
aa3378df 1249 /*
089fbbd2 1250 * Got connection. Fork a child to handle it, unless
1251 * we are in debugging mode.
aa3378df 1252 */
089fbbd2 1253 if (debug_flag) {
aa3378df 1254 /*
089fbbd2 1255 * In debugging mode. Close the listening
1256 * socket, and start processing the
1257 * connection without forking.
aa3378df 1258 */
089fbbd2 1259 debug("Server will not fork when running in debugging mode.");
48e671d5 1260 close_listen_socks();
5260325f 1261 sock_in = newsock;
1262 sock_out = newsock;
5540ea9b 1263 startup_pipe = -1;
3f7a7e4a 1264 pid = getpid();
5260325f 1265 break;
089fbbd2 1266 } else {
1267 /*
1268 * Normal production daemon. Fork, and have
1269 * the child process the connection. The
1270 * parent continues listening.
1271 */
1272 if ((pid = fork()) == 0) {
1273 /*
1274 * Child. Close the listening and max_startup
1275 * sockets. Start using the accepted socket.
1276 * Reinitialize logging (since our pid has
1277 * changed). We break out of the loop to handle
1278 * the connection.
1279 */
1280 startup_pipe = startup_p[1];
7ace8c3b 1281 close_startup_pipes();
089fbbd2 1282 close_listen_socks();
1283 sock_in = newsock;
1284 sock_out = newsock;
1fe6a48f 1285 log_init(__progname, options.log_level, options.log_facility, log_stderr);
089fbbd2 1286 break;
1287 }
5260325f 1288 }
5260325f 1289
089fbbd2 1290 /* Parent. Stay in the loop. */
1291 if (pid < 0)
1292 error("fork: %.100s", strerror(errno));
1293 else
1294 debug("Forked child %d.", pid);
5260325f 1295
089fbbd2 1296 close(startup_p[1]);
5260325f 1297
089fbbd2 1298 /* Mark that the key has been used (it was "given" to the child). */
59c97189 1299 if ((options.protocol & SSH_PROTO_1) &&
1300 key_used == 0) {
1301 /* Schedule server key regeneration alarm. */
1302 signal(SIGALRM, key_regeneration_alarm);
1303 alarm(options.key_regeneration_time);
1304 key_used = 1;
1305 }
5260325f 1306
089fbbd2 1307 arc4random_stir();
1308
1309 /* Close the new socket (the child is now taking care of it). */
1310 close(newsock);
1311 }
48e671d5 1312 /* child process check (or debug mode) */
1313 if (num_listen_socks < 0)
1314 break;
5260325f 1315 }
1316 }
8efc0c15 1317
5260325f 1318 /* This is the child processing a new connection. */
1319
aa3378df 1320 /*
1321 * Disable the key regeneration alarm. We will not regenerate the
1322 * key since we are no longer in a position to give it to anyone. We
1323 * will not restart on SIGHUP since it no longer makes sense.
1324 */
5260325f 1325 alarm(0);
1326 signal(SIGALRM, SIG_DFL);
1327 signal(SIGHUP, SIG_DFL);
1328 signal(SIGTERM, SIG_DFL);
1329 signal(SIGQUIT, SIG_DFL);
1330 signal(SIGCHLD, SIG_DFL);
9aaf9be4 1331 signal(SIGINT, SIG_DFL);
5260325f 1332
aa3378df 1333 /*
1334 * Set socket options for the connection. We want the socket to
1335 * close as fast as possible without waiting for anything. If the
1336 * connection is not a socket, these will do nothing.
1337 */
1338 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
5260325f 1339 linger.l_onoff = 1;
1340 linger.l_linger = 5;
db518d9b 1341 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
5260325f 1342
b5c334cc 1343 /* Set keepalives if requested. */
1344 if (options.keepalives &&
db518d9b 1345 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
b5c334cc 1346 sizeof(on)) < 0)
1347 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1348
aa3378df 1349 /*
1350 * Register our connection. This turns encryption off because we do
1351 * not have a key.
1352 */
5260325f 1353 packet_set_connection(sock_in, sock_out);
1354
1355 remote_port = get_remote_port();
1356 remote_ip = get_remote_ipaddr();
1357
5260325f 1358#ifdef LIBWRAP
ac28afd8 1359 /* Check whether logins are denied from this host. */
5260325f 1360 {
1361 struct request_info req;
8efc0c15 1362
8fbc356d 1363 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
5260325f 1364 fromhost(&req);
8efc0c15 1365
5260325f 1366 if (!hosts_access(&req)) {
ac28afd8 1367 debug("Connection refused by tcp wrapper");
563834bb 1368 refuse(&req);
ac28afd8 1369 /* NOTREACHED */
1370 fatal("libwrap refuse returns");
5260325f 1371 }
8efc0c15 1372 }
48e671d5 1373#endif /* LIBWRAP */
ac28afd8 1374
5260325f 1375 /* Log the connection. */
1376 verbose("Connection from %.500s port %d", remote_ip, remote_port);
8efc0c15 1377
aa3378df 1378 /*
1379 * We don\'t want to listen forever unless the other side
1380 * successfully authenticates itself. So we set up an alarm which is
1381 * cleared after successful authentication. A limit of zero
1382 * indicates no limit. Note that we don\'t set the alarm in debugging
1383 * mode; it is just annoying to have the server exit just when you
1384 * are about to discover the bug.
1385 */
5260325f 1386 signal(SIGALRM, grace_alarm_handler);
1387 if (!debug_flag)
1388 alarm(options.login_grace_time);
1389
7368a6c8 1390 sshd_exchange_identification(sock_in, sock_out);
aa3378df 1391 /*
6ffc9c88 1392 * Check that the connection comes from a privileged port.
1393 * Rhosts-Authentication only makes sense from priviledged
aa3378df 1394 * programs. Of course, if the intruder has root access on his local
1395 * machine, he can connect from any port. So do not use these
1396 * authentication methods from machines that you do not trust.
1397 */
44b1a8e5 1398 if (options.rhosts_authentication &&
1399 (remote_port >= IPPORT_RESERVED ||
1400 remote_port < IPPORT_RESERVED / 2)) {
6ffc9c88 1401 debug("Rhosts Authentication disabled, "
9ae3f727 1402 "originating port %d not trusted.", remote_port);
5260325f 1403 options.rhosts_authentication = 0;
5260325f 1404 }
ced49be2 1405#if defined(KRB4) && !defined(KRB5)
48e671d5 1406 if (!packet_connection_is_ipv4() &&
1407 options.kerberos_authentication) {
1408 debug("Kerberos Authentication disabled, only available for IPv4.");
1409 options.kerberos_authentication = 0;
1410 }
ced49be2 1411#endif /* KRB4 && !KRB5 */
abf1f107 1412#ifdef AFS
1413 /* If machine has AFS, set process authentication group. */
1414 if (k_hasafs()) {
1415 k_setpag();
1416 k_unlog();
1417 }
1418#endif /* AFS */
48e671d5 1419
5260325f 1420 packet_set_nonblocking();
1421
324bf712 1422 if (use_privsep)
1423 if ((authctxt = privsep_preauth()) != NULL)
1424 goto authenticated;
1853d1ef 1425
7b2ea3a1 1426 /* perform the key exchange */
7b2ea3a1 1427 /* authenticate user and start session */
e78a59f5 1428 if (compat20) {
1429 do_ssh2_kex();
1b34c1b3 1430 authctxt = do_authentication2();
e78a59f5 1431 } else {
1432 do_ssh1_kex();
1b34c1b3 1433 authctxt = do_authentication();
e78a59f5 1434 }
324bf712 1435 /*
1436 * If we use privilege separation, the unprivileged child transfers
1437 * the current keystate and exits
1438 */
1439 if (use_privsep) {
1853d1ef 1440 mm_send_keystate(monitor);
1853d1ef 1441 exit(0);
324bf712 1442 }
1853d1ef 1443
1444 authenticated:
762715ce 1445 /*
1853d1ef 1446 * In privilege separation, we fork another child and prepare
1447 * file descriptor passing.
1448 */
1449 if (use_privsep) {
324bf712 1450 privsep_postauth(authctxt);
1451 /* the monitor process [priv] will not return */
1853d1ef 1452 if (!compat20)
1453 destroy_sensitive_data();
1454 }
1b34c1b3 1455
1456 /* Perform session preparation. */
1457 do_authenticated(authctxt);
1458
63284fbb 1459 /* The connection has been terminated. */
1460 verbose("Closing connection to %.100s", remote_ip);
8efc0c15 1461
d94aa2ae 1462#ifdef USE_PAM
a5c9cd31 1463 finish_pam();
d94aa2ae 1464#endif /* USE_PAM */
8efc0c15 1465
5260325f 1466 packet_close();
1853d1ef 1467
1468 if (use_privsep)
1469 mm_terminate();
1470
5260325f 1471 exit(0);
1472}
8efc0c15 1473
4f08e98d 1474/*
1475 * Decrypt session_key_int using our private server key and private host key
1476 * (key with larger modulus first).
1477 */
1853d1ef 1478int
4f08e98d 1479ssh1_session_key(BIGNUM *session_key_int)
1480{
1481 int rsafail = 0;
1482
1483 if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1484 /* Server key has bigger modulus. */
1485 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1486 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1487 fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1488 get_remote_ipaddr(),
1489 BN_num_bits(sensitive_data.server_key->rsa->n),
1490 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1491 SSH_KEY_BITS_RESERVED);
1492 }
1493 if (rsa_private_decrypt(session_key_int, session_key_int,
1494 sensitive_data.server_key->rsa) <= 0)
1495 rsafail++;
1496 if (rsa_private_decrypt(session_key_int, session_key_int,
1497 sensitive_data.ssh1_host_key->rsa) <= 0)
1498 rsafail++;
1499 } else {
1500 /* Host key has bigger modulus (or they are equal). */
1501 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1502 BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1503 fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1504 get_remote_ipaddr(),
1505 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1506 BN_num_bits(sensitive_data.server_key->rsa->n),
1507 SSH_KEY_BITS_RESERVED);
1508 }
1509 if (rsa_private_decrypt(session_key_int, session_key_int,
1510 sensitive_data.ssh1_host_key->rsa) < 0)
1511 rsafail++;
1512 if (rsa_private_decrypt(session_key_int, session_key_int,
1513 sensitive_data.server_key->rsa) < 0)
1514 rsafail++;
1515 }
1516 return (rsafail);
1517}
5260325f 1518/*
7b2ea3a1 1519 * SSH1 key exchange
5260325f 1520 */
396c147e 1521static void
1e3b8b07 1522do_ssh1_kex(void)
8efc0c15 1523{
5260325f 1524 int i, len;
46aa2d1f 1525 int rsafail = 0;
5260325f 1526 BIGNUM *session_key_int;
1e3b8b07 1527 u_char session_key[SSH_SESSION_KEY_LENGTH];
1528 u_char cookie[8];
1529 u_int cipher_type, auth_mask, protocol_flags;
5260325f 1530 u_int32_t rand = 0;
1531
aa3378df 1532 /*
1533 * Generate check bytes that the client must send back in the user
1534 * packet in order for it to be accepted; this is used to defy ip
1535 * spoofing attacks. Note that this only works against somebody
1536 * doing IP spoofing from a remote machine; any machine on the local
1537 * network can still see outgoing packets and catch the random
1538 * cookie. This only affects rhosts authentication, and this is one
1539 * of the reasons why it is inherently insecure.
1540 */
5260325f 1541 for (i = 0; i < 8; i++) {
1542 if (i % 4 == 0)
1543 rand = arc4random();
7b2ea3a1 1544 cookie[i] = rand & 0xff;
5260325f 1545 rand >>= 8;
1546 }
1547
aa3378df 1548 /*
1549 * Send our public key. We include in the packet 64 bits of random
1550 * data that must be matched in the reply in order to prevent IP
1551 * spoofing.
1552 */
5260325f 1553 packet_start(SSH_SMSG_PUBLIC_KEY);
1554 for (i = 0; i < 8; i++)
7b2ea3a1 1555 packet_put_char(cookie[i]);
5260325f 1556
1557 /* Store our public server RSA key. */
fa08c86b 1558 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1559 packet_put_bignum(sensitive_data.server_key->rsa->e);
1560 packet_put_bignum(sensitive_data.server_key->rsa->n);
5260325f 1561
1562 /* Store our public host RSA key. */
fa08c86b 1563 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1564 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1565 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
5260325f 1566
1567 /* Put protocol flags. */
1568 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1569
1570 /* Declare which ciphers we support. */
94ec8c6b 1571 packet_put_int(cipher_mask_ssh1(0));
5260325f 1572
1573 /* Declare supported authentication types. */
1574 auth_mask = 0;
1575 if (options.rhosts_authentication)
1576 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1577 if (options.rhosts_rsa_authentication)
1578 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1579 if (options.rsa_authentication)
1580 auth_mask |= 1 << SSH_AUTH_RSA;
ced49be2 1581#if defined(KRB4) || defined(KRB5)
5260325f 1582 if (options.kerberos_authentication)
1583 auth_mask |= 1 << SSH_AUTH_KERBEROS;
8efc0c15 1584#endif
ced49be2 1585#if defined(AFS) || defined(KRB5)
5260325f 1586 if (options.kerberos_tgt_passing)
1587 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
ced49be2 1588#endif
1589#ifdef AFS
5260325f 1590 if (options.afs_token_passing)
1591 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
8efc0c15 1592#endif
5ba55ada 1593 if (options.challenge_response_authentication == 1)
5260325f 1594 auth_mask |= 1 << SSH_AUTH_TIS;
5260325f 1595 if (options.password_authentication)
1596 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1597 packet_put_int(auth_mask);
1598
1599 /* Send the packet and wait for it to be sent. */
1600 packet_send();
1601 packet_write_wait();
1602
fa08c86b 1603 debug("Sent %d bit server key and %d bit host key.",
1604 BN_num_bits(sensitive_data.server_key->rsa->n),
1605 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
5260325f 1606
1607 /* Read clients reply (cipher type and session key). */
54a5250f 1608 packet_read_expect(SSH_CMSG_SESSION_KEY);
5260325f 1609
2d86a6cc 1610 /* Get cipher type and check whether we accept this. */
5260325f 1611 cipher_type = packet_get_char();
1612
94ec8c6b 1613 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2d86a6cc 1614 packet_disconnect("Warning: client selects unsupported cipher.");
1615
5260325f 1616 /* Get check bytes from the packet. These must match those we
1617 sent earlier with the public key packet. */
1618 for (i = 0; i < 8; i++)
7b2ea3a1 1619 if (cookie[i] != packet_get_char())
5260325f 1620 packet_disconnect("IP Spoofing check bytes do not match.");
1621
1622 debug("Encryption type: %.200s", cipher_name(cipher_type));
1623
1624 /* Get the encrypted integer. */
b775c6f2 1625 if ((session_key_int = BN_new()) == NULL)
1626 fatal("do_ssh1_kex: BN_new failed");
20b279e6 1627 packet_get_bignum(session_key_int);
5260325f 1628
5260325f 1629 protocol_flags = packet_get_int();
1630 packet_set_protocol_flags(protocol_flags);
95500969 1631 packet_check_eom();
5260325f 1632
4f08e98d 1633 /* Decrypt session_key_int using host/server keys */
1853d1ef 1634 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
1635
aa3378df 1636 /*
1637 * Extract session key from the decrypted integer. The key is in the
1638 * least significant 256 bits of the integer; the first byte of the
1639 * key is in the highest bits.
1640 */
46aa2d1f 1641 if (!rsafail) {
1642 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1643 len = BN_num_bytes(session_key_int);
1644 if (len < 0 || len > sizeof(session_key)) {
1645 error("do_connection: bad session key len from %s: "
5ca51e19 1646 "session_key_int %d > sizeof(session_key) %lu",
1647 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
46aa2d1f 1648 rsafail++;
1649 } else {
1650 memset(session_key, 0, sizeof(session_key));
1651 BN_bn2bin(session_key_int,
1652 session_key + sizeof(session_key) - len);
00be5382 1653
1654 compute_session_id(session_id, cookie,
1655 sensitive_data.ssh1_host_key->rsa->n,
1656 sensitive_data.server_key->rsa->n);
1657 /*
1658 * Xor the first 16 bytes of the session key with the
1659 * session id.
1660 */
1661 for (i = 0; i < 16; i++)
1662 session_key[i] ^= session_id[i];
46aa2d1f 1663 }
1664 }
1665 if (rsafail) {
00be5382 1666 int bytes = BN_num_bytes(session_key_int);
f6b1ba8f 1667 u_char *buf = xmalloc(bytes);
00be5382 1668 MD5_CTX md;
1669
46aa2d1f 1670 log("do_connection: generating a fake encryption key");
00be5382 1671 BN_bn2bin(session_key_int, buf);
1672 MD5_Init(&md);
1673 MD5_Update(&md, buf, bytes);
1674 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1675 MD5_Final(session_key, &md);
1676 MD5_Init(&md);
1677 MD5_Update(&md, session_key, 16);
1678 MD5_Update(&md, buf, bytes);
1679 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1680 MD5_Final(session_key + 16, &md);
1681 memset(buf, 0, bytes);
1682 xfree(buf);
0572fe75 1683 for (i = 0; i < 16; i++)
1684 session_id[i] = session_key[i] ^ session_key[i + 16];
46aa2d1f 1685 }
1853d1ef 1686 /* Destroy the private and public keys. No longer. */
63284fbb 1687 destroy_sensitive_data();
00be5382 1688
1853d1ef 1689 if (use_privsep)
1690 mm_ssh1_session_id(session_id);
1691
7b2ea3a1 1692 /* Destroy the decrypted integer. It is no longer needed. */
1693 BN_clear_free(session_key_int);
1694
5260325f 1695 /* Set the session key. From this on all communications will be encrypted. */
1696 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1697
1698 /* Destroy our copy of the session key. It is no longer needed. */
1699 memset(session_key, 0, sizeof(session_key));
1700
1701 debug("Received session key; encryption turned on.");
1702
1703 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1704 packet_start(SSH_SMSG_SUCCESS);
1705 packet_send();
1706 packet_write_wait();
5260325f 1707}
e78a59f5 1708
1709/*
1710 * SSH2 key exchange: diffie-hellman-group1-sha1
1711 */
396c147e 1712static void
1e3b8b07 1713do_ssh2_kex(void)
e78a59f5 1714{
e78a59f5 1715 Kex *kex;
e78a59f5 1716
a8be9f80 1717 if (options.ciphers != NULL) {
6ae2364d 1718 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
a8be9f80 1719 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1720 }
1ad64a93 1721 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1722 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1723 myproposal[PROPOSAL_ENC_ALGS_STOC] =
1724 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1725
b2552997 1726 if (options.macs != NULL) {
1727 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1728 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1729 }
fa08c86b 1730 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1731
7a37c112 1732 /* start key exchange */
d8ee838b 1733 kex = kex_setup(myproposal);
a5c9ffdb 1734 kex->server = 1;
1735 kex->client_version_string=client_version_string;
1736 kex->server_version_string=server_version_string;
1737 kex->load_host_key=&get_hostkey_by_type;
1853d1ef 1738 kex->host_key_index=&get_hostkey_index;
94ec8c6b 1739
7a37c112 1740 xxx_kex = kex;
1741
c422989b 1742 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
94ec8c6b 1743
d1ac6175 1744 session_id2 = kex->session_id;
1745 session_id2_len = kex->session_id_len;
1746
94ec8c6b 1747#ifdef DEBUG_KEXDH
1748 /* send 1st encrypted/maced/compressed message */
1749 packet_start(SSH2_MSG_IGNORE);
1750 packet_put_cstring("markus");
1751 packet_send();
1752 packet_write_wait();
1753#endif
a5c9ffdb 1754 debug("KEX done");
e78a59f5 1755}
This page took 1.532569 seconds and 5 git commands to generate.