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