xref: /openbsd/usr.bin/ssh/monitor.c (revision 40a7db51)
1 /* $OpenBSD: monitor.c,v 1.168 2017/05/30 08:52:19 markus 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 <sys/types.h>
29 #include <sys/wait.h>
30 #include <sys/socket.h>
31 #include <sys/tree.h>
32 #include <sys/queue.h>
33 
34 #ifdef WITH_OPENSSL
35 #include <openssl/dh.h>
36 #endif
37 
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <limits.h>
41 #include <paths.h>
42 #include <poll.h>
43 #include <pwd.h>
44 #include <signal.h>
45 #include <stdarg.h>
46 #include <stdint.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 
51 #include "atomicio.h"
52 #include "xmalloc.h"
53 #include "ssh.h"
54 #include "key.h"
55 #include "buffer.h"
56 #include "hostfile.h"
57 #include "auth.h"
58 #include "cipher.h"
59 #include "kex.h"
60 #include "dh.h"
61 #include <zlib.h>
62 #include "packet.h"
63 #include "auth-options.h"
64 #include "sshpty.h"
65 #include "channels.h"
66 #include "session.h"
67 #include "sshlogin.h"
68 #include "canohost.h"
69 #include "log.h"
70 #include "misc.h"
71 #include "servconf.h"
72 #include "monitor.h"
73 #ifdef GSSAPI
74 #include "ssh-gss.h"
75 #endif
76 #include "monitor_wrap.h"
77 #include "monitor_fdpass.h"
78 #include "compat.h"
79 #include "ssh2.h"
80 #include "authfd.h"
81 #include "match.h"
82 #include "ssherr.h"
83 
84 #ifdef GSSAPI
85 static Gssctxt *gsscontext = NULL;
86 #endif
87 
88 /* Imports */
89 extern ServerOptions options;
90 extern u_int utmp_len;
91 extern u_char session_id[];
92 extern Buffer auth_debug;
93 extern int auth_debug_init;
94 extern Buffer loginmsg;
95 
96 /* State exported from the child */
97 static struct sshbuf *child_state;
98 
99 /* Functions on the monitor that answer unprivileged requests */
100 
101 int mm_answer_moduli(int, Buffer *);
102 int mm_answer_sign(int, Buffer *);
103 int mm_answer_pwnamallow(int, Buffer *);
104 int mm_answer_auth2_read_banner(int, Buffer *);
105 int mm_answer_authserv(int, Buffer *);
106 int mm_answer_authpassword(int, Buffer *);
107 int mm_answer_bsdauthquery(int, Buffer *);
108 int mm_answer_bsdauthrespond(int, Buffer *);
109 int mm_answer_skeyquery(int, Buffer *);
110 int mm_answer_skeyrespond(int, Buffer *);
111 int mm_answer_keyallowed(int, Buffer *);
112 int mm_answer_keyverify(int, Buffer *);
113 int mm_answer_pty(int, Buffer *);
114 int mm_answer_pty_cleanup(int, Buffer *);
115 int mm_answer_term(int, Buffer *);
116 int mm_answer_rsa_keyallowed(int, Buffer *);
117 int mm_answer_rsa_challenge(int, Buffer *);
118 int mm_answer_rsa_response(int, Buffer *);
119 int mm_answer_sesskey(int, Buffer *);
120 int mm_answer_sessid(int, Buffer *);
121 
122 #ifdef GSSAPI
123 int mm_answer_gss_setup_ctx(int, Buffer *);
124 int mm_answer_gss_accept_ctx(int, Buffer *);
125 int mm_answer_gss_userok(int, Buffer *);
126 int mm_answer_gss_checkmic(int, Buffer *);
127 #endif
128 
129 static int monitor_read_log(struct monitor *);
130 
131 static Authctxt *authctxt;
132 
133 /* local state for key verify */
134 static u_char *key_blob = NULL;
135 static u_int key_bloblen = 0;
136 static int key_blobtype = MM_NOKEY;
137 static char *hostbased_cuser = NULL;
138 static char *hostbased_chost = NULL;
139 static char *auth_method = "unknown";
140 static char *auth_submethod = NULL;
141 static u_int session_id2_len = 0;
142 static u_char *session_id2 = NULL;
143 static pid_t monitor_child_pid;
144 
145 struct mon_table {
146 	enum monitor_reqtype type;
147 	int flags;
148 	int (*f)(int, Buffer *);
149 };
150 
151 #define MON_ISAUTH	0x0004	/* Required for Authentication */
152 #define MON_AUTHDECIDE	0x0008	/* Decides Authentication */
153 #define MON_ONCE	0x0010	/* Disable after calling */
154 #define MON_ALOG	0x0020	/* Log auth attempt without authenticating */
155 
156 #define MON_AUTH	(MON_ISAUTH|MON_AUTHDECIDE)
157 
158 #define MON_PERMIT	0x1000	/* Request is permitted */
159 
160 struct mon_table mon_dispatch_proto20[] = {
161 #ifdef WITH_OPENSSL
162     {MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli},
163 #endif
164     {MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign},
165     {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
166     {MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv},
167     {MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner},
168     {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
169     {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
170     {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
171     {MONITOR_REQ_KEYALLOWED, MON_ISAUTH, mm_answer_keyallowed},
172     {MONITOR_REQ_KEYVERIFY, MON_AUTH, mm_answer_keyverify},
173 #ifdef GSSAPI
174     {MONITOR_REQ_GSSSETUP, MON_ISAUTH, mm_answer_gss_setup_ctx},
175     {MONITOR_REQ_GSSSTEP, 0, mm_answer_gss_accept_ctx},
176     {MONITOR_REQ_GSSUSEROK, MON_ONCE|MON_AUTHDECIDE, mm_answer_gss_userok},
177     {MONITOR_REQ_GSSCHECKMIC, MON_ONCE, mm_answer_gss_checkmic},
178 #endif
179     {0, 0, NULL}
180 };
181 
182 struct mon_table mon_dispatch_postauth20[] = {
183 #ifdef WITH_OPENSSL
184     {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
185 #endif
186     {MONITOR_REQ_SIGN, 0, mm_answer_sign},
187     {MONITOR_REQ_PTY, 0, mm_answer_pty},
188     {MONITOR_REQ_PTYCLEANUP, 0, mm_answer_pty_cleanup},
189     {MONITOR_REQ_TERM, 0, mm_answer_term},
190     {0, 0, NULL}
191 };
192 
193 struct mon_table *mon_dispatch;
194 
195 /* Specifies if a certain message is allowed at the moment */
196 
197 static void
198 monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit)
199 {
200 	while (ent->f != NULL) {
201 		if (ent->type == type) {
202 			ent->flags &= ~MON_PERMIT;
203 			ent->flags |= permit ? MON_PERMIT : 0;
204 			return;
205 		}
206 		ent++;
207 	}
208 }
209 
210 static void
211 monitor_permit_authentications(int permit)
212 {
213 	struct mon_table *ent = mon_dispatch;
214 
215 	while (ent->f != NULL) {
216 		if (ent->flags & MON_AUTH) {
217 			ent->flags &= ~MON_PERMIT;
218 			ent->flags |= permit ? MON_PERMIT : 0;
219 		}
220 		ent++;
221 	}
222 }
223 
224 void
225 monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor)
226 {
227 	struct ssh *ssh = active_state;	/* XXX */
228 	struct mon_table *ent;
229 	int authenticated = 0, partial = 0;
230 
231 	debug3("preauth child monitor started");
232 
233 	close(pmonitor->m_recvfd);
234 	close(pmonitor->m_log_sendfd);
235 	pmonitor->m_log_sendfd = pmonitor->m_recvfd = -1;
236 
237 	authctxt = _authctxt;
238 	memset(authctxt, 0, sizeof(*authctxt));
239 
240 	mon_dispatch = mon_dispatch_proto20;
241 	/* Permit requests for moduli and signatures */
242 	monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
243 	monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
244 
245 	/* The first few requests do not require asynchronous access */
246 	while (!authenticated) {
247 		partial = 0;
248 		auth_method = "unknown";
249 		auth_submethod = NULL;
250 		authenticated = (monitor_read(pmonitor, mon_dispatch, &ent) == 1);
251 
252 		/* Special handling for multiple required authentications */
253 		if (options.num_auth_methods != 0) {
254 			if (authenticated &&
255 			    !auth2_update_methods_lists(authctxt,
256 			    auth_method, auth_submethod)) {
257 				debug3("%s: method %s: partial", __func__,
258 				    auth_method);
259 				authenticated = 0;
260 				partial = 1;
261 			}
262 		}
263 
264 		if (authenticated) {
265 			if (!(ent->flags & MON_AUTHDECIDE))
266 				fatal("%s: unexpected authentication from %d",
267 				    __func__, ent->type);
268 			if (authctxt->pw->pw_uid == 0 &&
269 			    !auth_root_allowed(auth_method))
270 				authenticated = 0;
271 		}
272 		if (ent->flags & (MON_AUTHDECIDE|MON_ALOG)) {
273 			auth_log(authctxt, authenticated, partial,
274 			    auth_method, auth_submethod);
275 			if (!partial && !authenticated)
276 				authctxt->failures++;
277 		}
278 	}
279 
280 	if (!authctxt->valid)
281 		fatal("%s: authenticated invalid user", __func__);
282 	if (strcmp(auth_method, "unknown") == 0)
283 		fatal("%s: authentication method name unknown", __func__);
284 
285 	debug("%s: %s has been authenticated by privileged process",
286 	    __func__, authctxt->user);
287 	ssh_packet_set_log_preamble(ssh, "user %s", authctxt->user);
288 
289 	mm_get_keystate(pmonitor);
290 
291 	/* Drain any buffered messages from the child */
292 	while (pmonitor->m_log_recvfd != -1 && monitor_read_log(pmonitor) == 0)
293 		;
294 
295 	close(pmonitor->m_sendfd);
296 	close(pmonitor->m_log_recvfd);
297 	pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1;
298 }
299 
300 static void
301 monitor_set_child_handler(pid_t pid)
302 {
303 	monitor_child_pid = pid;
304 }
305 
306 static void
307 monitor_child_handler(int sig)
308 {
309 	kill(monitor_child_pid, sig);
310 }
311 
312 void
313 monitor_child_postauth(struct monitor *pmonitor)
314 {
315 	close(pmonitor->m_recvfd);
316 	pmonitor->m_recvfd = -1;
317 
318 	monitor_set_child_handler(pmonitor->m_pid);
319 	signal(SIGHUP, &monitor_child_handler);
320 	signal(SIGTERM, &monitor_child_handler);
321 	signal(SIGINT, &monitor_child_handler);
322 
323 	mon_dispatch = mon_dispatch_postauth20;
324 
325 	/* Permit requests for moduli and signatures */
326 	monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
327 	monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
328 	monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
329 
330 	if (!no_pty_flag) {
331 		monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1);
332 		monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1);
333 	}
334 
335 	for (;;)
336 		monitor_read(pmonitor, mon_dispatch, NULL);
337 }
338 
339 static int
340 monitor_read_log(struct monitor *pmonitor)
341 {
342 	Buffer logmsg;
343 	u_int len, level;
344 	char *msg;
345 
346 	buffer_init(&logmsg);
347 
348 	/* Read length */
349 	buffer_append_space(&logmsg, 4);
350 	if (atomicio(read, pmonitor->m_log_recvfd,
351 	    buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg)) {
352 		if (errno == EPIPE) {
353 			buffer_free(&logmsg);
354 			debug("%s: child log fd closed", __func__);
355 			close(pmonitor->m_log_recvfd);
356 			pmonitor->m_log_recvfd = -1;
357 			return -1;
358 		}
359 		fatal("%s: log fd read: %s", __func__, strerror(errno));
360 	}
361 	len = buffer_get_int(&logmsg);
362 	if (len <= 4 || len > 8192)
363 		fatal("%s: invalid log message length %u", __func__, len);
364 
365 	/* Read severity, message */
366 	buffer_clear(&logmsg);
367 	buffer_append_space(&logmsg, len);
368 	if (atomicio(read, pmonitor->m_log_recvfd,
369 	    buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg))
370 		fatal("%s: log fd read: %s", __func__, strerror(errno));
371 
372 	/* Log it */
373 	level = buffer_get_int(&logmsg);
374 	msg = buffer_get_string(&logmsg, NULL);
375 	if (log_level_name(level) == NULL)
376 		fatal("%s: invalid log level %u (corrupted message?)",
377 		    __func__, level);
378 	do_log2(level, "%s [preauth]", msg);
379 
380 	buffer_free(&logmsg);
381 	free(msg);
382 
383 	return 0;
384 }
385 
386 int
387 monitor_read(struct monitor *pmonitor, struct mon_table *ent,
388     struct mon_table **pent)
389 {
390 	Buffer m;
391 	int ret;
392 	u_char type;
393 	struct pollfd pfd[2];
394 
395 	for (;;) {
396 		memset(&pfd, 0, sizeof(pfd));
397 		pfd[0].fd = pmonitor->m_sendfd;
398 		pfd[0].events = POLLIN;
399 		pfd[1].fd = pmonitor->m_log_recvfd;
400 		pfd[1].events = pfd[1].fd == -1 ? 0 : POLLIN;
401 		if (poll(pfd, pfd[1].fd == -1 ? 1 : 2, -1) == -1) {
402 			if (errno == EINTR || errno == EAGAIN)
403 				continue;
404 			fatal("%s: poll: %s", __func__, strerror(errno));
405 		}
406 		if (pfd[1].revents) {
407 			/*
408 			 * Drain all log messages before processing next
409 			 * monitor request.
410 			 */
411 			monitor_read_log(pmonitor);
412 			continue;
413 		}
414 		if (pfd[0].revents)
415 			break;  /* Continues below */
416 	}
417 
418 	buffer_init(&m);
419 
420 	mm_request_receive(pmonitor->m_sendfd, &m);
421 	type = buffer_get_char(&m);
422 
423 	debug3("%s: checking request %d", __func__, type);
424 
425 	while (ent->f != NULL) {
426 		if (ent->type == type)
427 			break;
428 		ent++;
429 	}
430 
431 	if (ent->f != NULL) {
432 		if (!(ent->flags & MON_PERMIT))
433 			fatal("%s: unpermitted request %d", __func__,
434 			    type);
435 		ret = (*ent->f)(pmonitor->m_sendfd, &m);
436 		buffer_free(&m);
437 
438 		/* The child may use this request only once, disable it */
439 		if (ent->flags & MON_ONCE) {
440 			debug2("%s: %d used once, disabling now", __func__,
441 			    type);
442 			ent->flags &= ~MON_PERMIT;
443 		}
444 
445 		if (pent != NULL)
446 			*pent = ent;
447 
448 		return ret;
449 	}
450 
451 	fatal("%s: unsupported request: %d", __func__, type);
452 
453 	/* NOTREACHED */
454 	return (-1);
455 }
456 
457 /* allowed key state */
458 static int
459 monitor_allowed_key(u_char *blob, u_int bloblen)
460 {
461 	/* make sure key is allowed */
462 	if (key_blob == NULL || key_bloblen != bloblen ||
463 	    timingsafe_bcmp(key_blob, blob, key_bloblen))
464 		return (0);
465 	return (1);
466 }
467 
468 static void
469 monitor_reset_key_state(void)
470 {
471 	/* reset state */
472 	free(key_blob);
473 	free(hostbased_cuser);
474 	free(hostbased_chost);
475 	key_blob = NULL;
476 	key_bloblen = 0;
477 	key_blobtype = MM_NOKEY;
478 	hostbased_cuser = NULL;
479 	hostbased_chost = NULL;
480 }
481 
482 #ifdef WITH_OPENSSL
483 int
484 mm_answer_moduli(int sock, Buffer *m)
485 {
486 	DH *dh;
487 	int min, want, max;
488 
489 	min = buffer_get_int(m);
490 	want = buffer_get_int(m);
491 	max = buffer_get_int(m);
492 
493 	debug3("%s: got parameters: %d %d %d",
494 	    __func__, min, want, max);
495 	/* We need to check here, too, in case the child got corrupted */
496 	if (max < min || want < min || max < want)
497 		fatal("%s: bad parameters: %d %d %d",
498 		    __func__, min, want, max);
499 
500 	buffer_clear(m);
501 
502 	dh = choose_dh(min, want, max);
503 	if (dh == NULL) {
504 		buffer_put_char(m, 0);
505 		return (0);
506 	} else {
507 		/* Send first bignum */
508 		buffer_put_char(m, 1);
509 		buffer_put_bignum2(m, dh->p);
510 		buffer_put_bignum2(m, dh->g);
511 
512 		DH_free(dh);
513 	}
514 	mm_request_send(sock, MONITOR_ANS_MODULI, m);
515 	return (0);
516 }
517 #endif
518 
519 int
520 mm_answer_sign(int sock, Buffer *m)
521 {
522 	struct ssh *ssh = active_state; 	/* XXX */
523 	extern int auth_sock;			/* XXX move to state struct? */
524 	struct sshkey *key;
525 	struct sshbuf *sigbuf = NULL;
526 	u_char *p = NULL, *signature = NULL;
527 	char *alg = NULL;
528 	size_t datlen, siglen, alglen;
529 	int r, is_proof = 0;
530 	u_int keyid;
531 	const char proof_req[] = "hostkeys-prove-00@openssh.com";
532 
533 	debug3("%s", __func__);
534 
535 	if ((r = sshbuf_get_u32(m, &keyid)) != 0 ||
536 	    (r = sshbuf_get_string(m, &p, &datlen)) != 0 ||
537 	    (r = sshbuf_get_cstring(m, &alg, &alglen)) != 0)
538 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
539 	if (keyid > INT_MAX)
540 		fatal("%s: invalid key ID", __func__);
541 
542 	/*
543 	 * Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes),
544 	 * SHA384 (48 bytes) and SHA512 (64 bytes).
545 	 *
546 	 * Otherwise, verify the signature request is for a hostkey
547 	 * proof.
548 	 *
549 	 * XXX perform similar check for KEX signature requests too?
550 	 * it's not trivial, since what is signed is the hash, rather
551 	 * than the full kex structure...
552 	 */
553 	if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64) {
554 		/*
555 		 * Construct expected hostkey proof and compare it to what
556 		 * the client sent us.
557 		 */
558 		if (session_id2_len == 0) /* hostkeys is never first */
559 			fatal("%s: bad data length: %zu", __func__, datlen);
560 		if ((key = get_hostkey_public_by_index(keyid, ssh)) == NULL)
561 			fatal("%s: no hostkey for index %d", __func__, keyid);
562 		if ((sigbuf = sshbuf_new()) == NULL)
563 			fatal("%s: sshbuf_new", __func__);
564 		if ((r = sshbuf_put_cstring(sigbuf, proof_req)) != 0 ||
565 		    (r = sshbuf_put_string(sigbuf, session_id2,
566 		    session_id2_len)) != 0 ||
567 		    (r = sshkey_puts(key, sigbuf)) != 0)
568 			fatal("%s: couldn't prepare private key "
569 			    "proof buffer: %s", __func__, ssh_err(r));
570 		if (datlen != sshbuf_len(sigbuf) ||
571 		    memcmp(p, sshbuf_ptr(sigbuf), sshbuf_len(sigbuf)) != 0)
572 			fatal("%s: bad data length: %zu, hostkey proof len %zu",
573 			    __func__, datlen, sshbuf_len(sigbuf));
574 		sshbuf_free(sigbuf);
575 		is_proof = 1;
576 	}
577 
578 	/* save session id, it will be passed on the first call */
579 	if (session_id2_len == 0) {
580 		session_id2_len = datlen;
581 		session_id2 = xmalloc(session_id2_len);
582 		memcpy(session_id2, p, session_id2_len);
583 	}
584 
585 	if ((key = get_hostkey_by_index(keyid)) != NULL) {
586 		if ((r = sshkey_sign(key, &signature, &siglen, p, datlen, alg,
587 		    datafellows)) != 0)
588 			fatal("%s: sshkey_sign failed: %s",
589 			    __func__, ssh_err(r));
590 	} else if ((key = get_hostkey_public_by_index(keyid, ssh)) != NULL &&
591 	    auth_sock > 0) {
592 		if ((r = ssh_agent_sign(auth_sock, key, &signature, &siglen,
593 		    p, datlen, alg, datafellows)) != 0) {
594 			fatal("%s: ssh_agent_sign failed: %s",
595 			    __func__, ssh_err(r));
596 		}
597 	} else
598 		fatal("%s: no hostkey from index %d", __func__, keyid);
599 
600 	debug3("%s: %s signature %p(%zu)", __func__,
601 	    is_proof ? "KEX" : "hostkey proof", signature, siglen);
602 
603 	sshbuf_reset(m);
604 	if ((r = sshbuf_put_string(m, signature, siglen)) != 0)
605 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
606 
607 	free(alg);
608 	free(p);
609 	free(signature);
610 
611 	mm_request_send(sock, MONITOR_ANS_SIGN, m);
612 
613 	/* Turn on permissions for getpwnam */
614 	monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
615 
616 	return (0);
617 }
618 
619 /* Retrieves the password entry and also checks if the user is permitted */
620 
621 int
622 mm_answer_pwnamallow(int sock, Buffer *m)
623 {
624 	struct ssh *ssh = active_state;	/* XXX */
625 	char *username;
626 	struct passwd *pwent;
627 	int allowed = 0;
628 	u_int i;
629 
630 	debug3("%s", __func__);
631 
632 	if (authctxt->attempt++ != 0)
633 		fatal("%s: multiple attempts for getpwnam", __func__);
634 
635 	username = buffer_get_string(m, NULL);
636 
637 	pwent = getpwnamallow(username);
638 
639 	authctxt->user = xstrdup(username);
640 	setproctitle("%s [priv]", pwent ? username : "unknown");
641 	free(username);
642 
643 	buffer_clear(m);
644 
645 	if (pwent == NULL) {
646 		buffer_put_char(m, 0);
647 		authctxt->pw = fakepw();
648 		goto out;
649 	}
650 
651 	allowed = 1;
652 	authctxt->pw = pwent;
653 	authctxt->valid = 1;
654 
655 	buffer_put_char(m, 1);
656 	buffer_put_string(m, pwent, sizeof(struct passwd));
657 	buffer_put_cstring(m, pwent->pw_name);
658 	buffer_put_cstring(m, "*");
659 	buffer_put_cstring(m, pwent->pw_gecos);
660 	buffer_put_cstring(m, pwent->pw_class);
661 	buffer_put_cstring(m, pwent->pw_dir);
662 	buffer_put_cstring(m, pwent->pw_shell);
663 
664  out:
665 	ssh_packet_set_log_preamble(ssh, "%suser %s",
666 	    authctxt->valid ? "authenticating" : "invalid ", authctxt->user);
667 	buffer_put_string(m, &options, sizeof(options));
668 
669 #define M_CP_STROPT(x) do { \
670 		if (options.x != NULL) \
671 			buffer_put_cstring(m, options.x); \
672 	} while (0)
673 #define M_CP_STRARRAYOPT(x, nx) do { \
674 		for (i = 0; i < options.nx; i++) \
675 			buffer_put_cstring(m, options.x[i]); \
676 	} while (0)
677 	/* See comment in servconf.h */
678 	COPY_MATCH_STRING_OPTS();
679 #undef M_CP_STROPT
680 #undef M_CP_STRARRAYOPT
681 
682 	/* Create valid auth method lists */
683 	if (auth2_setup_methods_lists(authctxt) != 0) {
684 		/*
685 		 * The monitor will continue long enough to let the child
686 		 * run to it's packet_disconnect(), but it must not allow any
687 		 * authentication to succeed.
688 		 */
689 		debug("%s: no valid authentication method lists", __func__);
690 	}
691 
692 	debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed);
693 	mm_request_send(sock, MONITOR_ANS_PWNAM, m);
694 
695 	/* Allow service/style information on the auth context */
696 	monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
697 	monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
698 
699 	return (0);
700 }
701 
702 int mm_answer_auth2_read_banner(int sock, Buffer *m)
703 {
704 	char *banner;
705 
706 	buffer_clear(m);
707 	banner = auth2_read_banner();
708 	buffer_put_cstring(m, banner != NULL ? banner : "");
709 	mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
710 	free(banner);
711 
712 	return (0);
713 }
714 
715 int
716 mm_answer_authserv(int sock, Buffer *m)
717 {
718 	monitor_permit_authentications(1);
719 
720 	authctxt->service = buffer_get_string(m, NULL);
721 	authctxt->style = buffer_get_string(m, NULL);
722 	debug3("%s: service=%s, style=%s",
723 	    __func__, authctxt->service, authctxt->style);
724 
725 	if (strlen(authctxt->style) == 0) {
726 		free(authctxt->style);
727 		authctxt->style = NULL;
728 	}
729 
730 	return (0);
731 }
732 
733 int
734 mm_answer_authpassword(int sock, Buffer *m)
735 {
736 	static int call_count;
737 	char *passwd;
738 	int authenticated;
739 	u_int plen;
740 
741 	if (!options.password_authentication)
742 		fatal("%s: password authentication not enabled", __func__);
743 	passwd = buffer_get_string(m, &plen);
744 	/* Only authenticate if the context is valid */
745 	authenticated = options.password_authentication &&
746 	    auth_password(authctxt, passwd);
747 	explicit_bzero(passwd, strlen(passwd));
748 	free(passwd);
749 
750 	buffer_clear(m);
751 	buffer_put_int(m, authenticated);
752 
753 	debug3("%s: sending result %d", __func__, authenticated);
754 	mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
755 
756 	call_count++;
757 	if (plen == 0 && call_count == 1)
758 		auth_method = "none";
759 	else
760 		auth_method = "password";
761 
762 	/* Causes monitor loop to terminate if authenticated */
763 	return (authenticated);
764 }
765 
766 int
767 mm_answer_bsdauthquery(int sock, Buffer *m)
768 {
769 	char *name, *infotxt;
770 	u_int numprompts;
771 	u_int *echo_on;
772 	char **prompts;
773 	u_int success;
774 
775 	if (!options.kbd_interactive_authentication)
776 		fatal("%s: kbd-int authentication not enabled", __func__);
777 	success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
778 	    &prompts, &echo_on) < 0 ? 0 : 1;
779 
780 	buffer_clear(m);
781 	buffer_put_int(m, success);
782 	if (success)
783 		buffer_put_cstring(m, prompts[0]);
784 
785 	debug3("%s: sending challenge success: %u", __func__, success);
786 	mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
787 
788 	if (success) {
789 		free(name);
790 		free(infotxt);
791 		free(prompts);
792 		free(echo_on);
793 	}
794 
795 	return (0);
796 }
797 
798 int
799 mm_answer_bsdauthrespond(int sock, Buffer *m)
800 {
801 	char *response;
802 	int authok;
803 
804 	if (!options.kbd_interactive_authentication)
805 		fatal("%s: kbd-int authentication not enabled", __func__);
806 	if (authctxt->as == NULL)
807 		fatal("%s: no bsd auth session", __func__);
808 
809 	response = buffer_get_string(m, NULL);
810 	authok = options.challenge_response_authentication &&
811 	    auth_userresponse(authctxt->as, response, 0);
812 	authctxt->as = NULL;
813 	debug3("%s: <%s> = <%d>", __func__, response, authok);
814 	free(response);
815 
816 	buffer_clear(m);
817 	buffer_put_int(m, authok);
818 
819 	debug3("%s: sending authenticated: %d", __func__, authok);
820 	mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
821 
822 	auth_method = "keyboard-interactive";
823 	auth_submethod = "bsdauth";
824 
825 	return (authok != 0);
826 }
827 
828 int
829 mm_answer_keyallowed(int sock, Buffer *m)
830 {
831 	struct sshkey *key;
832 	char *cuser, *chost;
833 	u_char *blob;
834 	u_int bloblen, pubkey_auth_attempt;
835 	enum mm_keytype type = 0;
836 	int allowed = 0;
837 
838 	debug3("%s entering", __func__);
839 
840 	type = buffer_get_int(m);
841 	cuser = buffer_get_string(m, NULL);
842 	chost = buffer_get_string(m, NULL);
843 	blob = buffer_get_string(m, &bloblen);
844 	pubkey_auth_attempt = buffer_get_int(m);
845 
846 	key = key_from_blob(blob, bloblen);
847 
848 	debug3("%s: key_from_blob: %p", __func__, key);
849 
850 	if (key != NULL && authctxt->valid) {
851 		/* These should not make it past the privsep child */
852 		if (key_type_plain(key->type) == KEY_RSA &&
853 		    (datafellows & SSH_BUG_RSASIGMD5) != 0)
854 			fatal("%s: passed a SSH_BUG_RSASIGMD5 key", __func__);
855 
856 		switch (type) {
857 		case MM_USERKEY:
858 			allowed = options.pubkey_authentication &&
859 			    !auth2_userkey_already_used(authctxt, key) &&
860 			    match_pattern_list(sshkey_ssh_name(key),
861 			    options.pubkey_key_types, 0) == 1 &&
862 			    user_key_allowed(authctxt->pw, key,
863 			    pubkey_auth_attempt);
864 			pubkey_auth_info(authctxt, key, NULL);
865 			auth_method = "publickey";
866 			if (options.pubkey_authentication &&
867 			    (!pubkey_auth_attempt || allowed != 1))
868 				auth_clear_options();
869 			break;
870 		case MM_HOSTKEY:
871 			allowed = options.hostbased_authentication &&
872 			    match_pattern_list(sshkey_ssh_name(key),
873 			    options.hostbased_key_types, 0) == 1 &&
874 			    hostbased_key_allowed(authctxt->pw,
875 			    cuser, chost, key);
876 			pubkey_auth_info(authctxt, key,
877 			    "client user \"%.100s\", client host \"%.100s\"",
878 			    cuser, chost);
879 			auth_method = "hostbased";
880 			break;
881 		default:
882 			fatal("%s: unknown key type %d", __func__, type);
883 			break;
884 		}
885 	}
886 
887 	debug3("%s: key %p is %s",
888 	    __func__, key, allowed ? "allowed" : "not allowed");
889 
890 	if (key != NULL)
891 		key_free(key);
892 
893 	/* clear temporarily storage (used by verify) */
894 	monitor_reset_key_state();
895 
896 	if (allowed) {
897 		/* Save temporarily for comparison in verify */
898 		key_blob = blob;
899 		key_bloblen = bloblen;
900 		key_blobtype = type;
901 		hostbased_cuser = cuser;
902 		hostbased_chost = chost;
903 	} else {
904 		/* Log failed attempt */
905 		auth_log(authctxt, 0, 0, auth_method, NULL);
906 		free(blob);
907 		free(cuser);
908 		free(chost);
909 	}
910 
911 	buffer_clear(m);
912 	buffer_put_int(m, allowed);
913 	buffer_put_int(m, forced_command != NULL);
914 
915 	mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
916 
917 	return (0);
918 }
919 
920 static int
921 monitor_valid_userblob(u_char *data, u_int datalen)
922 {
923 	Buffer b;
924 	u_char *p;
925 	char *userstyle, *cp;
926 	u_int len;
927 	int fail = 0;
928 
929 	buffer_init(&b);
930 	buffer_append(&b, data, datalen);
931 
932 	if (datafellows & SSH_OLD_SESSIONID) {
933 		p = buffer_ptr(&b);
934 		len = buffer_len(&b);
935 		if ((session_id2 == NULL) ||
936 		    (len < session_id2_len) ||
937 		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
938 			fail++;
939 		buffer_consume(&b, session_id2_len);
940 	} else {
941 		p = buffer_get_string(&b, &len);
942 		if ((session_id2 == NULL) ||
943 		    (len != session_id2_len) ||
944 		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
945 			fail++;
946 		free(p);
947 	}
948 	if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
949 		fail++;
950 	cp = buffer_get_cstring(&b, NULL);
951 	xasprintf(&userstyle, "%s%s%s", authctxt->user,
952 	    authctxt->style ? ":" : "",
953 	    authctxt->style ? authctxt->style : "");
954 	if (strcmp(userstyle, cp) != 0) {
955 		logit("wrong user name passed to monitor: "
956 		    "expected %s != %.100s", userstyle, cp);
957 		fail++;
958 	}
959 	free(userstyle);
960 	free(cp);
961 	buffer_skip_string(&b);
962 	if (datafellows & SSH_BUG_PKAUTH) {
963 		if (!buffer_get_char(&b))
964 			fail++;
965 	} else {
966 		cp = buffer_get_cstring(&b, NULL);
967 		if (strcmp("publickey", cp) != 0)
968 			fail++;
969 		free(cp);
970 		if (!buffer_get_char(&b))
971 			fail++;
972 		buffer_skip_string(&b);
973 	}
974 	buffer_skip_string(&b);
975 	if (buffer_len(&b) != 0)
976 		fail++;
977 	buffer_free(&b);
978 	return (fail == 0);
979 }
980 
981 static int
982 monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
983     char *chost)
984 {
985 	Buffer b;
986 	char *p, *userstyle;
987 	u_int len;
988 	int fail = 0;
989 
990 	buffer_init(&b);
991 	buffer_append(&b, data, datalen);
992 
993 	p = buffer_get_string(&b, &len);
994 	if ((session_id2 == NULL) ||
995 	    (len != session_id2_len) ||
996 	    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
997 		fail++;
998 	free(p);
999 
1000 	if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
1001 		fail++;
1002 	p = buffer_get_cstring(&b, NULL);
1003 	xasprintf(&userstyle, "%s%s%s", authctxt->user,
1004 	    authctxt->style ? ":" : "",
1005 	    authctxt->style ? authctxt->style : "");
1006 	if (strcmp(userstyle, p) != 0) {
1007 		logit("wrong user name passed to monitor: expected %s != %.100s",
1008 		    userstyle, p);
1009 		fail++;
1010 	}
1011 	free(userstyle);
1012 	free(p);
1013 	buffer_skip_string(&b);	/* service */
1014 	p = buffer_get_cstring(&b, NULL);
1015 	if (strcmp(p, "hostbased") != 0)
1016 		fail++;
1017 	free(p);
1018 	buffer_skip_string(&b);	/* pkalg */
1019 	buffer_skip_string(&b);	/* pkblob */
1020 
1021 	/* verify client host, strip trailing dot if necessary */
1022 	p = buffer_get_string(&b, NULL);
1023 	if (((len = strlen(p)) > 0) && p[len - 1] == '.')
1024 		p[len - 1] = '\0';
1025 	if (strcmp(p, chost) != 0)
1026 		fail++;
1027 	free(p);
1028 
1029 	/* verify client user */
1030 	p = buffer_get_string(&b, NULL);
1031 	if (strcmp(p, cuser) != 0)
1032 		fail++;
1033 	free(p);
1034 
1035 	if (buffer_len(&b) != 0)
1036 		fail++;
1037 	buffer_free(&b);
1038 	return (fail == 0);
1039 }
1040 
1041 int
1042 mm_answer_keyverify(int sock, Buffer *m)
1043 {
1044 	struct sshkey *key;
1045 	u_char *signature, *data, *blob;
1046 	u_int signaturelen, datalen, bloblen;
1047 	int verified = 0;
1048 	int valid_data = 0;
1049 
1050 	blob = buffer_get_string(m, &bloblen);
1051 	signature = buffer_get_string(m, &signaturelen);
1052 	data = buffer_get_string(m, &datalen);
1053 
1054 	if (hostbased_cuser == NULL || hostbased_chost == NULL ||
1055 	  !monitor_allowed_key(blob, bloblen))
1056 		fatal("%s: bad key, not previously allowed", __func__);
1057 
1058 	key = key_from_blob(blob, bloblen);
1059 	if (key == NULL)
1060 		fatal("%s: bad public key blob", __func__);
1061 
1062 	switch (key_blobtype) {
1063 	case MM_USERKEY:
1064 		valid_data = monitor_valid_userblob(data, datalen);
1065 		break;
1066 	case MM_HOSTKEY:
1067 		valid_data = monitor_valid_hostbasedblob(data, datalen,
1068 		    hostbased_cuser, hostbased_chost);
1069 		break;
1070 	default:
1071 		valid_data = 0;
1072 		break;
1073 	}
1074 	if (!valid_data)
1075 		fatal("%s: bad signature data blob", __func__);
1076 
1077 	verified = key_verify(key, signature, signaturelen, data, datalen);
1078 	debug3("%s: key %p signature %s",
1079 	    __func__, key, (verified == 1) ? "verified" : "unverified");
1080 
1081 	/* If auth was successful then record key to ensure it isn't reused */
1082 	if (verified == 1 && key_blobtype == MM_USERKEY)
1083 		auth2_record_userkey(authctxt, key);
1084 	else
1085 		key_free(key);
1086 
1087 	free(blob);
1088 	free(signature);
1089 	free(data);
1090 
1091 	auth_method = key_blobtype == MM_USERKEY ? "publickey" : "hostbased";
1092 
1093 	monitor_reset_key_state();
1094 
1095 	buffer_clear(m);
1096 	buffer_put_int(m, verified);
1097 	mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
1098 
1099 	return (verified == 1);
1100 }
1101 
1102 static void
1103 mm_record_login(Session *s, struct passwd *pw)
1104 {
1105 	struct ssh *ssh = active_state;	/* XXX */
1106 	socklen_t fromlen;
1107 	struct sockaddr_storage from;
1108 
1109 	/*
1110 	 * Get IP address of client. If the connection is not a socket, let
1111 	 * the address be 0.0.0.0.
1112 	 */
1113 	memset(&from, 0, sizeof(from));
1114 	fromlen = sizeof(from);
1115 	if (packet_connection_is_on_socket()) {
1116 		if (getpeername(packet_get_connection_in(),
1117 		    (struct sockaddr *)&from, &fromlen) < 0) {
1118 			debug("getpeername: %.100s", strerror(errno));
1119 			cleanup_exit(255);
1120 		}
1121 	}
1122 	/* Record that there was a login on that tty from the remote host. */
1123 	record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
1124 	    session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
1125 	    (struct sockaddr *)&from, fromlen);
1126 }
1127 
1128 static void
1129 mm_session_close(Session *s)
1130 {
1131 	debug3("%s: session %d pid %ld", __func__, s->self, (long)s->pid);
1132 	if (s->ttyfd != -1) {
1133 		debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ptyfd);
1134 		session_pty_cleanup2(s);
1135 	}
1136 	session_unused(s->self);
1137 }
1138 
1139 int
1140 mm_answer_pty(int sock, Buffer *m)
1141 {
1142 	extern struct monitor *pmonitor;
1143 	Session *s;
1144 	int res, fd0;
1145 
1146 	debug3("%s entering", __func__);
1147 
1148 	buffer_clear(m);
1149 	s = session_new();
1150 	if (s == NULL)
1151 		goto error;
1152 	s->authctxt = authctxt;
1153 	s->pw = authctxt->pw;
1154 	s->pid = pmonitor->m_pid;
1155 	res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1156 	if (res == 0)
1157 		goto error;
1158 	pty_setowner(authctxt->pw, s->tty);
1159 
1160 	buffer_put_int(m, 1);
1161 	buffer_put_cstring(m, s->tty);
1162 
1163 	/* We need to trick ttyslot */
1164 	if (dup2(s->ttyfd, 0) == -1)
1165 		fatal("%s: dup2", __func__);
1166 
1167 	mm_record_login(s, authctxt->pw);
1168 
1169 	/* Now we can close the file descriptor again */
1170 	close(0);
1171 
1172 	/* send messages generated by record_login */
1173 	buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
1174 	buffer_clear(&loginmsg);
1175 
1176 	mm_request_send(sock, MONITOR_ANS_PTY, m);
1177 
1178 	if (mm_send_fd(sock, s->ptyfd) == -1 ||
1179 	    mm_send_fd(sock, s->ttyfd) == -1)
1180 		fatal("%s: send fds failed", __func__);
1181 
1182 	/* make sure nothing uses fd 0 */
1183 	if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0)
1184 		fatal("%s: open(/dev/null): %s", __func__, strerror(errno));
1185 	if (fd0 != 0)
1186 		error("%s: fd0 %d != 0", __func__, fd0);
1187 
1188 	/* slave is not needed */
1189 	close(s->ttyfd);
1190 	s->ttyfd = s->ptyfd;
1191 	/* no need to dup() because nobody closes ptyfd */
1192 	s->ptymaster = s->ptyfd;
1193 
1194 	debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd);
1195 
1196 	return (0);
1197 
1198  error:
1199 	if (s != NULL)
1200 		mm_session_close(s);
1201 	buffer_put_int(m, 0);
1202 	mm_request_send(sock, MONITOR_ANS_PTY, m);
1203 	return (0);
1204 }
1205 
1206 int
1207 mm_answer_pty_cleanup(int sock, Buffer *m)
1208 {
1209 	Session *s;
1210 	char *tty;
1211 
1212 	debug3("%s entering", __func__);
1213 
1214 	tty = buffer_get_string(m, NULL);
1215 	if ((s = session_by_tty(tty)) != NULL)
1216 		mm_session_close(s);
1217 	buffer_clear(m);
1218 	free(tty);
1219 	return (0);
1220 }
1221 
1222 int
1223 mm_answer_term(int sock, Buffer *req)
1224 {
1225 	extern struct monitor *pmonitor;
1226 	int res, status;
1227 
1228 	debug3("%s: tearing down sessions", __func__);
1229 
1230 	/* The child is terminating */
1231 	session_destroy_all(&mm_session_close);
1232 
1233 	while (waitpid(pmonitor->m_pid, &status, 0) == -1)
1234 		if (errno != EINTR)
1235 			exit(1);
1236 
1237 	res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1238 
1239 	/* Terminate process */
1240 	exit(res);
1241 }
1242 
1243 void
1244 monitor_apply_keystate(struct monitor *pmonitor)
1245 {
1246 	struct ssh *ssh = active_state;	/* XXX */
1247 	struct kex *kex;
1248 	int r;
1249 
1250 	debug3("%s: packet_set_state", __func__);
1251 	if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
1252                 fatal("%s: packet_set_state: %s", __func__, ssh_err(r));
1253 	sshbuf_free(child_state);
1254 	child_state = NULL;
1255 
1256 	if ((kex = ssh->kex) != NULL) {
1257 		/* XXX set callbacks */
1258 #ifdef WITH_OPENSSL
1259 		kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1260 		kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1261 		kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
1262 		kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
1263 		kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
1264 		kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1265 		kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1266 		kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1267 #endif
1268 		kex->kex[KEX_C25519_SHA256] = kexc25519_server;
1269 		kex->load_host_public_key=&get_hostkey_public_by_type;
1270 		kex->load_host_private_key=&get_hostkey_private_by_type;
1271 		kex->host_key_index=&get_hostkey_index;
1272 		kex->sign = sshd_hostkey_sign;
1273 	}
1274 }
1275 
1276 /* This function requries careful sanity checking */
1277 
1278 void
1279 mm_get_keystate(struct monitor *pmonitor)
1280 {
1281 	debug3("%s: Waiting for new keys", __func__);
1282 
1283 	if ((child_state = sshbuf_new()) == NULL)
1284 		fatal("%s: sshbuf_new failed", __func__);
1285 	mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT,
1286 	    child_state);
1287 	debug3("%s: GOT new keys", __func__);
1288 }
1289 
1290 
1291 /* XXX */
1292 
1293 #define FD_CLOSEONEXEC(x) do { \
1294 	if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \
1295 		fatal("fcntl(%d, F_SETFD)", x); \
1296 } while (0)
1297 
1298 static void
1299 monitor_openfds(struct monitor *mon, int do_logfds)
1300 {
1301 	int pair[2];
1302 
1303 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
1304 		fatal("%s: socketpair: %s", __func__, strerror(errno));
1305 	FD_CLOSEONEXEC(pair[0]);
1306 	FD_CLOSEONEXEC(pair[1]);
1307 	mon->m_recvfd = pair[0];
1308 	mon->m_sendfd = pair[1];
1309 
1310 	if (do_logfds) {
1311 		if (pipe(pair) == -1)
1312 			fatal("%s: pipe: %s", __func__, strerror(errno));
1313 		FD_CLOSEONEXEC(pair[0]);
1314 		FD_CLOSEONEXEC(pair[1]);
1315 		mon->m_log_recvfd = pair[0];
1316 		mon->m_log_sendfd = pair[1];
1317 	} else
1318 		mon->m_log_recvfd = mon->m_log_sendfd = -1;
1319 }
1320 
1321 #define MM_MEMSIZE	65536
1322 
1323 struct monitor *
1324 monitor_init(void)
1325 {
1326 	struct monitor *mon;
1327 
1328 	mon = xcalloc(1, sizeof(*mon));
1329 	monitor_openfds(mon, 1);
1330 
1331 	return mon;
1332 }
1333 
1334 void
1335 monitor_reinit(struct monitor *mon)
1336 {
1337 	monitor_openfds(mon, 0);
1338 }
1339 
1340 #ifdef GSSAPI
1341 int
1342 mm_answer_gss_setup_ctx(int sock, Buffer *m)
1343 {
1344 	gss_OID_desc goid;
1345 	OM_uint32 major;
1346 	u_int len;
1347 
1348 	if (!options.gss_authentication)
1349 		fatal("%s: GSSAPI authentication not enabled", __func__);
1350 
1351 	goid.elements = buffer_get_string(m, &len);
1352 	goid.length = len;
1353 
1354 	major = ssh_gssapi_server_ctx(&gsscontext, &goid);
1355 
1356 	free(goid.elements);
1357 
1358 	buffer_clear(m);
1359 	buffer_put_int(m, major);
1360 
1361 	mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
1362 
1363 	/* Now we have a context, enable the step */
1364 	monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
1365 
1366 	return (0);
1367 }
1368 
1369 int
1370 mm_answer_gss_accept_ctx(int sock, Buffer *m)
1371 {
1372 	gss_buffer_desc in;
1373 	gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
1374 	OM_uint32 major, minor;
1375 	OM_uint32 flags = 0; /* GSI needs this */
1376 	u_int len;
1377 
1378 	if (!options.gss_authentication)
1379 		fatal("%s: GSSAPI authentication not enabled", __func__);
1380 
1381 	in.value = buffer_get_string(m, &len);
1382 	in.length = len;
1383 	major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
1384 	free(in.value);
1385 
1386 	buffer_clear(m);
1387 	buffer_put_int(m, major);
1388 	buffer_put_string(m, out.value, out.length);
1389 	buffer_put_int(m, flags);
1390 	mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
1391 
1392 	gss_release_buffer(&minor, &out);
1393 
1394 	if (major == GSS_S_COMPLETE) {
1395 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
1396 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1397 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
1398 	}
1399 	return (0);
1400 }
1401 
1402 int
1403 mm_answer_gss_checkmic(int sock, Buffer *m)
1404 {
1405 	gss_buffer_desc gssbuf, mic;
1406 	OM_uint32 ret;
1407 	u_int len;
1408 
1409 	if (!options.gss_authentication)
1410 		fatal("%s: GSSAPI authentication not enabled", __func__);
1411 
1412 	gssbuf.value = buffer_get_string(m, &len);
1413 	gssbuf.length = len;
1414 	mic.value = buffer_get_string(m, &len);
1415 	mic.length = len;
1416 
1417 	ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
1418 
1419 	free(gssbuf.value);
1420 	free(mic.value);
1421 
1422 	buffer_clear(m);
1423 	buffer_put_int(m, ret);
1424 
1425 	mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
1426 
1427 	if (!GSS_ERROR(ret))
1428 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1429 
1430 	return (0);
1431 }
1432 
1433 int
1434 mm_answer_gss_userok(int sock, Buffer *m)
1435 {
1436 	int authenticated;
1437 
1438 	if (!options.gss_authentication)
1439 		fatal("%s: GSSAPI authentication not enabled", __func__);
1440 
1441 	authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
1442 
1443 	buffer_clear(m);
1444 	buffer_put_int(m, authenticated);
1445 
1446 	debug3("%s: sending result %d", __func__, authenticated);
1447 	mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
1448 
1449 	auth_method = "gssapi-with-mic";
1450 
1451 	/* Monitor loop will terminate if authenticated */
1452 	return (authenticated);
1453 }
1454 #endif /* GSSAPI */
1455 
1456