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