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