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