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