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