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