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