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