xref: /freebsd/crypto/openssh/sshd-session.c (revision 61d8af38bf1c5328c27ccfcd8a3b73e9e8604d16)
1 /* $OpenBSD: sshd-session.c,v 1.9 2024/09/09 02:39:57 djm Exp $ */
2 /*
3  * SSH2 implementation:
4  * Privilege Separation:
5  *
6  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
7  * Copyright (c) 2002 Niels Provos.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include "includes.h"
31 
32 #include <sys/types.h>
33 #include <sys/ioctl.h>
34 #include <sys/socket.h>
35 #ifdef HAVE_SYS_STAT_H
36 # include <sys/stat.h>
37 #endif
38 #ifdef HAVE_SYS_TIME_H
39 # include <sys/time.h>
40 #endif
41 #include "openbsd-compat/sys-tree.h"
42 #include "openbsd-compat/sys-queue.h"
43 #include <sys/wait.h>
44 
45 #include <errno.h>
46 #include <fcntl.h>
47 #include <netdb.h>
48 #ifdef HAVE_PATHS_H
49 # include <paths.h>
50 #endif
51 #include <pwd.h>
52 #include <grp.h>
53 #include <signal.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <stdarg.h>
58 #include <unistd.h>
59 #include <limits.h>
60 
61 #ifdef WITH_OPENSSL
62 #include <openssl/bn.h>
63 #include <openssl/evp.h>
64 #include <openssl/rand.h>
65 #include "openbsd-compat/openssl-compat.h"
66 #endif
67 
68 #ifdef HAVE_SECUREWARE
69 #include <sys/security.h>
70 #include <prot.h>
71 #endif
72 
73 #include "xmalloc.h"
74 #include "ssh.h"
75 #include "ssh2.h"
76 #include "sshpty.h"
77 #include "packet.h"
78 #include "log.h"
79 #include "sshbuf.h"
80 #include "misc.h"
81 #include "match.h"
82 #include "servconf.h"
83 #include "uidswap.h"
84 #include "compat.h"
85 #include "cipher.h"
86 #include "digest.h"
87 #include "sshkey.h"
88 #include "kex.h"
89 #include "authfile.h"
90 #include "pathnames.h"
91 #include "atomicio.h"
92 #include "canohost.h"
93 #include "hostfile.h"
94 #include "auth.h"
95 #include "authfd.h"
96 #include "msg.h"
97 #include "dispatch.h"
98 #include "channels.h"
99 #include "session.h"
100 #include "monitor.h"
101 #ifdef GSSAPI
102 #include "ssh-gss.h"
103 #endif
104 #include "monitor_wrap.h"
105 #include "ssh-sandbox.h"
106 #include "auth-options.h"
107 #include "version.h"
108 #include "ssherr.h"
109 #include "sk-api.h"
110 #include "srclimit.h"
111 #include "dh.h"
112 #include "blacklist_client.h"
113 
114 /* Re-exec fds */
115 #define REEXEC_DEVCRYPTO_RESERVED_FD	(STDERR_FILENO + 1)
116 #define REEXEC_STARTUP_PIPE_FD		(STDERR_FILENO + 2)
117 #define REEXEC_CONFIG_PASS_FD		(STDERR_FILENO + 3)
118 #define REEXEC_MIN_FREE_FD		(STDERR_FILENO + 4)
119 
120 extern char *__progname;
121 
122 /* Server configuration options. */
123 ServerOptions options;
124 
125 /* Name of the server configuration file. */
126 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
127 
128 /*
129  * Debug mode flag.  This can be set on the command line.  If debug
130  * mode is enabled, extra debugging output will be sent to the system
131  * log, the daemon will not go to background, and will exit after processing
132  * the first connection.
133  */
134 int debug_flag = 0;
135 
136 /* Flag indicating that the daemon is being started from inetd. */
137 static int inetd_flag = 0;
138 
139 /* debug goes to stderr unless inetd_flag is set */
140 static int log_stderr = 0;
141 
142 /* Saved arguments to main(). */
143 static char **saved_argv;
144 static int saved_argc;
145 
146 /* Daemon's agent connection */
147 int auth_sock = -1;
148 static int have_agent = 0;
149 
150 /*
151  * Any really sensitive data in the application is contained in this
152  * structure. The idea is that this structure could be locked into memory so
153  * that the pages do not get written into swap.  However, there are some
154  * problems. The private key contains BIGNUMs, and we do not (in principle)
155  * have access to the internals of them, and locking just the structure is
156  * not very useful.  Currently, memory locking is not implemented.
157  */
158 struct {
159 	u_int		num_hostkeys;
160 	struct sshkey	**host_keys;		/* all private host keys */
161 	struct sshkey	**host_pubkeys;		/* all public host keys */
162 	struct sshkey	**host_certificates;	/* all public host certificates */
163 } sensitive_data;
164 
165 /* record remote hostname or ip */
166 u_int utmp_len = HOST_NAME_MAX+1;
167 
168 static int startup_pipe = -1;		/* in child */
169 
170 /* variables used for privilege separation */
171 struct monitor *pmonitor = NULL;
172 int privsep_is_preauth = 1;
173 static int privsep_chroot = 1;
174 
175 /* Unprivileged user */
176 struct passwd *privsep_pw = NULL;
177 
178 /* global connection state and authentication contexts */
179 Authctxt *the_authctxt = NULL;
180 struct ssh *the_active_state;
181 
182 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
183 struct sshauthopt *auth_opts = NULL;
184 
185 /* sshd_config buffer */
186 struct sshbuf *cfg;
187 
188 /* Included files from the configuration file */
189 struct include_list includes = TAILQ_HEAD_INITIALIZER(includes);
190 
191 /* message to be displayed after login */
192 struct sshbuf *loginmsg;
193 
194 /* Prototypes for various functions defined later in this file. */
195 void destroy_sensitive_data(void);
196 void demote_sensitive_data(void);
197 static void do_ssh2_kex(struct ssh *);
198 
199 /*
200  * Signal handler for the alarm after the login grace period has expired.
201  * As usual, this may only take signal-safe actions, even though it is
202  * terminal.
203  */
204 static void
grace_alarm_handler(int sig)205 grace_alarm_handler(int sig)
206 {
207 	/*
208 	 * Try to kill any processes that we have spawned, E.g. authorized
209 	 * keys command helpers or privsep children.
210 	 */
211 	if (getpgid(0) == getpid()) {
212 		struct sigaction sa;
213 
214 		/* mask all other signals while in handler */
215 		memset(&sa, 0, sizeof(sa));
216 		sa.sa_handler = SIG_IGN;
217 		sigfillset(&sa.sa_mask);
218 #if defined(SA_RESTART)
219 		sa.sa_flags = SA_RESTART;
220 #endif
221 		(void)sigaction(SIGTERM, &sa, NULL);
222 		kill(0, SIGTERM);
223 	}
224 	_exit(EXIT_LOGIN_GRACE);
225 }
226 
227 /* Destroy the host and server keys.  They will no longer be needed. */
228 void
destroy_sensitive_data(void)229 destroy_sensitive_data(void)
230 {
231 	u_int i;
232 
233 	for (i = 0; i < options.num_host_key_files; i++) {
234 		if (sensitive_data.host_keys[i]) {
235 			sshkey_free(sensitive_data.host_keys[i]);
236 			sensitive_data.host_keys[i] = NULL;
237 		}
238 		if (sensitive_data.host_certificates[i]) {
239 			sshkey_free(sensitive_data.host_certificates[i]);
240 			sensitive_data.host_certificates[i] = NULL;
241 		}
242 	}
243 }
244 
245 /* Demote private to public keys for network child */
246 void
demote_sensitive_data(void)247 demote_sensitive_data(void)
248 {
249 	struct sshkey *tmp;
250 	u_int i;
251 	int r;
252 
253 	for (i = 0; i < options.num_host_key_files; i++) {
254 		if (sensitive_data.host_keys[i]) {
255 			if ((r = sshkey_from_private(
256 			    sensitive_data.host_keys[i], &tmp)) != 0)
257 				fatal_r(r, "could not demote host %s key",
258 				    sshkey_type(sensitive_data.host_keys[i]));
259 			sshkey_free(sensitive_data.host_keys[i]);
260 			sensitive_data.host_keys[i] = tmp;
261 		}
262 		/* Certs do not need demotion */
263 	}
264 }
265 
266 static void
reseed_prngs(void)267 reseed_prngs(void)
268 {
269 	u_int32_t rnd[256];
270 
271 #ifdef WITH_OPENSSL
272 	RAND_poll();
273 #endif
274 	arc4random_stir(); /* noop on recent arc4random() implementations */
275 	arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
276 
277 #ifdef WITH_OPENSSL
278 	RAND_seed(rnd, sizeof(rnd));
279 	/* give libcrypto a chance to notice the PID change */
280 	if ((RAND_bytes((u_char *)rnd, 1)) != 1)
281 		fatal("%s: RAND_bytes failed", __func__);
282 #endif
283 
284 	explicit_bzero(rnd, sizeof(rnd));
285 }
286 
287 static void
privsep_preauth_child(void)288 privsep_preauth_child(void)
289 {
290 	gid_t gidset[1];
291 
292 	/* Enable challenge-response authentication for privilege separation */
293 	privsep_challenge_enable();
294 
295 #ifdef GSSAPI
296 	/* Cache supported mechanism OIDs for later use */
297 	ssh_gssapi_prepare_supported_oids();
298 #endif
299 
300 	reseed_prngs();
301 
302 	/* Demote the private keys to public keys. */
303 	demote_sensitive_data();
304 
305 	/* Demote the child */
306 	if (privsep_chroot) {
307 		/* Change our root directory */
308 		if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
309 			fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
310 			    strerror(errno));
311 		if (chdir("/") == -1)
312 			fatal("chdir(\"/\"): %s", strerror(errno));
313 
314 		/* Drop our privileges */
315 		debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
316 		    (u_int)privsep_pw->pw_gid);
317 		gidset[0] = privsep_pw->pw_gid;
318 		if (setgroups(1, gidset) == -1)
319 			fatal("setgroups: %.100s", strerror(errno));
320 		permanently_set_uid(privsep_pw);
321 	}
322 }
323 
324 static int
privsep_preauth(struct ssh * ssh)325 privsep_preauth(struct ssh *ssh)
326 {
327 	int status, r;
328 	pid_t pid;
329 	struct ssh_sandbox *box = NULL;
330 
331 	/* Set up unprivileged child process to deal with network data */
332 	pmonitor = monitor_init();
333 	/* Store a pointer to the kex for later rekeying */
334 	pmonitor->m_pkex = &ssh->kex;
335 
336 	box = ssh_sandbox_init(pmonitor);
337 	pid = fork();
338 	if (pid == -1) {
339 		fatal("fork of unprivileged child failed");
340 	} else if (pid != 0) {
341 		debug2("Network child is on pid %ld", (long)pid);
342 
343 		pmonitor->m_pid = pid;
344 		if (have_agent) {
345 			r = ssh_get_authentication_socket(&auth_sock);
346 			if (r != 0) {
347 				error_r(r, "Could not get agent socket");
348 				have_agent = 0;
349 			}
350 		}
351 		if (box != NULL)
352 			ssh_sandbox_parent_preauth(box, pid);
353 		monitor_child_preauth(ssh, pmonitor);
354 
355 		/* Wait for the child's exit status */
356 		while (waitpid(pid, &status, 0) == -1) {
357 			if (errno == EINTR)
358 				continue;
359 			pmonitor->m_pid = -1;
360 			fatal_f("waitpid: %s", strerror(errno));
361 		}
362 		privsep_is_preauth = 0;
363 		pmonitor->m_pid = -1;
364 		if (WIFEXITED(status)) {
365 			if (WEXITSTATUS(status) != 0)
366 				fatal_f("preauth child exited with status %d",
367 				    WEXITSTATUS(status));
368 		} else if (WIFSIGNALED(status))
369 			fatal_f("preauth child terminated by signal %d",
370 			    WTERMSIG(status));
371 		if (box != NULL)
372 			ssh_sandbox_parent_finish(box);
373 		return 1;
374 	} else {
375 		/* child */
376 		close(pmonitor->m_sendfd);
377 		close(pmonitor->m_log_recvfd);
378 
379 		/* Arrange for logging to be sent to the monitor */
380 		set_log_handler(mm_log_handler, pmonitor);
381 
382 		privsep_preauth_child();
383 		setproctitle("%s", "[net]");
384 		if (box != NULL)
385 			ssh_sandbox_child(box);
386 
387 		return 0;
388 	}
389 }
390 
391 static void
privsep_postauth(struct ssh * ssh,Authctxt * authctxt)392 privsep_postauth(struct ssh *ssh, Authctxt *authctxt)
393 {
394 	int skip_privdrop = 0;
395 
396 	/*
397 	 * Hack for systems that don't support FD passing: retain privileges
398 	 * in the post-auth privsep process so it can allocate PTYs directly.
399 	 * This is basically equivalent to what we did <= 9.7, which was to
400 	 * disable post-auth privsep entriely.
401 	 * Cygwin doesn't need to drop privs here although it doesn't support
402 	 * fd passing, as AFAIK PTY allocation on this platform doesn't require
403 	 * special privileges to begin with.
404 	 */
405 #if defined(DISABLE_FD_PASSING) && !defined(HAVE_CYGWIN)
406 	skip_privdrop = 1;
407 #endif
408 
409 	/* New socket pair */
410 	monitor_reinit(pmonitor);
411 
412 	pmonitor->m_pid = fork();
413 	if (pmonitor->m_pid == -1)
414 		fatal("fork of unprivileged child failed");
415 	else if (pmonitor->m_pid != 0) {
416 		verbose("User child is on pid %ld", (long)pmonitor->m_pid);
417 		sshbuf_reset(loginmsg);
418 		monitor_clear_keystate(ssh, pmonitor);
419 		monitor_child_postauth(ssh, pmonitor);
420 
421 		/* NEVERREACHED */
422 		exit(0);
423 	}
424 
425 	/* child */
426 
427 	close(pmonitor->m_sendfd);
428 	pmonitor->m_sendfd = -1;
429 
430 	/* Demote the private keys to public keys. */
431 	demote_sensitive_data();
432 
433 	reseed_prngs();
434 
435 	/* Drop privileges */
436 	if (!skip_privdrop)
437 		do_setusercontext(authctxt->pw);
438 
439 	/* It is safe now to apply the key state */
440 	monitor_apply_keystate(ssh, pmonitor);
441 
442 	/*
443 	 * Tell the packet layer that authentication was successful, since
444 	 * this information is not part of the key state.
445 	 */
446 	ssh_packet_set_authenticated(ssh);
447 }
448 
449 static void
append_hostkey_type(struct sshbuf * b,const char * s)450 append_hostkey_type(struct sshbuf *b, const char *s)
451 {
452 	int r;
453 
454 	if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
455 		debug3_f("%s key not permitted by HostkeyAlgorithms", s);
456 		return;
457 	}
458 	if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
459 		fatal_fr(r, "sshbuf_putf");
460 }
461 
462 static char *
list_hostkey_types(void)463 list_hostkey_types(void)
464 {
465 	struct sshbuf *b;
466 	struct sshkey *key;
467 	char *ret;
468 	u_int i;
469 
470 	if ((b = sshbuf_new()) == NULL)
471 		fatal_f("sshbuf_new failed");
472 	for (i = 0; i < options.num_host_key_files; i++) {
473 		key = sensitive_data.host_keys[i];
474 		if (key == NULL)
475 			key = sensitive_data.host_pubkeys[i];
476 		if (key == NULL)
477 			continue;
478 		switch (key->type) {
479 		case KEY_RSA:
480 			/* for RSA we also support SHA2 signatures */
481 			append_hostkey_type(b, "rsa-sha2-512");
482 			append_hostkey_type(b, "rsa-sha2-256");
483 			/* FALLTHROUGH */
484 		case KEY_DSA:
485 		case KEY_ECDSA:
486 		case KEY_ED25519:
487 		case KEY_ECDSA_SK:
488 		case KEY_ED25519_SK:
489 		case KEY_XMSS:
490 			append_hostkey_type(b, sshkey_ssh_name(key));
491 			break;
492 		}
493 		/* If the private key has a cert peer, then list that too */
494 		key = sensitive_data.host_certificates[i];
495 		if (key == NULL)
496 			continue;
497 		switch (key->type) {
498 		case KEY_RSA_CERT:
499 			/* for RSA we also support SHA2 signatures */
500 			append_hostkey_type(b,
501 			    "rsa-sha2-512-cert-v01@openssh.com");
502 			append_hostkey_type(b,
503 			    "rsa-sha2-256-cert-v01@openssh.com");
504 			/* FALLTHROUGH */
505 		case KEY_DSA_CERT:
506 		case KEY_ECDSA_CERT:
507 		case KEY_ED25519_CERT:
508 		case KEY_ECDSA_SK_CERT:
509 		case KEY_ED25519_SK_CERT:
510 		case KEY_XMSS_CERT:
511 			append_hostkey_type(b, sshkey_ssh_name(key));
512 			break;
513 		}
514 	}
515 	if ((ret = sshbuf_dup_string(b)) == NULL)
516 		fatal_f("sshbuf_dup_string failed");
517 	sshbuf_free(b);
518 	debug_f("%s", ret);
519 	return ret;
520 }
521 
522 static struct sshkey *
get_hostkey_by_type(int type,int nid,int need_private,struct ssh * ssh)523 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
524 {
525 	u_int i;
526 	struct sshkey *key;
527 
528 	for (i = 0; i < options.num_host_key_files; i++) {
529 		switch (type) {
530 		case KEY_RSA_CERT:
531 		case KEY_DSA_CERT:
532 		case KEY_ECDSA_CERT:
533 		case KEY_ED25519_CERT:
534 		case KEY_ECDSA_SK_CERT:
535 		case KEY_ED25519_SK_CERT:
536 		case KEY_XMSS_CERT:
537 			key = sensitive_data.host_certificates[i];
538 			break;
539 		default:
540 			key = sensitive_data.host_keys[i];
541 			if (key == NULL && !need_private)
542 				key = sensitive_data.host_pubkeys[i];
543 			break;
544 		}
545 		if (key == NULL || key->type != type)
546 			continue;
547 		switch (type) {
548 		case KEY_ECDSA:
549 		case KEY_ECDSA_SK:
550 		case KEY_ECDSA_CERT:
551 		case KEY_ECDSA_SK_CERT:
552 			if (key->ecdsa_nid != nid)
553 				continue;
554 			/* FALLTHROUGH */
555 		default:
556 			return need_private ?
557 			    sensitive_data.host_keys[i] : key;
558 		}
559 	}
560 	return NULL;
561 }
562 
563 struct sshkey *
get_hostkey_public_by_type(int type,int nid,struct ssh * ssh)564 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
565 {
566 	return get_hostkey_by_type(type, nid, 0, ssh);
567 }
568 
569 struct sshkey *
get_hostkey_private_by_type(int type,int nid,struct ssh * ssh)570 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
571 {
572 	return get_hostkey_by_type(type, nid, 1, ssh);
573 }
574 
575 struct sshkey *
get_hostkey_by_index(int ind)576 get_hostkey_by_index(int ind)
577 {
578 	if (ind < 0 || (u_int)ind >= options.num_host_key_files)
579 		return (NULL);
580 	return (sensitive_data.host_keys[ind]);
581 }
582 
583 struct sshkey *
get_hostkey_public_by_index(int ind,struct ssh * ssh)584 get_hostkey_public_by_index(int ind, struct ssh *ssh)
585 {
586 	if (ind < 0 || (u_int)ind >= options.num_host_key_files)
587 		return (NULL);
588 	return (sensitive_data.host_pubkeys[ind]);
589 }
590 
591 int
get_hostkey_index(struct sshkey * key,int compare,struct ssh * ssh)592 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
593 {
594 	u_int i;
595 
596 	for (i = 0; i < options.num_host_key_files; i++) {
597 		if (sshkey_is_cert(key)) {
598 			if (key == sensitive_data.host_certificates[i] ||
599 			    (compare && sensitive_data.host_certificates[i] &&
600 			    sshkey_equal(key,
601 			    sensitive_data.host_certificates[i])))
602 				return (i);
603 		} else {
604 			if (key == sensitive_data.host_keys[i] ||
605 			    (compare && sensitive_data.host_keys[i] &&
606 			    sshkey_equal(key, sensitive_data.host_keys[i])))
607 				return (i);
608 			if (key == sensitive_data.host_pubkeys[i] ||
609 			    (compare && sensitive_data.host_pubkeys[i] &&
610 			    sshkey_equal(key, sensitive_data.host_pubkeys[i])))
611 				return (i);
612 		}
613 	}
614 	return (-1);
615 }
616 
617 /* Inform the client of all hostkeys */
618 static void
notify_hostkeys(struct ssh * ssh)619 notify_hostkeys(struct ssh *ssh)
620 {
621 	struct sshbuf *buf;
622 	struct sshkey *key;
623 	u_int i, nkeys;
624 	int r;
625 	char *fp;
626 
627 	/* Some clients cannot cope with the hostkeys message, skip those. */
628 	if (ssh->compat & SSH_BUG_HOSTKEYS)
629 		return;
630 
631 	if ((buf = sshbuf_new()) == NULL)
632 		fatal_f("sshbuf_new");
633 	for (i = nkeys = 0; i < options.num_host_key_files; i++) {
634 		key = get_hostkey_public_by_index(i, ssh);
635 		if (key == NULL || key->type == KEY_UNSPEC ||
636 		    sshkey_is_cert(key))
637 			continue;
638 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
639 		    SSH_FP_DEFAULT);
640 		debug3_f("key %d: %s %s", i, sshkey_ssh_name(key), fp);
641 		free(fp);
642 		if (nkeys == 0) {
643 			/*
644 			 * Start building the request when we find the
645 			 * first usable key.
646 			 */
647 			if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
648 			    (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 ||
649 			    (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */
650 				sshpkt_fatal(ssh, r, "%s: start request", __func__);
651 		}
652 		/* Append the key to the request */
653 		sshbuf_reset(buf);
654 		if ((r = sshkey_putb(key, buf)) != 0)
655 			fatal_fr(r, "couldn't put hostkey %d", i);
656 		if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
657 			sshpkt_fatal(ssh, r, "%s: append key", __func__);
658 		nkeys++;
659 	}
660 	debug3_f("sent %u hostkeys", nkeys);
661 	if (nkeys == 0)
662 		fatal_f("no hostkeys");
663 	if ((r = sshpkt_send(ssh)) != 0)
664 		sshpkt_fatal(ssh, r, "%s: send", __func__);
665 	sshbuf_free(buf);
666 }
667 
668 static void
usage(void)669 usage(void)
670 {
671 	fprintf(stderr, "%s, %s\n", SSH_RELEASE, SSH_OPENSSL_VERSION);
672 	fprintf(stderr,
673 "usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n"
674 "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
675 "            [-h host_key_file] [-o option] [-p port] [-u len]\n"
676 	);
677 	exit(1);
678 }
679 
680 static void
parse_hostkeys(struct sshbuf * hostkeys)681 parse_hostkeys(struct sshbuf *hostkeys)
682 {
683 	int r;
684 	u_int num_keys = 0;
685 	struct sshkey *k;
686 	struct sshbuf *kbuf;
687 	const u_char *cp;
688 	size_t len;
689 
690 	while (sshbuf_len(hostkeys) != 0) {
691 		if (num_keys > 2048)
692 			fatal_f("too many hostkeys");
693 		sensitive_data.host_keys = xrecallocarray(
694 		    sensitive_data.host_keys, num_keys, num_keys + 1,
695 		    sizeof(*sensitive_data.host_pubkeys));
696 		sensitive_data.host_pubkeys = xrecallocarray(
697 		    sensitive_data.host_pubkeys, num_keys, num_keys + 1,
698 		    sizeof(*sensitive_data.host_pubkeys));
699 		sensitive_data.host_certificates = xrecallocarray(
700 		    sensitive_data.host_certificates, num_keys, num_keys + 1,
701 		    sizeof(*sensitive_data.host_certificates));
702 		/* private key */
703 		k = NULL;
704 		if ((r = sshbuf_froms(hostkeys, &kbuf)) != 0)
705 			fatal_fr(r, "extract privkey");
706 		if (sshbuf_len(kbuf) != 0 &&
707 		    (r = sshkey_private_deserialize(kbuf, &k)) != 0)
708 			fatal_fr(r, "parse pubkey");
709 		sensitive_data.host_keys[num_keys] = k;
710 		sshbuf_free(kbuf);
711 		if (k)
712 			debug2_f("privkey %u: %s", num_keys, sshkey_ssh_name(k));
713 		/* public key */
714 		k = NULL;
715 		if ((r = sshbuf_get_string_direct(hostkeys, &cp, &len)) != 0)
716 			fatal_fr(r, "extract pubkey");
717 		if (len != 0 && (r = sshkey_from_blob(cp, len, &k)) != 0)
718 			fatal_fr(r, "parse pubkey");
719 		sensitive_data.host_pubkeys[num_keys] = k;
720 		if (k)
721 			debug2_f("pubkey %u: %s", num_keys, sshkey_ssh_name(k));
722 		/* certificate */
723 		k = NULL;
724 		if ((r = sshbuf_get_string_direct(hostkeys, &cp, &len)) != 0)
725 			fatal_fr(r, "extract pubkey");
726 		if (len != 0 && (r = sshkey_from_blob(cp, len, &k)) != 0)
727 			fatal_fr(r, "parse pubkey");
728 		sensitive_data.host_certificates[num_keys] = k;
729 		if (k)
730 			debug2_f("cert %u: %s", num_keys, sshkey_ssh_name(k));
731 		num_keys++;
732 	}
733 	sensitive_data.num_hostkeys = num_keys;
734 }
735 
736 static void
recv_rexec_state(int fd,struct sshbuf * conf,uint64_t * timing_secretp)737 recv_rexec_state(int fd, struct sshbuf *conf, uint64_t *timing_secretp)
738 {
739 	struct sshbuf *m, *inc, *hostkeys;
740 	u_char *cp, ver;
741 	size_t len;
742 	int r;
743 	struct include_item *item;
744 
745 	debug3_f("entering fd = %d", fd);
746 
747 	if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL)
748 		fatal_f("sshbuf_new failed");
749 	if (ssh_msg_recv(fd, m) == -1)
750 		fatal_f("ssh_msg_recv failed");
751 	if ((r = sshbuf_get_u8(m, &ver)) != 0)
752 		fatal_fr(r, "parse version");
753 	if (ver != 0)
754 		fatal_f("rexec version mismatch");
755 	if ((r = sshbuf_get_string(m, &cp, &len)) != 0 || /* XXX _direct */
756 	    (r = sshbuf_get_u64(m, timing_secretp)) != 0 ||
757 	    (r = sshbuf_froms(m, &hostkeys)) != 0 ||
758 	    (r = sshbuf_get_stringb(m, inc)) != 0)
759 		fatal_fr(r, "parse config");
760 
761 	if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
762 		fatal_fr(r, "sshbuf_put");
763 
764 	while (sshbuf_len(inc) != 0) {
765 		item = xcalloc(1, sizeof(*item));
766 		if ((item->contents = sshbuf_new()) == NULL)
767 			fatal_f("sshbuf_new failed");
768 		if ((r = sshbuf_get_cstring(inc, &item->selector, NULL)) != 0 ||
769 		    (r = sshbuf_get_cstring(inc, &item->filename, NULL)) != 0 ||
770 		    (r = sshbuf_get_stringb(inc, item->contents)) != 0)
771 			fatal_fr(r, "parse includes");
772 		TAILQ_INSERT_TAIL(&includes, item, entry);
773 	}
774 
775 	parse_hostkeys(hostkeys);
776 
777 	free(cp);
778 	sshbuf_free(m);
779 	sshbuf_free(hostkeys);
780 	sshbuf_free(inc);
781 
782 	debug3_f("done");
783 }
784 
785 /*
786  * If IP options are supported, make sure there are none (log and
787  * return an error if any are found).  Basically we are worried about
788  * source routing; it can be used to pretend you are somebody
789  * (ip-address) you are not. That itself may be "almost acceptable"
790  * under certain circumstances, but rhosts authentication is useless
791  * if source routing is accepted. Notice also that if we just dropped
792  * source routing here, the other side could use IP spoofing to do
793  * rest of the interaction and could still bypass security.  So we
794  * exit here if we detect any IP options.
795  */
796 static void
check_ip_options(struct ssh * ssh)797 check_ip_options(struct ssh *ssh)
798 {
799 #ifdef IP_OPTIONS
800 	int sock_in = ssh_packet_get_connection_in(ssh);
801 	struct sockaddr_storage from;
802 	u_char opts[200];
803 	socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
804 	char text[sizeof(opts) * 3 + 1];
805 
806 	memset(&from, 0, sizeof(from));
807 	if (getpeername(sock_in, (struct sockaddr *)&from,
808 	    &fromlen) == -1)
809 		return;
810 	if (from.ss_family != AF_INET)
811 		return;
812 	/* XXX IPv6 options? */
813 
814 	if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
815 	    &option_size) >= 0 && option_size != 0) {
816 		text[0] = '\0';
817 		for (i = 0; i < option_size; i++)
818 			snprintf(text + i*3, sizeof(text) - i*3,
819 			    " %2.2x", opts[i]);
820 		fatal("Connection from %.100s port %d with IP opts: %.800s",
821 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
822 	}
823 #endif /* IP_OPTIONS */
824 }
825 
826 /* Set the routing domain for this process */
827 static void
set_process_rdomain(struct ssh * ssh,const char * name)828 set_process_rdomain(struct ssh *ssh, const char *name)
829 {
830 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
831 	if (name == NULL)
832 		return; /* default */
833 
834 	if (strcmp(name, "%D") == 0) {
835 		/* "expands" to routing domain of connection */
836 		if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
837 			return;
838 	}
839 	/* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
840 	return sys_set_process_rdomain(name);
841 #elif defined(__OpenBSD__)
842 	int rtable, ortable = getrtable();
843 	const char *errstr;
844 
845 	if (name == NULL)
846 		return; /* default */
847 
848 	if (strcmp(name, "%D") == 0) {
849 		/* "expands" to routing domain of connection */
850 		if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
851 			return;
852 	}
853 
854 	rtable = (int)strtonum(name, 0, 255, &errstr);
855 	if (errstr != NULL) /* Shouldn't happen */
856 		fatal("Invalid routing domain \"%s\": %s", name, errstr);
857 	if (rtable != ortable && setrtable(rtable) != 0)
858 		fatal("Unable to set routing domain %d: %s",
859 		    rtable, strerror(errno));
860 	debug_f("set routing domain %d (was %d)", rtable, ortable);
861 #else /* defined(__OpenBSD__) */
862 	fatal("Unable to set routing domain: not supported in this platform");
863 #endif
864 }
865 
866 /*
867  * Main program for the daemon.
868  */
869 int
main(int ac,char ** av)870 main(int ac, char **av)
871 {
872 	struct ssh *ssh = NULL;
873 	extern char *optarg;
874 	extern int optind;
875 	int r, opt, on = 1, remote_port;
876 	int sock_in = -1, sock_out = -1, rexeced_flag = 0, have_key = 0;
877 	const char *remote_ip, *rdomain;
878 	char *line, *laddr, *logfile = NULL;
879 	u_int i;
880 	u_int64_t ibytes, obytes;
881 	mode_t new_umask;
882 	Authctxt *authctxt;
883 	struct connection_info *connection_info = NULL;
884 	sigset_t sigmask;
885 	uint64_t timing_secret = 0;
886 	struct itimerval itv;
887 
888 	sigemptyset(&sigmask);
889 	sigprocmask(SIG_SETMASK, &sigmask, NULL);
890 
891 #ifdef HAVE_SECUREWARE
892 	(void)set_auth_parameters(ac, av);
893 #endif
894 	__progname = ssh_get_progname(av[0]);
895 
896 	/* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
897 	saved_argc = ac;
898 	saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
899 	for (i = 0; (int)i < ac; i++)
900 		saved_argv[i] = xstrdup(av[i]);
901 	saved_argv[i] = NULL;
902 
903 #ifndef HAVE_SETPROCTITLE
904 	/* Prepare for later setproctitle emulation */
905 	compat_init_setproctitle(ac, av);
906 	av = saved_argv;
907 #endif
908 
909 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
910 	sanitise_stdfd();
911 
912 	/* Initialize configuration options to their default values. */
913 	initialize_server_options(&options);
914 
915 	/* Parse command-line arguments. */
916 	while ((opt = getopt(ac, av,
917 	    "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) {
918 		switch (opt) {
919 		case '4':
920 			options.address_family = AF_INET;
921 			break;
922 		case '6':
923 			options.address_family = AF_INET6;
924 			break;
925 		case 'f':
926 			config_file_name = optarg;
927 			break;
928 		case 'c':
929 			servconf_add_hostcert("[command-line]", 0,
930 			    &options, optarg);
931 			break;
932 		case 'd':
933 			if (debug_flag == 0) {
934 				debug_flag = 1;
935 				options.log_level = SYSLOG_LEVEL_DEBUG1;
936 			} else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
937 				options.log_level++;
938 			break;
939 		case 'D':
940 			/* ignore */
941 			break;
942 		case 'E':
943 			logfile = optarg;
944 			/* FALLTHROUGH */
945 		case 'e':
946 			log_stderr = 1;
947 			break;
948 		case 'i':
949 			inetd_flag = 1;
950 			break;
951 		case 'r':
952 			/* ignore */
953 			break;
954 		case 'R':
955 			rexeced_flag = 1;
956 			break;
957 		case 'Q':
958 			/* ignored */
959 			break;
960 		case 'q':
961 			options.log_level = SYSLOG_LEVEL_QUIET;
962 			break;
963 		case 'b':
964 			/* protocol 1, ignored */
965 			break;
966 		case 'p':
967 			options.ports_from_cmdline = 1;
968 			if (options.num_ports >= MAX_PORTS) {
969 				fprintf(stderr, "too many ports.\n");
970 				exit(1);
971 			}
972 			options.ports[options.num_ports++] = a2port(optarg);
973 			if (options.ports[options.num_ports-1] <= 0) {
974 				fprintf(stderr, "Bad port number.\n");
975 				exit(1);
976 			}
977 			break;
978 		case 'g':
979 			if ((options.login_grace_time = convtime(optarg)) == -1) {
980 				fprintf(stderr, "Invalid login grace time.\n");
981 				exit(1);
982 			}
983 			break;
984 		case 'k':
985 			/* protocol 1, ignored */
986 			break;
987 		case 'h':
988 			servconf_add_hostkey("[command-line]", 0,
989 			    &options, optarg, 1);
990 			break;
991 		case 't':
992 		case 'T':
993 		case 'G':
994 			fatal("test/dump modes not supported");
995 			break;
996 		case 'C':
997 			connection_info = server_get_connection_info(ssh, 0, 0);
998 			if (parse_server_match_testspec(connection_info,
999 			    optarg) == -1)
1000 				exit(1);
1001 			break;
1002 		case 'u':
1003 			utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1004 			if (utmp_len > HOST_NAME_MAX+1) {
1005 				fprintf(stderr, "Invalid utmp length.\n");
1006 				exit(1);
1007 			}
1008 			break;
1009 		case 'o':
1010 			line = xstrdup(optarg);
1011 			if (process_server_config_line(&options, line,
1012 			    "command-line", 0, NULL, NULL, &includes) != 0)
1013 				exit(1);
1014 			free(line);
1015 			break;
1016 		case 'V':
1017 			fprintf(stderr, "%s, %s\n",
1018 			    SSH_RELEASE, SSH_OPENSSL_VERSION);
1019 			exit(0);
1020 		default:
1021 			usage();
1022 			break;
1023 		}
1024 	}
1025 
1026 	/* Check that there are no remaining arguments. */
1027 	if (optind < ac) {
1028 		fprintf(stderr, "Extra argument %s.\n", av[optind]);
1029 		exit(1);
1030 	}
1031 
1032 	debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1033 
1034 	if (!rexeced_flag)
1035 		fatal("sshd-session should not be executed directly");
1036 
1037 	closefrom(REEXEC_MIN_FREE_FD);
1038 
1039 	seed_rng();
1040 
1041 	/* If requested, redirect the logs to the specified logfile. */
1042 	if (logfile != NULL) {
1043 		char *cp, pid_s[32];
1044 
1045 		snprintf(pid_s, sizeof(pid_s), "%ld", (unsigned long)getpid());
1046 		cp = percent_expand(logfile,
1047 		    "p", pid_s,
1048 		    "P", "sshd-session",
1049 		    (char *)NULL);
1050 		log_redirect_stderr_to(cp);
1051 		free(cp);
1052 	}
1053 
1054 	/*
1055 	 * Force logging to stderr until we have loaded the private host
1056 	 * key (unless started from inetd)
1057 	 */
1058 	log_init(__progname,
1059 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1060 	    SYSLOG_LEVEL_INFO : options.log_level,
1061 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1062 	    SYSLOG_FACILITY_AUTH : options.log_facility,
1063 	    log_stderr || !inetd_flag || debug_flag);
1064 
1065 	debug("sshd version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION);
1066 
1067 	/* Fetch our configuration */
1068 	if ((cfg = sshbuf_new()) == NULL)
1069 		fatal("sshbuf_new config buf failed");
1070 	setproctitle("%s", "[rexeced]");
1071 	recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg, &timing_secret);
1072 	close(REEXEC_CONFIG_PASS_FD);
1073 	parse_server_config(&options, "rexec", cfg, &includes, NULL, 1);
1074 	/* Fill in default values for those options not explicitly set. */
1075 	fill_default_server_options(&options);
1076 	options.timing_secret = timing_secret;
1077 
1078 	/* Store privilege separation user for later use if required. */
1079 	privsep_chroot = (getuid() == 0 || geteuid() == 0);
1080 	if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1081 		if (privsep_chroot || options.kerberos_authentication)
1082 			fatal("Privilege separation user %s does not exist",
1083 			    SSH_PRIVSEP_USER);
1084 	} else {
1085 		privsep_pw = pwcopy(privsep_pw);
1086 		freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
1087 		privsep_pw->pw_passwd = xstrdup("*");
1088 	}
1089 	endpwent();
1090 
1091 	if (!debug_flag) {
1092 		startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1093 		close(REEXEC_STARTUP_PIPE_FD);
1094 		/*
1095 		 * Signal parent that this child is at a point where
1096 		 * they can go away if they have a SIGHUP pending.
1097 		 */
1098 		(void)atomicio(vwrite, startup_pipe, "\0", 1);
1099 	}
1100 
1101 	/* Check that options are sensible */
1102 	if (options.authorized_keys_command_user == NULL &&
1103 	    (options.authorized_keys_command != NULL &&
1104 	    strcasecmp(options.authorized_keys_command, "none") != 0))
1105 		fatal("AuthorizedKeysCommand set without "
1106 		    "AuthorizedKeysCommandUser");
1107 	if (options.authorized_principals_command_user == NULL &&
1108 	    (options.authorized_principals_command != NULL &&
1109 	    strcasecmp(options.authorized_principals_command, "none") != 0))
1110 		fatal("AuthorizedPrincipalsCommand set without "
1111 		    "AuthorizedPrincipalsCommandUser");
1112 
1113 	/*
1114 	 * Check whether there is any path through configured auth methods.
1115 	 * Unfortunately it is not possible to verify this generally before
1116 	 * daemonisation in the presence of Match block, but this catches
1117 	 * and warns for trivial misconfigurations that could break login.
1118 	 */
1119 	if (options.num_auth_methods != 0) {
1120 		for (i = 0; i < options.num_auth_methods; i++) {
1121 			if (auth2_methods_valid(options.auth_methods[i],
1122 			    1) == 0)
1123 				break;
1124 		}
1125 		if (i >= options.num_auth_methods)
1126 			fatal("AuthenticationMethods cannot be satisfied by "
1127 			    "enabled authentication methods");
1128 	}
1129 
1130 #ifdef WITH_OPENSSL
1131 	if (options.moduli_file != NULL)
1132 		dh_set_moduli_file(options.moduli_file);
1133 #endif
1134 
1135 	if (options.host_key_agent) {
1136 		if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1137 			setenv(SSH_AUTHSOCKET_ENV_NAME,
1138 			    options.host_key_agent, 1);
1139 		if ((r = ssh_get_authentication_socket(NULL)) == 0)
1140 			have_agent = 1;
1141 		else
1142 			error_r(r, "Could not connect to agent \"%s\"",
1143 			    options.host_key_agent);
1144 	}
1145 
1146 	if (options.num_host_key_files != sensitive_data.num_hostkeys) {
1147 		fatal("internal error: hostkeys confused (config %u recvd %u)",
1148 		    options.num_host_key_files, sensitive_data.num_hostkeys);
1149 	}
1150 
1151 	for (i = 0; i < options.num_host_key_files; i++) {
1152 		if (sensitive_data.host_keys[i] != NULL ||
1153 		    (have_agent && sensitive_data.host_pubkeys[i] != NULL)) {
1154 			have_key = 1;
1155 			break;
1156 		}
1157 	}
1158 	if (!have_key)
1159 		fatal("internal error: monitor received no hostkeys");
1160 
1161 	/* Ensure that umask disallows at least group and world write */
1162 	new_umask = umask(0077) | 0022;
1163 	(void) umask(new_umask);
1164 
1165 	/* Initialize the log (it is reinitialized below in case we forked). */
1166 	if (debug_flag)
1167 		log_stderr = 1;
1168 	log_init(__progname, options.log_level,
1169 	    options.log_facility, log_stderr);
1170 	for (i = 0; i < options.num_log_verbose; i++)
1171 		log_verbose_add(options.log_verbose[i]);
1172 
1173 	/* Reinitialize the log (because of the fork above). */
1174 	log_init(__progname, options.log_level, options.log_facility, log_stderr);
1175 
1176 	/*
1177 	 * Chdir to the root directory so that the current disk can be
1178 	 * unmounted if desired.
1179 	 */
1180 	if (chdir("/") == -1)
1181 		error("chdir(\"/\"): %s", strerror(errno));
1182 
1183 	/* ignore SIGPIPE */
1184 	ssh_signal(SIGPIPE, SIG_IGN);
1185 
1186 	/* Get a connection, either from inetd or rexec */
1187 	if (inetd_flag) {
1188 		/*
1189 		 * NB. must be different fd numbers for the !socket case,
1190 		 * as packet_connection_is_on_socket() depends on this.
1191 		 */
1192 		sock_in = dup(STDIN_FILENO);
1193 		sock_out = dup(STDOUT_FILENO);
1194 	} else {
1195 		/* rexec case; accept()ed socket in ancestor listener */
1196 		sock_in = sock_out = dup(STDIN_FILENO);
1197 	}
1198 
1199 	/*
1200 	 * We intentionally do not close the descriptors 0, 1, and 2
1201 	 * as our code for setting the descriptors won't work if
1202 	 * ttyfd happens to be one of those.
1203 	 */
1204 	if (stdfd_devnull(1, 1, !log_stderr) == -1)
1205 		error("stdfd_devnull failed");
1206 	debug("network sockets: %d, %d", sock_in, sock_out);
1207 
1208 	/* This is the child processing a new connection. */
1209 	setproctitle("%s", "[accepted]");
1210 
1211 	/* Executed child processes don't need these. */
1212 	fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1213 	fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1214 
1215 	/* We will not restart on SIGHUP since it no longer makes sense. */
1216 	ssh_signal(SIGALRM, SIG_DFL);
1217 	ssh_signal(SIGHUP, SIG_DFL);
1218 	ssh_signal(SIGTERM, SIG_DFL);
1219 	ssh_signal(SIGQUIT, SIG_DFL);
1220 	ssh_signal(SIGCHLD, SIG_DFL);
1221 	ssh_signal(SIGINT, SIG_DFL);
1222 
1223 	/*
1224 	 * Register our connection.  This turns encryption off because we do
1225 	 * not have a key.
1226 	 */
1227 	if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
1228 		fatal("Unable to create connection");
1229 	the_active_state = ssh;
1230 	ssh_packet_set_server(ssh);
1231 
1232 	check_ip_options(ssh);
1233 
1234 	/* Prepare the channels layer */
1235 	channel_init_channels(ssh);
1236 	channel_set_af(ssh, options.address_family);
1237 	server_process_channel_timeouts(ssh);
1238 	server_process_permitopen(ssh);
1239 
1240 	/* Set SO_KEEPALIVE if requested. */
1241 	if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) &&
1242 	    setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1)
1243 		error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1244 
1245 	if ((remote_port = ssh_remote_port(ssh)) < 0) {
1246 		debug("ssh_remote_port failed");
1247 		cleanup_exit(255);
1248 	}
1249 
1250 #ifdef HAVE_LOGIN_CAP
1251 	/* Also caches remote hostname for sandboxed child. */
1252 	auth_get_canonical_hostname(ssh, options.use_dns);
1253 #endif
1254 
1255 	/*
1256 	 * The rest of the code depends on the fact that
1257 	 * ssh_remote_ipaddr() caches the remote ip, even if
1258 	 * the socket goes away.
1259 	 */
1260 	remote_ip = ssh_remote_ipaddr(ssh);
1261 
1262 #ifdef SSH_AUDIT_EVENTS
1263 	audit_connection_from(remote_ip, remote_port);
1264 #endif
1265 
1266 	rdomain = ssh_packet_rdomain_in(ssh);
1267 
1268 	/* Log the connection. */
1269 	laddr = get_local_ipaddr(sock_in);
1270 	verbose("Connection from %s port %d on %s port %d%s%s%s",
1271 	    remote_ip, remote_port, laddr,  ssh_local_port(ssh),
1272 	    rdomain == NULL ? "" : " rdomain \"",
1273 	    rdomain == NULL ? "" : rdomain,
1274 	    rdomain == NULL ? "" : "\"");
1275 	free(laddr);
1276 
1277 	/*
1278 	 * We don't want to listen forever unless the other side
1279 	 * successfully authenticates itself.  So we set up an alarm which is
1280 	 * cleared after successful authentication.  A limit of zero
1281 	 * indicates no limit. Note that we don't set the alarm in debugging
1282 	 * mode; it is just annoying to have the server exit just when you
1283 	 * are about to discover the bug.
1284 	 */
1285 	ssh_signal(SIGALRM, grace_alarm_handler);
1286 	if (!debug_flag && options.login_grace_time > 0) {
1287 		int ujitter = arc4random_uniform(4 * 1000000);
1288 
1289 		timerclear(&itv.it_interval);
1290 		itv.it_value.tv_sec = options.login_grace_time;
1291 		itv.it_value.tv_sec += ujitter / 1000000;
1292 		itv.it_value.tv_usec = ujitter % 1000000;
1293 
1294 		if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
1295 			fatal("login grace time setitimer failed");
1296 	}
1297 
1298 	if ((r = kex_exchange_identification(ssh, -1,
1299 	    options.version_addendum)) != 0)
1300 		sshpkt_fatal(ssh, r, "banner exchange");
1301 
1302 	ssh_packet_set_nonblocking(ssh);
1303 
1304 	/* allocate authentication context */
1305 	authctxt = xcalloc(1, sizeof(*authctxt));
1306 	ssh->authctxt = authctxt;
1307 
1308 	/* XXX global for cleanup, access from other modules */
1309 	the_authctxt = authctxt;
1310 
1311 	/* Set default key authentication options */
1312 	if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
1313 		fatal("allocation failed");
1314 
1315 	/* prepare buffer to collect messages to display to user after login */
1316 	if ((loginmsg = sshbuf_new()) == NULL)
1317 		fatal("sshbuf_new loginmsg failed");
1318 	auth_debug_reset();
1319 
1320 	BLACKLIST_INIT();
1321 
1322 	if (privsep_preauth(ssh) == 1)
1323 		goto authenticated;
1324 
1325 	/* perform the key exchange */
1326 	/* authenticate user and start session */
1327 	do_ssh2_kex(ssh);
1328 	do_authentication2(ssh);
1329 
1330 	/*
1331 	 * The unprivileged child now transfers the current keystate and exits.
1332 	 */
1333 	mm_send_keystate(ssh, pmonitor);
1334 	ssh_packet_clear_keys(ssh);
1335 	exit(0);
1336 
1337  authenticated:
1338 	/*
1339 	 * Cancel the alarm we set to limit the time taken for
1340 	 * authentication.
1341 	 */
1342 	timerclear(&itv.it_interval);
1343 	timerclear(&itv.it_value);
1344 	if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
1345 		fatal("login grace time clear failed");
1346 	ssh_signal(SIGALRM, SIG_DFL);
1347 	authctxt->authenticated = 1;
1348 	if (startup_pipe != -1) {
1349 		/* signal listener that authentication completed successfully */
1350 		(void)atomicio(vwrite, startup_pipe, "\001", 1);
1351 		close(startup_pipe);
1352 		startup_pipe = -1;
1353 	}
1354 
1355 	if (options.routing_domain != NULL)
1356 		set_process_rdomain(ssh, options.routing_domain);
1357 
1358 #ifdef SSH_AUDIT_EVENTS
1359 	audit_event(ssh, SSH_AUTH_SUCCESS);
1360 #endif
1361 
1362 #ifdef GSSAPI
1363 	if (options.gss_authentication) {
1364 		temporarily_use_uid(authctxt->pw);
1365 		ssh_gssapi_storecreds();
1366 		restore_uid();
1367 	}
1368 #endif
1369 #ifdef USE_PAM
1370 	if (options.use_pam) {
1371 		do_pam_setcred();
1372 		do_pam_session(ssh);
1373 	}
1374 #endif
1375 
1376 	/*
1377 	 * In privilege separation, we fork another child and prepare
1378 	 * file descriptor passing.
1379 	 */
1380 	privsep_postauth(ssh, authctxt);
1381 	/* the monitor process [priv] will not return */
1382 
1383 	ssh_packet_set_timeout(ssh, options.client_alive_interval,
1384 	    options.client_alive_count_max);
1385 
1386 	/* Try to send all our hostkeys to the client */
1387 	notify_hostkeys(ssh);
1388 
1389 	/* Start session. */
1390 	do_authenticated(ssh, authctxt);
1391 
1392 	/* The connection has been terminated. */
1393 	ssh_packet_get_bytes(ssh, &ibytes, &obytes);
1394 	verbose("Transferred: sent %llu, received %llu bytes",
1395 	    (unsigned long long)obytes, (unsigned long long)ibytes);
1396 
1397 	verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1398 
1399 #ifdef USE_PAM
1400 	if (options.use_pam)
1401 		finish_pam();
1402 #endif /* USE_PAM */
1403 
1404 #ifdef SSH_AUDIT_EVENTS
1405 	mm_audit_event(ssh, SSH_CONNECTION_CLOSE);
1406 #endif
1407 
1408 	ssh_packet_close(ssh);
1409 
1410 	mm_terminate();
1411 
1412 	exit(0);
1413 }
1414 
1415 int
sshd_hostkey_sign(struct ssh * ssh,struct sshkey * privkey,struct sshkey * pubkey,u_char ** signature,size_t * slenp,const u_char * data,size_t dlen,const char * alg)1416 sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey,
1417     struct sshkey *pubkey, u_char **signature, size_t *slenp,
1418     const u_char *data, size_t dlen, const char *alg)
1419 {
1420 	if (privkey) {
1421 		if (mm_sshkey_sign(ssh, privkey, signature, slenp,
1422 		    data, dlen, alg, options.sk_provider, NULL,
1423 		    ssh->compat) < 0)
1424 			fatal_f("privkey sign failed");
1425 	} else {
1426 		if (mm_sshkey_sign(ssh, pubkey, signature, slenp,
1427 		    data, dlen, alg, options.sk_provider, NULL,
1428 		    ssh->compat) < 0)
1429 			fatal_f("pubkey sign failed");
1430 	}
1431 	return 0;
1432 }
1433 
1434 /* SSH2 key exchange */
1435 static void
do_ssh2_kex(struct ssh * ssh)1436 do_ssh2_kex(struct ssh *ssh)
1437 {
1438 	char *hkalgs = NULL, *myproposal[PROPOSAL_MAX];
1439 	const char *compression = NULL;
1440 	struct kex *kex;
1441 	int r;
1442 
1443 	if (options.rekey_limit || options.rekey_interval)
1444 		ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
1445 		    options.rekey_interval);
1446 
1447 	if (options.compression == COMP_NONE)
1448 		compression = "none";
1449 	hkalgs = list_hostkey_types();
1450 
1451 	kex_proposal_populate_entries(ssh, myproposal, options.kex_algorithms,
1452 	    options.ciphers, options.macs, compression, hkalgs);
1453 
1454 	free(hkalgs);
1455 
1456 	/* start key exchange */
1457 	if ((r = kex_setup(ssh, myproposal)) != 0)
1458 		fatal_r(r, "kex_setup");
1459 	kex_set_server_sig_algs(ssh, options.pubkey_accepted_algos);
1460 	kex = ssh->kex;
1461 
1462 #ifdef WITH_OPENSSL
1463 	kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
1464 	kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
1465 	kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
1466 	kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
1467 	kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
1468 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1469 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1470  #ifdef OPENSSL_HAS_ECC
1471 	kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
1472  #endif
1473 #endif
1474 	kex->kex[KEX_C25519_SHA256] = kex_gen_server;
1475 	kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
1476  	kex->kex[KEX_KEM_MLKEM768X25519_SHA256] = kex_gen_server;
1477 	kex->load_host_public_key=&get_hostkey_public_by_type;
1478 	kex->load_host_private_key=&get_hostkey_private_by_type;
1479 	kex->host_key_index=&get_hostkey_index;
1480 	kex->sign = sshd_hostkey_sign;
1481 
1482 	ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
1483 	kex_proposal_free_entries(myproposal);
1484 
1485 #ifdef DEBUG_KEXDH
1486 	/* send 1st encrypted/maced/compressed message */
1487 	if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 ||
1488 	    (r = sshpkt_put_cstring(ssh, "markus")) != 0 ||
1489 	    (r = sshpkt_send(ssh)) != 0 ||
1490 	    (r = ssh_packet_write_wait(ssh)) != 0)
1491 		fatal_fr(r, "send test");
1492 #endif
1493 	debug("KEX done");
1494 }
1495 
1496 /* server specific fatal cleanup */
1497 void
cleanup_exit(int i)1498 cleanup_exit(int i)
1499 {
1500 	extern int auth_attempted; /* monitor.c */
1501 
1502 	if (the_active_state != NULL && the_authctxt != NULL) {
1503 		do_cleanup(the_active_state, the_authctxt);
1504 		if (privsep_is_preauth &&
1505 		    pmonitor != NULL && pmonitor->m_pid > 1) {
1506 			debug("Killing privsep child %d", pmonitor->m_pid);
1507 			if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
1508 			    errno != ESRCH) {
1509 				error_f("kill(%d): %s", pmonitor->m_pid,
1510 				    strerror(errno));
1511 			}
1512 		}
1513 	}
1514 #ifdef SSH_AUDIT_EVENTS
1515 	/* done after do_cleanup so it can cancel the PAM auth 'thread' */
1516 	if (the_active_state != NULL && mm_is_monitor())
1517 		audit_event(the_active_state, SSH_CONNECTION_ABANDON);
1518 #endif
1519 	/* Override default fatal exit value when auth was attempted */
1520 	if (i == 255 && auth_attempted)
1521 		_exit(EXIT_AUTH_ATTEMPTED);
1522 	_exit(i);
1523 }
1524