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