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