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