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