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