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