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