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