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