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