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