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