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