]> andersk Git - gssapi-openssh.git/blame - openssh/sshd.c
o Reorganize merge messages.
[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"
e54b3d7c 45RCSID("$OpenBSD: sshd.c,v 1.260 2002/09/27 10:42:09 mickey 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"
63#include "mpaux.h"
64#include "log.h"
65#include "servconf.h"
66#include "uidswap.h"
67#include "compat.h"
68#include "buffer.h"
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"
80#include "dispatch.h"
81#include "channels.h"
2980ea68 82#include "session.h"
83#include "monitor_mm.h"
84#include "monitor.h"
85#include "monitor_wrap.h"
86#include "monitor_fdpass.h"
3c0ef626 87
5598e598 88#ifdef GSSAPI
89#include "ssh-gss.h"
90#endif
91
0b582e46 92#ifdef GSSAPI
93#include <openssl/md5.h>
94#include "bufaux.h"
95#endif /* GSSAPI */
0b582e46 96
3c0ef626 97#ifdef LIBWRAP
98#include <tcpd.h>
99#include <syslog.h>
100int allow_severity = LOG_INFO;
101int deny_severity = LOG_WARNING;
102#endif /* LIBWRAP */
103
104#ifndef O_NOCTTY
105#define O_NOCTTY 0
106#endif
107
108#ifdef HAVE___PROGNAME
109extern char *__progname;
110#else
111char *__progname;
112#endif
113
114/* Server configuration options. */
115ServerOptions options;
116
117/* Name of the server configuration file. */
ae43c103 118char *config_file_name;
3c0ef626 119
120/*
121 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
122 * Default value is AF_UNSPEC means both IPv4 and IPv6.
123 */
124#ifdef IPV4_DEFAULT
125int IPv4or6 = AF_INET;
126#else
127int IPv4or6 = AF_UNSPEC;
128#endif
129
130/*
131 * Debug mode flag. This can be set on the command line. If debug
132 * mode is enabled, extra debugging output will be sent to the system
133 * log, the daemon will not go to background, and will exit after processing
134 * the first connection.
135 */
136int debug_flag = 0;
137
138/* Flag indicating that the daemon should only test the configuration and keys. */
139int test_flag = 0;
140
141/* Flag indicating that the daemon is being started from inetd. */
142int inetd_flag = 0;
143
144/* Flag indicating that sshd should not detach and become a daemon. */
145int no_daemon_flag = 0;
146
147/* debug goes to stderr unless inetd_flag is set */
148int log_stderr = 0;
149
150/* Saved arguments to main(). */
151char **saved_argv;
152int saved_argc;
153
154/*
155 * The sockets that the server is listening; this is used in the SIGHUP
156 * signal handler.
157 */
158#define MAX_LISTEN_SOCKS 16
159int listen_socks[MAX_LISTEN_SOCKS];
160int num_listen_socks = 0;
161
162/*
163 * the client's version string, passed by sshd2 in compat mode. if != NULL,
164 * sshd will skip the version-number exchange
165 */
166char *client_version_string = NULL;
167char *server_version_string = NULL;
168
169/* for rekeying XXX fixme */
170Kex *xxx_kex;
171
172/*
173 * Any really sensitive data in the application is contained in this
174 * structure. The idea is that this structure could be locked into memory so
175 * that the pages do not get written into swap. However, there are some
176 * problems. The private key contains BIGNUMs, and we do not (in principle)
177 * have access to the internals of them, and locking just the structure is
178 * not very useful. Currently, memory locking is not implemented.
179 */
180struct {
181 Key *server_key; /* ephemeral server key */
182 Key *ssh1_host_key; /* ssh1 host key */
183 Key **host_keys; /* all private host keys */
184 int have_ssh1_key;
185 int have_ssh2_key;
186 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
187} sensitive_data;
188
189/*
190 * Flag indicating whether the RSA server key needs to be regenerated.
191 * Is set in the SIGALRM handler and cleared when the key is regenerated.
192 */
1e608e42 193static volatile sig_atomic_t key_do_regen = 0;
3c0ef626 194
195/* This is set to true when a signal is received. */
1e608e42 196static volatile sig_atomic_t received_sighup = 0;
197static volatile sig_atomic_t received_sigterm = 0;
3c0ef626 198
199/* session identifier, used by RSA-auth */
200u_char session_id[16];
201
202/* same for ssh2 */
203u_char *session_id2 = NULL;
204int session_id2_len = 0;
205
206/* record remote hostname or ip */
207u_int utmp_len = MAXHOSTNAMELEN;
208
1e608e42 209/* options.max_startup sized array of fd ints */
210int *startup_pipes = NULL;
211int startup_pipe; /* in child */
212
2980ea68 213/* variables used for privilege separation */
214extern struct monitor *pmonitor;
215extern int use_privsep;
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{
270 log("Received SIGHUP; restarting.");
271 close_listen_socks();
1e608e42 272 close_startup_pipes();
3c0ef626 273 execv(saved_argv[0], saved_argv);
ff2d7a98 274 log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
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
3c0ef626 315 /* Log error and exit. */
e54b3d7c 316 fatal("Timeout before authentication for %s", get_remote_ipaddr());
3c0ef626 317}
318
319/*
320 * Signal handler for the key regeneration alarm. Note that this
321 * alarm only occurs in the daemon waiting for connections, and it does not
322 * do anything with the private key or random state before forking.
323 * Thus there should be no concurrency control/asynchronous execution
324 * problems.
325 */
326static void
327generate_ephemeral_server_key(void)
328{
e54b3d7c 329 u_int32_t rnd = 0;
3c0ef626 330 int i;
331
332 verbose("Generating %s%d bit RSA key.",
333 sensitive_data.server_key ? "new " : "", options.server_key_bits);
334 if (sensitive_data.server_key != NULL)
335 key_free(sensitive_data.server_key);
336 sensitive_data.server_key = key_generate(KEY_RSA1,
337 options.server_key_bits);
338 verbose("RSA key generation complete.");
339
340 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
341 if (i % 4 == 0)
e54b3d7c 342 rnd = arc4random();
343 sensitive_data.ssh1_cookie[i] = rnd & 0xff;
344 rnd >>= 8;
3c0ef626 345 }
346 arc4random_stir();
347}
348
349static void
350key_regeneration_alarm(int sig)
351{
352 int save_errno = errno;
ff2d7a98 353
3c0ef626 354 signal(SIGALRM, SIG_DFL);
355 errno = save_errno;
356 key_do_regen = 1;
357}
358
359static void
360sshd_exchange_identification(int sock_in, int sock_out)
361{
362 int i, mismatch;
363 int remote_major, remote_minor;
364 int major, minor;
365 char *s;
366 char buf[256]; /* Must not be larger than remote_version. */
367 char remote_version[256]; /* Must be at least as big as buf. */
368
369 if ((options.protocol & SSH_PROTO_1) &&
370 (options.protocol & SSH_PROTO_2)) {
371 major = PROTOCOL_MAJOR_1;
372 minor = 99;
373 } else if (options.protocol & SSH_PROTO_2) {
374 major = PROTOCOL_MAJOR_2;
375 minor = PROTOCOL_MINOR_2;
376 } else {
377 major = PROTOCOL_MAJOR_1;
378 minor = PROTOCOL_MINOR_1;
379 }
380 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, SSH_VERSION);
381 server_version_string = xstrdup(buf);
382
383 if (client_version_string == NULL) {
384 /* Send our protocol version identification. */
ff2d7a98 385 if (atomicio(write, sock_out, server_version_string,
386 strlen(server_version_string))
3c0ef626 387 != strlen(server_version_string)) {
388 log("Could not write ident string to %s", get_remote_ipaddr());
389 fatal_cleanup();
390 }
391
ff2d7a98 392 /* Read other sides version identification. */
3c0ef626 393 memset(buf, 0, sizeof(buf));
394 for (i = 0; i < sizeof(buf) - 1; i++) {
395 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
396 log("Did not receive identification string from %s",
397 get_remote_ipaddr());
398 fatal_cleanup();
399 }
400 if (buf[i] == '\r') {
401 buf[i] = 0;
402 /* Kludge for F-Secure Macintosh < 1.0.2 */
403 if (i == 12 &&
404 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
405 break;
406 continue;
407 }
408 if (buf[i] == '\n') {
409 buf[i] = 0;
410 break;
411 }
412 }
413 buf[sizeof(buf) - 1] = 0;
414 client_version_string = xstrdup(buf);
415 }
416
417 /*
418 * Check that the versions match. In future this might accept
419 * several versions and set appropriate flags to handle them.
420 */
421 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
422 &remote_major, &remote_minor, remote_version) != 3) {
423 s = "Protocol mismatch.\n";
424 (void) atomicio(write, sock_out, s, strlen(s));
425 close(sock_in);
426 close(sock_out);
427 log("Bad protocol version identification '%.100s' from %s",
428 client_version_string, get_remote_ipaddr());
429 fatal_cleanup();
430 }
431 debug("Client protocol version %d.%d; client software version %.100s",
1e608e42 432 remote_major, remote_minor, remote_version);
3c0ef626 433
434 compat_datafellows(remote_version);
435
e54b3d7c 436 if (datafellows & SSH_BUG_PROBE) {
437 log("probed from %s with %s. Don't panic.",
438 get_remote_ipaddr(), client_version_string);
439 fatal_cleanup();
440 }
441
3c0ef626 442 if (datafellows & SSH_BUG_SCANNER) {
443 log("scanned from %s with %s. Don't panic.",
444 get_remote_ipaddr(), client_version_string);
445 fatal_cleanup();
446 }
447
448 mismatch = 0;
1e608e42 449 switch (remote_major) {
3c0ef626 450 case 1:
451 if (remote_minor == 99) {
452 if (options.protocol & SSH_PROTO_2)
453 enable_compat20();
454 else
455 mismatch = 1;
456 break;
457 }
458 if (!(options.protocol & SSH_PROTO_1)) {
459 mismatch = 1;
460 break;
461 }
462 if (remote_minor < 3) {
463 packet_disconnect("Your ssh version is too old and "
464 "is no longer supported. Please install a newer version.");
465 } else if (remote_minor == 3) {
466 /* note that this disables agent-forwarding */
467 enable_compat13();
468 }
469 break;
470 case 2:
471 if (options.protocol & SSH_PROTO_2) {
472 enable_compat20();
473 break;
474 }
475 /* FALLTHROUGH */
476 default:
477 mismatch = 1;
478 break;
479 }
480 chop(server_version_string);
481 debug("Local version string %.200s", server_version_string);
482
483 if (mismatch) {
484 s = "Protocol major versions differ.\n";
485 (void) atomicio(write, sock_out, s, strlen(s));
486 close(sock_in);
487 close(sock_out);
488 log("Protocol major versions differ for %s: %.200s vs. %.200s",
489 get_remote_ipaddr(),
490 server_version_string, client_version_string);
491 fatal_cleanup();
492 }
493}
494
3c0ef626 495/* Destroy the host and server keys. They will no longer be needed. */
496void
497destroy_sensitive_data(void)
498{
499 int i;
500
501 if (sensitive_data.server_key) {
502 key_free(sensitive_data.server_key);
503 sensitive_data.server_key = NULL;
504 }
1e608e42 505 for (i = 0; i < options.num_host_key_files; i++) {
3c0ef626 506 if (sensitive_data.host_keys[i]) {
507 key_free(sensitive_data.host_keys[i]);
508 sensitive_data.host_keys[i] = NULL;
509 }
510 }
511 sensitive_data.ssh1_host_key = NULL;
512 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
513}
514
2980ea68 515/* Demote private to public keys for network child */
516void
517demote_sensitive_data(void)
518{
519 Key *tmp;
520 int i;
521
522 if (sensitive_data.server_key) {
523 tmp = key_demote(sensitive_data.server_key);
524 key_free(sensitive_data.server_key);
525 sensitive_data.server_key = tmp;
526 }
527
528 for (i = 0; i < options.num_host_key_files; i++) {
529 if (sensitive_data.host_keys[i]) {
530 tmp = key_demote(sensitive_data.host_keys[i]);
531 key_free(sensitive_data.host_keys[i]);
532 sensitive_data.host_keys[i] = tmp;
533 if (tmp->type == KEY_RSA1)
534 sensitive_data.ssh1_host_key = tmp;
535 }
536 }
537
538 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
539}
540
541static void
542privsep_preauth_child(void)
543{
e54b3d7c 544 u_int32_t rnd[256];
545 gid_t gidset[1];
2980ea68 546 struct passwd *pw;
ff2d7a98 547 int i;
2980ea68 548
549 /* Enable challenge-response authentication for privilege separation */
550 privsep_challenge_enable();
551
552 for (i = 0; i < 256; i++)
e54b3d7c 553 rnd[i] = arc4random();
554 RAND_seed(rnd, sizeof(rnd));
2980ea68 555
556 /* Demote the private keys to public keys. */
557 demote_sensitive_data();
558
559 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
560 fatal("Privilege separation user %s does not exist",
561 SSH_PRIVSEP_USER);
562 memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
563 endpwent();
564
e54b3d7c 565 /* Change our root directory */
2980ea68 566 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
567 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
568 strerror(errno));
569 if (chdir("/") == -1)
570 fatal("chdir(\"/\"): %s", strerror(errno));
571
572 /* Drop our privileges */
573 debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
574 (u_int)pw->pw_gid);
ff2d7a98 575#if 0
576 /* XXX not ready, to heavy after chroot */
2980ea68 577 do_setusercontext(pw);
ff2d7a98 578#else
579 gidset[0] = pw->pw_gid;
580 if (setgid(pw->pw_gid) < 0)
581 fatal("setgid failed for %u", pw->pw_gid );
582 if (setgroups(1, gidset) < 0)
583 fatal("setgroups: %.100s", strerror(errno));
584 permanently_set_uid(pw);
585#endif
2980ea68 586}
587
e54b3d7c 588static Authctxt *
2980ea68 589privsep_preauth(void)
590{
591 Authctxt *authctxt = NULL;
592 int status;
593 pid_t pid;
594
595 /* Set up unprivileged child process to deal with network data */
596 pmonitor = monitor_init();
597 /* Store a pointer to the kex for later rekeying */
598 pmonitor->m_pkex = &xxx_kex;
599
600 pid = fork();
601 if (pid == -1) {
602 fatal("fork of unprivileged child failed");
603 } else if (pid != 0) {
e54b3d7c 604 fatal_remove_cleanup((void (*) (void *)) packet_close, NULL);
605
ff2d7a98 606 debug2("Network child is on pid %ld", (long)pid);
2980ea68 607
608 close(pmonitor->m_recvfd);
609 authctxt = monitor_child_preauth(pmonitor);
610 close(pmonitor->m_sendfd);
611
612 /* Sync memory */
613 monitor_sync(pmonitor);
614
615 /* Wait for the child's exit status */
616 while (waitpid(pid, &status, 0) < 0)
617 if (errno != EINTR)
618 break;
e54b3d7c 619
620 /* Reinstall, since the child has finished */
621 fatal_add_cleanup((void (*) (void *)) packet_close, NULL);
622
2980ea68 623 return (authctxt);
624 } else {
625 /* child */
626
627 close(pmonitor->m_sendfd);
628
629 /* Demote the child */
630 if (getuid() == 0 || geteuid() == 0)
631 privsep_preauth_child();
632 setproctitle("%s", "[net]");
633 }
634 return (NULL);
635}
636
637static void
638privsep_postauth(Authctxt *authctxt)
639{
640 extern Authctxt *x_authctxt;
641
642 /* XXX - Remote port forwarding */
643 x_authctxt = authctxt;
644
e54b3d7c 645#ifdef DISABLE_FD_PASSING
ff2d7a98 646 if (1) {
647#else
2980ea68 648 if (authctxt->pw->pw_uid == 0 || options.use_login) {
ff2d7a98 649#endif
2980ea68 650 /* File descriptor passing is broken or root login */
651 monitor_apply_keystate(pmonitor);
652 use_privsep = 0;
653 return;
654 }
655
656 /* Authentication complete */
657 alarm(0);
658 if (startup_pipe != -1) {
659 close(startup_pipe);
660 startup_pipe = -1;
661 }
662
663 /* New socket pair */
664 monitor_reinit(pmonitor);
665
666 pmonitor->m_pid = fork();
667 if (pmonitor->m_pid == -1)
668 fatal("fork of unprivileged child failed");
669 else if (pmonitor->m_pid != 0) {
e54b3d7c 670 fatal_remove_cleanup((void (*) (void *)) packet_close, NULL);
671
ff2d7a98 672 debug2("User child is on pid %ld", (long)pmonitor->m_pid);
2980ea68 673 close(pmonitor->m_recvfd);
674 monitor_child_postauth(pmonitor);
675
676 /* NEVERREACHED */
677 exit(0);
678 }
679
680 close(pmonitor->m_sendfd);
681
682 /* Demote the private keys to public keys. */
683 demote_sensitive_data();
684
685 /* Drop privileges */
686 do_setusercontext(authctxt->pw);
687
688 /* It is safe now to apply the key state */
689 monitor_apply_keystate(pmonitor);
690}
691
3c0ef626 692static char *
693list_hostkey_types(void)
694{
1e608e42 695 Buffer b;
696 char *p;
3c0ef626 697 int i;
1e608e42 698
699 buffer_init(&b);
700 for (i = 0; i < options.num_host_key_files; i++) {
3c0ef626 701 Key *key = sensitive_data.host_keys[i];
702 if (key == NULL)
703 continue;
1e608e42 704 switch (key->type) {
3c0ef626 705 case KEY_RSA:
706 case KEY_DSA:
1e608e42 707 if (buffer_len(&b) > 0)
708 buffer_append(&b, ",", 1);
709 p = key_ssh_name(key);
710 buffer_append(&b, p, strlen(p));
3c0ef626 711 break;
712 }
713 }
1e608e42 714 buffer_append(&b, "\0", 1);
715 p = xstrdup(buffer_ptr(&b));
716 buffer_free(&b);
717 debug("list_hostkey_types: %s", p);
718 return p;
3c0ef626 719}
720
2980ea68 721Key *
3c0ef626 722get_hostkey_by_type(int type)
723{
724 int i;
ff2d7a98 725
1e608e42 726 for (i = 0; i < options.num_host_key_files; i++) {
3c0ef626 727 Key *key = sensitive_data.host_keys[i];
728 if (key != NULL && key->type == type)
729 return key;
730 }
731 return NULL;
732}
733
2980ea68 734Key *
735get_hostkey_by_index(int ind)
736{
737 if (ind < 0 || ind >= options.num_host_key_files)
738 return (NULL);
739 return (sensitive_data.host_keys[ind]);
740}
741
742int
743get_hostkey_index(Key *key)
744{
745 int i;
ff2d7a98 746
2980ea68 747 for (i = 0; i < options.num_host_key_files; i++) {
748 if (key == sensitive_data.host_keys[i])
749 return (i);
750 }
751 return (-1);
752}
753
3c0ef626 754/*
755 * returns 1 if connection should be dropped, 0 otherwise.
756 * dropping starts at connection #max_startups_begin with a probability
757 * of (max_startups_rate/100). the probability increases linearly until
758 * all connections are dropped for startups > max_startups
759 */
760static int
761drop_connection(int startups)
762{
763 double p, r;
764
765 if (startups < options.max_startups_begin)
766 return 0;
767 if (startups >= options.max_startups)
768 return 1;
769 if (options.max_startups_rate == 100)
770 return 1;
771
772 p = 100 - options.max_startups_rate;
773 p *= startups - options.max_startups_begin;
774 p /= (double) (options.max_startups - options.max_startups_begin);
775 p += options.max_startups_rate;
776 p /= 100.0;
777 r = arc4random() / (double) UINT_MAX;
778
779 debug("drop_connection: p %g, r %g", p, r);
780 return (r < p) ? 1 : 0;
781}
782
1e608e42 783static void
784usage(void)
785{
786 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
787 fprintf(stderr, "Usage: %s [options]\n", __progname);
788 fprintf(stderr, "Options:\n");
789 fprintf(stderr, " -f file Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
790 fprintf(stderr, " -d Debugging mode (multiple -d means more debugging)\n");
791 fprintf(stderr, " -i Started from inetd\n");
792 fprintf(stderr, " -D Do not fork into daemon mode\n");
793 fprintf(stderr, " -t Only test configuration file and keys\n");
794 fprintf(stderr, " -q Quiet (no logging)\n");
795 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
796 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
797 fprintf(stderr, " -g seconds Grace period for authentication (default: 600)\n");
798 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
799 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
800 _PATH_HOST_KEY_FILE);
801 fprintf(stderr, " -u len Maximum hostname length for utmp recording\n");
802 fprintf(stderr, " -4 Use IPv4 only\n");
803 fprintf(stderr, " -6 Use IPv6 only\n");
804 fprintf(stderr, " -o option Process the option as if it was read from a configuration file.\n");
805 exit(1);
806}
3c0ef626 807
808/*
809 * Main program for the daemon.
810 */
811int
812main(int ac, char **av)
813{
814 extern char *optarg;
815 extern int optind;
816 int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
817 pid_t pid;
818 socklen_t fromlen;
819 fd_set *fdset;
820 struct sockaddr_storage from;
821 const char *remote_ip;
822 int remote_port;
823 FILE *f;
3c0ef626 824 struct addrinfo *ai;
825 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
826 int listen_sock, maxfd;
827 int startup_p[2];
828 int startups = 0;
2980ea68 829 Authctxt *authctxt;
3c0ef626 830 Key *key;
831 int ret, key_used = 0;
832
2980ea68 833#ifdef HAVE_SECUREWARE
834 (void)set_auth_parameters(ac, av);
835#endif
3c0ef626 836 __progname = get_progname(av[0]);
ae43c103 837 init_pathnames();
838 config_file_name = _PATH_SERVER_CONFIG_FILE;
3c0ef626 839 init_rng();
840
841 /* Save argv. */
842 saved_argc = ac;
843 saved_argv = av;
844
845 /* Initialize configuration options to their default values. */
846 initialize_server_options(&options);
847
848 /* Parse command-line arguments. */
1e608e42 849 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
3c0ef626 850 switch (opt) {
851 case '4':
852 IPv4or6 = AF_INET;
853 break;
854 case '6':
855 IPv4or6 = AF_INET6;
856 break;
857 case 'f':
858 config_file_name = optarg;
859 break;
860 case 'd':
861 if (0 == debug_flag) {
862 debug_flag = 1;
863 options.log_level = SYSLOG_LEVEL_DEBUG1;
864 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
865 options.log_level++;
866 } else {
867 fprintf(stderr, "Too high debugging level.\n");
868 exit(1);
869 }
870 break;
871 case 'D':
872 no_daemon_flag = 1;
873 break;
874 case 'e':
875 log_stderr = 1;
876 break;
877 case 'i':
878 inetd_flag = 1;
879 break;
880 case 'Q':
881 /* ignored */
882 break;
883 case 'q':
884 options.log_level = SYSLOG_LEVEL_QUIET;
885 break;
886 case 'b':
887 options.server_key_bits = atoi(optarg);
888 break;
889 case 'p':
890 options.ports_from_cmdline = 1;
891 if (options.num_ports >= MAX_PORTS) {
892 fprintf(stderr, "too many ports.\n");
893 exit(1);
894 }
895 options.ports[options.num_ports++] = a2port(optarg);
896 if (options.ports[options.num_ports-1] == 0) {
897 fprintf(stderr, "Bad port number.\n");
898 exit(1);
899 }
900 break;
901 case 'g':
902 if ((options.login_grace_time = convtime(optarg)) == -1) {
903 fprintf(stderr, "Invalid login grace time.\n");
904 exit(1);
905 }
906 break;
907 case 'k':
908 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
909 fprintf(stderr, "Invalid key regeneration interval.\n");
910 exit(1);
911 }
912 break;
913 case 'h':
914 if (options.num_host_key_files >= MAX_HOSTKEYS) {
915 fprintf(stderr, "too many host keys.\n");
916 exit(1);
917 }
918 options.host_key_files[options.num_host_key_files++] = optarg;
919 break;
920 case 'V':
921 client_version_string = optarg;
922 /* only makes sense with inetd_flag, i.e. no listen() */
923 inetd_flag = 1;
924 break;
925 case 't':
926 test_flag = 1;
927 break;
928 case 'u':
929 utmp_len = atoi(optarg);
e54b3d7c 930 if (utmp_len > MAXHOSTNAMELEN) {
931 fprintf(stderr, "Invalid utmp length.\n");
932 exit(1);
933 }
3c0ef626 934 break;
1e608e42 935 case 'o':
936 if (process_server_config_line(&options, optarg,
937 "command-line", 0) != 0)
938 exit(1);
939 break;
3c0ef626 940 case '?':
941 default:
1e608e42 942 usage();
943 break;
3c0ef626 944 }
945 }
946 SSLeay_add_all_algorithms();
947 channel_set_af(IPv4or6);
948
949 /*
950 * Force logging to stderr until we have loaded the private host
951 * key (unless started from inetd)
952 */
953 log_init(__progname,
1e608e42 954 options.log_level == SYSLOG_LEVEL_NOT_SET ?
955 SYSLOG_LEVEL_INFO : options.log_level,
956 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
957 SYSLOG_FACILITY_AUTH : options.log_facility,
3c0ef626 958 !inetd_flag);
959
e54b3d7c 960#ifdef _UNICOS
3c0ef626 961 /* Cray can define user privs drop all prives now!
962 * Not needed on PRIV_SU systems!
963 */
964 drop_cray_privs();
965#endif
966
967 seed_rng();
968
969 /* Read server configuration options from the configuration file. */
970 read_server_config(&options, config_file_name);
971
972 /* Fill in default values for those options not explicitly set. */
973 fill_default_server_options(&options);
974
975 /* Check that there are no remaining arguments. */
976 if (optind < ac) {
977 fprintf(stderr, "Extra argument %s.\n", av[optind]);
978 exit(1);
979 }
980
981 debug("sshd version %.100s", SSH_VERSION);
982
983 /* load private host keys */
e54b3d7c 984 sensitive_data.host_keys = xmalloc(options.num_host_key_files *
985 sizeof(Key *));
1e608e42 986 for (i = 0; i < options.num_host_key_files; i++)
3c0ef626 987 sensitive_data.host_keys[i] = NULL;
988 sensitive_data.server_key = NULL;
989 sensitive_data.ssh1_host_key = NULL;
990 sensitive_data.have_ssh1_key = 0;
991 sensitive_data.have_ssh2_key = 0;
992
1e608e42 993 for (i = 0; i < options.num_host_key_files; i++) {
3c0ef626 994 key = key_load_private(options.host_key_files[i], "", NULL);
995 sensitive_data.host_keys[i] = key;
996 if (key == NULL) {
997 error("Could not load host key: %s",
998 options.host_key_files[i]);
999 sensitive_data.host_keys[i] = NULL;
1000 continue;
1001 }
1e608e42 1002 switch (key->type) {
3c0ef626 1003 case KEY_RSA1:
1004 sensitive_data.ssh1_host_key = key;
1005 sensitive_data.have_ssh1_key = 1;
1006 break;
1007 case KEY_RSA:
1008 case KEY_DSA:
1009 sensitive_data.have_ssh2_key = 1;
1010 break;
1011 }
1012 debug("private host key: #%d type %d %s", i, key->type,
1013 key_type(key));
1014 }
1015 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1016 log("Disabling protocol version 1. Could not load host key");
1017 options.protocol &= ~SSH_PROTO_1;
1018 }
5598e598 1019#ifndef GSSAPI
1020 /* The GSSAPI key exchange can run without a host key */
3c0ef626 1021 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1022 log("Disabling protocol version 2. Could not load host key");
1023 options.protocol &= ~SSH_PROTO_2;
1024 }
5598e598 1025#endif
3c0ef626 1026 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1027 log("sshd: no hostkeys available -- exiting.");
1028 exit(1);
1029 }
1030
1031 /* Check certain values for sanity. */
1032 if (options.protocol & SSH_PROTO_1) {
1033 if (options.server_key_bits < 512 ||
1034 options.server_key_bits > 32768) {
1035 fprintf(stderr, "Bad server key size.\n");
1036 exit(1);
1037 }
1038 /*
1039 * Check that server and host key lengths differ sufficiently. This
1040 * is necessary to make double encryption work with rsaref. Oh, I
1041 * hate software patents. I dont know if this can go? Niels
1042 */
1043 if (options.server_key_bits >
ff2d7a98 1044 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1045 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1046 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1047 SSH_KEY_BITS_RESERVED) {
3c0ef626 1048 options.server_key_bits =
ff2d7a98 1049 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1050 SSH_KEY_BITS_RESERVED;
3c0ef626 1051 debug("Forcing server key to %d bits to make it differ from host key.",
1052 options.server_key_bits);
1053 }
1054 }
1055
ff2d7a98 1056 if (use_privsep) {
1057 struct passwd *pw;
1058 struct stat st;
1059
1060 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
1061 fatal("Privilege separation user %s does not exist",
1062 SSH_PRIVSEP_USER);
1063 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1064 (S_ISDIR(st.st_mode) == 0))
1065 fatal("Missing privilege separation directory: %s",
1066 _PATH_PRIVSEP_CHROOT_DIR);
e54b3d7c 1067
1068#ifdef HAVE_CYGWIN
1069 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1070 (st.st_uid != getuid () ||
1071 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1072#else
ff2d7a98 1073 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
e54b3d7c 1074#endif
ff2d7a98 1075 fatal("Bad owner or mode for %s",
1076 _PATH_PRIVSEP_CHROOT_DIR);
1077 }
1078
3c0ef626 1079 /* Configuration looks good, so exit if in test mode. */
1080 if (test_flag)
1081 exit(0);
1082
0b582e46 1083#ifdef GSSAPI
c7221eee 1084 ssh_gssapi_clean_env();
0b582e46 1085#endif /* GSSAPI */
0b582e46 1086
2980ea68 1087 /*
1088 * Clear out any supplemental groups we may have inherited. This
1089 * prevents inadvertent creation of files with bad modes (in the
1090 * portable version at least, it's certainly possible for PAM
1091 * to create a file, and we can't control the code in every
1092 * module which might be used).
1093 */
1094 if (setgroups(0, NULL) < 0)
1095 debug("setgroups() failed: %.200s", strerror(errno));
3c0ef626 1096
1097 /* Initialize the log (it is reinitialized below in case we forked). */
1098 if (debug_flag && !inetd_flag)
1099 log_stderr = 1;
1100 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1101
1102 /*
1103 * If not in debugging mode, and not started from inetd, disconnect
1104 * from the controlling terminal, and fork. The original process
1105 * exits.
1106 */
1107 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1108#ifdef TIOCNOTTY
1109 int fd;
1110#endif /* TIOCNOTTY */
1111 if (daemon(0, 0) < 0)
1112 fatal("daemon() failed: %.200s", strerror(errno));
1113
1114 /* Disconnect from the controlling tty. */
1115#ifdef TIOCNOTTY
1116 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1117 if (fd >= 0) {
1118 (void) ioctl(fd, TIOCNOTTY, NULL);
1119 close(fd);
1120 }
1121#endif /* TIOCNOTTY */
1122 }
1123 /* Reinitialize the log (because of the fork above). */
1124 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1125
1126 /* Initialize the random number generator. */
1127 arc4random_stir();
1128
1129 /* Chdir to the root directory so that the current disk can be
1130 unmounted if desired. */
1131 chdir("/");
1e608e42 1132
3c0ef626 1133 /* ignore SIGPIPE */
1134 signal(SIGPIPE, SIG_IGN);
1135
1136 /* Start listening for a socket, unless started from inetd. */
1137 if (inetd_flag) {
1138 int s1;
1139 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
1140 dup(s1);
1141 sock_in = dup(0);
1142 sock_out = dup(1);
1143 startup_pipe = -1;
1144 /*
1145 * We intentionally do not close the descriptors 0, 1, and 2
1146 * as our code for setting the descriptors won\'t work if
1147 * ttyfd happens to be one of those.
1148 */
1149 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1150 if (options.protocol & SSH_PROTO_1)
1151 generate_ephemeral_server_key();
1152 } else {
1153 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1154 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1155 continue;
1156 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1157 fatal("Too many listen sockets. "
1158 "Enlarge MAX_LISTEN_SOCKS");
1159 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
1160 ntop, sizeof(ntop), strport, sizeof(strport),
1161 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1162 error("getnameinfo failed");
1163 continue;
1164 }
1165 /* Create socket for listening. */
1166 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
1167 if (listen_sock < 0) {
1168 /* kernel may not support ipv6 */
1169 verbose("socket: %.100s", strerror(errno));
1170 continue;
1171 }
1172 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
1173 error("listen_sock O_NONBLOCK: %s", strerror(errno));
1174 close(listen_sock);
1175 continue;
1176 }
1177 /*
e54b3d7c 1178 * Set socket options.
1179 * Allow local port reuse in TIME_WAIT.
3c0ef626 1180 */
e54b3d7c 1181 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1182 &on, sizeof(on)) == -1)
1183 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
3c0ef626 1184
1185 debug("Bind to port %s on %s.", strport, ntop);
1186
1187 /* Bind the socket to the desired port. */
1188 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1189 if (!ai->ai_next)
1190 error("Bind to port %s on %s failed: %.200s.",
1191 strport, ntop, strerror(errno));
1192 close(listen_sock);
1193 continue;
1194 }
1195 listen_socks[num_listen_socks] = listen_sock;
1196 num_listen_socks++;
1197
1198 /* Start listening on the port. */
1199 log("Server listening on %s port %s.", ntop, strport);
1200 if (listen(listen_sock, 5) < 0)
1201 fatal("listen: %.100s", strerror(errno));
1202
1203 }
1204 freeaddrinfo(options.listen_addrs);
1205
1206 if (!num_listen_socks)
1207 fatal("Cannot bind any address.");
1208
1209 if (options.protocol & SSH_PROTO_1)
1210 generate_ephemeral_server_key();
1211
1212 /*
1213 * Arrange to restart on SIGHUP. The handler needs
1214 * listen_sock.
1215 */
1216 signal(SIGHUP, sighup_handler);
1217
1218 signal(SIGTERM, sigterm_handler);
1219 signal(SIGQUIT, sigterm_handler);
1220
1221 /* Arrange SIGCHLD to be caught. */
1222 signal(SIGCHLD, main_sigchld_handler);
1223
1224 /* Write out the pid file after the sigterm handler is setup */
1225 if (!debug_flag) {
1226 /*
1227 * Record our pid in /var/run/sshd.pid to make it
1228 * easier to kill the correct sshd. We don't want to
1229 * do this before the bind above because the bind will
1230 * fail if there already is a daemon, and this will
1231 * overwrite any old pid in the file.
1232 */
1233 f = fopen(options.pid_file, "wb");
1234 if (f) {
ff2d7a98 1235 fprintf(f, "%ld\n", (long) getpid());
3c0ef626 1236 fclose(f);
1237 }
1238 }
1239
1240 /* setup fd set for listen */
1241 fdset = NULL;
1242 maxfd = 0;
1243 for (i = 0; i < num_listen_socks; i++)
1244 if (listen_socks[i] > maxfd)
1245 maxfd = listen_socks[i];
1246 /* pipes connected to unauthenticated childs */
1247 startup_pipes = xmalloc(options.max_startups * sizeof(int));
1248 for (i = 0; i < options.max_startups; i++)
1249 startup_pipes[i] = -1;
1250
1251 /*
1252 * Stay listening for connections until the system crashes or
1253 * the daemon is killed with a signal.
1254 */
1255 for (;;) {
1256 if (received_sighup)
1257 sighup_restart();
1258 if (fdset != NULL)
1259 xfree(fdset);
1260 fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1261 fdset = (fd_set *)xmalloc(fdsetsz);
1262 memset(fdset, 0, fdsetsz);
1263
1264 for (i = 0; i < num_listen_socks; i++)
1265 FD_SET(listen_socks[i], fdset);
1266 for (i = 0; i < options.max_startups; i++)
1267 if (startup_pipes[i] != -1)
1268 FD_SET(startup_pipes[i], fdset);
1269
1270 /* Wait in select until there is a connection. */
1271 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1272 if (ret < 0 && errno != EINTR)
1273 error("select: %.100s", strerror(errno));
1274 if (received_sigterm) {
1275 log("Received signal %d; terminating.",
1e608e42 1276 (int) received_sigterm);
3c0ef626 1277 close_listen_socks();
1278 unlink(options.pid_file);
1279 exit(255);
1280 }
1281 if (key_used && key_do_regen) {
1282 generate_ephemeral_server_key();
1283 key_used = 0;
1284 key_do_regen = 0;
1285 }
1286 if (ret < 0)
1287 continue;
1288
1289 for (i = 0; i < options.max_startups; i++)
1290 if (startup_pipes[i] != -1 &&
1291 FD_ISSET(startup_pipes[i], fdset)) {
1292 /*
1293 * the read end of the pipe is ready
1294 * if the child has closed the pipe
1295 * after successful authentication
1296 * or if the child has died
1297 */
1298 close(startup_pipes[i]);
1299 startup_pipes[i] = -1;
1300 startups--;
1301 }
1302 for (i = 0; i < num_listen_socks; i++) {
1303 if (!FD_ISSET(listen_socks[i], fdset))
1304 continue;
1305 fromlen = sizeof(from);
1306 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
1307 &fromlen);
1308 if (newsock < 0) {
1309 if (errno != EINTR && errno != EWOULDBLOCK)
1310 error("accept: %.100s", strerror(errno));
1311 continue;
1312 }
1313 if (fcntl(newsock, F_SETFL, 0) < 0) {
1314 error("newsock del O_NONBLOCK: %s", strerror(errno));
1e608e42 1315 close(newsock);
3c0ef626 1316 continue;
1317 }
1318 if (drop_connection(startups) == 1) {
1319 debug("drop connection #%d", startups);
1320 close(newsock);
1321 continue;
1322 }
1323 if (pipe(startup_p) == -1) {
1324 close(newsock);
1325 continue;
1326 }
1327
1328 for (j = 0; j < options.max_startups; j++)
1329 if (startup_pipes[j] == -1) {
1330 startup_pipes[j] = startup_p[0];
1331 if (maxfd < startup_p[0])
1332 maxfd = startup_p[0];
1333 startups++;
1334 break;
1335 }
1336
1337 /*
1338 * Got connection. Fork a child to handle it, unless
1339 * we are in debugging mode.
1340 */
1341 if (debug_flag) {
1342 /*
1343 * In debugging mode. Close the listening
1344 * socket, and start processing the
1345 * connection without forking.
1346 */
1347 debug("Server will not fork when running in debugging mode.");
1348 close_listen_socks();
1349 sock_in = newsock;
1350 sock_out = newsock;
1351 startup_pipe = -1;
1352 pid = getpid();
1353 break;
1354 } else {
1355 /*
1356 * Normal production daemon. Fork, and have
1357 * the child process the connection. The
1358 * parent continues listening.
1359 */
1360 if ((pid = fork()) == 0) {
1361 /*
1362 * Child. Close the listening and max_startup
1363 * sockets. Start using the accepted socket.
1364 * Reinitialize logging (since our pid has
1365 * changed). We break out of the loop to handle
1366 * the connection.
1367 */
1368 startup_pipe = startup_p[1];
1e608e42 1369 close_startup_pipes();
3c0ef626 1370 close_listen_socks();
1371 sock_in = newsock;
1372 sock_out = newsock;
1373 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1374 break;
1375 }
1376 }
1377
1378 /* Parent. Stay in the loop. */
1379 if (pid < 0)
1380 error("fork: %.100s", strerror(errno));
1381 else
ff2d7a98 1382 debug("Forked child %ld.", (long)pid);
3c0ef626 1383
1384 close(startup_p[1]);
1385
1386 /* Mark that the key has been used (it was "given" to the child). */
1387 if ((options.protocol & SSH_PROTO_1) &&
1388 key_used == 0) {
1389 /* Schedule server key regeneration alarm. */
1390 signal(SIGALRM, key_regeneration_alarm);
1391 alarm(options.key_regeneration_time);
1392 key_used = 1;
1393 }
1394
1395 arc4random_stir();
1396
1397 /* Close the new socket (the child is now taking care of it). */
1398 close(newsock);
1399 }
1400 /* child process check (or debug mode) */
1401 if (num_listen_socks < 0)
1402 break;
1403 }
1404 }
1405
1406 /* This is the child processing a new connection. */
1407
2980ea68 1408 /*
1409 * Create a new session and process group since the 4.4BSD
1410 * setlogin() affects the entire process group. We don't
1411 * want the child to be able to affect the parent.
1412 */
1413#if 0
1414 /* XXX: this breaks Solaris */
ff2d7a98 1415 if (!debug_flag && !inetd_flag && setsid() < 0)
2980ea68 1416 error("setsid: %.100s", strerror(errno));
1417#endif
1418
3c0ef626 1419 /*
1420 * Disable the key regeneration alarm. We will not regenerate the
1421 * key since we are no longer in a position to give it to anyone. We
1422 * will not restart on SIGHUP since it no longer makes sense.
1423 */
1424 alarm(0);
1425 signal(SIGALRM, SIG_DFL);
1426 signal(SIGHUP, SIG_DFL);
1427 signal(SIGTERM, SIG_DFL);
1428 signal(SIGQUIT, SIG_DFL);
1429 signal(SIGCHLD, SIG_DFL);
1430 signal(SIGINT, SIG_DFL);
1431
3c0ef626 1432 /* Set keepalives if requested. */
1433 if (options.keepalives &&
1e608e42 1434 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
3c0ef626 1435 sizeof(on)) < 0)
1436 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1437
1438 /*
1439 * Register our connection. This turns encryption off because we do
1440 * not have a key.
1441 */
1442 packet_set_connection(sock_in, sock_out);
1443
1444 remote_port = get_remote_port();
1445 remote_ip = get_remote_ipaddr();
1446
1447#ifdef LIBWRAP
1448 /* Check whether logins are denied from this host. */
1449 {
1450 struct request_info req;
1451
1452 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1453 fromhost(&req);
1454
1455 if (!hosts_access(&req)) {
1456 debug("Connection refused by tcp wrapper");
1457 refuse(&req);
1458 /* NOTREACHED */
1459 fatal("libwrap refuse returns");
1460 }
1461 }
1462#endif /* LIBWRAP */
1463
1464 /* Log the connection. */
1465 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1466
1467 /*
1468 * We don\'t want to listen forever unless the other side
1469 * successfully authenticates itself. So we set up an alarm which is
1470 * cleared after successful authentication. A limit of zero
1471 * indicates no limit. Note that we don\'t set the alarm in debugging
1472 * mode; it is just annoying to have the server exit just when you
1473 * are about to discover the bug.
1474 */
1475 signal(SIGALRM, grace_alarm_handler);
1476 if (!debug_flag)
1477 alarm(options.login_grace_time);
1478
1479 sshd_exchange_identification(sock_in, sock_out);
1480 /*
1481 * Check that the connection comes from a privileged port.
ff2d7a98 1482 * Rhosts-Authentication only makes sense from privileged
3c0ef626 1483 * programs. Of course, if the intruder has root access on his local
1484 * machine, he can connect from any port. So do not use these
1485 * authentication methods from machines that you do not trust.
1486 */
1e608e42 1487 if (options.rhosts_authentication &&
1488 (remote_port >= IPPORT_RESERVED ||
1489 remote_port < IPPORT_RESERVED / 2)) {
3c0ef626 1490 debug("Rhosts Authentication disabled, "
1491 "originating port %d not trusted.", remote_port);
1492 options.rhosts_authentication = 0;
1493 }
1494#if defined(KRB4) && !defined(KRB5)
1495 if (!packet_connection_is_ipv4() &&
1496 options.kerberos_authentication) {
1497 debug("Kerberos Authentication disabled, only available for IPv4.");
1498 options.kerberos_authentication = 0;
1499 }
1500#endif /* KRB4 && !KRB5 */
f2fd21a2 1501#if defined(AFS) || defined(AFS_KRB5)
3c0ef626 1502 /* If machine has AFS, set process authentication group. */
1503 if (k_hasafs()) {
1504 k_setpag();
1505 k_unlog();
1506 }
f2fd21a2 1507#endif /* AFS || AFS_KRB5 */
3c0ef626 1508
1509 packet_set_nonblocking();
1510
2980ea68 1511 if (use_privsep)
1512 if ((authctxt = privsep_preauth()) != NULL)
1513 goto authenticated;
1514
3c0ef626 1515 /* perform the key exchange */
1516 /* authenticate user and start session */
1517 if (compat20) {
1518 do_ssh2_kex();
2980ea68 1519 authctxt = do_authentication2();
3c0ef626 1520 } else {
1521 do_ssh1_kex();
2980ea68 1522 authctxt = do_authentication();
1523 }
1524 /*
1525 * If we use privilege separation, the unprivileged child transfers
1526 * the current keystate and exits
1527 */
1528 if (use_privsep) {
1529 mm_send_keystate(pmonitor);
1530 exit(0);
3c0ef626 1531 }
2980ea68 1532
1533 authenticated:
1534 /*
1535 * In privilege separation, we fork another child and prepare
1536 * file descriptor passing.
1537 */
1538 if (use_privsep) {
1539 privsep_postauth(authctxt);
1540 /* the monitor process [priv] will not return */
1541 if (!compat20)
1542 destroy_sensitive_data();
1543 }
1544
1545 /* Perform session preparation. */
1546 do_authenticated(authctxt);
1547
3c0ef626 1548 /* The connection has been terminated. */
1549 verbose("Closing connection to %.100s", remote_ip);
1550
1551#ifdef USE_PAM
1552 finish_pam();
1553#endif /* USE_PAM */
1554
1555 packet_close();
2980ea68 1556
1557 if (use_privsep)
1558 mm_terminate();
1559
3c0ef626 1560 exit(0);
1561}
1562
2980ea68 1563/*
1564 * Decrypt session_key_int using our private server key and private host key
1565 * (key with larger modulus first).
1566 */
1567int
1568ssh1_session_key(BIGNUM *session_key_int)
1569{
1570 int rsafail = 0;
1571
1572 if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1573 /* Server key has bigger modulus. */
1574 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1575 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1576 fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1577 get_remote_ipaddr(),
1578 BN_num_bits(sensitive_data.server_key->rsa->n),
1579 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1580 SSH_KEY_BITS_RESERVED);
1581 }
1582 if (rsa_private_decrypt(session_key_int, session_key_int,
1583 sensitive_data.server_key->rsa) <= 0)
1584 rsafail++;
1585 if (rsa_private_decrypt(session_key_int, session_key_int,
1586 sensitive_data.ssh1_host_key->rsa) <= 0)
1587 rsafail++;
1588 } else {
1589 /* Host key has bigger modulus (or they are equal). */
1590 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1591 BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1592 fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1593 get_remote_ipaddr(),
1594 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1595 BN_num_bits(sensitive_data.server_key->rsa->n),
1596 SSH_KEY_BITS_RESERVED);
1597 }
1598 if (rsa_private_decrypt(session_key_int, session_key_int,
1599 sensitive_data.ssh1_host_key->rsa) < 0)
1600 rsafail++;
1601 if (rsa_private_decrypt(session_key_int, session_key_int,
1602 sensitive_data.server_key->rsa) < 0)
1603 rsafail++;
1604 }
1605 return (rsafail);
1606}
3c0ef626 1607/*
1608 * SSH1 key exchange
1609 */
1610static void
1611do_ssh1_kex(void)
1612{
1613 int i, len;
3c0ef626 1614 int rsafail = 0;
1615 BIGNUM *session_key_int;
1616 u_char session_key[SSH_SESSION_KEY_LENGTH];
1617 u_char cookie[8];
1618 u_int cipher_type, auth_mask, protocol_flags;
e54b3d7c 1619 u_int32_t rnd = 0;
3c0ef626 1620
1621 /*
1622 * Generate check bytes that the client must send back in the user
1623 * packet in order for it to be accepted; this is used to defy ip
1624 * spoofing attacks. Note that this only works against somebody
1625 * doing IP spoofing from a remote machine; any machine on the local
1626 * network can still see outgoing packets and catch the random
1627 * cookie. This only affects rhosts authentication, and this is one
1628 * of the reasons why it is inherently insecure.
1629 */
1630 for (i = 0; i < 8; i++) {
1631 if (i % 4 == 0)
e54b3d7c 1632 rnd = arc4random();
1633 cookie[i] = rnd & 0xff;
1634 rnd >>= 8;
3c0ef626 1635 }
1636
1637 /*
1638 * Send our public key. We include in the packet 64 bits of random
1639 * data that must be matched in the reply in order to prevent IP
1640 * spoofing.
1641 */
1642 packet_start(SSH_SMSG_PUBLIC_KEY);
1643 for (i = 0; i < 8; i++)
1644 packet_put_char(cookie[i]);
1645
1646 /* Store our public server RSA key. */
1647 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1648 packet_put_bignum(sensitive_data.server_key->rsa->e);
1649 packet_put_bignum(sensitive_data.server_key->rsa->n);
1650
1651 /* Store our public host RSA key. */
1652 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1653 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1654 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1655
1656 /* Put protocol flags. */
1657 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1658
1659 /* Declare which ciphers we support. */
1660 packet_put_int(cipher_mask_ssh1(0));
1661
1662 /* Declare supported authentication types. */
1663 auth_mask = 0;
1664 if (options.rhosts_authentication)
1665 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1666 if (options.rhosts_rsa_authentication)
1667 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1668 if (options.rsa_authentication)
1669 auth_mask |= 1 << SSH_AUTH_RSA;
1670#if defined(KRB4) || defined(KRB5)
1671 if (options.kerberos_authentication)
1672 auth_mask |= 1 << SSH_AUTH_KERBEROS;
1673#endif
1674#if defined(AFS) || defined(KRB5)
1675 if (options.kerberos_tgt_passing)
1676 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1677#endif
1678#ifdef AFS
1679 if (options.afs_token_passing)
1680 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1681#endif
0b582e46 1682#ifdef GSSAPI
ff2d7a98 1683 if (options.gss_authentication)
1684 auth_mask |= 1 << SSH_AUTH_GSSAPI;
0b582e46 1685#endif
ff2d7a98 1686 if (options.challenge_response_authentication == 1)
1687 auth_mask |= 1 << SSH_AUTH_TIS;
3c0ef626 1688 if (options.password_authentication)
1689 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1690 packet_put_int(auth_mask);
1691
1692 /* Send the packet and wait for it to be sent. */
1693 packet_send();
1694 packet_write_wait();
1695
1696 debug("Sent %d bit server key and %d bit host key.",
1697 BN_num_bits(sensitive_data.server_key->rsa->n),
1698 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1699
1700 /* Read clients reply (cipher type and session key). */
1e608e42 1701 packet_read_expect(SSH_CMSG_SESSION_KEY);
3c0ef626 1702
1703 /* Get cipher type and check whether we accept this. */
1704 cipher_type = packet_get_char();
1705
1706 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1707 packet_disconnect("Warning: client selects unsupported cipher.");
1708
1709 /* Get check bytes from the packet. These must match those we
1710 sent earlier with the public key packet. */
1711 for (i = 0; i < 8; i++)
1712 if (cookie[i] != packet_get_char())
1713 packet_disconnect("IP Spoofing check bytes do not match.");
1714
1715 debug("Encryption type: %.200s", cipher_name(cipher_type));
1716
1717 /* Get the encrypted integer. */
1e608e42 1718 if ((session_key_int = BN_new()) == NULL)
1719 fatal("do_ssh1_kex: BN_new failed");
1720 packet_get_bignum(session_key_int);
3c0ef626 1721
1722 protocol_flags = packet_get_int();
1723 packet_set_protocol_flags(protocol_flags);
1e608e42 1724 packet_check_eom();
3c0ef626 1725
2980ea68 1726 /* Decrypt session_key_int using host/server keys */
1727 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
1728
3c0ef626 1729 /*
1730 * Extract session key from the decrypted integer. The key is in the
1731 * least significant 256 bits of the integer; the first byte of the
1732 * key is in the highest bits.
1733 */
1734 if (!rsafail) {
1735 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1736 len = BN_num_bytes(session_key_int);
1737 if (len < 0 || len > sizeof(session_key)) {
1738 error("do_connection: bad session key len from %s: "
1739 "session_key_int %d > sizeof(session_key) %lu",
1740 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1741 rsafail++;
1742 } else {
1743 memset(session_key, 0, sizeof(session_key));
1744 BN_bn2bin(session_key_int,
1745 session_key + sizeof(session_key) - len);
1746
1747 compute_session_id(session_id, cookie,
1748 sensitive_data.ssh1_host_key->rsa->n,
1749 sensitive_data.server_key->rsa->n);
1750 /*
1751 * Xor the first 16 bytes of the session key with the
1752 * session id.
1753 */
1754 for (i = 0; i < 16; i++)
1755 session_key[i] ^= session_id[i];
1756 }
1757 }
1758 if (rsafail) {
1759 int bytes = BN_num_bytes(session_key_int);
1e608e42 1760 u_char *buf = xmalloc(bytes);
3c0ef626 1761 MD5_CTX md;
1762
1763 log("do_connection: generating a fake encryption key");
1764 BN_bn2bin(session_key_int, buf);
1765 MD5_Init(&md);
1766 MD5_Update(&md, buf, bytes);
1767 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1768 MD5_Final(session_key, &md);
1769 MD5_Init(&md);
1770 MD5_Update(&md, session_key, 16);
1771 MD5_Update(&md, buf, bytes);
1772 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1773 MD5_Final(session_key + 16, &md);
1774 memset(buf, 0, bytes);
1775 xfree(buf);
1776 for (i = 0; i < 16; i++)
1777 session_id[i] = session_key[i] ^ session_key[i + 16];
1778 }
0b582e46 1779
0b582e46 1780#ifdef GSSAPI
1781 /*
1782 * Before we destroy the host and server keys, hash them so we can
1783 * send the hash over to the client via a secure channel so that it
1784 * can verify them.
1785 */
1786 {
1787 MD5_CTX md5context;
1788 Buffer buf;
1789 unsigned char *data;
1790 unsigned int data_len;
ff2d7a98 1791 extern unsigned char ssh1_key_digest[16]; /* in gss-genr.c */
0b582e46 1792
1793
1794 debug("Calculating MD5 hash of server and host keys...");
1795
1796 /* Write all the keys to a temporary buffer */
1797 buffer_init(&buf);
1798
1799 /* Server key */
1800 buffer_put_bignum(&buf, sensitive_data.server_key->rsa->e);
1801 buffer_put_bignum(&buf, sensitive_data.server_key->rsa->n);
1802
1803 /* Host key */
1804 buffer_put_bignum(&buf, sensitive_data.ssh1_host_key->rsa->e);
1805 buffer_put_bignum(&buf, sensitive_data.ssh1_host_key->rsa->n);
1806
1807 /* Get the resulting data */
1808 data = (unsigned char *) buffer_ptr(&buf);
1809 data_len = buffer_len(&buf);
1810
1811 /* And hash it */
1812 MD5_Init(&md5context);
1813 MD5_Update(&md5context, data, data_len);
c3f0c567 1814 MD5_Final(ssh1_key_digest, &md5context);
0b582e46 1815
1816 /* Clean up */
1817 buffer_clear(&buf);
1818 buffer_free(&buf);
1819 }
1820#endif /* GSSAPI */
0b582e46 1821
2980ea68 1822 /* Destroy the private and public keys. No longer. */
3c0ef626 1823 destroy_sensitive_data();
1824
2980ea68 1825 if (use_privsep)
1826 mm_ssh1_session_id(session_id);
1827
3c0ef626 1828 /* Destroy the decrypted integer. It is no longer needed. */
1829 BN_clear_free(session_key_int);
1830
1831 /* Set the session key. From this on all communications will be encrypted. */
1832 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1833
1834 /* Destroy our copy of the session key. It is no longer needed. */
1835 memset(session_key, 0, sizeof(session_key));
1836
1837 debug("Received session key; encryption turned on.");
1838
ff2d7a98 1839 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
3c0ef626 1840 packet_start(SSH_SMSG_SUCCESS);
1841 packet_send();
1842 packet_write_wait();
1843}
1844
1845/*
1846 * SSH2 key exchange: diffie-hellman-group1-sha1
1847 */
1848static void
1849do_ssh2_kex(void)
1850{
1851 Kex *kex;
1852
1853 if (options.ciphers != NULL) {
1854 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1855 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1856 }
1857 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1858 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1859 myproposal[PROPOSAL_ENC_ALGS_STOC] =
1860 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1861
1862 if (options.macs != NULL) {
1863 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1864 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1865 }
ff2d7a98 1866 if (!options.compression) {
1867 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
1868 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
1869 }
3c0ef626 1870 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1871
5598e598 1872#ifdef GSSAPI
1873 {
1874 char *orig;
1875 char *gss = NULL;
1876 char *newstr = NULL;
1877 orig = myproposal[PROPOSAL_KEX_ALGS];
1878
1879 /* If we don't have a host key, then all of the algorithms
1880 * currently in myproposal are useless */
1881 if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])==0)
1882 orig= NULL;
1883
1884 if (options.gss_keyex)
1885 gss = ssh_gssapi_mechanisms(1,NULL);
1886 else
1887 gss = NULL;
1888
1889 if (gss && orig) {
1890 int len = strlen(orig) + strlen(gss) +2;
1891 newstr=xmalloc(len);
1892 snprintf(newstr,len,"%s,%s",gss,orig);
1893 } else if (gss) {
1894 newstr=gss;
1895 } else if (orig) {
1896 newstr=orig;
1897 }
1898 /* If we've got GSSAPI mechanisms, then we've also got the 'null'
1899 host key algorithm, but we're not allowed to advertise it, unless
1900 its the only host key algorithm we're supporting */
1901 if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0) {
1902 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]="null";
1903 }
1904 if (newstr)
1905 myproposal[PROPOSAL_KEX_ALGS]=newstr;
1906 else
1907 fatal("No supported key exchange algorithms");
1908 }
1909#endif
1910
3c0ef626 1911 /* start key exchange */
1912 kex = kex_setup(myproposal);
1913 kex->server = 1;
1914 kex->client_version_string=client_version_string;
1915 kex->server_version_string=server_version_string;
1916 kex->load_host_key=&get_hostkey_by_type;
2980ea68 1917 kex->host_key_index=&get_hostkey_index;
3c0ef626 1918
1919 xxx_kex = kex;
1920
1921 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1922
1923 session_id2 = kex->session_id;
1924 session_id2_len = kex->session_id_len;
1925
1926#ifdef DEBUG_KEXDH
1927 /* send 1st encrypted/maced/compressed message */
1928 packet_start(SSH2_MSG_IGNORE);
1929 packet_put_cstring("markus");
1930 packet_send();
1931 packet_write_wait();
1932#endif
1933 debug("KEX done");
1934}
This page took 0.344781 seconds and 5 git commands to generate.