monitor.c 58 KB
Newer Older
1
/* $OpenBSD: monitor.c,v 1.128 2013/11/04 11:51:16 markus Exp $ */
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*
 * Copyright 2002 Niels Provos <provos@citi.umich.edu>
 * Copyright 2002 Markus Friedl <markus@openbsd.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "includes.h"
29 30

#include <sys/types.h>
31
#include <sys/param.h>
32
#include <sys/socket.h>
33
#include "openbsd-compat/sys-tree.h"
34
#include <sys/wait.h>
35

36
#include <errno.h>
37
#include <fcntl.h>
38
#ifdef HAVE_PATHS_H
39
#include <paths.h>
40
#endif
41
#include <pwd.h>
42
#include <signal.h>
43
#include <stdarg.h>
44
#include <stdlib.h>
45
#include <string.h>
46
#include <unistd.h>
47 48 49 50 51 52 53
#ifdef HAVE_POLL_H
#include <poll.h>
#else
# ifdef HAVE_SYS_POLL_H
#  include <sys/poll.h>
# endif
#endif
54 55 56 57 58

#ifdef SKEY
#include <skey.h>
#endif

59 60
#include <openssl/dh.h>

61
#include "openbsd-compat/sys-queue.h"
62
#include "atomicio.h"
63
#include "xmalloc.h"
64
#include "ssh.h"
65 66 67
#include "key.h"
#include "buffer.h"
#include "hostfile.h"
68
#include "auth.h"
69
#include "cipher.h"
70 71
#include "kex.h"
#include "dh.h"
72 73
#ifdef TARGET_OS_MAC	/* XXX Broken krb5 headers on Mac */
#undef TARGET_OS_MAC
74
#include "zlib.h"
75 76 77 78
#define TARGET_OS_MAC 1
#else
#include "zlib.h"
#endif
79 80 81 82 83 84 85 86 87 88 89
#include "packet.h"
#include "auth-options.h"
#include "sshpty.h"
#include "channels.h"
#include "session.h"
#include "sshlogin.h"
#include "canohost.h"
#include "log.h"
#include "servconf.h"
#include "monitor.h"
#include "monitor_mm.h"
90 91 92
#ifdef GSSAPI
#include "ssh-gss.h"
#endif
93 94 95 96 97
#include "monitor_wrap.h"
#include "monitor_fdpass.h"
#include "misc.h"
#include "compat.h"
#include "ssh2.h"
98
#include "jpake.h"
99
#include "roaming.h"
100
#include "authfd.h"
101

102 103 104 105
#ifdef GSSAPI
static Gssctxt *gsscontext = NULL;
#endif

106 107 108 109 110 111 112 113 114
/* Imports */
extern ServerOptions options;
extern u_int utmp_len;
extern Newkeys *current_keys[];
extern z_stream incoming_stream;
extern z_stream outgoing_stream;
extern u_char session_id[];
extern Buffer auth_debug;
extern int auth_debug_init;
115
extern Buffer loginmsg;
116 117 118 119 120 121 122 123 124 125 126 127 128 129

/* State exported from the child */

struct {
	z_stream incoming;
	z_stream outgoing;
	u_char *keyin;
	u_int keyinlen;
	u_char *keyout;
	u_int keyoutlen;
	u_char *ivin;
	u_int ivinlen;
	u_char *ivout;
	u_int ivoutlen;
130 131
	u_char *ssh1key;
	u_int ssh1keylen;
132 133 134 135 136 137
	int ssh1cipher;
	int ssh1protoflags;
	u_char *input;
	u_int ilen;
	u_char *output;
	u_int olen;
138 139
	u_int64_t sent_bytes;
	u_int64_t recv_bytes;
140 141
} child_state;

142
/* Functions on the monitor that answer unprivileged requests */
143 144 145 146

int mm_answer_moduli(int, Buffer *);
int mm_answer_sign(int, Buffer *);
int mm_answer_pwnamallow(int, Buffer *);
147
int mm_answer_auth2_read_banner(int, Buffer *);
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
int mm_answer_authserv(int, Buffer *);
int mm_answer_authpassword(int, Buffer *);
int mm_answer_bsdauthquery(int, Buffer *);
int mm_answer_bsdauthrespond(int, Buffer *);
int mm_answer_skeyquery(int, Buffer *);
int mm_answer_skeyrespond(int, Buffer *);
int mm_answer_keyallowed(int, Buffer *);
int mm_answer_keyverify(int, Buffer *);
int mm_answer_pty(int, Buffer *);
int mm_answer_pty_cleanup(int, Buffer *);
int mm_answer_term(int, Buffer *);
int mm_answer_rsa_keyallowed(int, Buffer *);
int mm_answer_rsa_challenge(int, Buffer *);
int mm_answer_rsa_response(int, Buffer *);
int mm_answer_sesskey(int, Buffer *);
int mm_answer_sessid(int, Buffer *);
164 165 166 167 168
int mm_answer_jpake_get_pwdata(int, Buffer *);
int mm_answer_jpake_step1(int, Buffer *);
int mm_answer_jpake_step2(int, Buffer *);
int mm_answer_jpake_key_confirm(int, Buffer *);
int mm_answer_jpake_check_confirm(int, Buffer *);
169

170 171
#ifdef USE_PAM
int mm_answer_pam_start(int, Buffer *);
172
int mm_answer_pam_account(int, Buffer *);
173 174 175 176
int mm_answer_pam_init_ctx(int, Buffer *);
int mm_answer_pam_query(int, Buffer *);
int mm_answer_pam_respond(int, Buffer *);
int mm_answer_pam_free_ctx(int, Buffer *);
177 178
#endif

179 180 181 182
#ifdef GSSAPI
int mm_answer_gss_setup_ctx(int, Buffer *);
int mm_answer_gss_accept_ctx(int, Buffer *);
int mm_answer_gss_userok(int, Buffer *);
183
int mm_answer_gss_checkmic(int, Buffer *);
184
#endif
185

186
#ifdef SSH_AUDIT_EVENTS
187 188 189 190
int mm_answer_audit_event(int, Buffer *);
int mm_answer_audit_command(int, Buffer *);
#endif

191 192
static int monitor_read_log(struct monitor *);

193 194 195 196 197 198 199
static Authctxt *authctxt;
static BIGNUM *ssh1_challenge = NULL;	/* used for ssh1 rsa auth */

/* local state for key verify */
static u_char *key_blob = NULL;
static u_int key_bloblen = 0;
static int key_blobtype = MM_NOKEY;
200 201
static char *hostbased_cuser = NULL;
static char *hostbased_chost = NULL;
202
static char *auth_method = "unknown";
203
static char *auth_submethod = NULL;
204
static u_int session_id2_len = 0;
205
static u_char *session_id2 = NULL;
206
static pid_t monitor_child_pid;
207 208 209 210 211 212 213 214 215 216

struct mon_table {
	enum monitor_reqtype type;
	int flags;
	int (*f)(int, Buffer *);
};

#define MON_ISAUTH	0x0004	/* Required for Authentication */
#define MON_AUTHDECIDE	0x0008	/* Decides Authentication */
#define MON_ONCE	0x0010	/* Disable after calling */
217
#define MON_ALOG	0x0020	/* Log auth attempt without authenticating */
218 219 220 221 222 223 224 225 226 227

#define MON_AUTH	(MON_ISAUTH|MON_AUTHDECIDE)

#define MON_PERMIT	0x1000	/* Request is permitted */

struct mon_table mon_dispatch_proto20[] = {
    {MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli},
    {MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign},
    {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
    {MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv},
228
    {MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner},
229
    {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
230 231
#ifdef USE_PAM
    {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
232
    {MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account},
233 234 235 236
    {MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx},
    {MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query},
    {MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond},
    {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
237
#endif
238
#ifdef SSH_AUDIT_EVENTS
239
    {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
240
#endif
241 242
#ifdef BSD_AUTH
    {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
243
    {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
244 245 246 247 248 249 250
#endif
#ifdef SKEY
    {MONITOR_REQ_SKEYQUERY, MON_ISAUTH, mm_answer_skeyquery},
    {MONITOR_REQ_SKEYRESPOND, MON_AUTH, mm_answer_skeyrespond},
#endif
    {MONITOR_REQ_KEYALLOWED, MON_ISAUTH, mm_answer_keyallowed},
    {MONITOR_REQ_KEYVERIFY, MON_AUTH, mm_answer_keyverify},
251 252 253 254
#ifdef GSSAPI
    {MONITOR_REQ_GSSSETUP, MON_ISAUTH, mm_answer_gss_setup_ctx},
    {MONITOR_REQ_GSSSTEP, MON_ISAUTH, mm_answer_gss_accept_ctx},
    {MONITOR_REQ_GSSUSEROK, MON_AUTH, mm_answer_gss_userok},
255
    {MONITOR_REQ_GSSCHECKMIC, MON_ISAUTH, mm_answer_gss_checkmic},
256 257 258 259 260 261 262
#endif
#ifdef JPAKE
    {MONITOR_REQ_JPAKE_GET_PWDATA, MON_ONCE, mm_answer_jpake_get_pwdata},
    {MONITOR_REQ_JPAKE_STEP1, MON_ISAUTH, mm_answer_jpake_step1},
    {MONITOR_REQ_JPAKE_STEP2, MON_ONCE, mm_answer_jpake_step2},
    {MONITOR_REQ_JPAKE_KEY_CONFIRM, MON_ONCE, mm_answer_jpake_key_confirm},
    {MONITOR_REQ_JPAKE_CHECK_CONFIRM, MON_AUTH, mm_answer_jpake_check_confirm},
263
#endif
264 265 266 267 268 269 270 271 272
    {0, 0, NULL}
};

struct mon_table mon_dispatch_postauth20[] = {
    {MONITOR_REQ_MODULI, 0, mm_answer_moduli},
    {MONITOR_REQ_SIGN, 0, mm_answer_sign},
    {MONITOR_REQ_PTY, 0, mm_answer_pty},
    {MONITOR_REQ_PTYCLEANUP, 0, mm_answer_pty_cleanup},
    {MONITOR_REQ_TERM, 0, mm_answer_term},
273
#ifdef SSH_AUDIT_EVENTS
274 275 276
    {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
    {MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT, mm_answer_audit_command},
#endif
277 278 279 280 281 282 283 284
    {0, 0, NULL}
};

struct mon_table mon_dispatch_proto15[] = {
    {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
    {MONITOR_REQ_SESSKEY, MON_ONCE, mm_answer_sesskey},
    {MONITOR_REQ_SESSID, MON_ONCE, mm_answer_sessid},
    {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
285 286
    {MONITOR_REQ_RSAKEYALLOWED, MON_ISAUTH|MON_ALOG, mm_answer_rsa_keyallowed},
    {MONITOR_REQ_KEYALLOWED, MON_ISAUTH|MON_ALOG, mm_answer_keyallowed},
287 288 289 290
    {MONITOR_REQ_RSACHALLENGE, MON_ONCE, mm_answer_rsa_challenge},
    {MONITOR_REQ_RSARESPONSE, MON_ONCE|MON_AUTHDECIDE, mm_answer_rsa_response},
#ifdef BSD_AUTH
    {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
291
    {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
292 293 294 295
#endif
#ifdef SKEY
    {MONITOR_REQ_SKEYQUERY, MON_ISAUTH, mm_answer_skeyquery},
    {MONITOR_REQ_SKEYRESPOND, MON_AUTH, mm_answer_skeyrespond},
296 297 298
#endif
#ifdef USE_PAM
    {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
299
    {MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account},
300 301 302 303
    {MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx},
    {MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query},
    {MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond},
    {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
304
#endif
305
#ifdef SSH_AUDIT_EVENTS
306
    {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
307 308 309 310 311 312 313 314
#endif
    {0, 0, NULL}
};

struct mon_table mon_dispatch_postauth15[] = {
    {MONITOR_REQ_PTY, MON_ONCE, mm_answer_pty},
    {MONITOR_REQ_PTYCLEANUP, MON_ONCE, mm_answer_pty_cleanup},
    {MONITOR_REQ_TERM, 0, mm_answer_term},
315
#ifdef SSH_AUDIT_EVENTS
316
    {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
317
    {MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT|MON_ONCE, mm_answer_audit_command},
318
#endif
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    {0, 0, NULL}
};

struct mon_table *mon_dispatch;

/* Specifies if a certain message is allowed at the moment */

static void
monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit)
{
	while (ent->f != NULL) {
		if (ent->type == type) {
			ent->flags &= ~MON_PERMIT;
			ent->flags |= permit ? MON_PERMIT : 0;
			return;
		}
		ent++;
	}
}

static void
monitor_permit_authentications(int permit)
{
	struct mon_table *ent = mon_dispatch;

	while (ent->f != NULL) {
		if (ent->flags & MON_AUTH) {
			ent->flags &= ~MON_PERMIT;
			ent->flags |= permit ? MON_PERMIT : 0;
		}
		ent++;
	}
}

353 354
void
monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor)
355 356
{
	struct mon_table *ent;
357
	int authenticated = 0, partial = 0;
358 359 360

	debug3("preauth child monitor started");

361 362 363 364
	close(pmonitor->m_recvfd);
	close(pmonitor->m_log_sendfd);
	pmonitor->m_log_sendfd = pmonitor->m_recvfd = -1;

365 366 367
	authctxt = _authctxt;
	memset(authctxt, 0, sizeof(*authctxt));

368 369
	authctxt->loginmsg = &loginmsg;

370 371 372 373 374 375 376 377 378 379 380 381 382 383
	if (compat20) {
		mon_dispatch = mon_dispatch_proto20;

		/* Permit requests for moduli and signatures */
		monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
		monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
	} else {
		mon_dispatch = mon_dispatch_proto15;

		monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 1);
	}

	/* The first few requests do not require asynchronous access */
	while (!authenticated) {
384
		partial = 0;
385
		auth_method = "unknown";
386
		auth_submethod = NULL;
387
		authenticated = (monitor_read(pmonitor, mon_dispatch, &ent) == 1);
388 389 390 391 392 393 394 395

		/* Special handling for multiple required authentications */
		if (options.num_auth_methods != 0) {
			if (!compat20)
				fatal("AuthenticationMethods is not supported"
				    "with SSH protocol 1");
			if (authenticated &&
			    !auth2_update_methods_lists(authctxt,
396
			    auth_method, auth_submethod)) {
397 398 399
				debug3("%s: method %s: partial", __func__,
				    auth_method);
				authenticated = 0;
400
				partial = 1;
401 402 403
			}
		}

404 405 406
		if (authenticated) {
			if (!(ent->flags & MON_AUTHDECIDE))
				fatal("%s: unexpected authentication from %d",
407
				    __func__, ent->type);
408 409 410
			if (authctxt->pw->pw_uid == 0 &&
			    !auth_root_allowed(auth_method))
				authenticated = 0;
411 412
#ifdef USE_PAM
			/* PAM needs to perform account checks after auth */
413
			if (options.use_pam && authenticated) {
414 415 416
				Buffer m;

				buffer_init(&m);
417
				mm_request_receive_expect(pmonitor->m_sendfd,
418 419 420 421 422
				    MONITOR_REQ_PAM_ACCOUNT, &m);
				authenticated = mm_answer_pam_account(pmonitor->m_sendfd, &m);
				buffer_free(&m);
			}
#endif
423
		}
424
		if (ent->flags & (MON_AUTHDECIDE|MON_ALOG)) {
425
			auth_log(authctxt, authenticated, partial,
426
			    auth_method, auth_submethod);
427 428 429
			if (!authenticated)
				authctxt->failures++;
		}
430 431 432 433 434 435 436 437 438
#ifdef JPAKE
		/* Cleanup JPAKE context after authentication */
		if (ent->flags & MON_AUTHDECIDE) {
			if (authctxt->jpake_ctx != NULL) {
				jpake_free(authctxt->jpake_ctx);
				authctxt->jpake_ctx = NULL;
			}
		}
#endif
439 440 441
	}

	if (!authctxt->valid)
442
		fatal("%s: authenticated invalid user", __func__);
443 444
	if (strcmp(auth_method, "unknown") == 0)
		fatal("%s: authentication method name unknown", __func__);
445 446

	debug("%s: %s has been authenticated by privileged process",
447
	    __func__, authctxt->user);
448

449
	mm_get_keystate(pmonitor);
450

451 452 453 454
	/* Drain any buffered messages from the child */
	while (pmonitor->m_log_recvfd != -1 && monitor_read_log(pmonitor) == 0)
		;

455 456 457
	close(pmonitor->m_sendfd);
	close(pmonitor->m_log_recvfd);
	pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1;
458 459
}

460 461 462 463 464 465 466
static void
monitor_set_child_handler(pid_t pid)
{
	monitor_child_pid = pid;
}

static void
467
monitor_child_handler(int sig)
468
{
469
	kill(monitor_child_pid, sig);
470 471
}

472
void
473
monitor_child_postauth(struct monitor *pmonitor)
474
{
475 476 477
	close(pmonitor->m_recvfd);
	pmonitor->m_recvfd = -1;

478 479 480
	monitor_set_child_handler(pmonitor->m_pid);
	signal(SIGHUP, &monitor_child_handler);
	signal(SIGTERM, &monitor_child_handler);
481
	signal(SIGINT, &monitor_child_handler);
482

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
	if (compat20) {
		mon_dispatch = mon_dispatch_postauth20;

		/* Permit requests for moduli and signatures */
		monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
		monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
		monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
	} else {
		mon_dispatch = mon_dispatch_postauth15;
		monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
	}
	if (!no_pty_flag) {
		monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1);
		monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1);
	}

	for (;;)
500
		monitor_read(pmonitor, mon_dispatch, NULL);
501 502 503
}

void
504
monitor_sync(struct monitor *pmonitor)
505
{
506 507 508 509
	if (options.compression) {
		/* The member allocation is not visible, so sync it */
		mm_share_sync(&pmonitor->m_zlib, &pmonitor->m_zback);
	}
510 511
}

512 513 514 515 516 517 518 519 520 521 522 523 524 525
static int
monitor_read_log(struct monitor *pmonitor)
{
	Buffer logmsg;
	u_int len, level;
	char *msg;

	buffer_init(&logmsg);

	/* Read length */
	buffer_append_space(&logmsg, 4);
	if (atomicio(read, pmonitor->m_log_recvfd,
	    buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg)) {
		if (errno == EPIPE) {
526
			buffer_free(&logmsg);
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
			debug("%s: child log fd closed", __func__);
			close(pmonitor->m_log_recvfd);
			pmonitor->m_log_recvfd = -1;
			return -1;
		}
		fatal("%s: log fd read: %s", __func__, strerror(errno));
	}
	len = buffer_get_int(&logmsg);
	if (len <= 4 || len > 8192)
		fatal("%s: invalid log message length %u", __func__, len);

	/* Read severity, message */
	buffer_clear(&logmsg);
	buffer_append_space(&logmsg, len);
	if (atomicio(read, pmonitor->m_log_recvfd,
	    buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg))
		fatal("%s: log fd read: %s", __func__, strerror(errno));

	/* Log it */
	level = buffer_get_int(&logmsg);
	msg = buffer_get_string(&logmsg, NULL);
	if (log_level_name(level) == NULL)
		fatal("%s: invalid log level %u (corrupted message?)",
		    __func__, level);
	do_log2(level, "%s [preauth]", msg);

	buffer_free(&logmsg);
554
	free(msg);
555 556 557 558

	return 0;
}

559
int
560
monitor_read(struct monitor *pmonitor, struct mon_table *ent,
561 562 563 564 565
    struct mon_table **pent)
{
	Buffer m;
	int ret;
	u_char type;
566 567 568 569 570 571 572 573
	struct pollfd pfd[2];

	for (;;) {
		bzero(&pfd, sizeof(pfd));
		pfd[0].fd = pmonitor->m_sendfd;
		pfd[0].events = POLLIN;
		pfd[1].fd = pmonitor->m_log_recvfd;
		pfd[1].events = pfd[1].fd == -1 ? 0 : POLLIN;
574 575 576
		if (poll(pfd, pfd[1].fd == -1 ? 1 : 2, -1) == -1) {
			if (errno == EINTR || errno == EAGAIN)
				continue;
577
			fatal("%s: poll: %s", __func__, strerror(errno));
578
		}
579 580 581 582 583 584 585 586 587 588 589
		if (pfd[1].revents) {
			/*
			 * Drain all log messages before processing next
			 * monitor request.
			 */
			monitor_read_log(pmonitor);
			continue;
		}
		if (pfd[0].revents)
			break;  /* Continues below */
	}
590 591 592

	buffer_init(&m);

593
	mm_request_receive(pmonitor->m_sendfd, &m);
594 595
	type = buffer_get_char(&m);

596
	debug3("%s: checking request %d", __func__, type);
597 598 599 600 601 602 603 604 605

	while (ent->f != NULL) {
		if (ent->type == type)
			break;
		ent++;
	}

	if (ent->f != NULL) {
		if (!(ent->flags & MON_PERMIT))
606
			fatal("%s: unpermitted request %d", __func__,
607
			    type);
608
		ret = (*ent->f)(pmonitor->m_sendfd, &m);
609 610 611 612
		buffer_free(&m);

		/* The child may use this request only once, disable it */
		if (ent->flags & MON_ONCE) {
613
			debug2("%s: %d used once, disabling now", __func__,
614 615 616 617 618 619 620 621 622 623
			    type);
			ent->flags &= ~MON_PERMIT;
		}

		if (pent != NULL)
			*pent = ent;

		return ret;
	}

624
	fatal("%s: unsupported request: %d", __func__, type);
625 626 627 628 629 630 631 632 633 634 635

	/* NOTREACHED */
	return (-1);
}

/* allowed key state */
static int
monitor_allowed_key(u_char *blob, u_int bloblen)
{
	/* make sure key is allowed */
	if (key_blob == NULL || key_bloblen != bloblen ||
636
	    timingsafe_bcmp(key_blob, blob, key_bloblen))
637 638 639 640 641 642 643 644
		return (0);
	return (1);
}

static void
monitor_reset_key_state(void)
{
	/* reset state */
645 646 647
	free(key_blob);
	free(hostbased_cuser);
	free(hostbased_chost);
648 649 650 651 652 653 654 655
	key_blob = NULL;
	key_bloblen = 0;
	key_blobtype = MM_NOKEY;
	hostbased_cuser = NULL;
	hostbased_chost = NULL;
}

int
656
mm_answer_moduli(int sock, Buffer *m)
657 658 659 660 661 662 663 664 665
{
	DH *dh;
	int min, want, max;

	min = buffer_get_int(m);
	want = buffer_get_int(m);
	max = buffer_get_int(m);

	debug3("%s: got parameters: %d %d %d",
666
	    __func__, min, want, max);
667 668 669
	/* We need to check here, too, in case the child got corrupted */
	if (max < min || want < min || max < want)
		fatal("%s: bad parameters: %d %d %d",
670
		    __func__, min, want, max);
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685

	buffer_clear(m);

	dh = choose_dh(min, want, max);
	if (dh == NULL) {
		buffer_put_char(m, 0);
		return (0);
	} else {
		/* Send first bignum */
		buffer_put_char(m, 1);
		buffer_put_bignum2(m, dh->p);
		buffer_put_bignum2(m, dh->g);

		DH_free(dh);
	}
686
	mm_request_send(sock, MONITOR_ANS_MODULI, m);
687 688 689
	return (0);
}

690 691
extern AuthenticationConnection *auth_conn;

692
int
693
mm_answer_sign(int sock, Buffer *m)
694 695 696 697 698 699 700
{
	Key *key;
	u_char *p;
	u_char *signature;
	u_int siglen, datlen;
	int keyid;

701
	debug3("%s", __func__);
702 703 704 705

	keyid = buffer_get_int(m);
	p = buffer_get_string(m, &datlen);

706
	/*
707 708
	 * Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes),
	 * SHA384 (48 bytes) and SHA512 (64 bytes).
709
	 */
710
	if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64)
711
		fatal("%s: data length incorrect: %u", __func__, datlen);
712

713 714 715 716 717 718 719
	/* save session id, it will be passed on the first call */
	if (session_id2_len == 0) {
		session_id2_len = datlen;
		session_id2 = xmalloc(session_id2_len);
		memcpy(session_id2, p, session_id2_len);
	}

720 721 722 723 724 725 726 727 728
	if ((key = get_hostkey_by_index(keyid)) != NULL) {
		if (key_sign(key, &signature, &siglen, p, datlen) < 0)
			fatal("%s: key_sign failed", __func__);
	} else if ((key = get_hostkey_public_by_index(keyid)) != NULL &&
	    auth_conn != NULL) {
		if (ssh_agent_sign(auth_conn, key, &signature, &siglen, p,
		    datlen) < 0)
			fatal("%s: ssh_agent_sign failed", __func__);
	} else
729
		fatal("%s: no hostkey from index %d", __func__, keyid);
730

731
	debug3("%s: signature %p(%u)", __func__, signature, siglen);
732 733 734 735

	buffer_clear(m);
	buffer_put_string(m, signature, siglen);

736 737
	free(p);
	free(signature);
738

739
	mm_request_send(sock, MONITOR_ANS_SIGN, m);
740 741 742 743 744 745 746 747 748 749

	/* Turn on permissions for getpwnam */
	monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);

	return (0);
}

/* Retrieves the password entry and also checks if the user is permitted */

int
750
mm_answer_pwnamallow(int sock, Buffer *m)
751
{
752
	char *username;
753 754
	struct passwd *pwent;
	int allowed = 0;
Damien Miller's avatar
Damien Miller committed
755
	u_int i;
756

757
	debug3("%s", __func__);
758 759

	if (authctxt->attempt++ != 0)
760
		fatal("%s: multiple attempts for getpwnam", __func__);
761

762
	username = buffer_get_string(m, NULL);
763

764
	pwent = getpwnamallow(username);
765

766 767
	authctxt->user = xstrdup(username);
	setproctitle("%s [priv]", pwent ? username : "unknown");
768
	free(username);
769 770 771 772 773

	buffer_clear(m);

	if (pwent == NULL) {
		buffer_put_char(m, 0);
774
		authctxt->pw = fakepw();
775 776 777 778 779 780 781 782 783 784 785
		goto out;
	}

	allowed = 1;
	authctxt->pw = pwent;
	authctxt->valid = 1;

	buffer_put_char(m, 1);
	buffer_put_string(m, pwent, sizeof(struct passwd));
	buffer_put_cstring(m, pwent->pw_name);
	buffer_put_cstring(m, "*");
786
#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
787
	buffer_put_cstring(m, pwent->pw_gecos);
788 789
#endif
#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
790
	buffer_put_cstring(m, pwent->pw_class);
791
#endif
792 793
	buffer_put_cstring(m, pwent->pw_dir);
	buffer_put_cstring(m, pwent->pw_shell);
794 795

 out:
796
	buffer_put_string(m, &options, sizeof(options));
797 798 799 800 801

#define M_CP_STROPT(x) do { \
		if (options.x != NULL) \
			buffer_put_cstring(m, options.x); \
	} while (0)
Damien Miller's avatar
Damien Miller committed
802 803 804 805
#define M_CP_STRARRAYOPT(x, nx) do { \
		for (i = 0; i < options.nx; i++) \
			buffer_put_cstring(m, options.x[i]); \
	} while (0)
806 807 808
	/* See comment in servconf.h */
	COPY_MATCH_STRING_OPTS();
#undef M_CP_STROPT
Damien Miller's avatar
Damien Miller committed
809
#undef M_CP_STRARRAYOPT
810 811 812 813 814 815 816 817 818 819 820

	/* Create valid auth method lists */
	if (compat20 && auth2_setup_methods_lists(authctxt) != 0) {
		/*
		 * The monitor will continue long enough to let the child
		 * run to it's packet_disconnect(), but it must not allow any
		 * authentication to succeed.
		 */
		debug("%s: no valid authentication method lists", __func__);
	}

821
	debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed);
822
	mm_request_send(sock, MONITOR_ANS_PWNAM, m);
823 824 825 826

	/* For SSHv1 allow authentication now */
	if (!compat20)
		monitor_permit_authentications(1);
827
	else {
828 829
		/* Allow service/style information on the auth context */
		monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
830 831
		monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
	}
832
#ifdef USE_PAM
833 834
	if (options.use_pam)
		monitor_permit(mon_dispatch, MONITOR_REQ_PAM_START, 1);
835
#endif
836 837 838 839

	return (0);
}

840
int mm_answer_auth2_read_banner(int sock, Buffer *m)
841 842 843 844 845 846
{
	char *banner;

	buffer_clear(m);
	banner = auth2_read_banner();
	buffer_put_cstring(m, banner != NULL ? banner : "");
847
	mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
848
	free(banner);
849 850 851 852

	return (0);
}

853
int
854
mm_answer_authserv(int sock, Buffer *m)
855 856 857 858 859 860
{
	monitor_permit_authentications(1);

	authctxt->service = buffer_get_string(m, NULL);
	authctxt->style = buffer_get_string(m, NULL);
	debug3("%s: service=%s, style=%s",
861
	    __func__, authctxt->service, authctxt->style);
862 863

	if (strlen(authctxt->style) == 0) {
864
		free(authctxt->style);
865 866 867 868 869 870 871
		authctxt->style = NULL;
	}

	return (0);
}

int
872
mm_answer_authpassword(int sock, Buffer *m)
873 874 875
{
	static int call_count;
	char *passwd;
876 877
	int authenticated;
	u_int plen;
878 879 880

	passwd = buffer_get_string(m, &plen);
	/* Only authenticate if the context is valid */
881
	authenticated = options.password_authentication &&
882
	    auth_password(authctxt, passwd);
883
	memset(passwd, 0, strlen(passwd));
884
	free(passwd);
885 886 887 888

	buffer_clear(m);
	buffer_put_int(m, authenticated);

889
	debug3("%s: sending result %d", __func__, authenticated);
890
	mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
891 892 893 894 895 896 897 898 899 900 901 902 903

	call_count++;
	if (plen == 0 && call_count == 1)
		auth_method = "none";
	else
		auth_method = "password";

	/* Causes monitor loop to terminate if authenticated */
	return (authenticated);
}

#ifdef BSD_AUTH
int
904
mm_answer_bsdauthquery(int sock, Buffer *m)
905 906 907 908 909
{
	char *name, *infotxt;
	u_int numprompts;
	u_int *echo_on;
	char **prompts;
910
	u_int success;
911

912 913
	success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
	    &prompts, &echo_on) < 0 ? 0 : 1;
914 915

	buffer_clear(m);
916 917
	buffer_put_int(m, success);
	if (success)
918 919
		buffer_put_cstring(m, prompts[0]);

920
	debug3("%s: sending challenge success: %u", __func__, success);
921
	mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
922

923
	if (success) {
924 925 926 927
		free(name);
		free(infotxt);
		free(prompts);
		free(echo_on);
928 929 930 931 932 933
	}

	return (0);
}

int
934
mm_answer_bsdauthrespond(int sock, Buffer *m)
935 936 937 938 939
{
	char *response;
	int authok;

	if (authctxt->as == 0)
940
		fatal("%s: no bsd auth session", __func__);
941 942

	response = buffer_get_string(m, NULL);
943 944
	authok = options.challenge_response_authentication &&
	    auth_userresponse(authctxt->as, response, 0);
945
	authctxt->as = NULL;
946
	debug3("%s: <%s> = <%d>", __func__, response, authok);
947
	free(response);
948 949 950 951

	buffer_clear(m);
	buffer_put_int(m, authok);

952
	debug3("%s: sending authenticated: %d", __func__, authok);
953
	mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
954

955 956 957 958
	if (compat20) {
		auth_method = "keyboard-interactive";
		auth_submethod = "bsdauth";
	} else
959
		auth_method = "bsdauth";
960 961 962 963 964 965 966

	return (authok != 0);
}
#endif

#ifdef SKEY
int
967
mm_answer_skeyquery(int sock, Buffer *m)
968 969 970
{
	struct skey skey;
	char challenge[1024];
971
	u_int success;
972

973 974
	success = _compat_skeychallenge(&skey, authctxt->user, challenge,
	    sizeof(challenge)) < 0 ? 0 : 1;
975 976

	buffer_clear(m);
977 978
	buffer_put_int(m, success);
	if (success)
979 980
		buffer_put_cstring(m, challenge);

981
	debug3("%s: sending challenge success: %u", __func__, success);
982
	mm_request_send(sock, MONITOR_ANS_SKEYQUERY, m);
983 984 985 986 987

	return (0);
}

int
988
mm_answer_skeyrespond(int sock, Buffer *m)
989 990 991 992 993 994
{
	char *response;
	int authok;

	response = buffer_get_string(m, NULL);

995 996
	authok = (options.challenge_response_authentication &&
	    authctxt->valid &&
997 998 999
	    skey_haskey(authctxt->pw->pw_name) == 0 &&
	    skey_passcheck(authctxt->pw->pw_name, response) != -1);

1000
	free(response);
1001 1002 1003 1004

	buffer_clear(m);
	buffer_put_int(m, authok);

1005
	debug3("%s: sending authenticated: %d", __func__, authok);
1006
	mm_request_send(sock, MONITOR_ANS_SKEYRESPOND, m);
1007 1008 1009 1010 1011 1012 1013

	auth_method = "skey";

	return (authok != 0);
}
#endif

1014 1015
#ifdef USE_PAM
int
1016
mm_answer_pam_start(int sock, Buffer *m)
1017
{
1018 1019 1020
	if (!options.use_pam)
		fatal("UsePAM not set, but ended up in %s anyway", __func__);

1021
	start_pam(authctxt);
1022

1023 1024
	monitor_permit(mon_dispatch, MONITOR_REQ_PAM_ACCOUNT, 1);

1025 1026
	return (0);
}
1027

1028
int
1029
mm_answer_pam_account(int sock, Buffer *m)
1030 1031
{
	u_int ret;
1032

1033 1034 1035 1036 1037 1038
	if (!options.use_pam)
		fatal("UsePAM not set, but ended up in %s anyway", __func__);

	ret = do_pam_account();

	buffer_put_int(m, ret);
1039
	buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
1040

1041
	mm_request_send(sock, MONITOR_ANS_PAM_ACCOUNT, m);
1042 1043 1044 1045

	return (ret);
}

1046 1047 1048 1049
static void *sshpam_ctxt, *sshpam_authok;
extern KbdintDevice sshpam_device;

int
1050
mm_answer_pam_init_ctx(int sock, Buffer *m)
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
{

	debug3("%s", __func__);
	authctxt->user = buffer_get_string(m, NULL);
	sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
	sshpam_authok = NULL;
	buffer_clear(m);
	if (sshpam_ctxt != NULL) {
		monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
		buffer_put_int(m, 1);
	} else {
		buffer_put_int(m, 0);
	}
1064
	mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
1065 1066 1067 1068
	return (0);
}

int
1069
mm_answer_pam_query(int sock, Buffer *m)
1070
{
1071 1072
	char *name = NULL, *info = NULL, **prompts = NULL;
	u_int i, num = 0, *echo_on = 0;
1073
	int ret;
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084

	debug3("%s", __func__);
	sshpam_authok = NULL;
	ret = (sshpam_device.query)(sshpam_ctxt, &name, &info, &num, &prompts, &echo_on);
	if (ret == 0 && num == 0)
		sshpam_authok = sshpam_ctxt;
	if (num > 1 || name == NULL || info == NULL)
		ret = -1;
	buffer_clear(m);
	buffer_put_int(m, ret);
	buffer_put_cstring(m, name);
1085
	free(name);
1086
	buffer_put_cstring(m, info);
1087
	free(info);
1088 1089 1090
	buffer_put_int(m, num);
	for (i = 0; i < num; ++i) {
		buffer_put_cstring(m, prompts[i]);
1091
		free(prompts[i]);
1092 1093
		buffer_put_int(m, echo_on[i]);
	}
1094 1095
	free(prompts);
	free(echo_on);
1096 1097
	auth_method = "keyboard-interactive";
	auth_submethod = "pam";
1098
	mm_request_send(sock, MONITOR_ANS_PAM_QUERY, m);
1099 1100 1101 1102
	return (0);
}

int
1103
mm_answer_pam_respond(int sock, Buffer *m)
1104 1105
{
	char **resp;
1106 1107
	u_int i, num;
	int ret;
1108 1109 1110 1111 1112

	debug3("%s", __func__);
	sshpam_authok = NULL;
	num = buffer_get_int(m);
	if (num > 0) {
1113
		resp = xcalloc(num, sizeof(char *));
1114 1115 1116 1117
		for (i = 0; i < num; ++i)
			resp[i] = buffer_get_string(m, NULL);
		ret = (sshpam_device.respond)(sshpam_ctxt, num, resp);
		for (i = 0; i < num; ++i)
1118 1119
			free(resp[i]);
		free(resp);
1120 1121 1122 1123 1124
	} else {
		ret = (sshpam_device.respond)(sshpam_ctxt, num, NULL);
	}
	buffer_clear(m);
	buffer_put_int(m, ret);
1125
	mm_request_send(sock, MONITOR_ANS_PAM_RESPOND, m);
1126 1127
	auth_method = "keyboard-interactive";
	auth_submethod = "pam";
1128 1129 1130 1131 1132 1133
	if (ret == 0)
		sshpam_authok = sshpam_ctxt;
	return (0);
}

int
1134
mm_answer_pam_free_ctx(int sock, Buffer *m)
1135 1136 1137 1138 1139
{

	debug3("%s", __func__);
	(sshpam_device.free_ctx)(sshpam_ctxt);
	buffer_clear(m);
1140
	mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
1141 1142
	auth_method = "keyboard-interactive";
	auth_submethod = "pam";
1143 1144
	return (sshpam_authok == sshpam_ctxt);
}
1145 1146
#endif

1147
int
1148
mm_answer_keyallowed(int sock, Buffer *m)
1149 1150
{
	Key *key;
1151 1152
	char *cuser, *chost;
	u_char *blob;
1153 1154 1155 1156
	u_int bloblen;
	enum mm_keytype type = 0;
	int allowed = 0;

1157
	debug3("%s entering", __func__);
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167

	type = buffer_get_int(m);
	cuser = buffer_get_string(m, NULL);
	chost = buffer_get_string(m, NULL);
	blob = buffer_get_string(m, &bloblen);

	key = key_from_blob(blob, bloblen);

	if ((compat20 && type == MM_RSAHOSTKEY) ||
	    (!compat20 && type != MM_RSAHOSTKEY))
1168
		fatal("%s: key type and protocol mismatch", __func__);
1169

1170
	debug3("%s: key_from_blob: %p", __func__, key);
1171

1172
	if (key != NULL && authctxt->valid) {
1173
		switch (type) {
1174
		case MM_USERKEY:
1175 1176
			allowed = options.pubkey_authentication &&
			    user_key_allowed(authctxt->pw, key);
1177
			pubkey_auth_info(authctxt, key, NULL);
1178
			auth_method = "publickey";
1179 1180
			if (options.pubkey_authentication && allowed != 1)
				auth_clear_options();
1181 1182
			break;
		case MM_HOSTKEY:
1183 1184
			allowed = options.hostbased_authentication &&
			    hostbased_key_allowed(authctxt->pw,
1185
			    cuser, chost, key);
1186 1187 1188
			pubkey_auth_info(authctxt, key,
			    "client user \"%.100s\", client host \"%.100s\"",
			    cuser, chost);
1189
			auth_method = "hostbased";
1190 1191 1192
			break;
		case MM_RSAHOSTKEY:
			key->type = KEY_RSA1; /* XXX */
1193 1194
			allowed = options.rhosts_rsa_authentication &&
			    auth_rhosts_rsa_key_allowed(authctxt->pw,
1195
			    cuser, chost, key);
1196 1197
			if (options.rhosts_rsa_authentication && allowed != 1)
				auth_clear_options();
1198
			auth_method = "rsa";
1199 1200
			break;
		default:
1201
			fatal("%s: unknown key type %d", __func__, type);
1202 1203 1204
			break;
		}
	}
Damien Miller's avatar
Damien Miller committed
1205 1206
	if (key != NULL)
		key_free(key);
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217

	/* clear temporarily storage (used by verify) */
	monitor_reset_key_state();

	if (allowed) {
		/* Save temporarily for comparison in verify */
		key_blob = blob;
		key_bloblen = bloblen;
		key_blobtype = type;
		hostbased_cuser = cuser;
		hostbased_chost = chost;
1218
	} else {
1219
		/* Log failed attempt */
1220
		auth_log(authctxt, 0, 0, auth_method, NULL);
1221 1222 1223
		free(blob);
		free(cuser);
		free(chost);
1224 1225 1226
	}

	debug3("%s: key %p is %s",
1227
	    __func__, key, allowed ? "allowed" : "not allowed");
1228 1229 1230

	buffer_clear(m);
	buffer_put_int(m, allowed);
1231
	buffer_put_int(m, forced_command != NULL);
1232

1233
	mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244

	if (type == MM_RSAHOSTKEY)
		monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);

	return (0);
}

static int
monitor_valid_userblob(u_char *data, u_int datalen)
{
	Buffer b;
1245
	char *p, *userstyle;
1246 1247 1248 1249 1250 1251 1252
	u_int len;
	int fail = 0;

	buffer_init(&b);
	buffer_append(&b, data, datalen);

	if (datafellows & SSH_OLD_SESSIONID) {
1253 1254 1255 1256
		p = buffer_ptr(&b);
		len = buffer_len(&b);
		if ((session_id2 == NULL) ||
		    (len < session_id2_len) ||
1257
		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1258
			fail++;
1259 1260
		buffer_consume(&b, session_id2_len);
	} else {
1261 1262 1263
		p = buffer_get_string(&b, &len);
		if ((session_id2 == NULL) ||
		    (len != session_id2_len) ||
1264
		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1265
			fail++;
1266
		free(p);
1267 1268 1269
	}
	if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
		fail++;
1270 1271 1272 1273 1274
	p = buffer_get_cstring(&b, NULL);
	xasprintf(&userstyle, "%s%s%s", authctxt->user,
	    authctxt->style ? ":" : "",
	    authctxt->style ? authctxt->style : "");
	if (strcmp(userstyle, p) != 0) {
1275
		logit("wrong user name passed to monitor: expected %s != %.100s",
1276
		    userstyle, p);
1277 1278
		fail++;
	}
1279 1280
	free(userstyle);
	free(p);
1281 1282 1283 1284 1285
	buffer_skip_string(&b);
	if (datafellows & SSH_BUG_PKAUTH) {
		if (!buffer_get_char(&b))
			fail++;
	} else {
1286
		p = buffer_get_cstring(&b, NULL);
1287 1288
		if (strcmp("publickey", p) != 0)
			fail++;
1289
		free(p);
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
		if (!buffer_get_char(&b))
			fail++;
		buffer_skip_string(&b);
	}
	buffer_skip_string(&b);
	if (buffer_len(&b) != 0)
		fail++;
	buffer_free(&b);
	return (fail == 0);
}

static int
1302 1303
monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
    char *chost)
1304 1305
{
	Buffer b;
1306
	char *p, *userstyle;
1307 1308 1309 1310 1311 1312
	u_int len;
	int fail = 0;

	buffer_init(&b);
	buffer_append(&b, data, datalen);

1313 1314 1315
	p = buffer_get_string(&b, &len);
	if ((session_id2 == NULL) ||
	    (len != session_id2_len) ||
1316
	    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1317
		fail++;
1318
	free(p);
1319

1320 1321
	if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
		fail++;
1322 1323 1324 1325 1326
	p = buffer_get_cstring(&b, NULL);
	xasprintf(&userstyle, "%s%s%s", authctxt->user,
	    authctxt->style ? ":" : "",
	    authctxt->style ? authctxt->style : "");
	if (strcmp(userstyle, p) != 0) {
1327
		logit("wrong user name passed to monitor: expected %s != %.100s",
1328
		    userstyle, p);
1329 1330
		fail++;
	}
1331
	free(userstyle);
1332
	free(p);
1333
	buffer_skip_string(&b);	/* service */
1334
	p = buffer_get_cstring(&b, NULL);
1335 1336
	if (strcmp(p, "hostbased") != 0)
		fail++;
1337
	free(p);
1338 1339 1340 1341 1342 1343 1344 1345 1346
	buffer_skip_string(&b);	/* pkalg */
	buffer_skip_string(&b);	/* pkblob */

	/* verify client host, strip trailing dot if necessary */
	p = buffer_get_string(&b, NULL);
	if (((len = strlen(p)) > 0) && p[len - 1] == '.')
		p[len - 1] = '\0';
	if (strcmp(p, chost) != 0)
		fail++;
1347
	free(p);
1348 1349 1350 1351 1352

	/* verify client user */
	p = buffer_get_string(&b, NULL);
	if (strcmp(p, cuser) != 0)
		fail++;
1353
	free(p);
1354 1355 1356 1357 1358 1359 1360 1361

	if (buffer_len(&b) != 0)
		fail++;
	buffer_free(&b);
	return (fail == 0);
}

int
1362
mm_answer_keyverify(int sock, Buffer *m)
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
{
	Key *key;
	u_char *signature, *data, *blob;
	u_int signaturelen, datalen, bloblen;
	int verified = 0;
	int valid_data = 0;

	blob = buffer_get_string(m, &bloblen);
	signature = buffer_get_string(m, &signaturelen);
	data = buffer_get_string(m, &datalen);

	if (hostbased_cuser == NULL || hostbased_chost == NULL ||
1375
	  !monitor_allowed_key(blob, bloblen))
1376
		fatal("%s: bad key, not previously allowed", __func__);
1377 1378 1379

	key = key_from_blob(blob, bloblen);
	if (key == NULL)
1380
		fatal("%s: bad public key blob", __func__);
1381 1382 1383 1384 1385 1386 1387