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