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