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