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