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