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