1 /* $OpenBSD: sshd.c,v 1.458 2015/08/20 22:32:42 deraadt Exp $ */
2 /*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * This program is the ssh daemon. It listens for connections from clients,
7 * and performs authentication, executes use commands or shell, and forwards
8 * information to/from the application to the user client over an encrypted
9 * connection. This can also handle forwarding of X11, TCP/IP, and
10 * authentication agent connections.
11 *
12 * As far as I am concerned, the code I have written for this software
13 * can be used freely for any purpose. Any derived versions of this
14 * software must be clearly marked as such, and if the derived work is
15 * incompatible with the protocol description in the RFC file, it must be
16 * called by a name other than "ssh" or "Secure Shell".
17 *
18 * SSH2 implementation:
19 * Privilege Separation:
20 *
21 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
22 * Copyright (c) 2002 Niels Provos. All rights reserved.
23 *
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
26 * are met:
27 * 1. Redistributions of source code must retain the above copyright
28 * notice, this list of conditions and the following disclaimer.
29 * 2. Redistributions in binary form must reproduce the above copyright
30 * notice, this list of conditions and the following disclaimer in the
31 * documentation and/or other materials provided with the distribution.
32 *
33 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 */
44
45 #include "includes.h"
46
47 #include <sys/types.h>
48 #include <sys/ioctl.h>
49 #include <sys/socket.h>
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
52 #endif
53 #ifdef HAVE_SYS_TIME_H
54 # include <sys/time.h>
55 #endif
56 #include "openbsd-compat/sys-tree.h"
57 #include "openbsd-compat/sys-queue.h"
58 #include <sys/wait.h>
59
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <netdb.h>
63 #ifdef HAVE_PATHS_H
64 #include <paths.h>
65 #endif
66 #include <grp.h>
67 #include <pwd.h>
68 #include <signal.h>
69 #include <stdarg.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <unistd.h>
74 #include <limits.h>
75
76 #ifdef WITH_OPENSSL
77 #include <openssl/dh.h>
78 #include <openssl/bn.h>
79 #include <openssl/rand.h>
80 #include "openbsd-compat/openssl-compat.h"
81 #endif
82
83 #ifdef HAVE_SECUREWARE
84 #include <sys/security.h>
85 #include <prot.h>
86 #endif
87
88 #include "xmalloc.h"
89 #include "ssh.h"
90 #include "ssh1.h"
91 #include "ssh2.h"
92 #include "rsa.h"
93 #include "sshpty.h"
94 #include "packet.h"
95 #include "log.h"
96 #include "buffer.h"
97 #include "misc.h"
98 #include "match.h"
99 #include "servconf.h"
100 #include "uidswap.h"
101 #include "compat.h"
102 #include "cipher.h"
103 #include "digest.h"
104 #include "key.h"
105 #include "kex.h"
106 #include "myproposal.h"
107 #include "authfile.h"
108 #include "pathnames.h"
109 #include "atomicio.h"
110 #include "canohost.h"
111 #include "hostfile.h"
112 #include "auth.h"
113 #include "authfd.h"
114 #include "msg.h"
115 #include "dispatch.h"
116 #include "channels.h"
117 #include "session.h"
118 #include "monitor_mm.h"
119 #include "monitor.h"
120 #ifdef GSSAPI
121 #include "ssh-gss.h"
122 #endif
123 #include "monitor_wrap.h"
124 #include "roaming.h"
125 #include "ssh-sandbox.h"
126 #include "version.h"
127 #include "ssherr.h"
128
129 #ifndef O_NOCTTY
130 #define O_NOCTTY 0
131 #endif
132
133 /* Re-exec fds */
134 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
135 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
136 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
137 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
138
139 extern char *__progname;
140
141 /* Server configuration options. */
142 ServerOptions options;
143
144 /* Name of the server configuration file. */
145 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
146
147 /*
148 * Debug mode flag. This can be set on the command line. If debug
149 * mode is enabled, extra debugging output will be sent to the system
150 * log, the daemon will not go to background, and will exit after processing
151 * the first connection.
152 */
153 int debug_flag = 0;
154
155 /* Flag indicating that the daemon should only test the configuration and keys. */
156 int test_flag = 0;
157
158 /* Flag indicating that the daemon is being started from inetd. */
159 int inetd_flag = 0;
160
161 /* Flag indicating that sshd should not detach and become a daemon. */
162 int no_daemon_flag = 0;
163
164 /* debug goes to stderr unless inetd_flag is set */
165 int log_stderr = 0;
166
167 /* Saved arguments to main(). */
168 char **saved_argv;
169 int saved_argc;
170
171 /* re-exec */
172 int rexeced_flag = 0;
173 int rexec_flag = 1;
174 int rexec_argc = 0;
175 char **rexec_argv;
176
177 /*
178 * The sockets that the server is listening; this is used in the SIGHUP
179 * signal handler.
180 */
181 #define MAX_LISTEN_SOCKS 16
182 int listen_socks[MAX_LISTEN_SOCKS];
183 int num_listen_socks = 0;
184
185 /*
186 * the client's version string, passed by sshd2 in compat mode. if != NULL,
187 * sshd will skip the version-number exchange
188 */
189 char *client_version_string = NULL;
190 char *server_version_string = NULL;
191
192 /* Daemon's agent connection */
193 int auth_sock = -1;
194 int have_agent = 0;
195
196 /*
197 * Any really sensitive data in the application is contained in this
198 * structure. The idea is that this structure could be locked into memory so
199 * that the pages do not get written into swap. However, there are some
200 * problems. The private key contains BIGNUMs, and we do not (in principle)
201 * have access to the internals of them, and locking just the structure is
202 * not very useful. Currently, memory locking is not implemented.
203 */
204 struct {
205 Key *server_key; /* ephemeral server key */
206 Key *ssh1_host_key; /* ssh1 host key */
207 Key **host_keys; /* all private host keys */
208 Key **host_pubkeys; /* all public host keys */
209 Key **host_certificates; /* all public host certificates */
210 int have_ssh1_key;
211 int have_ssh2_key;
212 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
213 } sensitive_data;
214
215 /*
216 * Flag indicating whether the RSA server key needs to be regenerated.
217 * Is set in the SIGALRM handler and cleared when the key is regenerated.
218 */
219 static volatile sig_atomic_t key_do_regen = 0;
220
221 /* This is set to true when a signal is received. */
222 static volatile sig_atomic_t received_sighup = 0;
223 static volatile sig_atomic_t received_sigterm = 0;
224
225 /* session identifier, used by RSA-auth */
226 u_char session_id[16];
227
228 /* same for ssh2 */
229 u_char *session_id2 = NULL;
230 u_int session_id2_len = 0;
231
232 /* record remote hostname or ip */
233 u_int utmp_len = HOST_NAME_MAX+1;
234
235 /* options.max_startup sized array of fd ints */
236 int *startup_pipes = NULL;
237 int startup_pipe; /* in child */
238
239 /* variables used for privilege separation */
240 int use_privsep = -1;
241 struct monitor *pmonitor = NULL;
242 int privsep_is_preauth = 1;
243
244 /* global authentication context */
245 Authctxt *the_authctxt = NULL;
246
247 /* sshd_config buffer */
248 Buffer cfg;
249
250 /* message to be displayed after login */
251 Buffer loginmsg;
252
253 /* Unprivileged user */
254 struct passwd *privsep_pw = NULL;
255
256 /* Prototypes for various functions defined later in this file. */
257 void destroy_sensitive_data(void);
258 void demote_sensitive_data(void);
259
260 #ifdef WITH_SSH1
261 static void do_ssh1_kex(void);
262 #endif
263 static void do_ssh2_kex(void);
264
265 /*
266 * Close all listening sockets
267 */
268 static void
close_listen_socks(void)269 close_listen_socks(void)
270 {
271 int i;
272
273 for (i = 0; i < num_listen_socks; i++)
274 close(listen_socks[i]);
275 num_listen_socks = -1;
276 }
277
278 static void
close_startup_pipes(void)279 close_startup_pipes(void)
280 {
281 int i;
282
283 if (startup_pipes)
284 for (i = 0; i < options.max_startups; i++)
285 if (startup_pipes[i] != -1)
286 close(startup_pipes[i]);
287 }
288
289 /*
290 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
291 * the effect is to reread the configuration file (and to regenerate
292 * the server key).
293 */
294
295 /*ARGSUSED*/
296 static void
sighup_handler(int sig)297 sighup_handler(int sig)
298 {
299 int save_errno = errno;
300
301 received_sighup = 1;
302 signal(SIGHUP, sighup_handler);
303 errno = save_errno;
304 }
305
306 /*
307 * Called from the main program after receiving SIGHUP.
308 * Restarts the server.
309 */
310 static void
sighup_restart(void)311 sighup_restart(void)
312 {
313 logit("Received SIGHUP; restarting.");
314 platform_pre_restart();
315 close_listen_socks();
316 close_startup_pipes();
317 alarm(0); /* alarm timer persists across exec */
318 signal(SIGHUP, SIG_IGN); /* will be restored after exec */
319 execv(saved_argv[0], saved_argv);
320 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
321 strerror(errno));
322 exit(1);
323 }
324
325 /*
326 * Generic signal handler for terminating signals in the master daemon.
327 */
328 /*ARGSUSED*/
329 static void
sigterm_handler(int sig)330 sigterm_handler(int sig)
331 {
332 received_sigterm = sig;
333 }
334
335 /*
336 * SIGCHLD handler. This is called whenever a child dies. This will then
337 * reap any zombies left by exited children.
338 */
339 /*ARGSUSED*/
340 static void
main_sigchld_handler(int sig)341 main_sigchld_handler(int sig)
342 {
343 int save_errno = errno;
344 pid_t pid;
345 int status;
346
347 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
348 (pid < 0 && errno == EINTR))
349 ;
350
351 signal(SIGCHLD, main_sigchld_handler);
352 errno = save_errno;
353 }
354
355 /*
356 * Signal handler for the alarm after the login grace period has expired.
357 */
358 /*ARGSUSED*/
359 static void
grace_alarm_handler(int sig)360 grace_alarm_handler(int sig)
361 {
362 if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
363 kill(pmonitor->m_pid, SIGALRM);
364
365 /*
366 * Try to kill any processes that we have spawned, E.g. authorized
367 * keys command helpers.
368 */
369 if (getpgid(0) == getpid()) {
370 signal(SIGTERM, SIG_IGN);
371 kill(0, SIGTERM);
372 }
373
374 /* Log error and exit. */
375 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
376 }
377
378 /*
379 * Signal handler for the key regeneration alarm. Note that this
380 * alarm only occurs in the daemon waiting for connections, and it does not
381 * do anything with the private key or random state before forking.
382 * Thus there should be no concurrency control/asynchronous execution
383 * problems.
384 */
385 static void
generate_ephemeral_server_key(void)386 generate_ephemeral_server_key(void)
387 {
388 verbose("Generating %s%d bit RSA key.",
389 sensitive_data.server_key ? "new " : "", options.server_key_bits);
390 if (sensitive_data.server_key != NULL)
391 key_free(sensitive_data.server_key);
392 sensitive_data.server_key = key_generate(KEY_RSA1,
393 options.server_key_bits);
394 verbose("RSA key generation complete.");
395
396 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
397 }
398
399 /*ARGSUSED*/
400 static void
key_regeneration_alarm(int sig)401 key_regeneration_alarm(int sig)
402 {
403 int save_errno = errno;
404
405 signal(SIGALRM, SIG_DFL);
406 errno = save_errno;
407 key_do_regen = 1;
408 }
409
410 static void
sshd_exchange_identification(int sock_in,int sock_out)411 sshd_exchange_identification(int sock_in, int sock_out)
412 {
413 u_int i;
414 int mismatch;
415 int remote_major, remote_minor;
416 int major, minor;
417 char *s, *newline = "\n";
418 char buf[256]; /* Must not be larger than remote_version. */
419 char remote_version[256]; /* Must be at least as big as buf. */
420
421 if ((options.protocol & SSH_PROTO_1) &&
422 (options.protocol & SSH_PROTO_2)) {
423 major = PROTOCOL_MAJOR_1;
424 minor = 99;
425 } else if (options.protocol & SSH_PROTO_2) {
426 major = PROTOCOL_MAJOR_2;
427 minor = PROTOCOL_MINOR_2;
428 newline = "\r\n";
429 } else {
430 major = PROTOCOL_MAJOR_1;
431 minor = PROTOCOL_MINOR_1;
432 }
433
434 xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s",
435 major, minor, SSH_VERSION,
436 *options.version_addendum == '\0' ? "" : " ",
437 options.version_addendum, newline);
438
439 /* Send our protocol version identification. */
440 if (roaming_atomicio(vwrite, sock_out, server_version_string,
441 strlen(server_version_string))
442 != strlen(server_version_string)) {
443 logit("Could not write ident string to %s", get_remote_ipaddr());
444 cleanup_exit(255);
445 }
446
447 /* Read other sides version identification. */
448 memset(buf, 0, sizeof(buf));
449 for (i = 0; i < sizeof(buf) - 1; i++) {
450 if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
451 logit("Did not receive identification string from %s",
452 get_remote_ipaddr());
453 cleanup_exit(255);
454 }
455 if (buf[i] == '\r') {
456 buf[i] = 0;
457 /* Kludge for F-Secure Macintosh < 1.0.2 */
458 if (i == 12 &&
459 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
460 break;
461 continue;
462 }
463 if (buf[i] == '\n') {
464 buf[i] = 0;
465 break;
466 }
467 }
468 buf[sizeof(buf) - 1] = 0;
469 client_version_string = xstrdup(buf);
470
471 /*
472 * Check that the versions match. In future this might accept
473 * several versions and set appropriate flags to handle them.
474 */
475 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
476 &remote_major, &remote_minor, remote_version) != 3) {
477 s = "Protocol mismatch.\n";
478 (void) atomicio(vwrite, sock_out, s, strlen(s));
479 logit("Bad protocol version identification '%.100s' "
480 "from %s port %d", client_version_string,
481 get_remote_ipaddr(), get_remote_port());
482 close(sock_in);
483 close(sock_out);
484 cleanup_exit(255);
485 }
486 debug("Client protocol version %d.%d; client software version %.100s",
487 remote_major, remote_minor, remote_version);
488
489 active_state->compat = compat_datafellows(remote_version);
490
491 if ((datafellows & SSH_BUG_PROBE) != 0) {
492 logit("probed from %s with %s. Don't panic.",
493 get_remote_ipaddr(), client_version_string);
494 cleanup_exit(255);
495 }
496 if ((datafellows & SSH_BUG_SCANNER) != 0) {
497 logit("scanned from %s with %s. Don't panic.",
498 get_remote_ipaddr(), client_version_string);
499 cleanup_exit(255);
500 }
501 if ((datafellows & SSH_BUG_RSASIGMD5) != 0) {
502 logit("Client version \"%.100s\" uses unsafe RSA signature "
503 "scheme; disabling use of RSA keys", remote_version);
504 }
505 if ((datafellows & SSH_BUG_DERIVEKEY) != 0) {
506 fatal("Client version \"%.100s\" uses unsafe key agreement; "
507 "refusing connection", remote_version);
508 }
509
510 mismatch = 0;
511 switch (remote_major) {
512 case 1:
513 if (remote_minor == 99) {
514 if (options.protocol & SSH_PROTO_2)
515 enable_compat20();
516 else
517 mismatch = 1;
518 break;
519 }
520 if (!(options.protocol & SSH_PROTO_1)) {
521 mismatch = 1;
522 break;
523 }
524 if (remote_minor < 3) {
525 packet_disconnect("Your ssh version is too old and "
526 "is no longer supported. Please install a newer version.");
527 } else if (remote_minor == 3) {
528 /* note that this disables agent-forwarding */
529 enable_compat13();
530 }
531 break;
532 case 2:
533 if (options.protocol & SSH_PROTO_2) {
534 enable_compat20();
535 break;
536 }
537 /* FALLTHROUGH */
538 default:
539 mismatch = 1;
540 break;
541 }
542 chop(server_version_string);
543 debug("Local version string %.200s", server_version_string);
544
545 if (mismatch) {
546 s = "Protocol major versions differ.\n";
547 (void) atomicio(vwrite, sock_out, s, strlen(s));
548 close(sock_in);
549 close(sock_out);
550 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
551 get_remote_ipaddr(),
552 server_version_string, client_version_string);
553 cleanup_exit(255);
554 }
555 }
556
557 /* Destroy the host and server keys. They will no longer be needed. */
558 void
destroy_sensitive_data(void)559 destroy_sensitive_data(void)
560 {
561 int i;
562
563 if (sensitive_data.server_key) {
564 key_free(sensitive_data.server_key);
565 sensitive_data.server_key = NULL;
566 }
567 for (i = 0; i < options.num_host_key_files; i++) {
568 if (sensitive_data.host_keys[i]) {
569 key_free(sensitive_data.host_keys[i]);
570 sensitive_data.host_keys[i] = NULL;
571 }
572 if (sensitive_data.host_certificates[i]) {
573 key_free(sensitive_data.host_certificates[i]);
574 sensitive_data.host_certificates[i] = NULL;
575 }
576 }
577 sensitive_data.ssh1_host_key = NULL;
578 explicit_bzero(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
579 }
580
581 /* Demote private to public keys for network child */
582 void
demote_sensitive_data(void)583 demote_sensitive_data(void)
584 {
585 Key *tmp;
586 int i;
587
588 if (sensitive_data.server_key) {
589 tmp = key_demote(sensitive_data.server_key);
590 key_free(sensitive_data.server_key);
591 sensitive_data.server_key = tmp;
592 }
593
594 for (i = 0; i < options.num_host_key_files; i++) {
595 if (sensitive_data.host_keys[i]) {
596 tmp = key_demote(sensitive_data.host_keys[i]);
597 key_free(sensitive_data.host_keys[i]);
598 sensitive_data.host_keys[i] = tmp;
599 if (tmp->type == KEY_RSA1)
600 sensitive_data.ssh1_host_key = tmp;
601 }
602 /* Certs do not need demotion */
603 }
604
605 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
606 }
607
608 static void
privsep_preauth_child(void)609 privsep_preauth_child(void)
610 {
611 u_int32_t rnd[256];
612 gid_t gidset[1];
613
614 /* Enable challenge-response authentication for privilege separation */
615 privsep_challenge_enable();
616
617 #ifdef GSSAPI
618 /* Cache supported mechanism OIDs for later use */
619 if (options.gss_authentication)
620 ssh_gssapi_prepare_supported_oids();
621 #endif
622
623 arc4random_stir();
624 arc4random_buf(rnd, sizeof(rnd));
625 #ifdef WITH_OPENSSL
626 RAND_seed(rnd, sizeof(rnd));
627 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
628 fatal("%s: RAND_bytes failed", __func__);
629 #endif
630 explicit_bzero(rnd, sizeof(rnd));
631
632 /* Demote the private keys to public keys. */
633 demote_sensitive_data();
634
635 /* Change our root directory */
636 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
637 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
638 strerror(errno));
639 if (chdir("/") == -1)
640 fatal("chdir(\"/\"): %s", strerror(errno));
641
642 /* Drop our privileges */
643 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
644 (u_int)privsep_pw->pw_gid);
645 #if 0
646 /* XXX not ready, too heavy after chroot */
647 do_setusercontext(privsep_pw);
648 #else
649 gidset[0] = privsep_pw->pw_gid;
650 if (setgroups(1, gidset) < 0)
651 fatal("setgroups: %.100s", strerror(errno));
652 permanently_set_uid(privsep_pw);
653 #endif
654 }
655
656 static int
privsep_preauth(Authctxt * authctxt)657 privsep_preauth(Authctxt *authctxt)
658 {
659 int status, r;
660 pid_t pid;
661 struct ssh_sandbox *box = NULL;
662
663 /* Set up unprivileged child process to deal with network data */
664 pmonitor = monitor_init();
665 /* Store a pointer to the kex for later rekeying */
666 pmonitor->m_pkex = &active_state->kex;
667
668 if (use_privsep == PRIVSEP_ON)
669 box = ssh_sandbox_init(pmonitor);
670 pid = fork();
671 if (pid == -1) {
672 fatal("fork of unprivileged child failed");
673 } else if (pid != 0) {
674 debug2("Network child is on pid %ld", (long)pid);
675
676 pmonitor->m_pid = pid;
677 if (have_agent) {
678 r = ssh_get_authentication_socket(&auth_sock);
679 if (r != 0) {
680 error("Could not get agent socket: %s",
681 ssh_err(r));
682 have_agent = 0;
683 }
684 }
685 if (box != NULL)
686 ssh_sandbox_parent_preauth(box, pid);
687 monitor_child_preauth(authctxt, pmonitor);
688
689 /* Sync memory */
690 monitor_sync(pmonitor);
691
692 /* Wait for the child's exit status */
693 while (waitpid(pid, &status, 0) < 0) {
694 if (errno == EINTR)
695 continue;
696 pmonitor->m_pid = -1;
697 fatal("%s: waitpid: %s", __func__, strerror(errno));
698 }
699 privsep_is_preauth = 0;
700 pmonitor->m_pid = -1;
701 if (WIFEXITED(status)) {
702 if (WEXITSTATUS(status) != 0)
703 fatal("%s: preauth child exited with status %d",
704 __func__, WEXITSTATUS(status));
705 } else if (WIFSIGNALED(status))
706 fatal("%s: preauth child terminated by signal %d",
707 __func__, WTERMSIG(status));
708 if (box != NULL)
709 ssh_sandbox_parent_finish(box);
710 return 1;
711 } else {
712 /* child */
713 close(pmonitor->m_sendfd);
714 close(pmonitor->m_log_recvfd);
715
716 /* Arrange for logging to be sent to the monitor */
717 set_log_handler(mm_log_handler, pmonitor);
718
719 /* Demote the child */
720 if (getuid() == 0 || geteuid() == 0)
721 privsep_preauth_child();
722 setproctitle("%s", "[net]");
723 if (box != NULL)
724 ssh_sandbox_child(box);
725
726 return 0;
727 }
728 }
729
730 static void
privsep_postauth(Authctxt * authctxt)731 privsep_postauth(Authctxt *authctxt)
732 {
733 u_int32_t rnd[256];
734
735 #ifdef DISABLE_FD_PASSING
736 if (1) {
737 #else
738 if (authctxt->pw->pw_uid == 0 || options.use_login) {
739 #endif
740 /* File descriptor passing is broken or root login */
741 use_privsep = 0;
742 goto skip;
743 }
744
745 /* New socket pair */
746 monitor_reinit(pmonitor);
747
748 pmonitor->m_pid = fork();
749 if (pmonitor->m_pid == -1)
750 fatal("fork of unprivileged child failed");
751 else if (pmonitor->m_pid != 0) {
752 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
753 buffer_clear(&loginmsg);
754 monitor_child_postauth(pmonitor);
755
756 /* NEVERREACHED */
757 exit(0);
758 }
759
760 /* child */
761
762 close(pmonitor->m_sendfd);
763 pmonitor->m_sendfd = -1;
764
765 /* Demote the private keys to public keys. */
766 demote_sensitive_data();
767
768 arc4random_stir();
769 arc4random_buf(rnd, sizeof(rnd));
770 #ifdef WITH_OPENSSL
771 RAND_seed(rnd, sizeof(rnd));
772 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
773 fatal("%s: RAND_bytes failed", __func__);
774 #endif
775 explicit_bzero(rnd, sizeof(rnd));
776
777 /* Drop privileges */
778 do_setusercontext(authctxt->pw);
779
780 skip:
781 /* It is safe now to apply the key state */
782 monitor_apply_keystate(pmonitor);
783
784 /*
785 * Tell the packet layer that authentication was successful, since
786 * this information is not part of the key state.
787 */
788 packet_set_authenticated();
789 }
790
791 static char *
792 list_hostkey_types(void)
793 {
794 Buffer b;
795 const char *p;
796 char *ret;
797 int i;
798 Key *key;
799
800 buffer_init(&b);
801 for (i = 0; i < options.num_host_key_files; i++) {
802 key = sensitive_data.host_keys[i];
803 if (key == NULL)
804 key = sensitive_data.host_pubkeys[i];
805 if (key == NULL || key->type == KEY_RSA1)
806 continue;
807 /* Check that the key is accepted in HostkeyAlgorithms */
808 if (match_pattern_list(sshkey_ssh_name(key),
809 options.hostkeyalgorithms, 0) != 1) {
810 debug3("%s: %s key not permitted by HostkeyAlgorithms",
811 __func__, sshkey_ssh_name(key));
812 continue;
813 }
814 switch (key->type) {
815 case KEY_RSA:
816 case KEY_DSA:
817 case KEY_ECDSA:
818 case KEY_ED25519:
819 if (buffer_len(&b) > 0)
820 buffer_append(&b, ",", 1);
821 p = key_ssh_name(key);
822 buffer_append(&b, p, strlen(p));
823 break;
824 }
825 /* If the private key has a cert peer, then list that too */
826 key = sensitive_data.host_certificates[i];
827 if (key == NULL)
828 continue;
829 switch (key->type) {
830 case KEY_RSA_CERT:
831 case KEY_DSA_CERT:
832 case KEY_ECDSA_CERT:
833 case KEY_ED25519_CERT:
834 if (buffer_len(&b) > 0)
835 buffer_append(&b, ",", 1);
836 p = key_ssh_name(key);
837 buffer_append(&b, p, strlen(p));
838 break;
839 }
840 }
841 buffer_append(&b, "\0", 1);
842 ret = xstrdup(buffer_ptr(&b));
843 buffer_free(&b);
844 debug("list_hostkey_types: %s", ret);
845 return ret;
846 }
847
848 static Key *
849 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
850 {
851 int i;
852 Key *key;
853
854 for (i = 0; i < options.num_host_key_files; i++) {
855 switch (type) {
856 case KEY_RSA_CERT:
857 case KEY_DSA_CERT:
858 case KEY_ECDSA_CERT:
859 case KEY_ED25519_CERT:
860 key = sensitive_data.host_certificates[i];
861 break;
862 default:
863 key = sensitive_data.host_keys[i];
864 if (key == NULL && !need_private)
865 key = sensitive_data.host_pubkeys[i];
866 break;
867 }
868 if (key != NULL && key->type == type &&
869 (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
870 return need_private ?
871 sensitive_data.host_keys[i] : key;
872 }
873 return NULL;
874 }
875
876 Key *
877 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
878 {
879 return get_hostkey_by_type(type, nid, 0, ssh);
880 }
881
882 Key *
883 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
884 {
885 return get_hostkey_by_type(type, nid, 1, ssh);
886 }
887
888 Key *
889 get_hostkey_by_index(int ind)
890 {
891 if (ind < 0 || ind >= options.num_host_key_files)
892 return (NULL);
893 return (sensitive_data.host_keys[ind]);
894 }
895
896 Key *
897 get_hostkey_public_by_index(int ind, struct ssh *ssh)
898 {
899 if (ind < 0 || ind >= options.num_host_key_files)
900 return (NULL);
901 return (sensitive_data.host_pubkeys[ind]);
902 }
903
904 int
905 get_hostkey_index(Key *key, int compare, struct ssh *ssh)
906 {
907 int i;
908
909 for (i = 0; i < options.num_host_key_files; i++) {
910 if (key_is_cert(key)) {
911 if (key == sensitive_data.host_certificates[i] ||
912 (compare && sensitive_data.host_certificates[i] &&
913 sshkey_equal(key,
914 sensitive_data.host_certificates[i])))
915 return (i);
916 } else {
917 if (key == sensitive_data.host_keys[i] ||
918 (compare && sensitive_data.host_keys[i] &&
919 sshkey_equal(key, sensitive_data.host_keys[i])))
920 return (i);
921 if (key == sensitive_data.host_pubkeys[i] ||
922 (compare && sensitive_data.host_pubkeys[i] &&
923 sshkey_equal(key, sensitive_data.host_pubkeys[i])))
924 return (i);
925 }
926 }
927 return (-1);
928 }
929
930 /* Inform the client of all hostkeys */
931 static void
932 notify_hostkeys(struct ssh *ssh)
933 {
934 struct sshbuf *buf;
935 struct sshkey *key;
936 int i, nkeys, r;
937 char *fp;
938
939 /* Some clients cannot cope with the hostkeys message, skip those. */
940 if (datafellows & SSH_BUG_HOSTKEYS)
941 return;
942
943 if ((buf = sshbuf_new()) == NULL)
944 fatal("%s: sshbuf_new", __func__);
945 for (i = nkeys = 0; i < options.num_host_key_files; i++) {
946 key = get_hostkey_public_by_index(i, ssh);
947 if (key == NULL || key->type == KEY_UNSPEC ||
948 key->type == KEY_RSA1 || sshkey_is_cert(key))
949 continue;
950 fp = sshkey_fingerprint(key, options.fingerprint_hash,
951 SSH_FP_DEFAULT);
952 debug3("%s: key %d: %s %s", __func__, i,
953 sshkey_ssh_name(key), fp);
954 free(fp);
955 if (nkeys == 0) {
956 packet_start(SSH2_MSG_GLOBAL_REQUEST);
957 packet_put_cstring("hostkeys-00@openssh.com");
958 packet_put_char(0); /* want-reply */
959 }
960 sshbuf_reset(buf);
961 if ((r = sshkey_putb(key, buf)) != 0)
962 fatal("%s: couldn't put hostkey %d: %s",
963 __func__, i, ssh_err(r));
964 packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
965 nkeys++;
966 }
967 debug3("%s: sent %d hostkeys", __func__, nkeys);
968 if (nkeys == 0)
969 fatal("%s: no hostkeys", __func__);
970 packet_send();
971 sshbuf_free(buf);
972 }
973
974 /*
975 * returns 1 if connection should be dropped, 0 otherwise.
976 * dropping starts at connection #max_startups_begin with a probability
977 * of (max_startups_rate/100). the probability increases linearly until
978 * all connections are dropped for startups > max_startups
979 */
980 static int
981 drop_connection(int startups)
982 {
983 int p, r;
984
985 if (startups < options.max_startups_begin)
986 return 0;
987 if (startups >= options.max_startups)
988 return 1;
989 if (options.max_startups_rate == 100)
990 return 1;
991
992 p = 100 - options.max_startups_rate;
993 p *= startups - options.max_startups_begin;
994 p /= options.max_startups - options.max_startups_begin;
995 p += options.max_startups_rate;
996 r = arc4random_uniform(100);
997
998 debug("drop_connection: p %d, r %d", p, r);
999 return (r < p) ? 1 : 0;
1000 }
1001
1002 static void
1003 usage(void)
1004 {
1005 fprintf(stderr, "%s, %s\n",
1006 SSH_RELEASE,
1007 #ifdef WITH_OPENSSL
1008 SSLeay_version(SSLEAY_VERSION)
1009 #else
1010 "without OpenSSL"
1011 #endif
1012 );
1013 fprintf(stderr,
1014 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
1015 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
1016 " [-h host_key_file] [-k key_gen_time] [-o option] [-p port]\n"
1017 " [-u len]\n"
1018 );
1019 exit(1);
1020 }
1021
1022 static void
1023 send_rexec_state(int fd, Buffer *conf)
1024 {
1025 Buffer m;
1026
1027 debug3("%s: entering fd = %d config len %d", __func__, fd,
1028 buffer_len(conf));
1029
1030 /*
1031 * Protocol from reexec master to child:
1032 * string configuration
1033 * u_int ephemeral_key_follows
1034 * bignum e (only if ephemeral_key_follows == 1)
1035 * bignum n "
1036 * bignum d "
1037 * bignum iqmp "
1038 * bignum p "
1039 * bignum q "
1040 * string rngseed (only if OpenSSL is not self-seeded)
1041 */
1042 buffer_init(&m);
1043 buffer_put_cstring(&m, buffer_ptr(conf));
1044
1045 #ifdef WITH_SSH1
1046 if (sensitive_data.server_key != NULL &&
1047 sensitive_data.server_key->type == KEY_RSA1) {
1048 buffer_put_int(&m, 1);
1049 buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
1050 buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
1051 buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
1052 buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1053 buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
1054 buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
1055 } else
1056 #endif
1057 buffer_put_int(&m, 0);
1058
1059 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1060 rexec_send_rng_seed(&m);
1061 #endif
1062
1063 if (ssh_msg_send(fd, 0, &m) == -1)
1064 fatal("%s: ssh_msg_send failed", __func__);
1065
1066 buffer_free(&m);
1067
1068 debug3("%s: done", __func__);
1069 }
1070
1071 static void
1072 recv_rexec_state(int fd, Buffer *conf)
1073 {
1074 Buffer m;
1075 char *cp;
1076 u_int len;
1077
1078 debug3("%s: entering fd = %d", __func__, fd);
1079
1080 buffer_init(&m);
1081
1082 if (ssh_msg_recv(fd, &m) == -1)
1083 fatal("%s: ssh_msg_recv failed", __func__);
1084 if (buffer_get_char(&m) != 0)
1085 fatal("%s: rexec version mismatch", __func__);
1086
1087 cp = buffer_get_string(&m, &len);
1088 if (conf != NULL)
1089 buffer_append(conf, cp, len + 1);
1090 free(cp);
1091
1092 if (buffer_get_int(&m)) {
1093 #ifdef WITH_SSH1
1094 if (sensitive_data.server_key != NULL)
1095 key_free(sensitive_data.server_key);
1096 sensitive_data.server_key = key_new_private(KEY_RSA1);
1097 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
1098 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
1099 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
1100 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1101 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
1102 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
1103 if (rsa_generate_additional_parameters(
1104 sensitive_data.server_key->rsa) != 0)
1105 fatal("%s: rsa_generate_additional_parameters "
1106 "error", __func__);
1107 #endif
1108 }
1109
1110 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1111 rexec_recv_rng_seed(&m);
1112 #endif
1113
1114 buffer_free(&m);
1115
1116 debug3("%s: done", __func__);
1117 }
1118
1119 /* Accept a connection from inetd */
1120 static void
1121 server_accept_inetd(int *sock_in, int *sock_out)
1122 {
1123 int fd;
1124
1125 startup_pipe = -1;
1126 if (rexeced_flag) {
1127 close(REEXEC_CONFIG_PASS_FD);
1128 *sock_in = *sock_out = dup(STDIN_FILENO);
1129 if (!debug_flag) {
1130 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1131 close(REEXEC_STARTUP_PIPE_FD);
1132 }
1133 } else {
1134 *sock_in = dup(STDIN_FILENO);
1135 *sock_out = dup(STDOUT_FILENO);
1136 }
1137 /*
1138 * We intentionally do not close the descriptors 0, 1, and 2
1139 * as our code for setting the descriptors won't work if
1140 * ttyfd happens to be one of those.
1141 */
1142 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1143 dup2(fd, STDIN_FILENO);
1144 dup2(fd, STDOUT_FILENO);
1145 if (!log_stderr)
1146 dup2(fd, STDERR_FILENO);
1147 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1148 close(fd);
1149 }
1150 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1151 }
1152
1153 /*
1154 * Listen for TCP connections
1155 */
1156 static void
1157 server_listen(void)
1158 {
1159 int ret, listen_sock, on = 1;
1160 struct addrinfo *ai;
1161 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1162
1163 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1164 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1165 continue;
1166 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1167 fatal("Too many listen sockets. "
1168 "Enlarge MAX_LISTEN_SOCKS");
1169 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1170 ntop, sizeof(ntop), strport, sizeof(strport),
1171 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1172 error("getnameinfo failed: %.100s",
1173 ssh_gai_strerror(ret));
1174 continue;
1175 }
1176 /* Create socket for listening. */
1177 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1178 ai->ai_protocol);
1179 if (listen_sock < 0) {
1180 /* kernel may not support ipv6 */
1181 verbose("socket: %.100s", strerror(errno));
1182 continue;
1183 }
1184 if (set_nonblock(listen_sock) == -1) {
1185 close(listen_sock);
1186 continue;
1187 }
1188 /*
1189 * Set socket options.
1190 * Allow local port reuse in TIME_WAIT.
1191 */
1192 if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1193 &on, sizeof(on)) == -1)
1194 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1195
1196 /* Only communicate in IPv6 over AF_INET6 sockets. */
1197 if (ai->ai_family == AF_INET6)
1198 sock_set_v6only(listen_sock);
1199
1200 debug("Bind to port %s on %s.", strport, ntop);
1201
1202 /* Bind the socket to the desired port. */
1203 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1204 error("Bind to port %s on %s failed: %.200s.",
1205 strport, ntop, strerror(errno));
1206 close(listen_sock);
1207 continue;
1208 }
1209 listen_socks[num_listen_socks] = listen_sock;
1210 num_listen_socks++;
1211
1212 /* Start listening on the port. */
1213 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1214 fatal("listen on [%s]:%s: %.100s",
1215 ntop, strport, strerror(errno));
1216 logit("Server listening on %s port %s.", ntop, strport);
1217 }
1218 freeaddrinfo(options.listen_addrs);
1219
1220 if (!num_listen_socks)
1221 fatal("Cannot bind any address.");
1222 }
1223
1224 /*
1225 * The main TCP accept loop. Note that, for the non-debug case, returns
1226 * from this function are in a forked subprocess.
1227 */
1228 static void
1229 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1230 {
1231 fd_set *fdset;
1232 int i, j, ret, maxfd;
1233 int key_used = 0, startups = 0;
1234 int startup_p[2] = { -1 , -1 };
1235 struct sockaddr_storage from;
1236 socklen_t fromlen;
1237 pid_t pid;
1238 u_char rnd[256];
1239
1240 /* setup fd set for accept */
1241 fdset = NULL;
1242 maxfd = 0;
1243 for (i = 0; i < num_listen_socks; i++)
1244 if (listen_socks[i] > maxfd)
1245 maxfd = listen_socks[i];
1246 /* pipes connected to unauthenticated childs */
1247 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1248 for (i = 0; i < options.max_startups; i++)
1249 startup_pipes[i] = -1;
1250
1251 /*
1252 * Stay listening for connections until the system crashes or
1253 * the daemon is killed with a signal.
1254 */
1255 for (;;) {
1256 if (received_sighup)
1257 sighup_restart();
1258 if (fdset != NULL)
1259 free(fdset);
1260 fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1261 sizeof(fd_mask));
1262
1263 for (i = 0; i < num_listen_socks; i++)
1264 FD_SET(listen_socks[i], fdset);
1265 for (i = 0; i < options.max_startups; i++)
1266 if (startup_pipes[i] != -1)
1267 FD_SET(startup_pipes[i], fdset);
1268
1269 /* Wait in select until there is a connection. */
1270 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1271 if (ret < 0 && errno != EINTR)
1272 error("select: %.100s", strerror(errno));
1273 if (received_sigterm) {
1274 logit("Received signal %d; terminating.",
1275 (int) received_sigterm);
1276 close_listen_socks();
1277 if (options.pid_file != NULL)
1278 unlink(options.pid_file);
1279 exit(received_sigterm == SIGTERM ? 0 : 255);
1280 }
1281 if (key_used && key_do_regen) {
1282 generate_ephemeral_server_key();
1283 key_used = 0;
1284 key_do_regen = 0;
1285 }
1286 if (ret < 0)
1287 continue;
1288
1289 for (i = 0; i < options.max_startups; i++)
1290 if (startup_pipes[i] != -1 &&
1291 FD_ISSET(startup_pipes[i], fdset)) {
1292 /*
1293 * the read end of the pipe is ready
1294 * if the child has closed the pipe
1295 * after successful authentication
1296 * or if the child has died
1297 */
1298 close(startup_pipes[i]);
1299 startup_pipes[i] = -1;
1300 startups--;
1301 }
1302 for (i = 0; i < num_listen_socks; i++) {
1303 if (!FD_ISSET(listen_socks[i], fdset))
1304 continue;
1305 fromlen = sizeof(from);
1306 *newsock = accept(listen_socks[i],
1307 (struct sockaddr *)&from, &fromlen);
1308 if (*newsock < 0) {
1309 if (errno != EINTR && errno != EWOULDBLOCK &&
1310 errno != ECONNABORTED && errno != EAGAIN)
1311 error("accept: %.100s",
1312 strerror(errno));
1313 if (errno == EMFILE || errno == ENFILE)
1314 usleep(100 * 1000);
1315 continue;
1316 }
1317 if (unset_nonblock(*newsock) == -1) {
1318 close(*newsock);
1319 continue;
1320 }
1321 if (drop_connection(startups) == 1) {
1322 debug("drop connection #%d", startups);
1323 close(*newsock);
1324 continue;
1325 }
1326 if (pipe(startup_p) == -1) {
1327 close(*newsock);
1328 continue;
1329 }
1330
1331 if (rexec_flag && socketpair(AF_UNIX,
1332 SOCK_STREAM, 0, config_s) == -1) {
1333 error("reexec socketpair: %s",
1334 strerror(errno));
1335 close(*newsock);
1336 close(startup_p[0]);
1337 close(startup_p[1]);
1338 continue;
1339 }
1340
1341 for (j = 0; j < options.max_startups; j++)
1342 if (startup_pipes[j] == -1) {
1343 startup_pipes[j] = startup_p[0];
1344 if (maxfd < startup_p[0])
1345 maxfd = startup_p[0];
1346 startups++;
1347 break;
1348 }
1349
1350 /*
1351 * Got connection. Fork a child to handle it, unless
1352 * we are in debugging mode.
1353 */
1354 if (debug_flag) {
1355 /*
1356 * In debugging mode. Close the listening
1357 * socket, and start processing the
1358 * connection without forking.
1359 */
1360 debug("Server will not fork when running in debugging mode.");
1361 close_listen_socks();
1362 *sock_in = *newsock;
1363 *sock_out = *newsock;
1364 close(startup_p[0]);
1365 close(startup_p[1]);
1366 startup_pipe = -1;
1367 pid = getpid();
1368 if (rexec_flag) {
1369 send_rexec_state(config_s[0],
1370 &cfg);
1371 close(config_s[0]);
1372 }
1373 break;
1374 }
1375
1376 /*
1377 * Normal production daemon. Fork, and have
1378 * the child process the connection. The
1379 * parent continues listening.
1380 */
1381 platform_pre_fork();
1382 if ((pid = fork()) == 0) {
1383 /*
1384 * Child. Close the listening and
1385 * max_startup sockets. Start using
1386 * the accepted socket. Reinitialize
1387 * logging (since our pid has changed).
1388 * We break out of the loop to handle
1389 * the connection.
1390 */
1391 platform_post_fork_child();
1392 startup_pipe = startup_p[1];
1393 close_startup_pipes();
1394 close_listen_socks();
1395 *sock_in = *newsock;
1396 *sock_out = *newsock;
1397 log_init(__progname,
1398 options.log_level,
1399 options.log_facility,
1400 log_stderr);
1401 if (rexec_flag)
1402 close(config_s[0]);
1403 break;
1404 }
1405
1406 /* Parent. Stay in the loop. */
1407 platform_post_fork_parent(pid);
1408 if (pid < 0)
1409 error("fork: %.100s", strerror(errno));
1410 else
1411 debug("Forked child %ld.", (long)pid);
1412
1413 close(startup_p[1]);
1414
1415 if (rexec_flag) {
1416 send_rexec_state(config_s[0], &cfg);
1417 close(config_s[0]);
1418 close(config_s[1]);
1419 }
1420
1421 /*
1422 * Mark that the key has been used (it
1423 * was "given" to the child).
1424 */
1425 if ((options.protocol & SSH_PROTO_1) &&
1426 key_used == 0) {
1427 /* Schedule server key regeneration alarm. */
1428 signal(SIGALRM, key_regeneration_alarm);
1429 alarm(options.key_regeneration_time);
1430 key_used = 1;
1431 }
1432
1433 close(*newsock);
1434
1435 /*
1436 * Ensure that our random state differs
1437 * from that of the child
1438 */
1439 arc4random_stir();
1440 arc4random_buf(rnd, sizeof(rnd));
1441 #ifdef WITH_OPENSSL
1442 RAND_seed(rnd, sizeof(rnd));
1443 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1444 fatal("%s: RAND_bytes failed", __func__);
1445 #endif
1446 explicit_bzero(rnd, sizeof(rnd));
1447 }
1448
1449 /* child process check (or debug mode) */
1450 if (num_listen_socks < 0)
1451 break;
1452 }
1453 }
1454
1455
1456 /*
1457 * Main program for the daemon.
1458 */
1459 int
1460 main(int ac, char **av)
1461 {
1462 extern char *optarg;
1463 extern int optind;
1464 int r, opt, i, j, on = 1;
1465 int sock_in = -1, sock_out = -1, newsock = -1;
1466 const char *remote_ip;
1467 int remote_port;
1468 char *fp, *line, *laddr, *logfile = NULL;
1469 int config_s[2] = { -1 , -1 };
1470 u_int n;
1471 u_int64_t ibytes, obytes;
1472 mode_t new_umask;
1473 Key *key;
1474 Key *pubkey;
1475 int keytype;
1476 Authctxt *authctxt;
1477 struct connection_info *connection_info = get_connection_info(0, 0);
1478
1479 #ifdef HAVE_SECUREWARE
1480 (void)set_auth_parameters(ac, av);
1481 #endif
1482 __progname = ssh_get_progname(av[0]);
1483
1484 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1485 saved_argc = ac;
1486 rexec_argc = ac;
1487 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1488 for (i = 0; i < ac; i++)
1489 saved_argv[i] = xstrdup(av[i]);
1490 saved_argv[i] = NULL;
1491
1492 #ifndef HAVE_SETPROCTITLE
1493 /* Prepare for later setproctitle emulation */
1494 compat_init_setproctitle(ac, av);
1495 av = saved_argv;
1496 #endif
1497
1498 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1499 debug("setgroups(): %.200s", strerror(errno));
1500
1501 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1502 sanitise_stdfd();
1503
1504 /* Initialize configuration options to their default values. */
1505 initialize_server_options(&options);
1506
1507 /* Parse command-line arguments. */
1508 while ((opt = getopt(ac, av,
1509 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1510 switch (opt) {
1511 case '4':
1512 options.address_family = AF_INET;
1513 break;
1514 case '6':
1515 options.address_family = AF_INET6;
1516 break;
1517 case 'f':
1518 config_file_name = optarg;
1519 break;
1520 case 'c':
1521 if (options.num_host_cert_files >= MAX_HOSTCERTS) {
1522 fprintf(stderr, "too many host certificates.\n");
1523 exit(1);
1524 }
1525 options.host_cert_files[options.num_host_cert_files++] =
1526 derelativise_path(optarg);
1527 break;
1528 case 'd':
1529 if (debug_flag == 0) {
1530 debug_flag = 1;
1531 options.log_level = SYSLOG_LEVEL_DEBUG1;
1532 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1533 options.log_level++;
1534 break;
1535 case 'D':
1536 no_daemon_flag = 1;
1537 break;
1538 case 'E':
1539 logfile = xstrdup(optarg);
1540 /* FALLTHROUGH */
1541 case 'e':
1542 log_stderr = 1;
1543 break;
1544 case 'i':
1545 inetd_flag = 1;
1546 break;
1547 case 'r':
1548 rexec_flag = 0;
1549 break;
1550 case 'R':
1551 rexeced_flag = 1;
1552 inetd_flag = 1;
1553 break;
1554 case 'Q':
1555 /* ignored */
1556 break;
1557 case 'q':
1558 options.log_level = SYSLOG_LEVEL_QUIET;
1559 break;
1560 case 'b':
1561 options.server_key_bits = (int)strtonum(optarg, 256,
1562 32768, NULL);
1563 break;
1564 case 'p':
1565 options.ports_from_cmdline = 1;
1566 if (options.num_ports >= MAX_PORTS) {
1567 fprintf(stderr, "too many ports.\n");
1568 exit(1);
1569 }
1570 options.ports[options.num_ports++] = a2port(optarg);
1571 if (options.ports[options.num_ports-1] <= 0) {
1572 fprintf(stderr, "Bad port number.\n");
1573 exit(1);
1574 }
1575 break;
1576 case 'g':
1577 if ((options.login_grace_time = convtime(optarg)) == -1) {
1578 fprintf(stderr, "Invalid login grace time.\n");
1579 exit(1);
1580 }
1581 break;
1582 case 'k':
1583 if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1584 fprintf(stderr, "Invalid key regeneration interval.\n");
1585 exit(1);
1586 }
1587 break;
1588 case 'h':
1589 if (options.num_host_key_files >= MAX_HOSTKEYS) {
1590 fprintf(stderr, "too many host keys.\n");
1591 exit(1);
1592 }
1593 options.host_key_files[options.num_host_key_files++] =
1594 derelativise_path(optarg);
1595 break;
1596 case 't':
1597 test_flag = 1;
1598 break;
1599 case 'T':
1600 test_flag = 2;
1601 break;
1602 case 'C':
1603 if (parse_server_match_testspec(connection_info,
1604 optarg) == -1)
1605 exit(1);
1606 break;
1607 case 'u':
1608 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1609 if (utmp_len > HOST_NAME_MAX+1) {
1610 fprintf(stderr, "Invalid utmp length.\n");
1611 exit(1);
1612 }
1613 break;
1614 case 'o':
1615 line = xstrdup(optarg);
1616 if (process_server_config_line(&options, line,
1617 "command-line", 0, NULL, NULL) != 0)
1618 exit(1);
1619 free(line);
1620 break;
1621 case '?':
1622 default:
1623 usage();
1624 break;
1625 }
1626 }
1627 if (rexeced_flag || inetd_flag)
1628 rexec_flag = 0;
1629 if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1630 fatal("sshd re-exec requires execution with an absolute path");
1631 if (rexeced_flag)
1632 closefrom(REEXEC_MIN_FREE_FD);
1633 else
1634 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1635
1636 #ifdef WITH_OPENSSL
1637 OpenSSL_add_all_algorithms();
1638 #endif
1639
1640 /* If requested, redirect the logs to the specified logfile. */
1641 if (logfile != NULL) {
1642 log_redirect_stderr_to(logfile);
1643 free(logfile);
1644 }
1645 /*
1646 * Force logging to stderr until we have loaded the private host
1647 * key (unless started from inetd)
1648 */
1649 log_init(__progname,
1650 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1651 SYSLOG_LEVEL_INFO : options.log_level,
1652 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1653 SYSLOG_FACILITY_AUTH : options.log_facility,
1654 log_stderr || !inetd_flag);
1655
1656 /*
1657 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1658 * root's environment
1659 */
1660 if (getenv("KRB5CCNAME") != NULL)
1661 (void) unsetenv("KRB5CCNAME");
1662
1663 #ifdef _UNICOS
1664 /* Cray can define user privs drop all privs now!
1665 * Not needed on PRIV_SU systems!
1666 */
1667 drop_cray_privs();
1668 #endif
1669
1670 sensitive_data.server_key = NULL;
1671 sensitive_data.ssh1_host_key = NULL;
1672 sensitive_data.have_ssh1_key = 0;
1673 sensitive_data.have_ssh2_key = 0;
1674
1675 /*
1676 * If we're doing an extended config test, make sure we have all of
1677 * the parameters we need. If we're not doing an extended test,
1678 * do not silently ignore connection test params.
1679 */
1680 if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1681 fatal("user, host and addr are all required when testing "
1682 "Match configs");
1683 if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1684 fatal("Config test connection parameter (-C) provided without "
1685 "test mode (-T)");
1686
1687 /* Fetch our configuration */
1688 buffer_init(&cfg);
1689 if (rexeced_flag)
1690 recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1691 else if (strcasecmp(config_file_name, "none") != 0)
1692 load_server_config(config_file_name, &cfg);
1693
1694 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1695 &cfg, NULL);
1696
1697 seed_rng();
1698
1699 /* Fill in default values for those options not explicitly set. */
1700 fill_default_server_options(&options);
1701
1702 /* challenge-response is implemented via keyboard interactive */
1703 if (options.challenge_response_authentication)
1704 options.kbd_interactive_authentication = 1;
1705
1706 /* Check that options are sensible */
1707 if (options.authorized_keys_command_user == NULL &&
1708 (options.authorized_keys_command != NULL &&
1709 strcasecmp(options.authorized_keys_command, "none") != 0))
1710 fatal("AuthorizedKeysCommand set without "
1711 "AuthorizedKeysCommandUser");
1712 if (options.authorized_principals_command_user == NULL &&
1713 (options.authorized_principals_command != NULL &&
1714 strcasecmp(options.authorized_principals_command, "none") != 0))
1715 fatal("AuthorizedPrincipalsCommand set without "
1716 "AuthorizedPrincipalsCommandUser");
1717
1718 /*
1719 * Check whether there is any path through configured auth methods.
1720 * Unfortunately it is not possible to verify this generally before
1721 * daemonisation in the presence of Match block, but this catches
1722 * and warns for trivial misconfigurations that could break login.
1723 */
1724 if (options.num_auth_methods != 0) {
1725 if ((options.protocol & SSH_PROTO_1))
1726 fatal("AuthenticationMethods is not supported with "
1727 "SSH protocol 1");
1728 for (n = 0; n < options.num_auth_methods; n++) {
1729 if (auth2_methods_valid(options.auth_methods[n],
1730 1) == 0)
1731 break;
1732 }
1733 if (n >= options.num_auth_methods)
1734 fatal("AuthenticationMethods cannot be satisfied by "
1735 "enabled authentication methods");
1736 }
1737
1738 /* set default channel AF */
1739 channel_set_af(options.address_family);
1740
1741 /* Check that there are no remaining arguments. */
1742 if (optind < ac) {
1743 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1744 exit(1);
1745 }
1746
1747 debug("sshd version %s, %s", SSH_VERSION,
1748 #ifdef WITH_OPENSSL
1749 SSLeay_version(SSLEAY_VERSION)
1750 #else
1751 "without OpenSSL"
1752 #endif
1753 );
1754
1755 /* Store privilege separation user for later use if required. */
1756 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1757 if (use_privsep || options.kerberos_authentication)
1758 fatal("Privilege separation user %s does not exist",
1759 SSH_PRIVSEP_USER);
1760 } else {
1761 if (privsep_pw->pw_passwd != NULL) {
1762 explicit_bzero(privsep_pw->pw_passwd,
1763 strlen(privsep_pw->pw_passwd));
1764 }
1765 privsep_pw = pwcopy(privsep_pw);
1766 if (privsep_pw->pw_passwd != NULL) {
1767 free(privsep_pw->pw_passwd);
1768 }
1769 privsep_pw->pw_passwd = xstrdup("*");
1770 }
1771 #if !defined(ANDROID)
1772 endpwent();
1773 #endif
1774
1775 /* load host keys */
1776 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1777 sizeof(Key *));
1778 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1779 sizeof(Key *));
1780
1781 if (options.host_key_agent) {
1782 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1783 setenv(SSH_AUTHSOCKET_ENV_NAME,
1784 options.host_key_agent, 1);
1785 if ((r = ssh_get_authentication_socket(NULL)) == 0)
1786 have_agent = 1;
1787 else
1788 error("Could not connect to agent \"%s\": %s",
1789 options.host_key_agent, ssh_err(r));
1790 }
1791
1792 for (i = 0; i < options.num_host_key_files; i++) {
1793 if (options.host_key_files[i] == NULL)
1794 continue;
1795 key = key_load_private(options.host_key_files[i], "", NULL);
1796 pubkey = key_load_public(options.host_key_files[i], NULL);
1797 if (pubkey == NULL && key != NULL)
1798 pubkey = key_demote(key);
1799 sensitive_data.host_keys[i] = key;
1800 sensitive_data.host_pubkeys[i] = pubkey;
1801
1802 if (key == NULL && pubkey != NULL && pubkey->type != KEY_RSA1 &&
1803 have_agent) {
1804 debug("will rely on agent for hostkey %s",
1805 options.host_key_files[i]);
1806 keytype = pubkey->type;
1807 } else if (key != NULL) {
1808 keytype = key->type;
1809 } else {
1810 error("Could not load host key: %s",
1811 options.host_key_files[i]);
1812 sensitive_data.host_keys[i] = NULL;
1813 sensitive_data.host_pubkeys[i] = NULL;
1814 continue;
1815 }
1816
1817 switch (keytype) {
1818 case KEY_RSA1:
1819 sensitive_data.ssh1_host_key = key;
1820 sensitive_data.have_ssh1_key = 1;
1821 break;
1822 case KEY_RSA:
1823 case KEY_DSA:
1824 case KEY_ECDSA:
1825 case KEY_ED25519:
1826 if (have_agent || key != NULL)
1827 sensitive_data.have_ssh2_key = 1;
1828 break;
1829 }
1830 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1831 SSH_FP_DEFAULT)) == NULL)
1832 fatal("sshkey_fingerprint failed");
1833 debug("%s host key #%d: %s %s",
1834 key ? "private" : "agent", i, keytype == KEY_RSA1 ?
1835 sshkey_type(pubkey) : sshkey_ssh_name(pubkey), fp);
1836 free(fp);
1837 }
1838 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1839 logit("Disabling protocol version 1. Could not load host key");
1840 options.protocol &= ~SSH_PROTO_1;
1841 }
1842 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1843 logit("Disabling protocol version 2. Could not load host key");
1844 options.protocol &= ~SSH_PROTO_2;
1845 }
1846 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1847 logit("sshd: no hostkeys available -- exiting.");
1848 exit(1);
1849 }
1850
1851 /*
1852 * Load certificates. They are stored in an array at identical
1853 * indices to the public keys that they relate to.
1854 */
1855 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1856 sizeof(Key *));
1857 for (i = 0; i < options.num_host_key_files; i++)
1858 sensitive_data.host_certificates[i] = NULL;
1859
1860 for (i = 0; i < options.num_host_cert_files; i++) {
1861 if (options.host_cert_files[i] == NULL)
1862 continue;
1863 key = key_load_public(options.host_cert_files[i], NULL);
1864 if (key == NULL) {
1865 error("Could not load host certificate: %s",
1866 options.host_cert_files[i]);
1867 continue;
1868 }
1869 if (!key_is_cert(key)) {
1870 error("Certificate file is not a certificate: %s",
1871 options.host_cert_files[i]);
1872 key_free(key);
1873 continue;
1874 }
1875 /* Find matching private key */
1876 for (j = 0; j < options.num_host_key_files; j++) {
1877 if (key_equal_public(key,
1878 sensitive_data.host_keys[j])) {
1879 sensitive_data.host_certificates[j] = key;
1880 break;
1881 }
1882 }
1883 if (j >= options.num_host_key_files) {
1884 error("No matching private key for certificate: %s",
1885 options.host_cert_files[i]);
1886 key_free(key);
1887 continue;
1888 }
1889 sensitive_data.host_certificates[j] = key;
1890 debug("host certificate: #%d type %d %s", j, key->type,
1891 key_type(key));
1892 }
1893
1894 #ifdef WITH_SSH1
1895 /* Check certain values for sanity. */
1896 if (options.protocol & SSH_PROTO_1) {
1897 if (options.server_key_bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1898 options.server_key_bits > OPENSSL_RSA_MAX_MODULUS_BITS) {
1899 fprintf(stderr, "Bad server key size.\n");
1900 exit(1);
1901 }
1902 /*
1903 * Check that server and host key lengths differ sufficiently. This
1904 * is necessary to make double encryption work with rsaref. Oh, I
1905 * hate software patents. I dont know if this can go? Niels
1906 */
1907 if (options.server_key_bits >
1908 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1909 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1910 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1911 SSH_KEY_BITS_RESERVED) {
1912 options.server_key_bits =
1913 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1914 SSH_KEY_BITS_RESERVED;
1915 debug("Forcing server key to %d bits to make it differ from host key.",
1916 options.server_key_bits);
1917 }
1918 }
1919 #endif
1920
1921 if (use_privsep) {
1922 struct stat st;
1923
1924 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1925 (S_ISDIR(st.st_mode) == 0))
1926 fatal("Missing privilege separation directory: %s",
1927 _PATH_PRIVSEP_CHROOT_DIR);
1928
1929 #ifdef HAVE_CYGWIN
1930 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1931 (st.st_uid != getuid () ||
1932 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1933 #else
1934 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1935 #endif
1936 fatal("%s must be owned by root and not group or "
1937 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1938 }
1939
1940 if (test_flag > 1) {
1941 if (server_match_spec_complete(connection_info) == 1)
1942 parse_server_match_config(&options, connection_info);
1943 dump_config(&options);
1944 }
1945
1946 /* Configuration looks good, so exit if in test mode. */
1947 if (test_flag)
1948 exit(0);
1949
1950 /*
1951 * Clear out any supplemental groups we may have inherited. This
1952 * prevents inadvertent creation of files with bad modes (in the
1953 * portable version at least, it's certainly possible for PAM
1954 * to create a file, and we can't control the code in every
1955 * module which might be used).
1956 */
1957 if (setgroups(0, NULL) < 0)
1958 debug("setgroups() failed: %.200s", strerror(errno));
1959
1960 if (rexec_flag) {
1961 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1962 for (i = 0; i < rexec_argc; i++) {
1963 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1964 rexec_argv[i] = saved_argv[i];
1965 }
1966 rexec_argv[rexec_argc] = "-R";
1967 rexec_argv[rexec_argc + 1] = NULL;
1968 }
1969
1970 /* Ensure that umask disallows at least group and world write */
1971 new_umask = umask(0077) | 0022;
1972 (void) umask(new_umask);
1973
1974 /* Initialize the log (it is reinitialized below in case we forked). */
1975 if (debug_flag && (!inetd_flag || rexeced_flag))
1976 log_stderr = 1;
1977 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1978
1979 /*
1980 * If not in debugging mode, and not started from inetd, disconnect
1981 * from the controlling terminal, and fork. The original process
1982 * exits.
1983 */
1984 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1985 #ifdef TIOCNOTTY
1986 int fd;
1987 #endif /* TIOCNOTTY */
1988 if (daemon(0, 0) < 0)
1989 fatal("daemon() failed: %.200s", strerror(errno));
1990
1991 /* Disconnect from the controlling tty. */
1992 #ifdef TIOCNOTTY
1993 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1994 if (fd >= 0) {
1995 (void) ioctl(fd, TIOCNOTTY, NULL);
1996 close(fd);
1997 }
1998 #endif /* TIOCNOTTY */
1999 }
2000 /* Reinitialize the log (because of the fork above). */
2001 log_init(__progname, options.log_level, options.log_facility, log_stderr);
2002
2003 /* Chdir to the root directory so that the current disk can be
2004 unmounted if desired. */
2005 if (chdir("/") == -1)
2006 error("chdir(\"/\"): %s", strerror(errno));
2007
2008 /* ignore SIGPIPE */
2009 signal(SIGPIPE, SIG_IGN);
2010
2011 /* Get a connection, either from inetd or a listening TCP socket */
2012 if (inetd_flag) {
2013 server_accept_inetd(&sock_in, &sock_out);
2014 } else {
2015 platform_pre_listen();
2016 server_listen();
2017
2018 if (options.protocol & SSH_PROTO_1)
2019 generate_ephemeral_server_key();
2020
2021 signal(SIGHUP, sighup_handler);
2022 signal(SIGCHLD, main_sigchld_handler);
2023 signal(SIGTERM, sigterm_handler);
2024 signal(SIGQUIT, sigterm_handler);
2025
2026 /*
2027 * Write out the pid file after the sigterm handler
2028 * is setup and the listen sockets are bound
2029 */
2030 if (options.pid_file != NULL && !debug_flag) {
2031 FILE *f = fopen(options.pid_file, "w");
2032
2033 if (f == NULL) {
2034 error("Couldn't create pid file \"%s\": %s",
2035 options.pid_file, strerror(errno));
2036 } else {
2037 fprintf(f, "%ld\n", (long) getpid());
2038 fclose(f);
2039 }
2040 }
2041
2042 /* Accept a connection and return in a forked child */
2043 server_accept_loop(&sock_in, &sock_out,
2044 &newsock, config_s);
2045 }
2046
2047 /* This is the child processing a new connection. */
2048 setproctitle("%s", "[accepted]");
2049
2050 /*
2051 * Create a new session and process group since the 4.4BSD
2052 * setlogin() affects the entire process group. We don't
2053 * want the child to be able to affect the parent.
2054 */
2055 #if !defined(SSHD_ACQUIRES_CTTY)
2056 /*
2057 * If setsid is called, on some platforms sshd will later acquire a
2058 * controlling terminal which will result in "could not set
2059 * controlling tty" errors.
2060 */
2061 if (!debug_flag && !inetd_flag && setsid() < 0)
2062 error("setsid: %.100s", strerror(errno));
2063 #endif
2064
2065 if (rexec_flag) {
2066 int fd;
2067
2068 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
2069 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2070 dup2(newsock, STDIN_FILENO);
2071 dup2(STDIN_FILENO, STDOUT_FILENO);
2072 if (startup_pipe == -1)
2073 close(REEXEC_STARTUP_PIPE_FD);
2074 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
2075 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
2076 close(startup_pipe);
2077 startup_pipe = REEXEC_STARTUP_PIPE_FD;
2078 }
2079
2080 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
2081 close(config_s[1]);
2082
2083 execv(rexec_argv[0], rexec_argv);
2084
2085 /* Reexec has failed, fall back and continue */
2086 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
2087 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
2088 log_init(__progname, options.log_level,
2089 options.log_facility, log_stderr);
2090
2091 /* Clean up fds */
2092 close(REEXEC_CONFIG_PASS_FD);
2093 newsock = sock_out = sock_in = dup(STDIN_FILENO);
2094 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2095 dup2(fd, STDIN_FILENO);
2096 dup2(fd, STDOUT_FILENO);
2097 if (fd > STDERR_FILENO)
2098 close(fd);
2099 }
2100 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2101 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2102 }
2103
2104 /* Executed child processes don't need these. */
2105 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2106 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2107
2108 /*
2109 * Disable the key regeneration alarm. We will not regenerate the
2110 * key since we are no longer in a position to give it to anyone. We
2111 * will not restart on SIGHUP since it no longer makes sense.
2112 */
2113 alarm(0);
2114 signal(SIGALRM, SIG_DFL);
2115 signal(SIGHUP, SIG_DFL);
2116 signal(SIGTERM, SIG_DFL);
2117 signal(SIGQUIT, SIG_DFL);
2118 signal(SIGCHLD, SIG_DFL);
2119 signal(SIGINT, SIG_DFL);
2120
2121 /*
2122 * Register our connection. This turns encryption off because we do
2123 * not have a key.
2124 */
2125 packet_set_connection(sock_in, sock_out);
2126 packet_set_server();
2127
2128 /* Set SO_KEEPALIVE if requested. */
2129 if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2130 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2131 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2132
2133 if ((remote_port = get_remote_port()) < 0) {
2134 debug("get_remote_port failed");
2135 cleanup_exit(255);
2136 }
2137
2138 /*
2139 * We use get_canonical_hostname with usedns = 0 instead of
2140 * get_remote_ipaddr here so IP options will be checked.
2141 */
2142 (void) get_canonical_hostname(0);
2143 /*
2144 * The rest of the code depends on the fact that
2145 * get_remote_ipaddr() caches the remote ip, even if
2146 * the socket goes away.
2147 */
2148 remote_ip = get_remote_ipaddr();
2149
2150 #ifdef SSH_AUDIT_EVENTS
2151 audit_connection_from(remote_ip, remote_port);
2152 #endif
2153
2154 /* Log the connection. */
2155 laddr = get_local_ipaddr(sock_in);
2156 verbose("Connection from %s port %d on %s port %d",
2157 remote_ip, remote_port, laddr, get_local_port());
2158 free(laddr);
2159
2160 /*
2161 * We don't want to listen forever unless the other side
2162 * successfully authenticates itself. So we set up an alarm which is
2163 * cleared after successful authentication. A limit of zero
2164 * indicates no limit. Note that we don't set the alarm in debugging
2165 * mode; it is just annoying to have the server exit just when you
2166 * are about to discover the bug.
2167 */
2168 signal(SIGALRM, grace_alarm_handler);
2169 if (!debug_flag)
2170 alarm(options.login_grace_time);
2171
2172 sshd_exchange_identification(sock_in, sock_out);
2173
2174 /* In inetd mode, generate ephemeral key only for proto 1 connections */
2175 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2176 generate_ephemeral_server_key();
2177
2178 packet_set_nonblocking();
2179
2180 /* allocate authentication context */
2181 authctxt = xcalloc(1, sizeof(*authctxt));
2182
2183 authctxt->loginmsg = &loginmsg;
2184
2185 /* XXX global for cleanup, access from other modules */
2186 the_authctxt = authctxt;
2187
2188 /* prepare buffer to collect messages to display to user after login */
2189 buffer_init(&loginmsg);
2190 auth_debug_reset();
2191
2192 if (use_privsep) {
2193 if (privsep_preauth(authctxt) == 1)
2194 goto authenticated;
2195 } else if (compat20 && have_agent) {
2196 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2197 error("Unable to get agent socket: %s", ssh_err(r));
2198 have_agent = 0;
2199 }
2200 }
2201
2202 /* perform the key exchange */
2203 /* authenticate user and start session */
2204 if (compat20) {
2205 do_ssh2_kex();
2206 do_authentication2(authctxt);
2207 } else {
2208 #ifdef WITH_SSH1
2209 do_ssh1_kex();
2210 do_authentication(authctxt);
2211 #else
2212 fatal("ssh1 not supported");
2213 #endif
2214 }
2215 /*
2216 * If we use privilege separation, the unprivileged child transfers
2217 * the current keystate and exits
2218 */
2219 if (use_privsep) {
2220 mm_send_keystate(pmonitor);
2221 exit(0);
2222 }
2223
2224 authenticated:
2225 /*
2226 * Cancel the alarm we set to limit the time taken for
2227 * authentication.
2228 */
2229 alarm(0);
2230 signal(SIGALRM, SIG_DFL);
2231 authctxt->authenticated = 1;
2232 if (startup_pipe != -1) {
2233 close(startup_pipe);
2234 startup_pipe = -1;
2235 }
2236
2237 #ifdef SSH_AUDIT_EVENTS
2238 audit_event(SSH_AUTH_SUCCESS);
2239 #endif
2240
2241 #ifdef GSSAPI
2242 if (options.gss_authentication) {
2243 temporarily_use_uid(authctxt->pw);
2244 ssh_gssapi_storecreds();
2245 restore_uid();
2246 }
2247 #endif
2248 #ifdef USE_PAM
2249 if (options.use_pam) {
2250 do_pam_setcred(1);
2251 do_pam_session();
2252 }
2253 #endif
2254
2255 /*
2256 * In privilege separation, we fork another child and prepare
2257 * file descriptor passing.
2258 */
2259 if (use_privsep) {
2260 privsep_postauth(authctxt);
2261 /* the monitor process [priv] will not return */
2262 if (!compat20)
2263 destroy_sensitive_data();
2264 }
2265
2266 packet_set_timeout(options.client_alive_interval,
2267 options.client_alive_count_max);
2268
2269 /* Try to send all our hostkeys to the client */
2270 if (compat20)
2271 notify_hostkeys(active_state);
2272
2273 /* Start session. */
2274 do_authenticated(authctxt);
2275
2276 /* The connection has been terminated. */
2277 packet_get_bytes(&ibytes, &obytes);
2278 verbose("Transferred: sent %llu, received %llu bytes",
2279 (unsigned long long)obytes, (unsigned long long)ibytes);
2280
2281 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2282
2283 #ifdef USE_PAM
2284 if (options.use_pam)
2285 finish_pam();
2286 #endif /* USE_PAM */
2287
2288 #ifdef SSH_AUDIT_EVENTS
2289 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2290 #endif
2291
2292 packet_close();
2293
2294 if (use_privsep)
2295 mm_terminate();
2296
2297 exit(0);
2298 }
2299
2300 #ifdef WITH_SSH1
2301 /*
2302 * Decrypt session_key_int using our private server key and private host key
2303 * (key with larger modulus first).
2304 */
2305 int
2306 ssh1_session_key(BIGNUM *session_key_int)
2307 {
2308 int rsafail = 0;
2309
2310 if (BN_cmp(sensitive_data.server_key->rsa->n,
2311 sensitive_data.ssh1_host_key->rsa->n) > 0) {
2312 /* Server key has bigger modulus. */
2313 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2314 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2315 SSH_KEY_BITS_RESERVED) {
2316 fatal("do_connection: %s: "
2317 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2318 get_remote_ipaddr(),
2319 BN_num_bits(sensitive_data.server_key->rsa->n),
2320 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2321 SSH_KEY_BITS_RESERVED);
2322 }
2323 if (rsa_private_decrypt(session_key_int, session_key_int,
2324 sensitive_data.server_key->rsa) != 0)
2325 rsafail++;
2326 if (rsa_private_decrypt(session_key_int, session_key_int,
2327 sensitive_data.ssh1_host_key->rsa) != 0)
2328 rsafail++;
2329 } else {
2330 /* Host key has bigger modulus (or they are equal). */
2331 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2332 BN_num_bits(sensitive_data.server_key->rsa->n) +
2333 SSH_KEY_BITS_RESERVED) {
2334 fatal("do_connection: %s: "
2335 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2336 get_remote_ipaddr(),
2337 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2338 BN_num_bits(sensitive_data.server_key->rsa->n),
2339 SSH_KEY_BITS_RESERVED);
2340 }
2341 if (rsa_private_decrypt(session_key_int, session_key_int,
2342 sensitive_data.ssh1_host_key->rsa) != 0)
2343 rsafail++;
2344 if (rsa_private_decrypt(session_key_int, session_key_int,
2345 sensitive_data.server_key->rsa) != 0)
2346 rsafail++;
2347 }
2348 return (rsafail);
2349 }
2350
2351 /*
2352 * SSH1 key exchange
2353 */
2354 static void
2355 do_ssh1_kex(void)
2356 {
2357 int i, len;
2358 int rsafail = 0;
2359 BIGNUM *session_key_int, *fake_key_int, *real_key_int;
2360 u_char session_key[SSH_SESSION_KEY_LENGTH];
2361 u_char fake_key_bytes[4096 / 8];
2362 size_t fake_key_len;
2363 u_char cookie[8];
2364 u_int cipher_type, auth_mask, protocol_flags;
2365
2366 /*
2367 * Generate check bytes that the client must send back in the user
2368 * packet in order for it to be accepted; this is used to defy ip
2369 * spoofing attacks. Note that this only works against somebody
2370 * doing IP spoofing from a remote machine; any machine on the local
2371 * network can still see outgoing packets and catch the random
2372 * cookie. This only affects rhosts authentication, and this is one
2373 * of the reasons why it is inherently insecure.
2374 */
2375 arc4random_buf(cookie, sizeof(cookie));
2376
2377 /*
2378 * Send our public key. We include in the packet 64 bits of random
2379 * data that must be matched in the reply in order to prevent IP
2380 * spoofing.
2381 */
2382 packet_start(SSH_SMSG_PUBLIC_KEY);
2383 for (i = 0; i < 8; i++)
2384 packet_put_char(cookie[i]);
2385
2386 /* Store our public server RSA key. */
2387 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2388 packet_put_bignum(sensitive_data.server_key->rsa->e);
2389 packet_put_bignum(sensitive_data.server_key->rsa->n);
2390
2391 /* Store our public host RSA key. */
2392 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2393 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2394 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2395
2396 /* Put protocol flags. */
2397 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2398
2399 /* Declare which ciphers we support. */
2400 packet_put_int(cipher_mask_ssh1(0));
2401
2402 /* Declare supported authentication types. */
2403 auth_mask = 0;
2404 if (options.rhosts_rsa_authentication)
2405 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2406 if (options.rsa_authentication)
2407 auth_mask |= 1 << SSH_AUTH_RSA;
2408 if (options.challenge_response_authentication == 1)
2409 auth_mask |= 1 << SSH_AUTH_TIS;
2410 if (options.password_authentication)
2411 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2412 packet_put_int(auth_mask);
2413
2414 /* Send the packet and wait for it to be sent. */
2415 packet_send();
2416 packet_write_wait();
2417
2418 debug("Sent %d bit server key and %d bit host key.",
2419 BN_num_bits(sensitive_data.server_key->rsa->n),
2420 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2421
2422 /* Read clients reply (cipher type and session key). */
2423 packet_read_expect(SSH_CMSG_SESSION_KEY);
2424
2425 /* Get cipher type and check whether we accept this. */
2426 cipher_type = packet_get_char();
2427
2428 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2429 packet_disconnect("Warning: client selects unsupported cipher.");
2430
2431 /* Get check bytes from the packet. These must match those we
2432 sent earlier with the public key packet. */
2433 for (i = 0; i < 8; i++)
2434 if (cookie[i] != packet_get_char())
2435 packet_disconnect("IP Spoofing check bytes do not match.");
2436
2437 debug("Encryption type: %.200s", cipher_name(cipher_type));
2438
2439 /* Get the encrypted integer. */
2440 if ((real_key_int = BN_new()) == NULL)
2441 fatal("do_ssh1_kex: BN_new failed");
2442 packet_get_bignum(real_key_int);
2443
2444 protocol_flags = packet_get_int();
2445 packet_set_protocol_flags(protocol_flags);
2446 packet_check_eom();
2447
2448 /* Setup a fake key in case RSA decryption fails */
2449 if ((fake_key_int = BN_new()) == NULL)
2450 fatal("do_ssh1_kex: BN_new failed");
2451 fake_key_len = BN_num_bytes(real_key_int);
2452 if (fake_key_len > sizeof(fake_key_bytes))
2453 fake_key_len = sizeof(fake_key_bytes);
2454 arc4random_buf(fake_key_bytes, fake_key_len);
2455 if (BN_bin2bn(fake_key_bytes, fake_key_len, fake_key_int) == NULL)
2456 fatal("do_ssh1_kex: BN_bin2bn failed");
2457
2458 /* Decrypt real_key_int using host/server keys */
2459 rsafail = PRIVSEP(ssh1_session_key(real_key_int));
2460 /* If decryption failed, use the fake key. Else, the real key. */
2461 if (rsafail)
2462 session_key_int = fake_key_int;
2463 else
2464 session_key_int = real_key_int;
2465
2466 /*
2467 * Extract session key from the decrypted integer. The key is in the
2468 * least significant 256 bits of the integer; the first byte of the
2469 * key is in the highest bits.
2470 */
2471 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2472 len = BN_num_bytes(session_key_int);
2473 if (len < 0 || (u_int)len > sizeof(session_key)) {
2474 error("do_ssh1_kex: bad session key len from %s: "
2475 "session_key_int %d > sizeof(session_key) %lu",
2476 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
2477 rsafail++;
2478 } else {
2479 explicit_bzero(session_key, sizeof(session_key));
2480 BN_bn2bin(session_key_int,
2481 session_key + sizeof(session_key) - len);
2482
2483 derive_ssh1_session_id(
2484 sensitive_data.ssh1_host_key->rsa->n,
2485 sensitive_data.server_key->rsa->n,
2486 cookie, session_id);
2487 /*
2488 * Xor the first 16 bytes of the session key with the
2489 * session id.
2490 */
2491 for (i = 0; i < 16; i++)
2492 session_key[i] ^= session_id[i];
2493 }
2494
2495 /* Destroy the private and public keys. No longer. */
2496 destroy_sensitive_data();
2497
2498 if (use_privsep)
2499 mm_ssh1_session_id(session_id);
2500
2501 /* Destroy the decrypted integer. It is no longer needed. */
2502 BN_clear_free(real_key_int);
2503 BN_clear_free(fake_key_int);
2504
2505 /* Set the session key. From this on all communications will be encrypted. */
2506 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2507
2508 /* Destroy our copy of the session key. It is no longer needed. */
2509 explicit_bzero(session_key, sizeof(session_key));
2510
2511 debug("Received session key; encryption turned on.");
2512
2513 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2514 packet_start(SSH_SMSG_SUCCESS);
2515 packet_send();
2516 packet_write_wait();
2517 }
2518 #endif
2519
2520 int
2521 sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen,
2522 const u_char *data, size_t dlen, u_int flag)
2523 {
2524 int r;
2525 u_int xxx_slen, xxx_dlen = dlen;
2526
2527 if (privkey) {
2528 if (PRIVSEP(key_sign(privkey, signature, &xxx_slen, data, xxx_dlen) < 0))
2529 fatal("%s: key_sign failed", __func__);
2530 if (slen)
2531 *slen = xxx_slen;
2532 } else if (use_privsep) {
2533 if (mm_key_sign(pubkey, signature, &xxx_slen, data, xxx_dlen) < 0)
2534 fatal("%s: pubkey_sign failed", __func__);
2535 if (slen)
2536 *slen = xxx_slen;
2537 } else {
2538 if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slen,
2539 data, dlen, datafellows)) != 0)
2540 fatal("%s: ssh_agent_sign failed: %s",
2541 __func__, ssh_err(r));
2542 }
2543 return 0;
2544 }
2545
2546 /* SSH2 key exchange */
2547 static void
2548 do_ssh2_kex(void)
2549 {
2550 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2551 struct kex *kex;
2552 int r;
2553
2554 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2555 options.kex_algorithms);
2556 myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
2557 options.ciphers);
2558 myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
2559 options.ciphers);
2560 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2561 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2562
2563 if (options.compression == COMP_NONE) {
2564 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2565 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2566 } else if (options.compression == COMP_DELAYED) {
2567 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2568 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
2569 }
2570
2571 if (options.rekey_limit || options.rekey_interval)
2572 packet_set_rekey_limits((u_int32_t)options.rekey_limit,
2573 (time_t)options.rekey_interval);
2574
2575 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2576 list_hostkey_types());
2577
2578 /* start key exchange */
2579 if ((r = kex_setup(active_state, myproposal)) != 0)
2580 fatal("kex_setup: %s", ssh_err(r));
2581 kex = active_state->kex;
2582 #ifdef WITH_OPENSSL
2583 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2584 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2585 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2586 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2587 # ifdef OPENSSL_HAS_ECC
2588 kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2589 # endif
2590 #endif
2591 kex->kex[KEX_C25519_SHA256] = kexc25519_server;
2592 kex->server = 1;
2593 kex->client_version_string=client_version_string;
2594 kex->server_version_string=server_version_string;
2595 kex->load_host_public_key=&get_hostkey_public_by_type;
2596 kex->load_host_private_key=&get_hostkey_private_by_type;
2597 kex->host_key_index=&get_hostkey_index;
2598 kex->sign = sshd_hostkey_sign;
2599
2600 dispatch_run(DISPATCH_BLOCK, &kex->done, active_state);
2601
2602 session_id2 = kex->session_id;
2603 session_id2_len = kex->session_id_len;
2604
2605 #ifdef DEBUG_KEXDH
2606 /* send 1st encrypted/maced/compressed message */
2607 packet_start(SSH2_MSG_IGNORE);
2608 packet_put_cstring("markus");
2609 packet_send();
2610 packet_write_wait();
2611 #endif
2612 debug("KEX done");
2613 }
2614
2615 /* server specific fatal cleanup */
2616 void
2617 cleanup_exit(int i)
2618 {
2619 if (the_authctxt) {
2620 do_cleanup(the_authctxt);
2621 if (use_privsep && privsep_is_preauth &&
2622 pmonitor != NULL && pmonitor->m_pid > 1) {
2623 debug("Killing privsep child %d", pmonitor->m_pid);
2624 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2625 errno != ESRCH)
2626 error("%s: kill(%d): %s", __func__,
2627 pmonitor->m_pid, strerror(errno));
2628 }
2629 }
2630 #ifdef SSH_AUDIT_EVENTS
2631 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2632 if (!use_privsep || mm_is_monitor())
2633 audit_event(SSH_CONNECTION_ABANDON);
2634 #endif
2635 _exit(i);
2636 }
2637