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