xref: /openbsd/usr.bin/ssh/monitor.c (revision 9e6efb0a)
1 /* $OpenBSD: monitor.c,v 1.239 2024/05/17 06:42:04 jsg Exp $ */
2 /*
3  * Copyright 2002 Niels Provos <provos@citi.umich.edu>
4  * Copyright 2002 Markus Friedl <markus@openbsd.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 #include <sys/socket.h>
31 #include <sys/tree.h>
32 #include <sys/queue.h>
33 
34 #ifdef WITH_OPENSSL
35 #include <openssl/dh.h>
36 #endif
37 
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <limits.h>
41 #include <paths.h>
42 #include <poll.h>
43 #include <pwd.h>
44 #include <signal.h>
45 #include <stdarg.h>
46 #include <stdint.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 
52 #include "atomicio.h"
53 #include "xmalloc.h"
54 #include "ssh.h"
55 #include "sshkey.h"
56 #include "sshbuf.h"
57 #include "hostfile.h"
58 #include "auth.h"
59 #include "cipher.h"
60 #include "kex.h"
61 #include "dh.h"
62 #include "packet.h"
63 #include "auth-options.h"
64 #include "sshpty.h"
65 #include "channels.h"
66 #include "session.h"
67 #include "sshlogin.h"
68 #include "canohost.h"
69 #include "log.h"
70 #include "misc.h"
71 #include "servconf.h"
72 #include "monitor.h"
73 #ifdef GSSAPI
74 #include "ssh-gss.h"
75 #endif
76 #include "monitor_wrap.h"
77 #include "monitor_fdpass.h"
78 #include "compat.h"
79 #include "ssh2.h"
80 #include "authfd.h"
81 #include "match.h"
82 #include "ssherr.h"
83 #include "sk-api.h"
84 
85 #ifdef GSSAPI
86 static Gssctxt *gsscontext = NULL;
87 #endif
88 
89 /* Imports */
90 extern ServerOptions options;
91 extern u_int utmp_len;
92 extern struct sshbuf *loginmsg;
93 extern struct sshauthopt *auth_opts; /* XXX move to permanent ssh->authctxt? */
94 
95 /* State exported from the child */
96 static struct sshbuf *child_state;
97 
98 /* Functions on the monitor that answer unprivileged requests */
99 
100 int mm_answer_moduli(struct ssh *, int, struct sshbuf *);
101 int mm_answer_sign(struct ssh *, int, struct sshbuf *);
102 int mm_answer_pwnamallow(struct ssh *, int, struct sshbuf *);
103 int mm_answer_auth2_read_banner(struct ssh *, int, struct sshbuf *);
104 int mm_answer_authserv(struct ssh *, int, struct sshbuf *);
105 int mm_answer_authpassword(struct ssh *, int, struct sshbuf *);
106 int mm_answer_bsdauthquery(struct ssh *, int, struct sshbuf *);
107 int mm_answer_bsdauthrespond(struct ssh *, int, struct sshbuf *);
108 int mm_answer_keyallowed(struct ssh *, int, struct sshbuf *);
109 int mm_answer_keyverify(struct ssh *, int, struct sshbuf *);
110 int mm_answer_pty(struct ssh *, int, struct sshbuf *);
111 int mm_answer_pty_cleanup(struct ssh *, int, struct sshbuf *);
112 int mm_answer_term(struct ssh *, int, struct sshbuf *);
113 
114 #ifdef GSSAPI
115 int mm_answer_gss_setup_ctx(struct ssh *, int, struct sshbuf *);
116 int mm_answer_gss_accept_ctx(struct ssh *, int, struct sshbuf *);
117 int mm_answer_gss_userok(struct ssh *, int, struct sshbuf *);
118 int mm_answer_gss_checkmic(struct ssh *, int, struct sshbuf *);
119 #endif
120 
121 static Authctxt *authctxt;
122 
123 /* local state for key verify */
124 static u_char *key_blob = NULL;
125 static size_t key_bloblen = 0;
126 static u_int key_blobtype = MM_NOKEY;
127 static struct sshauthopt *key_opts = NULL;
128 static char *hostbased_cuser = NULL;
129 static char *hostbased_chost = NULL;
130 static char *auth_method = "unknown";
131 static char *auth_submethod = NULL;
132 static u_int session_id2_len = 0;
133 static u_char *session_id2 = NULL;
134 static pid_t monitor_child_pid;
135 
136 struct mon_table {
137 	enum monitor_reqtype type;
138 	int flags;
139 	int (*f)(struct ssh *, int, struct sshbuf *);
140 };
141 
142 #define MON_ISAUTH	0x0004	/* Required for Authentication */
143 #define MON_AUTHDECIDE	0x0008	/* Decides Authentication */
144 #define MON_ONCE	0x0010	/* Disable after calling */
145 #define MON_ALOG	0x0020	/* Log auth attempt without authenticating */
146 
147 #define MON_AUTH	(MON_ISAUTH|MON_AUTHDECIDE)
148 
149 #define MON_PERMIT	0x1000	/* Request is permitted */
150 
151 static int monitor_read(struct ssh *, struct monitor *, struct mon_table *,
152     struct mon_table **);
153 static int monitor_read_log(struct monitor *);
154 
155 struct mon_table mon_dispatch_proto20[] = {
156 #ifdef WITH_OPENSSL
157     {MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli},
158 #endif
159     {MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign},
160     {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
161     {MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv},
162     {MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner},
163     {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
164     {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
165     {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
166     {MONITOR_REQ_KEYALLOWED, MON_ISAUTH, mm_answer_keyallowed},
167     {MONITOR_REQ_KEYVERIFY, MON_AUTH, mm_answer_keyverify},
168 #ifdef GSSAPI
169     {MONITOR_REQ_GSSSETUP, MON_ISAUTH, mm_answer_gss_setup_ctx},
170     {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
171     {MONITOR_REQ_GSSUSEROK, MON_ONCE|MON_AUTHDECIDE, mm_answer_gss_userok},
172     {MONITOR_REQ_GSSCHECKMIC, MON_ONCE, mm_answer_gss_checkmic},
173 #endif
174     {0, 0, NULL}
175 };
176 
177 struct mon_table mon_dispatch_postauth20[] = {
178 #ifdef WITH_OPENSSL
179     {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
180 #endif
181     {MONITOR_REQ_SIGN, 0, mm_answer_sign},
182     {MONITOR_REQ_PTY, 0, mm_answer_pty},
183     {MONITOR_REQ_PTYCLEANUP, 0, mm_answer_pty_cleanup},
184     {MONITOR_REQ_TERM, 0, mm_answer_term},
185     {0, 0, NULL}
186 };
187 
188 struct mon_table *mon_dispatch;
189 
190 /* Specifies if a certain message is allowed at the moment */
191 static void
192 monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit)
193 {
194 	while (ent->f != NULL) {
195 		if (ent->type == type) {
196 			ent->flags &= ~MON_PERMIT;
197 			ent->flags |= permit ? MON_PERMIT : 0;
198 			return;
199 		}
200 		ent++;
201 	}
202 }
203 
204 static void
205 monitor_permit_authentications(int permit)
206 {
207 	struct mon_table *ent = mon_dispatch;
208 
209 	while (ent->f != NULL) {
210 		if (ent->flags & MON_AUTH) {
211 			ent->flags &= ~MON_PERMIT;
212 			ent->flags |= permit ? MON_PERMIT : 0;
213 		}
214 		ent++;
215 	}
216 }
217 
218 void
219 monitor_child_preauth(struct ssh *ssh, struct monitor *pmonitor)
220 {
221 	struct mon_table *ent;
222 	int authenticated = 0, partial = 0;
223 
224 	debug3("preauth child monitor started");
225 
226 	if (pmonitor->m_recvfd >= 0)
227 		close(pmonitor->m_recvfd);
228 	if (pmonitor->m_log_sendfd >= 0)
229 		close(pmonitor->m_log_sendfd);
230 	pmonitor->m_log_sendfd = pmonitor->m_recvfd = -1;
231 
232 	authctxt = (Authctxt *)ssh->authctxt;
233 	memset(authctxt, 0, sizeof(*authctxt));
234 	ssh->authctxt = authctxt;
235 
236 	mon_dispatch = mon_dispatch_proto20;
237 	/* Permit requests for moduli and signatures */
238 	monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
239 	monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
240 
241 	/* The first few requests do not require asynchronous access */
242 	while (!authenticated) {
243 		partial = 0;
244 		auth_method = "unknown";
245 		auth_submethod = NULL;
246 		auth2_authctxt_reset_info(authctxt);
247 
248 		authenticated = (monitor_read(ssh, pmonitor,
249 		    mon_dispatch, &ent) == 1);
250 
251 		/* Special handling for multiple required authentications */
252 		if (options.num_auth_methods != 0) {
253 			if (authenticated &&
254 			    !auth2_update_methods_lists(authctxt,
255 			    auth_method, auth_submethod)) {
256 				debug3_f("method %s: partial", auth_method);
257 				authenticated = 0;
258 				partial = 1;
259 			}
260 		}
261 
262 		if (authenticated) {
263 			if (!(ent->flags & MON_AUTHDECIDE))
264 				fatal_f("unexpected authentication from %d",
265 				    ent->type);
266 			if (authctxt->pw->pw_uid == 0 &&
267 			    !auth_root_allowed(ssh, auth_method))
268 				authenticated = 0;
269 		}
270 		if (ent->flags & (MON_AUTHDECIDE|MON_ALOG)) {
271 			auth_log(ssh, authenticated, partial,
272 			    auth_method, auth_submethod);
273 			if (!partial && !authenticated)
274 				authctxt->failures++;
275 			if (authenticated || partial) {
276 				auth2_update_session_info(authctxt,
277 				    auth_method, auth_submethod);
278 			}
279 		}
280 		if (authctxt->failures > options.max_authtries) {
281 			/* Shouldn't happen */
282 			fatal_f("privsep child made too many authentication "
283 			    "attempts");
284 		}
285 	}
286 
287 	if (!authctxt->valid)
288 		fatal_f("authenticated invalid user");
289 	if (strcmp(auth_method, "unknown") == 0)
290 		fatal_f("authentication method name unknown");
291 
292 	debug_f("user %s authenticated by privileged process", authctxt->user);
293 	ssh->authctxt = NULL;
294 	ssh_packet_set_log_preamble(ssh, "user %s", authctxt->user);
295 
296 	mm_get_keystate(ssh, pmonitor);
297 
298 	/* Drain any buffered messages from the child */
299 	while (pmonitor->m_log_recvfd != -1 && monitor_read_log(pmonitor) == 0)
300 		;
301 
302 	if (pmonitor->m_recvfd >= 0)
303 		close(pmonitor->m_recvfd);
304 	if (pmonitor->m_log_sendfd >= 0)
305 		close(pmonitor->m_log_sendfd);
306 	pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1;
307 }
308 
309 static void
310 monitor_set_child_handler(pid_t pid)
311 {
312 	monitor_child_pid = pid;
313 }
314 
315 static void
316 monitor_child_handler(int sig)
317 {
318 	kill(monitor_child_pid, sig);
319 }
320 
321 void
322 monitor_child_postauth(struct ssh *ssh, struct monitor *pmonitor)
323 {
324 	close(pmonitor->m_recvfd);
325 	pmonitor->m_recvfd = -1;
326 
327 	monitor_set_child_handler(pmonitor->m_pid);
328 	ssh_signal(SIGHUP, &monitor_child_handler);
329 	ssh_signal(SIGTERM, &monitor_child_handler);
330 	ssh_signal(SIGINT, &monitor_child_handler);
331 
332 	mon_dispatch = mon_dispatch_postauth20;
333 
334 	/* Permit requests for moduli and signatures */
335 	monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
336 	monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
337 	monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
338 
339 	if (auth_opts->permit_pty_flag) {
340 		monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1);
341 		monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1);
342 	}
343 
344 	for (;;)
345 		monitor_read(ssh, pmonitor, mon_dispatch, NULL);
346 }
347 
348 static int
349 monitor_read_log(struct monitor *pmonitor)
350 {
351 	struct sshbuf *logmsg;
352 	u_int len, level, forced;
353 	char *msg;
354 	u_char *p;
355 	int r;
356 
357 	if ((logmsg = sshbuf_new()) == NULL)
358 		fatal_f("sshbuf_new");
359 
360 	/* Read length */
361 	if ((r = sshbuf_reserve(logmsg, 4, &p)) != 0)
362 		fatal_fr(r, "reserve len");
363 	if (atomicio(read, pmonitor->m_log_recvfd, p, 4) != 4) {
364 		if (errno == EPIPE) {
365 			sshbuf_free(logmsg);
366 			debug_f("child log fd closed");
367 			close(pmonitor->m_log_recvfd);
368 			pmonitor->m_log_recvfd = -1;
369 			return -1;
370 		}
371 		fatal_f("log fd read: %s", strerror(errno));
372 	}
373 	if ((r = sshbuf_get_u32(logmsg, &len)) != 0)
374 		fatal_fr(r, "parse len");
375 	if (len <= 4 || len > 8192)
376 		fatal_f("invalid log message length %u", len);
377 
378 	/* Read severity, message */
379 	sshbuf_reset(logmsg);
380 	if ((r = sshbuf_reserve(logmsg, len, &p)) != 0)
381 		fatal_fr(r, "reserve msg");
382 	if (atomicio(read, pmonitor->m_log_recvfd, p, len) != len)
383 		fatal_f("log fd read: %s", strerror(errno));
384 	if ((r = sshbuf_get_u32(logmsg, &level)) != 0 ||
385 	    (r = sshbuf_get_u32(logmsg, &forced)) != 0 ||
386 	    (r = sshbuf_get_cstring(logmsg, &msg, NULL)) != 0)
387 		fatal_fr(r, "parse");
388 
389 	/* Log it */
390 	if (log_level_name(level) == NULL)
391 		fatal_f("invalid log level %u (corrupted message?)", level);
392 	sshlogdirect(level, forced, "%s [preauth]", msg);
393 
394 	sshbuf_free(logmsg);
395 	free(msg);
396 
397 	return 0;
398 }
399 
400 static int
401 monitor_read(struct ssh *ssh, struct monitor *pmonitor, struct mon_table *ent,
402     struct mon_table **pent)
403 {
404 	struct sshbuf *m;
405 	int r, ret;
406 	u_char type;
407 	struct pollfd pfd[2];
408 
409 	for (;;) {
410 		memset(&pfd, 0, sizeof(pfd));
411 		pfd[0].fd = pmonitor->m_sendfd;
412 		pfd[0].events = POLLIN;
413 		pfd[1].fd = pmonitor->m_log_recvfd;
414 		pfd[1].events = pfd[1].fd == -1 ? 0 : POLLIN;
415 		if (poll(pfd, pfd[1].fd == -1 ? 1 : 2, -1) == -1) {
416 			if (errno == EINTR || errno == EAGAIN)
417 				continue;
418 			fatal_f("poll: %s", strerror(errno));
419 		}
420 		if (pfd[1].revents) {
421 			/*
422 			 * Drain all log messages before processing next
423 			 * monitor request.
424 			 */
425 			monitor_read_log(pmonitor);
426 			continue;
427 		}
428 		if (pfd[0].revents)
429 			break;  /* Continues below */
430 	}
431 
432 	if ((m = sshbuf_new()) == NULL)
433 		fatal_f("sshbuf_new");
434 
435 	mm_request_receive(pmonitor->m_sendfd, m);
436 	if ((r = sshbuf_get_u8(m, &type)) != 0)
437 		fatal_fr(r, "parse type");
438 
439 	debug3_f("checking request %d", type);
440 
441 	while (ent->f != NULL) {
442 		if (ent->type == type)
443 			break;
444 		ent++;
445 	}
446 
447 	if (ent->f != NULL) {
448 		if (!(ent->flags & MON_PERMIT))
449 			fatal_f("unpermitted request %d", type);
450 		ret = (*ent->f)(ssh, pmonitor->m_sendfd, m);
451 		sshbuf_free(m);
452 
453 		/* The child may use this request only once, disable it */
454 		if (ent->flags & MON_ONCE) {
455 			debug2_f("%d used once, disabling now", type);
456 			ent->flags &= ~MON_PERMIT;
457 		}
458 
459 		if (pent != NULL)
460 			*pent = ent;
461 
462 		return ret;
463 	}
464 
465 	fatal_f("unsupported request: %d", type);
466 
467 	/* NOTREACHED */
468 	return (-1);
469 }
470 
471 /* allowed key state */
472 static int
473 monitor_allowed_key(const u_char *blob, u_int bloblen)
474 {
475 	/* make sure key is allowed */
476 	if (key_blob == NULL || key_bloblen != bloblen ||
477 	    timingsafe_bcmp(key_blob, blob, key_bloblen))
478 		return (0);
479 	return (1);
480 }
481 
482 static void
483 monitor_reset_key_state(void)
484 {
485 	/* reset state */
486 	free(key_blob);
487 	free(hostbased_cuser);
488 	free(hostbased_chost);
489 	sshauthopt_free(key_opts);
490 	key_blob = NULL;
491 	key_bloblen = 0;
492 	key_blobtype = MM_NOKEY;
493 	key_opts = NULL;
494 	hostbased_cuser = NULL;
495 	hostbased_chost = NULL;
496 }
497 
498 #ifdef WITH_OPENSSL
499 int
500 mm_answer_moduli(struct ssh *ssh, int sock, struct sshbuf *m)
501 {
502 	DH *dh;
503 	const BIGNUM *dh_p, *dh_g;
504 	int r;
505 	u_int min, want, max;
506 
507 	if ((r = sshbuf_get_u32(m, &min)) != 0 ||
508 	    (r = sshbuf_get_u32(m, &want)) != 0 ||
509 	    (r = sshbuf_get_u32(m, &max)) != 0)
510 		fatal_fr(r, "parse");
511 
512 	debug3_f("got parameters: %d %d %d", min, want, max);
513 	/* We need to check here, too, in case the child got corrupted */
514 	if (max < min || want < min || max < want)
515 		fatal_f("bad parameters: %d %d %d", min, want, max);
516 
517 	sshbuf_reset(m);
518 
519 	dh = choose_dh(min, want, max);
520 	if (dh == NULL) {
521 		if ((r = sshbuf_put_u8(m, 0)) != 0)
522 			fatal_fr(r, "assemble empty");
523 		return (0);
524 	} else {
525 		/* Send first bignum */
526 		DH_get0_pqg(dh, &dh_p, NULL, &dh_g);
527 		if ((r = sshbuf_put_u8(m, 1)) != 0 ||
528 		    (r = sshbuf_put_bignum2(m, dh_p)) != 0 ||
529 		    (r = sshbuf_put_bignum2(m, dh_g)) != 0)
530 			fatal_fr(r, "assemble");
531 
532 		DH_free(dh);
533 	}
534 	mm_request_send(sock, MONITOR_ANS_MODULI, m);
535 	return (0);
536 }
537 #endif
538 
539 int
540 mm_answer_sign(struct ssh *ssh, int sock, struct sshbuf *m)
541 {
542 	extern int auth_sock;			/* XXX move to state struct? */
543 	struct sshkey *key;
544 	struct sshbuf *sigbuf = NULL;
545 	u_char *p = NULL, *signature = NULL;
546 	char *alg = NULL;
547 	size_t datlen, siglen, alglen;
548 	int r, is_proof = 0;
549 	u_int keyid, compat;
550 	const char proof_req[] = "hostkeys-prove-00@openssh.com";
551 
552 	debug3_f("entering");
553 
554 	if ((r = sshbuf_get_u32(m, &keyid)) != 0 ||
555 	    (r = sshbuf_get_string(m, &p, &datlen)) != 0 ||
556 	    (r = sshbuf_get_cstring(m, &alg, &alglen)) != 0 ||
557 	    (r = sshbuf_get_u32(m, &compat)) != 0)
558 		fatal_fr(r, "parse");
559 	if (keyid > INT_MAX)
560 		fatal_f("invalid key ID");
561 
562 	/*
563 	 * Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes),
564 	 * SHA384 (48 bytes) and SHA512 (64 bytes).
565 	 *
566 	 * Otherwise, verify the signature request is for a hostkey
567 	 * proof.
568 	 *
569 	 * XXX perform similar check for KEX signature requests too?
570 	 * it's not trivial, since what is signed is the hash, rather
571 	 * than the full kex structure...
572 	 */
573 	if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64) {
574 		/*
575 		 * Construct expected hostkey proof and compare it to what
576 		 * the client sent us.
577 		 */
578 		if (session_id2_len == 0) /* hostkeys is never first */
579 			fatal_f("bad data length: %zu", datlen);
580 		if ((key = get_hostkey_public_by_index(keyid, ssh)) == NULL)
581 			fatal_f("no hostkey for index %d", keyid);
582 		if ((sigbuf = sshbuf_new()) == NULL)
583 			fatal_f("sshbuf_new");
584 		if ((r = sshbuf_put_cstring(sigbuf, proof_req)) != 0 ||
585 		    (r = sshbuf_put_string(sigbuf, session_id2,
586 		    session_id2_len)) != 0 ||
587 		    (r = sshkey_puts(key, sigbuf)) != 0)
588 			fatal_fr(r, "assemble private key proof");
589 		if (datlen != sshbuf_len(sigbuf) ||
590 		    memcmp(p, sshbuf_ptr(sigbuf), sshbuf_len(sigbuf)) != 0)
591 			fatal_f("bad data length: %zu, hostkey proof len %zu",
592 			    datlen, sshbuf_len(sigbuf));
593 		sshbuf_free(sigbuf);
594 		is_proof = 1;
595 	}
596 
597 	/* save session id, it will be passed on the first call */
598 	if (session_id2_len == 0) {
599 		session_id2_len = datlen;
600 		session_id2 = xmalloc(session_id2_len);
601 		memcpy(session_id2, p, session_id2_len);
602 	}
603 
604 	if ((key = get_hostkey_by_index(keyid)) != NULL) {
605 		if ((r = sshkey_sign(key, &signature, &siglen, p, datlen, alg,
606 		    options.sk_provider, NULL, compat)) != 0)
607 			fatal_fr(r, "sign");
608 	} else if ((key = get_hostkey_public_by_index(keyid, ssh)) != NULL &&
609 	    auth_sock > 0) {
610 		if ((r = ssh_agent_sign(auth_sock, key, &signature, &siglen,
611 		    p, datlen, alg, compat)) != 0)
612 			fatal_fr(r, "agent sign");
613 	} else
614 		fatal_f("no hostkey from index %d", keyid);
615 
616 	debug3_f("%s %s signature len=%zu", alg,
617 	    is_proof ? "hostkey proof" : "KEX", siglen);
618 
619 	sshbuf_reset(m);
620 	if ((r = sshbuf_put_string(m, signature, siglen)) != 0)
621 		fatal_fr(r, "assemble");
622 
623 	free(alg);
624 	free(p);
625 	free(signature);
626 
627 	mm_request_send(sock, MONITOR_ANS_SIGN, m);
628 
629 	/* Turn on permissions for getpwnam */
630 	monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
631 
632 	return (0);
633 }
634 
635 #define PUTPW(b, id) \
636 	do { \
637 		if ((r = sshbuf_put_string(b, \
638 		    &pwent->id, sizeof(pwent->id))) != 0) \
639 			fatal_fr(r, "assemble %s", #id); \
640 	} while (0)
641 
642 void
643 mm_encode_server_options(struct sshbuf *m)
644 {
645 	int r;
646 	u_int i;
647 
648 	/* XXX this leaks raw pointers to the unpriv child processes */
649 	if ((r = sshbuf_put_string(m, &options, sizeof(options))) != 0)
650 		fatal_fr(r, "assemble options");
651 
652 #define M_CP_STROPT(x) do { \
653 		if (options.x != NULL && \
654 		    (r = sshbuf_put_cstring(m, options.x)) != 0) \
655 			fatal_fr(r, "assemble %s", #x); \
656 	} while (0)
657 #define M_CP_STRARRAYOPT(x, nx) do { \
658 		for (i = 0; i < options.nx; i++) { \
659 			if ((r = sshbuf_put_cstring(m, options.x[i])) != 0) \
660 				fatal_fr(r, "assemble %s", #x); \
661 		} \
662 	} while (0)
663 	/* See comment in servconf.h */
664 	COPY_MATCH_STRING_OPTS();
665 #undef M_CP_STROPT
666 #undef M_CP_STRARRAYOPT
667 }
668 
669 /* Retrieves the password entry and also checks if the user is permitted */
670 int
671 mm_answer_pwnamallow(struct ssh *ssh, int sock, struct sshbuf *m)
672 {
673 	struct passwd *pwent;
674 	int r, allowed = 0;
675 
676 	debug3_f("entering");
677 
678 	if (authctxt->attempt++ != 0)
679 		fatal_f("multiple attempts for getpwnam");
680 
681 	if ((r = sshbuf_get_cstring(m, &authctxt->user, NULL)) != 0)
682 		fatal_fr(r, "parse");
683 
684 	pwent = getpwnamallow(ssh, authctxt->user);
685 
686 	setproctitle("%s [priv]", pwent ? authctxt->user : "unknown");
687 
688 	sshbuf_reset(m);
689 
690 	if (pwent == NULL) {
691 		if ((r = sshbuf_put_u8(m, 0)) != 0)
692 			fatal_fr(r, "assemble fakepw");
693 		authctxt->pw = fakepw();
694 		goto out;
695 	}
696 
697 	allowed = 1;
698 	authctxt->pw = pwent;
699 	authctxt->valid = 1;
700 
701 	/* XXX send fake class/dir/shell, etc. */
702 	if ((r = sshbuf_put_u8(m, 1)) != 0)
703 		fatal_fr(r, "assemble ok");
704 	PUTPW(m, pw_uid);
705 	PUTPW(m, pw_gid);
706 	PUTPW(m, pw_change);
707 	PUTPW(m, pw_expire);
708 	if ((r = sshbuf_put_cstring(m, pwent->pw_name)) != 0 ||
709 	    (r = sshbuf_put_cstring(m, "*")) != 0 ||
710 	    (r = sshbuf_put_cstring(m, pwent->pw_gecos)) != 0 ||
711 	    (r = sshbuf_put_cstring(m, pwent->pw_class)) != 0 ||
712 	    (r = sshbuf_put_cstring(m, pwent->pw_dir)) != 0 ||
713 	    (r = sshbuf_put_cstring(m, pwent->pw_shell)) != 0)
714 		fatal_fr(r, "assemble pw");
715 
716  out:
717 	ssh_packet_set_log_preamble(ssh, "%suser %s",
718 	    authctxt->valid ? "authenticating" : "invalid ", authctxt->user);
719 
720 	/* Send active options to unpriv */
721 	mm_encode_server_options(m);
722 
723 	/* Create valid auth method lists */
724 	if (auth2_setup_methods_lists(authctxt) != 0) {
725 		/*
726 		 * The monitor will continue long enough to let the child
727 		 * run to its packet_disconnect(), but it must not allow any
728 		 * authentication to succeed.
729 		 */
730 		debug_f("no valid authentication method lists");
731 	}
732 
733 	debug3_f("sending MONITOR_ANS_PWNAM: %d", allowed);
734 	mm_request_send(sock, MONITOR_ANS_PWNAM, m);
735 
736 	/* Allow service/style information on the auth context */
737 	monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
738 	monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
739 
740 	return (0);
741 }
742 
743 int mm_answer_auth2_read_banner(struct ssh *ssh, int sock, struct sshbuf *m)
744 {
745 	char *banner;
746 	int r;
747 
748 	sshbuf_reset(m);
749 	banner = auth2_read_banner();
750 	if ((r = sshbuf_put_cstring(m, banner != NULL ? banner : "")) != 0)
751 		fatal_fr(r, "assemble");
752 	mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
753 	free(banner);
754 
755 	return (0);
756 }
757 
758 int
759 mm_answer_authserv(struct ssh *ssh, int sock, struct sshbuf *m)
760 {
761 	int r;
762 
763 	monitor_permit_authentications(1);
764 
765 	if ((r = sshbuf_get_cstring(m, &authctxt->service, NULL)) != 0 ||
766 	    (r = sshbuf_get_cstring(m, &authctxt->style, NULL)) != 0)
767 		fatal_fr(r, "parse");
768 	debug3_f("service=%s, style=%s", authctxt->service, authctxt->style);
769 
770 	if (strlen(authctxt->style) == 0) {
771 		free(authctxt->style);
772 		authctxt->style = NULL;
773 	}
774 
775 	return (0);
776 }
777 
778 int
779 mm_answer_authpassword(struct ssh *ssh, int sock, struct sshbuf *m)
780 {
781 	static int call_count;
782 	char *passwd;
783 	int r, authenticated;
784 	size_t plen;
785 
786 	if (!options.password_authentication)
787 		fatal_f("password authentication not enabled");
788 	if ((r = sshbuf_get_cstring(m, &passwd, &plen)) != 0)
789 		fatal_fr(r, "parse");
790 	/* Only authenticate if the context is valid */
791 	authenticated = options.password_authentication &&
792 	    auth_password(ssh, passwd);
793 	freezero(passwd, plen);
794 
795 	sshbuf_reset(m);
796 	if ((r = sshbuf_put_u32(m, authenticated)) != 0)
797 		fatal_fr(r, "assemble");
798 
799 	debug3_f("sending result %d", authenticated);
800 	mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
801 
802 	call_count++;
803 	if (plen == 0 && call_count == 1)
804 		auth_method = "none";
805 	else
806 		auth_method = "password";
807 
808 	/* Causes monitor loop to terminate if authenticated */
809 	return (authenticated);
810 }
811 
812 int
813 mm_answer_bsdauthquery(struct ssh *ssh, int sock, struct sshbuf *m)
814 {
815 	char *name, *infotxt;
816 	u_int numprompts, *echo_on, success;
817 	char **prompts;
818 	int r;
819 
820 	if (!options.kbd_interactive_authentication)
821 		fatal_f("kbd-int authentication not enabled");
822 	success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
823 	    &prompts, &echo_on) < 0 ? 0 : 1;
824 
825 	sshbuf_reset(m);
826 	if ((r = sshbuf_put_u32(m, success)) != 0)
827 		fatal_fr(r, "assemble");
828 	if (success) {
829 		if ((r = sshbuf_put_cstring(m, prompts[0])) != 0)
830 			fatal_fr(r, "assemble prompt");
831 	}
832 
833 	debug3_f("sending challenge success: %u", success);
834 	mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
835 
836 	if (success) {
837 		free(name);
838 		free(infotxt);
839 		free(prompts);
840 		free(echo_on);
841 	}
842 
843 	return (0);
844 }
845 
846 int
847 mm_answer_bsdauthrespond(struct ssh *ssh, int sock, struct sshbuf *m)
848 {
849 	char *response;
850 	int r, authok;
851 
852 	if (!options.kbd_interactive_authentication)
853 		fatal_f("kbd-int authentication not enabled");
854 	if (authctxt->as == NULL)
855 		fatal_f("no bsd auth session");
856 
857 	if ((r = sshbuf_get_cstring(m, &response, NULL)) != 0)
858 		fatal_fr(r, "parse");
859 	authok = options.kbd_interactive_authentication &&
860 	    auth_userresponse(authctxt->as, response, 0);
861 	authctxt->as = NULL;
862 	debug3_f("<%s> = <%d>", response, authok);
863 	free(response);
864 
865 	sshbuf_reset(m);
866 	if ((r = sshbuf_put_u32(m, authok)) != 0)
867 		fatal_fr(r, "assemble");
868 
869 	debug3_f("sending authenticated: %d", authok);
870 	mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
871 
872 	auth_method = "keyboard-interactive";
873 	auth_submethod = "bsdauth";
874 
875 	return (authok != 0);
876 }
877 
878 /*
879  * Check that the key type appears in the supplied pattern list, ignoring
880  * mismatches in the signature algorithm. (Signature algorithm checks are
881  * performed in the unprivileged authentication code).
882  * Returns 1 on success, 0 otherwise.
883  */
884 static int
885 key_base_type_match(const char *method, const struct sshkey *key,
886     const char *list)
887 {
888 	char *s, *l, *ol = xstrdup(list);
889 	int found = 0;
890 
891 	l = ol;
892 	for ((s = strsep(&l, ",")); s && *s != '\0'; (s = strsep(&l, ","))) {
893 		if (sshkey_type_from_name(s) == key->type) {
894 			found = 1;
895 			break;
896 		}
897 	}
898 	if (!found) {
899 		error("%s key type %s is not in permitted list %s", method,
900 		    sshkey_ssh_name(key), list);
901 	}
902 
903 	free(ol);
904 	return found;
905 }
906 
907 int
908 mm_answer_keyallowed(struct ssh *ssh, int sock, struct sshbuf *m)
909 {
910 	struct sshkey *key = NULL;
911 	char *cuser, *chost;
912 	u_int pubkey_auth_attempt;
913 	u_int type = 0;
914 	int r, allowed = 0;
915 	struct sshauthopt *opts = NULL;
916 
917 	debug3_f("entering");
918 	if ((r = sshbuf_get_u32(m, &type)) != 0 ||
919 	    (r = sshbuf_get_cstring(m, &cuser, NULL)) != 0 ||
920 	    (r = sshbuf_get_cstring(m, &chost, NULL)) != 0 ||
921 	    (r = sshkey_froms(m, &key)) != 0 ||
922 	    (r = sshbuf_get_u32(m, &pubkey_auth_attempt)) != 0)
923 		fatal_fr(r, "parse");
924 
925 	if (key != NULL && authctxt->valid) {
926 		switch (type) {
927 		case MM_USERKEY:
928 			auth_method = "publickey";
929 			if (!options.pubkey_authentication)
930 				break;
931 			if (auth2_key_already_used(authctxt, key))
932 				break;
933 			if (!key_base_type_match(auth_method, key,
934 			    options.pubkey_accepted_algos))
935 				break;
936 			allowed = user_key_allowed(ssh, authctxt->pw, key,
937 			    pubkey_auth_attempt, &opts);
938 			break;
939 		case MM_HOSTKEY:
940 			auth_method = "hostbased";
941 			if (!options.hostbased_authentication)
942 				break;
943 			if (auth2_key_already_used(authctxt, key))
944 				break;
945 			if (!key_base_type_match(auth_method, key,
946 			    options.hostbased_accepted_algos))
947 				break;
948 			allowed = hostbased_key_allowed(ssh, authctxt->pw,
949 			    cuser, chost, key);
950 			auth2_record_info(authctxt,
951 			    "client user \"%.100s\", client host \"%.100s\"",
952 			    cuser, chost);
953 			break;
954 		default:
955 			fatal_f("unknown key type %u", type);
956 			break;
957 		}
958 	}
959 
960 	debug3_f("%s authentication%s: %s key is %s", auth_method,
961 	    pubkey_auth_attempt ? "" : " test",
962 	    (key == NULL || !authctxt->valid) ? "invalid" : sshkey_type(key),
963 	    allowed ? "allowed" : "not allowed");
964 
965 	auth2_record_key(authctxt, 0, key);
966 
967 	/* clear temporarily storage (used by verify) */
968 	monitor_reset_key_state();
969 
970 	if (allowed) {
971 		/* Save temporarily for comparison in verify */
972 		if ((r = sshkey_to_blob(key, &key_blob, &key_bloblen)) != 0)
973 			fatal_fr(r, "sshkey_to_blob");
974 		key_blobtype = type;
975 		key_opts = opts;
976 		hostbased_cuser = cuser;
977 		hostbased_chost = chost;
978 	} else {
979 		/* Log failed attempt */
980 		auth_log(ssh, 0, 0, auth_method, NULL);
981 		free(cuser);
982 		free(chost);
983 	}
984 	sshkey_free(key);
985 
986 	sshbuf_reset(m);
987 	if ((r = sshbuf_put_u32(m, allowed)) != 0)
988 		fatal_fr(r, "assemble");
989 	if (opts != NULL && (r = sshauthopt_serialise(opts, m, 1)) != 0)
990 		fatal_fr(r, "sshauthopt_serialise");
991 	mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
992 
993 	if (!allowed)
994 		sshauthopt_free(opts);
995 
996 	return (0);
997 }
998 
999 static int
1000 monitor_valid_userblob(struct ssh *ssh, const u_char *data, u_int datalen)
1001 {
1002 	struct sshbuf *b;
1003 	struct sshkey *hostkey = NULL;
1004 	const u_char *p;
1005 	char *userstyle, *cp;
1006 	size_t len;
1007 	u_char type;
1008 	int hostbound = 0, r, fail = 0;
1009 
1010 	if ((b = sshbuf_from(data, datalen)) == NULL)
1011 		fatal_f("sshbuf_from");
1012 
1013 	if (ssh->compat & SSH_OLD_SESSIONID) {
1014 		p = sshbuf_ptr(b);
1015 		len = sshbuf_len(b);
1016 		if ((session_id2 == NULL) ||
1017 		    (len < session_id2_len) ||
1018 		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1019 			fail++;
1020 		if ((r = sshbuf_consume(b, session_id2_len)) != 0)
1021 			fatal_fr(r, "consume");
1022 	} else {
1023 		if ((r = sshbuf_get_string_direct(b, &p, &len)) != 0)
1024 			fatal_fr(r, "parse sessionid");
1025 		if ((session_id2 == NULL) ||
1026 		    (len != session_id2_len) ||
1027 		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1028 			fail++;
1029 	}
1030 	if ((r = sshbuf_get_u8(b, &type)) != 0)
1031 		fatal_fr(r, "parse type");
1032 	if (type != SSH2_MSG_USERAUTH_REQUEST)
1033 		fail++;
1034 	if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1035 		fatal_fr(r, "parse userstyle");
1036 	xasprintf(&userstyle, "%s%s%s", authctxt->user,
1037 	    authctxt->style ? ":" : "",
1038 	    authctxt->style ? authctxt->style : "");
1039 	if (strcmp(userstyle, cp) != 0) {
1040 		logit("wrong user name passed to monitor: "
1041 		    "expected %s != %.100s", userstyle, cp);
1042 		fail++;
1043 	}
1044 	free(userstyle);
1045 	free(cp);
1046 	if ((r = sshbuf_skip_string(b)) != 0 ||	/* service */
1047 	    (r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1048 		fatal_fr(r, "parse method");
1049 	if (strcmp("publickey", cp) != 0) {
1050 		if (strcmp("publickey-hostbound-v00@openssh.com", cp) == 0)
1051 			hostbound = 1;
1052 		else
1053 			fail++;
1054 	}
1055 	free(cp);
1056 	if ((r = sshbuf_get_u8(b, &type)) != 0)
1057 		fatal_fr(r, "parse pktype");
1058 	if (type == 0)
1059 		fail++;
1060 	if ((r = sshbuf_skip_string(b)) != 0 ||	/* pkalg */
1061 	    (r = sshbuf_skip_string(b)) != 0 ||	/* pkblob */
1062 	    (hostbound && (r = sshkey_froms(b, &hostkey)) != 0))
1063 		fatal_fr(r, "parse pk");
1064 	if (sshbuf_len(b) != 0)
1065 		fail++;
1066 	sshbuf_free(b);
1067 	if (hostkey != NULL) {
1068 		/*
1069 		 * Ensure this is actually one of our hostkeys; unfortunately
1070 		 * can't check ssh->kex->initial_hostkey directly at this point
1071 		 * as packet state has not yet been exported to monitor.
1072 		 */
1073 		if (get_hostkey_index(hostkey, 1, ssh) == -1)
1074 			fatal_f("hostbound hostkey does not match");
1075 		sshkey_free(hostkey);
1076 	}
1077 	return (fail == 0);
1078 }
1079 
1080 static int
1081 monitor_valid_hostbasedblob(const u_char *data, u_int datalen,
1082     const char *cuser, const char *chost)
1083 {
1084 	struct sshbuf *b;
1085 	const u_char *p;
1086 	char *cp, *userstyle;
1087 	size_t len;
1088 	int r, fail = 0;
1089 	u_char type;
1090 
1091 	if ((b = sshbuf_from(data, datalen)) == NULL)
1092 		fatal_f("sshbuf_new");
1093 	if ((r = sshbuf_get_string_direct(b, &p, &len)) != 0)
1094 		fatal_fr(r, "parse sessionid");
1095 
1096 	if ((session_id2 == NULL) ||
1097 	    (len != session_id2_len) ||
1098 	    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1099 		fail++;
1100 
1101 	if ((r = sshbuf_get_u8(b, &type)) != 0)
1102 		fatal_fr(r, "parse type");
1103 	if (type != SSH2_MSG_USERAUTH_REQUEST)
1104 		fail++;
1105 	if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1106 		fatal_fr(r, "parse userstyle");
1107 	xasprintf(&userstyle, "%s%s%s", authctxt->user,
1108 	    authctxt->style ? ":" : "",
1109 	    authctxt->style ? authctxt->style : "");
1110 	if (strcmp(userstyle, cp) != 0) {
1111 		logit("wrong user name passed to monitor: "
1112 		    "expected %s != %.100s", userstyle, cp);
1113 		fail++;
1114 	}
1115 	free(userstyle);
1116 	free(cp);
1117 	if ((r = sshbuf_skip_string(b)) != 0 ||	/* service */
1118 	    (r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1119 		fatal_fr(r, "parse method");
1120 	if (strcmp(cp, "hostbased") != 0)
1121 		fail++;
1122 	free(cp);
1123 	if ((r = sshbuf_skip_string(b)) != 0 ||	/* pkalg */
1124 	    (r = sshbuf_skip_string(b)) != 0)	/* pkblob */
1125 		fatal_fr(r, "parse pk");
1126 
1127 	/* verify client host, strip trailing dot if necessary */
1128 	if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1129 		fatal_fr(r, "parse host");
1130 	if (((len = strlen(cp)) > 0) && cp[len - 1] == '.')
1131 		cp[len - 1] = '\0';
1132 	if (strcmp(cp, chost) != 0)
1133 		fail++;
1134 	free(cp);
1135 
1136 	/* verify client user */
1137 	if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1138 		fatal_fr(r, "parse ruser");
1139 	if (strcmp(cp, cuser) != 0)
1140 		fail++;
1141 	free(cp);
1142 
1143 	if (sshbuf_len(b) != 0)
1144 		fail++;
1145 	sshbuf_free(b);
1146 	return (fail == 0);
1147 }
1148 
1149 int
1150 mm_answer_keyverify(struct ssh *ssh, int sock, struct sshbuf *m)
1151 {
1152 	struct sshkey *key;
1153 	const u_char *signature, *data, *blob;
1154 	char *sigalg = NULL, *fp = NULL;
1155 	size_t signaturelen, datalen, bloblen;
1156 	int r, ret, req_presence = 0, req_verify = 0, valid_data = 0;
1157 	int encoded_ret;
1158 	struct sshkey_sig_details *sig_details = NULL;
1159 
1160 	if ((r = sshbuf_get_string_direct(m, &blob, &bloblen)) != 0 ||
1161 	    (r = sshbuf_get_string_direct(m, &signature, &signaturelen)) != 0 ||
1162 	    (r = sshbuf_get_string_direct(m, &data, &datalen)) != 0 ||
1163 	    (r = sshbuf_get_cstring(m, &sigalg, NULL)) != 0)
1164 		fatal_fr(r, "parse");
1165 
1166 	if (hostbased_cuser == NULL || hostbased_chost == NULL ||
1167 	  !monitor_allowed_key(blob, bloblen))
1168 		fatal_f("bad key, not previously allowed");
1169 
1170 	/* Empty signature algorithm means NULL. */
1171 	if (*sigalg == '\0') {
1172 		free(sigalg);
1173 		sigalg = NULL;
1174 	}
1175 
1176 	/* XXX use sshkey_froms here; need to change key_blob, etc. */
1177 	if ((r = sshkey_from_blob(blob, bloblen, &key)) != 0)
1178 		fatal_fr(r, "parse key");
1179 
1180 	switch (key_blobtype) {
1181 	case MM_USERKEY:
1182 		valid_data = monitor_valid_userblob(ssh, data, datalen);
1183 		auth_method = "publickey";
1184 		break;
1185 	case MM_HOSTKEY:
1186 		valid_data = monitor_valid_hostbasedblob(data, datalen,
1187 		    hostbased_cuser, hostbased_chost);
1188 		auth_method = "hostbased";
1189 		break;
1190 	default:
1191 		valid_data = 0;
1192 		break;
1193 	}
1194 	if (!valid_data)
1195 		fatal_f("bad %s signature data blob",
1196 		    key_blobtype == MM_USERKEY ? "userkey" :
1197 		    (key_blobtype == MM_HOSTKEY ? "hostkey" : "unknown"));
1198 
1199 	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
1200 	    SSH_FP_DEFAULT)) == NULL)
1201 		fatal_f("sshkey_fingerprint failed");
1202 
1203 	ret = sshkey_verify(key, signature, signaturelen, data, datalen,
1204 	    sigalg, ssh->compat, &sig_details);
1205 	debug3_f("%s %s signature using %s %s%s%s", auth_method,
1206 	    sshkey_type(key), sigalg == NULL ? "default" : sigalg,
1207 	    (ret == 0) ? "verified" : "unverified",
1208 	    (ret != 0) ? ": " : "", (ret != 0) ? ssh_err(ret) : "");
1209 
1210 	if (ret == 0 && key_blobtype == MM_USERKEY && sig_details != NULL) {
1211 		req_presence = (options.pubkey_auth_options &
1212 		    PUBKEYAUTH_TOUCH_REQUIRED) ||
1213 		    !key_opts->no_require_user_presence;
1214 		if (req_presence &&
1215 		    (sig_details->sk_flags & SSH_SK_USER_PRESENCE_REQD) == 0) {
1216 			error("public key %s %s signature for %s%s from %.128s "
1217 			    "port %d rejected: user presence "
1218 			    "(authenticator touch) requirement not met ",
1219 			    sshkey_type(key), fp,
1220 			    authctxt->valid ? "" : "invalid user ",
1221 			    authctxt->user, ssh_remote_ipaddr(ssh),
1222 			    ssh_remote_port(ssh));
1223 			ret = SSH_ERR_SIGNATURE_INVALID;
1224 		}
1225 		req_verify = (options.pubkey_auth_options &
1226 		    PUBKEYAUTH_VERIFY_REQUIRED) || key_opts->require_verify;
1227 		if (req_verify &&
1228 		    (sig_details->sk_flags & SSH_SK_USER_VERIFICATION_REQD) == 0) {
1229 			error("public key %s %s signature for %s%s from %.128s "
1230 			    "port %d rejected: user verification requirement "
1231 			    "not met ", sshkey_type(key), fp,
1232 			    authctxt->valid ? "" : "invalid user ",
1233 			    authctxt->user, ssh_remote_ipaddr(ssh),
1234 			    ssh_remote_port(ssh));
1235 			ret = SSH_ERR_SIGNATURE_INVALID;
1236 		}
1237 	}
1238 	auth2_record_key(authctxt, ret == 0, key);
1239 
1240 	if (key_blobtype == MM_USERKEY)
1241 		auth_activate_options(ssh, key_opts);
1242 	monitor_reset_key_state();
1243 
1244 	sshbuf_reset(m);
1245 
1246 	/* encode ret != 0 as positive integer, since we're sending u32 */
1247 	encoded_ret = (ret != 0);
1248 	if ((r = sshbuf_put_u32(m, encoded_ret)) != 0 ||
1249 	    (r = sshbuf_put_u8(m, sig_details != NULL)) != 0)
1250 		fatal_fr(r, "assemble");
1251 	if (sig_details != NULL) {
1252 		if ((r = sshbuf_put_u32(m, sig_details->sk_counter)) != 0 ||
1253 		    (r = sshbuf_put_u8(m, sig_details->sk_flags)) != 0)
1254 			fatal_fr(r, "assemble sk");
1255 	}
1256 	sshkey_sig_details_free(sig_details);
1257 	mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
1258 
1259 	free(sigalg);
1260 	free(fp);
1261 	sshkey_free(key);
1262 
1263 	return ret == 0;
1264 }
1265 
1266 static void
1267 mm_record_login(struct ssh *ssh, Session *s, struct passwd *pw)
1268 {
1269 	socklen_t fromlen;
1270 	struct sockaddr_storage from;
1271 
1272 	/*
1273 	 * Get IP address of client. If the connection is not a socket, let
1274 	 * the address be 0.0.0.0.
1275 	 */
1276 	memset(&from, 0, sizeof(from));
1277 	fromlen = sizeof(from);
1278 	if (ssh_packet_connection_is_on_socket(ssh)) {
1279 		if (getpeername(ssh_packet_get_connection_in(ssh),
1280 		    (struct sockaddr *)&from, &fromlen) == -1) {
1281 			debug("getpeername: %.100s", strerror(errno));
1282 			cleanup_exit(255);
1283 		}
1284 	}
1285 	/* Record that there was a login on that tty from the remote host. */
1286 	record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
1287 	    session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
1288 	    (struct sockaddr *)&from, fromlen);
1289 }
1290 
1291 static void
1292 mm_session_close(Session *s)
1293 {
1294 	debug3_f("session %d pid %ld", s->self, (long)s->pid);
1295 	if (s->ttyfd != -1) {
1296 		debug3_f("tty %s ptyfd %d", s->tty, s->ptyfd);
1297 		session_pty_cleanup2(s);
1298 	}
1299 	session_unused(s->self);
1300 }
1301 
1302 int
1303 mm_answer_pty(struct ssh *ssh, int sock, struct sshbuf *m)
1304 {
1305 	extern struct monitor *pmonitor;
1306 	Session *s;
1307 	int r, res, fd0;
1308 
1309 	debug3_f("entering");
1310 
1311 	sshbuf_reset(m);
1312 	s = session_new();
1313 	if (s == NULL)
1314 		goto error;
1315 	s->authctxt = authctxt;
1316 	s->pw = authctxt->pw;
1317 	s->pid = pmonitor->m_pid;
1318 	res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1319 	if (res == 0)
1320 		goto error;
1321 	pty_setowner(authctxt->pw, s->tty);
1322 
1323 	if ((r = sshbuf_put_u32(m, 1)) != 0 ||
1324 	    (r = sshbuf_put_cstring(m, s->tty)) != 0)
1325 		fatal_fr(r, "assemble");
1326 
1327 	/* We need to trick ttyslot */
1328 	if (dup2(s->ttyfd, 0) == -1)
1329 		fatal_f("dup2");
1330 
1331 	mm_record_login(ssh, s, authctxt->pw);
1332 
1333 	/* Now we can close the file descriptor again */
1334 	close(0);
1335 
1336 	/* send messages generated by record_login */
1337 	if ((r = sshbuf_put_stringb(m, loginmsg)) != 0)
1338 		fatal_fr(r, "assemble loginmsg");
1339 	sshbuf_reset(loginmsg);
1340 
1341 	mm_request_send(sock, MONITOR_ANS_PTY, m);
1342 
1343 	if (mm_send_fd(sock, s->ptyfd) == -1 ||
1344 	    mm_send_fd(sock, s->ttyfd) == -1)
1345 		fatal_f("send fds failed");
1346 
1347 	/* make sure nothing uses fd 0 */
1348 	if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1349 		fatal_f("open(/dev/null): %s", strerror(errno));
1350 	if (fd0 != 0)
1351 		error_f("fd0 %d != 0", fd0);
1352 
1353 	/* slave side of pty is not needed */
1354 	close(s->ttyfd);
1355 	s->ttyfd = s->ptyfd;
1356 	/* no need to dup() because nobody closes ptyfd */
1357 	s->ptymaster = s->ptyfd;
1358 
1359 	debug3_f("tty %s ptyfd %d", s->tty, s->ttyfd);
1360 
1361 	return (0);
1362 
1363  error:
1364 	if (s != NULL)
1365 		mm_session_close(s);
1366 	if ((r = sshbuf_put_u32(m, 0)) != 0)
1367 		fatal_fr(r, "assemble 0");
1368 	mm_request_send(sock, MONITOR_ANS_PTY, m);
1369 	return (0);
1370 }
1371 
1372 int
1373 mm_answer_pty_cleanup(struct ssh *ssh, int sock, struct sshbuf *m)
1374 {
1375 	Session *s;
1376 	char *tty;
1377 	int r;
1378 
1379 	debug3_f("entering");
1380 
1381 	if ((r = sshbuf_get_cstring(m, &tty, NULL)) != 0)
1382 		fatal_fr(r, "parse tty");
1383 	if ((s = session_by_tty(tty)) != NULL)
1384 		mm_session_close(s);
1385 	sshbuf_reset(m);
1386 	free(tty);
1387 	return (0);
1388 }
1389 
1390 int
1391 mm_answer_term(struct ssh *ssh, int sock, struct sshbuf *req)
1392 {
1393 	extern struct monitor *pmonitor;
1394 	int res, status;
1395 
1396 	debug3_f("tearing down sessions");
1397 
1398 	/* The child is terminating */
1399 	session_destroy_all(ssh, &mm_session_close);
1400 
1401 	while (waitpid(pmonitor->m_pid, &status, 0) == -1)
1402 		if (errno != EINTR)
1403 			exit(1);
1404 
1405 	res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1406 
1407 	/* Terminate process */
1408 	exit(res);
1409 }
1410 
1411 void
1412 monitor_clear_keystate(struct ssh *ssh, struct monitor *pmonitor)
1413 {
1414 	ssh_clear_newkeys(ssh, MODE_IN);
1415 	ssh_clear_newkeys(ssh, MODE_OUT);
1416 	sshbuf_free(child_state);
1417 	child_state = NULL;
1418 }
1419 
1420 void
1421 monitor_apply_keystate(struct ssh *ssh, struct monitor *pmonitor)
1422 {
1423 	struct kex *kex;
1424 	int r;
1425 
1426 	debug3_f("packet_set_state");
1427 	if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
1428 		fatal_fr(r, "packet_set_state");
1429 	sshbuf_free(child_state);
1430 	child_state = NULL;
1431 	if ((kex = ssh->kex) == NULL)
1432 		fatal_f("internal error: ssh->kex == NULL");
1433 	if (session_id2_len != sshbuf_len(ssh->kex->session_id)) {
1434 		fatal_f("incorrect session id length %zu (expected %u)",
1435 		    sshbuf_len(ssh->kex->session_id), session_id2_len);
1436 	}
1437 	if (memcmp(sshbuf_ptr(ssh->kex->session_id), session_id2,
1438 	    session_id2_len) != 0)
1439 		fatal_f("session ID mismatch");
1440 	/* XXX set callbacks */
1441 #ifdef WITH_OPENSSL
1442 	kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
1443 	kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
1444 	kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
1445 	kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
1446 	kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
1447 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1448 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1449 	kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
1450 #endif
1451 	kex->kex[KEX_C25519_SHA256] = kex_gen_server;
1452 	kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
1453 	kex->load_host_public_key=&get_hostkey_public_by_type;
1454 	kex->load_host_private_key=&get_hostkey_private_by_type;
1455 	kex->host_key_index=&get_hostkey_index;
1456 	kex->sign = sshd_hostkey_sign;
1457 }
1458 
1459 /* This function requires careful sanity checking */
1460 
1461 void
1462 mm_get_keystate(struct ssh *ssh, struct monitor *pmonitor)
1463 {
1464 	debug3_f("Waiting for new keys");
1465 
1466 	if ((child_state = sshbuf_new()) == NULL)
1467 		fatal_f("sshbuf_new failed");
1468 	mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT,
1469 	    child_state);
1470 	debug3_f("GOT new keys");
1471 }
1472 
1473 
1474 /* XXX */
1475 
1476 #define FD_CLOSEONEXEC(x) do { \
1477 	if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \
1478 		fatal("fcntl(%d, F_SETFD)", x); \
1479 } while (0)
1480 
1481 static void
1482 monitor_openfds(struct monitor *mon, int do_logfds)
1483 {
1484 	int pair[2];
1485 #ifdef SO_ZEROIZE
1486 	int on = 1;
1487 #endif
1488 
1489 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
1490 		fatal_f("socketpair: %s", strerror(errno));
1491 #ifdef SO_ZEROIZE
1492 	if (setsockopt(pair[0], SOL_SOCKET, SO_ZEROIZE, &on, sizeof(on)) == -1)
1493 		error("setsockopt SO_ZEROIZE(0): %.100s", strerror(errno));
1494 	if (setsockopt(pair[1], SOL_SOCKET, SO_ZEROIZE, &on, sizeof(on)) == -1)
1495 		error("setsockopt SO_ZEROIZE(1): %.100s", strerror(errno));
1496 #endif
1497 	FD_CLOSEONEXEC(pair[0]);
1498 	FD_CLOSEONEXEC(pair[1]);
1499 	mon->m_recvfd = pair[0];
1500 	mon->m_sendfd = pair[1];
1501 
1502 	if (do_logfds) {
1503 		if (pipe(pair) == -1)
1504 			fatal_f("pipe: %s", strerror(errno));
1505 		FD_CLOSEONEXEC(pair[0]);
1506 		FD_CLOSEONEXEC(pair[1]);
1507 		mon->m_log_recvfd = pair[0];
1508 		mon->m_log_sendfd = pair[1];
1509 	} else
1510 		mon->m_log_recvfd = mon->m_log_sendfd = -1;
1511 }
1512 
1513 #define MM_MEMSIZE	65536
1514 
1515 struct monitor *
1516 monitor_init(void)
1517 {
1518 	struct monitor *mon;
1519 
1520 	mon = xcalloc(1, sizeof(*mon));
1521 	monitor_openfds(mon, 1);
1522 
1523 	return mon;
1524 }
1525 
1526 void
1527 monitor_reinit(struct monitor *mon)
1528 {
1529 	monitor_openfds(mon, 0);
1530 }
1531 
1532 #ifdef GSSAPI
1533 int
1534 mm_answer_gss_setup_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
1535 {
1536 	gss_OID_desc goid;
1537 	OM_uint32 major;
1538 	size_t len;
1539 	u_char *p;
1540 	int r;
1541 
1542 	if (!options.gss_authentication)
1543 		fatal_f("GSSAPI authentication not enabled");
1544 
1545 	if ((r = sshbuf_get_string(m, &p, &len)) != 0)
1546 		fatal_fr(r, "parse");
1547 	goid.elements = p;
1548 	goid.length = len;
1549 
1550 	major = ssh_gssapi_server_ctx(&gsscontext, &goid);
1551 
1552 	free(goid.elements);
1553 
1554 	sshbuf_reset(m);
1555 	if ((r = sshbuf_put_u32(m, major)) != 0)
1556 		fatal_fr(r, "assemble");
1557 
1558 	mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
1559 
1560 	/* Now we have a context, enable the step */
1561 	monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
1562 
1563 	return (0);
1564 }
1565 
1566 int
1567 mm_answer_gss_accept_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
1568 {
1569 	gss_buffer_desc in;
1570 	gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
1571 	OM_uint32 major, minor;
1572 	OM_uint32 flags = 0; /* GSI needs this */
1573 	int r;
1574 
1575 	if (!options.gss_authentication)
1576 		fatal_f("GSSAPI authentication not enabled");
1577 
1578 	if ((r = ssh_gssapi_get_buffer_desc(m, &in)) != 0)
1579 		fatal_fr(r, "ssh_gssapi_get_buffer_desc");
1580 	major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
1581 	free(in.value);
1582 
1583 	sshbuf_reset(m);
1584 	if ((r = sshbuf_put_u32(m, major)) != 0 ||
1585 	    (r = sshbuf_put_string(m, out.value, out.length)) != 0 ||
1586 	    (r = sshbuf_put_u32(m, flags)) != 0)
1587 		fatal_fr(r, "assemble");
1588 	mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
1589 
1590 	gss_release_buffer(&minor, &out);
1591 
1592 	if (major == GSS_S_COMPLETE) {
1593 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
1594 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1595 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
1596 	}
1597 	return (0);
1598 }
1599 
1600 int
1601 mm_answer_gss_checkmic(struct ssh *ssh, int sock, struct sshbuf *m)
1602 {
1603 	gss_buffer_desc gssbuf, mic;
1604 	OM_uint32 ret;
1605 	int r;
1606 
1607 	if (!options.gss_authentication)
1608 		fatal_f("GSSAPI authentication not enabled");
1609 
1610 	if ((r = ssh_gssapi_get_buffer_desc(m, &gssbuf)) != 0 ||
1611 	    (r = ssh_gssapi_get_buffer_desc(m, &mic)) != 0)
1612 		fatal_fr(r, "ssh_gssapi_get_buffer_desc");
1613 
1614 	ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
1615 
1616 	free(gssbuf.value);
1617 	free(mic.value);
1618 
1619 	sshbuf_reset(m);
1620 	if ((r = sshbuf_put_u32(m, ret)) != 0)
1621 		fatal_fr(r, "assemble");
1622 
1623 	mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
1624 
1625 	if (!GSS_ERROR(ret))
1626 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1627 
1628 	return (0);
1629 }
1630 
1631 int
1632 mm_answer_gss_userok(struct ssh *ssh, int sock, struct sshbuf *m)
1633 {
1634 	int r, authenticated;
1635 	const char *displayname;
1636 
1637 	if (!options.gss_authentication)
1638 		fatal_f("GSSAPI authentication not enabled");
1639 
1640 	authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
1641 
1642 	sshbuf_reset(m);
1643 	if ((r = sshbuf_put_u32(m, authenticated)) != 0)
1644 		fatal_fr(r, "assemble");
1645 
1646 	debug3_f("sending result %d", authenticated);
1647 	mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
1648 
1649 	auth_method = "gssapi-with-mic";
1650 
1651 	if ((displayname = ssh_gssapi_displayname()) != NULL)
1652 		auth2_record_info(authctxt, "%s", displayname);
1653 
1654 	/* Monitor loop will terminate if authenticated */
1655 	return (authenticated);
1656 }
1657 #endif /* GSSAPI */
1658 
1659