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