monitor.c revision 1.113
1/* $OpenBSD: monitor.c,v 1.113 2011/05/23 03:30:07 djm 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
79static Gssctxt *gsscontext = NULL;
80#endif
81
82/* Imports */
83extern ServerOptions options;
84extern u_int utmp_len;
85extern Newkeys *current_keys[];
86extern z_stream incoming_stream;
87extern z_stream outgoing_stream;
88extern u_char session_id[];
89extern Buffer auth_debug;
90extern int auth_debug_init;
91extern Buffer loginmsg;
92
93/* State exported from the child */
94
95struct {
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
120int mm_answer_moduli(int, Buffer *);
121int mm_answer_sign(int, Buffer *);
122int mm_answer_pwnamallow(int, Buffer *);
123int mm_answer_auth2_read_banner(int, Buffer *);
124int mm_answer_authserv(int, Buffer *);
125int mm_answer_authpassword(int, Buffer *);
126int mm_answer_bsdauthquery(int, Buffer *);
127int mm_answer_bsdauthrespond(int, Buffer *);
128int mm_answer_skeyquery(int, Buffer *);
129int mm_answer_skeyrespond(int, Buffer *);
130int mm_answer_keyallowed(int, Buffer *);
131int mm_answer_keyverify(int, Buffer *);
132int mm_answer_pty(int, Buffer *);
133int mm_answer_pty_cleanup(int, Buffer *);
134int mm_answer_term(int, Buffer *);
135int mm_answer_rsa_keyallowed(int, Buffer *);
136int mm_answer_rsa_challenge(int, Buffer *);
137int mm_answer_rsa_response(int, Buffer *);
138int mm_answer_sesskey(int, Buffer *);
139int mm_answer_sessid(int, Buffer *);
140int mm_answer_jpake_get_pwdata(int, Buffer *);
141int mm_answer_jpake_step1(int, Buffer *);
142int mm_answer_jpake_step2(int, Buffer *);
143int mm_answer_jpake_key_confirm(int, Buffer *);
144int mm_answer_jpake_check_confirm(int, Buffer *);
145
146#ifdef GSSAPI
147int mm_answer_gss_setup_ctx(int, Buffer *);
148int mm_answer_gss_accept_ctx(int, Buffer *);
149int mm_answer_gss_userok(int, Buffer *);
150int mm_answer_gss_checkmic(int, Buffer *);
151#endif
152
153static Authctxt *authctxt;
154static BIGNUM *ssh1_challenge = NULL;	/* used for ssh1 rsa auth */
155
156/* local state for key verify */
157static u_char *key_blob = NULL;
158static u_int key_bloblen = 0;
159static int key_blobtype = MM_NOKEY;
160static char *hostbased_cuser = NULL;
161static char *hostbased_chost = NULL;
162static char *auth_method = "unknown";
163static u_int session_id2_len = 0;
164static u_char *session_id2 = NULL;
165static pid_t monitor_child_pid;
166
167struct 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
182struct 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
209struct 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
218struct 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
232struct 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
239struct mon_table *mon_dispatch;
240
241/* Specifies if a certain message is allowed at the moment */
242
243static void
244monitor_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
256static void
257monitor_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
270void
271monitor_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
334static void
335monitor_set_child_handler(pid_t pid)
336{
337	monitor_child_pid = pid;
338}
339
340static void
341monitor_child_handler(int sig)
342{
343	kill(monitor_child_pid, sig);
344}
345
346void
347monitor_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
374void
375monitor_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
383int
384monitor_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 */
431static int
432monitor_allowed_key(u_char *blob, u_int bloblen)
433{
434	/* make sure key is allowed */
435	if (key_blob == NULL || key_bloblen != bloblen ||
436	    timingsafe_bcmp(key_blob, blob, key_bloblen))
437		return (0);
438	return (1);
439}
440
441static void
442monitor_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
458int
459mm_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
493int
494mm_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 use SHA1 (20 bytes), SHA256 (32 bytes),
509	 * SHA384 (48 bytes) and SHA512 (64 bytes).
510	 */
511	if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64)
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
544int
545mm_answer_pwnamallow(int sock, Buffer *m)
546{
547	char *username;
548	struct passwd *pwent;
549	int allowed = 0;
550	u_int i;
551
552	debug3("%s", __func__);
553
554	if (authctxt->attempt++ != 0)
555		fatal("%s: multiple attempts for getpwnam", __func__);
556
557	username = buffer_get_string(m, NULL);
558
559	pwent = getpwnamallow(username);
560
561	authctxt->user = xstrdup(username);
562	setproctitle("%s [priv]", pwent ? username : "unknown");
563	xfree(username);
564
565	buffer_clear(m);
566
567	if (pwent == NULL) {
568		buffer_put_char(m, 0);
569		authctxt->pw = fakepw();
570		goto out;
571	}
572
573	allowed = 1;
574	authctxt->pw = pwent;
575	authctxt->valid = 1;
576
577	buffer_put_char(m, 1);
578	buffer_put_string(m, pwent, sizeof(struct passwd));
579	buffer_put_cstring(m, pwent->pw_name);
580	buffer_put_cstring(m, "*");
581	buffer_put_cstring(m, pwent->pw_gecos);
582	buffer_put_cstring(m, pwent->pw_class);
583	buffer_put_cstring(m, pwent->pw_dir);
584	buffer_put_cstring(m, pwent->pw_shell);
585
586 out:
587	buffer_put_string(m, &options, sizeof(options));
588
589#define M_CP_STROPT(x) do { \
590		if (options.x != NULL) \
591			buffer_put_cstring(m, options.x); \
592	} while (0)
593#define M_CP_STRARRAYOPT(x, nx) do { \
594		for (i = 0; i < options.nx; i++) \
595			buffer_put_cstring(m, options.x[i]); \
596	} while (0)
597	/* See comment in servconf.h */
598	COPY_MATCH_STRING_OPTS();
599#undef M_CP_STROPT
600#undef M_CP_STRARRAYOPT
601
602	debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed);
603	mm_request_send(sock, MONITOR_ANS_PWNAM, m);
604
605	/* For SSHv1 allow authentication now */
606	if (!compat20)
607		monitor_permit_authentications(1);
608	else {
609		/* Allow service/style information on the auth context */
610		monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
611		monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
612	}
613
614	return (0);
615}
616
617int mm_answer_auth2_read_banner(int sock, Buffer *m)
618{
619	char *banner;
620
621	buffer_clear(m);
622	banner = auth2_read_banner();
623	buffer_put_cstring(m, banner != NULL ? banner : "");
624	mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
625
626	if (banner != NULL)
627		xfree(banner);
628
629	return (0);
630}
631
632int
633mm_answer_authserv(int sock, Buffer *m)
634{
635	monitor_permit_authentications(1);
636
637	authctxt->service = buffer_get_string(m, NULL);
638	authctxt->style = buffer_get_string(m, NULL);
639	debug3("%s: service=%s, style=%s",
640	    __func__, authctxt->service, authctxt->style);
641
642	if (strlen(authctxt->style) == 0) {
643		xfree(authctxt->style);
644		authctxt->style = NULL;
645	}
646
647	return (0);
648}
649
650int
651mm_answer_authpassword(int sock, Buffer *m)
652{
653	static int call_count;
654	char *passwd;
655	int authenticated;
656	u_int plen;
657
658	passwd = buffer_get_string(m, &plen);
659	/* Only authenticate if the context is valid */
660	authenticated = options.password_authentication &&
661	    auth_password(authctxt, passwd);
662	memset(passwd, 0, strlen(passwd));
663	xfree(passwd);
664
665	buffer_clear(m);
666	buffer_put_int(m, authenticated);
667
668	debug3("%s: sending result %d", __func__, authenticated);
669	mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
670
671	call_count++;
672	if (plen == 0 && call_count == 1)
673		auth_method = "none";
674	else
675		auth_method = "password";
676
677	/* Causes monitor loop to terminate if authenticated */
678	return (authenticated);
679}
680
681int
682mm_answer_bsdauthquery(int sock, Buffer *m)
683{
684	char *name, *infotxt;
685	u_int numprompts;
686	u_int *echo_on;
687	char **prompts;
688	u_int success;
689
690	success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
691	    &prompts, &echo_on) < 0 ? 0 : 1;
692
693	buffer_clear(m);
694	buffer_put_int(m, success);
695	if (success)
696		buffer_put_cstring(m, prompts[0]);
697
698	debug3("%s: sending challenge success: %u", __func__, success);
699	mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
700
701	if (success) {
702		xfree(name);
703		xfree(infotxt);
704		xfree(prompts);
705		xfree(echo_on);
706	}
707
708	return (0);
709}
710
711int
712mm_answer_bsdauthrespond(int sock, Buffer *m)
713{
714	char *response;
715	int authok;
716
717	if (authctxt->as == 0)
718		fatal("%s: no bsd auth session", __func__);
719
720	response = buffer_get_string(m, NULL);
721	authok = options.challenge_response_authentication &&
722	    auth_userresponse(authctxt->as, response, 0);
723	authctxt->as = NULL;
724	debug3("%s: <%s> = <%d>", __func__, response, authok);
725	xfree(response);
726
727	buffer_clear(m);
728	buffer_put_int(m, authok);
729
730	debug3("%s: sending authenticated: %d", __func__, authok);
731	mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
732
733	auth_method = "bsdauth";
734
735	return (authok != 0);
736}
737
738int
739mm_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_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
821
822	if (type == MM_RSAHOSTKEY)
823		monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
824
825	return (0);
826}
827
828static int
829monitor_valid_userblob(u_char *data, u_int datalen)
830{
831	Buffer b;
832	char *p;
833	u_int len;
834	int fail = 0;
835
836	buffer_init(&b);
837	buffer_append(&b, data, datalen);
838
839	if (datafellows & SSH_OLD_SESSIONID) {
840		p = buffer_ptr(&b);
841		len = buffer_len(&b);
842		if ((session_id2 == NULL) ||
843		    (len < session_id2_len) ||
844		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
845			fail++;
846		buffer_consume(&b, session_id2_len);
847	} else {
848		p = buffer_get_string(&b, &len);
849		if ((session_id2 == NULL) ||
850		    (len != session_id2_len) ||
851		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
852			fail++;
853		xfree(p);
854	}
855	if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
856		fail++;
857	p = buffer_get_string(&b, NULL);
858	if (strcmp(authctxt->user, p) != 0) {
859		logit("wrong user name passed to monitor: expected %s != %.100s",
860		    authctxt->user, p);
861		fail++;
862	}
863	xfree(p);
864	buffer_skip_string(&b);
865	if (datafellows & SSH_BUG_PKAUTH) {
866		if (!buffer_get_char(&b))
867			fail++;
868	} else {
869		p = buffer_get_string(&b, NULL);
870		if (strcmp("publickey", p) != 0)
871			fail++;
872		xfree(p);
873		if (!buffer_get_char(&b))
874			fail++;
875		buffer_skip_string(&b);
876	}
877	buffer_skip_string(&b);
878	if (buffer_len(&b) != 0)
879		fail++;
880	buffer_free(&b);
881	return (fail == 0);
882}
883
884static int
885monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
886    char *chost)
887{
888	Buffer b;
889	char *p;
890	u_int len;
891	int fail = 0;
892
893	buffer_init(&b);
894	buffer_append(&b, data, datalen);
895
896	p = buffer_get_string(&b, &len);
897	if ((session_id2 == NULL) ||
898	    (len != session_id2_len) ||
899	    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
900		fail++;
901	xfree(p);
902
903	if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
904		fail++;
905	p = buffer_get_string(&b, NULL);
906	if (strcmp(authctxt->user, p) != 0) {
907		logit("wrong user name passed to monitor: expected %s != %.100s",
908		    authctxt->user, p);
909		fail++;
910	}
911	xfree(p);
912	buffer_skip_string(&b);	/* service */
913	p = buffer_get_string(&b, NULL);
914	if (strcmp(p, "hostbased") != 0)
915		fail++;
916	xfree(p);
917	buffer_skip_string(&b);	/* pkalg */
918	buffer_skip_string(&b);	/* pkblob */
919
920	/* verify client host, strip trailing dot if necessary */
921	p = buffer_get_string(&b, NULL);
922	if (((len = strlen(p)) > 0) && p[len - 1] == '.')
923		p[len - 1] = '\0';
924	if (strcmp(p, chost) != 0)
925		fail++;
926	xfree(p);
927
928	/* verify client user */
929	p = buffer_get_string(&b, NULL);
930	if (strcmp(p, cuser) != 0)
931		fail++;
932	xfree(p);
933
934	if (buffer_len(&b) != 0)
935		fail++;
936	buffer_free(&b);
937	return (fail == 0);
938}
939
940int
941mm_answer_keyverify(int sock, Buffer *m)
942{
943	Key *key;
944	u_char *signature, *data, *blob;
945	u_int signaturelen, datalen, bloblen;
946	int verified = 0;
947	int valid_data = 0;
948
949	blob = buffer_get_string(m, &bloblen);
950	signature = buffer_get_string(m, &signaturelen);
951	data = buffer_get_string(m, &datalen);
952
953	if (hostbased_cuser == NULL || hostbased_chost == NULL ||
954	  !monitor_allowed_key(blob, bloblen))
955		fatal("%s: bad key, not previously allowed", __func__);
956
957	key = key_from_blob(blob, bloblen);
958	if (key == NULL)
959		fatal("%s: bad public key blob", __func__);
960
961	switch (key_blobtype) {
962	case MM_USERKEY:
963		valid_data = monitor_valid_userblob(data, datalen);
964		break;
965	case MM_HOSTKEY:
966		valid_data = monitor_valid_hostbasedblob(data, datalen,
967		    hostbased_cuser, hostbased_chost);
968		break;
969	default:
970		valid_data = 0;
971		break;
972	}
973	if (!valid_data)
974		fatal("%s: bad signature data blob", __func__);
975
976	verified = key_verify(key, signature, signaturelen, data, datalen);
977	debug3("%s: key %p signature %s",
978	    __func__, key, (verified == 1) ? "verified" : "unverified");
979
980	key_free(key);
981	xfree(blob);
982	xfree(signature);
983	xfree(data);
984
985	auth_method = key_blobtype == MM_USERKEY ? "publickey" : "hostbased";
986
987	monitor_reset_key_state();
988
989	buffer_clear(m);
990	buffer_put_int(m, verified);
991	mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
992
993	return (verified == 1);
994}
995
996static void
997mm_record_login(Session *s, struct passwd *pw)
998{
999	socklen_t fromlen;
1000	struct sockaddr_storage from;
1001
1002	/*
1003	 * Get IP address of client. If the connection is not a socket, let
1004	 * the address be 0.0.0.0.
1005	 */
1006	memset(&from, 0, sizeof(from));
1007	fromlen = sizeof(from);
1008	if (packet_connection_is_on_socket()) {
1009		if (getpeername(packet_get_connection_in(),
1010		    (struct sockaddr *)&from, &fromlen) < 0) {
1011			debug("getpeername: %.100s", strerror(errno));
1012			cleanup_exit(255);
1013		}
1014	}
1015	/* Record that there was a login on that tty from the remote host. */
1016	record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
1017	    get_remote_name_or_ip(utmp_len, options.use_dns),
1018	    (struct sockaddr *)&from, fromlen);
1019}
1020
1021static void
1022mm_session_close(Session *s)
1023{
1024	debug3("%s: session %d pid %ld", __func__, s->self, (long)s->pid);
1025	if (s->ttyfd != -1) {
1026		debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ptyfd);
1027		session_pty_cleanup2(s);
1028	}
1029	session_unused(s->self);
1030}
1031
1032int
1033mm_answer_pty(int sock, Buffer *m)
1034{
1035	extern struct monitor *pmonitor;
1036	Session *s;
1037	int res, fd0;
1038
1039	debug3("%s entering", __func__);
1040
1041	buffer_clear(m);
1042	s = session_new();
1043	if (s == NULL)
1044		goto error;
1045	s->authctxt = authctxt;
1046	s->pw = authctxt->pw;
1047	s->pid = pmonitor->m_pid;
1048	res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1049	if (res == 0)
1050		goto error;
1051	pty_setowner(authctxt->pw, s->tty);
1052
1053	buffer_put_int(m, 1);
1054	buffer_put_cstring(m, s->tty);
1055
1056	/* We need to trick ttyslot */
1057	if (dup2(s->ttyfd, 0) == -1)
1058		fatal("%s: dup2", __func__);
1059
1060	mm_record_login(s, authctxt->pw);
1061
1062	/* Now we can close the file descriptor again */
1063	close(0);
1064
1065	/* send messages generated by record_login */
1066	buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
1067	buffer_clear(&loginmsg);
1068
1069	mm_request_send(sock, MONITOR_ANS_PTY, m);
1070
1071	if (mm_send_fd(sock, s->ptyfd) == -1 ||
1072	    mm_send_fd(sock, s->ttyfd) == -1)
1073		fatal("%s: send fds failed", __func__);
1074
1075	/* make sure nothing uses fd 0 */
1076	if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0)
1077		fatal("%s: open(/dev/null): %s", __func__, strerror(errno));
1078	if (fd0 != 0)
1079		error("%s: fd0 %d != 0", __func__, fd0);
1080
1081	/* slave is not needed */
1082	close(s->ttyfd);
1083	s->ttyfd = s->ptyfd;
1084	/* no need to dup() because nobody closes ptyfd */
1085	s->ptymaster = s->ptyfd;
1086
1087	debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd);
1088
1089	return (0);
1090
1091 error:
1092	if (s != NULL)
1093		mm_session_close(s);
1094	buffer_put_int(m, 0);
1095	mm_request_send(sock, MONITOR_ANS_PTY, m);
1096	return (0);
1097}
1098
1099int
1100mm_answer_pty_cleanup(int sock, Buffer *m)
1101{
1102	Session *s;
1103	char *tty;
1104
1105	debug3("%s entering", __func__);
1106
1107	tty = buffer_get_string(m, NULL);
1108	if ((s = session_by_tty(tty)) != NULL)
1109		mm_session_close(s);
1110	buffer_clear(m);
1111	xfree(tty);
1112	return (0);
1113}
1114
1115int
1116mm_answer_sesskey(int sock, Buffer *m)
1117{
1118	BIGNUM *p;
1119	int rsafail;
1120
1121	/* Turn off permissions */
1122	monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 0);
1123
1124	if ((p = BN_new()) == NULL)
1125		fatal("%s: BN_new", __func__);
1126
1127	buffer_get_bignum2(m, p);
1128
1129	rsafail = ssh1_session_key(p);
1130
1131	buffer_clear(m);
1132	buffer_put_int(m, rsafail);
1133	buffer_put_bignum2(m, p);
1134
1135	BN_clear_free(p);
1136
1137	mm_request_send(sock, MONITOR_ANS_SESSKEY, m);
1138
1139	/* Turn on permissions for sessid passing */
1140	monitor_permit(mon_dispatch, MONITOR_REQ_SESSID, 1);
1141
1142	return (0);
1143}
1144
1145int
1146mm_answer_sessid(int sock, Buffer *m)
1147{
1148	int i;
1149
1150	debug3("%s entering", __func__);
1151
1152	if (buffer_len(m) != 16)
1153		fatal("%s: bad ssh1 session id", __func__);
1154	for (i = 0; i < 16; i++)
1155		session_id[i] = buffer_get_char(m);
1156
1157	/* Turn on permissions for getpwnam */
1158	monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
1159
1160	return (0);
1161}
1162
1163int
1164mm_answer_rsa_keyallowed(int sock, Buffer *m)
1165{
1166	BIGNUM *client_n;
1167	Key *key = NULL;
1168	u_char *blob = NULL;
1169	u_int blen = 0;
1170	int allowed = 0;
1171
1172	debug3("%s entering", __func__);
1173
1174	auth_method = "rsa";
1175	if (options.rsa_authentication && authctxt->valid) {
1176		if ((client_n = BN_new()) == NULL)
1177			fatal("%s: BN_new", __func__);
1178		buffer_get_bignum2(m, client_n);
1179		allowed = auth_rsa_key_allowed(authctxt->pw, client_n, &key);
1180		BN_clear_free(client_n);
1181	}
1182	buffer_clear(m);
1183	buffer_put_int(m, allowed);
1184	buffer_put_int(m, forced_command != NULL);
1185
1186	/* clear temporarily storage (used by generate challenge) */
1187	monitor_reset_key_state();
1188
1189	if (allowed && key != NULL) {
1190		key->type = KEY_RSA;	/* cheat for key_to_blob */
1191		if (key_to_blob(key, &blob, &blen) == 0)
1192			fatal("%s: key_to_blob failed", __func__);
1193		buffer_put_string(m, blob, blen);
1194
1195		/* Save temporarily for comparison in verify */
1196		key_blob = blob;
1197		key_bloblen = blen;
1198		key_blobtype = MM_RSAUSERKEY;
1199	}
1200	if (key != NULL)
1201		key_free(key);
1202
1203	mm_request_send(sock, MONITOR_ANS_RSAKEYALLOWED, m);
1204
1205	monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
1206	monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 0);
1207	return (0);
1208}
1209
1210int
1211mm_answer_rsa_challenge(int sock, Buffer *m)
1212{
1213	Key *key = NULL;
1214	u_char *blob;
1215	u_int blen;
1216
1217	debug3("%s entering", __func__);
1218
1219	if (!authctxt->valid)
1220		fatal("%s: authctxt not valid", __func__);
1221	blob = buffer_get_string(m, &blen);
1222	if (!monitor_allowed_key(blob, blen))
1223		fatal("%s: bad key, not previously allowed", __func__);
1224	if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
1225		fatal("%s: key type mismatch", __func__);
1226	if ((key = key_from_blob(blob, blen)) == NULL)
1227		fatal("%s: received bad key", __func__);
1228	if (key->type != KEY_RSA)
1229		fatal("%s: received bad key type %d", __func__, key->type);
1230	key->type = KEY_RSA1;
1231	if (ssh1_challenge)
1232		BN_clear_free(ssh1_challenge);
1233	ssh1_challenge = auth_rsa_generate_challenge(key);
1234
1235	buffer_clear(m);
1236	buffer_put_bignum2(m, ssh1_challenge);
1237
1238	debug3("%s sending reply", __func__);
1239	mm_request_send(sock, MONITOR_ANS_RSACHALLENGE, m);
1240
1241	monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 1);
1242
1243	xfree(blob);
1244	key_free(key);
1245	return (0);
1246}
1247
1248int
1249mm_answer_rsa_response(int sock, Buffer *m)
1250{
1251	Key *key = NULL;
1252	u_char *blob, *response;
1253	u_int blen, len;
1254	int success;
1255
1256	debug3("%s entering", __func__);
1257
1258	if (!authctxt->valid)
1259		fatal("%s: authctxt not valid", __func__);
1260	if (ssh1_challenge == NULL)
1261		fatal("%s: no ssh1_challenge", __func__);
1262
1263	blob = buffer_get_string(m, &blen);
1264	if (!monitor_allowed_key(blob, blen))
1265		fatal("%s: bad key, not previously allowed", __func__);
1266	if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
1267		fatal("%s: key type mismatch: %d", __func__, key_blobtype);
1268	if ((key = key_from_blob(blob, blen)) == NULL)
1269		fatal("%s: received bad key", __func__);
1270	response = buffer_get_string(m, &len);
1271	if (len != 16)
1272		fatal("%s: received bad response to challenge", __func__);
1273	success = auth_rsa_verify_response(key, ssh1_challenge, response);
1274
1275	xfree(blob);
1276	key_free(key);
1277	xfree(response);
1278
1279	auth_method = key_blobtype == MM_RSAUSERKEY ? "rsa" : "rhosts-rsa";
1280
1281	/* reset state */
1282	BN_clear_free(ssh1_challenge);
1283	ssh1_challenge = NULL;
1284	monitor_reset_key_state();
1285
1286	buffer_clear(m);
1287	buffer_put_int(m, success);
1288	mm_request_send(sock, MONITOR_ANS_RSARESPONSE, m);
1289
1290	return (success);
1291}
1292
1293int
1294mm_answer_term(int sock, Buffer *req)
1295{
1296	extern struct monitor *pmonitor;
1297	int res, status;
1298
1299	debug3("%s: tearing down sessions", __func__);
1300
1301	/* The child is terminating */
1302	session_destroy_all(&mm_session_close);
1303
1304	while (waitpid(pmonitor->m_pid, &status, 0) == -1)
1305		if (errno != EINTR)
1306			exit(1);
1307
1308	res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1309
1310	/* Terminate process */
1311	exit(res);
1312}
1313
1314void
1315monitor_apply_keystate(struct monitor *pmonitor)
1316{
1317	if (compat20) {
1318		set_newkeys(MODE_IN);
1319		set_newkeys(MODE_OUT);
1320	} else {
1321		packet_set_protocol_flags(child_state.ssh1protoflags);
1322		packet_set_encryption_key(child_state.ssh1key,
1323		    child_state.ssh1keylen, child_state.ssh1cipher);
1324		xfree(child_state.ssh1key);
1325	}
1326
1327	/* for rc4 and other stateful ciphers */
1328	packet_set_keycontext(MODE_OUT, child_state.keyout);
1329	xfree(child_state.keyout);
1330	packet_set_keycontext(MODE_IN, child_state.keyin);
1331	xfree(child_state.keyin);
1332
1333	if (!compat20) {
1334		packet_set_iv(MODE_OUT, child_state.ivout);
1335		xfree(child_state.ivout);
1336		packet_set_iv(MODE_IN, child_state.ivin);
1337		xfree(child_state.ivin);
1338	}
1339
1340	memcpy(&incoming_stream, &child_state.incoming,
1341	    sizeof(incoming_stream));
1342	memcpy(&outgoing_stream, &child_state.outgoing,
1343	    sizeof(outgoing_stream));
1344
1345	/* Update with new address */
1346	if (options.compression)
1347		mm_init_compression(pmonitor->m_zlib);
1348
1349	/* Network I/O buffers */
1350	/* XXX inefficient for large buffers, need: buffer_init_from_string */
1351	buffer_clear(packet_get_input());
1352	buffer_append(packet_get_input(), child_state.input, child_state.ilen);
1353	memset(child_state.input, 0, child_state.ilen);
1354	xfree(child_state.input);
1355
1356	buffer_clear(packet_get_output());
1357	buffer_append(packet_get_output(), child_state.output,
1358		      child_state.olen);
1359	memset(child_state.output, 0, child_state.olen);
1360	xfree(child_state.output);
1361
1362	/* Roaming */
1363	if (compat20)
1364		roam_set_bytes(child_state.sent_bytes, child_state.recv_bytes);
1365}
1366
1367static Kex *
1368mm_get_kex(Buffer *m)
1369{
1370	Kex *kex;
1371	void *blob;
1372	u_int bloblen;
1373
1374	kex = xcalloc(1, sizeof(*kex));
1375	kex->session_id = buffer_get_string(m, &kex->session_id_len);
1376	if (session_id2 == NULL ||
1377	    kex->session_id_len != session_id2_len ||
1378	    timingsafe_bcmp(kex->session_id, session_id2, session_id2_len) != 0)
1379		fatal("mm_get_get: internal error: bad session id");
1380	kex->we_need = buffer_get_int(m);
1381	kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1382	kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1383	kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1384	kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1385	kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1386	kex->server = 1;
1387	kex->hostkey_type = buffer_get_int(m);
1388	kex->kex_type = buffer_get_int(m);
1389	blob = buffer_get_string(m, &bloblen);
1390	buffer_init(&kex->my);
1391	buffer_append(&kex->my, blob, bloblen);
1392	xfree(blob);
1393	blob = buffer_get_string(m, &bloblen);
1394	buffer_init(&kex->peer);
1395	buffer_append(&kex->peer, blob, bloblen);
1396	xfree(blob);
1397	kex->done = 1;
1398	kex->flags = buffer_get_int(m);
1399	kex->client_version_string = buffer_get_string(m, NULL);
1400	kex->server_version_string = buffer_get_string(m, NULL);
1401	kex->load_host_public_key=&get_hostkey_public_by_type;
1402	kex->load_host_private_key=&get_hostkey_private_by_type;
1403	kex->host_key_index=&get_hostkey_index;
1404
1405	return (kex);
1406}
1407
1408/* This function requries careful sanity checking */
1409
1410void
1411mm_get_keystate(struct monitor *pmonitor)
1412{
1413	Buffer m;
1414	u_char *blob, *p;
1415	u_int bloblen, plen;
1416	u_int32_t seqnr, packets;
1417	u_int64_t blocks, bytes;
1418
1419	debug3("%s: Waiting for new keys", __func__);
1420
1421	buffer_init(&m);
1422	mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT, &m);
1423	if (!compat20) {
1424		child_state.ssh1protoflags = buffer_get_int(&m);
1425		child_state.ssh1cipher = buffer_get_int(&m);
1426		child_state.ssh1key = buffer_get_string(&m,
1427		    &child_state.ssh1keylen);
1428		child_state.ivout = buffer_get_string(&m,
1429		    &child_state.ivoutlen);
1430		child_state.ivin = buffer_get_string(&m, &child_state.ivinlen);
1431		goto skip;
1432	} else {
1433		/* Get the Kex for rekeying */
1434		*pmonitor->m_pkex = mm_get_kex(&m);
1435	}
1436
1437	blob = buffer_get_string(&m, &bloblen);
1438	current_keys[MODE_OUT] = mm_newkeys_from_blob(blob, bloblen);
1439	xfree(blob);
1440
1441	debug3("%s: Waiting for second key", __func__);
1442	blob = buffer_get_string(&m, &bloblen);
1443	current_keys[MODE_IN] = mm_newkeys_from_blob(blob, bloblen);
1444	xfree(blob);
1445
1446	/* Now get sequence numbers for the packets */
1447	seqnr = buffer_get_int(&m);
1448	blocks = buffer_get_int64(&m);
1449	packets = buffer_get_int(&m);
1450	bytes = buffer_get_int64(&m);
1451	packet_set_state(MODE_OUT, seqnr, blocks, packets, bytes);
1452	seqnr = buffer_get_int(&m);
1453	blocks = buffer_get_int64(&m);
1454	packets = buffer_get_int(&m);
1455	bytes = buffer_get_int64(&m);
1456	packet_set_state(MODE_IN, seqnr, blocks, packets, bytes);
1457
1458 skip:
1459	/* Get the key context */
1460	child_state.keyout = buffer_get_string(&m, &child_state.keyoutlen);
1461	child_state.keyin  = buffer_get_string(&m, &child_state.keyinlen);
1462
1463	debug3("%s: Getting compression state", __func__);
1464	/* Get compression state */
1465	p = buffer_get_string(&m, &plen);
1466	if (plen != sizeof(child_state.outgoing))
1467		fatal("%s: bad request size", __func__);
1468	memcpy(&child_state.outgoing, p, sizeof(child_state.outgoing));
1469	xfree(p);
1470
1471	p = buffer_get_string(&m, &plen);
1472	if (plen != sizeof(child_state.incoming))
1473		fatal("%s: bad request size", __func__);
1474	memcpy(&child_state.incoming, p, sizeof(child_state.incoming));
1475	xfree(p);
1476
1477	/* Network I/O buffers */
1478	debug3("%s: Getting Network I/O buffers", __func__);
1479	child_state.input = buffer_get_string(&m, &child_state.ilen);
1480	child_state.output = buffer_get_string(&m, &child_state.olen);
1481
1482	/* Roaming */
1483	if (compat20) {
1484		child_state.sent_bytes = buffer_get_int64(&m);
1485		child_state.recv_bytes = buffer_get_int64(&m);
1486	}
1487
1488	buffer_free(&m);
1489}
1490
1491
1492/* Allocation functions for zlib */
1493void *
1494mm_zalloc(struct mm_master *mm, u_int ncount, u_int size)
1495{
1496	size_t len = (size_t) size * ncount;
1497	void *address;
1498
1499	if (len == 0 || ncount > SIZE_T_MAX / size)
1500		fatal("%s: mm_zalloc(%u, %u)", __func__, ncount, size);
1501
1502	address = mm_malloc(mm, len);
1503
1504	return (address);
1505}
1506
1507void
1508mm_zfree(struct mm_master *mm, void *address)
1509{
1510	mm_free(mm, address);
1511}
1512
1513void
1514mm_init_compression(struct mm_master *mm)
1515{
1516	outgoing_stream.zalloc = (alloc_func)mm_zalloc;
1517	outgoing_stream.zfree = (free_func)mm_zfree;
1518	outgoing_stream.opaque = mm;
1519
1520	incoming_stream.zalloc = (alloc_func)mm_zalloc;
1521	incoming_stream.zfree = (free_func)mm_zfree;
1522	incoming_stream.opaque = mm;
1523}
1524
1525/* XXX */
1526
1527#define FD_CLOSEONEXEC(x) do { \
1528	if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \
1529		fatal("fcntl(%d, F_SETFD)", x); \
1530} while (0)
1531
1532static void
1533monitor_socketpair(int *pair)
1534{
1535	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
1536		fatal("%s: socketpair", __func__);
1537	FD_CLOSEONEXEC(pair[0]);
1538	FD_CLOSEONEXEC(pair[1]);
1539}
1540
1541#define MM_MEMSIZE	65536
1542
1543struct monitor *
1544monitor_init(void)
1545{
1546	struct monitor *mon;
1547	int pair[2];
1548
1549	mon = xcalloc(1, sizeof(*mon));
1550
1551	monitor_socketpair(pair);
1552
1553	mon->m_recvfd = pair[0];
1554	mon->m_sendfd = pair[1];
1555
1556	/* Used to share zlib space across processes */
1557	if (options.compression) {
1558		mon->m_zback = mm_create(NULL, MM_MEMSIZE);
1559		mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE);
1560
1561		/* Compression needs to share state across borders */
1562		mm_init_compression(mon->m_zlib);
1563	}
1564
1565	return mon;
1566}
1567
1568void
1569monitor_reinit(struct monitor *mon)
1570{
1571	int pair[2];
1572
1573	monitor_socketpair(pair);
1574
1575	mon->m_recvfd = pair[0];
1576	mon->m_sendfd = pair[1];
1577}
1578
1579#ifdef GSSAPI
1580int
1581mm_answer_gss_setup_ctx(int sock, Buffer *m)
1582{
1583	gss_OID_desc goid;
1584	OM_uint32 major;
1585	u_int len;
1586
1587	goid.elements = buffer_get_string(m, &len);
1588	goid.length = len;
1589
1590	major = ssh_gssapi_server_ctx(&gsscontext, &goid);
1591
1592	xfree(goid.elements);
1593
1594	buffer_clear(m);
1595	buffer_put_int(m, major);
1596
1597	mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
1598
1599	/* Now we have a context, enable the step */
1600	monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
1601
1602	return (0);
1603}
1604
1605int
1606mm_answer_gss_accept_ctx(int sock, Buffer *m)
1607{
1608	gss_buffer_desc in;
1609	gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
1610	OM_uint32 major, minor;
1611	OM_uint32 flags = 0; /* GSI needs this */
1612	u_int len;
1613
1614	in.value = buffer_get_string(m, &len);
1615	in.length = len;
1616	major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
1617	xfree(in.value);
1618
1619	buffer_clear(m);
1620	buffer_put_int(m, major);
1621	buffer_put_string(m, out.value, out.length);
1622	buffer_put_int(m, flags);
1623	mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
1624
1625	gss_release_buffer(&minor, &out);
1626
1627	if (major == GSS_S_COMPLETE) {
1628		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
1629		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1630		monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
1631	}
1632	return (0);
1633}
1634
1635int
1636mm_answer_gss_checkmic(int sock, Buffer *m)
1637{
1638	gss_buffer_desc gssbuf, mic;
1639	OM_uint32 ret;
1640	u_int len;
1641
1642	gssbuf.value = buffer_get_string(m, &len);
1643	gssbuf.length = len;
1644	mic.value = buffer_get_string(m, &len);
1645	mic.length = len;
1646
1647	ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
1648
1649	xfree(gssbuf.value);
1650	xfree(mic.value);
1651
1652	buffer_clear(m);
1653	buffer_put_int(m, ret);
1654
1655	mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
1656
1657	if (!GSS_ERROR(ret))
1658		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1659
1660	return (0);
1661}
1662
1663int
1664mm_answer_gss_userok(int sock, Buffer *m)
1665{
1666	int authenticated;
1667
1668	authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
1669
1670	buffer_clear(m);
1671	buffer_put_int(m, authenticated);
1672
1673	debug3("%s: sending result %d", __func__, authenticated);
1674	mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
1675
1676	auth_method = "gssapi-with-mic";
1677
1678	/* Monitor loop will terminate if authenticated */
1679	return (authenticated);
1680}
1681#endif /* GSSAPI */
1682
1683#ifdef JPAKE
1684int
1685mm_answer_jpake_step1(int sock, Buffer *m)
1686{
1687	struct jpake_ctx *pctx;
1688	u_char *x3_proof, *x4_proof;
1689	u_int x3_proof_len, x4_proof_len;
1690
1691	if (!options.zero_knowledge_password_authentication)
1692		fatal("zero_knowledge_password_authentication disabled");
1693
1694	if (authctxt->jpake_ctx != NULL)
1695		fatal("%s: authctxt->jpake_ctx already set (%p)",
1696		    __func__, authctxt->jpake_ctx);
1697	authctxt->jpake_ctx = pctx = jpake_new();
1698
1699	jpake_step1(pctx->grp,
1700	    &pctx->server_id, &pctx->server_id_len,
1701	    &pctx->x3, &pctx->x4, &pctx->g_x3, &pctx->g_x4,
1702	    &x3_proof, &x3_proof_len,
1703	    &x4_proof, &x4_proof_len);
1704
1705	JPAKE_DEBUG_CTX((pctx, "step1 done in %s", __func__));
1706
1707	buffer_clear(m);
1708
1709	buffer_put_string(m, pctx->server_id, pctx->server_id_len);
1710	buffer_put_bignum2(m, pctx->g_x3);
1711	buffer_put_bignum2(m, pctx->g_x4);
1712	buffer_put_string(m, x3_proof, x3_proof_len);
1713	buffer_put_string(m, x4_proof, x4_proof_len);
1714
1715	debug3("%s: sending step1", __func__);
1716	mm_request_send(sock, MONITOR_ANS_JPAKE_STEP1, m);
1717
1718	bzero(x3_proof, x3_proof_len);
1719	bzero(x4_proof, x4_proof_len);
1720	xfree(x3_proof);
1721	xfree(x4_proof);
1722
1723	monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_GET_PWDATA, 1);
1724	monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_STEP1, 0);
1725
1726	return 0;
1727}
1728
1729int
1730mm_answer_jpake_get_pwdata(int sock, Buffer *m)
1731{
1732	struct jpake_ctx *pctx = authctxt->jpake_ctx;
1733	char *hash_scheme, *salt;
1734
1735	if (pctx == NULL)
1736		fatal("%s: pctx == NULL", __func__);
1737
1738	auth2_jpake_get_pwdata(authctxt, &pctx->s, &hash_scheme, &salt);
1739
1740	buffer_clear(m);
1741	/* pctx->s is sensitive, not returned to slave */
1742	buffer_put_cstring(m, hash_scheme);
1743	buffer_put_cstring(m, salt);
1744
1745	debug3("%s: sending pwdata", __func__);
1746	mm_request_send(sock, MONITOR_ANS_JPAKE_GET_PWDATA, m);
1747
1748	bzero(hash_scheme, strlen(hash_scheme));
1749	bzero(salt, strlen(salt));
1750	xfree(hash_scheme);
1751	xfree(salt);
1752
1753	monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_STEP2, 1);
1754
1755	return 0;
1756}
1757
1758int
1759mm_answer_jpake_step2(int sock, Buffer *m)
1760{
1761	struct jpake_ctx *pctx = authctxt->jpake_ctx;
1762	u_char *x1_proof, *x2_proof, *x4_s_proof;
1763	u_int x1_proof_len, x2_proof_len, x4_s_proof_len;
1764
1765	if (pctx == NULL)
1766		fatal("%s: pctx == NULL", __func__);
1767
1768	if ((pctx->g_x1 = BN_new()) == NULL ||
1769	    (pctx->g_x2 = BN_new()) == NULL)
1770		fatal("%s: BN_new", __func__);
1771	buffer_get_bignum2(m, pctx->g_x1);
1772	buffer_get_bignum2(m, pctx->g_x2);
1773	pctx->client_id = buffer_get_string(m, &pctx->client_id_len);
1774	x1_proof = buffer_get_string(m, &x1_proof_len);
1775	x2_proof = buffer_get_string(m, &x2_proof_len);
1776
1777	jpake_step2(pctx->grp, pctx->s, pctx->g_x3,
1778	    pctx->g_x1, pctx->g_x2, pctx->x4,
1779	    pctx->client_id, pctx->client_id_len,
1780	    pctx->server_id, pctx->server_id_len,
1781	    x1_proof, x1_proof_len,
1782	    x2_proof, x2_proof_len,
1783	    &pctx->b,
1784	    &x4_s_proof, &x4_s_proof_len);
1785
1786	JPAKE_DEBUG_CTX((pctx, "step2 done in %s", __func__));
1787
1788	bzero(x1_proof, x1_proof_len);
1789	bzero(x2_proof, x2_proof_len);
1790	xfree(x1_proof);
1791	xfree(x2_proof);
1792
1793	buffer_clear(m);
1794
1795	buffer_put_bignum2(m, pctx->b);
1796	buffer_put_string(m, x4_s_proof, x4_s_proof_len);
1797
1798	debug3("%s: sending step2", __func__);
1799	mm_request_send(sock, MONITOR_ANS_JPAKE_STEP2, m);
1800
1801	bzero(x4_s_proof, x4_s_proof_len);
1802	xfree(x4_s_proof);
1803
1804	monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_KEY_CONFIRM, 1);
1805
1806	return 0;
1807}
1808
1809int
1810mm_answer_jpake_key_confirm(int sock, Buffer *m)
1811{
1812	struct jpake_ctx *pctx = authctxt->jpake_ctx;
1813	u_char *x2_s_proof;
1814	u_int x2_s_proof_len;
1815
1816	if (pctx == NULL)
1817		fatal("%s: pctx == NULL", __func__);
1818
1819	if ((pctx->a = BN_new()) == NULL)
1820		fatal("%s: BN_new", __func__);
1821	buffer_get_bignum2(m, pctx->a);
1822	x2_s_proof = buffer_get_string(m, &x2_s_proof_len);
1823
1824	jpake_key_confirm(pctx->grp, pctx->s, pctx->a,
1825	    pctx->x4, pctx->g_x3, pctx->g_x4, pctx->g_x1, pctx->g_x2,
1826	    pctx->server_id, pctx->server_id_len,
1827	    pctx->client_id, pctx->client_id_len,
1828	    session_id2, session_id2_len,
1829	    x2_s_proof, x2_s_proof_len,
1830	    &pctx->k,
1831	    &pctx->h_k_sid_sessid, &pctx->h_k_sid_sessid_len);
1832
1833	JPAKE_DEBUG_CTX((pctx, "key_confirm done in %s", __func__));
1834
1835	bzero(x2_s_proof, x2_s_proof_len);
1836	buffer_clear(m);
1837
1838	/* pctx->k is sensitive, not sent */
1839	buffer_put_string(m, pctx->h_k_sid_sessid, pctx->h_k_sid_sessid_len);
1840
1841	debug3("%s: sending confirmation hash", __func__);
1842	mm_request_send(sock, MONITOR_ANS_JPAKE_KEY_CONFIRM, m);
1843
1844	monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_CHECK_CONFIRM, 1);
1845
1846	return 0;
1847}
1848
1849int
1850mm_answer_jpake_check_confirm(int sock, Buffer *m)
1851{
1852	int authenticated = 0;
1853	u_char *peer_confirm_hash;
1854	u_int peer_confirm_hash_len;
1855	struct jpake_ctx *pctx = authctxt->jpake_ctx;
1856
1857	if (pctx == NULL)
1858		fatal("%s: pctx == NULL", __func__);
1859
1860	peer_confirm_hash = buffer_get_string(m, &peer_confirm_hash_len);
1861
1862	authenticated = jpake_check_confirm(pctx->k,
1863	    pctx->client_id, pctx->client_id_len,
1864	    session_id2, session_id2_len,
1865	    peer_confirm_hash, peer_confirm_hash_len) && authctxt->valid;
1866
1867	JPAKE_DEBUG_CTX((pctx, "check_confirm done in %s", __func__));
1868
1869	bzero(peer_confirm_hash, peer_confirm_hash_len);
1870	xfree(peer_confirm_hash);
1871
1872	buffer_clear(m);
1873	buffer_put_int(m, authenticated);
1874
1875	debug3("%s: sending result %d", __func__, authenticated);
1876	mm_request_send(sock, MONITOR_ANS_JPAKE_CHECK_CONFIRM, m);
1877
1878	monitor_permit(mon_dispatch, MONITOR_REQ_JPAKE_STEP1, 1);
1879
1880	auth_method = "jpake-01@openssh.com";
1881	return authenticated;
1882}
1883
1884#endif /* JPAKE */
1885