xref: /freebsd/crypto/openssh/monitor.c (revision 3332f1b444d4a73238e9f59cca27bfc95fe936bd)
1 /* $OpenBSD: monitor.c,v 1.228 2021/08/11 05:20:17 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_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 	char *username;
713 	struct passwd *pwent;
714 	int r, allowed = 0;
715 	u_int i;
716 
717 	debug3_f("entering");
718 
719 	if (authctxt->attempt++ != 0)
720 		fatal_f("multiple attempts for getpwnam");
721 
722 	if ((r = sshbuf_get_cstring(m, &username, NULL)) != 0)
723 		fatal_fr(r, "parse");
724 
725 	pwent = getpwnamallow(ssh, username);
726 
727 	authctxt->user = xstrdup(username);
728 	setproctitle("%s [priv]", pwent ? username : "unknown");
729 	free(username);
730 
731 	sshbuf_reset(m);
732 
733 	if (pwent == NULL) {
734 		if ((r = sshbuf_put_u8(m, 0)) != 0)
735 			fatal_fr(r, "assemble fakepw");
736 		authctxt->pw = fakepw();
737 		goto out;
738 	}
739 
740 	allowed = 1;
741 	authctxt->pw = pwent;
742 	authctxt->valid = 1;
743 
744 	/* XXX send fake class/dir/shell, etc. */
745 	if ((r = sshbuf_put_u8(m, 1)) != 0)
746 		fatal_fr(r, "assemble ok");
747 	PUTPW(m, pw_uid);
748 	PUTPW(m, pw_gid);
749 #ifdef HAVE_STRUCT_PASSWD_PW_CHANGE
750 	PUTPW(m, pw_change);
751 #endif
752 #ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
753 	PUTPW(m, pw_expire);
754 #endif
755 	if ((r = sshbuf_put_cstring(m, pwent->pw_name)) != 0 ||
756 	    (r = sshbuf_put_cstring(m, "*")) != 0 ||
757 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
758 	    (r = sshbuf_put_cstring(m, pwent->pw_gecos)) != 0 ||
759 #endif
760 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
761 	    (r = sshbuf_put_cstring(m, pwent->pw_class)) != 0 ||
762 #endif
763 	    (r = sshbuf_put_cstring(m, pwent->pw_dir)) != 0 ||
764 	    (r = sshbuf_put_cstring(m, pwent->pw_shell)) != 0)
765 		fatal_fr(r, "assemble pw");
766 
767  out:
768 	ssh_packet_set_log_preamble(ssh, "%suser %s",
769 	    authctxt->valid ? "authenticating" : "invalid ", authctxt->user);
770 	if ((r = sshbuf_put_string(m, &options, sizeof(options))) != 0)
771 		fatal_fr(r, "assemble options");
772 
773 #define M_CP_STROPT(x) do { \
774 		if (options.x != NULL && \
775 		    (r = sshbuf_put_cstring(m, options.x)) != 0) \
776 			fatal_fr(r, "assemble %s", #x); \
777 	} while (0)
778 #define M_CP_STRARRAYOPT(x, nx) do { \
779 		for (i = 0; i < options.nx; i++) { \
780 			if ((r = sshbuf_put_cstring(m, options.x[i])) != 0) \
781 				fatal_fr(r, "assemble %s", #x); \
782 		} \
783 	} while (0)
784 	/* See comment in servconf.h */
785 	COPY_MATCH_STRING_OPTS();
786 #undef M_CP_STROPT
787 #undef M_CP_STRARRAYOPT
788 
789 	/* Create valid auth method lists */
790 	if (auth2_setup_methods_lists(authctxt) != 0) {
791 		/*
792 		 * The monitor will continue long enough to let the child
793 		 * run to it's packet_disconnect(), but it must not allow any
794 		 * authentication to succeed.
795 		 */
796 		debug_f("no valid authentication method lists");
797 	}
798 
799 	debug3_f("sending MONITOR_ANS_PWNAM: %d", allowed);
800 	mm_request_send(sock, MONITOR_ANS_PWNAM, m);
801 
802 	/* Allow service/style information on the auth context */
803 	monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
804 	monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
805 
806 #ifdef USE_PAM
807 	if (options.use_pam)
808 		monitor_permit(mon_dispatch, MONITOR_REQ_PAM_START, 1);
809 #endif
810 
811 	return (0);
812 }
813 
814 int mm_answer_auth2_read_banner(struct ssh *ssh, int sock, struct sshbuf *m)
815 {
816 	char *banner;
817 	int r;
818 
819 	sshbuf_reset(m);
820 	banner = auth2_read_banner();
821 	if ((r = sshbuf_put_cstring(m, banner != NULL ? banner : "")) != 0)
822 		fatal_fr(r, "assemble");
823 	mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
824 	free(banner);
825 
826 	return (0);
827 }
828 
829 int
830 mm_answer_authserv(struct ssh *ssh, int sock, struct sshbuf *m)
831 {
832 	int r;
833 
834 	monitor_permit_authentications(1);
835 
836 	if ((r = sshbuf_get_cstring(m, &authctxt->service, NULL)) != 0 ||
837 	    (r = sshbuf_get_cstring(m, &authctxt->style, NULL)) != 0)
838 		fatal_fr(r, "parse");
839 	debug3_f("service=%s, style=%s", authctxt->service, authctxt->style);
840 
841 	if (strlen(authctxt->style) == 0) {
842 		free(authctxt->style);
843 		authctxt->style = NULL;
844 	}
845 
846 	return (0);
847 }
848 
849 /*
850  * Check that the key type appears in the supplied pattern list, ignoring
851  * mismatches in the signature algorithm. (Signature algorithm checks are
852  * performed in the unprivileged authentication code).
853  * Returns 1 on success, 0 otherwise.
854  */
855 static int
856 key_base_type_match(const char *method, const struct sshkey *key,
857     const char *list)
858 {
859 	char *s, *l, *ol = xstrdup(list);
860 	int found = 0;
861 
862 	l = ol;
863 	for ((s = strsep(&l, ",")); s && *s != '\0'; (s = strsep(&l, ","))) {
864 		if (sshkey_type_from_name(s) == key->type) {
865 			found = 1;
866 			break;
867 		}
868 	}
869 	if (!found) {
870 		error("%s key type %s is not in permitted list %s", method,
871 		    sshkey_ssh_name(key), list);
872 	}
873 
874 	free(ol);
875 	return found;
876 }
877 
878 int
879 mm_answer_authpassword(struct ssh *ssh, int sock, struct sshbuf *m)
880 {
881 	static int call_count;
882 	char *passwd;
883 	int r, authenticated;
884 	size_t plen;
885 
886 	if (!options.password_authentication)
887 		fatal_f("password authentication not enabled");
888 	if ((r = sshbuf_get_cstring(m, &passwd, &plen)) != 0)
889 		fatal_fr(r, "parse");
890 	/* Only authenticate if the context is valid */
891 	authenticated = options.password_authentication &&
892 	    auth_password(ssh, passwd);
893 	freezero(passwd, plen);
894 
895 	sshbuf_reset(m);
896 	if ((r = sshbuf_put_u32(m, authenticated)) != 0)
897 		fatal_fr(r, "assemble");
898 #ifdef USE_PAM
899 	if ((r = sshbuf_put_u32(m, sshpam_get_maxtries_reached())) != 0)
900 		fatal_fr(r, "assemble PAM");
901 #endif
902 
903 	debug3("%s: sending result %d", __func__, authenticated);
904 	debug3_f("sending result %d", authenticated);
905 	mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
906 
907 	call_count++;
908 	if (plen == 0 && call_count == 1)
909 		auth_method = "none";
910 	else
911 		auth_method = "password";
912 
913 	/* Causes monitor loop to terminate if authenticated */
914 	return (authenticated);
915 }
916 
917 #ifdef BSD_AUTH
918 int
919 mm_answer_bsdauthquery(struct ssh *ssh, int sock, struct sshbuf *m)
920 {
921 	char *name, *infotxt;
922 	u_int numprompts, *echo_on, success;
923 	char **prompts;
924 	int r;
925 
926 	if (!options.kbd_interactive_authentication)
927 		fatal_f("kbd-int authentication not enabled");
928 	success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
929 	    &prompts, &echo_on) < 0 ? 0 : 1;
930 
931 	sshbuf_reset(m);
932 	if ((r = sshbuf_put_u32(m, success)) != 0)
933 		fatal_fr(r, "assemble");
934 	if (success) {
935 		if ((r = sshbuf_put_cstring(m, prompts[0])) != 0)
936 			fatal_fr(r, "assemble prompt");
937 	}
938 
939 	debug3_f("sending challenge success: %u", success);
940 	mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
941 
942 	if (success) {
943 		free(name);
944 		free(infotxt);
945 		free(prompts);
946 		free(echo_on);
947 	}
948 
949 	return (0);
950 }
951 
952 int
953 mm_answer_bsdauthrespond(struct ssh *ssh, int sock, struct sshbuf *m)
954 {
955 	char *response;
956 	int r, authok;
957 
958 	if (!options.kbd_interactive_authentication)
959 		fatal_f("kbd-int authentication not enabled");
960 	if (authctxt->as == NULL)
961 		fatal_f("no bsd auth session");
962 
963 	if ((r = sshbuf_get_cstring(m, &response, NULL)) != 0)
964 		fatal_fr(r, "parse");
965 	authok = options.kbd_interactive_authentication &&
966 	    auth_userresponse(authctxt->as, response, 0);
967 	authctxt->as = NULL;
968 	debug3_f("<%s> = <%d>", response, authok);
969 	free(response);
970 
971 	sshbuf_reset(m);
972 	if ((r = sshbuf_put_u32(m, authok)) != 0)
973 		fatal_fr(r, "assemble");
974 
975 	debug3_f("sending authenticated: %d", authok);
976 	mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
977 
978 	auth_method = "keyboard-interactive";
979 	auth_submethod = "bsdauth";
980 
981 	return (authok != 0);
982 }
983 #endif
984 
985 #ifdef USE_PAM
986 int
987 mm_answer_pam_start(struct ssh *ssh, int sock, struct sshbuf *m)
988 {
989 	if (!options.use_pam)
990 		fatal("UsePAM not set, but ended up in %s anyway", __func__);
991 
992 	start_pam(ssh);
993 
994 	monitor_permit(mon_dispatch, MONITOR_REQ_PAM_ACCOUNT, 1);
995 	if (options.kbd_interactive_authentication)
996 		monitor_permit(mon_dispatch, MONITOR_REQ_PAM_INIT_CTX, 1);
997 
998 	return (0);
999 }
1000 
1001 int
1002 mm_answer_pam_account(struct ssh *ssh, int sock, struct sshbuf *m)
1003 {
1004 	u_int ret;
1005 	int r;
1006 
1007 	if (!options.use_pam)
1008 		fatal("%s: PAM not enabled", __func__);
1009 
1010 	ret = do_pam_account();
1011 
1012 	if ((r = sshbuf_put_u32(m, ret)) != 0 ||
1013 	    (r = sshbuf_put_stringb(m, loginmsg)) != 0)
1014 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1015 
1016 	mm_request_send(sock, MONITOR_ANS_PAM_ACCOUNT, m);
1017 
1018 	return (ret);
1019 }
1020 
1021 static void *sshpam_ctxt, *sshpam_authok;
1022 extern KbdintDevice sshpam_device;
1023 
1024 int
1025 mm_answer_pam_init_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
1026 {
1027 	u_int ok = 0;
1028 	int r;
1029 
1030 	debug3("%s", __func__);
1031 	if (!options.kbd_interactive_authentication)
1032 		fatal("%s: kbd-int authentication not enabled", __func__);
1033 	if (sshpam_ctxt != NULL)
1034 		fatal("%s: already called", __func__);
1035 	sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
1036 	sshpam_authok = NULL;
1037 	sshbuf_reset(m);
1038 	if (sshpam_ctxt != NULL) {
1039 		monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
1040 		monitor_permit(mon_dispatch, MONITOR_REQ_PAM_QUERY, 1);
1041 		ok = 1;
1042 	}
1043 	if ((r = sshbuf_put_u32(m, ok)) != 0)
1044 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1045 	mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
1046 	return (0);
1047 }
1048 
1049 int
1050 mm_answer_pam_query(struct ssh *ssh, int sock, struct sshbuf *m)
1051 {
1052 	char *name = NULL, *info = NULL, **prompts = NULL;
1053 	u_int i, num = 0, *echo_on = 0;
1054 	int r, ret;
1055 
1056 	debug3("%s", __func__);
1057 	sshpam_authok = NULL;
1058 	if (sshpam_ctxt == NULL)
1059 		fatal("%s: no context", __func__);
1060 	ret = (sshpam_device.query)(sshpam_ctxt, &name, &info,
1061 	    &num, &prompts, &echo_on);
1062 	if (ret == 0 && num == 0)
1063 		sshpam_authok = sshpam_ctxt;
1064 	if (num > 1 || name == NULL || info == NULL)
1065 		fatal("sshpam_device.query failed");
1066 	monitor_permit(mon_dispatch, MONITOR_REQ_PAM_RESPOND, 1);
1067 	sshbuf_reset(m);
1068 	if ((r = sshbuf_put_u32(m, ret)) != 0 ||
1069 	    (r = sshbuf_put_cstring(m, name)) != 0 ||
1070 	    (r = sshbuf_put_cstring(m, info)) != 0 ||
1071 	    (r = sshbuf_put_u32(m, sshpam_get_maxtries_reached())) != 0 ||
1072 	    (r = sshbuf_put_u32(m, num)) != 0)
1073 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1074 	free(name);
1075 	free(info);
1076 	for (i = 0; i < num; ++i) {
1077 		if ((r = sshbuf_put_cstring(m, prompts[i])) != 0 ||
1078 		    (r = sshbuf_put_u32(m, echo_on[i])) != 0)
1079 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
1080 		free(prompts[i]);
1081 	}
1082 	free(prompts);
1083 	free(echo_on);
1084 	auth_method = "keyboard-interactive";
1085 	auth_submethod = "pam";
1086 	mm_request_send(sock, MONITOR_ANS_PAM_QUERY, m);
1087 	return (0);
1088 }
1089 
1090 int
1091 mm_answer_pam_respond(struct ssh *ssh, int sock, struct sshbuf *m)
1092 {
1093 	char **resp;
1094 	u_int i, num;
1095 	int r, ret;
1096 
1097 	debug3("%s", __func__);
1098 	if (sshpam_ctxt == NULL)
1099 		fatal("%s: no context", __func__);
1100 	sshpam_authok = NULL;
1101 	if ((r = sshbuf_get_u32(m, &num)) != 0)
1102 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1103 	if (num > 0) {
1104 		resp = xcalloc(num, sizeof(char *));
1105 		for (i = 0; i < num; ++i) {
1106 			if ((r = sshbuf_get_cstring(m, &(resp[i]), NULL)) != 0)
1107 				fatal("%s: buffer error: %s",
1108 				    __func__, ssh_err(r));
1109 		}
1110 		ret = (sshpam_device.respond)(sshpam_ctxt, num, resp);
1111 		for (i = 0; i < num; ++i)
1112 			free(resp[i]);
1113 		free(resp);
1114 	} else {
1115 		ret = (sshpam_device.respond)(sshpam_ctxt, num, NULL);
1116 	}
1117 	sshbuf_reset(m);
1118 	if ((r = sshbuf_put_u32(m, ret)) != 0)
1119 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1120 	mm_request_send(sock, MONITOR_ANS_PAM_RESPOND, m);
1121 	auth_method = "keyboard-interactive";
1122 	auth_submethod = "pam";
1123 	if (ret == 0)
1124 		sshpam_authok = sshpam_ctxt;
1125 	return (0);
1126 }
1127 
1128 int
1129 mm_answer_pam_free_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
1130 {
1131 	int r = sshpam_authok != NULL && sshpam_authok == sshpam_ctxt;
1132 
1133 	debug3("%s", __func__);
1134 	if (sshpam_ctxt == NULL)
1135 		fatal("%s: no context", __func__);
1136 	(sshpam_device.free_ctx)(sshpam_ctxt);
1137 	sshpam_ctxt = sshpam_authok = NULL;
1138 	sshbuf_reset(m);
1139 	mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
1140 	/* Allow another attempt */
1141 	monitor_permit(mon_dispatch, MONITOR_REQ_PAM_INIT_CTX, 1);
1142 	auth_method = "keyboard-interactive";
1143 	auth_submethod = "pam";
1144 	return r;
1145 }
1146 #endif
1147 
1148 int
1149 mm_answer_keyallowed(struct ssh *ssh, int sock, struct sshbuf *m)
1150 {
1151 	struct sshkey *key = NULL;
1152 	char *cuser, *chost;
1153 	u_int pubkey_auth_attempt;
1154 	u_int type = 0;
1155 	int r, allowed = 0;
1156 	struct sshauthopt *opts = NULL;
1157 
1158 	debug3_f("entering");
1159 	if ((r = sshbuf_get_u32(m, &type)) != 0 ||
1160 	    (r = sshbuf_get_cstring(m, &cuser, NULL)) != 0 ||
1161 	    (r = sshbuf_get_cstring(m, &chost, NULL)) != 0 ||
1162 	    (r = sshkey_froms(m, &key)) != 0 ||
1163 	    (r = sshbuf_get_u32(m, &pubkey_auth_attempt)) != 0)
1164 		fatal_fr(r, "parse");
1165 
1166 	if (key != NULL && authctxt->valid) {
1167 		/* These should not make it past the privsep child */
1168 		if (sshkey_type_plain(key->type) == KEY_RSA &&
1169 		    (ssh->compat & SSH_BUG_RSASIGMD5) != 0)
1170 			fatal_f("passed a SSH_BUG_RSASIGMD5 key");
1171 
1172 		switch (type) {
1173 		case MM_USERKEY:
1174 			auth_method = "publickey";
1175 			if (!options.pubkey_authentication)
1176 				break;
1177 			if (auth2_key_already_used(authctxt, key))
1178 				break;
1179 			if (!key_base_type_match(auth_method, key,
1180 			    options.pubkey_accepted_algos))
1181 				break;
1182 			allowed = user_key_allowed(ssh, authctxt->pw, key,
1183 			    pubkey_auth_attempt, &opts);
1184 			break;
1185 		case MM_HOSTKEY:
1186 			auth_method = "hostbased";
1187 			if (!options.hostbased_authentication)
1188 				break;
1189 			if (auth2_key_already_used(authctxt, key))
1190 				break;
1191 			if (!key_base_type_match(auth_method, key,
1192 			    options.hostbased_accepted_algos))
1193 				break;
1194 			allowed = hostbased_key_allowed(ssh, authctxt->pw,
1195 			    cuser, chost, key);
1196 			auth2_record_info(authctxt,
1197 			    "client user \"%.100s\", client host \"%.100s\"",
1198 			    cuser, chost);
1199 			break;
1200 		default:
1201 			fatal_f("unknown key type %u", type);
1202 			break;
1203 		}
1204 	}
1205 
1206 	debug3_f("%s authentication%s: %s key is %s", auth_method,
1207 	    pubkey_auth_attempt ? "" : " test",
1208 	    (key == NULL || !authctxt->valid) ? "invalid" : sshkey_type(key),
1209 	    allowed ? "allowed" : "not allowed");
1210 
1211 	auth2_record_key(authctxt, 0, key);
1212 
1213 	/* clear temporarily storage (used by verify) */
1214 	monitor_reset_key_state();
1215 
1216 	if (allowed) {
1217 		/* Save temporarily for comparison in verify */
1218 		if ((r = sshkey_to_blob(key, &key_blob, &key_bloblen)) != 0)
1219 			fatal_fr(r, "sshkey_to_blob");
1220 		key_blobtype = type;
1221 		key_opts = opts;
1222 		hostbased_cuser = cuser;
1223 		hostbased_chost = chost;
1224 	} else {
1225 		/* Log failed attempt */
1226 		auth_log(ssh, 0, 0, auth_method, NULL);
1227 		free(cuser);
1228 		free(chost);
1229 	}
1230 	sshkey_free(key);
1231 
1232 	sshbuf_reset(m);
1233 	if ((r = sshbuf_put_u32(m, allowed)) != 0)
1234 		fatal_fr(r, "assemble");
1235 	if (opts != NULL && (r = sshauthopt_serialise(opts, m, 1)) != 0)
1236 		fatal_fr(r, "sshauthopt_serialise");
1237 	mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
1238 
1239 	if (!allowed)
1240 		sshauthopt_free(opts);
1241 
1242 	return (0);
1243 }
1244 
1245 static int
1246 monitor_valid_userblob(struct ssh *ssh, const u_char *data, u_int datalen)
1247 {
1248 	struct sshbuf *b;
1249 	const u_char *p;
1250 	char *userstyle, *cp;
1251 	size_t len;
1252 	u_char type;
1253 	int r, fail = 0;
1254 
1255 	if ((b = sshbuf_from(data, datalen)) == NULL)
1256 		fatal_f("sshbuf_from");
1257 
1258 	if (ssh->compat & SSH_OLD_SESSIONID) {
1259 		p = sshbuf_ptr(b);
1260 		len = sshbuf_len(b);
1261 		if ((session_id2 == NULL) ||
1262 		    (len < session_id2_len) ||
1263 		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1264 			fail++;
1265 		if ((r = sshbuf_consume(b, session_id2_len)) != 0)
1266 			fatal_fr(r, "consume");
1267 	} else {
1268 		if ((r = sshbuf_get_string_direct(b, &p, &len)) != 0)
1269 			fatal_fr(r, "parse sessionid");
1270 		if ((session_id2 == NULL) ||
1271 		    (len != session_id2_len) ||
1272 		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1273 			fail++;
1274 	}
1275 	if ((r = sshbuf_get_u8(b, &type)) != 0)
1276 		fatal_fr(r, "parse type");
1277 	if (type != SSH2_MSG_USERAUTH_REQUEST)
1278 		fail++;
1279 	if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1280 		fatal_fr(r, "parse userstyle");
1281 	xasprintf(&userstyle, "%s%s%s", authctxt->user,
1282 	    authctxt->style ? ":" : "",
1283 	    authctxt->style ? authctxt->style : "");
1284 	if (strcmp(userstyle, cp) != 0) {
1285 		logit("wrong user name passed to monitor: "
1286 		    "expected %s != %.100s", userstyle, cp);
1287 		fail++;
1288 	}
1289 	free(userstyle);
1290 	free(cp);
1291 	if ((r = sshbuf_skip_string(b)) != 0 ||	/* service */
1292 	    (r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1293 		fatal_fr(r, "parse method");
1294 	if (strcmp("publickey", cp) != 0)
1295 		fail++;
1296 	free(cp);
1297 	if ((r = sshbuf_get_u8(b, &type)) != 0)
1298 		fatal_fr(r, "parse pktype");
1299 	if (type == 0)
1300 		fail++;
1301 	if ((r = sshbuf_skip_string(b)) != 0 ||	/* pkalg */
1302 	    (r = sshbuf_skip_string(b)) != 0)	/* pkblob */
1303 		fatal_fr(r, "parse pk");
1304 	if (sshbuf_len(b) != 0)
1305 		fail++;
1306 	sshbuf_free(b);
1307 	return (fail == 0);
1308 }
1309 
1310 static int
1311 monitor_valid_hostbasedblob(const u_char *data, u_int datalen,
1312     const char *cuser, const char *chost)
1313 {
1314 	struct sshbuf *b;
1315 	const u_char *p;
1316 	char *cp, *userstyle;
1317 	size_t len;
1318 	int r, fail = 0;
1319 	u_char type;
1320 
1321 	if ((b = sshbuf_from(data, datalen)) == NULL)
1322 		fatal_f("sshbuf_new");
1323 	if ((r = sshbuf_get_string_direct(b, &p, &len)) != 0)
1324 		fatal_fr(r, "parse sessionid");
1325 
1326 	if ((session_id2 == NULL) ||
1327 	    (len != session_id2_len) ||
1328 	    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1329 		fail++;
1330 
1331 	if ((r = sshbuf_get_u8(b, &type)) != 0)
1332 		fatal_fr(r, "parse type");
1333 	if (type != SSH2_MSG_USERAUTH_REQUEST)
1334 		fail++;
1335 	if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1336 		fatal_fr(r, "parse userstyle");
1337 	xasprintf(&userstyle, "%s%s%s", authctxt->user,
1338 	    authctxt->style ? ":" : "",
1339 	    authctxt->style ? authctxt->style : "");
1340 	if (strcmp(userstyle, cp) != 0) {
1341 		logit("wrong user name passed to monitor: "
1342 		    "expected %s != %.100s", userstyle, cp);
1343 		fail++;
1344 	}
1345 	free(userstyle);
1346 	free(cp);
1347 	if ((r = sshbuf_skip_string(b)) != 0 ||	/* service */
1348 	    (r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1349 		fatal_fr(r, "parse method");
1350 	if (strcmp(cp, "hostbased") != 0)
1351 		fail++;
1352 	free(cp);
1353 	if ((r = sshbuf_skip_string(b)) != 0 ||	/* pkalg */
1354 	    (r = sshbuf_skip_string(b)) != 0)	/* pkblob */
1355 		fatal_fr(r, "parse pk");
1356 
1357 	/* verify client host, strip trailing dot if necessary */
1358 	if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1359 		fatal_fr(r, "parse host");
1360 	if (((len = strlen(cp)) > 0) && cp[len - 1] == '.')
1361 		cp[len - 1] = '\0';
1362 	if (strcmp(cp, chost) != 0)
1363 		fail++;
1364 	free(cp);
1365 
1366 	/* verify client user */
1367 	if ((r = sshbuf_get_cstring(b, &cp, NULL)) != 0)
1368 		fatal_fr(r, "parse ruser");
1369 	if (strcmp(cp, cuser) != 0)
1370 		fail++;
1371 	free(cp);
1372 
1373 	if (sshbuf_len(b) != 0)
1374 		fail++;
1375 	sshbuf_free(b);
1376 	return (fail == 0);
1377 }
1378 
1379 int
1380 mm_answer_keyverify(struct ssh *ssh, int sock, struct sshbuf *m)
1381 {
1382 	struct sshkey *key;
1383 	const u_char *signature, *data, *blob;
1384 	char *sigalg = NULL, *fp = NULL;
1385 	size_t signaturelen, datalen, bloblen;
1386 	int r, ret, req_presence = 0, req_verify = 0, valid_data = 0;
1387 	int encoded_ret;
1388 	struct sshkey_sig_details *sig_details = NULL;
1389 
1390 	if ((r = sshbuf_get_string_direct(m, &blob, &bloblen)) != 0 ||
1391 	    (r = sshbuf_get_string_direct(m, &signature, &signaturelen)) != 0 ||
1392 	    (r = sshbuf_get_string_direct(m, &data, &datalen)) != 0 ||
1393 	    (r = sshbuf_get_cstring(m, &sigalg, NULL)) != 0)
1394 		fatal_fr(r, "parse");
1395 
1396 	if (hostbased_cuser == NULL || hostbased_chost == NULL ||
1397 	  !monitor_allowed_key(blob, bloblen))
1398 		fatal_f("bad key, not previously allowed");
1399 
1400 	/* Empty signature algorithm means NULL. */
1401 	if (*sigalg == '\0') {
1402 		free(sigalg);
1403 		sigalg = NULL;
1404 	}
1405 
1406 	/* XXX use sshkey_froms here; need to change key_blob, etc. */
1407 	if ((r = sshkey_from_blob(blob, bloblen, &key)) != 0)
1408 		fatal_fr(r, "parse key");
1409 
1410 	switch (key_blobtype) {
1411 	case MM_USERKEY:
1412 		valid_data = monitor_valid_userblob(ssh, data, datalen);
1413 		auth_method = "publickey";
1414 		break;
1415 	case MM_HOSTKEY:
1416 		valid_data = monitor_valid_hostbasedblob(data, datalen,
1417 		    hostbased_cuser, hostbased_chost);
1418 		auth_method = "hostbased";
1419 		break;
1420 	default:
1421 		valid_data = 0;
1422 		break;
1423 	}
1424 	if (!valid_data)
1425 		fatal_f("bad %s signature data blob",
1426 		    key_blobtype == MM_USERKEY ? "userkey" :
1427 		    (key_blobtype == MM_HOSTKEY ? "hostkey" : "unknown"));
1428 
1429 	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
1430 	    SSH_FP_DEFAULT)) == NULL)
1431 		fatal_f("sshkey_fingerprint failed");
1432 
1433 	ret = sshkey_verify(key, signature, signaturelen, data, datalen,
1434 	    sigalg, ssh->compat, &sig_details);
1435 	debug3_f("%s %s signature %s%s%s", auth_method, sshkey_type(key),
1436 	    (ret == 0) ? "verified" : "unverified",
1437 	    (ret != 0) ? ": " : "", (ret != 0) ? ssh_err(ret) : "");
1438 
1439 	if (ret == 0 && key_blobtype == MM_USERKEY && sig_details != NULL) {
1440 		req_presence = (options.pubkey_auth_options &
1441 		    PUBKEYAUTH_TOUCH_REQUIRED) ||
1442 		    !key_opts->no_require_user_presence;
1443 		if (req_presence &&
1444 		    (sig_details->sk_flags & SSH_SK_USER_PRESENCE_REQD) == 0) {
1445 			error("public key %s %s signature for %s%s from %.128s "
1446 			    "port %d rejected: user presence "
1447 			    "(authenticator touch) requirement not met ",
1448 			    sshkey_type(key), fp,
1449 			    authctxt->valid ? "" : "invalid user ",
1450 			    authctxt->user, ssh_remote_ipaddr(ssh),
1451 			    ssh_remote_port(ssh));
1452 			ret = SSH_ERR_SIGNATURE_INVALID;
1453 		}
1454 		req_verify = (options.pubkey_auth_options &
1455 		    PUBKEYAUTH_VERIFY_REQUIRED) || key_opts->require_verify;
1456 		if (req_verify &&
1457 		    (sig_details->sk_flags & SSH_SK_USER_VERIFICATION_REQD) == 0) {
1458 			error("public key %s %s signature for %s%s from %.128s "
1459 			    "port %d rejected: user verification requirement "
1460 			    "not met ", sshkey_type(key), fp,
1461 			    authctxt->valid ? "" : "invalid user ",
1462 			    authctxt->user, ssh_remote_ipaddr(ssh),
1463 			    ssh_remote_port(ssh));
1464 			ret = SSH_ERR_SIGNATURE_INVALID;
1465 		}
1466 	}
1467 	auth2_record_key(authctxt, ret == 0, key);
1468 
1469 	if (key_blobtype == MM_USERKEY)
1470 		auth_activate_options(ssh, key_opts);
1471 	monitor_reset_key_state();
1472 
1473 	sshbuf_reset(m);
1474 
1475 	/* encode ret != 0 as positive integer, since we're sending u32 */
1476 	encoded_ret = (ret != 0);
1477 	if ((r = sshbuf_put_u32(m, encoded_ret)) != 0 ||
1478 	    (r = sshbuf_put_u8(m, sig_details != NULL)) != 0)
1479 		fatal_fr(r, "assemble");
1480 	if (sig_details != NULL) {
1481 		if ((r = sshbuf_put_u32(m, sig_details->sk_counter)) != 0 ||
1482 		    (r = sshbuf_put_u8(m, sig_details->sk_flags)) != 0)
1483 			fatal_fr(r, "assemble sk");
1484 	}
1485 	sshkey_sig_details_free(sig_details);
1486 	mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
1487 
1488 	free(sigalg);
1489 	free(fp);
1490 	sshkey_free(key);
1491 
1492 	return ret == 0;
1493 }
1494 
1495 static void
1496 mm_record_login(struct ssh *ssh, Session *s, struct passwd *pw)
1497 {
1498 	socklen_t fromlen;
1499 	struct sockaddr_storage from;
1500 
1501 	/*
1502 	 * Get IP address of client. If the connection is not a socket, let
1503 	 * the address be 0.0.0.0.
1504 	 */
1505 	memset(&from, 0, sizeof(from));
1506 	fromlen = sizeof(from);
1507 	if (ssh_packet_connection_is_on_socket(ssh)) {
1508 		if (getpeername(ssh_packet_get_connection_in(ssh),
1509 		    (struct sockaddr *)&from, &fromlen) == -1) {
1510 			debug("getpeername: %.100s", strerror(errno));
1511 			cleanup_exit(255);
1512 		}
1513 	}
1514 	/* Record that there was a login on that tty from the remote host. */
1515 	record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
1516 	    session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
1517 	    (struct sockaddr *)&from, fromlen);
1518 }
1519 
1520 static void
1521 mm_session_close(Session *s)
1522 {
1523 	debug3_f("session %d pid %ld", s->self, (long)s->pid);
1524 	if (s->ttyfd != -1) {
1525 		debug3_f("tty %s ptyfd %d", s->tty, s->ptyfd);
1526 		session_pty_cleanup2(s);
1527 	}
1528 	session_unused(s->self);
1529 }
1530 
1531 int
1532 mm_answer_pty(struct ssh *ssh, int sock, struct sshbuf *m)
1533 {
1534 	extern struct monitor *pmonitor;
1535 	Session *s;
1536 	int r, res, fd0;
1537 
1538 	debug3_f("entering");
1539 
1540 	sshbuf_reset(m);
1541 	s = session_new();
1542 	if (s == NULL)
1543 		goto error;
1544 	s->authctxt = authctxt;
1545 	s->pw = authctxt->pw;
1546 	s->pid = pmonitor->m_pid;
1547 	res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1548 	if (res == 0)
1549 		goto error;
1550 	pty_setowner(authctxt->pw, s->tty);
1551 
1552 	if ((r = sshbuf_put_u32(m, 1)) != 0 ||
1553 	    (r = sshbuf_put_cstring(m, s->tty)) != 0)
1554 		fatal_fr(r, "assemble");
1555 
1556 	/* We need to trick ttyslot */
1557 	if (dup2(s->ttyfd, 0) == -1)
1558 		fatal_f("dup2");
1559 
1560 	mm_record_login(ssh, s, authctxt->pw);
1561 
1562 	/* Now we can close the file descriptor again */
1563 	close(0);
1564 
1565 	/* send messages generated by record_login */
1566 	if ((r = sshbuf_put_stringb(m, loginmsg)) != 0)
1567 		fatal_fr(r, "assemble loginmsg");
1568 	sshbuf_reset(loginmsg);
1569 
1570 	mm_request_send(sock, MONITOR_ANS_PTY, m);
1571 
1572 	if (mm_send_fd(sock, s->ptyfd) == -1 ||
1573 	    mm_send_fd(sock, s->ttyfd) == -1)
1574 		fatal_f("send fds failed");
1575 
1576 	/* make sure nothing uses fd 0 */
1577 	if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1578 		fatal_f("open(/dev/null): %s", strerror(errno));
1579 	if (fd0 != 0)
1580 		error_f("fd0 %d != 0", fd0);
1581 
1582 	/* slave side of pty is not needed */
1583 	close(s->ttyfd);
1584 	s->ttyfd = s->ptyfd;
1585 	/* no need to dup() because nobody closes ptyfd */
1586 	s->ptymaster = s->ptyfd;
1587 
1588 	debug3_f("tty %s ptyfd %d", s->tty, s->ttyfd);
1589 
1590 	return (0);
1591 
1592  error:
1593 	if (s != NULL)
1594 		mm_session_close(s);
1595 	if ((r = sshbuf_put_u32(m, 0)) != 0)
1596 		fatal_fr(r, "assemble 0");
1597 	mm_request_send(sock, MONITOR_ANS_PTY, m);
1598 	return (0);
1599 }
1600 
1601 int
1602 mm_answer_pty_cleanup(struct ssh *ssh, int sock, struct sshbuf *m)
1603 {
1604 	Session *s;
1605 	char *tty;
1606 	int r;
1607 
1608 	debug3_f("entering");
1609 
1610 	if ((r = sshbuf_get_cstring(m, &tty, NULL)) != 0)
1611 		fatal_fr(r, "parse tty");
1612 	if ((s = session_by_tty(tty)) != NULL)
1613 		mm_session_close(s);
1614 	sshbuf_reset(m);
1615 	free(tty);
1616 	return (0);
1617 }
1618 
1619 int
1620 mm_answer_term(struct ssh *ssh, int sock, struct sshbuf *req)
1621 {
1622 	extern struct monitor *pmonitor;
1623 	int res, status;
1624 
1625 	debug3_f("tearing down sessions");
1626 
1627 	/* The child is terminating */
1628 	session_destroy_all(ssh, &mm_session_close);
1629 
1630 #ifdef USE_PAM
1631 	if (options.use_pam)
1632 		sshpam_cleanup();
1633 #endif
1634 
1635 	while (waitpid(pmonitor->m_pid, &status, 0) == -1)
1636 		if (errno != EINTR)
1637 			exit(1);
1638 
1639 	res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1640 
1641 	/* Terminate process */
1642 	exit(res);
1643 }
1644 
1645 #ifdef SSH_AUDIT_EVENTS
1646 /* Report that an audit event occurred */
1647 int
1648 mm_answer_audit_event(struct ssh *ssh, int socket, struct sshbuf *m)
1649 {
1650 	u_int n;
1651 	ssh_audit_event_t event;
1652 	int r;
1653 
1654 	debug3("%s entering", __func__);
1655 
1656 	if ((r = sshbuf_get_u32(m, &n)) != 0)
1657 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1658 	event = (ssh_audit_event_t)n;
1659 	switch (event) {
1660 	case SSH_AUTH_FAIL_PUBKEY:
1661 	case SSH_AUTH_FAIL_HOSTBASED:
1662 	case SSH_AUTH_FAIL_GSSAPI:
1663 	case SSH_LOGIN_EXCEED_MAXTRIES:
1664 	case SSH_LOGIN_ROOT_DENIED:
1665 	case SSH_CONNECTION_CLOSE:
1666 	case SSH_INVALID_USER:
1667 		audit_event(ssh, event);
1668 		break;
1669 	default:
1670 		fatal("Audit event type %d not permitted", event);
1671 	}
1672 
1673 	return (0);
1674 }
1675 
1676 int
1677 mm_answer_audit_command(struct ssh *ssh, int socket, struct sshbuf *m)
1678 {
1679 	char *cmd;
1680 	int r;
1681 
1682 	debug3("%s entering", __func__);
1683 	if ((r = sshbuf_get_cstring(m, &cmd, NULL)) != 0)
1684 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
1685 	/* sanity check command, if so how? */
1686 	audit_run_command(cmd);
1687 	free(cmd);
1688 	return (0);
1689 }
1690 #endif /* SSH_AUDIT_EVENTS */
1691 
1692 void
1693 monitor_clear_keystate(struct ssh *ssh, struct monitor *pmonitor)
1694 {
1695 	ssh_clear_newkeys(ssh, MODE_IN);
1696 	ssh_clear_newkeys(ssh, MODE_OUT);
1697 	sshbuf_free(child_state);
1698 	child_state = NULL;
1699 }
1700 
1701 void
1702 monitor_apply_keystate(struct ssh *ssh, struct monitor *pmonitor)
1703 {
1704 	struct kex *kex;
1705 	int r;
1706 
1707 	debug3_f("packet_set_state");
1708 	if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
1709 		fatal_fr(r, "packet_set_state");
1710 	sshbuf_free(child_state);
1711 	child_state = NULL;
1712 	if ((kex = ssh->kex) == NULL)
1713 		fatal_f("internal error: ssh->kex == NULL");
1714 	if (session_id2_len != sshbuf_len(ssh->kex->session_id)) {
1715 		fatal_f("incorrect session id length %zu (expected %u)",
1716 		    sshbuf_len(ssh->kex->session_id), session_id2_len);
1717 	}
1718 	if (memcmp(sshbuf_ptr(ssh->kex->session_id), session_id2,
1719 	    session_id2_len) != 0)
1720 		fatal_f("session ID mismatch");
1721 	/* XXX set callbacks */
1722 #ifdef WITH_OPENSSL
1723 	kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_server;
1724 	kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_server;
1725 	kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_server;
1726 	kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_server;
1727 	kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_server;
1728 	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1729 	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1730 # ifdef OPENSSL_HAS_ECC
1731 	kex->kex[KEX_ECDH_SHA2] = kex_gen_server;
1732 # endif
1733 #endif /* WITH_OPENSSL */
1734 	kex->kex[KEX_C25519_SHA256] = kex_gen_server;
1735 	kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_server;
1736 	kex->load_host_public_key=&get_hostkey_public_by_type;
1737 	kex->load_host_private_key=&get_hostkey_private_by_type;
1738 	kex->host_key_index=&get_hostkey_index;
1739 	kex->sign = sshd_hostkey_sign;
1740 }
1741 
1742 /* This function requires careful sanity checking */
1743 
1744 void
1745 mm_get_keystate(struct ssh *ssh, struct monitor *pmonitor)
1746 {
1747 	debug3_f("Waiting for new keys");
1748 
1749 	if ((child_state = sshbuf_new()) == NULL)
1750 		fatal_f("sshbuf_new failed");
1751 	mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT,
1752 	    child_state);
1753 	debug3_f("GOT new keys");
1754 }
1755 
1756 
1757 /* XXX */
1758 
1759 #define FD_CLOSEONEXEC(x) do { \
1760 	if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \
1761 		fatal("fcntl(%d, F_SETFD)", x); \
1762 } while (0)
1763 
1764 static void
1765 monitor_openfds(struct monitor *mon, int do_logfds)
1766 {
1767 	int pair[2];
1768 #ifdef SO_ZEROIZE
1769 	int on = 1;
1770 #endif
1771 
1772 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
1773 		fatal_f("socketpair: %s", strerror(errno));
1774 #ifdef SO_ZEROIZE
1775 	if (setsockopt(pair[0], SOL_SOCKET, SO_ZEROIZE, &on, sizeof(on)) == -1)
1776 		error("setsockopt SO_ZEROIZE(0): %.100s", strerror(errno));
1777 	if (setsockopt(pair[1], SOL_SOCKET, SO_ZEROIZE, &on, sizeof(on)) == -1)
1778 		error("setsockopt SO_ZEROIZE(1): %.100s", strerror(errno));
1779 #endif
1780 	FD_CLOSEONEXEC(pair[0]);
1781 	FD_CLOSEONEXEC(pair[1]);
1782 	mon->m_recvfd = pair[0];
1783 	mon->m_sendfd = pair[1];
1784 
1785 	if (do_logfds) {
1786 		if (pipe(pair) == -1)
1787 			fatal_f("pipe: %s", strerror(errno));
1788 		FD_CLOSEONEXEC(pair[0]);
1789 		FD_CLOSEONEXEC(pair[1]);
1790 		mon->m_log_recvfd = pair[0];
1791 		mon->m_log_sendfd = pair[1];
1792 	} else
1793 		mon->m_log_recvfd = mon->m_log_sendfd = -1;
1794 }
1795 
1796 #define MM_MEMSIZE	65536
1797 
1798 struct monitor *
1799 monitor_init(void)
1800 {
1801 	struct monitor *mon;
1802 
1803 	mon = xcalloc(1, sizeof(*mon));
1804 	monitor_openfds(mon, 1);
1805 
1806 	return mon;
1807 }
1808 
1809 void
1810 monitor_reinit(struct monitor *mon)
1811 {
1812 	monitor_openfds(mon, 0);
1813 }
1814 
1815 #ifdef GSSAPI
1816 int
1817 mm_answer_gss_setup_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
1818 {
1819 	gss_OID_desc goid;
1820 	OM_uint32 major;
1821 	size_t len;
1822 	u_char *p;
1823 	int r;
1824 
1825 	if (!options.gss_authentication)
1826 		fatal_f("GSSAPI authentication not enabled");
1827 
1828 	if ((r = sshbuf_get_string(m, &p, &len)) != 0)
1829 		fatal_fr(r, "parse");
1830 	goid.elements = p;
1831 	goid.length = len;
1832 
1833 	major = ssh_gssapi_server_ctx(&gsscontext, &goid);
1834 
1835 	free(goid.elements);
1836 
1837 	sshbuf_reset(m);
1838 	if ((r = sshbuf_put_u32(m, major)) != 0)
1839 		fatal_fr(r, "assemble");
1840 
1841 	mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
1842 
1843 	/* Now we have a context, enable the step */
1844 	monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
1845 
1846 	return (0);
1847 }
1848 
1849 int
1850 mm_answer_gss_accept_ctx(struct ssh *ssh, int sock, struct sshbuf *m)
1851 {
1852 	gss_buffer_desc in;
1853 	gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
1854 	OM_uint32 major, minor;
1855 	OM_uint32 flags = 0; /* GSI needs this */
1856 	int r;
1857 
1858 	if (!options.gss_authentication)
1859 		fatal_f("GSSAPI authentication not enabled");
1860 
1861 	if ((r = ssh_gssapi_get_buffer_desc(m, &in)) != 0)
1862 		fatal_fr(r, "ssh_gssapi_get_buffer_desc");
1863 	major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
1864 	free(in.value);
1865 
1866 	sshbuf_reset(m);
1867 	if ((r = sshbuf_put_u32(m, major)) != 0 ||
1868 	    (r = sshbuf_put_string(m, out.value, out.length)) != 0 ||
1869 	    (r = sshbuf_put_u32(m, flags)) != 0)
1870 		fatal_fr(r, "assemble");
1871 	mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
1872 
1873 	gss_release_buffer(&minor, &out);
1874 
1875 	if (major == GSS_S_COMPLETE) {
1876 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
1877 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1878 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
1879 	}
1880 	return (0);
1881 }
1882 
1883 int
1884 mm_answer_gss_checkmic(struct ssh *ssh, int sock, struct sshbuf *m)
1885 {
1886 	gss_buffer_desc gssbuf, mic;
1887 	OM_uint32 ret;
1888 	int r;
1889 
1890 	if (!options.gss_authentication)
1891 		fatal_f("GSSAPI authentication not enabled");
1892 
1893 	if ((r = ssh_gssapi_get_buffer_desc(m, &gssbuf)) != 0 ||
1894 	    (r = ssh_gssapi_get_buffer_desc(m, &mic)) != 0)
1895 		fatal_fr(r, "ssh_gssapi_get_buffer_desc");
1896 
1897 	ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
1898 
1899 	free(gssbuf.value);
1900 	free(mic.value);
1901 
1902 	sshbuf_reset(m);
1903 	if ((r = sshbuf_put_u32(m, ret)) != 0)
1904 		fatal_fr(r, "assemble");
1905 
1906 	mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
1907 
1908 	if (!GSS_ERROR(ret))
1909 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1910 
1911 	return (0);
1912 }
1913 
1914 int
1915 mm_answer_gss_userok(struct ssh *ssh, int sock, struct sshbuf *m)
1916 {
1917 	int r, authenticated;
1918 	const char *displayname;
1919 
1920 	if (!options.gss_authentication)
1921 		fatal_f("GSSAPI authentication not enabled");
1922 
1923 	authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
1924 
1925 	sshbuf_reset(m);
1926 	if ((r = sshbuf_put_u32(m, authenticated)) != 0)
1927 		fatal_fr(r, "assemble");
1928 
1929 	debug3_f("sending result %d", authenticated);
1930 	mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
1931 
1932 	auth_method = "gssapi-with-mic";
1933 
1934 	if ((displayname = ssh_gssapi_displayname()) != NULL)
1935 		auth2_record_info(authctxt, "%s", displayname);
1936 
1937 	/* Monitor loop will terminate if authenticated */
1938 	return (authenticated);
1939 }
1940 #endif /* GSSAPI */
1941 
1942