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