1 /* $OpenBSD: sshd.c,v 1.591 2022/09/17 10:34:29 djm 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 __RCSID("$FreeBSD: stable/12/crypto/openssh/sshd.c 372663 2022-10-26 16:48:40Z git2svn $");
47
48 #include <sys/types.h>
49 #include <sys/ioctl.h>
50 #include <sys/mman.h>
51 #include <sys/socket.h>
52 #ifdef HAVE_SYS_STAT_H
53 # include <sys/stat.h>
54 #endif
55 #ifdef HAVE_SYS_TIME_H
56 # include <sys/time.h>
57 #endif
58 #include "openbsd-compat/sys-tree.h"
59 #include "openbsd-compat/sys-queue.h"
60 #include <sys/wait.h>
61
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <netdb.h>
65 #ifdef HAVE_PATHS_H
66 #include <paths.h>
67 #endif
68 #include <grp.h>
69 #ifdef HAVE_POLL_H
70 #include <poll.h>
71 #endif
72 #include <pwd.h>
73 #include <signal.h>
74 #include <stdarg.h>
75 #include <stdio.h>
76 #include <stdlib.h>
77 #include <string.h>
78 #include <unistd.h>
79 #include <limits.h>
80
81 #ifdef WITH_OPENSSL
82 #include <openssl/dh.h>
83 #include <openssl/bn.h>
84 #include <openssl/rand.h>
85 #include "openbsd-compat/openssl-compat.h"
86 #endif
87
88 #ifdef HAVE_SECUREWARE
89 #include <sys/security.h>
90 #include <prot.h>
91 #endif
92
93 #ifdef __FreeBSD__
94 #include <resolv.h>
95 #if defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
96 #include <gssapi/gssapi.h>
97 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_H)
98 #include <gssapi.h>
99 #endif
100 #endif
101
102 #include "xmalloc.h"
103 #include "ssh.h"
104 #include "ssh2.h"
105 #include "sshpty.h"
106 #include "packet.h"
107 #include "log.h"
108 #include "sshbuf.h"
109 #include "misc.h"
110 #include "match.h"
111 #include "servconf.h"
112 #include "uidswap.h"
113 #include "compat.h"
114 #include "cipher.h"
115 #include "digest.h"
116 #include "sshkey.h"
117 #include "kex.h"
118 #include "myproposal.h"
119 #include "authfile.h"
120 #include "pathnames.h"
121 #include "atomicio.h"
122 #include "canohost.h"
123 #include "hostfile.h"
124 #include "auth.h"
125 #include "authfd.h"
126 #include "msg.h"
127 #include "dispatch.h"
128 #include "channels.h"
129 #include "session.h"
130 #include "monitor.h"
131 #ifdef GSSAPI
132 #include "ssh-gss.h"
133 #endif
134 #include "monitor_wrap.h"
135 #include "ssh-sandbox.h"
136 #include "auth-options.h"
137 #include "version.h"
138 #include "ssherr.h"
139 #include "sk-api.h"
140 #include "srclimit.h"
141 #include "dh.h"
142 #include "blacklist_client.h"
143
144 #ifdef LIBWRAP
145 #include <tcpd.h>
146 #include <syslog.h>
147 extern int allow_severity;
148 extern int deny_severity;
149 #endif /* LIBWRAP */
150
151 /* Re-exec fds */
152 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
153 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
154 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
155 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
156
157 extern char *__progname;
158
159 /* Server configuration options. */
160 ServerOptions options;
161
162 /* Name of the server configuration file. */
163 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
164
165 /*
166 * Debug mode flag. This can be set on the command line. If debug
167 * mode is enabled, extra debugging output will be sent to the system
168 * log, the daemon will not go to background, and will exit after processing
169 * the first connection.
170 */
171 int debug_flag = 0;
172
173 /*
174 * Indicating that the daemon should only test the configuration and keys.
175 * If test_flag > 1 ("-T" flag), then sshd will also dump the effective
176 * configuration, optionally using connection information provided by the
177 * "-C" flag.
178 */
179 static int test_flag = 0;
180
181 /* Flag indicating that the daemon is being started from inetd. */
182 static int inetd_flag = 0;
183
184 /* Flag indicating that sshd should not detach and become a daemon. */
185 static int no_daemon_flag = 0;
186
187 /* debug goes to stderr unless inetd_flag is set */
188 static int log_stderr = 0;
189
190 /* Saved arguments to main(). */
191 static char **saved_argv;
192 static int saved_argc;
193
194 /* re-exec */
195 static int rexeced_flag = 0;
196 static int rexec_flag = 1;
197 static int rexec_argc = 0;
198 static char **rexec_argv;
199
200 /*
201 * The sockets that the server is listening; this is used in the SIGHUP
202 * signal handler.
203 */
204 #define MAX_LISTEN_SOCKS 16
205 static int listen_socks[MAX_LISTEN_SOCKS];
206 static int num_listen_socks = 0;
207
208 /* Daemon's agent connection */
209 int auth_sock = -1;
210 static int have_agent = 0;
211
212 /*
213 * Any really sensitive data in the application is contained in this
214 * structure. The idea is that this structure could be locked into memory so
215 * that the pages do not get written into swap. However, there are some
216 * problems. The private key contains BIGNUMs, and we do not (in principle)
217 * have access to the internals of them, and locking just the structure is
218 * not very useful. Currently, memory locking is not implemented.
219 */
220 struct {
221 struct sshkey **host_keys; /* all private host keys */
222 struct sshkey **host_pubkeys; /* all public host keys */
223 struct sshkey **host_certificates; /* all public host certificates */
224 int have_ssh2_key;
225 } sensitive_data;
226
227 /* This is set to true when a signal is received. */
228 static volatile sig_atomic_t received_sighup = 0;
229 static volatile sig_atomic_t received_sigterm = 0;
230
231 /* record remote hostname or ip */
232 u_int utmp_len = HOST_NAME_MAX+1;
233
234 /*
235 * startup_pipes/flags are used for tracking children of the listening sshd
236 * process early in their lifespans. This tracking is needed for three things:
237 *
238 * 1) Implementing the MaxStartups limit of concurrent unauthenticated
239 * connections.
240 * 2) Avoiding a race condition for SIGHUP processing, where child processes
241 * may have listen_socks open that could collide with main listener process
242 * after it restarts.
243 * 3) Ensuring that rexec'd sshd processes have received their initial state
244 * from the parent listen process before handling SIGHUP.
245 *
246 * Child processes signal that they have completed closure of the listen_socks
247 * and (if applicable) received their rexec state by sending a char over their
248 * sock. Child processes signal that authentication has completed by closing
249 * the sock (or by exiting).
250 */
251 static int *startup_pipes = NULL;
252 static int *startup_flags = NULL; /* Indicates child closed listener */
253 static int startup_pipe = -1; /* in child */
254
255 /* variables used for privilege separation */
256 int use_privsep = -1;
257 struct monitor *pmonitor = NULL;
258 int privsep_is_preauth = 1;
259 static int privsep_chroot = 1;
260
261 /* global connection state and authentication contexts */
262 Authctxt *the_authctxt = NULL;
263 struct ssh *the_active_state;
264
265 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
266 struct sshauthopt *auth_opts = NULL;
267
268 /* sshd_config buffer */
269 struct sshbuf *cfg;
270
271 /* Included files from the configuration file */
272 struct include_list includes = TAILQ_HEAD_INITIALIZER(includes);
273
274 /* message to be displayed after login */
275 struct sshbuf *loginmsg;
276
277 /* Unprivileged user */
278 struct passwd *privsep_pw = NULL;
279
280 /* Prototypes for various functions defined later in this file. */
281 void destroy_sensitive_data(void);
282 void demote_sensitive_data(void);
283 static void do_ssh2_kex(struct ssh *);
284
285 static char *listener_proctitle;
286
287 /*
288 * Close all listening sockets
289 */
290 static void
close_listen_socks(void)291 close_listen_socks(void)
292 {
293 int i;
294
295 for (i = 0; i < num_listen_socks; i++)
296 close(listen_socks[i]);
297 num_listen_socks = 0;
298 }
299
300 static void
close_startup_pipes(void)301 close_startup_pipes(void)
302 {
303 int i;
304
305 if (startup_pipes)
306 for (i = 0; i < options.max_startups; i++)
307 if (startup_pipes[i] != -1)
308 close(startup_pipes[i]);
309 }
310
311 /*
312 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
313 * the effect is to reread the configuration file (and to regenerate
314 * the server key).
315 */
316
317 /*ARGSUSED*/
318 static void
sighup_handler(int sig)319 sighup_handler(int sig)
320 {
321 received_sighup = 1;
322 }
323
324 /*
325 * Called from the main program after receiving SIGHUP.
326 * Restarts the server.
327 */
328 static void
sighup_restart(void)329 sighup_restart(void)
330 {
331 logit("Received SIGHUP; restarting.");
332 if (options.pid_file != NULL)
333 unlink(options.pid_file);
334 platform_pre_restart();
335 close_listen_socks();
336 close_startup_pipes();
337 ssh_signal(SIGHUP, SIG_IGN); /* will be restored after exec */
338 execv(saved_argv[0], saved_argv);
339 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
340 strerror(errno));
341 exit(1);
342 }
343
344 /*
345 * Generic signal handler for terminating signals in the master daemon.
346 */
347 /*ARGSUSED*/
348 static void
sigterm_handler(int sig)349 sigterm_handler(int sig)
350 {
351 received_sigterm = sig;
352 }
353
354 /*
355 * SIGCHLD handler. This is called whenever a child dies. This will then
356 * reap any zombies left by exited children.
357 */
358 /*ARGSUSED*/
359 static void
main_sigchld_handler(int sig)360 main_sigchld_handler(int sig)
361 {
362 int save_errno = errno;
363 pid_t pid;
364 int status;
365
366 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
367 (pid == -1 && errno == EINTR))
368 ;
369 errno = save_errno;
370 }
371
372 /*
373 * Signal handler for the alarm after the login grace period has expired.
374 */
375 /*ARGSUSED*/
376 static void
grace_alarm_handler(int sig)377 grace_alarm_handler(int sig)
378 {
379 /*
380 * Try to kill any processes that we have spawned, E.g. authorized
381 * keys command helpers or privsep children.
382 */
383 if (getpgid(0) == getpid()) {
384 ssh_signal(SIGTERM, SIG_IGN);
385 kill(0, SIGTERM);
386 }
387
388 BLACKLIST_NOTIFY(the_active_state, BLACKLIST_AUTH_FAIL, "ssh");
389
390 /* Log error and exit. */
391 sigdie("Timeout before authentication for %s port %d",
392 ssh_remote_ipaddr(the_active_state),
393 ssh_remote_port(the_active_state));
394 }
395
396 /* Destroy the host and server keys. They will no longer be needed. */
397 void
destroy_sensitive_data(void)398 destroy_sensitive_data(void)
399 {
400 u_int i;
401
402 for (i = 0; i < options.num_host_key_files; i++) {
403 if (sensitive_data.host_keys[i]) {
404 sshkey_free(sensitive_data.host_keys[i]);
405 sensitive_data.host_keys[i] = NULL;
406 }
407 if (sensitive_data.host_certificates[i]) {
408 sshkey_free(sensitive_data.host_certificates[i]);
409 sensitive_data.host_certificates[i] = NULL;
410 }
411 }
412 }
413
414 /* Demote private to public keys for network child */
415 void
demote_sensitive_data(void)416 demote_sensitive_data(void)
417 {
418 struct sshkey *tmp;
419 u_int i;
420 int r;
421
422 for (i = 0; i < options.num_host_key_files; i++) {
423 if (sensitive_data.host_keys[i]) {
424 if ((r = sshkey_from_private(
425 sensitive_data.host_keys[i], &tmp)) != 0)
426 fatal_r(r, "could not demote host %s key",
427 sshkey_type(sensitive_data.host_keys[i]));
428 sshkey_free(sensitive_data.host_keys[i]);
429 sensitive_data.host_keys[i] = tmp;
430 }
431 /* Certs do not need demotion */
432 }
433 }
434
435 static void
reseed_prngs(void)436 reseed_prngs(void)
437 {
438 u_int32_t rnd[256];
439
440 #ifdef WITH_OPENSSL
441 RAND_poll();
442 #endif
443 arc4random_stir(); /* noop on recent arc4random() implementations */
444 arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
445
446 #ifdef WITH_OPENSSL
447 RAND_seed(rnd, sizeof(rnd));
448 /* give libcrypto a chance to notice the PID change */
449 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
450 fatal("%s: RAND_bytes failed", __func__);
451 #endif
452
453 explicit_bzero(rnd, sizeof(rnd));
454 }
455
456 static void
privsep_preauth_child(void)457 privsep_preauth_child(void)
458 {
459 gid_t gidset[1];
460
461 /* Enable challenge-response authentication for privilege separation */
462 privsep_challenge_enable();
463
464 #ifdef GSSAPI
465 /* Cache supported mechanism OIDs for later use */
466 ssh_gssapi_prepare_supported_oids();
467 #endif
468
469 reseed_prngs();
470
471 /* Demote the private keys to public keys. */
472 demote_sensitive_data();
473
474 /* Demote the child */
475 if (privsep_chroot) {
476 /* Change our root directory */
477 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
478 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
479 strerror(errno));
480 if (chdir("/") == -1)
481 fatal("chdir(\"/\"): %s", strerror(errno));
482
483 /* Drop our privileges */
484 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
485 (u_int)privsep_pw->pw_gid);
486 gidset[0] = privsep_pw->pw_gid;
487 if (setgroups(1, gidset) == -1)
488 fatal("setgroups: %.100s", strerror(errno));
489 permanently_set_uid(privsep_pw);
490 }
491 }
492
493 static int
privsep_preauth(struct ssh * ssh)494 privsep_preauth(struct ssh *ssh)
495 {
496 int status, r;
497 pid_t pid;
498 struct ssh_sandbox *box = NULL;
499
500 /* Set up unprivileged child process to deal with network data */
501 pmonitor = monitor_init();
502 /* Store a pointer to the kex for later rekeying */
503 pmonitor->m_pkex = &ssh->kex;
504
505 if (use_privsep == PRIVSEP_ON)
506 box = ssh_sandbox_init(pmonitor);
507 pid = fork();
508 if (pid == -1) {
509 fatal("fork of unprivileged child failed");
510 } else if (pid != 0) {
511 debug2("Network child is on pid %ld", (long)pid);
512
513 pmonitor->m_pid = pid;
514 if (have_agent) {
515 r = ssh_get_authentication_socket(&auth_sock);
516 if (r != 0) {
517 error_r(r, "Could not get agent socket");
518 have_agent = 0;
519 }
520 }
521 if (box != NULL)
522 ssh_sandbox_parent_preauth(box, pid);
523 monitor_child_preauth(ssh, pmonitor);
524
525 /* Wait for the child's exit status */
526 while (waitpid(pid, &status, 0) == -1) {
527 if (errno == EINTR)
528 continue;
529 pmonitor->m_pid = -1;
530 fatal_f("waitpid: %s", strerror(errno));
531 }
532 privsep_is_preauth = 0;
533 pmonitor->m_pid = -1;
534 if (WIFEXITED(status)) {
535 if (WEXITSTATUS(status) != 0)
536 fatal_f("preauth child exited with status %d",
537 WEXITSTATUS(status));
538 } else if (WIFSIGNALED(status))
539 fatal_f("preauth child terminated by signal %d",
540 WTERMSIG(status));
541 if (box != NULL)
542 ssh_sandbox_parent_finish(box);
543 return 1;
544 } else {
545 /* child */
546 close(pmonitor->m_sendfd);
547 close(pmonitor->m_log_recvfd);
548
549 /* Arrange for logging to be sent to the monitor */
550 set_log_handler(mm_log_handler, pmonitor);
551
552 privsep_preauth_child();
553 setproctitle("%s", "[net]");
554 if (box != NULL)
555 ssh_sandbox_child(box);
556
557 return 0;
558 }
559 }
560
561 static void
privsep_postauth(struct ssh * ssh,Authctxt * authctxt)562 privsep_postauth(struct ssh *ssh, Authctxt *authctxt)
563 {
564 #ifdef DISABLE_FD_PASSING
565 if (1) {
566 #else
567 if (authctxt->pw->pw_uid == 0) {
568 #endif
569 /* File descriptor passing is broken or root login */
570 use_privsep = 0;
571 goto skip;
572 }
573
574 /* New socket pair */
575 monitor_reinit(pmonitor);
576
577 pmonitor->m_pid = fork();
578 if (pmonitor->m_pid == -1)
579 fatal("fork of unprivileged child failed");
580 else if (pmonitor->m_pid != 0) {
581 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
582 sshbuf_reset(loginmsg);
583 monitor_clear_keystate(ssh, pmonitor);
584 monitor_child_postauth(ssh, pmonitor);
585
586 /* NEVERREACHED */
587 exit(0);
588 }
589
590 /* child */
591
592 close(pmonitor->m_sendfd);
593 pmonitor->m_sendfd = -1;
594
595 /* Demote the private keys to public keys. */
596 demote_sensitive_data();
597
598 reseed_prngs();
599
600 /* Drop privileges */
601 do_setusercontext(authctxt->pw);
602
603 skip:
604 /* It is safe now to apply the key state */
605 monitor_apply_keystate(ssh, pmonitor);
606
607 /*
608 * Tell the packet layer that authentication was successful, since
609 * this information is not part of the key state.
610 */
611 ssh_packet_set_authenticated(ssh);
612 }
613
614 static void
615 append_hostkey_type(struct sshbuf *b, const char *s)
616 {
617 int r;
618
619 if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
620 debug3_f("%s key not permitted by HostkeyAlgorithms", s);
621 return;
622 }
623 if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
624 fatal_fr(r, "sshbuf_putf");
625 }
626
627 static char *
628 list_hostkey_types(void)
629 {
630 struct sshbuf *b;
631 struct sshkey *key;
632 char *ret;
633 u_int i;
634
635 if ((b = sshbuf_new()) == NULL)
636 fatal_f("sshbuf_new failed");
637 for (i = 0; i < options.num_host_key_files; i++) {
638 key = sensitive_data.host_keys[i];
639 if (key == NULL)
640 key = sensitive_data.host_pubkeys[i];
641 if (key == NULL)
642 continue;
643 switch (key->type) {
644 case KEY_RSA:
645 /* for RSA we also support SHA2 signatures */
646 append_hostkey_type(b, "rsa-sha2-512");
647 append_hostkey_type(b, "rsa-sha2-256");
648 /* FALLTHROUGH */
649 case KEY_DSA:
650 case KEY_ECDSA:
651 case KEY_ED25519:
652 case KEY_ECDSA_SK:
653 case KEY_ED25519_SK:
654 case KEY_XMSS:
655 append_hostkey_type(b, sshkey_ssh_name(key));
656 break;
657 }
658 /* If the private key has a cert peer, then list that too */
659 key = sensitive_data.host_certificates[i];
660 if (key == NULL)
661 continue;
662 switch (key->type) {
663 case KEY_RSA_CERT:
664 /* for RSA we also support SHA2 signatures */
665 append_hostkey_type(b,
666 "rsa-sha2-512-cert-v01@openssh.com");
667 append_hostkey_type(b,
668 "rsa-sha2-256-cert-v01@openssh.com");
669 /* FALLTHROUGH */
670 case KEY_DSA_CERT:
671 case KEY_ECDSA_CERT:
672 case KEY_ED25519_CERT:
673 case KEY_ECDSA_SK_CERT:
674 case KEY_ED25519_SK_CERT:
675 case KEY_XMSS_CERT:
676 append_hostkey_type(b, sshkey_ssh_name(key));
677 break;
678 }
679 }
680 if ((ret = sshbuf_dup_string(b)) == NULL)
681 fatal_f("sshbuf_dup_string failed");
682 sshbuf_free(b);
683 debug_f("%s", ret);
684 return ret;
685 }
686
687 static struct sshkey *
688 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
689 {
690 u_int i;
691 struct sshkey *key;
692
693 for (i = 0; i < options.num_host_key_files; i++) {
694 switch (type) {
695 case KEY_RSA_CERT:
696 case KEY_DSA_CERT:
697 case KEY_ECDSA_CERT:
698 case KEY_ED25519_CERT:
699 case KEY_ECDSA_SK_CERT:
700 case KEY_ED25519_SK_CERT:
701 case KEY_XMSS_CERT:
702 key = sensitive_data.host_certificates[i];
703 break;
704 default:
705 key = sensitive_data.host_keys[i];
706 if (key == NULL && !need_private)
707 key = sensitive_data.host_pubkeys[i];
708 break;
709 }
710 if (key == NULL || key->type != type)
711 continue;
712 switch (type) {
713 case KEY_ECDSA:
714 case KEY_ECDSA_SK:
715 case KEY_ECDSA_CERT:
716 case KEY_ECDSA_SK_CERT:
717 if (key->ecdsa_nid != nid)
718 continue;
719 /* FALLTHROUGH */
720 default:
721 return need_private ?
722 sensitive_data.host_keys[i] : key;
723 }
724 }
725 return NULL;
726 }
727
728 struct sshkey *
729 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
730 {
731 return get_hostkey_by_type(type, nid, 0, ssh);
732 }
733
734 struct sshkey *
735 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
736 {
737 return get_hostkey_by_type(type, nid, 1, ssh);
738 }
739
740 struct sshkey *
741 get_hostkey_by_index(int ind)
742 {
743 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
744 return (NULL);
745 return (sensitive_data.host_keys[ind]);
746 }
747
748 struct sshkey *
749 get_hostkey_public_by_index(int ind, struct ssh *ssh)
750 {
751 if (ind < 0 || (u_int)ind >= options.num_host_key_files)
752 return (NULL);
753 return (sensitive_data.host_pubkeys[ind]);
754 }
755
756 int
757 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
758 {
759 u_int i;
760
761 for (i = 0; i < options.num_host_key_files; i++) {
762 if (sshkey_is_cert(key)) {
763 if (key == sensitive_data.host_certificates[i] ||
764 (compare && sensitive_data.host_certificates[i] &&
765 sshkey_equal(key,
766 sensitive_data.host_certificates[i])))
767 return (i);
768 } else {
769 if (key == sensitive_data.host_keys[i] ||
770 (compare && sensitive_data.host_keys[i] &&
771 sshkey_equal(key, sensitive_data.host_keys[i])))
772 return (i);
773 if (key == sensitive_data.host_pubkeys[i] ||
774 (compare && sensitive_data.host_pubkeys[i] &&
775 sshkey_equal(key, sensitive_data.host_pubkeys[i])))
776 return (i);
777 }
778 }
779 return (-1);
780 }
781
782 /* Inform the client of all hostkeys */
783 static void
784 notify_hostkeys(struct ssh *ssh)
785 {
786 struct sshbuf *buf;
787 struct sshkey *key;
788 u_int i, nkeys;
789 int r;
790 char *fp;
791
792 /* Some clients cannot cope with the hostkeys message, skip those. */
793 if (ssh->compat & SSH_BUG_HOSTKEYS)
794 return;
795
796 if ((buf = sshbuf_new()) == NULL)
797 fatal_f("sshbuf_new");
798 for (i = nkeys = 0; i < options.num_host_key_files; i++) {
799 key = get_hostkey_public_by_index(i, ssh);
800 if (key == NULL || key->type == KEY_UNSPEC ||
801 sshkey_is_cert(key))
802 continue;
803 fp = sshkey_fingerprint(key, options.fingerprint_hash,
804 SSH_FP_DEFAULT);
805 debug3_f("key %d: %s %s", i, sshkey_ssh_name(key), fp);
806 free(fp);
807 if (nkeys == 0) {
808 /*
809 * Start building the request when we find the
810 * first usable key.
811 */
812 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
813 (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 ||
814 (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */
815 sshpkt_fatal(ssh, r, "%s: start request", __func__);
816 }
817 /* Append the key to the request */
818 sshbuf_reset(buf);
819 if ((r = sshkey_putb(key, buf)) != 0)
820 fatal_fr(r, "couldn't put hostkey %d", i);
821 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
822 sshpkt_fatal(ssh, r, "%s: append key", __func__);
823 nkeys++;
824 }
825 debug3_f("sent %u hostkeys", nkeys);
826 if (nkeys == 0)
827 fatal_f("no hostkeys");
828 if ((r = sshpkt_send(ssh)) != 0)
829 sshpkt_fatal(ssh, r, "%s: send", __func__);
830 sshbuf_free(buf);
831 }
832
833 /*
834 * returns 1 if connection should be dropped, 0 otherwise.
835 * dropping starts at connection #max_startups_begin with a probability
836 * of (max_startups_rate/100). the probability increases linearly until
837 * all connections are dropped for startups > max_startups
838 */
839 static int
840 should_drop_connection(int startups)
841 {
842 int p, r;
843
844 if (startups < options.max_startups_begin)
845 return 0;
846 if (startups >= options.max_startups)
847 return 1;
848 if (options.max_startups_rate == 100)
849 return 1;
850
851 p = 100 - options.max_startups_rate;
852 p *= startups - options.max_startups_begin;
853 p /= options.max_startups - options.max_startups_begin;
854 p += options.max_startups_rate;
855 r = arc4random_uniform(100);
856
857 debug_f("p %d, r %d", p, r);
858 return (r < p) ? 1 : 0;
859 }
860
861 /*
862 * Check whether connection should be accepted by MaxStartups.
863 * Returns 0 if the connection is accepted. If the connection is refused,
864 * returns 1 and attempts to send notification to client.
865 * Logs when the MaxStartups condition is entered or exited, and periodically
866 * while in that state.
867 */
868 static int
869 drop_connection(int sock, int startups, int notify_pipe)
870 {
871 char *laddr, *raddr;
872 const char msg[] = "Exceeded MaxStartups\r\n";
873 static time_t last_drop, first_drop;
874 static u_int ndropped;
875 LogLevel drop_level = SYSLOG_LEVEL_VERBOSE;
876 time_t now;
877
878 now = monotime();
879 if (!should_drop_connection(startups) &&
880 srclimit_check_allow(sock, notify_pipe) == 1) {
881 if (last_drop != 0 &&
882 startups < options.max_startups_begin - 1) {
883 /* XXX maybe need better hysteresis here */
884 logit("exited MaxStartups throttling after %s, "
885 "%u connections dropped",
886 fmt_timeframe(now - first_drop), ndropped);
887 last_drop = 0;
888 }
889 return 0;
890 }
891
892 #define SSHD_MAXSTARTUPS_LOG_INTERVAL (5 * 60)
893 if (last_drop == 0) {
894 error("beginning MaxStartups throttling");
895 drop_level = SYSLOG_LEVEL_INFO;
896 first_drop = now;
897 ndropped = 0;
898 } else if (last_drop + SSHD_MAXSTARTUPS_LOG_INTERVAL < now) {
899 /* Periodic logs */
900 error("in MaxStartups throttling for %s, "
901 "%u connections dropped",
902 fmt_timeframe(now - first_drop), ndropped + 1);
903 drop_level = SYSLOG_LEVEL_INFO;
904 }
905 last_drop = now;
906 ndropped++;
907
908 laddr = get_local_ipaddr(sock);
909 raddr = get_peer_ipaddr(sock);
910 do_log2(drop_level, "drop connection #%d from [%s]:%d on [%s]:%d "
911 "past MaxStartups", startups, raddr, get_peer_port(sock),
912 laddr, get_local_port(sock));
913 free(laddr);
914 free(raddr);
915 /* best-effort notification to client */
916 (void)write(sock, msg, sizeof(msg) - 1);
917 return 1;
918 }
919
920 static void
921 usage(void)
922 {
923 if (options.version_addendum != NULL &&
924 *options.version_addendum != '\0')
925 fprintf(stderr, "%s %s, %s\n",
926 SSH_RELEASE,
927 options.version_addendum, SSH_OPENSSL_VERSION);
928 else
929 fprintf(stderr, "%s, %s\n",
930 SSH_RELEASE, SSH_OPENSSL_VERSION);
931 fprintf(stderr,
932 "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
933 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
934 " [-h host_key_file] [-o option] [-p port] [-u len]\n"
935 );
936 exit(1);
937 }
938
939 static void
940 send_rexec_state(int fd, struct sshbuf *conf)
941 {
942 struct sshbuf *m = NULL, *inc = NULL;
943 struct include_item *item = NULL;
944 int r;
945
946 debug3_f("entering fd = %d config len %zu", fd,
947 sshbuf_len(conf));
948
949 if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
950 fatal_f("sshbuf_new failed");
951
952 /* pack includes into a string */
953 TAILQ_FOREACH(item, &includes, entry) {
954 if ((r = sshbuf_put_cstring(inc, item->selector)) != 0 ||
955 (r = sshbuf_put_cstring(inc, item->filename)) != 0 ||
956 (r = sshbuf_put_stringb(inc, item->contents)) != 0)
957 fatal_fr(r, "compose includes");
958 }
959
960 /*
961 * Protocol from reexec master to child:
962 * string configuration
963 * string included_files[] {
964 * string selector
965 * string filename
966 * string contents
967 * }
968 * string rng_seed (if required)
969 */
970 if ((r = sshbuf_put_stringb(m, conf)) != 0 ||
971 (r = sshbuf_put_stringb(m, inc)) != 0)
972 fatal_fr(r, "compose config");
973 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
974 rexec_send_rng_seed(m);
975 #endif
976 if (ssh_msg_send(fd, 0, m) == -1)
977 error_f("ssh_msg_send failed");
978
979 sshbuf_free(m);
980 sshbuf_free(inc);
981
982 debug3_f("done");
983 }
984
985 static void
986 recv_rexec_state(int fd, struct sshbuf *conf)
987 {
988 struct sshbuf *m, *inc;
989 u_char *cp, ver;
990 size_t len;
991 int r;
992 struct include_item *item;
993
994 debug3_f("entering fd = %d", fd);
995
996 if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
997 fatal_f("sshbuf_new failed");
998 if (ssh_msg_recv(fd, m) == -1)
999 fatal_f("ssh_msg_recv failed");
1000 if ((r = sshbuf_get_u8(m, &ver)) != 0)
1001 fatal_fr(r, "parse version");
1002 if (ver != 0)
1003 fatal_f("rexec version mismatch");
1004 if ((r = sshbuf_get_string(m, &cp, &len)) != 0 ||
1005 (r = sshbuf_get_stringb(m, inc)) != 0)
1006 fatal_fr(r, "parse config");
1007
1008 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1009 rexec_recv_rng_seed(m);
1010 #endif
1011
1012 if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
1013 fatal_fr(r, "sshbuf_put");
1014
1015 while (sshbuf_len(inc) != 0) {
1016 item = xcalloc(1, sizeof(*item));
1017 if ((item->contents = sshbuf_new()) == NULL)
1018 fatal_f("sshbuf_new failed");
1019 if ((r = sshbuf_get_cstring(inc, &item->selector, NULL)) != 0 ||
1020 (r = sshbuf_get_cstring(inc, &item->filename, NULL)) != 0 ||
1021 (r = sshbuf_get_stringb(inc, item->contents)) != 0)
1022 fatal_fr(r, "parse includes");
1023 TAILQ_INSERT_TAIL(&includes, item, entry);
1024 }
1025
1026 free(cp);
1027 sshbuf_free(m);
1028
1029 debug3_f("done");
1030 }
1031
1032 /* Accept a connection from inetd */
1033 static void
1034 server_accept_inetd(int *sock_in, int *sock_out)
1035 {
1036 if (rexeced_flag) {
1037 close(REEXEC_CONFIG_PASS_FD);
1038 *sock_in = *sock_out = dup(STDIN_FILENO);
1039 } else {
1040 *sock_in = dup(STDIN_FILENO);
1041 *sock_out = dup(STDOUT_FILENO);
1042 }
1043 /*
1044 * We intentionally do not close the descriptors 0, 1, and 2
1045 * as our code for setting the descriptors won't work if
1046 * ttyfd happens to be one of those.
1047 */
1048 if (stdfd_devnull(1, 1, !log_stderr) == -1)
1049 error_f("stdfd_devnull failed");
1050 debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1051 }
1052
1053 /*
1054 * Listen for TCP connections
1055 */
1056 static void
1057 listen_on_addrs(struct listenaddr *la)
1058 {
1059 int ret, listen_sock;
1060 struct addrinfo *ai;
1061 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1062
1063 for (ai = la->addrs; ai; ai = ai->ai_next) {
1064 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1065 continue;
1066 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1067 fatal("Too many listen sockets. "
1068 "Enlarge MAX_LISTEN_SOCKS");
1069 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1070 ntop, sizeof(ntop), strport, sizeof(strport),
1071 NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1072 error("getnameinfo failed: %.100s",
1073 ssh_gai_strerror(ret));
1074 continue;
1075 }
1076 /* Create socket for listening. */
1077 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1078 ai->ai_protocol);
1079 if (listen_sock == -1) {
1080 /* kernel may not support ipv6 */
1081 verbose("socket: %.100s", strerror(errno));
1082 continue;
1083 }
1084 if (set_nonblock(listen_sock) == -1) {
1085 close(listen_sock);
1086 continue;
1087 }
1088 if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
1089 verbose("socket: CLOEXEC: %s", strerror(errno));
1090 close(listen_sock);
1091 continue;
1092 }
1093 /* Socket options */
1094 set_reuseaddr(listen_sock);
1095 if (la->rdomain != NULL &&
1096 set_rdomain(listen_sock, la->rdomain) == -1) {
1097 close(listen_sock);
1098 continue;
1099 }
1100
1101 /* Only communicate in IPv6 over AF_INET6 sockets. */
1102 if (ai->ai_family == AF_INET6)
1103 sock_set_v6only(listen_sock);
1104
1105 debug("Bind to port %s on %s.", strport, ntop);
1106
1107 /* Bind the socket to the desired port. */
1108 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) == -1) {
1109 error("Bind to port %s on %s failed: %.200s.",
1110 strport, ntop, strerror(errno));
1111 close(listen_sock);
1112 continue;
1113 }
1114 listen_socks[num_listen_socks] = listen_sock;
1115 num_listen_socks++;
1116
1117 /* Start listening on the port. */
1118 if (listen(listen_sock, SSH_LISTEN_BACKLOG) == -1)
1119 fatal("listen on [%s]:%s: %.100s",
1120 ntop, strport, strerror(errno));
1121 logit("Server listening on %s port %s%s%s.",
1122 ntop, strport,
1123 la->rdomain == NULL ? "" : " rdomain ",
1124 la->rdomain == NULL ? "" : la->rdomain);
1125 }
1126 }
1127
1128 static void
1129 server_listen(void)
1130 {
1131 u_int i;
1132
1133 /* Initialise per-source limit tracking. */
1134 srclimit_init(options.max_startups, options.per_source_max_startups,
1135 options.per_source_masklen_ipv4, options.per_source_masklen_ipv6);
1136
1137 for (i = 0; i < options.num_listen_addrs; i++) {
1138 listen_on_addrs(&options.listen_addrs[i]);
1139 freeaddrinfo(options.listen_addrs[i].addrs);
1140 free(options.listen_addrs[i].rdomain);
1141 memset(&options.listen_addrs[i], 0,
1142 sizeof(options.listen_addrs[i]));
1143 }
1144 free(options.listen_addrs);
1145 options.listen_addrs = NULL;
1146 options.num_listen_addrs = 0;
1147
1148 if (!num_listen_socks)
1149 fatal("Cannot bind any address.");
1150 }
1151
1152 /*
1153 * The main TCP accept loop. Note that, for the non-debug case, returns
1154 * from this function are in a forked subprocess.
1155 */
1156 static void
1157 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1158 {
1159 struct pollfd *pfd = NULL;
1160 int i, j, ret, npfd;
1161 int ostartups = -1, startups = 0, listening = 0, lameduck = 0;
1162 int startup_p[2] = { -1 , -1 }, *startup_pollfd;
1163 char c = 0;
1164 struct sockaddr_storage from;
1165 socklen_t fromlen;
1166 pid_t pid;
1167 u_char rnd[256];
1168 sigset_t nsigset, osigset;
1169 #ifdef LIBWRAP
1170 struct request_info req;
1171
1172 request_init(&req, RQ_DAEMON, __progname, 0);
1173 #endif
1174
1175 /* pipes connected to unauthenticated child sshd processes */
1176 startup_pipes = xcalloc(options.max_startups, sizeof(int));
1177 startup_flags = xcalloc(options.max_startups, sizeof(int));
1178 startup_pollfd = xcalloc(options.max_startups, sizeof(int));
1179 for (i = 0; i < options.max_startups; i++)
1180 startup_pipes[i] = -1;
1181
1182 /*
1183 * Prepare signal mask that we use to block signals that might set
1184 * received_sigterm or received_sighup, so that we are guaranteed
1185 * to immediately wake up the ppoll if a signal is received after
1186 * the flag is checked.
1187 */
1188 sigemptyset(&nsigset);
1189 sigaddset(&nsigset, SIGHUP);
1190 sigaddset(&nsigset, SIGCHLD);
1191 sigaddset(&nsigset, SIGTERM);
1192 sigaddset(&nsigset, SIGQUIT);
1193
1194 /* sized for worst-case */
1195 pfd = xcalloc(num_listen_socks + options.max_startups,
1196 sizeof(struct pollfd));
1197
1198 /*
1199 * Stay listening for connections until the system crashes or
1200 * the daemon is killed with a signal.
1201 */
1202 for (;;) {
1203 sigprocmask(SIG_BLOCK, &nsigset, &osigset);
1204 if (received_sigterm) {
1205 logit("Received signal %d; terminating.",
1206 (int) received_sigterm);
1207 close_listen_socks();
1208 if (options.pid_file != NULL)
1209 unlink(options.pid_file);
1210 exit(received_sigterm == SIGTERM ? 0 : 255);
1211 }
1212 if (ostartups != startups) {
1213 setproctitle("%s [listener] %d of %d-%d startups",
1214 listener_proctitle, startups,
1215 options.max_startups_begin, options.max_startups);
1216 ostartups = startups;
1217 }
1218 if (received_sighup) {
1219 if (!lameduck) {
1220 debug("Received SIGHUP; waiting for children");
1221 close_listen_socks();
1222 lameduck = 1;
1223 }
1224 if (listening <= 0) {
1225 sigprocmask(SIG_SETMASK, &osigset, NULL);
1226 sighup_restart();
1227 }
1228 }
1229
1230 for (i = 0; i < num_listen_socks; i++) {
1231 pfd[i].fd = listen_socks[i];
1232 pfd[i].events = POLLIN;
1233 }
1234 npfd = num_listen_socks;
1235 for (i = 0; i < options.max_startups; i++) {
1236 startup_pollfd[i] = -1;
1237 if (startup_pipes[i] != -1) {
1238 pfd[npfd].fd = startup_pipes[i];
1239 pfd[npfd].events = POLLIN;
1240 startup_pollfd[i] = npfd++;
1241 }
1242 }
1243
1244 /* Wait until a connection arrives or a child exits. */
1245 ret = ppoll(pfd, npfd, NULL, &osigset);
1246 if (ret == -1 && errno != EINTR) {
1247 error("ppoll: %.100s", strerror(errno));
1248 if (errno == EINVAL)
1249 cleanup_exit(1); /* can't recover */
1250 }
1251 sigprocmask(SIG_SETMASK, &osigset, NULL);
1252 if (ret == -1)
1253 continue;
1254
1255 for (i = 0; i < options.max_startups; i++) {
1256 if (startup_pipes[i] == -1 ||
1257 startup_pollfd[i] == -1 ||
1258 !(pfd[startup_pollfd[i]].revents & (POLLIN|POLLHUP)))
1259 continue;
1260 switch (read(startup_pipes[i], &c, sizeof(c))) {
1261 case -1:
1262 if (errno == EINTR || errno == EAGAIN)
1263 continue;
1264 if (errno != EPIPE) {
1265 error_f("startup pipe %d (fd=%d): "
1266 "read %s", i, startup_pipes[i],
1267 strerror(errno));
1268 }
1269 /* FALLTHROUGH */
1270 case 0:
1271 /* child exited or completed auth */
1272 close(startup_pipes[i]);
1273 srclimit_done(startup_pipes[i]);
1274 startup_pipes[i] = -1;
1275 startups--;
1276 if (startup_flags[i])
1277 listening--;
1278 break;
1279 case 1:
1280 /* child has finished preliminaries */
1281 if (startup_flags[i]) {
1282 listening--;
1283 startup_flags[i] = 0;
1284 }
1285 break;
1286 }
1287 }
1288 for (i = 0; i < num_listen_socks; i++) {
1289 if (!(pfd[i].revents & POLLIN))
1290 continue;
1291 fromlen = sizeof(from);
1292 *newsock = accept(listen_socks[i],
1293 (struct sockaddr *)&from, &fromlen);
1294 if (*newsock == -1) {
1295 if (errno != EINTR && errno != EWOULDBLOCK &&
1296 errno != ECONNABORTED && errno != EAGAIN)
1297 error("accept: %.100s",
1298 strerror(errno));
1299 if (errno == EMFILE || errno == ENFILE)
1300 usleep(100 * 1000);
1301 continue;
1302 }
1303 #ifdef LIBWRAP
1304 /* Check whether logins are denied from this host. */
1305 request_set(&req, RQ_FILE, *newsock,
1306 RQ_CLIENT_NAME, "", RQ_CLIENT_ADDR, "", 0);
1307 sock_host(&req);
1308 if (!hosts_access(&req)) {
1309 const struct linger l = { .l_onoff = 1,
1310 .l_linger = 0 };
1311
1312 (void )setsockopt(*newsock, SOL_SOCKET,
1313 SO_LINGER, &l, sizeof(l));
1314 (void )close(*newsock);
1315 /*
1316 * Mimic message from libwrap's refuse()
1317 * exactly. sshguard, and supposedly lots
1318 * of custom made scripts rely on it.
1319 */
1320 syslog(deny_severity,
1321 "refused connect from %s (%s)",
1322 eval_client(&req),
1323 eval_hostaddr(req.client));
1324 debug("Connection refused by tcp wrapper");
1325 continue;
1326 }
1327 #endif /* LIBWRAP */
1328 if (unset_nonblock(*newsock) == -1) {
1329 close(*newsock);
1330 continue;
1331 }
1332 if (pipe(startup_p) == -1) {
1333 error_f("pipe(startup_p): %s", strerror(errno));
1334 close(*newsock);
1335 continue;
1336 }
1337 if (drop_connection(*newsock, startups, startup_p[0])) {
1338 close(*newsock);
1339 close(startup_p[0]);
1340 close(startup_p[1]);
1341 continue;
1342 }
1343
1344 if (rexec_flag && socketpair(AF_UNIX,
1345 SOCK_STREAM, 0, config_s) == -1) {
1346 error("reexec socketpair: %s",
1347 strerror(errno));
1348 close(*newsock);
1349 close(startup_p[0]);
1350 close(startup_p[1]);
1351 continue;
1352 }
1353
1354 for (j = 0; j < options.max_startups; j++)
1355 if (startup_pipes[j] == -1) {
1356 startup_pipes[j] = startup_p[0];
1357 startups++;
1358 startup_flags[j] = 1;
1359 break;
1360 }
1361
1362 /*
1363 * Got connection. Fork a child to handle it, unless
1364 * we are in debugging mode.
1365 */
1366 if (debug_flag) {
1367 /*
1368 * In debugging mode. Close the listening
1369 * socket, and start processing the
1370 * connection without forking.
1371 */
1372 debug("Server will not fork when running in debugging mode.");
1373 close_listen_socks();
1374 *sock_in = *newsock;
1375 *sock_out = *newsock;
1376 close(startup_p[0]);
1377 close(startup_p[1]);
1378 startup_pipe = -1;
1379 pid = getpid();
1380 if (rexec_flag) {
1381 send_rexec_state(config_s[0], cfg);
1382 close(config_s[0]);
1383 }
1384 free(pfd);
1385 return;
1386 }
1387
1388 /*
1389 * Normal production daemon. Fork, and have
1390 * the child process the connection. The
1391 * parent continues listening.
1392 */
1393 platform_pre_fork();
1394 listening++;
1395 if ((pid = fork()) == 0) {
1396 /*
1397 * Child. Close the listening and
1398 * max_startup sockets. Start using
1399 * the accepted socket. Reinitialize
1400 * logging (since our pid has changed).
1401 * We return from this function to handle
1402 * the connection.
1403 */
1404 platform_post_fork_child();
1405 startup_pipe = startup_p[1];
1406 close_startup_pipes();
1407 close_listen_socks();
1408 *sock_in = *newsock;
1409 *sock_out = *newsock;
1410 log_init(__progname,
1411 options.log_level,
1412 options.log_facility,
1413 log_stderr);
1414 if (rexec_flag)
1415 close(config_s[0]);
1416 else {
1417 /*
1418 * Signal parent that the preliminaries
1419 * for this child are complete. For the
1420 * re-exec case, this happens after the
1421 * child has received the rexec state
1422 * from the server.
1423 */
1424 (void)atomicio(vwrite, startup_pipe,
1425 "\0", 1);
1426 }
1427 free(pfd);
1428 return;
1429 }
1430
1431 /* Parent. Stay in the loop. */
1432 platform_post_fork_parent(pid);
1433 if (pid == -1)
1434 error("fork: %.100s", strerror(errno));
1435 else
1436 debug("Forked child %ld.", (long)pid);
1437
1438 close(startup_p[1]);
1439
1440 if (rexec_flag) {
1441 close(config_s[1]);
1442 send_rexec_state(config_s[0], cfg);
1443 close(config_s[0]);
1444 }
1445 close(*newsock);
1446
1447 /*
1448 * Ensure that our random state differs
1449 * from that of the child
1450 */
1451 arc4random_stir();
1452 arc4random_buf(rnd, sizeof(rnd));
1453 #ifdef WITH_OPENSSL
1454 RAND_seed(rnd, sizeof(rnd));
1455 if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1456 fatal("%s: RAND_bytes failed", __func__);
1457 #endif
1458 explicit_bzero(rnd, sizeof(rnd));
1459 }
1460 }
1461 }
1462
1463 /*
1464 * If IP options are supported, make sure there are none (log and
1465 * return an error if any are found). Basically we are worried about
1466 * source routing; it can be used to pretend you are somebody
1467 * (ip-address) you are not. That itself may be "almost acceptable"
1468 * under certain circumstances, but rhosts authentication is useless
1469 * if source routing is accepted. Notice also that if we just dropped
1470 * source routing here, the other side could use IP spoofing to do
1471 * rest of the interaction and could still bypass security. So we
1472 * exit here if we detect any IP options.
1473 */
1474 static void
1475 check_ip_options(struct ssh *ssh)
1476 {
1477 #ifdef IP_OPTIONS
1478 int sock_in = ssh_packet_get_connection_in(ssh);
1479 struct sockaddr_storage from;
1480 u_char opts[200];
1481 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1482 char text[sizeof(opts) * 3 + 1];
1483
1484 memset(&from, 0, sizeof(from));
1485 if (getpeername(sock_in, (struct sockaddr *)&from,
1486 &fromlen) == -1)
1487 return;
1488 if (from.ss_family != AF_INET)
1489 return;
1490 /* XXX IPv6 options? */
1491
1492 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1493 &option_size) >= 0 && option_size != 0) {
1494 text[0] = '\0';
1495 for (i = 0; i < option_size; i++)
1496 snprintf(text + i*3, sizeof(text) - i*3,
1497 " %2.2x", opts[i]);
1498 fatal("Connection from %.100s port %d with IP opts: %.800s",
1499 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1500 }
1501 return;
1502 #endif /* IP_OPTIONS */
1503 }
1504
1505 /* Set the routing domain for this process */
1506 static void
1507 set_process_rdomain(struct ssh *ssh, const char *name)
1508 {
1509 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
1510 if (name == NULL)
1511 return; /* default */
1512
1513 if (strcmp(name, "%D") == 0) {
1514 /* "expands" to routing domain of connection */
1515 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1516 return;
1517 }
1518 /* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
1519 return sys_set_process_rdomain(name);
1520 #elif defined(__OpenBSD__)
1521 int rtable, ortable = getrtable();
1522 const char *errstr;
1523
1524 if (name == NULL)
1525 return; /* default */
1526
1527 if (strcmp(name, "%D") == 0) {
1528 /* "expands" to routing domain of connection */
1529 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1530 return;
1531 }
1532
1533 rtable = (int)strtonum(name, 0, 255, &errstr);
1534 if (errstr != NULL) /* Shouldn't happen */
1535 fatal("Invalid routing domain \"%s\": %s", name, errstr);
1536 if (rtable != ortable && setrtable(rtable) != 0)
1537 fatal("Unable to set routing domain %d: %s",
1538 rtable, strerror(errno));
1539 debug_f("set routing domain %d (was %d)", rtable, ortable);
1540 #else /* defined(__OpenBSD__) */
1541 fatal("Unable to set routing domain: not supported in this platform");
1542 #endif
1543 }
1544
1545 static void
1546 accumulate_host_timing_secret(struct sshbuf *server_cfg,
1547 struct sshkey *key)
1548 {
1549 static struct ssh_digest_ctx *ctx;
1550 u_char *hash;
1551 size_t len;
1552 struct sshbuf *buf;
1553 int r;
1554
1555 if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
1556 fatal_f("ssh_digest_start");
1557 if (key == NULL) { /* finalize */
1558 /* add server config in case we are using agent for host keys */
1559 if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
1560 sshbuf_len(server_cfg)) != 0)
1561 fatal_f("ssh_digest_update");
1562 len = ssh_digest_bytes(SSH_DIGEST_SHA512);
1563 hash = xmalloc(len);
1564 if (ssh_digest_final(ctx, hash, len) != 0)
1565 fatal_f("ssh_digest_final");
1566 options.timing_secret = PEEK_U64(hash);
1567 freezero(hash, len);
1568 ssh_digest_free(ctx);
1569 ctx = NULL;
1570 return;
1571 }
1572 if ((buf = sshbuf_new()) == NULL)
1573 fatal_f("could not allocate buffer");
1574 if ((r = sshkey_private_serialize(key, buf)) != 0)
1575 fatal_fr(r, "decode key");
1576 if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
1577 fatal_f("ssh_digest_update");
1578 sshbuf_reset(buf);
1579 sshbuf_free(buf);
1580 }
1581
1582 static char *
1583 prepare_proctitle(int ac, char **av)
1584 {
1585 char *ret = NULL;
1586 int i;
1587
1588 for (i = 0; i < ac; i++)
1589 xextendf(&ret, " ", "%s", av[i]);
1590 return ret;
1591 }
1592
1593 /*
1594 * Main program for the daemon.
1595 */
1596 int
1597 main(int ac, char **av)
1598 {
1599 struct ssh *ssh = NULL;
1600 extern char *optarg;
1601 extern int optind;
1602 int r, opt, on = 1, already_daemon, remote_port;
1603 int sock_in = -1, sock_out = -1, newsock = -1;
1604 const char *remote_ip, *rdomain;
1605 char *fp, *line, *laddr, *logfile = NULL;
1606 int config_s[2] = { -1 , -1 };
1607 u_int i, j;
1608 u_int64_t ibytes, obytes;
1609 mode_t new_umask;
1610 struct sshkey *key;
1611 struct sshkey *pubkey;
1612 int keytype;
1613 Authctxt *authctxt;
1614 struct connection_info *connection_info = NULL;
1615
1616 #ifdef HAVE_SECUREWARE
1617 (void)set_auth_parameters(ac, av);
1618 #endif
1619 __progname = ssh_get_progname(av[0]);
1620
1621 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1622 saved_argc = ac;
1623 rexec_argc = ac;
1624 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1625 for (i = 0; (int)i < ac; i++)
1626 saved_argv[i] = xstrdup(av[i]);
1627 saved_argv[i] = NULL;
1628
1629 #ifndef HAVE_SETPROCTITLE
1630 /* Prepare for later setproctitle emulation */
1631 compat_init_setproctitle(ac, av);
1632 av = saved_argv;
1633 #endif
1634
1635 if (geteuid() == 0 && setgroups(0, NULL) == -1)
1636 debug("setgroups(): %.200s", strerror(errno));
1637
1638 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1639 sanitise_stdfd();
1640
1641 seed_rng();
1642
1643 /* Initialize configuration options to their default values. */
1644 initialize_server_options(&options);
1645
1646 /* Parse command-line arguments. */
1647 while ((opt = getopt(ac, av,
1648 "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1649 switch (opt) {
1650 case '4':
1651 options.address_family = AF_INET;
1652 break;
1653 case '6':
1654 options.address_family = AF_INET6;
1655 break;
1656 case 'f':
1657 config_file_name = optarg;
1658 break;
1659 case 'c':
1660 servconf_add_hostcert("[command-line]", 0,
1661 &options, optarg);
1662 break;
1663 case 'd':
1664 if (debug_flag == 0) {
1665 debug_flag = 1;
1666 options.log_level = SYSLOG_LEVEL_DEBUG1;
1667 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1668 options.log_level++;
1669 break;
1670 case 'D':
1671 no_daemon_flag = 1;
1672 break;
1673 case 'E':
1674 logfile = optarg;
1675 /* FALLTHROUGH */
1676 case 'e':
1677 log_stderr = 1;
1678 break;
1679 case 'i':
1680 inetd_flag = 1;
1681 break;
1682 case 'r':
1683 rexec_flag = 0;
1684 break;
1685 case 'R':
1686 rexeced_flag = 1;
1687 inetd_flag = 1;
1688 break;
1689 case 'Q':
1690 /* ignored */
1691 break;
1692 case 'q':
1693 options.log_level = SYSLOG_LEVEL_QUIET;
1694 break;
1695 case 'b':
1696 /* protocol 1, ignored */
1697 break;
1698 case 'p':
1699 options.ports_from_cmdline = 1;
1700 if (options.num_ports >= MAX_PORTS) {
1701 fprintf(stderr, "too many ports.\n");
1702 exit(1);
1703 }
1704 options.ports[options.num_ports++] = a2port(optarg);
1705 if (options.ports[options.num_ports-1] <= 0) {
1706 fprintf(stderr, "Bad port number.\n");
1707 exit(1);
1708 }
1709 break;
1710 case 'g':
1711 if ((options.login_grace_time = convtime(optarg)) == -1) {
1712 fprintf(stderr, "Invalid login grace time.\n");
1713 exit(1);
1714 }
1715 break;
1716 case 'k':
1717 /* protocol 1, ignored */
1718 break;
1719 case 'h':
1720 servconf_add_hostkey("[command-line]", 0,
1721 &options, optarg, 1);
1722 break;
1723 case 't':
1724 test_flag = 1;
1725 break;
1726 case 'T':
1727 test_flag = 2;
1728 break;
1729 case 'C':
1730 connection_info = get_connection_info(ssh, 0, 0);
1731 if (parse_server_match_testspec(connection_info,
1732 optarg) == -1)
1733 exit(1);
1734 break;
1735 case 'u':
1736 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1737 if (utmp_len > HOST_NAME_MAX+1) {
1738 fprintf(stderr, "Invalid utmp length.\n");
1739 exit(1);
1740 }
1741 break;
1742 case 'o':
1743 line = xstrdup(optarg);
1744 if (process_server_config_line(&options, line,
1745 "command-line", 0, NULL, NULL, &includes) != 0)
1746 exit(1);
1747 free(line);
1748 break;
1749 case '?':
1750 default:
1751 usage();
1752 break;
1753 }
1754 }
1755 if (rexeced_flag || inetd_flag)
1756 rexec_flag = 0;
1757 if (!test_flag && rexec_flag && !path_absolute(av[0]))
1758 fatal("sshd re-exec requires execution with an absolute path");
1759 if (rexeced_flag)
1760 closefrom(REEXEC_MIN_FREE_FD);
1761 else
1762 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1763
1764 /* If requested, redirect the logs to the specified logfile. */
1765 if (logfile != NULL)
1766 log_redirect_stderr_to(logfile);
1767 /*
1768 * Force logging to stderr until we have loaded the private host
1769 * key (unless started from inetd)
1770 */
1771 log_init(__progname,
1772 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1773 SYSLOG_LEVEL_INFO : options.log_level,
1774 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1775 SYSLOG_FACILITY_AUTH : options.log_facility,
1776 log_stderr || !inetd_flag || debug_flag);
1777
1778 /*
1779 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1780 * root's environment
1781 */
1782 if (getenv("KRB5CCNAME") != NULL)
1783 (void) unsetenv("KRB5CCNAME");
1784
1785 sensitive_data.have_ssh2_key = 0;
1786
1787 /*
1788 * If we're not doing an extended test do not silently ignore connection
1789 * test params.
1790 */
1791 if (test_flag < 2 && connection_info != NULL)
1792 fatal("Config test connection parameter (-C) provided without "
1793 "test mode (-T)");
1794
1795 /* Fetch our configuration */
1796 if ((cfg = sshbuf_new()) == NULL)
1797 fatal_f("sshbuf_new failed");
1798 if (rexeced_flag) {
1799 setproctitle("%s", "[rexeced]");
1800 recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg);
1801 if (!debug_flag) {
1802 startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1803 close(REEXEC_STARTUP_PIPE_FD);
1804 /*
1805 * Signal parent that this child is at a point where
1806 * they can go away if they have a SIGHUP pending.
1807 */
1808 (void)atomicio(vwrite, startup_pipe, "\0", 1);
1809 }
1810 } else if (strcasecmp(config_file_name, "none") != 0)
1811 load_server_config(config_file_name, cfg);
1812
1813 parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1814 cfg, &includes, NULL, rexeced_flag);
1815
1816 #ifdef WITH_OPENSSL
1817 if (options.moduli_file != NULL)
1818 dh_set_moduli_file(options.moduli_file);
1819 #endif
1820
1821 /* Fill in default values for those options not explicitly set. */
1822 fill_default_server_options(&options);
1823
1824 /* Check that options are sensible */
1825 if (options.authorized_keys_command_user == NULL &&
1826 (options.authorized_keys_command != NULL &&
1827 strcasecmp(options.authorized_keys_command, "none") != 0))
1828 fatal("AuthorizedKeysCommand set without "
1829 "AuthorizedKeysCommandUser");
1830 if (options.authorized_principals_command_user == NULL &&
1831 (options.authorized_principals_command != NULL &&
1832 strcasecmp(options.authorized_principals_command, "none") != 0))
1833 fatal("AuthorizedPrincipalsCommand set without "
1834 "AuthorizedPrincipalsCommandUser");
1835
1836 /*
1837 * Check whether there is any path through configured auth methods.
1838 * Unfortunately it is not possible to verify this generally before
1839 * daemonisation in the presence of Match block, but this catches
1840 * and warns for trivial misconfigurations that could break login.
1841 */
1842 if (options.num_auth_methods != 0) {
1843 for (i = 0; i < options.num_auth_methods; i++) {
1844 if (auth2_methods_valid(options.auth_methods[i],
1845 1) == 0)
1846 break;
1847 }
1848 if (i >= options.num_auth_methods)
1849 fatal("AuthenticationMethods cannot be satisfied by "
1850 "enabled authentication methods");
1851 }
1852
1853 /* Check that there are no remaining arguments. */
1854 if (optind < ac) {
1855 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1856 exit(1);
1857 }
1858
1859 debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1860
1861 /* Store privilege separation user for later use if required. */
1862 privsep_chroot = use_privsep && (getuid() == 0 || geteuid() == 0);
1863 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1864 if (privsep_chroot || options.kerberos_authentication)
1865 fatal("Privilege separation user %s does not exist",
1866 SSH_PRIVSEP_USER);
1867 } else {
1868 privsep_pw = pwcopy(privsep_pw);
1869 freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
1870 privsep_pw->pw_passwd = xstrdup("*");
1871 }
1872 endpwent();
1873
1874 /* load host keys */
1875 sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1876 sizeof(struct sshkey *));
1877 sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1878 sizeof(struct sshkey *));
1879
1880 if (options.host_key_agent) {
1881 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1882 setenv(SSH_AUTHSOCKET_ENV_NAME,
1883 options.host_key_agent, 1);
1884 if ((r = ssh_get_authentication_socket(NULL)) == 0)
1885 have_agent = 1;
1886 else
1887 error_r(r, "Could not connect to agent \"%s\"",
1888 options.host_key_agent);
1889 }
1890
1891 for (i = 0; i < options.num_host_key_files; i++) {
1892 int ll = options.host_key_file_userprovided[i] ?
1893 SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
1894
1895 if (options.host_key_files[i] == NULL)
1896 continue;
1897 if ((r = sshkey_load_private(options.host_key_files[i], "",
1898 &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1899 do_log2_r(r, ll, "Unable to load host key \"%s\"",
1900 options.host_key_files[i]);
1901 if (sshkey_is_sk(key) &&
1902 key->sk_flags & SSH_SK_USER_PRESENCE_REQD) {
1903 debug("host key %s requires user presence, ignoring",
1904 options.host_key_files[i]);
1905 key->sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
1906 }
1907 if (r == 0 && key != NULL &&
1908 (r = sshkey_shield_private(key)) != 0) {
1909 do_log2_r(r, ll, "Unable to shield host key \"%s\"",
1910 options.host_key_files[i]);
1911 sshkey_free(key);
1912 key = NULL;
1913 }
1914 if ((r = sshkey_load_public(options.host_key_files[i],
1915 &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1916 do_log2_r(r, ll, "Unable to load host key \"%s\"",
1917 options.host_key_files[i]);
1918 if (pubkey != NULL && key != NULL) {
1919 if (!sshkey_equal(pubkey, key)) {
1920 error("Public key for %s does not match "
1921 "private key", options.host_key_files[i]);
1922 sshkey_free(pubkey);
1923 pubkey = NULL;
1924 }
1925 }
1926 if (pubkey == NULL && key != NULL) {
1927 if ((r = sshkey_from_private(key, &pubkey)) != 0)
1928 fatal_r(r, "Could not demote key: \"%s\"",
1929 options.host_key_files[i]);
1930 }
1931 if (pubkey != NULL && (r = sshkey_check_rsa_length(pubkey,
1932 options.required_rsa_size)) != 0) {
1933 error_fr(r, "Host key %s", options.host_key_files[i]);
1934 sshkey_free(pubkey);
1935 sshkey_free(key);
1936 continue;
1937 }
1938 sensitive_data.host_keys[i] = key;
1939 sensitive_data.host_pubkeys[i] = pubkey;
1940
1941 if (key == NULL && pubkey != NULL && have_agent) {
1942 debug("will rely on agent for hostkey %s",
1943 options.host_key_files[i]);
1944 keytype = pubkey->type;
1945 } else if (key != NULL) {
1946 keytype = key->type;
1947 accumulate_host_timing_secret(cfg, key);
1948 } else {
1949 do_log2(ll, "Unable to load host key: %s",
1950 options.host_key_files[i]);
1951 sensitive_data.host_keys[i] = NULL;
1952 sensitive_data.host_pubkeys[i] = NULL;
1953 continue;
1954 }
1955
1956 switch (keytype) {
1957 case KEY_RSA:
1958 case KEY_DSA:
1959 case KEY_ECDSA:
1960 case KEY_ED25519:
1961 case KEY_ECDSA_SK:
1962 case KEY_ED25519_SK:
1963 case KEY_XMSS:
1964 if (have_agent || key != NULL)
1965 sensitive_data.have_ssh2_key = 1;
1966 break;
1967 }
1968 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1969 SSH_FP_DEFAULT)) == NULL)
1970 fatal("sshkey_fingerprint failed");
1971 debug("%s host key #%d: %s %s",
1972 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1973 free(fp);
1974 }
1975 accumulate_host_timing_secret(cfg, NULL);
1976 if (!sensitive_data.have_ssh2_key) {
1977 logit("sshd: no hostkeys available -- exiting.");
1978 exit(1);
1979 }
1980
1981 /*
1982 * Load certificates. They are stored in an array at identical
1983 * indices to the public keys that they relate to.
1984 */
1985 sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1986 sizeof(struct sshkey *));
1987 for (i = 0; i < options.num_host_key_files; i++)
1988 sensitive_data.host_certificates[i] = NULL;
1989
1990 for (i = 0; i < options.num_host_cert_files; i++) {
1991 if (options.host_cert_files[i] == NULL)
1992 continue;
1993 if ((r = sshkey_load_public(options.host_cert_files[i],
1994 &key, NULL)) != 0) {
1995 error_r(r, "Could not load host certificate \"%s\"",
1996 options.host_cert_files[i]);
1997 continue;
1998 }
1999 if (!sshkey_is_cert(key)) {
2000 error("Certificate file is not a certificate: %s",
2001 options.host_cert_files[i]);
2002 sshkey_free(key);
2003 continue;
2004 }
2005 /* Find matching private key */
2006 for (j = 0; j < options.num_host_key_files; j++) {
2007 if (sshkey_equal_public(key,
2008 sensitive_data.host_pubkeys[j])) {
2009 sensitive_data.host_certificates[j] = key;
2010 break;
2011 }
2012 }
2013 if (j >= options.num_host_key_files) {
2014 error("No matching private key for certificate: %s",
2015 options.host_cert_files[i]);
2016 sshkey_free(key);
2017 continue;
2018 }
2019 sensitive_data.host_certificates[j] = key;
2020 debug("host certificate: #%u type %d %s", j, key->type,
2021 sshkey_type(key));
2022 }
2023
2024 if (privsep_chroot) {
2025 struct stat st;
2026
2027 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
2028 (S_ISDIR(st.st_mode) == 0))
2029 fatal("Missing privilege separation directory: %s",
2030 _PATH_PRIVSEP_CHROOT_DIR);
2031
2032 #ifdef HAVE_CYGWIN
2033 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
2034 (st.st_uid != getuid () ||
2035 (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
2036 #else
2037 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
2038 #endif
2039 fatal("%s must be owned by root and not group or "
2040 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
2041 }
2042
2043 if (test_flag > 1) {
2044 /*
2045 * If no connection info was provided by -C then use
2046 * use a blank one that will cause no predicate to match.
2047 */
2048 if (connection_info == NULL)
2049 connection_info = get_connection_info(ssh, 0, 0);
2050 connection_info->test = 1;
2051 parse_server_match_config(&options, &includes, connection_info);
2052 dump_config(&options);
2053 }
2054
2055 /* Configuration looks good, so exit if in test mode. */
2056 if (test_flag)
2057 exit(0);
2058
2059 /*
2060 * Clear out any supplemental groups we may have inherited. This
2061 * prevents inadvertent creation of files with bad modes (in the
2062 * portable version at least, it's certainly possible for PAM
2063 * to create a file, and we can't control the code in every
2064 * module which might be used).
2065 */
2066 if (setgroups(0, NULL) < 0)
2067 debug("setgroups() failed: %.200s", strerror(errno));
2068
2069 if (rexec_flag) {
2070 if (rexec_argc < 0)
2071 fatal("rexec_argc %d < 0", rexec_argc);
2072 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
2073 for (i = 0; i < (u_int)rexec_argc; i++) {
2074 debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
2075 rexec_argv[i] = saved_argv[i];
2076 }
2077 rexec_argv[rexec_argc] = "-R";
2078 rexec_argv[rexec_argc + 1] = NULL;
2079 }
2080 listener_proctitle = prepare_proctitle(ac, av);
2081
2082 /* Ensure that umask disallows at least group and world write */
2083 new_umask = umask(0077) | 0022;
2084 (void) umask(new_umask);
2085
2086 /* Initialize the log (it is reinitialized below in case we forked). */
2087 if (debug_flag && (!inetd_flag || rexeced_flag))
2088 log_stderr = 1;
2089 log_init(__progname, options.log_level,
2090 options.log_facility, log_stderr);
2091 for (i = 0; i < options.num_log_verbose; i++)
2092 log_verbose_add(options.log_verbose[i]);
2093
2094 /*
2095 * If not in debugging mode, not started from inetd and not already
2096 * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
2097 * terminal, and fork. The original process exits.
2098 */
2099 already_daemon = daemonized();
2100 if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
2101
2102 if (daemon(0, 0) == -1)
2103 fatal("daemon() failed: %.200s", strerror(errno));
2104
2105 disconnect_controlling_tty();
2106 }
2107 /* Reinitialize the log (because of the fork above). */
2108 log_init(__progname, options.log_level, options.log_facility, log_stderr);
2109
2110 #ifdef LIBWRAP
2111 /*
2112 * We log refusals ourselves. However, libwrap will report
2113 * syntax errors in hosts.allow via syslog(3).
2114 */
2115 allow_severity = options.log_facility|LOG_INFO;
2116 deny_severity = options.log_facility|LOG_WARNING;
2117 #endif
2118 /* Avoid killing the process in high-pressure swapping environments. */
2119 if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
2120 debug("madvise(): %.200s", strerror(errno));
2121
2122 /*
2123 * Chdir to the root directory so that the current disk can be
2124 * unmounted if desired.
2125 */
2126 if (chdir("/") == -1)
2127 error("chdir(\"/\"): %s", strerror(errno));
2128
2129 /* ignore SIGPIPE */
2130 ssh_signal(SIGPIPE, SIG_IGN);
2131
2132 /* Get a connection, either from inetd or a listening TCP socket */
2133 if (inetd_flag) {
2134 server_accept_inetd(&sock_in, &sock_out);
2135 } else {
2136 platform_pre_listen();
2137 server_listen();
2138
2139 ssh_signal(SIGHUP, sighup_handler);
2140 ssh_signal(SIGCHLD, main_sigchld_handler);
2141 ssh_signal(SIGTERM, sigterm_handler);
2142 ssh_signal(SIGQUIT, sigterm_handler);
2143
2144 /*
2145 * Write out the pid file after the sigterm handler
2146 * is setup and the listen sockets are bound
2147 */
2148 if (options.pid_file != NULL && !debug_flag) {
2149 FILE *f = fopen(options.pid_file, "w");
2150
2151 if (f == NULL) {
2152 error("Couldn't create pid file \"%s\": %s",
2153 options.pid_file, strerror(errno));
2154 } else {
2155 fprintf(f, "%ld\n", (long) getpid());
2156 fclose(f);
2157 }
2158 }
2159
2160 /* Accept a connection and return in a forked child */
2161 server_accept_loop(&sock_in, &sock_out,
2162 &newsock, config_s);
2163 }
2164
2165 /* This is the child processing a new connection. */
2166 setproctitle("%s", "[accepted]");
2167
2168 /*
2169 * Create a new session and process group since the 4.4BSD
2170 * setlogin() affects the entire process group. We don't
2171 * want the child to be able to affect the parent.
2172 */
2173 if (!debug_flag && !inetd_flag && setsid() == -1)
2174 error("setsid: %.100s", strerror(errno));
2175
2176 if (rexec_flag) {
2177 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
2178 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2179 dup2(newsock, STDIN_FILENO);
2180 dup2(STDIN_FILENO, STDOUT_FILENO);
2181 if (startup_pipe == -1)
2182 close(REEXEC_STARTUP_PIPE_FD);
2183 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
2184 dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
2185 close(startup_pipe);
2186 startup_pipe = REEXEC_STARTUP_PIPE_FD;
2187 }
2188
2189 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
2190 close(config_s[1]);
2191
2192 ssh_signal(SIGHUP, SIG_IGN); /* avoid reset to SIG_DFL */
2193 execv(rexec_argv[0], rexec_argv);
2194
2195 /* Reexec has failed, fall back and continue */
2196 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
2197 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
2198 log_init(__progname, options.log_level,
2199 options.log_facility, log_stderr);
2200
2201 /* Clean up fds */
2202 close(REEXEC_CONFIG_PASS_FD);
2203 newsock = sock_out = sock_in = dup(STDIN_FILENO);
2204 if (stdfd_devnull(1, 1, 0) == -1)
2205 error_f("stdfd_devnull failed");
2206 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2207 sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2208 }
2209
2210 /* Executed child processes don't need these. */
2211 fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2212 fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2213
2214 /* We will not restart on SIGHUP since it no longer makes sense. */
2215 ssh_signal(SIGALRM, SIG_DFL);
2216 ssh_signal(SIGHUP, SIG_DFL);
2217 ssh_signal(SIGTERM, SIG_DFL);
2218 ssh_signal(SIGQUIT, SIG_DFL);
2219 ssh_signal(SIGCHLD, SIG_DFL);
2220 ssh_signal(SIGINT, SIG_DFL);
2221
2222 #ifdef __FreeBSD__
2223 /*
2224 * Initialize the resolver. This may not happen automatically
2225 * before privsep chroot().
2226 */
2227 if ((_res.options & RES_INIT) == 0) {
2228 debug("res_init()");
2229 res_init();
2230 }
2231 #ifdef GSSAPI
2232 /*
2233 * Force GSS-API to parse its configuration and load any
2234 * mechanism plugins.
2235 */
2236 {
2237 gss_OID_set mechs;
2238 OM_uint32 minor_status;
2239 gss_indicate_mechs(&minor_status, &mechs);
2240 gss_release_oid_set(&minor_status, &mechs);
2241 }
2242 #endif
2243 #endif
2244
2245 /*
2246 * Register our connection. This turns encryption off because we do
2247 * not have a key.
2248 */
2249 if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
2250 fatal("Unable to create connection");
2251 the_active_state = ssh;
2252 ssh_packet_set_server(ssh);
2253
2254 check_ip_options(ssh);
2255
2256 /* Prepare the channels layer */
2257 channel_init_channels(ssh);
2258 channel_set_af(ssh, options.address_family);
2259 process_permitopen(ssh, &options);
2260
2261 /* Set SO_KEEPALIVE if requested. */
2262 if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) &&
2263 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1)
2264 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2265
2266 if ((remote_port = ssh_remote_port(ssh)) < 0) {
2267 debug("ssh_remote_port failed");
2268 cleanup_exit(255);
2269 }
2270
2271 if (options.routing_domain != NULL)
2272 set_process_rdomain(ssh, options.routing_domain);
2273
2274 /*
2275 * The rest of the code depends on the fact that
2276 * ssh_remote_ipaddr() caches the remote ip, even if
2277 * the socket goes away.
2278 */
2279 remote_ip = ssh_remote_ipaddr(ssh);
2280
2281 #ifdef HAVE_LOGIN_CAP
2282 /* Also caches remote hostname for sandboxed child. */
2283 auth_get_canonical_hostname(ssh, options.use_dns);
2284 #endif
2285
2286 #ifdef SSH_AUDIT_EVENTS
2287 audit_connection_from(remote_ip, remote_port);
2288 #endif
2289
2290 rdomain = ssh_packet_rdomain_in(ssh);
2291
2292 /* Log the connection. */
2293 laddr = get_local_ipaddr(sock_in);
2294 verbose("Connection from %s port %d on %s port %d%s%s%s",
2295 remote_ip, remote_port, laddr, ssh_local_port(ssh),
2296 rdomain == NULL ? "" : " rdomain \"",
2297 rdomain == NULL ? "" : rdomain,
2298 rdomain == NULL ? "" : "\"");
2299 free(laddr);
2300
2301 /*
2302 * We don't want to listen forever unless the other side
2303 * successfully authenticates itself. So we set up an alarm which is
2304 * cleared after successful authentication. A limit of zero
2305 * indicates no limit. Note that we don't set the alarm in debugging
2306 * mode; it is just annoying to have the server exit just when you
2307 * are about to discover the bug.
2308 */
2309 ssh_signal(SIGALRM, grace_alarm_handler);
2310 if (!debug_flag)
2311 alarm(options.login_grace_time);
2312
2313 if ((r = kex_exchange_identification(ssh, -1,
2314 options.version_addendum)) != 0)
2315 sshpkt_fatal(ssh, r, "banner exchange");
2316
2317 ssh_packet_set_nonblocking(ssh);
2318
2319 /* allocate authentication context */
2320 authctxt = xcalloc(1, sizeof(*authctxt));
2321 ssh->authctxt = authctxt;
2322
2323 authctxt->loginmsg = loginmsg;
2324
2325 /* XXX global for cleanup, access from other modules */
2326 the_authctxt = authctxt;
2327
2328 /* Set default key authentication options */
2329 if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
2330 fatal("allocation failed");
2331
2332 /* prepare buffer to collect messages to display to user after login */
2333 if ((loginmsg = sshbuf_new()) == NULL)
2334 fatal_f("sshbuf_new failed");
2335 auth_debug_reset();
2336
2337 BLACKLIST_INIT();
2338
2339 if (use_privsep) {
2340 if (privsep_preauth(ssh) == 1)
2341 goto authenticated;
2342 } else if (have_agent) {
2343 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2344 error_r(r, "Unable to get agent socket");
2345 have_agent = 0;
2346 }
2347 }
2348
2349 /* perform the key exchange */
2350 /* authenticate user and start session */
2351 do_ssh2_kex(ssh);
2352 do_authentication2(ssh);
2353
2354 /*
2355 * If we use privilege separation, the unprivileged child transfers
2356 * the current keystate and exits
2357 */
2358 if (use_privsep) {
2359 mm_send_keystate(ssh, pmonitor);
2360 ssh_packet_clear_keys(ssh);
2361 exit(0);
2362 }
2363
2364 authenticated:
2365 /*
2366 * Cancel the alarm we set to limit the time taken for
2367 * authentication.
2368 */
2369 alarm(0);
2370 ssh_signal(SIGALRM, SIG_DFL);
2371 authctxt->authenticated = 1;
2372 if (startup_pipe != -1) {
2373 close(startup_pipe);
2374 startup_pipe = -1;
2375 }
2376
2377 #ifdef SSH_AUDIT_EVENTS
2378 audit_event(ssh, SSH_AUTH_SUCCESS);
2379 #endif
2380
2381 #ifdef GSSAPI
2382 if (options.gss_authentication) {
2383 temporarily_use_uid(authctxt->pw);
2384 ssh_gssapi_storecreds();
2385 restore_uid();
2386 }
2387 #endif
2388 #ifdef USE_PAM
2389 if (options.use_pam) {
2390 do_pam_setcred(1);
2391 do_pam_session(ssh);
2392 }
2393 #endif
2394
2395 /*
2396 * In privilege separation, we fork another child and prepare
2397 * file descriptor passing.
2398 */
2399 if (use_privsep) {
2400 privsep_postauth(ssh, authctxt);
2401 /* the monitor process [priv] will not return */
2402 }
2403
2404 ssh_packet_set_timeout(ssh, options.client_alive_interval,
2405 options.client_alive_count_max);
2406
2407 /* Try to send all our hostkeys to the client */
2408 notify_hostkeys(ssh);
2409
2410 /* Start session. */
2411 do_authenticated(ssh, authctxt);
2412
2413 /* The connection has been terminated. */
2414 ssh_packet_get_bytes(ssh, &ibytes, &obytes);
2415 verbose("Transferred: sent %llu, received %llu bytes",
2416 (unsigned long long)obytes, (unsigned long long)ibytes);
2417
2418 verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2419
2420 #ifdef USE_PAM
2421 if (options.use_pam)
2422 finish_pam();
2423 #endif /* USE_PAM */
2424
2425 #ifdef SSH_AUDIT_EVENTS
2426 PRIVSEP(audit_event(ssh, SSH_CONNECTION_CLOSE));
2427 #endif
2428
2429 ssh_packet_close(ssh);
2430
2431 if (use_privsep)
2432 mm_terminate();
2433
2434 exit(0);
2435 }
2436
2437 int
2438 sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
2439 struct sshkey *pubkey, u_char **signature, size_t *slenp,
2440 const u_char *data, size_t dlen, const char *alg)
2441 {
2442 int r;
2443
2444 if (use_privsep) {
2445 if (privkey) {
2446 if (mm_sshkey_sign(ssh, privkey, signature, slenp,
2447 data, dlen, alg, options.sk_provider, NULL,
2448 ssh->compat) < 0)
2449 fatal_f("privkey sign failed");
2450 } else {
2451 if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
2452 data, dlen, alg, options.sk_provider, NULL,
2453 ssh->compat) < 0)
2454 fatal_f("pubkey sign failed");
2455 }
2456 } else {
2457 if (privkey) {
2458 if (sshkey_sign(privkey, signature, slenp, data, dlen,
2459 alg, options.sk_provider, NULL, ssh->compat) < 0)
2460 fatal_f("privkey sign failed");
2461 } else {
2462 if ((r = ssh_agent_sign(auth_sock, pubkey,
2463 signature, slenp, data, dlen, alg,
2464 ssh->compat)) != 0) {
2465 fatal_fr(r, "agent sign failed");
2466 }
2467 }
2468 }
2469 return 0;
2470 }
2471
2472 /* SSH2 key exchange */
2473 static void
2474 do_ssh2_kex(struct ssh *ssh)
2475 {
2476 char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2477 struct kex *kex;
2478 char *prop_kex = NULL, *prop_enc = NULL, *prop_hostkey = NULL;
2479 int r;
2480
2481 myproposal[PROPOSAL_KEX_ALGS] = prop_kex = compat_kex_proposal(ssh,
2482 options.kex_algorithms);
2483 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2484 myproposal[PROPOSAL_ENC_ALGS_STOC] = prop_enc =
2485 compat_cipher_proposal(ssh, options.ciphers);
2486 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2487 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2488
2489 if (options.compression == COMP_NONE) {
2490 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2491 myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2492 }
2493
2494 if (options.rekey_limit || options.rekey_interval)
2495 ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
2496 options.rekey_interval);
2497
2498 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = prop_hostkey =
2499 compat_pkalg_proposal(ssh, list_hostkey_types());
2500
2501 /* start key exchange */
2502 if ((r = kex_setup(ssh, myproposal)) != 0)
2503 fatal_r(r, "kex_setup");
2504 kex = ssh->kex;
2505 #ifdef WITH_OPENSSL
2506 kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
2507 kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
2508 kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
2509 kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
2510 kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
2511 kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2512 kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2513 # ifdef OPENSSL_HAS_ECC
2514 kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
2515 # endif
2516 #endif
2517 kex->kex[KEX_C25519_SHA256] = kex_gen_server;
2518 kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
2519 kex->load_host_public_key=&get_hostkey_public_by_type;
2520 kex->load_host_private_key=&get_hostkey_private_by_type;
2521 kex->host_key_index=&get_hostkey_index;
2522 kex->sign = sshd_hostkey_sign;
2523
2524 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
2525
2526 #ifdef DEBUG_KEXDH
2527 /* send 1st encrypted/maced/compressed message */
2528 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
2529 (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
2530 (r = sshpkt_send(ssh)) != 0 ||
2531 (r = ssh_packet_write_wait(ssh)) != 0)
2532 fatal_fr(r, "send test");
2533 #endif
2534 free(prop_kex);
2535 free(prop_enc);
2536 free(prop_hostkey);
2537 debug("KEX done");
2538 }
2539
2540 /* server specific fatal cleanup */
2541 void
2542 cleanup_exit(int i)
2543 {
2544 if (the_active_state != NULL && the_authctxt != NULL) {
2545 do_cleanup(the_active_state, the_authctxt);
2546 if (use_privsep && privsep_is_preauth &&
2547 pmonitor != NULL && pmonitor->m_pid > 1) {
2548 debug("Killing privsep child %d", pmonitor->m_pid);
2549 if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2550 errno != ESRCH) {
2551 error_f("kill(%d): %s", pmonitor->m_pid,
2552 strerror(errno));
2553 }
2554 }
2555 }
2556 #ifdef SSH_AUDIT_EVENTS
2557 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2558 if (the_active_state != NULL && (!use_privsep || mm_is_monitor()))
2559 audit_event(the_active_state, SSH_CONNECTION_ABANDON);
2560 #endif
2561 _exit(i);
2562 }
2563