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