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