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