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