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