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