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