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