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