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