xref: /openbsd/usr.bin/ssh/monitor.c (revision 71ae1114)
1 /* $OpenBSD: monitor.c,v 1.220 2021/01/22 02:44:58 dtucker 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 #define PUTPW(b, id) \
643 	do { \
644 		if ((r = sshbuf_put_string(b, \
645 		    &pwent->id, sizeof(pwent->id))) != 0) \
646 			fatal_fr(r, "assemble %s", #id); \
647 	} while (0)
648 
649 /* Retrieves the password entry and also checks if the user is permitted */
650 int
651 mm_answer_pwnamallow(struct ssh *ssh, int sock, struct sshbuf *m)
652 {
653 	char *username;
654 	struct passwd *pwent;
655 	int r, allowed = 0;
656 	u_int i;
657 
658 	debug3_f("entering");
659 
660 	if (authctxt->attempt++ != 0)
661 		fatal_f("multiple attempts for getpwnam");
662 
663 	if ((r = sshbuf_get_cstring(m, &username, NULL)) != 0)
664 		fatal_fr(r, "parse");
665 
666 	pwent = getpwnamallow(ssh, username);
667 
668 	authctxt->user = xstrdup(username);
669 	setproctitle("%s [priv]", pwent ? username : "unknown");
670 	free(username);
671 
672 	sshbuf_reset(m);
673 
674 	if (pwent == NULL) {
675 		if ((r = sshbuf_put_u8(m, 0)) != 0)
676 			fatal_fr(r, "assemble fakepw");
677 		authctxt->pw = fakepw();
678 		goto out;
679 	}
680 
681 	allowed = 1;
682 	authctxt->pw = pwent;
683 	authctxt->valid = 1;
684 
685 	/* XXX send fake class/dir/shell, etc. */
686 	if ((r = sshbuf_put_u8(m, 1)) != 0)
687 		fatal_fr(r, "assemble ok");
688 	PUTPW(m, pw_uid);
689 	PUTPW(m, pw_gid);
690 	PUTPW(m, pw_change);
691 	PUTPW(m, pw_expire);
692 	if ((r = sshbuf_put_cstring(m, pwent->pw_name)) != 0 ||
693 	    (r = sshbuf_put_cstring(m, "*")) != 0 ||
694 	    (r = sshbuf_put_cstring(m, pwent->pw_gecos)) != 0 ||
695 	    (r = sshbuf_put_cstring(m, pwent->pw_class)) != 0 ||
696 	    (r = sshbuf_put_cstring(m, pwent->pw_dir)) != 0 ||
697 	    (r = sshbuf_put_cstring(m, pwent->pw_shell)) != 0)
698 		fatal_fr(r, "assemble pw");
699 
700  out:
701 	ssh_packet_set_log_preamble(ssh, "%suser %s",
702 	    authctxt->valid ? "authenticating" : "invalid ", authctxt->user);
703 	if ((r = sshbuf_put_string(m, &options, sizeof(options))) != 0)
704 		fatal_fr(r, "assemble options");
705 
706 #define M_CP_STROPT(x) do { \
707 		if (options.x != NULL && \
708 		    (r = sshbuf_put_cstring(m, options.x)) != 0) \
709 			fatal_fr(r, "assemble %s", #x); \
710 	} while (0)
711 #define M_CP_STRARRAYOPT(x, nx) do { \
712 		for (i = 0; i < options.nx; i++) { \
713 			if ((r = sshbuf_put_cstring(m, options.x[i])) != 0) \
714 				fatal_fr(r, "assemble %s", #x); \
715 		} \
716 	} while (0)
717 	/* See comment in servconf.h */
718 	COPY_MATCH_STRING_OPTS();
719 #undef M_CP_STROPT
720 #undef M_CP_STRARRAYOPT
721 
722 	/* Create valid auth method lists */
723 	if (auth2_setup_methods_lists(authctxt) != 0) {
724 		/*
725 		 * The monitor will continue long enough to let the child
726 		 * run to it's packet_disconnect(), but it must not allow any
727 		 * authentication to succeed.
728 		 */
729 		debug_f("no valid authentication method lists");
730 	}
731 
732 	debug3_f("sending MONITOR_ANS_PWNAM: %d", allowed);
733 	mm_request_send(sock, MONITOR_ANS_PWNAM, m);
734 
735 	/* Allow service/style information on the auth context */
736 	monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
737 	monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
738 
739 	return (0);
740 }
741 
742 int mm_answer_auth2_read_banner(struct ssh *ssh, int sock, struct sshbuf *m)
743 {
744 	char *banner;
745 	int r;
746 
747 	sshbuf_reset(m);
748 	banner = auth2_read_banner();
749 	if ((r = sshbuf_put_cstring(m, banner != NULL ? banner : "")) != 0)
750 		fatal_fr(r, "assemble");
751 	mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
752 	free(banner);
753 
754 	return (0);
755 }
756 
757 int
758 mm_answer_authserv(struct ssh *ssh, int sock, struct sshbuf *m)
759 {
760 	int r;
761 
762 	monitor_permit_authentications(1);
763 
764 	if ((r = sshbuf_get_cstring(m, &authctxt->service, NULL)) != 0 ||
765 	    (r = sshbuf_get_cstring(m, &authctxt->style, NULL)) != 0)
766 		fatal_fr(r, "parse");
767 	debug3_f("service=%s, style=%s", authctxt->service, authctxt->style);
768 
769 	if (strlen(authctxt->style) == 0) {
770 		free(authctxt->style);
771 		authctxt->style = NULL;
772 	}
773 
774 	return (0);
775 }
776 
777 int
778 mm_answer_authpassword(struct ssh *ssh, int sock, struct sshbuf *m)
779 {
780 	static int call_count;
781 	char *passwd;
782 	int r, authenticated;
783 	size_t plen;
784 
785 	if (!options.password_authentication)
786 		fatal_f("password authentication not enabled");
787 	if ((r = sshbuf_get_cstring(m, &passwd, &plen)) != 0)
788 		fatal_fr(r, "parse");
789 	/* Only authenticate if the context is valid */
790 	authenticated = options.password_authentication &&
791 	    auth_password(ssh, passwd);
792 	freezero(passwd, plen);
793 
794 	sshbuf_reset(m);
795 	if ((r = sshbuf_put_u32(m, authenticated)) != 0)
796 		fatal_fr(r, "assemble");
797 
798 	debug3_f("sending result %d", authenticated);
799 	mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
800 
801 	call_count++;
802 	if (plen == 0 && call_count == 1)
803 		auth_method = "none";
804 	else
805 		auth_method = "password";
806 
807 	/* Causes monitor loop to terminate if authenticated */
808 	return (authenticated);
809 }
810 
811 int
812 mm_answer_bsdauthquery(struct ssh *ssh, int sock, struct sshbuf *m)
813 {
814 	char *name, *infotxt;
815 	u_int numprompts, *echo_on, success;
816 	char **prompts;
817 	int r;
818 
819 	if (!options.kbd_interactive_authentication)
820 		fatal_f("kbd-int authentication not enabled");
821 	success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
822 	    &prompts, &echo_on) < 0 ? 0 : 1;
823 
824 	sshbuf_reset(m);
825 	if ((r = sshbuf_put_u32(m, success)) != 0)
826 		fatal_fr(r, "assemble");
827 	if (success) {
828 		if ((r = sshbuf_put_cstring(m, prompts[0])) != 0)
829 			fatal_fr(r, "assemble prompt");
830 	}
831 
832 	debug3_f("sending challenge success: %u", success);
833 	mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
834 
835 	if (success) {
836 		free(name);
837 		free(infotxt);
838 		free(prompts);
839 		free(echo_on);
840 	}
841 
842 	return (0);
843 }
844 
845 int
846 mm_answer_bsdauthrespond(struct ssh *ssh, int sock, struct sshbuf *m)
847 {
848 	char *response;
849 	int r, authok;
850 
851 	if (!options.kbd_interactive_authentication)
852 		fatal_f("kbd-int authentication not enabled");
853 	if (authctxt->as == NULL)
854 		fatal_f("no bsd auth session");
855 
856 	if ((r = sshbuf_get_cstring(m, &response, NULL)) != 0)
857 		fatal_fr(r, "parse");
858 	authok = options.challenge_response_authentication &&
859 	    auth_userresponse(authctxt->as, response, 0);
860 	authctxt->as = NULL;
861 	debug3_f("<%s> = <%d>", response, authok);
862 	free(response);
863 
864 	sshbuf_reset(m);
865 	if ((r = sshbuf_put_u32(m, authok)) != 0)
866 		fatal_fr(r, "assemble");
867 
868 	debug3_f("sending authenticated: %d", authok);
869 	mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
870 
871 	auth_method = "keyboard-interactive";
872 	auth_submethod = "bsdauth";
873 
874 	return (authok != 0);
875 }
876 
877 /*
878  * Check that the key type appears in the supplied pattern list, ignoring
879  * mismatches in the signature algorithm. (Signature algorithm checks are
880  * performed in the unprivileged authentication code).
881  * Returns 1 on success, 0 otherwise.
882  */
883 static int
884 key_base_type_match(const char *method, const struct sshkey *key,
885     const char *list)
886 {
887 	char *s, *l, *ol = xstrdup(list);
888 	int found = 0;
889 
890 	l = ol;
891 	for ((s = strsep(&l, ",")); s && *s != '\0'; (s = strsep(&l, ","))) {
892 		if (sshkey_type_from_name(s) == key->type) {
893 			found = 1;
894 			break;
895 		}
896 	}
897 	if (!found) {
898 		error("%s key type %s is not in permitted list %s", method,
899 		    sshkey_ssh_name(key), list);
900 	}
901 
902 	free(ol);
903 	return found;
904 }
905 
906 int
907 mm_answer_keyallowed(struct ssh *ssh, int sock, struct sshbuf *m)
908 {
909 	struct sshkey *key = NULL;
910 	char *cuser, *chost;
911 	u_int pubkey_auth_attempt;
912 	enum mm_keytype type = 0;
913 	int r, allowed = 0;
914 	struct sshauthopt *opts = NULL;
915 
916 	debug3_f("entering");
917 	if ((r = sshbuf_get_u32(m, &type)) != 0 ||
918 	    (r = sshbuf_get_cstring(m, &cuser, NULL)) != 0 ||
919 	    (r = sshbuf_get_cstring(m, &chost, NULL)) != 0 ||
920 	    (r = sshkey_froms(m, &key)) != 0 ||
921 	    (r = sshbuf_get_u32(m, &pubkey_auth_attempt)) != 0)
922 		fatal_fr(r, "parse");
923 
924 	debug3_f("key_from_blob: %p", key);
925 
926 	if (key != NULL && authctxt->valid) {
927 		/* These should not make it past the privsep child */
928 		if (sshkey_type_plain(key->type) == KEY_RSA &&
929 		    (datafellows & SSH_BUG_RSASIGMD5) != 0)
930 			fatal_f("passed a SSH_BUG_RSASIGMD5 key");
931 
932 		switch (type) {
933 		case MM_USERKEY:
934 			auth_method = "publickey";
935 			if (!options.pubkey_authentication)
936 				break;
937 			if (auth2_key_already_used(authctxt, key))
938 				break;
939 			if (!key_base_type_match(auth_method, key,
940 			    options.pubkey_accepted_algos))
941 				break;
942 			allowed = user_key_allowed(ssh, authctxt->pw, key,
943 			    pubkey_auth_attempt, &opts);
944 			break;
945 		case MM_HOSTKEY:
946 			auth_method = "hostbased";
947 			if (!options.hostbased_authentication)
948 				break;
949 			if (auth2_key_already_used(authctxt, key))
950 				break;
951 			if (!key_base_type_match(auth_method, key,
952 			    options.hostbased_key_types))
953 				break;
954 			allowed = hostbased_key_allowed(ssh, authctxt->pw,
955 			    cuser, chost, key);
956 			auth2_record_info(authctxt,
957 			    "client user \"%.100s\", client host \"%.100s\"",
958 			    cuser, chost);
959 			break;
960 		default:
961 			fatal_f("unknown key type %d", type);
962 			break;
963 		}
964 	}
965 
966 	debug3_f("%s authentication%s: %s key is %s", auth_method,
967 	    pubkey_auth_attempt ? "" : " test",
968 	    (key == NULL || !authctxt->valid) ? "invalid" : sshkey_type(key),
969 	    allowed ? "allowed" : "not allowed");
970 
971 	auth2_record_key(authctxt, 0, key);
972 
973 	/* clear temporarily storage (used by verify) */
974 	monitor_reset_key_state();
975 
976 	if (allowed) {
977 		/* Save temporarily for comparison in verify */
978 		if ((r = sshkey_to_blob(key, &key_blob, &key_bloblen)) != 0)
979 			fatal_fr(r, "sshkey_to_blob");
980 		key_blobtype = type;
981 		key_opts = opts;
982 		hostbased_cuser = cuser;
983 		hostbased_chost = chost;
984 	} else {
985 		/* Log failed attempt */
986 		auth_log(ssh, 0, 0, auth_method, NULL);
987 		free(cuser);
988 		free(chost);
989 	}
990 	sshkey_free(key);
991 
992 	sshbuf_reset(m);
993 	if ((r = sshbuf_put_u32(m, allowed)) != 0)
994 		fatal_fr(r, "assemble");
995 	if (opts != NULL && (r = sshauthopt_serialise(opts, m, 1)) != 0)
996 		fatal_fr(r, "sshauthopt_serialise");
997 	mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
998 
999 	if (!allowed)
1000 		sshauthopt_free(opts);
1001 
1002 	return (0);
1003 }
1004 
1005 static int
1006 monitor_valid_userblob(const u_char *data, u_int datalen)
1007 {
1008 	struct sshbuf *b;
1009 	const u_char *p;
1010 	char *userstyle, *cp;
1011 	size_t len;
1012 	u_char type;
1013 	int r, fail = 0;
1014 
1015 	if ((b = sshbuf_from(data, datalen)) == NULL)
1016 		fatal_f("sshbuf_from");
1017 
1018 	if (datafellows & SSH_OLD_SESSIONID) {
1019 		p = sshbuf_ptr(b);
1020 		len = sshbuf_len(b);
1021 		if ((session_id2 == NULL) ||
1022 		    (len < session_id2_len) ||
1023 		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1024 			fail++;
1025 		if ((r = sshbuf_consume(b, session_id2_len)) != 0)
1026 			fatal_fr(r, "consume");
1027 	} else {
1028 		if ((r = sshbuf_get_string_direct(b, &p, &len)) != 0)
1029 			fatal_fr(r, "parse sessionid");
1030 		if ((session_id2 == NULL) ||
1031 		    (len != session_id2_len) ||
1032 		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1033 			fail++;
1034 	}
1035 	if ((r = sshbuf_get_u8(b, &type)) != 0)
1036 		fatal_fr(r, "parse type");
1037 	if (type != SSH2_MSG_USERAUTH_REQUEST)
1038 		fail++;
1039 	if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1040 		fatal_fr(r, "parse userstyle");
1041 	xasprintf(&userstyle, "%s%s%s", authctxt->user,
1042 	    authctxt->style ? ":" : "",
1043 	    authctxt->style ? authctxt->style : "");
1044 	if (strcmp(userstyle, cp) != 0) {
1045 		logit("wrong user name passed to monitor: "
1046 		    "expected %s != %.100s", userstyle, cp);
1047 		fail++;
1048 	}
1049 	free(userstyle);
1050 	free(cp);
1051 	if ((r = sshbuf_skip_string(b)) != 0 ||	/* service */
1052 	    (r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1053 		fatal_fr(r, "parse method");
1054 	if (strcmp("publickey", cp) != 0)
1055 		fail++;
1056 	free(cp);
1057 	if ((r = sshbuf_get_u8(b, &type)) != 0)
1058 		fatal_fr(r, "parse pktype");
1059 	if (type == 0)
1060 		fail++;
1061 	if ((r = sshbuf_skip_string(b)) != 0 ||	/* pkalg */
1062 	    (r = sshbuf_skip_string(b)) != 0)	/* pkblob */
1063 		fatal_fr(r, "parse pk");
1064 	if (sshbuf_len(b) != 0)
1065 		fail++;
1066 	sshbuf_free(b);
1067 	return (fail == 0);
1068 }
1069 
1070 static int
1071 monitor_valid_hostbasedblob(const u_char *data, u_int datalen,
1072     const char *cuser, const char *chost)
1073 {
1074 	struct sshbuf *b;
1075 	const u_char *p;
1076 	char *cp, *userstyle;
1077 	size_t len;
1078 	int r, fail = 0;
1079 	u_char type;
1080 
1081 	if ((b = sshbuf_from(data, datalen)) == NULL)
1082 		fatal_f("sshbuf_new");
1083 	if ((r = sshbuf_get_string_direct(b, &p, &len)) != 0)
1084 		fatal_fr(r, "parse sessionid");
1085 
1086 	if ((session_id2 == NULL) ||
1087 	    (len != session_id2_len) ||
1088 	    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1089 		fail++;
1090 
1091 	if ((r = sshbuf_get_u8(b, &type)) != 0)
1092 		fatal_fr(r, "parse type");
1093 	if (type != SSH2_MSG_USERAUTH_REQUEST)
1094 		fail++;
1095 	if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1096 		fatal_fr(r, "parse userstyle");
1097 	xasprintf(&userstyle, "%s%s%s", authctxt->user,
1098 	    authctxt->style ? ":" : "",
1099 	    authctxt->style ? authctxt->style : "");
1100 	if (strcmp(userstyle, cp) != 0) {
1101 		logit("wrong user name passed to monitor: "
1102 		    "expected %s != %.100s", userstyle, cp);
1103 		fail++;
1104 	}
1105 	free(userstyle);
1106 	free(cp);
1107 	if ((r = sshbuf_skip_string(b)) != 0 ||	/* service */
1108 	    (r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1109 		fatal_fr(r, "parse method");
1110 	if (strcmp(cp, "hostbased") != 0)
1111 		fail++;
1112 	free(cp);
1113 	if ((r = sshbuf_skip_string(b)) != 0 ||	/* pkalg */
1114 	    (r = sshbuf_skip_string(b)) != 0)	/* pkblob */
1115 		fatal_fr(r, "parse pk");
1116 
1117 	/* verify client host, strip trailing dot if necessary */
1118 	if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1119 		fatal_fr(r, "parse host");
1120 	if (((len = strlen(cp)) > 0) && cp[len - 1] == '.')
1121 		cp[len - 1] = '\0';
1122 	if (strcmp(cp, chost) != 0)
1123 		fail++;
1124 	free(cp);
1125 
1126 	/* verify client user */
1127 	if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1128 		fatal_fr(r, "parse ruser");
1129 	if (strcmp(cp, cuser) != 0)
1130 		fail++;
1131 	free(cp);
1132 
1133 	if (sshbuf_len(b) != 0)
1134 		fail++;
1135 	sshbuf_free(b);
1136 	return (fail == 0);
1137 }
1138 
1139 int
1140 mm_answer_keyverify(struct ssh *ssh, int sock, struct sshbuf *m)
1141 {
1142 	struct sshkey *key;
1143 	const u_char *signature, *data, *blob;
1144 	char *sigalg = NULL, *fp = NULL;
1145 	size_t signaturelen, datalen, bloblen;
1146 	int r, ret, req_presence = 0, req_verify = 0, valid_data = 0;
1147 	int encoded_ret;
1148 	struct sshkey_sig_details *sig_details = NULL;
1149 
1150 	if ((r = sshbuf_get_string_direct(m, &blob, &bloblen)) != 0 ||
1151 	    (r = sshbuf_get_string_direct(m, &signature, &signaturelen)) != 0 ||
1152 	    (r = sshbuf_get_string_direct(m, &data, &datalen)) != 0 ||
1153 	    (r = sshbuf_get_cstring(m, &sigalg, NULL)) != 0)
1154 		fatal_fr(r, "parse");
1155 
1156 	if (hostbased_cuser == NULL || hostbased_chost == NULL ||
1157 	  !monitor_allowed_key(blob, bloblen))
1158 		fatal_f("bad key, not previously allowed");
1159 
1160 	/* Empty signature algorithm means NULL. */
1161 	if (*sigalg == '\0') {
1162 		free(sigalg);
1163 		sigalg = NULL;
1164 	}
1165 
1166 	/* XXX use sshkey_froms here; need to change key_blob, etc. */
1167 	if ((r = sshkey_from_blob(blob, bloblen, &key)) != 0)
1168 		fatal_fr(r, "parse key");
1169 
1170 	switch (key_blobtype) {
1171 	case MM_USERKEY:
1172 		valid_data = monitor_valid_userblob(data, datalen);
1173 		auth_method = "publickey";
1174 		break;
1175 	case MM_HOSTKEY:
1176 		valid_data = monitor_valid_hostbasedblob(data, datalen,
1177 		    hostbased_cuser, hostbased_chost);
1178 		auth_method = "hostbased";
1179 		break;
1180 	default:
1181 		valid_data = 0;
1182 		break;
1183 	}
1184 	if (!valid_data)
1185 		fatal_f("bad signature data blob");
1186 
1187 	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
1188 	    SSH_FP_DEFAULT)) == NULL)
1189 		fatal_f("sshkey_fingerprint failed");
1190 
1191 	ret = sshkey_verify(key, signature, signaturelen, data, datalen,
1192 	    sigalg, ssh->compat, &sig_details);
1193 	debug3_f("%s %p signature %s%s%s", auth_method, key,
1194 	    (ret == 0) ? "verified" : "unverified",
1195 	    (ret != 0) ? ": " : "", (ret != 0) ? ssh_err(ret) : "");
1196 
1197 	if (ret == 0 && key_blobtype == MM_USERKEY && sig_details != NULL) {
1198 		req_presence = (options.pubkey_auth_options &
1199 		    PUBKEYAUTH_TOUCH_REQUIRED) ||
1200 		    !key_opts->no_require_user_presence;
1201 		if (req_presence &&
1202 		    (sig_details->sk_flags & SSH_SK_USER_PRESENCE_REQD) == 0) {
1203 			error("public key %s %s signature for %s%s from %.128s "
1204 			    "port %d rejected: user presence "
1205 			    "(authenticator touch) requirement not met ",
1206 			    sshkey_type(key), fp,
1207 			    authctxt->valid ? "" : "invalid user ",
1208 			    authctxt->user, ssh_remote_ipaddr(ssh),
1209 			    ssh_remote_port(ssh));
1210 			ret = SSH_ERR_SIGNATURE_INVALID;
1211 		}
1212 		req_verify = (options.pubkey_auth_options &
1213 		    PUBKEYAUTH_VERIFY_REQUIRED) || key_opts->require_verify;
1214 		if (req_verify &&
1215 		    (sig_details->sk_flags & SSH_SK_USER_VERIFICATION_REQD) == 0) {
1216 			error("public key %s %s signature for %s%s from %.128s "
1217 			    "port %d rejected: user verification requirement "
1218 			    "not met ", sshkey_type(key), fp,
1219 			    authctxt->valid ? "" : "invalid user ",
1220 			    authctxt->user, ssh_remote_ipaddr(ssh),
1221 			    ssh_remote_port(ssh));
1222 			ret = SSH_ERR_SIGNATURE_INVALID;
1223 		}
1224 	}
1225 	auth2_record_key(authctxt, ret == 0, key);
1226 
1227 	if (key_blobtype == MM_USERKEY)
1228 		auth_activate_options(ssh, key_opts);
1229 	monitor_reset_key_state();
1230 
1231 	sshbuf_reset(m);
1232 
1233 	/* encode ret != 0 as positive integer, since we're sending u32 */
1234 	encoded_ret = (ret != 0);
1235 	if ((r = sshbuf_put_u32(m, encoded_ret)) != 0 ||
1236 	    (r = sshbuf_put_u8(m, sig_details != NULL)) != 0)
1237 		fatal_fr(r, "assemble");
1238 	if (sig_details != NULL) {
1239 		if ((r = sshbuf_put_u32(m, sig_details->sk_counter)) != 0 ||
1240 		    (r = sshbuf_put_u8(m, sig_details->sk_flags)) != 0)
1241 			fatal_fr(r, "assemble sk");
1242 	}
1243 	sshkey_sig_details_free(sig_details);
1244 	mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
1245 
1246 	free(sigalg);
1247 	free(fp);
1248 	sshkey_free(key);
1249 
1250 	return ret == 0;
1251 }
1252 
1253 static void
1254 mm_record_login(struct ssh *ssh, Session *s, struct passwd *pw)
1255 {
1256 	socklen_t fromlen;
1257 	struct sockaddr_storage from;
1258 
1259 	/*
1260 	 * Get IP address of client. If the connection is not a socket, let
1261 	 * the address be 0.0.0.0.
1262 	 */
1263 	memset(&from, 0, sizeof(from));
1264 	fromlen = sizeof(from);
1265 	if (ssh_packet_connection_is_on_socket(ssh)) {
1266 		if (getpeername(ssh_packet_get_connection_in(ssh),
1267 		    (struct sockaddr *)&from, &fromlen) == -1) {
1268 			debug("getpeername: %.100s", strerror(errno));
1269 			cleanup_exit(255);
1270 		}
1271 	}
1272 	/* Record that there was a login on that tty from the remote host. */
1273 	record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
1274 	    session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
1275 	    (struct sockaddr *)&from, fromlen);
1276 }
1277 
1278 static void
1279 mm_session_close(Session *s)
1280 {
1281 	debug3_f("session %d pid %ld", s->self, (long)s->pid);
1282 	if (s->ttyfd != -1) {
1283 		debug3_f("tty %s ptyfd %d", s->tty, s->ptyfd);
1284 		session_pty_cleanup2(s);
1285 	}
1286 	session_unused(s->self);
1287 }
1288 
1289 int
1290 mm_answer_pty(struct ssh *ssh, int sock, struct sshbuf *m)
1291 {
1292 	extern struct monitor *pmonitor;
1293 	Session *s;
1294 	int r, res, fd0;
1295 
1296 	debug3_f("entering");
1297 
1298 	sshbuf_reset(m);
1299 	s = session_new();
1300 	if (s == NULL)
1301 		goto error;
1302 	s->authctxt = authctxt;
1303 	s->pw = authctxt->pw;
1304 	s->pid = pmonitor->m_pid;
1305 	res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1306 	if (res == 0)
1307 		goto error;
1308 	pty_setowner(authctxt->pw, s->tty);
1309 
1310 	if ((r = sshbuf_put_u32(m, 1)) != 0 ||
1311 	    (r = sshbuf_put_cstring(m, s->tty)) != 0)
1312 		fatal_fr(r, "assemble");
1313 
1314 	/* We need to trick ttyslot */
1315 	if (dup2(s->ttyfd, 0) == -1)
1316 		fatal_f("dup2");
1317 
1318 	mm_record_login(ssh, s, authctxt->pw);
1319 
1320 	/* Now we can close the file descriptor again */
1321 	close(0);
1322 
1323 	/* send messages generated by record_login */
1324 	if ((r = sshbuf_put_stringb(m, loginmsg)) != 0)
1325 		fatal_fr(r, "assemble loginmsg");
1326 	sshbuf_reset(loginmsg);
1327 
1328 	mm_request_send(sock, MONITOR_ANS_PTY, m);
1329 
1330 	if (mm_send_fd(sock, s->ptyfd) == -1 ||
1331 	    mm_send_fd(sock, s->ttyfd) == -1)
1332 		fatal_f("send fds failed");
1333 
1334 	/* make sure nothing uses fd 0 */
1335 	if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1336 		fatal_f("open(/dev/null): %s", strerror(errno));
1337 	if (fd0 != 0)
1338 		error_f("fd0 %d != 0", fd0);
1339 
1340 	/* slave side of pty is not needed */
1341 	close(s->ttyfd);
1342 	s->ttyfd = s->ptyfd;
1343 	/* no need to dup() because nobody closes ptyfd */
1344 	s->ptymaster = s->ptyfd;
1345 
1346 	debug3_f("tty %s ptyfd %d", s->tty, s->ttyfd);
1347 
1348 	return (0);
1349 
1350  error:
1351 	if (s != NULL)
1352 		mm_session_close(s);
1353 	if ((r = sshbuf_put_u32(m, 0)) != 0)
1354 		fatal_fr(r, "assemble 0");
1355 	mm_request_send(sock, MONITOR_ANS_PTY, m);
1356 	return (0);
1357 }
1358 
1359 int
1360 mm_answer_pty_cleanup(struct ssh *ssh, int sock, struct sshbuf *m)
1361 {
1362 	Session *s;
1363 	char *tty;
1364 	int r;
1365 
1366 	debug3_f("entering");
1367 
1368 	if ((r = sshbuf_get_cstring(m, &tty, NULL)) != 0)
1369 		fatal_fr(r, "parse tty");
1370 	if ((s = session_by_tty(tty)) != NULL)
1371 		mm_session_close(s);
1372 	sshbuf_reset(m);
1373 	free(tty);
1374 	return (0);
1375 }
1376 
1377 int
1378 mm_answer_term(struct ssh *ssh, int sock, struct sshbuf *req)
1379 {
1380 	extern struct monitor *pmonitor;
1381 	int res, status;
1382 
1383 	debug3_f("tearing down sessions");
1384 
1385 	/* The child is terminating */
1386 	session_destroy_all(ssh, &mm_session_close);
1387 
1388 	while (waitpid(pmonitor->m_pid, &status, 0) == -1)
1389 		if (errno != EINTR)
1390 			exit(1);
1391 
1392 	res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1393 
1394 	/* Terminate process */
1395 	exit(res);
1396 }
1397 
1398 void
1399 monitor_clear_keystate(struct ssh *ssh, struct monitor *pmonitor)
1400 {
1401 	ssh_clear_newkeys(ssh, MODE_IN);
1402 	ssh_clear_newkeys(ssh, MODE_OUT);
1403 	sshbuf_free(child_state);
1404 	child_state = NULL;
1405 }
1406 
1407 void
1408 monitor_apply_keystate(struct ssh *ssh, struct monitor *pmonitor)
1409 {
1410 	struct kex *kex;
1411 	int r;
1412 
1413 	debug3_f("packet_set_state");
1414 	if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
1415 		fatal_fr(r, "packet_set_state");
1416 	sshbuf_free(child_state);
1417 	child_state = NULL;
1418 
1419 	if ((kex = ssh->kex) != NULL) {
1420 		/* XXX set callbacks */
1421 #ifdef WITH_OPENSSL
1422 		kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
1423 		kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
1424 		kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
1425 		kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
1426 		kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
1427 		kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1428 		kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1429 		kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
1430 #endif
1431 		kex->kex[KEX_C25519_SHA256] = kex_gen_server;
1432 		kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
1433 		kex->load_host_public_key=&get_hostkey_public_by_type;
1434 		kex->load_host_private_key=&get_hostkey_private_by_type;
1435 		kex->host_key_index=&get_hostkey_index;
1436 		kex->sign = sshd_hostkey_sign;
1437 	}
1438 }
1439 
1440 /* This function requires careful sanity checking */
1441 
1442 void
1443 mm_get_keystate(struct ssh *ssh, struct monitor *pmonitor)
1444 {
1445 	debug3_f("Waiting for new keys");
1446 
1447 	if ((child_state = sshbuf_new()) == NULL)
1448 		fatal_f("sshbuf_new failed");
1449 	mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT,
1450 	    child_state);
1451 	debug3_f("GOT new keys");
1452 }
1453 
1454 
1455 /* XXX */
1456 
1457 #define FD_CLOSEONEXEC(x) do { \
1458 	if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \
1459 		fatal("fcntl(%d, F_SETFD)", x); \
1460 } while (0)
1461 
1462 static void
1463 monitor_openfds(struct monitor *mon, int do_logfds)
1464 {
1465 	int pair[2];
1466 #ifdef SO_ZEROIZE
1467 	int on = 1;
1468 #endif
1469 
1470 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
1471 		fatal_f("socketpair: %s", strerror(errno));
1472 #ifdef SO_ZEROIZE
1473 	if (setsockopt(pair[0], SOL_SOCKET, SO_ZEROIZE, &on, sizeof(on)) == -1)
1474 		error("setsockopt SO_ZEROIZE(0): %.100s", strerror(errno));
1475 	if (setsockopt(pair[1], SOL_SOCKET, SO_ZEROIZE, &on, sizeof(on)) == -1)
1476 		error("setsockopt SO_ZEROIZE(1): %.100s", strerror(errno));
1477 #endif
1478 	FD_CLOSEONEXEC(pair[0]);
1479 	FD_CLOSEONEXEC(pair[1]);
1480 	mon->m_recvfd = pair[0];
1481 	mon->m_sendfd = pair[1];
1482 
1483 	if (do_logfds) {
1484 		if (pipe(pair) == -1)
1485 			fatal_f("pipe: %s", strerror(errno));
1486 		FD_CLOSEONEXEC(pair[0]);
1487 		FD_CLOSEONEXEC(pair[1]);
1488 		mon->m_log_recvfd = pair[0];
1489 		mon->m_log_sendfd = pair[1];
1490 	} else
1491 		mon->m_log_recvfd = mon->m_log_sendfd = -1;
1492 }
1493 
1494 #define MM_MEMSIZE	65536
1495 
1496 struct monitor *
1497 monitor_init(void)
1498 {
1499 	struct monitor *mon;
1500 
1501 	mon = xcalloc(1, sizeof(*mon));
1502 	monitor_openfds(mon, 1);
1503 
1504 	return mon;
1505 }
1506 
1507 void
1508 monitor_reinit(struct monitor *mon)
1509 {
1510 	monitor_openfds(mon, 0);
1511 }
1512 
1513 #ifdef GSSAPI
1514 int
1515 mm_answer_gss_setup_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
1516 {
1517 	gss_OID_desc goid;
1518 	OM_uint32 major;
1519 	size_t len;
1520 	u_char *p;
1521 	int r;
1522 
1523 	if (!options.gss_authentication)
1524 		fatal_f("GSSAPI authentication not enabled");
1525 
1526 	if ((r = sshbuf_get_string(m, &p, &len)) != 0)
1527 		fatal_fr(r, "parse");
1528 	goid.elements = p;
1529 	goid.length = len;
1530 
1531 	major = ssh_gssapi_server_ctx(&gsscontext, &goid);
1532 
1533 	free(goid.elements);
1534 
1535 	sshbuf_reset(m);
1536 	if ((r = sshbuf_put_u32(m, major)) != 0)
1537 		fatal_fr(r, "assemble");
1538 
1539 	mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
1540 
1541 	/* Now we have a context, enable the step */
1542 	monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
1543 
1544 	return (0);
1545 }
1546 
1547 int
1548 mm_answer_gss_accept_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
1549 {
1550 	gss_buffer_desc in;
1551 	gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
1552 	OM_uint32 major, minor;
1553 	OM_uint32 flags = 0; /* GSI needs this */
1554 	int r;
1555 
1556 	if (!options.gss_authentication)
1557 		fatal_f("GSSAPI authentication not enabled");
1558 
1559 	if ((r = ssh_gssapi_get_buffer_desc(m, &in)) != 0)
1560 		fatal_fr(r, "ssh_gssapi_get_buffer_desc");
1561 	major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
1562 	free(in.value);
1563 
1564 	sshbuf_reset(m);
1565 	if ((r = sshbuf_put_u32(m, major)) != 0 ||
1566 	    (r = sshbuf_put_string(m, out.value, out.length)) != 0 ||
1567 	    (r = sshbuf_put_u32(m, flags)) != 0)
1568 		fatal_fr(r, "assemble");
1569 	mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
1570 
1571 	gss_release_buffer(&minor, &out);
1572 
1573 	if (major == GSS_S_COMPLETE) {
1574 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
1575 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1576 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
1577 	}
1578 	return (0);
1579 }
1580 
1581 int
1582 mm_answer_gss_checkmic(struct ssh *ssh, int sock, struct sshbuf *m)
1583 {
1584 	gss_buffer_desc gssbuf, mic;
1585 	OM_uint32 ret;
1586 	int r;
1587 
1588 	if (!options.gss_authentication)
1589 		fatal_f("GSSAPI authentication not enabled");
1590 
1591 	if ((r = ssh_gssapi_get_buffer_desc(m, &gssbuf)) != 0 ||
1592 	    (r = ssh_gssapi_get_buffer_desc(m, &mic)) != 0)
1593 		fatal_fr(r, "ssh_gssapi_get_buffer_desc");
1594 
1595 	ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
1596 
1597 	free(gssbuf.value);
1598 	free(mic.value);
1599 
1600 	sshbuf_reset(m);
1601 	if ((r = sshbuf_put_u32(m, ret)) != 0)
1602 		fatal_fr(r, "assemble");
1603 
1604 	mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
1605 
1606 	if (!GSS_ERROR(ret))
1607 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1608 
1609 	return (0);
1610 }
1611 
1612 int
1613 mm_answer_gss_userok(struct ssh *ssh, int sock, struct sshbuf *m)
1614 {
1615 	int r, authenticated;
1616 	const char *displayname;
1617 
1618 	if (!options.gss_authentication)
1619 		fatal_f("GSSAPI authentication not enabled");
1620 
1621 	authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
1622 
1623 	sshbuf_reset(m);
1624 	if ((r = sshbuf_put_u32(m, authenticated)) != 0)
1625 		fatal_fr(r, "assemble");
1626 
1627 	debug3_f("sending result %d", authenticated);
1628 	mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
1629 
1630 	auth_method = "gssapi-with-mic";
1631 
1632 	if ((displayname = ssh_gssapi_displayname()) != NULL)
1633 		auth2_record_info(authctxt, "%s", displayname);
1634 
1635 	/* Monitor loop will terminate if authenticated */
1636 	return (authenticated);
1637 }
1638 #endif /* GSSAPI */
1639 
1640