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