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