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