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