xref: /openbsd-src/usr.bin/ssh/monitor.c (revision 0b7734b3d77bb9b21afec6f4621cae6c805dbd45)
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 <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 <limits.h>
41 #include <paths.h>
42 #include <poll.h>
43 #include <pwd.h>
44 #include <signal.h>
45 #include <stdarg.h>
46 #include <stdint.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 
51 #include "atomicio.h"
52 #include "xmalloc.h"
53 #include "ssh.h"
54 #include "key.h"
55 #include "buffer.h"
56 #include "hostfile.h"
57 #include "auth.h"
58 #include "cipher.h"
59 #include "kex.h"
60 #include "dh.h"
61 #include <zlib.h>
62 #include "packet.h"
63 #include "auth-options.h"
64 #include "sshpty.h"
65 #include "channels.h"
66 #include "session.h"
67 #include "sshlogin.h"
68 #include "canohost.h"
69 #include "log.h"
70 #include "misc.h"
71 #include "servconf.h"
72 #include "monitor.h"
73 #include "monitor_mm.h"
74 #ifdef GSSAPI
75 #include "ssh-gss.h"
76 #endif
77 #include "monitor_wrap.h"
78 #include "monitor_fdpass.h"
79 #include "compat.h"
80 #include "ssh2.h"
81 #include "authfd.h"
82 #include "match.h"
83 #include "ssherr.h"
84 
85 #ifdef GSSAPI
86 static Gssctxt *gsscontext = NULL;
87 #endif
88 
89 /* Imports */
90 extern ServerOptions options;
91 extern u_int utmp_len;
92 extern u_char session_id[];
93 extern Buffer auth_debug;
94 extern int auth_debug_init;
95 extern Buffer loginmsg;
96 
97 /* State exported from the child */
98 static struct sshbuf *child_state;
99 
100 /* Functions on the monitor that answer unprivileged requests */
101 
102 int mm_answer_moduli(int, Buffer *);
103 int mm_answer_sign(int, Buffer *);
104 int mm_answer_pwnamallow(int, Buffer *);
105 int mm_answer_auth2_read_banner(int, Buffer *);
106 int mm_answer_authserv(int, Buffer *);
107 int mm_answer_authpassword(int, Buffer *);
108 int mm_answer_bsdauthquery(int, Buffer *);
109 int mm_answer_bsdauthrespond(int, Buffer *);
110 int mm_answer_skeyquery(int, Buffer *);
111 int mm_answer_skeyrespond(int, Buffer *);
112 int mm_answer_keyallowed(int, Buffer *);
113 int mm_answer_keyverify(int, Buffer *);
114 int mm_answer_pty(int, Buffer *);
115 int mm_answer_pty_cleanup(int, Buffer *);
116 int mm_answer_term(int, Buffer *);
117 int mm_answer_rsa_keyallowed(int, Buffer *);
118 int mm_answer_rsa_challenge(int, Buffer *);
119 int mm_answer_rsa_response(int, Buffer *);
120 int mm_answer_sesskey(int, Buffer *);
121 int mm_answer_sessid(int, Buffer *);
122 
123 #ifdef GSSAPI
124 int mm_answer_gss_setup_ctx(int, Buffer *);
125 int mm_answer_gss_accept_ctx(int, Buffer *);
126 int mm_answer_gss_userok(int, Buffer *);
127 int mm_answer_gss_checkmic(int, Buffer *);
128 #endif
129 
130 static int monitor_read_log(struct monitor *);
131 
132 static Authctxt *authctxt;
133 
134 #ifdef WITH_SSH1
135 static BIGNUM *ssh1_challenge = NULL;	/* used for ssh1 rsa auth */
136 #endif
137 
138 /* local state for key verify */
139 static u_char *key_blob = NULL;
140 static u_int key_bloblen = 0;
141 static int key_blobtype = MM_NOKEY;
142 static char *hostbased_cuser = NULL;
143 static char *hostbased_chost = NULL;
144 static char *auth_method = "unknown";
145 static char *auth_submethod = NULL;
146 static u_int session_id2_len = 0;
147 static u_char *session_id2 = NULL;
148 static pid_t monitor_child_pid;
149 
150 struct 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 
165 struct 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 
187 struct 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 
198 struct 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 
214 struct 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 
223 struct mon_table *mon_dispatch;
224 
225 /* Specifies if a certain message is allowed at the moment */
226 
227 static void
228 monitor_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 
240 static void
241 monitor_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 
254 void
255 monitor_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 
338 static void
339 monitor_set_child_handler(pid_t pid)
340 {
341 	monitor_child_pid = pid;
342 }
343 
344 static void
345 monitor_child_handler(int sig)
346 {
347 	kill(monitor_child_pid, sig);
348 }
349 
350 void
351 monitor_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 
381 void
382 monitor_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 */
391 static void *
392 mm_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 
400 static void
401 mm_zfree(struct mm_master *mm, void *address)
402 {
403 	mm_free(mm, address);
404 }
405 
406 static int
407 monitor_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 
453 int
454 monitor_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 */
525 static int
526 monitor_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 
535 static void
536 monitor_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
550 int
551 mm_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 
586 int
587 mm_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 = NULL;
593 	u_char *p = NULL, *signature = NULL;
594 	char *alg = NULL;
595 	size_t datlen, siglen, alglen;
596 	int r, is_proof = 0;
597 	u_int keyid;
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 	if (keyid > INT_MAX)
607 		fatal("%s: invalid key ID", __func__);
608 
609 	/*
610 	 * Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes),
611 	 * SHA384 (48 bytes) and SHA512 (64 bytes).
612 	 *
613 	 * Otherwise, verify the signature request is for a hostkey
614 	 * proof.
615 	 *
616 	 * XXX perform similar check for KEX signature requests too?
617 	 * it's not trivial, since what is signed is the hash, rather
618 	 * than the full kex structure...
619 	 */
620 	if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64) {
621 		/*
622 		 * Construct expected hostkey proof and compare it to what
623 		 * the client sent us.
624 		 */
625 		if (session_id2_len == 0) /* hostkeys is never first */
626 			fatal("%s: bad data length: %zu", __func__, datlen);
627 		if ((key = get_hostkey_public_by_index(keyid, ssh)) == NULL)
628 			fatal("%s: no hostkey for index %d", __func__, keyid);
629 		if ((sigbuf = sshbuf_new()) == NULL)
630 			fatal("%s: sshbuf_new", __func__);
631 		if ((r = sshbuf_put_cstring(sigbuf, proof_req)) != 0 ||
632 		    (r = sshbuf_put_string(sigbuf, session_id2,
633 		    session_id2_len)) != 0 ||
634 		    (r = sshkey_puts(key, sigbuf)) != 0)
635 			fatal("%s: couldn't prepare private key "
636 			    "proof buffer: %s", __func__, ssh_err(r));
637 		if (datlen != sshbuf_len(sigbuf) ||
638 		    memcmp(p, sshbuf_ptr(sigbuf), sshbuf_len(sigbuf)) != 0)
639 			fatal("%s: bad data length: %zu, hostkey proof len %zu",
640 			    __func__, datlen, sshbuf_len(sigbuf));
641 		sshbuf_free(sigbuf);
642 		is_proof = 1;
643 	}
644 
645 	/* save session id, it will be passed on the first call */
646 	if (session_id2_len == 0) {
647 		session_id2_len = datlen;
648 		session_id2 = xmalloc(session_id2_len);
649 		memcpy(session_id2, p, session_id2_len);
650 	}
651 
652 	if ((key = get_hostkey_by_index(keyid)) != NULL) {
653 		if ((r = sshkey_sign(key, &signature, &siglen, p, datlen, alg,
654 		    datafellows)) != 0)
655 			fatal("%s: sshkey_sign failed: %s",
656 			    __func__, ssh_err(r));
657 	} else if ((key = get_hostkey_public_by_index(keyid, ssh)) != NULL &&
658 	    auth_sock > 0) {
659 		if ((r = ssh_agent_sign(auth_sock, key, &signature, &siglen,
660 		    p, datlen, alg, datafellows)) != 0) {
661 			fatal("%s: ssh_agent_sign failed: %s",
662 			    __func__, ssh_err(r));
663 		}
664 	} else
665 		fatal("%s: no hostkey from index %d", __func__, keyid);
666 
667 	debug3("%s: %s signature %p(%zu)", __func__,
668 	    is_proof ? "KEX" : "hostkey proof", signature, siglen);
669 
670 	sshbuf_reset(m);
671 	if ((r = sshbuf_put_string(m, signature, siglen)) != 0)
672 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
673 
674 	free(alg);
675 	free(p);
676 	free(signature);
677 
678 	mm_request_send(sock, MONITOR_ANS_SIGN, m);
679 
680 	/* Turn on permissions for getpwnam */
681 	monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
682 
683 	return (0);
684 }
685 
686 /* Retrieves the password entry and also checks if the user is permitted */
687 
688 int
689 mm_answer_pwnamallow(int sock, Buffer *m)
690 {
691 	char *username;
692 	struct passwd *pwent;
693 	int allowed = 0;
694 	u_int i;
695 
696 	debug3("%s", __func__);
697 
698 	if (authctxt->attempt++ != 0)
699 		fatal("%s: multiple attempts for getpwnam", __func__);
700 
701 	username = buffer_get_string(m, NULL);
702 
703 	pwent = getpwnamallow(username);
704 
705 	authctxt->user = xstrdup(username);
706 	setproctitle("%s [priv]", pwent ? username : "unknown");
707 	free(username);
708 
709 	buffer_clear(m);
710 
711 	if (pwent == NULL) {
712 		buffer_put_char(m, 0);
713 		authctxt->pw = fakepw();
714 		goto out;
715 	}
716 
717 	allowed = 1;
718 	authctxt->pw = pwent;
719 	authctxt->valid = 1;
720 
721 	buffer_put_char(m, 1);
722 	buffer_put_string(m, pwent, sizeof(struct passwd));
723 	buffer_put_cstring(m, pwent->pw_name);
724 	buffer_put_cstring(m, "*");
725 	buffer_put_cstring(m, pwent->pw_gecos);
726 	buffer_put_cstring(m, pwent->pw_class);
727 	buffer_put_cstring(m, pwent->pw_dir);
728 	buffer_put_cstring(m, pwent->pw_shell);
729 
730  out:
731 	buffer_put_string(m, &options, sizeof(options));
732 
733 #define M_CP_STROPT(x) do { \
734 		if (options.x != NULL) \
735 			buffer_put_cstring(m, options.x); \
736 	} while (0)
737 #define M_CP_STRARRAYOPT(x, nx) do { \
738 		for (i = 0; i < options.nx; i++) \
739 			buffer_put_cstring(m, options.x[i]); \
740 	} while (0)
741 	/* See comment in servconf.h */
742 	COPY_MATCH_STRING_OPTS();
743 #undef M_CP_STROPT
744 #undef M_CP_STRARRAYOPT
745 
746 	/* Create valid auth method lists */
747 	if (compat20 && auth2_setup_methods_lists(authctxt) != 0) {
748 		/*
749 		 * The monitor will continue long enough to let the child
750 		 * run to it's packet_disconnect(), but it must not allow any
751 		 * authentication to succeed.
752 		 */
753 		debug("%s: no valid authentication method lists", __func__);
754 	}
755 
756 	debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed);
757 	mm_request_send(sock, MONITOR_ANS_PWNAM, m);
758 
759 	/* For SSHv1 allow authentication now */
760 	if (!compat20)
761 		monitor_permit_authentications(1);
762 	else {
763 		/* Allow service/style information on the auth context */
764 		monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
765 		monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
766 	}
767 
768 	return (0);
769 }
770 
771 int mm_answer_auth2_read_banner(int sock, Buffer *m)
772 {
773 	char *banner;
774 
775 	buffer_clear(m);
776 	banner = auth2_read_banner();
777 	buffer_put_cstring(m, banner != NULL ? banner : "");
778 	mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
779 	free(banner);
780 
781 	return (0);
782 }
783 
784 int
785 mm_answer_authserv(int sock, Buffer *m)
786 {
787 	monitor_permit_authentications(1);
788 
789 	authctxt->service = buffer_get_string(m, NULL);
790 	authctxt->style = buffer_get_string(m, NULL);
791 	debug3("%s: service=%s, style=%s",
792 	    __func__, authctxt->service, authctxt->style);
793 
794 	if (strlen(authctxt->style) == 0) {
795 		free(authctxt->style);
796 		authctxt->style = NULL;
797 	}
798 
799 	return (0);
800 }
801 
802 int
803 mm_answer_authpassword(int sock, Buffer *m)
804 {
805 	static int call_count;
806 	char *passwd;
807 	int authenticated;
808 	u_int plen;
809 
810 	passwd = buffer_get_string(m, &plen);
811 	/* Only authenticate if the context is valid */
812 	authenticated = options.password_authentication &&
813 	    auth_password(authctxt, passwd);
814 	explicit_bzero(passwd, strlen(passwd));
815 	free(passwd);
816 
817 	buffer_clear(m);
818 	buffer_put_int(m, authenticated);
819 
820 	debug3("%s: sending result %d", __func__, authenticated);
821 	mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
822 
823 	call_count++;
824 	if (plen == 0 && call_count == 1)
825 		auth_method = "none";
826 	else
827 		auth_method = "password";
828 
829 	/* Causes monitor loop to terminate if authenticated */
830 	return (authenticated);
831 }
832 
833 int
834 mm_answer_bsdauthquery(int sock, Buffer *m)
835 {
836 	char *name, *infotxt;
837 	u_int numprompts;
838 	u_int *echo_on;
839 	char **prompts;
840 	u_int success;
841 
842 	success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
843 	    &prompts, &echo_on) < 0 ? 0 : 1;
844 
845 	buffer_clear(m);
846 	buffer_put_int(m, success);
847 	if (success)
848 		buffer_put_cstring(m, prompts[0]);
849 
850 	debug3("%s: sending challenge success: %u", __func__, success);
851 	mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
852 
853 	if (success) {
854 		free(name);
855 		free(infotxt);
856 		free(prompts);
857 		free(echo_on);
858 	}
859 
860 	return (0);
861 }
862 
863 int
864 mm_answer_bsdauthrespond(int sock, Buffer *m)
865 {
866 	char *response;
867 	int authok;
868 
869 	if (authctxt->as == NULL)
870 		fatal("%s: no bsd auth session", __func__);
871 
872 	response = buffer_get_string(m, NULL);
873 	authok = options.challenge_response_authentication &&
874 	    auth_userresponse(authctxt->as, response, 0);
875 	authctxt->as = NULL;
876 	debug3("%s: <%s> = <%d>", __func__, response, authok);
877 	free(response);
878 
879 	buffer_clear(m);
880 	buffer_put_int(m, authok);
881 
882 	debug3("%s: sending authenticated: %d", __func__, authok);
883 	mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
884 
885 	if (compat20) {
886 		auth_method = "keyboard-interactive";
887 		auth_submethod = "bsdauth";
888 	} else
889 		auth_method = "bsdauth";
890 
891 	return (authok != 0);
892 }
893 
894 int
895 mm_answer_keyallowed(int sock, Buffer *m)
896 {
897 	Key *key;
898 	char *cuser, *chost;
899 	u_char *blob;
900 	u_int bloblen, pubkey_auth_attempt;
901 	enum mm_keytype type = 0;
902 	int allowed = 0;
903 
904 	debug3("%s entering", __func__);
905 
906 	type = buffer_get_int(m);
907 	cuser = buffer_get_string(m, NULL);
908 	chost = buffer_get_string(m, NULL);
909 	blob = buffer_get_string(m, &bloblen);
910 	pubkey_auth_attempt = buffer_get_int(m);
911 
912 	key = key_from_blob(blob, bloblen);
913 
914 	if ((compat20 && type == MM_RSAHOSTKEY) ||
915 	    (!compat20 && type != MM_RSAHOSTKEY))
916 		fatal("%s: key type and protocol mismatch", __func__);
917 
918 	debug3("%s: key_from_blob: %p", __func__, key);
919 
920 	if (key != NULL && authctxt->valid) {
921 		/* These should not make it past the privsep child */
922 		if (key_type_plain(key->type) == KEY_RSA &&
923 		    (datafellows & SSH_BUG_RSASIGMD5) != 0)
924 			fatal("%s: passed a SSH_BUG_RSASIGMD5 key", __func__);
925 
926 		switch (type) {
927 		case MM_USERKEY:
928 			allowed = options.pubkey_authentication &&
929 			    !auth2_userkey_already_used(authctxt, key) &&
930 			    match_pattern_list(sshkey_ssh_name(key),
931 			    options.pubkey_key_types, 0) == 1 &&
932 			    user_key_allowed(authctxt->pw, key,
933 			    pubkey_auth_attempt);
934 			pubkey_auth_info(authctxt, key, NULL);
935 			auth_method = "publickey";
936 			if (options.pubkey_authentication &&
937 			    (!pubkey_auth_attempt || allowed != 1))
938 				auth_clear_options();
939 			break;
940 		case MM_HOSTKEY:
941 			allowed = options.hostbased_authentication &&
942 			    match_pattern_list(sshkey_ssh_name(key),
943 			    options.hostbased_key_types, 0) == 1 &&
944 			    hostbased_key_allowed(authctxt->pw,
945 			    cuser, chost, key);
946 			pubkey_auth_info(authctxt, key,
947 			    "client user \"%.100s\", client host \"%.100s\"",
948 			    cuser, chost);
949 			auth_method = "hostbased";
950 			break;
951 #ifdef WITH_SSH1
952 		case MM_RSAHOSTKEY:
953 			key->type = KEY_RSA1; /* XXX */
954 			allowed = options.rhosts_rsa_authentication &&
955 			    auth_rhosts_rsa_key_allowed(authctxt->pw,
956 			    cuser, chost, key);
957 			if (options.rhosts_rsa_authentication && allowed != 1)
958 				auth_clear_options();
959 			auth_method = "rsa";
960 			break;
961 #endif
962 		default:
963 			fatal("%s: unknown key type %d", __func__, type);
964 			break;
965 		}
966 	}
967 
968 	debug3("%s: key %p is %s",
969 	    __func__, key, allowed ? "allowed" : "not allowed");
970 
971 	if (key != NULL)
972 		key_free(key);
973 
974 	/* clear temporarily storage (used by verify) */
975 	monitor_reset_key_state();
976 
977 	if (allowed) {
978 		/* Save temporarily for comparison in verify */
979 		key_blob = blob;
980 		key_bloblen = bloblen;
981 		key_blobtype = type;
982 		hostbased_cuser = cuser;
983 		hostbased_chost = chost;
984 	} else {
985 		/* Log failed attempt */
986 		auth_log(authctxt, 0, 0, auth_method, NULL);
987 		free(blob);
988 		free(cuser);
989 		free(chost);
990 	}
991 
992 	buffer_clear(m);
993 	buffer_put_int(m, allowed);
994 	buffer_put_int(m, forced_command != NULL);
995 
996 	mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
997 
998 	if (type == MM_RSAHOSTKEY)
999 		monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
1000 
1001 	return (0);
1002 }
1003 
1004 static int
1005 monitor_valid_userblob(u_char *data, u_int datalen)
1006 {
1007 	Buffer b;
1008 	u_char *p;
1009 	char *userstyle, *cp;
1010 	u_int len;
1011 	int fail = 0;
1012 
1013 	buffer_init(&b);
1014 	buffer_append(&b, data, datalen);
1015 
1016 	if (datafellows & SSH_OLD_SESSIONID) {
1017 		p = buffer_ptr(&b);
1018 		len = buffer_len(&b);
1019 		if ((session_id2 == NULL) ||
1020 		    (len < session_id2_len) ||
1021 		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1022 			fail++;
1023 		buffer_consume(&b, session_id2_len);
1024 	} else {
1025 		p = buffer_get_string(&b, &len);
1026 		if ((session_id2 == NULL) ||
1027 		    (len != session_id2_len) ||
1028 		    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1029 			fail++;
1030 		free(p);
1031 	}
1032 	if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
1033 		fail++;
1034 	cp = buffer_get_cstring(&b, NULL);
1035 	xasprintf(&userstyle, "%s%s%s", authctxt->user,
1036 	    authctxt->style ? ":" : "",
1037 	    authctxt->style ? authctxt->style : "");
1038 	if (strcmp(userstyle, cp) != 0) {
1039 		logit("wrong user name passed to monitor: "
1040 		    "expected %s != %.100s", userstyle, cp);
1041 		fail++;
1042 	}
1043 	free(userstyle);
1044 	free(cp);
1045 	buffer_skip_string(&b);
1046 	if (datafellows & SSH_BUG_PKAUTH) {
1047 		if (!buffer_get_char(&b))
1048 			fail++;
1049 	} else {
1050 		cp = buffer_get_cstring(&b, NULL);
1051 		if (strcmp("publickey", cp) != 0)
1052 			fail++;
1053 		free(cp);
1054 		if (!buffer_get_char(&b))
1055 			fail++;
1056 		buffer_skip_string(&b);
1057 	}
1058 	buffer_skip_string(&b);
1059 	if (buffer_len(&b) != 0)
1060 		fail++;
1061 	buffer_free(&b);
1062 	return (fail == 0);
1063 }
1064 
1065 static int
1066 monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
1067     char *chost)
1068 {
1069 	Buffer b;
1070 	char *p, *userstyle;
1071 	u_int len;
1072 	int fail = 0;
1073 
1074 	buffer_init(&b);
1075 	buffer_append(&b, data, datalen);
1076 
1077 	p = buffer_get_string(&b, &len);
1078 	if ((session_id2 == NULL) ||
1079 	    (len != session_id2_len) ||
1080 	    (timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
1081 		fail++;
1082 	free(p);
1083 
1084 	if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
1085 		fail++;
1086 	p = buffer_get_cstring(&b, NULL);
1087 	xasprintf(&userstyle, "%s%s%s", authctxt->user,
1088 	    authctxt->style ? ":" : "",
1089 	    authctxt->style ? authctxt->style : "");
1090 	if (strcmp(userstyle, p) != 0) {
1091 		logit("wrong user name passed to monitor: expected %s != %.100s",
1092 		    userstyle, p);
1093 		fail++;
1094 	}
1095 	free(userstyle);
1096 	free(p);
1097 	buffer_skip_string(&b);	/* service */
1098 	p = buffer_get_cstring(&b, NULL);
1099 	if (strcmp(p, "hostbased") != 0)
1100 		fail++;
1101 	free(p);
1102 	buffer_skip_string(&b);	/* pkalg */
1103 	buffer_skip_string(&b);	/* pkblob */
1104 
1105 	/* verify client host, strip trailing dot if necessary */
1106 	p = buffer_get_string(&b, NULL);
1107 	if (((len = strlen(p)) > 0) && p[len - 1] == '.')
1108 		p[len - 1] = '\0';
1109 	if (strcmp(p, chost) != 0)
1110 		fail++;
1111 	free(p);
1112 
1113 	/* verify client user */
1114 	p = buffer_get_string(&b, NULL);
1115 	if (strcmp(p, cuser) != 0)
1116 		fail++;
1117 	free(p);
1118 
1119 	if (buffer_len(&b) != 0)
1120 		fail++;
1121 	buffer_free(&b);
1122 	return (fail == 0);
1123 }
1124 
1125 int
1126 mm_answer_keyverify(int sock, Buffer *m)
1127 {
1128 	Key *key;
1129 	u_char *signature, *data, *blob;
1130 	u_int signaturelen, datalen, bloblen;
1131 	int verified = 0;
1132 	int valid_data = 0;
1133 
1134 	blob = buffer_get_string(m, &bloblen);
1135 	signature = buffer_get_string(m, &signaturelen);
1136 	data = buffer_get_string(m, &datalen);
1137 
1138 	if (hostbased_cuser == NULL || hostbased_chost == NULL ||
1139 	  !monitor_allowed_key(blob, bloblen))
1140 		fatal("%s: bad key, not previously allowed", __func__);
1141 
1142 	key = key_from_blob(blob, bloblen);
1143 	if (key == NULL)
1144 		fatal("%s: bad public key blob", __func__);
1145 
1146 	switch (key_blobtype) {
1147 	case MM_USERKEY:
1148 		valid_data = monitor_valid_userblob(data, datalen);
1149 		break;
1150 	case MM_HOSTKEY:
1151 		valid_data = monitor_valid_hostbasedblob(data, datalen,
1152 		    hostbased_cuser, hostbased_chost);
1153 		break;
1154 	default:
1155 		valid_data = 0;
1156 		break;
1157 	}
1158 	if (!valid_data)
1159 		fatal("%s: bad signature data blob", __func__);
1160 
1161 	verified = key_verify(key, signature, signaturelen, data, datalen);
1162 	debug3("%s: key %p signature %s",
1163 	    __func__, key, (verified == 1) ? "verified" : "unverified");
1164 
1165 	/* If auth was successful then record key to ensure it isn't reused */
1166 	if (verified == 1 && key_blobtype == MM_USERKEY)
1167 		auth2_record_userkey(authctxt, key);
1168 	else
1169 		key_free(key);
1170 
1171 	free(blob);
1172 	free(signature);
1173 	free(data);
1174 
1175 	auth_method = key_blobtype == MM_USERKEY ? "publickey" : "hostbased";
1176 
1177 	monitor_reset_key_state();
1178 
1179 	buffer_clear(m);
1180 	buffer_put_int(m, verified);
1181 	mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
1182 
1183 	return (verified == 1);
1184 }
1185 
1186 static void
1187 mm_record_login(Session *s, struct passwd *pw)
1188 {
1189 	struct ssh *ssh = active_state;	/* XXX */
1190 	socklen_t fromlen;
1191 	struct sockaddr_storage from;
1192 
1193 	if (options.use_login)
1194 		return;
1195 
1196 	/*
1197 	 * Get IP address of client. If the connection is not a socket, let
1198 	 * the address be 0.0.0.0.
1199 	 */
1200 	memset(&from, 0, sizeof(from));
1201 	fromlen = sizeof(from);
1202 	if (packet_connection_is_on_socket()) {
1203 		if (getpeername(packet_get_connection_in(),
1204 		    (struct sockaddr *)&from, &fromlen) < 0) {
1205 			debug("getpeername: %.100s", strerror(errno));
1206 			cleanup_exit(255);
1207 		}
1208 	}
1209 	/* Record that there was a login on that tty from the remote host. */
1210 	record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
1211 	    session_get_remote_name_or_ip(ssh, utmp_len, options.use_dns),
1212 	    (struct sockaddr *)&from, fromlen);
1213 }
1214 
1215 static void
1216 mm_session_close(Session *s)
1217 {
1218 	debug3("%s: session %d pid %ld", __func__, s->self, (long)s->pid);
1219 	if (s->ttyfd != -1) {
1220 		debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ptyfd);
1221 		session_pty_cleanup2(s);
1222 	}
1223 	session_unused(s->self);
1224 }
1225 
1226 int
1227 mm_answer_pty(int sock, Buffer *m)
1228 {
1229 	extern struct monitor *pmonitor;
1230 	Session *s;
1231 	int res, fd0;
1232 
1233 	debug3("%s entering", __func__);
1234 
1235 	buffer_clear(m);
1236 	s = session_new();
1237 	if (s == NULL)
1238 		goto error;
1239 	s->authctxt = authctxt;
1240 	s->pw = authctxt->pw;
1241 	s->pid = pmonitor->m_pid;
1242 	res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
1243 	if (res == 0)
1244 		goto error;
1245 	pty_setowner(authctxt->pw, s->tty);
1246 
1247 	buffer_put_int(m, 1);
1248 	buffer_put_cstring(m, s->tty);
1249 
1250 	/* We need to trick ttyslot */
1251 	if (dup2(s->ttyfd, 0) == -1)
1252 		fatal("%s: dup2", __func__);
1253 
1254 	mm_record_login(s, authctxt->pw);
1255 
1256 	/* Now we can close the file descriptor again */
1257 	close(0);
1258 
1259 	/* send messages generated by record_login */
1260 	buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
1261 	buffer_clear(&loginmsg);
1262 
1263 	mm_request_send(sock, MONITOR_ANS_PTY, m);
1264 
1265 	if (mm_send_fd(sock, s->ptyfd) == -1 ||
1266 	    mm_send_fd(sock, s->ttyfd) == -1)
1267 		fatal("%s: send fds failed", __func__);
1268 
1269 	/* make sure nothing uses fd 0 */
1270 	if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0)
1271 		fatal("%s: open(/dev/null): %s", __func__, strerror(errno));
1272 	if (fd0 != 0)
1273 		error("%s: fd0 %d != 0", __func__, fd0);
1274 
1275 	/* slave is not needed */
1276 	close(s->ttyfd);
1277 	s->ttyfd = s->ptyfd;
1278 	/* no need to dup() because nobody closes ptyfd */
1279 	s->ptymaster = s->ptyfd;
1280 
1281 	debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd);
1282 
1283 	return (0);
1284 
1285  error:
1286 	if (s != NULL)
1287 		mm_session_close(s);
1288 	buffer_put_int(m, 0);
1289 	mm_request_send(sock, MONITOR_ANS_PTY, m);
1290 	return (0);
1291 }
1292 
1293 int
1294 mm_answer_pty_cleanup(int sock, Buffer *m)
1295 {
1296 	Session *s;
1297 	char *tty;
1298 
1299 	debug3("%s entering", __func__);
1300 
1301 	tty = buffer_get_string(m, NULL);
1302 	if ((s = session_by_tty(tty)) != NULL)
1303 		mm_session_close(s);
1304 	buffer_clear(m);
1305 	free(tty);
1306 	return (0);
1307 }
1308 
1309 #ifdef WITH_SSH1
1310 int
1311 mm_answer_sesskey(int sock, Buffer *m)
1312 {
1313 	BIGNUM *p;
1314 	int rsafail;
1315 
1316 	/* Turn off permissions */
1317 	monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 0);
1318 
1319 	if ((p = BN_new()) == NULL)
1320 		fatal("%s: BN_new", __func__);
1321 
1322 	buffer_get_bignum2(m, p);
1323 
1324 	rsafail = ssh1_session_key(p);
1325 
1326 	buffer_clear(m);
1327 	buffer_put_int(m, rsafail);
1328 	buffer_put_bignum2(m, p);
1329 
1330 	BN_clear_free(p);
1331 
1332 	mm_request_send(sock, MONITOR_ANS_SESSKEY, m);
1333 
1334 	/* Turn on permissions for sessid passing */
1335 	monitor_permit(mon_dispatch, MONITOR_REQ_SESSID, 1);
1336 
1337 	return (0);
1338 }
1339 
1340 int
1341 mm_answer_sessid(int sock, Buffer *m)
1342 {
1343 	int i;
1344 
1345 	debug3("%s entering", __func__);
1346 
1347 	if (buffer_len(m) != 16)
1348 		fatal("%s: bad ssh1 session id", __func__);
1349 	for (i = 0; i < 16; i++)
1350 		session_id[i] = buffer_get_char(m);
1351 
1352 	/* Turn on permissions for getpwnam */
1353 	monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
1354 
1355 	return (0);
1356 }
1357 
1358 int
1359 mm_answer_rsa_keyallowed(int sock, Buffer *m)
1360 {
1361 	BIGNUM *client_n;
1362 	Key *key = NULL;
1363 	u_char *blob = NULL;
1364 	u_int blen = 0;
1365 	int allowed = 0;
1366 
1367 	debug3("%s entering", __func__);
1368 
1369 	auth_method = "rsa";
1370 	if (options.rsa_authentication && authctxt->valid) {
1371 		if ((client_n = BN_new()) == NULL)
1372 			fatal("%s: BN_new", __func__);
1373 		buffer_get_bignum2(m, client_n);
1374 		allowed = auth_rsa_key_allowed(authctxt->pw, client_n, &key);
1375 		BN_clear_free(client_n);
1376 	}
1377 	buffer_clear(m);
1378 	buffer_put_int(m, allowed);
1379 	buffer_put_int(m, forced_command != NULL);
1380 
1381 	/* clear temporarily storage (used by generate challenge) */
1382 	monitor_reset_key_state();
1383 
1384 	if (allowed && key != NULL) {
1385 		key->type = KEY_RSA;	/* cheat for key_to_blob */
1386 		if (key_to_blob(key, &blob, &blen) == 0)
1387 			fatal("%s: key_to_blob failed", __func__);
1388 		buffer_put_string(m, blob, blen);
1389 
1390 		/* Save temporarily for comparison in verify */
1391 		key_blob = blob;
1392 		key_bloblen = blen;
1393 		key_blobtype = MM_RSAUSERKEY;
1394 	}
1395 	if (key != NULL)
1396 		key_free(key);
1397 
1398 	mm_request_send(sock, MONITOR_ANS_RSAKEYALLOWED, m);
1399 
1400 	monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
1401 	monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 0);
1402 	return (0);
1403 }
1404 
1405 int
1406 mm_answer_rsa_challenge(int sock, Buffer *m)
1407 {
1408 	Key *key = NULL;
1409 	u_char *blob;
1410 	u_int blen;
1411 
1412 	debug3("%s entering", __func__);
1413 
1414 	if (!authctxt->valid)
1415 		fatal("%s: authctxt not valid", __func__);
1416 	blob = buffer_get_string(m, &blen);
1417 	if (!monitor_allowed_key(blob, blen))
1418 		fatal("%s: bad key, not previously allowed", __func__);
1419 	if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
1420 		fatal("%s: key type mismatch", __func__);
1421 	if ((key = key_from_blob(blob, blen)) == NULL)
1422 		fatal("%s: received bad key", __func__);
1423 	if (key->type != KEY_RSA)
1424 		fatal("%s: received bad key type %d", __func__, key->type);
1425 	key->type = KEY_RSA1;
1426 	if (ssh1_challenge)
1427 		BN_clear_free(ssh1_challenge);
1428 	ssh1_challenge = auth_rsa_generate_challenge(key);
1429 
1430 	buffer_clear(m);
1431 	buffer_put_bignum2(m, ssh1_challenge);
1432 
1433 	debug3("%s sending reply", __func__);
1434 	mm_request_send(sock, MONITOR_ANS_RSACHALLENGE, m);
1435 
1436 	monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 1);
1437 
1438 	free(blob);
1439 	key_free(key);
1440 	return (0);
1441 }
1442 
1443 int
1444 mm_answer_rsa_response(int sock, Buffer *m)
1445 {
1446 	Key *key = NULL;
1447 	u_char *blob, *response;
1448 	u_int blen, len;
1449 	int success;
1450 
1451 	debug3("%s entering", __func__);
1452 
1453 	if (!authctxt->valid)
1454 		fatal("%s: authctxt not valid", __func__);
1455 	if (ssh1_challenge == NULL)
1456 		fatal("%s: no ssh1_challenge", __func__);
1457 
1458 	blob = buffer_get_string(m, &blen);
1459 	if (!monitor_allowed_key(blob, blen))
1460 		fatal("%s: bad key, not previously allowed", __func__);
1461 	if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
1462 		fatal("%s: key type mismatch: %d", __func__, key_blobtype);
1463 	if ((key = key_from_blob(blob, blen)) == NULL)
1464 		fatal("%s: received bad key", __func__);
1465 	response = buffer_get_string(m, &len);
1466 	if (len != 16)
1467 		fatal("%s: received bad response to challenge", __func__);
1468 	success = auth_rsa_verify_response(key, ssh1_challenge, response);
1469 
1470 	free(blob);
1471 	key_free(key);
1472 	free(response);
1473 
1474 	auth_method = key_blobtype == MM_RSAUSERKEY ? "rsa" : "rhosts-rsa";
1475 
1476 	/* reset state */
1477 	BN_clear_free(ssh1_challenge);
1478 	ssh1_challenge = NULL;
1479 	monitor_reset_key_state();
1480 
1481 	buffer_clear(m);
1482 	buffer_put_int(m, success);
1483 	mm_request_send(sock, MONITOR_ANS_RSARESPONSE, m);
1484 
1485 	return (success);
1486 }
1487 #endif
1488 
1489 int
1490 mm_answer_term(int sock, Buffer *req)
1491 {
1492 	extern struct monitor *pmonitor;
1493 	int res, status;
1494 
1495 	debug3("%s: tearing down sessions", __func__);
1496 
1497 	/* The child is terminating */
1498 	session_destroy_all(&mm_session_close);
1499 
1500 	while (waitpid(pmonitor->m_pid, &status, 0) == -1)
1501 		if (errno != EINTR)
1502 			exit(1);
1503 
1504 	res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1505 
1506 	/* Terminate process */
1507 	exit(res);
1508 }
1509 
1510 void
1511 monitor_apply_keystate(struct monitor *pmonitor)
1512 {
1513 	struct ssh *ssh = active_state;	/* XXX */
1514 	struct kex *kex;
1515 	int r;
1516 
1517 	debug3("%s: packet_set_state", __func__);
1518 	if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
1519                 fatal("%s: packet_set_state: %s", __func__, ssh_err(r));
1520 	sshbuf_free(child_state);
1521 	child_state = NULL;
1522 
1523 	if ((kex = ssh->kex) != NULL) {
1524 		/* XXX set callbacks */
1525 #ifdef WITH_OPENSSL
1526 		kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1527 		kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1528 		kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
1529 		kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
1530 		kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
1531 		kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1532 		kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1533 		kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1534 #endif
1535 		kex->kex[KEX_C25519_SHA256] = kexc25519_server;
1536 		kex->load_host_public_key=&get_hostkey_public_by_type;
1537 		kex->load_host_private_key=&get_hostkey_private_by_type;
1538 		kex->host_key_index=&get_hostkey_index;
1539 		kex->sign = sshd_hostkey_sign;
1540 	}
1541 
1542 	/* Update with new address */
1543 	if (options.compression) {
1544 		ssh_packet_set_compress_hooks(ssh, pmonitor->m_zlib,
1545 		    (ssh_packet_comp_alloc_func *)mm_zalloc,
1546 		    (ssh_packet_comp_free_func *)mm_zfree);
1547 	}
1548 }
1549 
1550 /* This function requries careful sanity checking */
1551 
1552 void
1553 mm_get_keystate(struct monitor *pmonitor)
1554 {
1555 	debug3("%s: Waiting for new keys", __func__);
1556 
1557 	if ((child_state = sshbuf_new()) == NULL)
1558 		fatal("%s: sshbuf_new failed", __func__);
1559 	mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT,
1560 	    child_state);
1561 	debug3("%s: GOT new keys", __func__);
1562 }
1563 
1564 
1565 /* XXX */
1566 
1567 #define FD_CLOSEONEXEC(x) do { \
1568 	if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \
1569 		fatal("fcntl(%d, F_SETFD)", x); \
1570 } while (0)
1571 
1572 static void
1573 monitor_openfds(struct monitor *mon, int do_logfds)
1574 {
1575 	int pair[2];
1576 
1577 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
1578 		fatal("%s: socketpair: %s", __func__, strerror(errno));
1579 	FD_CLOSEONEXEC(pair[0]);
1580 	FD_CLOSEONEXEC(pair[1]);
1581 	mon->m_recvfd = pair[0];
1582 	mon->m_sendfd = pair[1];
1583 
1584 	if (do_logfds) {
1585 		if (pipe(pair) == -1)
1586 			fatal("%s: pipe: %s", __func__, strerror(errno));
1587 		FD_CLOSEONEXEC(pair[0]);
1588 		FD_CLOSEONEXEC(pair[1]);
1589 		mon->m_log_recvfd = pair[0];
1590 		mon->m_log_sendfd = pair[1];
1591 	} else
1592 		mon->m_log_recvfd = mon->m_log_sendfd = -1;
1593 }
1594 
1595 #define MM_MEMSIZE	65536
1596 
1597 struct monitor *
1598 monitor_init(void)
1599 {
1600 	struct ssh *ssh = active_state;			/* XXX */
1601 	struct monitor *mon;
1602 
1603 	mon = xcalloc(1, sizeof(*mon));
1604 
1605 	monitor_openfds(mon, 1);
1606 
1607 	/* Used to share zlib space across processes */
1608 	if (options.compression) {
1609 		mon->m_zback = mm_create(NULL, MM_MEMSIZE);
1610 		mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE);
1611 
1612 		/* Compression needs to share state across borders */
1613 		ssh_packet_set_compress_hooks(ssh, mon->m_zlib,
1614 		    (ssh_packet_comp_alloc_func *)mm_zalloc,
1615 		    (ssh_packet_comp_free_func *)mm_zfree);
1616 	}
1617 
1618 	return mon;
1619 }
1620 
1621 void
1622 monitor_reinit(struct monitor *mon)
1623 {
1624 	monitor_openfds(mon, 0);
1625 }
1626 
1627 #ifdef GSSAPI
1628 int
1629 mm_answer_gss_setup_ctx(int sock, Buffer *m)
1630 {
1631 	gss_OID_desc goid;
1632 	OM_uint32 major;
1633 	u_int len;
1634 
1635 	goid.elements = buffer_get_string(m, &len);
1636 	goid.length = len;
1637 
1638 	major = ssh_gssapi_server_ctx(&gsscontext, &goid);
1639 
1640 	free(goid.elements);
1641 
1642 	buffer_clear(m);
1643 	buffer_put_int(m, major);
1644 
1645 	mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
1646 
1647 	/* Now we have a context, enable the step */
1648 	monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
1649 
1650 	return (0);
1651 }
1652 
1653 int
1654 mm_answer_gss_accept_ctx(int sock, Buffer *m)
1655 {
1656 	gss_buffer_desc in;
1657 	gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
1658 	OM_uint32 major, minor;
1659 	OM_uint32 flags = 0; /* GSI needs this */
1660 	u_int len;
1661 
1662 	in.value = buffer_get_string(m, &len);
1663 	in.length = len;
1664 	major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
1665 	free(in.value);
1666 
1667 	buffer_clear(m);
1668 	buffer_put_int(m, major);
1669 	buffer_put_string(m, out.value, out.length);
1670 	buffer_put_int(m, flags);
1671 	mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
1672 
1673 	gss_release_buffer(&minor, &out);
1674 
1675 	if (major == GSS_S_COMPLETE) {
1676 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
1677 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1678 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
1679 	}
1680 	return (0);
1681 }
1682 
1683 int
1684 mm_answer_gss_checkmic(int sock, Buffer *m)
1685 {
1686 	gss_buffer_desc gssbuf, mic;
1687 	OM_uint32 ret;
1688 	u_int len;
1689 
1690 	gssbuf.value = buffer_get_string(m, &len);
1691 	gssbuf.length = len;
1692 	mic.value = buffer_get_string(m, &len);
1693 	mic.length = len;
1694 
1695 	ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
1696 
1697 	free(gssbuf.value);
1698 	free(mic.value);
1699 
1700 	buffer_clear(m);
1701 	buffer_put_int(m, ret);
1702 
1703 	mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
1704 
1705 	if (!GSS_ERROR(ret))
1706 		monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
1707 
1708 	return (0);
1709 }
1710 
1711 int
1712 mm_answer_gss_userok(int sock, Buffer *m)
1713 {
1714 	int authenticated;
1715 
1716 	authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
1717 
1718 	buffer_clear(m);
1719 	buffer_put_int(m, authenticated);
1720 
1721 	debug3("%s: sending result %d", __func__, authenticated);
1722 	mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
1723 
1724 	auth_method = "gssapi-with-mic";
1725 
1726 	/* Monitor loop will terminate if authenticated */
1727 	return (authenticated);
1728 }
1729 #endif /* GSSAPI */
1730 
1731