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