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