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