]> andersk Git - gssapi-openssh.git/blame - openssh/sshd.c
It turns out that whitespace is very significant in GPT Build_Steps.
[gssapi-openssh.git] / openssh / sshd.c
CommitLineData
6f25cbdd 1/* $OpenBSD: sshd.c,v 1.364 2008/07/10 18:08:11 markus 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:
2980ea68 19 * Privilege Separation:
3c0ef626 20 *
2980ea68 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"
2e437378 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"
6f25cbdd 57#include "openbsd-compat/sys-queue.h"
2e437378 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>
2980ea68 78#include <openssl/rand.h>
bd5d5d2a 79#include "openbsd-compat/openssl-compat.h"
80
2980ea68 81#ifdef HAVE_SECUREWARE
82#include <sys/security.h>
83#include <prot.h>
84#endif
3c0ef626 85
2e437378 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"
2e437378 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"
2e437378 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"
2e437378 107#include "hostfile.h"
3c0ef626 108#include "auth.h"
109#include "misc.h"
1b56ff3d 110#include "msg.h"
3c0ef626 111#include "dispatch.h"
112#include "channels.h"
2980ea68 113#include "session.h"
114#include "monitor_mm.h"
115#include "monitor.h"
2e437378 116#ifdef GSSAPI
117#include "ssh-gss.h"
118#endif
2980ea68 119#include "monitor_wrap.h"
120#include "monitor_fdpass.h"
2e437378 121#include "version.h"
3c0ef626 122
34fee935 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>
bd5d5d2a 130int allow_severity;
131int deny_severity;
3c0ef626 132#endif /* LIBWRAP */
133
134#ifndef O_NOCTTY
135#define O_NOCTTY 0
136#endif
137
1b56ff3d 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
bd5d5d2a 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. */
ae43c103 153char *config_file_name;
3c0ef626 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
1b56ff3d 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;
70791e56 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
2980ea68 244/* variables used for privilege separation */
2e437378 245int use_privsep = -1;
416fd2a8 246struct monitor *pmonitor = NULL;
2980ea68 247
416fd2a8 248/* global authentication context */
249Authctxt *the_authctxt = NULL;
250
2e437378 251/* sshd_config buffer */
252Buffer cfg;
253
1b56ff3d 254/* message to be displayed after login */
255Buffer loginmsg;
256
2e437378 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);
2980ea68 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;
ff2d7a98 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;
ff2d7a98 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 */
2e437378 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{
70791e56 315 logit("Received SIGHUP; restarting.");
3c0ef626 316 close_listen_socks();
1e608e42 317 close_startup_pipes();
2278ffa1 318 alarm(0); /* alarm timer persists across exec */
3c0ef626 319 execv(saved_argv[0], saved_argv);
70791e56 320 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
ff2d7a98 321 strerror(errno));
3c0ef626 322 exit(1);
323}
324
325/*
326 * Generic signal handler for terminating signals in the master daemon.
327 */
2e437378 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 */
2e437378 339/*ARGSUSED*/
3c0ef626 340static void
341main_sigchld_handler(int sig)
342{
343 int save_errno = errno;
ff2d7a98 344 pid_t pid;
3c0ef626 345 int status;
346
2980ea68 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 */
2e437378 358/*ARGSUSED*/
3c0ef626 359static void
360grace_alarm_handler(int sig)
361{
416fd2a8 362 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
363 kill(pmonitor->m_pid, SIGALRM);
364
3c0ef626 365 /* Log error and exit. */
2e437378 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
6f25cbdd 387 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
3c0ef626 388 arc4random_stir();
389}
390
2e437378 391/*ARGSUSED*/
3c0ef626 392static void
393key_regeneration_alarm(int sig)
394{
395 int save_errno = errno;
ff2d7a98 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{
34fee935 405 u_int i;
406 int mismatch;
3c0ef626 407 int remote_major, remote_minor;
408 int major, minor;
6f25cbdd 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;
6f25cbdd 420 newline = "\r\n";
3c0ef626 421 } else {
422 major = PROTOCOL_MAJOR_1;
423 minor = PROTOCOL_MINOR_1;
424 }
6f25cbdd 425 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s%s", major, minor,
426 SSH_RELEASE, newline);
3c0ef626 427 server_version_string = xstrdup(buf);
428
70791e56 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());
416fd2a8 434 cleanup_exit(255);
70791e56 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());
416fd2a8 443 cleanup_exit(255);
3c0ef626 444 }
70791e56 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;
70791e56 451 continue;
452 }
453 if (buf[i] == '\n') {
454 buf[i] = 0;
455 break;
3c0ef626 456 }
3c0ef626 457 }
70791e56 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";
70791e56 468 (void) atomicio(vwrite, sock_out, s, strlen(s));
3c0ef626 469 close(sock_in);
470 close(sock_out);
70791e56 471 logit("Bad protocol version identification '%.100s' from %s",
3c0ef626 472 client_version_string, get_remote_ipaddr());
416fd2a8 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);
bd5d5d2a 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
e54b3d7c 483 if (datafellows & SSH_BUG_PROBE) {
70791e56 484 logit("probed from %s with %s. Don't panic.",
e54b3d7c 485 get_remote_ipaddr(), client_version_string);
416fd2a8 486 cleanup_exit(255);
e54b3d7c 487 }
488
3c0ef626 489 if (datafellows & SSH_BUG_SCANNER) {
70791e56 490 logit("scanned from %s with %s. Don't panic.",
3c0ef626 491 get_remote_ipaddr(), client_version_string);
416fd2a8 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";
70791e56 532 (void) atomicio(vwrite, sock_out, s, strlen(s));
3c0ef626 533 close(sock_in);
534 close(sock_out);
70791e56 535 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
3c0ef626 536 get_remote_ipaddr(),
537 server_version_string, client_version_string);
416fd2a8 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
2980ea68 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{
6f25cbdd 591 u_int32_t rnd[256];
e54b3d7c 592 gid_t gidset[1];
2980ea68 593
594 /* Enable challenge-response authentication for privilege separation */
595 privsep_challenge_enable();
596
bd5d5d2a 597 arc4random_stir();
6f25cbdd 598 arc4random_buf(rnd, sizeof(rnd));
e54b3d7c 599 RAND_seed(rnd, sizeof(rnd));
2980ea68 600
601 /* Demote the private keys to public keys. */
602 demote_sensitive_data();
603
e54b3d7c 604 /* Change our root directory */
2980ea68 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 */
2e437378 612 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
613 (u_int)privsep_pw->pw_gid);
ff2d7a98 614#if 0
2a304a95 615 /* XXX not ready, too heavy after chroot */
2e437378 616 do_setusercontext(privsep_pw);
ff2d7a98 617#else
2e437378 618 gidset[0] = privsep_pw->pw_gid;
ff2d7a98 619 if (setgroups(1, gidset) < 0)
620 fatal("setgroups: %.100s", strerror(errno));
2e437378 621 permanently_set_uid(privsep_pw);
ff2d7a98 622#endif
2980ea68 623}
624
416fd2a8 625static int
626privsep_preauth(Authctxt *authctxt)
2980ea68 627{
2980ea68 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) {
ff2d7a98 640 debug2("Network child is on pid %ld", (long)pid);
2980ea68 641
642 close(pmonitor->m_recvfd);
416fd2a8 643 pmonitor->m_pid = pid;
644 monitor_child_preauth(authctxt, pmonitor);
2980ea68 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;
416fd2a8 654 return (1);
2980ea68 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 }
416fd2a8 665 return (0);
2980ea68 666}
667
668static void
669privsep_postauth(Authctxt *authctxt)
670{
bd5d5d2a 671 u_int32_t rnd[256];
bd5d5d2a 672
e54b3d7c 673#ifdef DISABLE_FD_PASSING
ff2d7a98 674 if (1) {
675#else
2980ea68 676 if (authctxt->pw->pw_uid == 0 || options.use_login) {
ff2d7a98 677#endif
2980ea68 678 /* File descriptor passing is broken or root login */
2980ea68 679 use_privsep = 0;
e00da40d 680 goto skip;
2980ea68 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) {
6f25cbdd 690 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
2980ea68 691 close(pmonitor->m_recvfd);
1b56ff3d 692 buffer_clear(&loginmsg);
2980ea68 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
bd5d5d2a 704 arc4random_stir();
6f25cbdd 705 arc4random_buf(rnd, sizeof(rnd));
bd5d5d2a 706 RAND_seed(rnd, sizeof(rnd));
707
2980ea68 708 /* Drop privileges */
709 do_setusercontext(authctxt->pw);
710
e00da40d 711 skip:
2980ea68 712 /* It is safe now to apply the key state */
713 monitor_apply_keystate(pmonitor);
34fee935 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();
2980ea68 720}
721
3c0ef626 722static char *
723list_hostkey_types(void)
724{
1e608e42 725 Buffer b;
416fd2a8 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);
416fd2a8 746 ret = xstrdup(buffer_ptr(&b));
1e608e42 747 buffer_free(&b);
416fd2a8 748 debug("list_hostkey_types: %s", ret);
749 return ret;
3c0ef626 750}
751
2980ea68 752Key *
3c0ef626 753get_hostkey_by_type(int type)
754{
755 int i;
ff2d7a98 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
2980ea68 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;
ff2d7a98 777
2980ea68 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{
34fee935 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;
34fee935 805 p /= options.max_startups - options.max_startups_begin;
3c0ef626 806 p += options.max_startups_rate;
6f25cbdd 807 r = arc4random_uniform(100);
3c0ef626 808
34fee935 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{
2a304a95 816 fprintf(stderr, "%s, %s\n",
34fee935 817 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
2a304a95 818 fprintf(stderr,
6f25cbdd 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"
2a304a95 822 );
1e608e42 823 exit(1);
824}
3c0ef626 825
1b56ff3d 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 "
e00da40d 844 * string rngseed (only if OpenSSL is not self-seeded)
1b56ff3d 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
e00da40d 861#ifndef OPENSSL_PRNG_ONLY
862 rexec_send_rng_seed(&m);
863#endif
864
1b56ff3d 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 }
e00da40d 907
908#ifndef OPENSSL_PRNG_ONLY
909 rexec_recv_rng_seed(&m);
910#endif
911
1b56ff3d 912 buffer_free(&m);
913
914 debug3("%s: done", __func__);
915}
916
2e437378 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];
958 int socksize;
959 int socksizelen = sizeof(int);
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",
bd5d5d2a 971 ssh_gai_strerror(ret));
2e437378 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
bd5d5d2a 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
2e437378 1004 debug("Bind to port %s on %s.", strport, ntop);
bd5d5d2a 1005
2e437378 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);
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) {
6f25cbdd 1116 if (errno != EINTR && errno != EAGAIN &&
1117 errno != EWOULDBLOCK)
2e437378 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;
2e437378 1261 int opt, i, on = 1;
1b56ff3d 1262 int sock_in = -1, sock_out = -1, newsock = -1;
3c0ef626 1263 const char *remote_ip;
6f25cbdd 1264 char *test_user = NULL, *test_host = NULL, *test_addr = NULL;
3c0ef626 1265 int remote_port;
6f25cbdd 1266 char *line, *p, *cp;
2e437378 1267 int config_s[2] = { -1 , -1 };
6f25cbdd 1268 u_int64_t ibytes, obytes;
1269 mode_t new_umask;
3c0ef626 1270 Key *key;
416fd2a8 1271 Authctxt *authctxt;
3c0ef626 1272
2980ea68 1273#ifdef HAVE_SECUREWARE
1274 (void)set_auth_parameters(ac, av);
1275#endif
70791e56 1276 __progname = ssh_get_progname(av[0]);
ae43c103 1277 init_pathnames();
004706ea 1278 config_file_name = _PATH_SERVER_CONFIG_FILE;
3c0ef626 1279 init_rng();
1280
1c14df9e 1281 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
3c0ef626 1282 saved_argc = ac;
1b56ff3d 1283 rexec_argc = ac;
2e437378 1284 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1c14df9e 1285 for (i = 0; i < ac; i++)
1286 saved_argv[i] = xstrdup(av[i]);
70791e56 1287 saved_argv[i] = NULL;
1c14df9e 1288
1289#ifndef HAVE_SETPROCTITLE
1290 /* Prepare for later setproctitle emulation */
1291 compat_init_setproctitle(ac, av);
70791e56 1292 av = saved_argv;
1c14df9e 1293#endif
3c0ef626 1294
2a304a95 1295 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1296 debug("setgroups(): %.200s", strerror(errno));
1297
e00da40d 1298 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1299 sanitise_stdfd();
1300
3c0ef626 1301 /* Initialize configuration options to their default values. */
1302 initialize_server_options(&options);
1303
1304 /* Parse command-line arguments. */
6f25cbdd 1305 while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeiqrtQRT46")) != -1) {
3c0ef626 1306 switch (opt) {
1307 case '4':
34fee935 1308 options.address_family = AF_INET;
3c0ef626 1309 break;
1310 case '6':
34fee935 1311 options.address_family = AF_INET6;
3c0ef626 1312 break;
1313 case 'f':
1314 config_file_name = optarg;
1315 break;
1316 case 'd':
70791e56 1317 if (debug_flag == 0) {
3c0ef626 1318 debug_flag = 1;
1319 options.log_level = SYSLOG_LEVEL_DEBUG1;
70791e56 1320 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
3c0ef626 1321 options.log_level++;
3c0ef626 1322 break;
1323 case 'D':
1324 no_daemon_flag = 1;
1325 break;
1326 case 'e':
1327 log_stderr = 1;
1328 break;
1329 case 'i':
1330 inetd_flag = 1;
1331 break;
1b56ff3d 1332 case 'r':
1333 rexec_flag = 0;
1334 break;
1335 case 'R':
1336 rexeced_flag = 1;
1337 inetd_flag = 1;
1338 break;
3c0ef626 1339 case 'Q':
1340 /* ignored */
1341 break;
1342 case 'q':
1343 options.log_level = SYSLOG_LEVEL_QUIET;
1344 break;
1345 case 'b':
2e437378 1346 options.server_key_bits = (int)strtonum(optarg, 256,
1347 32768, NULL);
3c0ef626 1348 break;
1349 case 'p':
1350 options.ports_from_cmdline = 1;
1351 if (options.num_ports >= MAX_PORTS) {
1352 fprintf(stderr, "too many ports.\n");
1353 exit(1);
1354 }
1355 options.ports[options.num_ports++] = a2port(optarg);
1356 if (options.ports[options.num_ports-1] == 0) {
1357 fprintf(stderr, "Bad port number.\n");
1358 exit(1);
1359 }
1360 break;
1361 case 'g':
1362 if ((options.login_grace_time = convtime(optarg)) == -1) {
1363 fprintf(stderr, "Invalid login grace time.\n");
1364 exit(1);
1365 }
1366 break;
1367 case 'k':
1368 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1369 fprintf(stderr, "Invalid key regeneration interval.\n");
1370 exit(1);
1371 }
1372 break;
1373 case 'h':
1374 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1375 fprintf(stderr, "too many host keys.\n");
1376 exit(1);
1377 }
1378 options.host_key_files[options.num_host_key_files++] = optarg;
1379 break;
3c0ef626 1380 case 't':
1381 test_flag = 1;
1382 break;
6f25cbdd 1383 case 'T':
1384 test_flag = 2;
1385 break;
1386 case 'C':
1387 cp = optarg;
1388 while ((p = strsep(&cp, ",")) && *p != '\0') {
1389 if (strncmp(p, "addr=", 5) == 0)
1390 test_addr = xstrdup(p + 5);
1391 else if (strncmp(p, "host=", 5) == 0)
1392 test_host = xstrdup(p + 5);
1393 else if (strncmp(p, "user=", 5) == 0)
1394 test_user = xstrdup(p + 5);
1395 else {
1396 fprintf(stderr, "Invalid test "
1397 "mode specification %s\n", p);
1398 exit(1);
1399 }
1400 }
1401 break;
3c0ef626 1402 case 'u':
2e437378 1403 utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
e54b3d7c 1404 if (utmp_len > MAXHOSTNAMELEN) {
1405 fprintf(stderr, "Invalid utmp length.\n");
1406 exit(1);
1407 }
3c0ef626 1408 break;
1e608e42 1409 case 'o':
416fd2a8 1410 line = xstrdup(optarg);
1411 if (process_server_config_line(&options, line,
2e437378 1412 "command-line", 0, NULL, NULL, NULL, NULL) != 0)
1e608e42 1413 exit(1);
416fd2a8 1414 xfree(line);
1e608e42 1415 break;
3c0ef626 1416 case '?':
1417 default:
1e608e42 1418 usage();
1419 break;
3c0ef626 1420 }
1421 }
1b56ff3d 1422 if (rexeced_flag || inetd_flag)
1423 rexec_flag = 0;
bd5d5d2a 1424 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1b56ff3d 1425 fatal("sshd re-exec requires execution with an absolute path");
1426 if (rexeced_flag)
1427 closefrom(REEXEC_MIN_FREE_FD);
1428 else
1429 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1430
3c0ef626 1431 SSLeay_add_all_algorithms();
3c0ef626 1432
1433 /*
1434 * Force logging to stderr until we have loaded the private host
1435 * key (unless started from inetd)
1436 */
1437 log_init(__progname,
1e608e42 1438 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1439 SYSLOG_LEVEL_INFO : options.log_level,
1440 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1441 SYSLOG_FACILITY_AUTH : options.log_facility,
1c14df9e 1442 log_stderr || !inetd_flag);
3c0ef626 1443
2a304a95 1444 /*
1445 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1446 * root's environment
34fee935 1447 */
1448 if (getenv("KRB5CCNAME") != NULL)
1449 unsetenv("KRB5CCNAME");
1450
e54b3d7c 1451#ifdef _UNICOS
1b56ff3d 1452 /* Cray can define user privs drop all privs now!
3c0ef626 1453 * Not needed on PRIV_SU systems!
1454 */
1455 drop_cray_privs();
1456#endif
1457
1b56ff3d 1458 sensitive_data.server_key = NULL;
1459 sensitive_data.ssh1_host_key = NULL;
1460 sensitive_data.have_ssh1_key = 0;
1461 sensitive_data.have_ssh2_key = 0;
1462
6f25cbdd 1463 /*
1464 * If we're doing an extended config test, make sure we have all of
1465 * the parameters we need. If we're not doing an extended test,
1466 * do not silently ignore connection test params.
1467 */
1468 if (test_flag >= 2 &&
1469 (test_user != NULL || test_host != NULL || test_addr != NULL)
1470 && (test_user == NULL || test_host == NULL || test_addr == NULL))
1471 fatal("user, host and addr are all required when testing "
1472 "Match configs");
1473 if (test_flag < 2 && (test_user != NULL || test_host != NULL ||
1474 test_addr != NULL))
1475 fatal("Config test connection parameter (-C) provided without "
1476 "test mode (-T)");
1477
1b56ff3d 1478 /* Fetch our configuration */
1479 buffer_init(&cfg);
1480 if (rexeced_flag)
1481 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1482 else
1483 load_server_config(config_file_name, &cfg);
1484
2e437378 1485 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1486 &cfg, NULL, NULL, NULL);
3c0ef626 1487
e00da40d 1488 seed_rng();
1489
3c0ef626 1490 /* Fill in default values for those options not explicitly set. */
1491 fill_default_server_options(&options);
1492
25d429a2 1493 /* challenge-response is implemented via keyboard interactive */
1494 if (options.challenge_response_authentication)
1495 options.kbd_interactive_authentication = 1;
1496
34fee935 1497 /* set default channel AF */
1498 channel_set_af(options.address_family);
1499
3c0ef626 1500 /* Check that there are no remaining arguments. */
1501 if (optind < ac) {
1502 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1503 exit(1);
1504 }
1505
34fee935 1506 debug("sshd version %.100s", SSH_RELEASE);
3c0ef626 1507
2e437378 1508 /* Store privilege separation user for later use if required. */
1509 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1510 if (use_privsep || options.kerberos_authentication)
1511 fatal("Privilege separation user %s does not exist",
1512 SSH_PRIVSEP_USER);
1513 } else {
1514 memset(privsep_pw->pw_passwd, 0, strlen(privsep_pw->pw_passwd));
1515 privsep_pw = pwcopy(privsep_pw);
1516 xfree(privsep_pw->pw_passwd);
1517 privsep_pw->pw_passwd = xstrdup("*");
1518 }
1519 endpwent();
1520
3c0ef626 1521 /* load private host keys */
2e437378 1522 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
e54b3d7c 1523 sizeof(Key *));
1e608e42 1524 for (i = 0; i < options.num_host_key_files; i++)
3c0ef626 1525 sensitive_data.host_keys[i] = NULL;
3c0ef626 1526
1e608e42 1527 for (i = 0; i < options.num_host_key_files; i++) {
3c0ef626 1528 key = key_load_private(options.host_key_files[i], "", NULL);
1529 sensitive_data.host_keys[i] = key;
1530 if (key == NULL) {
1531 error("Could not load host key: %s",
1532 options.host_key_files[i]);
1533 sensitive_data.host_keys[i] = NULL;
1534 continue;
1535 }
1e608e42 1536 switch (key->type) {
3c0ef626 1537 case KEY_RSA1:
1538 sensitive_data.ssh1_host_key = key;
1539 sensitive_data.have_ssh1_key = 1;
1540 break;
1541 case KEY_RSA:
1542 case KEY_DSA:
1543 sensitive_data.have_ssh2_key = 1;
1544 break;
1545 }
1546 debug("private host key: #%d type %d %s", i, key->type,
1547 key_type(key));
1548 }
1549 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
70791e56 1550 logit("Disabling protocol version 1. Could not load host key");
3c0ef626 1551 options.protocol &= ~SSH_PROTO_1;
1552 }
5598e598 1553#ifndef GSSAPI
1554 /* The GSSAPI key exchange can run without a host key */
3c0ef626 1555 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
70791e56 1556 logit("Disabling protocol version 2. Could not load host key");
3c0ef626 1557 options.protocol &= ~SSH_PROTO_2;
1558 }
5598e598 1559#endif
3c0ef626 1560 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
70791e56 1561 logit("sshd: no hostkeys available -- exiting.");
3c0ef626 1562 exit(1);
1563 }
1564
1565 /* Check certain values for sanity. */
1566 if (options.protocol & SSH_PROTO_1) {
1567 if (options.server_key_bits < 512 ||
1568 options.server_key_bits > 32768) {
1569 fprintf(stderr, "Bad server key size.\n");
1570 exit(1);
1571 }
1572 /*
1573 * Check that server and host key lengths differ sufficiently. This
1574 * is necessary to make double encryption work with rsaref. Oh, I
1575 * hate software patents. I dont know if this can go? Niels
1576 */
1577 if (options.server_key_bits >
ff2d7a98 1578 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1579 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1580 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1581 SSH_KEY_BITS_RESERVED) {
3c0ef626 1582 options.server_key_bits =
ff2d7a98 1583 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1584 SSH_KEY_BITS_RESERVED;
3c0ef626 1585 debug("Forcing server key to %d bits to make it differ from host key.",
1586 options.server_key_bits);
1587 }
1588 }
1589
ff2d7a98 1590 if (use_privsep) {
ff2d7a98 1591 struct stat st;
1592
ff2d7a98 1593 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1594 (S_ISDIR(st.st_mode) == 0))
1595 fatal("Missing privilege separation directory: %s",
1596 _PATH_PRIVSEP_CHROOT_DIR);
e54b3d7c 1597
1598#ifdef HAVE_CYGWIN
1599 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1600 (st.st_uid != getuid () ||
1601 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1602#else
ff2d7a98 1603 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
e54b3d7c 1604#endif
1c14df9e 1605 fatal("%s must be owned by root and not group or "
1606 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
ff2d7a98 1607 }
1608
6f25cbdd 1609 if (test_flag > 1) {
1610 if (test_user != NULL && test_addr != NULL && test_host != NULL)
1611 parse_server_match_config(&options, test_user,
1612 test_host, test_addr);
1613 dump_config(&options);
1614 }
1615
3c0ef626 1616 /* Configuration looks good, so exit if in test mode. */
1617 if (test_flag)
1618 exit(0);
1619
2980ea68 1620 /*
1621 * Clear out any supplemental groups we may have inherited. This
1622 * prevents inadvertent creation of files with bad modes (in the
416fd2a8 1623 * portable version at least, it's certainly possible for PAM
1624 * to create a file, and we can't control the code in every
2980ea68 1625 * module which might be used).
1626 */
1627 if (setgroups(0, NULL) < 0)
1628 debug("setgroups() failed: %.200s", strerror(errno));
3c0ef626 1629
1b56ff3d 1630 if (rexec_flag) {
2e437378 1631 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1b56ff3d 1632 for (i = 0; i < rexec_argc; i++) {
1633 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1634 rexec_argv[i] = saved_argv[i];
1635 }
1636 rexec_argv[rexec_argc] = "-R";
1637 rexec_argv[rexec_argc + 1] = NULL;
1638 }
1639
6f25cbdd 1640 /* Ensure that umask disallows at least group and world write */
1641 new_umask = umask(0077) | 0022;
1642 (void) umask(new_umask);
1643
3c0ef626 1644 /* Initialize the log (it is reinitialized below in case we forked). */
34fee935 1645 if (debug_flag && (!inetd_flag || rexeced_flag))
3c0ef626 1646 log_stderr = 1;
1647 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1648
1649 /*
1650 * If not in debugging mode, and not started from inetd, disconnect
1651 * from the controlling terminal, and fork. The original process
1652 * exits.
1653 */
1654 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1655#ifdef TIOCNOTTY
1656 int fd;
1657#endif /* TIOCNOTTY */
1658 if (daemon(0, 0) < 0)
1659 fatal("daemon() failed: %.200s", strerror(errno));
1660
1661 /* Disconnect from the controlling tty. */
1662#ifdef TIOCNOTTY
1663 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1664 if (fd >= 0) {
1665 (void) ioctl(fd, TIOCNOTTY, NULL);
1666 close(fd);
1667 }
1668#endif /* TIOCNOTTY */
1669 }
1670 /* Reinitialize the log (because of the fork above). */
1671 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1672
1673 /* Initialize the random number generator. */
1674 arc4random_stir();
1675
1676 /* Chdir to the root directory so that the current disk can be
1677 unmounted if desired. */
1678 chdir("/");
1e608e42 1679
3c0ef626 1680 /* ignore SIGPIPE */
1681 signal(SIGPIPE, SIG_IGN);
1682
2e437378 1683 /* Get a connection, either from inetd or a listening TCP socket */
3c0ef626 1684 if (inetd_flag) {
2e437378 1685 server_accept_inetd(&sock_in, &sock_out);
3c0ef626 1686 } else {
2e437378 1687 server_listen();
3c0ef626 1688
1689 if (options.protocol & SSH_PROTO_1)
1690 generate_ephemeral_server_key();
1691
3c0ef626 1692 signal(SIGHUP, sighup_handler);
2e437378 1693 signal(SIGCHLD, main_sigchld_handler);
3c0ef626 1694 signal(SIGTERM, sigterm_handler);
1695 signal(SIGQUIT, sigterm_handler);
1696
2e437378 1697 /*
1698 * Write out the pid file after the sigterm handler
1699 * is setup and the listen sockets are bound
1700 */
3c0ef626 1701 if (!debug_flag) {
2e437378 1702 FILE *f = fopen(options.pid_file, "w");
1703
70791e56 1704 if (f == NULL) {
1705 error("Couldn't create pid file \"%s\": %s",
1706 options.pid_file, strerror(errno));
1707 } else {
ff2d7a98 1708 fprintf(f, "%ld\n", (long) getpid());
3c0ef626 1709 fclose(f);
1710 }
1711 }
1712
2e437378 1713 /* Accept a connection and return in a forked child */
1714 server_accept_loop(&sock_in, &sock_out,
1715 &newsock, config_s);
3c0ef626 1716 }
1717
1718 /* This is the child processing a new connection. */
2a304a95 1719 setproctitle("%s", "[accepted]");
3c0ef626 1720
2980ea68 1721 /*
1722 * Create a new session and process group since the 4.4BSD
1723 * setlogin() affects the entire process group. We don't
1724 * want the child to be able to affect the parent.
1725 */
70791e56 1726#if !defined(SSHD_ACQUIRES_CTTY)
1c14df9e 1727 /*
70791e56 1728 * If setsid is called, on some platforms sshd will later acquire a
1729 * controlling terminal which will result in "could not set
1730 * controlling tty" errors.
1c14df9e 1731 */
ff2d7a98 1732 if (!debug_flag && !inetd_flag && setsid() < 0)
2980ea68 1733 error("setsid: %.100s", strerror(errno));
1734#endif
1735
1b56ff3d 1736 if (rexec_flag) {
1737 int fd;
1738
1739 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1740 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1741 dup2(newsock, STDIN_FILENO);
1742 dup2(STDIN_FILENO, STDOUT_FILENO);
1743 if (startup_pipe == -1)
1744 close(REEXEC_STARTUP_PIPE_FD);
1745 else
1746 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1747
1748 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1749 close(config_s[1]);
1750 if (startup_pipe != -1)
1751 close(startup_pipe);
1752
1753 execv(rexec_argv[0], rexec_argv);
1754
1755 /* Reexec has failed, fall back and continue */
1756 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1757 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1758 log_init(__progname, options.log_level,
1759 options.log_facility, log_stderr);
1760
1761 /* Clean up fds */
1762 startup_pipe = REEXEC_STARTUP_PIPE_FD;
1763 close(config_s[1]);
1764 close(REEXEC_CONFIG_PASS_FD);
1765 newsock = sock_out = sock_in = dup(STDIN_FILENO);
1766 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1767 dup2(fd, STDIN_FILENO);
1768 dup2(fd, STDOUT_FILENO);
1769 if (fd > STDERR_FILENO)
1770 close(fd);
1771 }
1772 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1773 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1774 }
1775
3c0ef626 1776 /*
1777 * Disable the key regeneration alarm. We will not regenerate the
1778 * key since we are no longer in a position to give it to anyone. We
1779 * will not restart on SIGHUP since it no longer makes sense.
1780 */
1781 alarm(0);
1782 signal(SIGALRM, SIG_DFL);
1783 signal(SIGHUP, SIG_DFL);
1784 signal(SIGTERM, SIG_DFL);
1785 signal(SIGQUIT, SIG_DFL);
1786 signal(SIGCHLD, SIG_DFL);
1787 signal(SIGINT, SIG_DFL);
1788
3c0ef626 1789 /*
1790 * Register our connection. This turns encryption off because we do
1791 * not have a key.
1792 */
1793 packet_set_connection(sock_in, sock_out);
34fee935 1794 packet_set_server();
1795
1796 /* Set SO_KEEPALIVE if requested. */
1797 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1798 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1799 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
3c0ef626 1800
34fee935 1801 if ((remote_port = get_remote_port()) < 0) {
1802 debug("get_remote_port failed");
1803 cleanup_exit(255);
1804 }
e00da40d 1805
1806 /*
1807 * We use get_canonical_hostname with usedns = 0 instead of
1808 * get_remote_ipaddr here so IP options will be checked.
1809 */
2e437378 1810 (void) get_canonical_hostname(0);
1811 /*
1812 * The rest of the code depends on the fact that
1813 * get_remote_ipaddr() caches the remote ip, even if
1814 * the socket goes away.
1815 */
1816 remote_ip = get_remote_ipaddr();
3c0ef626 1817
34fee935 1818#ifdef SSH_AUDIT_EVENTS
1819 audit_connection_from(remote_ip, remote_port);
1820#endif
3c0ef626 1821#ifdef LIBWRAP
bd5d5d2a 1822 allow_severity = options.log_facility|LOG_INFO;
1823 deny_severity = options.log_facility|LOG_WARNING;
3c0ef626 1824 /* Check whether logins are denied from this host. */
1b56ff3d 1825 if (packet_connection_is_on_socket()) {
3c0ef626 1826 struct request_info req;
1827
1828 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1829 fromhost(&req);
1830
1831 if (!hosts_access(&req)) {
1832 debug("Connection refused by tcp wrapper");
1833 refuse(&req);
1834 /* NOTREACHED */
1835 fatal("libwrap refuse returns");
1836 }
1837 }
1838#endif /* LIBWRAP */
1839
1840 /* Log the connection. */
1841 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1842
34fee935 1843#ifdef USE_SECURITY_SESSION_API
1844 /*
1845 * Create a new security session for use by the new user login if
1846 * the current session is the root session or we are not launched
1847 * by inetd (eg: debugging mode or server mode). We do not
1848 * necessarily need to create a session if we are launched from
1849 * inetd because Panther xinetd will create a session for us.
1850 *
1851 * The only case where this logic will fail is if there is an
1852 * inetd running in a non-root session which is not creating
1853 * new sessions for us. Then all the users will end up in the
1854 * same session (bad).
1855 *
1856 * When the client exits, the session will be destroyed for us
1857 * automatically.
1858 *
1859 * We must create the session before any credentials are stored
1860 * (including AFS pags, which happens a few lines below).
1861 */
1862 {
1863 OSStatus err = 0;
1864 SecuritySessionId sid = 0;
1865 SessionAttributeBits sattrs = 0;
1866
1867 err = SessionGetInfo(callerSecuritySession, &sid, &sattrs);
1868 if (err)
1869 error("SessionGetInfo() failed with error %.8X",
1870 (unsigned) err);
1871 else
1872 debug("Current Session ID is %.8X / Session Attributes are %.8X",
1873 (unsigned) sid, (unsigned) sattrs);
1874
1875 if (inetd_flag && !(sattrs & sessionIsRoot))
1876 debug("Running in inetd mode in a non-root session... "
1877 "assuming inetd created the session for us.");
1878 else {
1879 debug("Creating new security session...");
1880 err = SessionCreate(0, sessionHasTTY | sessionIsRemote);
1881 if (err)
1882 error("SessionCreate() failed with error %.8X",
1883 (unsigned) err);
1884
1885 err = SessionGetInfo(callerSecuritySession, &sid,
1886 &sattrs);
1887 if (err)
1888 error("SessionGetInfo() failed with error %.8X",
1889 (unsigned) err);
1890 else
1891 debug("New Session ID is %.8X / Session Attributes are %.8X",
1892 (unsigned) sid, (unsigned) sattrs);
1893 }
1894 }
1895#endif
1896
6f25cbdd 1897 /* set the HPN options for the child */
1898 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1899
3c0ef626 1900 /*
e00da40d 1901 * We don't want to listen forever unless the other side
3c0ef626 1902 * successfully authenticates itself. So we set up an alarm which is
1903 * cleared after successful authentication. A limit of zero
e00da40d 1904 * indicates no limit. Note that we don't set the alarm in debugging
3c0ef626 1905 * mode; it is just annoying to have the server exit just when you
1906 * are about to discover the bug.
1907 */
1908 signal(SIGALRM, grace_alarm_handler);
1909 if (!debug_flag)
1910 alarm(options.login_grace_time);
1911
1912 sshd_exchange_identification(sock_in, sock_out);
70791e56 1913#if defined(AFS_KRB5)
3c0ef626 1914 /* If machine has AFS, set process authentication group. */
1915 if (k_hasafs()) {
1916 k_setpag();
1917 k_unlog();
1918 }
f2fd21a2 1919#endif /* AFS || AFS_KRB5 */
3c0ef626 1920
bd5d5d2a 1921 /* In inetd mode, generate ephemeral key only for proto 1 connections */
1922 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
1923 generate_ephemeral_server_key();
1924
3c0ef626 1925 packet_set_nonblocking();
1926
416fd2a8 1927 /* allocate authentication context */
2e437378 1928 authctxt = xcalloc(1, sizeof(*authctxt));
416fd2a8 1929
34fee935 1930 authctxt->loginmsg = &loginmsg;
1931
416fd2a8 1932 /* XXX global for cleanup, access from other modules */
1933 the_authctxt = authctxt;
1934
34fee935 1935 /* prepare buffer to collect messages to display to user after login */
1936 buffer_init(&loginmsg);
1937
2980ea68 1938 if (use_privsep)
416fd2a8 1939 if (privsep_preauth(authctxt) == 1)
2980ea68 1940 goto authenticated;
1941
3c0ef626 1942 /* perform the key exchange */
1943 /* authenticate user and start session */
1944 if (compat20) {
1945 do_ssh2_kex();
416fd2a8 1946 do_authentication2(authctxt);
3c0ef626 1947 } else {
1948 do_ssh1_kex();
416fd2a8 1949 do_authentication(authctxt);
2980ea68 1950 }
1951 /*
1952 * If we use privilege separation, the unprivileged child transfers
1953 * the current keystate and exits
1954 */
1955 if (use_privsep) {
1956 mm_send_keystate(pmonitor);
1957 exit(0);
3c0ef626 1958 }
2980ea68 1959
1960 authenticated:
e00da40d 1961 /*
1962 * Cancel the alarm we set to limit the time taken for
1963 * authentication.
1964 */
1965 alarm(0);
1966 signal(SIGALRM, SIG_DFL);
2e437378 1967 authctxt->authenticated = 1;
e00da40d 1968 if (startup_pipe != -1) {
1969 close(startup_pipe);
1970 startup_pipe = -1;
1971 }
1972
34fee935 1973#ifdef SSH_AUDIT_EVENTS
1974 audit_event(SSH_AUTH_SUCCESS);
1975#endif
1976
bd5d5d2a 1977#ifdef GSSAPI
6f25cbdd 1978 if (options.gss_authentication && options.gss_deleg_creds) {
bd5d5d2a 1979 temporarily_use_uid(authctxt->pw);
1980 ssh_gssapi_storecreds();
1981 restore_uid();
1982 }
1983#endif
1984#ifdef USE_PAM
1985 if (options.use_pam) {
1986 do_pam_setcred(1);
1987 do_pam_session();
1988 }
1989#endif
1990
2980ea68 1991 /*
1992 * In privilege separation, we fork another child and prepare
1993 * file descriptor passing.
1994 */
1995 if (use_privsep) {
1996 privsep_postauth(authctxt);
1997 /* the monitor process [priv] will not return */
1998 if (!compat20)
1999 destroy_sensitive_data();
2000 }
2001
6f25cbdd 2002 packet_set_timeout(options.client_alive_interval,
2003 options.client_alive_count_max);
2004
416fd2a8 2005 /* Start session. */
2980ea68 2006 do_authenticated(authctxt);
2007
3c0ef626 2008 /* The connection has been terminated. */
6f25cbdd 2009 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
2010 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
2011 verbose("Transferred: sent %llu, received %llu bytes", obytes, ibytes);
2012
2013 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
3c0ef626 2014
2015#ifdef USE_PAM
70791e56 2016 if (options.use_pam)
2017 finish_pam();
3c0ef626 2018#endif /* USE_PAM */
2019
34fee935 2020#ifdef SSH_AUDIT_EVENTS
2021 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2022#endif
2023
3c0ef626 2024 packet_close();
2980ea68 2025
2026 if (use_privsep)
2027 mm_terminate();
2028
3c0ef626 2029 exit(0);
2030}
2031
2980ea68 2032/*
2033 * Decrypt session_key_int using our private server key and private host key
2034 * (key with larger modulus first).
2035 */
2036int
2037ssh1_session_key(BIGNUM *session_key_int)
2038{
2039 int rsafail = 0;
2040
2e437378 2041 if (BN_cmp(sensitive_data.server_key->rsa->n,
2042 sensitive_data.ssh1_host_key->rsa->n) > 0) {
2980ea68 2043 /* Server key has bigger modulus. */
2044 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2e437378 2045 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2046 SSH_KEY_BITS_RESERVED) {
2047 fatal("do_connection: %s: "
2048 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2980ea68 2049 get_remote_ipaddr(),
2050 BN_num_bits(sensitive_data.server_key->rsa->n),
2051 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2052 SSH_KEY_BITS_RESERVED);
2053 }
2054 if (rsa_private_decrypt(session_key_int, session_key_int,
2055 sensitive_data.server_key->rsa) <= 0)
2056 rsafail++;
2057 if (rsa_private_decrypt(session_key_int, session_key_int,
2058 sensitive_data.ssh1_host_key->rsa) <= 0)
2059 rsafail++;
2060 } else {
2061 /* Host key has bigger modulus (or they are equal). */
2062 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2e437378 2063 BN_num_bits(sensitive_data.server_key->rsa->n) +
2064 SSH_KEY_BITS_RESERVED) {
2065 fatal("do_connection: %s: "
2066 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2980ea68 2067 get_remote_ipaddr(),
2068 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2069 BN_num_bits(sensitive_data.server_key->rsa->n),
2070 SSH_KEY_BITS_RESERVED);
2071 }
2072 if (rsa_private_decrypt(session_key_int, session_key_int,
2073 sensitive_data.ssh1_host_key->rsa) < 0)
2074 rsafail++;
2075 if (rsa_private_decrypt(session_key_int, session_key_int,
2076 sensitive_data.server_key->rsa) < 0)
2077 rsafail++;
2078 }
2079 return (rsafail);
2080}
3c0ef626 2081/*
2082 * SSH1 key exchange
2083 */
2084static void
2085do_ssh1_kex(void)
2086{
2087 int i, len;
3c0ef626 2088 int rsafail = 0;
2089 BIGNUM *session_key_int;
2090 u_char session_key[SSH_SESSION_KEY_LENGTH];
2091 u_char cookie[8];
2092 u_int cipher_type, auth_mask, protocol_flags;
3c0ef626 2093
2094 /*
2095 * Generate check bytes that the client must send back in the user
2096 * packet in order for it to be accepted; this is used to defy ip
2097 * spoofing attacks. Note that this only works against somebody
2098 * doing IP spoofing from a remote machine; any machine on the local
2099 * network can still see outgoing packets and catch the random
2100 * cookie. This only affects rhosts authentication, and this is one
2101 * of the reasons why it is inherently insecure.
2102 */
6f25cbdd 2103 arc4random_buf(cookie, sizeof(cookie));
3c0ef626 2104
2105 /*
2106 * Send our public key. We include in the packet 64 bits of random
2107 * data that must be matched in the reply in order to prevent IP
2108 * spoofing.
2109 */
2110 packet_start(SSH_SMSG_PUBLIC_KEY);
2111 for (i = 0; i < 8; i++)
2112 packet_put_char(cookie[i]);
2113
2114 /* Store our public server RSA key. */
2115 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2116 packet_put_bignum(sensitive_data.server_key->rsa->e);
2117 packet_put_bignum(sensitive_data.server_key->rsa->n);
2118
2119 /* Store our public host RSA key. */
2120 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2121 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2122 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2123
2124 /* Put protocol flags. */
2125 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2126
2127 /* Declare which ciphers we support. */
2128 packet_put_int(cipher_mask_ssh1(0));
2129
2130 /* Declare supported authentication types. */
2131 auth_mask = 0;
3c0ef626 2132 if (options.rhosts_rsa_authentication)
2133 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2134 if (options.rsa_authentication)
2135 auth_mask |= 1 << SSH_AUTH_RSA;
ff2d7a98 2136 if (options.challenge_response_authentication == 1)
2137 auth_mask |= 1 << SSH_AUTH_TIS;
3c0ef626 2138 if (options.password_authentication)
2139 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2140 packet_put_int(auth_mask);
2141
2142 /* Send the packet and wait for it to be sent. */
2143 packet_send();
2144 packet_write_wait();
2145
2146 debug("Sent %d bit server key and %d bit host key.",
2147 BN_num_bits(sensitive_data.server_key->rsa->n),
2148 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2149
2150 /* Read clients reply (cipher type and session key). */
1e608e42 2151 packet_read_expect(SSH_CMSG_SESSION_KEY);
3c0ef626 2152
2153 /* Get cipher type and check whether we accept this. */
2154 cipher_type = packet_get_char();
2155
2156 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2157 packet_disconnect("Warning: client selects unsupported cipher.");
2158
2159 /* Get check bytes from the packet. These must match those we
2160 sent earlier with the public key packet. */
2161 for (i = 0; i < 8; i++)
2162 if (cookie[i] != packet_get_char())
2163 packet_disconnect("IP Spoofing check bytes do not match.");
2164
2165 debug("Encryption type: %.200s", cipher_name(cipher_type));
2166
2167 /* Get the encrypted integer. */
1e608e42 2168 if ((session_key_int = BN_new()) == NULL)
2169 fatal("do_ssh1_kex: BN_new failed");
2170 packet_get_bignum(session_key_int);
3c0ef626 2171
2172 protocol_flags = packet_get_int();
2173 packet_set_protocol_flags(protocol_flags);
1e608e42 2174 packet_check_eom();
3c0ef626 2175
2980ea68 2176 /* Decrypt session_key_int using host/server keys */
2177 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2178
3c0ef626 2179 /*
2180 * Extract session key from the decrypted integer. The key is in the
2181 * least significant 256 bits of the integer; the first byte of the
2182 * key is in the highest bits.
2183 */
2184 if (!rsafail) {
2e437378 2185 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
3c0ef626 2186 len = BN_num_bytes(session_key_int);
34fee935 2187 if (len < 0 || (u_int)len > sizeof(session_key)) {
2e437378 2188 error("do_ssh1_kex: bad session key len from %s: "
3c0ef626 2189 "session_key_int %d > sizeof(session_key) %lu",
2190 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2191 rsafail++;
2192 } else {
2193 memset(session_key, 0, sizeof(session_key));
2194 BN_bn2bin(session_key_int,
2195 session_key + sizeof(session_key) - len);
2196
1b56ff3d 2197 derive_ssh1_session_id(
3c0ef626 2198 sensitive_data.ssh1_host_key->rsa->n,
1b56ff3d 2199 sensitive_data.server_key->rsa->n,
2200 cookie, session_id);
3c0ef626 2201 /*
2202 * Xor the first 16 bytes of the session key with the
2203 * session id.
2204 */
2205 for (i = 0; i < 16; i++)
2206 session_key[i] ^= session_id[i];
2207 }
2208 }
2209 if (rsafail) {
2210 int bytes = BN_num_bytes(session_key_int);
1e608e42 2211 u_char *buf = xmalloc(bytes);
3c0ef626 2212 MD5_CTX md;
2213
70791e56 2214 logit("do_connection: generating a fake encryption key");
3c0ef626 2215 BN_bn2bin(session_key_int, buf);
2216 MD5_Init(&md);
2217 MD5_Update(&md, buf, bytes);
2218 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2219 MD5_Final(session_key, &md);
2220 MD5_Init(&md);
2221 MD5_Update(&md, session_key, 16);
2222 MD5_Update(&md, buf, bytes);
2223 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2224 MD5_Final(session_key + 16, &md);
2225 memset(buf, 0, bytes);
2226 xfree(buf);
2227 for (i = 0; i < 16; i++)
2228 session_id[i] = session_key[i] ^ session_key[i + 16];
2229 }
2980ea68 2230 /* Destroy the private and public keys. No longer. */
3c0ef626 2231 destroy_sensitive_data();
2232
2980ea68 2233 if (use_privsep)
2234 mm_ssh1_session_id(session_id);
2235
3c0ef626 2236 /* Destroy the decrypted integer. It is no longer needed. */
2237 BN_clear_free(session_key_int);
2238
2239 /* Set the session key. From this on all communications will be encrypted. */
2240 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2241
2242 /* Destroy our copy of the session key. It is no longer needed. */
2243 memset(session_key, 0, sizeof(session_key));
2244
2245 debug("Received session key; encryption turned on.");
2246
ff2d7a98 2247 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
3c0ef626 2248 packet_start(SSH_SMSG_SUCCESS);
2249 packet_send();
2250 packet_write_wait();
2251}
2252
2253/*
2254 * SSH2 key exchange: diffie-hellman-group1-sha1
2255 */
2256static void
2257do_ssh2_kex(void)
2258{
2259 Kex *kex;
2260
bd5d5d2a 2261 myflag++;
2262 debug ("MYFLAG IS %d", myflag);
3c0ef626 2263 if (options.ciphers != NULL) {
2264 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2265 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
e00da40d 2266 } else if (options.none_enabled == 1) {
2267 debug ("WARNING: None cipher enabled");
2268 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2269 myproposal[PROPOSAL_ENC_ALGS_STOC] = KEX_ENCRYPT_INCLUDE_NONE;
3c0ef626 2270 }
2271 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2272 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2273 myproposal[PROPOSAL_ENC_ALGS_STOC] =
2274 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2275
2276 if (options.macs != NULL) {
2277 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2278 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2279 }
34fee935 2280 if (options.compression == COMP_NONE) {
ff2d7a98 2281 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2282 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
34fee935 2283 } else if (options.compression == COMP_DELAYED) {
2284 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2285 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
ff2d7a98 2286 }
2e437378 2287
3c0ef626 2288 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2289
5598e598 2290#ifdef GSSAPI
34fee935 2291 {
5598e598 2292 char *orig;
2293 char *gss = NULL;
2294 char *newstr = NULL;
34fee935 2295 orig = myproposal[PROPOSAL_KEX_ALGS];
2296
2297 /*
2e437378 2298 * If we don't have a host key, then there's no point advertising
2299 * the other key exchange algorithms
34fee935 2300 */
2301
2302 if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]) == 0)
2303 orig = NULL;
2304
2305 if (options.gss_keyex)
2306 gss = ssh_gssapi_server_mechanisms();
2307 else
2308 gss = NULL;
2309
2e437378 2310 if (gss && orig)
2311 xasprintf(&newstr, "%s,%s", gss, orig);
2312 else if (gss)
34fee935 2313 newstr = gss;
2e437378 2314 else if (orig)
34fee935 2315 newstr = orig;
2e437378 2316
34fee935 2317 /*
2318 * If we've got GSSAPI mechanisms, then we've got the 'null' host
2319 * key alg, but we can't tell people about it unless its the only
2320 * host key algorithm we support
2321 */
2322 if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0)
2323 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = "null";
2324
5598e598 2325 if (newstr)
34fee935 2326 myproposal[PROPOSAL_KEX_ALGS] = newstr;
5598e598 2327 else
2328 fatal("No supported key exchange algorithms");
34fee935 2329 }
5598e598 2330#endif
2331
2e437378 2332 /* start key exchange */
2333 /* start key exchange */
2334 kex = kex_setup(myproposal);
2335 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1b56ff3d 2336 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1c14df9e 2337 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2e437378 2338 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1c14df9e 2339#ifdef GSSAPI
2340 kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
2e437378 2341 kex->kex[KEX_GSS_GRP14_SHA1] = kexgss_server;
34fee935 2342 kex->kex[KEX_GSS_GEX_SHA1] = kexgss_server;
1c14df9e 2343#endif
2e437378 2344 kex->server = 1;
2345 kex->client_version_string=client_version_string;
2346 kex->server_version_string=server_version_string;
3c0ef626 2347 kex->load_host_key=&get_hostkey_by_type;
2980ea68 2348 kex->host_key_index=&get_hostkey_index;
3c0ef626 2349
2350 xxx_kex = kex;
2351
2352 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
2353
2354 session_id2 = kex->session_id;
2355 session_id2_len = kex->session_id_len;
2356
2357#ifdef DEBUG_KEXDH
2358 /* send 1st encrypted/maced/compressed message */
2359 packet_start(SSH2_MSG_IGNORE);
2360 packet_put_cstring("markus");
2361 packet_send();
2362 packet_write_wait();
2363#endif
2364 debug("KEX done");
2365}
416fd2a8 2366
2367/* server specific fatal cleanup */
2368void
2369cleanup_exit(int i)
2370{
2371 if (the_authctxt)
2372 do_cleanup(the_authctxt);
34fee935 2373#ifdef SSH_AUDIT_EVENTS
2374 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2375 if (!use_privsep || mm_is_monitor())
2376 audit_event(SSH_CONNECTION_ABANDON);
2377#endif
416fd2a8 2378 _exit(i);
2379}
This page took 0.451997 seconds and 5 git commands to generate.