]> andersk Git - gssapi-openssh.git/blame - openssh/sshd.c
added my pgp key
[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"
1c14df9e 45RCSID("$OpenBSD: sshd.c,v 1.263 2003/02/16 17:09:57 markus 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 */
1c14df9e 214int use_privsep;
215struct monitor *pmonitor;
2980ea68 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
1c14df9e 841 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
3c0ef626 842 saved_argc = ac;
843 saved_argv = av;
1c14df9e 844 saved_argv = xmalloc(sizeof(*saved_argv) * ac);
845 for (i = 0; i < ac; i++)
846 saved_argv[i] = xstrdup(av[i]);
847
848#ifndef HAVE_SETPROCTITLE
849 /* Prepare for later setproctitle emulation */
850 compat_init_setproctitle(ac, av);
851#endif
3c0ef626 852
853 /* Initialize configuration options to their default values. */
854 initialize_server_options(&options);
855
856 /* Parse command-line arguments. */
1e608e42 857 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:o:dDeiqtQ46")) != -1) {
3c0ef626 858 switch (opt) {
859 case '4':
860 IPv4or6 = AF_INET;
861 break;
862 case '6':
863 IPv4or6 = AF_INET6;
864 break;
865 case 'f':
866 config_file_name = optarg;
867 break;
868 case 'd':
869 if (0 == debug_flag) {
870 debug_flag = 1;
871 options.log_level = SYSLOG_LEVEL_DEBUG1;
872 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
873 options.log_level++;
874 } else {
875 fprintf(stderr, "Too high debugging level.\n");
876 exit(1);
877 }
878 break;
879 case 'D':
880 no_daemon_flag = 1;
881 break;
882 case 'e':
883 log_stderr = 1;
884 break;
885 case 'i':
886 inetd_flag = 1;
887 break;
888 case 'Q':
889 /* ignored */
890 break;
891 case 'q':
892 options.log_level = SYSLOG_LEVEL_QUIET;
893 break;
894 case 'b':
895 options.server_key_bits = atoi(optarg);
896 break;
897 case 'p':
898 options.ports_from_cmdline = 1;
899 if (options.num_ports >= MAX_PORTS) {
900 fprintf(stderr, "too many ports.\n");
901 exit(1);
902 }
903 options.ports[options.num_ports++] = a2port(optarg);
904 if (options.ports[options.num_ports-1] == 0) {
905 fprintf(stderr, "Bad port number.\n");
906 exit(1);
907 }
908 break;
909 case 'g':
910 if ((options.login_grace_time = convtime(optarg)) == -1) {
911 fprintf(stderr, "Invalid login grace time.\n");
912 exit(1);
913 }
914 break;
915 case 'k':
916 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
917 fprintf(stderr, "Invalid key regeneration interval.\n");
918 exit(1);
919 }
920 break;
921 case 'h':
922 if (options.num_host_key_files >= MAX_HOSTKEYS) {
923 fprintf(stderr, "too many host keys.\n");
924 exit(1);
925 }
926 options.host_key_files[options.num_host_key_files++] = optarg;
927 break;
928 case 'V':
929 client_version_string = optarg;
930 /* only makes sense with inetd_flag, i.e. no listen() */
931 inetd_flag = 1;
932 break;
933 case 't':
934 test_flag = 1;
935 break;
936 case 'u':
937 utmp_len = atoi(optarg);
e54b3d7c 938 if (utmp_len > MAXHOSTNAMELEN) {
939 fprintf(stderr, "Invalid utmp length.\n");
940 exit(1);
941 }
3c0ef626 942 break;
1e608e42 943 case 'o':
944 if (process_server_config_line(&options, optarg,
945 "command-line", 0) != 0)
946 exit(1);
947 break;
3c0ef626 948 case '?':
949 default:
1e608e42 950 usage();
951 break;
3c0ef626 952 }
953 }
954 SSLeay_add_all_algorithms();
955 channel_set_af(IPv4or6);
956
957 /*
958 * Force logging to stderr until we have loaded the private host
959 * key (unless started from inetd)
960 */
961 log_init(__progname,
1e608e42 962 options.log_level == SYSLOG_LEVEL_NOT_SET ?
963 SYSLOG_LEVEL_INFO : options.log_level,
964 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
965 SYSLOG_FACILITY_AUTH : options.log_facility,
1c14df9e 966 log_stderr || !inetd_flag);
3c0ef626 967
e54b3d7c 968#ifdef _UNICOS
3c0ef626 969 /* Cray can define user privs drop all prives now!
970 * Not needed on PRIV_SU systems!
971 */
972 drop_cray_privs();
973#endif
974
975 seed_rng();
976
977 /* Read server configuration options from the configuration file. */
978 read_server_config(&options, config_file_name);
979
980 /* Fill in default values for those options not explicitly set. */
981 fill_default_server_options(&options);
982
983 /* Check that there are no remaining arguments. */
984 if (optind < ac) {
985 fprintf(stderr, "Extra argument %s.\n", av[optind]);
986 exit(1);
987 }
988
989 debug("sshd version %.100s", SSH_VERSION);
990
991 /* load private host keys */
e54b3d7c 992 sensitive_data.host_keys = xmalloc(options.num_host_key_files *
993 sizeof(Key *));
1e608e42 994 for (i = 0; i < options.num_host_key_files; i++)
3c0ef626 995 sensitive_data.host_keys[i] = NULL;
996 sensitive_data.server_key = NULL;
997 sensitive_data.ssh1_host_key = NULL;
998 sensitive_data.have_ssh1_key = 0;
999 sensitive_data.have_ssh2_key = 0;
1000
1e608e42 1001 for (i = 0; i < options.num_host_key_files; i++) {
3c0ef626 1002 key = key_load_private(options.host_key_files[i], "", NULL);
1003 sensitive_data.host_keys[i] = key;
1004 if (key == NULL) {
1005 error("Could not load host key: %s",
1006 options.host_key_files[i]);
1007 sensitive_data.host_keys[i] = NULL;
1008 continue;
1009 }
1e608e42 1010 switch (key->type) {
3c0ef626 1011 case KEY_RSA1:
1012 sensitive_data.ssh1_host_key = key;
1013 sensitive_data.have_ssh1_key = 1;
1014 break;
1015 case KEY_RSA:
1016 case KEY_DSA:
1017 sensitive_data.have_ssh2_key = 1;
1018 break;
1019 }
1020 debug("private host key: #%d type %d %s", i, key->type,
1021 key_type(key));
1022 }
1023 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1024 log("Disabling protocol version 1. Could not load host key");
1025 options.protocol &= ~SSH_PROTO_1;
1026 }
5598e598 1027#ifndef GSSAPI
1028 /* The GSSAPI key exchange can run without a host key */
3c0ef626 1029 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1030 log("Disabling protocol version 2. Could not load host key");
1031 options.protocol &= ~SSH_PROTO_2;
1032 }
5598e598 1033#endif
3c0ef626 1034 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1035 log("sshd: no hostkeys available -- exiting.");
1036 exit(1);
1037 }
1038
1039 /* Check certain values for sanity. */
1040 if (options.protocol & SSH_PROTO_1) {
1041 if (options.server_key_bits < 512 ||
1042 options.server_key_bits > 32768) {
1043 fprintf(stderr, "Bad server key size.\n");
1044 exit(1);
1045 }
1046 /*
1047 * Check that server and host key lengths differ sufficiently. This
1048 * is necessary to make double encryption work with rsaref. Oh, I
1049 * hate software patents. I dont know if this can go? Niels
1050 */
1051 if (options.server_key_bits >
ff2d7a98 1052 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1053 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1054 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1055 SSH_KEY_BITS_RESERVED) {
3c0ef626 1056 options.server_key_bits =
ff2d7a98 1057 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1058 SSH_KEY_BITS_RESERVED;
3c0ef626 1059 debug("Forcing server key to %d bits to make it differ from host key.",
1060 options.server_key_bits);
1061 }
1062 }
1063
ff2d7a98 1064 if (use_privsep) {
1065 struct passwd *pw;
1066 struct stat st;
1067
1068 if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
1069 fatal("Privilege separation user %s does not exist",
1070 SSH_PRIVSEP_USER);
1071 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1072 (S_ISDIR(st.st_mode) == 0))
1073 fatal("Missing privilege separation directory: %s",
1074 _PATH_PRIVSEP_CHROOT_DIR);
e54b3d7c 1075
1076#ifdef HAVE_CYGWIN
1077 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1078 (st.st_uid != getuid () ||
1079 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1080#else
ff2d7a98 1081 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
e54b3d7c 1082#endif
1c14df9e 1083 fatal("%s must be owned by root and not group or "
1084 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
ff2d7a98 1085 }
1086
3c0ef626 1087 /* Configuration looks good, so exit if in test mode. */
1088 if (test_flag)
1089 exit(0);
1090
2980ea68 1091 /*
1092 * Clear out any supplemental groups we may have inherited. This
1093 * prevents inadvertent creation of files with bad modes (in the
1094 * portable version at least, it's certainly possible for PAM
1095 * to create a file, and we can't control the code in every
1096 * module which might be used).
1097 */
1098 if (setgroups(0, NULL) < 0)
1099 debug("setgroups() failed: %.200s", strerror(errno));
3c0ef626 1100
1101 /* Initialize the log (it is reinitialized below in case we forked). */
1102 if (debug_flag && !inetd_flag)
1103 log_stderr = 1;
1104 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1105
1106 /*
1107 * If not in debugging mode, and not started from inetd, disconnect
1108 * from the controlling terminal, and fork. The original process
1109 * exits.
1110 */
1111 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1112#ifdef TIOCNOTTY
1113 int fd;
1114#endif /* TIOCNOTTY */
1115 if (daemon(0, 0) < 0)
1116 fatal("daemon() failed: %.200s", strerror(errno));
1117
1118 /* Disconnect from the controlling tty. */
1119#ifdef TIOCNOTTY
1120 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1121 if (fd >= 0) {
1122 (void) ioctl(fd, TIOCNOTTY, NULL);
1123 close(fd);
1124 }
1125#endif /* TIOCNOTTY */
1126 }
1127 /* Reinitialize the log (because of the fork above). */
1128 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1129
1130 /* Initialize the random number generator. */
1131 arc4random_stir();
1132
1133 /* Chdir to the root directory so that the current disk can be
1134 unmounted if desired. */
1135 chdir("/");
1e608e42 1136
3c0ef626 1137 /* ignore SIGPIPE */
1138 signal(SIGPIPE, SIG_IGN);
1139
1140 /* Start listening for a socket, unless started from inetd. */
1141 if (inetd_flag) {
1142 int s1;
1143 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
1144 dup(s1);
1145 sock_in = dup(0);
1146 sock_out = dup(1);
1147 startup_pipe = -1;
1148 /*
1149 * We intentionally do not close the descriptors 0, 1, and 2
1150 * as our code for setting the descriptors won\'t work if
1151 * ttyfd happens to be one of those.
1152 */
1153 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
1154 if (options.protocol & SSH_PROTO_1)
1155 generate_ephemeral_server_key();
1156 } else {
1157 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1158 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1159 continue;
1160 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1161 fatal("Too many listen sockets. "
1162 "Enlarge MAX_LISTEN_SOCKS");
1163 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
1164 ntop, sizeof(ntop), strport, sizeof(strport),
1165 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1166 error("getnameinfo failed");
1167 continue;
1168 }
1169 /* Create socket for listening. */
1170 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
1171 if (listen_sock < 0) {
1172 /* kernel may not support ipv6 */
1173 verbose("socket: %.100s", strerror(errno));
1174 continue;
1175 }
1176 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
1177 error("listen_sock O_NONBLOCK: %s", strerror(errno));
1178 close(listen_sock);
1179 continue;
1180 }
1181 /*
e54b3d7c 1182 * Set socket options.
1183 * Allow local port reuse in TIME_WAIT.
3c0ef626 1184 */
e54b3d7c 1185 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1186 &on, sizeof(on)) == -1)
1187 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
3c0ef626 1188
1189 debug("Bind to port %s on %s.", strport, ntop);
1190
1191 /* Bind the socket to the desired port. */
1192 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1193 if (!ai->ai_next)
1194 error("Bind to port %s on %s failed: %.200s.",
1195 strport, ntop, strerror(errno));
1196 close(listen_sock);
1197 continue;
1198 }
1199 listen_socks[num_listen_socks] = listen_sock;
1200 num_listen_socks++;
1201
1202 /* Start listening on the port. */
1203 log("Server listening on %s port %s.", ntop, strport);
1204 if (listen(listen_sock, 5) < 0)
1205 fatal("listen: %.100s", strerror(errno));
1206
1207 }
1208 freeaddrinfo(options.listen_addrs);
1209
1210 if (!num_listen_socks)
1211 fatal("Cannot bind any address.");
1212
1213 if (options.protocol & SSH_PROTO_1)
1214 generate_ephemeral_server_key();
1215
1216 /*
1217 * Arrange to restart on SIGHUP. The handler needs
1218 * listen_sock.
1219 */
1220 signal(SIGHUP, sighup_handler);
1221
1222 signal(SIGTERM, sigterm_handler);
1223 signal(SIGQUIT, sigterm_handler);
1224
1225 /* Arrange SIGCHLD to be caught. */
1226 signal(SIGCHLD, main_sigchld_handler);
1227
1228 /* Write out the pid file after the sigterm handler is setup */
1229 if (!debug_flag) {
1230 /*
1231 * Record our pid in /var/run/sshd.pid to make it
1232 * easier to kill the correct sshd. We don't want to
1233 * do this before the bind above because the bind will
1234 * fail if there already is a daemon, and this will
1235 * overwrite any old pid in the file.
1236 */
1237 f = fopen(options.pid_file, "wb");
1238 if (f) {
ff2d7a98 1239 fprintf(f, "%ld\n", (long) getpid());
3c0ef626 1240 fclose(f);
1241 }
1242 }
1243
1244 /* setup fd set for listen */
1245 fdset = NULL;
1246 maxfd = 0;
1247 for (i = 0; i < num_listen_socks; i++)
1248 if (listen_socks[i] > maxfd)
1249 maxfd = listen_socks[i];
1250 /* pipes connected to unauthenticated childs */
1251 startup_pipes = xmalloc(options.max_startups * sizeof(int));
1252 for (i = 0; i < options.max_startups; i++)
1253 startup_pipes[i] = -1;
1254
1255 /*
1256 * Stay listening for connections until the system crashes or
1257 * the daemon is killed with a signal.
1258 */
1259 for (;;) {
1260 if (received_sighup)
1261 sighup_restart();
1262 if (fdset != NULL)
1263 xfree(fdset);
1264 fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1265 fdset = (fd_set *)xmalloc(fdsetsz);
1266 memset(fdset, 0, fdsetsz);
1267
1268 for (i = 0; i < num_listen_socks; i++)
1269 FD_SET(listen_socks[i], fdset);
1270 for (i = 0; i < options.max_startups; i++)
1271 if (startup_pipes[i] != -1)
1272 FD_SET(startup_pipes[i], fdset);
1273
1274 /* Wait in select until there is a connection. */
1275 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1276 if (ret < 0 && errno != EINTR)
1277 error("select: %.100s", strerror(errno));
1278 if (received_sigterm) {
1279 log("Received signal %d; terminating.",
1e608e42 1280 (int) received_sigterm);
3c0ef626 1281 close_listen_socks();
1282 unlink(options.pid_file);
1283 exit(255);
1284 }
1285 if (key_used && key_do_regen) {
1286 generate_ephemeral_server_key();
1287 key_used = 0;
1288 key_do_regen = 0;
1289 }
1290 if (ret < 0)
1291 continue;
1292
1293 for (i = 0; i < options.max_startups; i++)
1294 if (startup_pipes[i] != -1 &&
1295 FD_ISSET(startup_pipes[i], fdset)) {
1296 /*
1297 * the read end of the pipe is ready
1298 * if the child has closed the pipe
1299 * after successful authentication
1300 * or if the child has died
1301 */
1302 close(startup_pipes[i]);
1303 startup_pipes[i] = -1;
1304 startups--;
1305 }
1306 for (i = 0; i < num_listen_socks; i++) {
1307 if (!FD_ISSET(listen_socks[i], fdset))
1308 continue;
1309 fromlen = sizeof(from);
1310 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
1311 &fromlen);
1312 if (newsock < 0) {
1313 if (errno != EINTR && errno != EWOULDBLOCK)
1314 error("accept: %.100s", strerror(errno));
1315 continue;
1316 }
1317 if (fcntl(newsock, F_SETFL, 0) < 0) {
1318 error("newsock del O_NONBLOCK: %s", strerror(errno));
1e608e42 1319 close(newsock);
3c0ef626 1320 continue;
1321 }
1322 if (drop_connection(startups) == 1) {
1323 debug("drop connection #%d", startups);
1324 close(newsock);
1325 continue;
1326 }
1327 if (pipe(startup_p) == -1) {
1328 close(newsock);
1329 continue;
1330 }
1331
1332 for (j = 0; j < options.max_startups; j++)
1333 if (startup_pipes[j] == -1) {
1334 startup_pipes[j] = startup_p[0];
1335 if (maxfd < startup_p[0])
1336 maxfd = startup_p[0];
1337 startups++;
1338 break;
1339 }
1340
1341 /*
1342 * Got connection. Fork a child to handle it, unless
1343 * we are in debugging mode.
1344 */
1345 if (debug_flag) {
1346 /*
1347 * In debugging mode. Close the listening
1348 * socket, and start processing the
1349 * connection without forking.
1350 */
1351 debug("Server will not fork when running in debugging mode.");
1352 close_listen_socks();
1353 sock_in = newsock;
1354 sock_out = newsock;
1355 startup_pipe = -1;
1356 pid = getpid();
1357 break;
1358 } else {
1359 /*
1360 * Normal production daemon. Fork, and have
1361 * the child process the connection. The
1362 * parent continues listening.
1363 */
1364 if ((pid = fork()) == 0) {
1365 /*
1366 * Child. Close the listening and max_startup
1367 * sockets. Start using the accepted socket.
1368 * Reinitialize logging (since our pid has
1369 * changed). We break out of the loop to handle
1370 * the connection.
1371 */
1372 startup_pipe = startup_p[1];
1e608e42 1373 close_startup_pipes();
3c0ef626 1374 close_listen_socks();
1375 sock_in = newsock;
1376 sock_out = newsock;
1377 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1378 break;
1379 }
1380 }
1381
1382 /* Parent. Stay in the loop. */
1383 if (pid < 0)
1384 error("fork: %.100s", strerror(errno));
1385 else
ff2d7a98 1386 debug("Forked child %ld.", (long)pid);
3c0ef626 1387
1388 close(startup_p[1]);
1389
1390 /* Mark that the key has been used (it was "given" to the child). */
1391 if ((options.protocol & SSH_PROTO_1) &&
1392 key_used == 0) {
1393 /* Schedule server key regeneration alarm. */
1394 signal(SIGALRM, key_regeneration_alarm);
1395 alarm(options.key_regeneration_time);
1396 key_used = 1;
1397 }
1398
1399 arc4random_stir();
1400
1401 /* Close the new socket (the child is now taking care of it). */
1402 close(newsock);
1403 }
1404 /* child process check (or debug mode) */
1405 if (num_listen_socks < 0)
1406 break;
1407 }
1408 }
1409
1410 /* This is the child processing a new connection. */
1411
2980ea68 1412 /*
1413 * Create a new session and process group since the 4.4BSD
1414 * setlogin() affects the entire process group. We don't
1415 * want the child to be able to affect the parent.
1416 */
1c14df9e 1417#if !defined(STREAMS_PUSH_ACQUIRES_CTTY)
1418 /*
1419 * If setsid is called on Solaris, sshd will acquire the controlling
1420 * terminal while pushing STREAMS modules. This will prevent the
1421 * shell from acquiring it later.
1422 */
ff2d7a98 1423 if (!debug_flag && !inetd_flag && setsid() < 0)
2980ea68 1424 error("setsid: %.100s", strerror(errno));
1425#endif
1426
3c0ef626 1427 /*
1428 * Disable the key regeneration alarm. We will not regenerate the
1429 * key since we are no longer in a position to give it to anyone. We
1430 * will not restart on SIGHUP since it no longer makes sense.
1431 */
1432 alarm(0);
1433 signal(SIGALRM, SIG_DFL);
1434 signal(SIGHUP, SIG_DFL);
1435 signal(SIGTERM, SIG_DFL);
1436 signal(SIGQUIT, SIG_DFL);
1437 signal(SIGCHLD, SIG_DFL);
1438 signal(SIGINT, SIG_DFL);
1439
3c0ef626 1440 /* Set keepalives if requested. */
1441 if (options.keepalives &&
1e608e42 1442 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on,
3c0ef626 1443 sizeof(on)) < 0)
1444 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1445
1446 /*
1447 * Register our connection. This turns encryption off because we do
1448 * not have a key.
1449 */
1450 packet_set_connection(sock_in, sock_out);
1451
1452 remote_port = get_remote_port();
1453 remote_ip = get_remote_ipaddr();
1454
1455#ifdef LIBWRAP
1456 /* Check whether logins are denied from this host. */
1457 {
1458 struct request_info req;
1459
1460 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1461 fromhost(&req);
1462
1463 if (!hosts_access(&req)) {
1464 debug("Connection refused by tcp wrapper");
1465 refuse(&req);
1466 /* NOTREACHED */
1467 fatal("libwrap refuse returns");
1468 }
1469 }
1470#endif /* LIBWRAP */
1471
1472 /* Log the connection. */
1473 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1474
1475 /*
1476 * We don\'t want to listen forever unless the other side
1477 * successfully authenticates itself. So we set up an alarm which is
1478 * cleared after successful authentication. A limit of zero
1479 * indicates no limit. Note that we don\'t set the alarm in debugging
1480 * mode; it is just annoying to have the server exit just when you
1481 * are about to discover the bug.
1482 */
1483 signal(SIGALRM, grace_alarm_handler);
1484 if (!debug_flag)
1485 alarm(options.login_grace_time);
1486
1487 sshd_exchange_identification(sock_in, sock_out);
1488 /*
1489 * Check that the connection comes from a privileged port.
ff2d7a98 1490 * Rhosts-Authentication only makes sense from privileged
3c0ef626 1491 * programs. Of course, if the intruder has root access on his local
1492 * machine, he can connect from any port. So do not use these
1493 * authentication methods from machines that you do not trust.
1494 */
1e608e42 1495 if (options.rhosts_authentication &&
1496 (remote_port >= IPPORT_RESERVED ||
1497 remote_port < IPPORT_RESERVED / 2)) {
3c0ef626 1498 debug("Rhosts Authentication disabled, "
1499 "originating port %d not trusted.", remote_port);
1500 options.rhosts_authentication = 0;
1501 }
1502#if defined(KRB4) && !defined(KRB5)
1503 if (!packet_connection_is_ipv4() &&
1504 options.kerberos_authentication) {
1505 debug("Kerberos Authentication disabled, only available for IPv4.");
1506 options.kerberos_authentication = 0;
1507 }
1508#endif /* KRB4 && !KRB5 */
f2fd21a2 1509#if defined(AFS) || defined(AFS_KRB5)
3c0ef626 1510 /* If machine has AFS, set process authentication group. */
1511 if (k_hasafs()) {
1512 k_setpag();
1513 k_unlog();
1514 }
f2fd21a2 1515#endif /* AFS || AFS_KRB5 */
3c0ef626 1516
1517 packet_set_nonblocking();
1518
2980ea68 1519 if (use_privsep)
1520 if ((authctxt = privsep_preauth()) != NULL)
1521 goto authenticated;
1522
3c0ef626 1523 /* perform the key exchange */
1524 /* authenticate user and start session */
1525 if (compat20) {
1526 do_ssh2_kex();
2980ea68 1527 authctxt = do_authentication2();
3c0ef626 1528 } else {
1529 do_ssh1_kex();
2980ea68 1530 authctxt = do_authentication();
1531 }
1532 /*
1533 * If we use privilege separation, the unprivileged child transfers
1534 * the current keystate and exits
1535 */
1536 if (use_privsep) {
1537 mm_send_keystate(pmonitor);
1538 exit(0);
3c0ef626 1539 }
2980ea68 1540
1541 authenticated:
1542 /*
1543 * In privilege separation, we fork another child and prepare
1544 * file descriptor passing.
1545 */
1546 if (use_privsep) {
1547 privsep_postauth(authctxt);
1548 /* the monitor process [priv] will not return */
1549 if (!compat20)
1550 destroy_sensitive_data();
1551 }
1552
1553 /* Perform session preparation. */
1554 do_authenticated(authctxt);
1555
3c0ef626 1556 /* The connection has been terminated. */
1557 verbose("Closing connection to %.100s", remote_ip);
1558
1559#ifdef USE_PAM
1560 finish_pam();
1561#endif /* USE_PAM */
1562
1563 packet_close();
2980ea68 1564
1565 if (use_privsep)
1566 mm_terminate();
1567
3c0ef626 1568 exit(0);
1569}
1570
2980ea68 1571/*
1572 * Decrypt session_key_int using our private server key and private host key
1573 * (key with larger modulus first).
1574 */
1575int
1576ssh1_session_key(BIGNUM *session_key_int)
1577{
1578 int rsafail = 0;
1579
1580 if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1581 /* Server key has bigger modulus. */
1582 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1583 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1584 fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1585 get_remote_ipaddr(),
1586 BN_num_bits(sensitive_data.server_key->rsa->n),
1587 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1588 SSH_KEY_BITS_RESERVED);
1589 }
1590 if (rsa_private_decrypt(session_key_int, session_key_int,
1591 sensitive_data.server_key->rsa) <= 0)
1592 rsafail++;
1593 if (rsa_private_decrypt(session_key_int, session_key_int,
1594 sensitive_data.ssh1_host_key->rsa) <= 0)
1595 rsafail++;
1596 } else {
1597 /* Host key has bigger modulus (or they are equal). */
1598 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1599 BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1600 fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1601 get_remote_ipaddr(),
1602 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1603 BN_num_bits(sensitive_data.server_key->rsa->n),
1604 SSH_KEY_BITS_RESERVED);
1605 }
1606 if (rsa_private_decrypt(session_key_int, session_key_int,
1607 sensitive_data.ssh1_host_key->rsa) < 0)
1608 rsafail++;
1609 if (rsa_private_decrypt(session_key_int, session_key_int,
1610 sensitive_data.server_key->rsa) < 0)
1611 rsafail++;
1612 }
1613 return (rsafail);
1614}
3c0ef626 1615/*
1616 * SSH1 key exchange
1617 */
1618static void
1619do_ssh1_kex(void)
1620{
1621 int i, len;
3c0ef626 1622 int rsafail = 0;
1623 BIGNUM *session_key_int;
1624 u_char session_key[SSH_SESSION_KEY_LENGTH];
1625 u_char cookie[8];
1626 u_int cipher_type, auth_mask, protocol_flags;
e54b3d7c 1627 u_int32_t rnd = 0;
3c0ef626 1628
1629 /*
1630 * Generate check bytes that the client must send back in the user
1631 * packet in order for it to be accepted; this is used to defy ip
1632 * spoofing attacks. Note that this only works against somebody
1633 * doing IP spoofing from a remote machine; any machine on the local
1634 * network can still see outgoing packets and catch the random
1635 * cookie. This only affects rhosts authentication, and this is one
1636 * of the reasons why it is inherently insecure.
1637 */
1638 for (i = 0; i < 8; i++) {
1639 if (i % 4 == 0)
e54b3d7c 1640 rnd = arc4random();
1641 cookie[i] = rnd & 0xff;
1642 rnd >>= 8;
3c0ef626 1643 }
1644
1645 /*
1646 * Send our public key. We include in the packet 64 bits of random
1647 * data that must be matched in the reply in order to prevent IP
1648 * spoofing.
1649 */
1650 packet_start(SSH_SMSG_PUBLIC_KEY);
1651 for (i = 0; i < 8; i++)
1652 packet_put_char(cookie[i]);
1653
1654 /* Store our public server RSA key. */
1655 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1656 packet_put_bignum(sensitive_data.server_key->rsa->e);
1657 packet_put_bignum(sensitive_data.server_key->rsa->n);
1658
1659 /* Store our public host RSA key. */
1660 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1661 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1662 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1663
1664 /* Put protocol flags. */
1665 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1666
1667 /* Declare which ciphers we support. */
1668 packet_put_int(cipher_mask_ssh1(0));
1669
1670 /* Declare supported authentication types. */
1671 auth_mask = 0;
1672 if (options.rhosts_authentication)
1673 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1674 if (options.rhosts_rsa_authentication)
1675 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1676 if (options.rsa_authentication)
1677 auth_mask |= 1 << SSH_AUTH_RSA;
1678#if defined(KRB4) || defined(KRB5)
1679 if (options.kerberos_authentication)
1680 auth_mask |= 1 << SSH_AUTH_KERBEROS;
1681#endif
1682#if defined(AFS) || defined(KRB5)
1683 if (options.kerberos_tgt_passing)
1684 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1685#endif
1686#ifdef AFS
1687 if (options.afs_token_passing)
1688 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1689#endif
0b582e46 1690#ifdef GSSAPI
ff2d7a98 1691 if (options.gss_authentication)
1692 auth_mask |= 1 << SSH_AUTH_GSSAPI;
0b582e46 1693#endif
ff2d7a98 1694 if (options.challenge_response_authentication == 1)
1695 auth_mask |= 1 << SSH_AUTH_TIS;
3c0ef626 1696 if (options.password_authentication)
1697 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1698 packet_put_int(auth_mask);
1699
1700 /* Send the packet and wait for it to be sent. */
1701 packet_send();
1702 packet_write_wait();
1703
1704 debug("Sent %d bit server key and %d bit host key.",
1705 BN_num_bits(sensitive_data.server_key->rsa->n),
1706 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1707
1708 /* Read clients reply (cipher type and session key). */
1e608e42 1709 packet_read_expect(SSH_CMSG_SESSION_KEY);
3c0ef626 1710
1711 /* Get cipher type and check whether we accept this. */
1712 cipher_type = packet_get_char();
1713
1714 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1715 packet_disconnect("Warning: client selects unsupported cipher.");
1716
1717 /* Get check bytes from the packet. These must match those we
1718 sent earlier with the public key packet. */
1719 for (i = 0; i < 8; i++)
1720 if (cookie[i] != packet_get_char())
1721 packet_disconnect("IP Spoofing check bytes do not match.");
1722
1723 debug("Encryption type: %.200s", cipher_name(cipher_type));
1724
1725 /* Get the encrypted integer. */
1e608e42 1726 if ((session_key_int = BN_new()) == NULL)
1727 fatal("do_ssh1_kex: BN_new failed");
1728 packet_get_bignum(session_key_int);
3c0ef626 1729
1730 protocol_flags = packet_get_int();
1731 packet_set_protocol_flags(protocol_flags);
1e608e42 1732 packet_check_eom();
3c0ef626 1733
2980ea68 1734 /* Decrypt session_key_int using host/server keys */
1735 rsafail = PRIVSEP(ssh1_session_key(session_key_int));
1736
3c0ef626 1737 /*
1738 * Extract session key from the decrypted integer. The key is in the
1739 * least significant 256 bits of the integer; the first byte of the
1740 * key is in the highest bits.
1741 */
1742 if (!rsafail) {
1743 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1744 len = BN_num_bytes(session_key_int);
1745 if (len < 0 || len > sizeof(session_key)) {
1746 error("do_connection: bad session key len from %s: "
1747 "session_key_int %d > sizeof(session_key) %lu",
1748 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1749 rsafail++;
1750 } else {
1751 memset(session_key, 0, sizeof(session_key));
1752 BN_bn2bin(session_key_int,
1753 session_key + sizeof(session_key) - len);
1754
1755 compute_session_id(session_id, cookie,
1756 sensitive_data.ssh1_host_key->rsa->n,
1757 sensitive_data.server_key->rsa->n);
1758 /*
1759 * Xor the first 16 bytes of the session key with the
1760 * session id.
1761 */
1762 for (i = 0; i < 16; i++)
1763 session_key[i] ^= session_id[i];
1764 }
1765 }
1766 if (rsafail) {
1767 int bytes = BN_num_bytes(session_key_int);
1e608e42 1768 u_char *buf = xmalloc(bytes);
3c0ef626 1769 MD5_CTX md;
1770
1771 log("do_connection: generating a fake encryption key");
1772 BN_bn2bin(session_key_int, buf);
1773 MD5_Init(&md);
1774 MD5_Update(&md, buf, bytes);
1775 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1776 MD5_Final(session_key, &md);
1777 MD5_Init(&md);
1778 MD5_Update(&md, session_key, 16);
1779 MD5_Update(&md, buf, bytes);
1780 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1781 MD5_Final(session_key + 16, &md);
1782 memset(buf, 0, bytes);
1783 xfree(buf);
1784 for (i = 0; i < 16; i++)
1785 session_id[i] = session_key[i] ^ session_key[i + 16];
1786 }
0b582e46 1787
0b582e46 1788#ifdef GSSAPI
1789 /*
1790 * Before we destroy the host and server keys, hash them so we can
1791 * send the hash over to the client via a secure channel so that it
1792 * can verify them.
1793 */
1794 {
1795 MD5_CTX md5context;
1796 Buffer buf;
1797 unsigned char *data;
1798 unsigned int data_len;
88928908 1799 extern unsigned char ssh1_key_digest[16]; /* in auth2-gss.c */
0b582e46 1800
1801
1802 debug("Calculating MD5 hash of server and host keys...");
1803
1804 /* Write all the keys to a temporary buffer */
1805 buffer_init(&buf);
1806
1807 /* Server key */
1808 buffer_put_bignum(&buf, sensitive_data.server_key->rsa->e);
1809 buffer_put_bignum(&buf, sensitive_data.server_key->rsa->n);
1810
1811 /* Host key */
1812 buffer_put_bignum(&buf, sensitive_data.ssh1_host_key->rsa->e);
1813 buffer_put_bignum(&buf, sensitive_data.ssh1_host_key->rsa->n);
1814
1815 /* Get the resulting data */
1816 data = (unsigned char *) buffer_ptr(&buf);
1817 data_len = buffer_len(&buf);
1818
1819 /* And hash it */
1820 MD5_Init(&md5context);
1821 MD5_Update(&md5context, data, data_len);
c3f0c567 1822 MD5_Final(ssh1_key_digest, &md5context);
0b582e46 1823
1824 /* Clean up */
1825 buffer_clear(&buf);
1826 buffer_free(&buf);
1827 }
1828#endif /* GSSAPI */
0b582e46 1829
2980ea68 1830 /* Destroy the private and public keys. No longer. */
3c0ef626 1831 destroy_sensitive_data();
1832
2980ea68 1833 if (use_privsep)
1834 mm_ssh1_session_id(session_id);
1835
3c0ef626 1836 /* Destroy the decrypted integer. It is no longer needed. */
1837 BN_clear_free(session_key_int);
1838
1839 /* Set the session key. From this on all communications will be encrypted. */
1840 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1841
1842 /* Destroy our copy of the session key. It is no longer needed. */
1843 memset(session_key, 0, sizeof(session_key));
1844
1845 debug("Received session key; encryption turned on.");
1846
ff2d7a98 1847 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
3c0ef626 1848 packet_start(SSH_SMSG_SUCCESS);
1849 packet_send();
1850 packet_write_wait();
1851}
1852
1853/*
1854 * SSH2 key exchange: diffie-hellman-group1-sha1
1855 */
1856static void
1857do_ssh2_kex(void)
1858{
1859 Kex *kex;
1860
1861 if (options.ciphers != NULL) {
1862 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1863 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1864 }
1865 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1866 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1867 myproposal[PROPOSAL_ENC_ALGS_STOC] =
1868 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1869
1870 if (options.macs != NULL) {
1871 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1872 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1873 }
ff2d7a98 1874 if (!options.compression) {
1875 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
1876 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
1877 }
3c0ef626 1878 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1879
5598e598 1880#ifdef GSSAPI
1881 {
1882 char *orig;
1883 char *gss = NULL;
1884 char *newstr = NULL;
1885 orig = myproposal[PROPOSAL_KEX_ALGS];
1886
1887 /* If we don't have a host key, then all of the algorithms
1888 * currently in myproposal are useless */
1889 if (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])==0)
1890 orig= NULL;
1891
1892 if (options.gss_keyex)
88928908 1893 gss = ssh_gssapi_server_mechanisms();
5598e598 1894 else
1895 gss = NULL;
1896
1897 if (gss && orig) {
1898 int len = strlen(orig) + strlen(gss) +2;
1899 newstr=xmalloc(len);
1900 snprintf(newstr,len,"%s,%s",gss,orig);
1901 } else if (gss) {
1902 newstr=gss;
1903 } else if (orig) {
1904 newstr=orig;
1905 }
1906 /* If we've got GSSAPI mechanisms, then we've also got the 'null'
1907 host key algorithm, but we're not allowed to advertise it, unless
1908 its the only host key algorithm we're supporting */
1909 if (gss && (strlen(myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS])) == 0) {
1910 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS]="null";
1911 }
1912 if (newstr)
1913 myproposal[PROPOSAL_KEX_ALGS]=newstr;
1914 else
1915 fatal("No supported key exchange algorithms");
1916 }
1917#endif
1918
3c0ef626 1919 /* start key exchange */
1920 kex = kex_setup(myproposal);
1c14df9e 1921 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1922 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1923#ifdef GSSAPI
1924 kex->kex[KEX_GSS_GRP1_SHA1] = kexgss_server;
1925#endif
3c0ef626 1926 kex->server = 1;
1927 kex->client_version_string=client_version_string;
1928 kex->server_version_string=server_version_string;
1929 kex->load_host_key=&get_hostkey_by_type;
2980ea68 1930 kex->host_key_index=&get_hostkey_index;
3c0ef626 1931
1932 xxx_kex = kex;
1933
1934 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1935
1936 session_id2 = kex->session_id;
1937 session_id2_len = kex->session_id_len;
1938
1939#ifdef DEBUG_KEXDH
1940 /* send 1st encrypted/maced/compressed message */
1941 packet_start(SSH2_MSG_IGNORE);
1942 packet_put_cstring("markus");
1943 packet_send();
1944 packet_write_wait();
1945#endif
1946 debug("KEX done");
1947}
This page took 7.46737 seconds and 5 git commands to generate.