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