xref: /freebsd/crypto/openssh/auth.c (revision 716fd348e01c5f2ba125f878a634a753436c2994)
1 /* $OpenBSD: auth.c,v 1.154 2022/02/23 11:17:10 djm Exp $ */
2 /*
3  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 
26 #include "includes.h"
27 
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/socket.h>
31 #include <sys/wait.h>
32 
33 #include <netinet/in.h>
34 
35 #include <stdlib.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #ifdef HAVE_PATHS_H
39 # include <paths.h>
40 #endif
41 #include <pwd.h>
42 #ifdef HAVE_LOGIN_H
43 #include <login.h>
44 #endif
45 #ifdef USE_SHADOW
46 #include <shadow.h>
47 #endif
48 #include <stdarg.h>
49 #include <stdio.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <limits.h>
53 #include <netdb.h>
54 #include <time.h>
55 
56 #include "xmalloc.h"
57 #include "match.h"
58 #include "groupaccess.h"
59 #include "log.h"
60 #include "sshbuf.h"
61 #include "misc.h"
62 #include "servconf.h"
63 #include "sshkey.h"
64 #include "hostfile.h"
65 #include "auth.h"
66 #include "auth-options.h"
67 #include "canohost.h"
68 #include "uidswap.h"
69 #include "packet.h"
70 #include "loginrec.h"
71 #ifdef GSSAPI
72 #include "ssh-gss.h"
73 #endif
74 #include "authfile.h"
75 #include "monitor_wrap.h"
76 #include "ssherr.h"
77 #include "compat.h"
78 #include "channels.h"
79 #include "blacklist_client.h"
80 
81 /* import */
82 extern ServerOptions options;
83 extern struct include_list includes;
84 extern int use_privsep;
85 extern struct sshbuf *loginmsg;
86 extern struct passwd *privsep_pw;
87 extern struct sshauthopt *auth_opts;
88 
89 /* Debugging messages */
90 static struct sshbuf *auth_debug;
91 
92 /*
93  * Check if the user is allowed to log in via ssh. If user is listed
94  * in DenyUsers or one of user's groups is listed in DenyGroups, false
95  * will be returned. If AllowUsers isn't empty and user isn't listed
96  * there, or if AllowGroups isn't empty and one of user's groups isn't
97  * listed there, false will be returned.
98  * If the user's shell is not executable, false will be returned.
99  * Otherwise true is returned.
100  */
101 int
102 allowed_user(struct ssh *ssh, struct passwd * pw)
103 {
104 	struct stat st;
105 	const char *hostname = NULL, *ipaddr = NULL;
106 	u_int i;
107 	int r;
108 
109 	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
110 	if (!pw || !pw->pw_name)
111 		return 0;
112 
113 	if (!options.use_pam && platform_locked_account(pw)) {
114 		logit("User %.100s not allowed because account is locked",
115 		    pw->pw_name);
116 		return 0;
117 	}
118 
119 	/*
120 	 * Deny if shell does not exist or is not executable unless we
121 	 * are chrooting.
122 	 */
123 	if (options.chroot_directory == NULL ||
124 	    strcasecmp(options.chroot_directory, "none") == 0) {
125 		char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
126 		    _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
127 
128 		if (stat(shell, &st) == -1) {
129 			logit("User %.100s not allowed because shell %.100s "
130 			    "does not exist", pw->pw_name, shell);
131 			free(shell);
132 			return 0;
133 		}
134 		if (S_ISREG(st.st_mode) == 0 ||
135 		    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
136 			logit("User %.100s not allowed because shell %.100s "
137 			    "is not executable", pw->pw_name, shell);
138 			free(shell);
139 			return 0;
140 		}
141 		free(shell);
142 	}
143 
144 	if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
145 	    options.num_deny_groups > 0 || options.num_allow_groups > 0) {
146 		hostname = auth_get_canonical_hostname(ssh, options.use_dns);
147 		ipaddr = ssh_remote_ipaddr(ssh);
148 	}
149 
150 	/* Return false if user is listed in DenyUsers */
151 	if (options.num_deny_users > 0) {
152 		for (i = 0; i < options.num_deny_users; i++) {
153 			r = match_user(pw->pw_name, hostname, ipaddr,
154 			    options.deny_users[i]);
155 			if (r < 0) {
156 				fatal("Invalid DenyUsers pattern \"%.100s\"",
157 				    options.deny_users[i]);
158 			} else if (r != 0) {
159 				logit("User %.100s from %.100s not allowed "
160 				    "because listed in DenyUsers",
161 				    pw->pw_name, hostname);
162 				return 0;
163 			}
164 		}
165 	}
166 	/* Return false if AllowUsers isn't empty and user isn't listed there */
167 	if (options.num_allow_users > 0) {
168 		for (i = 0; i < options.num_allow_users; i++) {
169 			r = match_user(pw->pw_name, hostname, ipaddr,
170 			    options.allow_users[i]);
171 			if (r < 0) {
172 				fatal("Invalid AllowUsers pattern \"%.100s\"",
173 				    options.allow_users[i]);
174 			} else if (r == 1)
175 				break;
176 		}
177 		/* i < options.num_allow_users iff we break for loop */
178 		if (i >= options.num_allow_users) {
179 			logit("User %.100s from %.100s not allowed because "
180 			    "not listed in AllowUsers", pw->pw_name, hostname);
181 			return 0;
182 		}
183 	}
184 	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
185 		/* Get the user's group access list (primary and supplementary) */
186 		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
187 			logit("User %.100s from %.100s not allowed because "
188 			    "not in any group", pw->pw_name, hostname);
189 			return 0;
190 		}
191 
192 		/* Return false if one of user's groups is listed in DenyGroups */
193 		if (options.num_deny_groups > 0)
194 			if (ga_match(options.deny_groups,
195 			    options.num_deny_groups)) {
196 				ga_free();
197 				logit("User %.100s from %.100s not allowed "
198 				    "because a group is listed in DenyGroups",
199 				    pw->pw_name, hostname);
200 				return 0;
201 			}
202 		/*
203 		 * Return false if AllowGroups isn't empty and one of user's groups
204 		 * isn't listed there
205 		 */
206 		if (options.num_allow_groups > 0)
207 			if (!ga_match(options.allow_groups,
208 			    options.num_allow_groups)) {
209 				ga_free();
210 				logit("User %.100s from %.100s not allowed "
211 				    "because none of user's groups are listed "
212 				    "in AllowGroups", pw->pw_name, hostname);
213 				return 0;
214 			}
215 		ga_free();
216 	}
217 
218 #ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
219 	if (!sys_auth_allowed_user(pw, loginmsg))
220 		return 0;
221 #endif
222 
223 	/* We found no reason not to let this user try to log on... */
224 	return 1;
225 }
226 
227 /*
228  * Formats any key left in authctxt->auth_method_key for inclusion in
229  * auth_log()'s message. Also includes authxtct->auth_method_info if present.
230  */
231 static char *
232 format_method_key(Authctxt *authctxt)
233 {
234 	const struct sshkey *key = authctxt->auth_method_key;
235 	const char *methinfo = authctxt->auth_method_info;
236 	char *fp, *cafp, *ret = NULL;
237 
238 	if (key == NULL)
239 		return NULL;
240 
241 	if (sshkey_is_cert(key)) {
242 		fp = sshkey_fingerprint(key,
243 		    options.fingerprint_hash, SSH_FP_DEFAULT);
244 		cafp = sshkey_fingerprint(key->cert->signature_key,
245 		    options.fingerprint_hash, SSH_FP_DEFAULT);
246 		xasprintf(&ret, "%s %s ID %s (serial %llu) CA %s %s%s%s",
247 		    sshkey_type(key), fp == NULL ? "(null)" : fp,
248 		    key->cert->key_id,
249 		    (unsigned long long)key->cert->serial,
250 		    sshkey_type(key->cert->signature_key),
251 		    cafp == NULL ? "(null)" : cafp,
252 		    methinfo == NULL ? "" : ", ",
253 		    methinfo == NULL ? "" : methinfo);
254 		free(fp);
255 		free(cafp);
256 	} else {
257 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
258 		    SSH_FP_DEFAULT);
259 		xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
260 		    fp == NULL ? "(null)" : fp,
261 		    methinfo == NULL ? "" : ", ",
262 		    methinfo == NULL ? "" : methinfo);
263 		free(fp);
264 	}
265 	return ret;
266 }
267 
268 void
269 auth_log(struct ssh *ssh, int authenticated, int partial,
270     const char *method, const char *submethod)
271 {
272 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
273 	int level = SYSLOG_LEVEL_VERBOSE;
274 	const char *authmsg;
275 	char *extra = NULL;
276 
277 	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
278 		return;
279 
280 	/* Raise logging level */
281 	if (authenticated == 1 ||
282 	    !authctxt->valid ||
283 	    authctxt->failures >= options.max_authtries / 2 ||
284 	    strcmp(method, "password") == 0)
285 		level = SYSLOG_LEVEL_INFO;
286 
287 	if (authctxt->postponed)
288 		authmsg = "Postponed";
289 	else if (partial)
290 		authmsg = "Partial";
291 	else {
292 		authmsg = authenticated ? "Accepted" : "Failed";
293 		if (authenticated)
294 			BLACKLIST_NOTIFY(ssh, BLACKLIST_AUTH_OK, "ssh");
295 	}
296 
297 	if ((extra = format_method_key(authctxt)) == NULL) {
298 		if (authctxt->auth_method_info != NULL)
299 			extra = xstrdup(authctxt->auth_method_info);
300 	}
301 
302 	do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
303 	    authmsg,
304 	    method,
305 	    submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
306 	    authctxt->valid ? "" : "invalid user ",
307 	    authctxt->user,
308 	    ssh_remote_ipaddr(ssh),
309 	    ssh_remote_port(ssh),
310 	    extra != NULL ? ": " : "",
311 	    extra != NULL ? extra : "");
312 
313 	free(extra);
314 
315 #if defined(CUSTOM_FAILED_LOGIN) || defined(SSH_AUDIT_EVENTS)
316 	if (authenticated == 0 && !(authctxt->postponed || partial)) {
317 		/* Log failed login attempt */
318 # ifdef CUSTOM_FAILED_LOGIN
319 		if (strcmp(method, "password") == 0 ||
320 		    strncmp(method, "keyboard-interactive", 20) == 0 ||
321 		    strcmp(method, "challenge-response") == 0)
322 			record_failed_login(ssh, authctxt->user,
323 			    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
324 # endif
325 # ifdef SSH_AUDIT_EVENTS
326 		audit_event(ssh, audit_classify_auth(method));
327 # endif
328 	}
329 #endif
330 #if defined(CUSTOM_FAILED_LOGIN) && defined(WITH_AIXAUTHENTICATE)
331 	if (authenticated)
332 		sys_auth_record_login(authctxt->user,
333 		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh",
334 		    loginmsg);
335 #endif
336 }
337 
338 void
339 auth_maxtries_exceeded(struct ssh *ssh)
340 {
341 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
342 
343 	error("maximum authentication attempts exceeded for "
344 	    "%s%.100s from %.200s port %d ssh2",
345 	    authctxt->valid ? "" : "invalid user ",
346 	    authctxt->user,
347 	    ssh_remote_ipaddr(ssh),
348 	    ssh_remote_port(ssh));
349 	ssh_packet_disconnect(ssh, "Too many authentication failures");
350 	/* NOTREACHED */
351 }
352 
353 /*
354  * Check whether root logins are disallowed.
355  */
356 int
357 auth_root_allowed(struct ssh *ssh, const char *method)
358 {
359 	switch (options.permit_root_login) {
360 	case PERMIT_YES:
361 		return 1;
362 	case PERMIT_NO_PASSWD:
363 		if (strcmp(method, "publickey") == 0 ||
364 		    strcmp(method, "hostbased") == 0 ||
365 		    strcmp(method, "gssapi-with-mic") == 0)
366 			return 1;
367 		break;
368 	case PERMIT_FORCED_ONLY:
369 		if (auth_opts->force_command != NULL) {
370 			logit("Root login accepted for forced command.");
371 			return 1;
372 		}
373 		break;
374 	}
375 	logit("ROOT LOGIN REFUSED FROM %.200s port %d",
376 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
377 	return 0;
378 }
379 
380 
381 /*
382  * Given a template and a passwd structure, build a filename
383  * by substituting % tokenised options. Currently, %% becomes '%',
384  * %h becomes the home directory and %u the username.
385  *
386  * This returns a buffer allocated by xmalloc.
387  */
388 char *
389 expand_authorized_keys(const char *filename, struct passwd *pw)
390 {
391 	char *file, uidstr[32], ret[PATH_MAX];
392 	int i;
393 
394 	snprintf(uidstr, sizeof(uidstr), "%llu",
395 	    (unsigned long long)pw->pw_uid);
396 	file = percent_expand(filename, "h", pw->pw_dir,
397 	    "u", pw->pw_name, "U", uidstr, (char *)NULL);
398 
399 	/*
400 	 * Ensure that filename starts anchored. If not, be backward
401 	 * compatible and prepend the '%h/'
402 	 */
403 	if (path_absolute(file))
404 		return (file);
405 
406 	i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
407 	if (i < 0 || (size_t)i >= sizeof(ret))
408 		fatal("expand_authorized_keys: path too long");
409 	free(file);
410 	return (xstrdup(ret));
411 }
412 
413 char *
414 authorized_principals_file(struct passwd *pw)
415 {
416 	if (options.authorized_principals_file == NULL)
417 		return NULL;
418 	return expand_authorized_keys(options.authorized_principals_file, pw);
419 }
420 
421 /* return ok if key exists in sysfile or userfile */
422 HostStatus
423 check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
424     const char *sysfile, const char *userfile)
425 {
426 	char *user_hostfile;
427 	struct stat st;
428 	HostStatus host_status;
429 	struct hostkeys *hostkeys;
430 	const struct hostkey_entry *found;
431 
432 	hostkeys = init_hostkeys();
433 	load_hostkeys(hostkeys, host, sysfile, 0);
434 	if (userfile != NULL) {
435 		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
436 		if (options.strict_modes &&
437 		    (stat(user_hostfile, &st) == 0) &&
438 		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
439 		    (st.st_mode & 022) != 0)) {
440 			logit("Authentication refused for %.100s: "
441 			    "bad owner or modes for %.200s",
442 			    pw->pw_name, user_hostfile);
443 			auth_debug_add("Ignored %.200s: bad ownership or modes",
444 			    user_hostfile);
445 		} else {
446 			temporarily_use_uid(pw);
447 			load_hostkeys(hostkeys, host, user_hostfile, 0);
448 			restore_uid();
449 		}
450 		free(user_hostfile);
451 	}
452 	host_status = check_key_in_hostkeys(hostkeys, key, &found);
453 	if (host_status == HOST_REVOKED)
454 		error("WARNING: revoked key for %s attempted authentication",
455 		    host);
456 	else if (host_status == HOST_OK)
457 		debug_f("key for %s found at %s:%ld",
458 		    found->host, found->file, found->line);
459 	else
460 		debug_f("key for host %s not found", host);
461 
462 	free_hostkeys(hostkeys);
463 
464 	return host_status;
465 }
466 
467 static FILE *
468 auth_openfile(const char *file, struct passwd *pw, int strict_modes,
469     int log_missing, char *file_type)
470 {
471 	char line[1024];
472 	struct stat st;
473 	int fd;
474 	FILE *f;
475 
476 	if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
477 		if (log_missing || errno != ENOENT)
478 			debug("Could not open %s '%s': %s", file_type, file,
479 			    strerror(errno));
480 		return NULL;
481 	}
482 
483 	if (fstat(fd, &st) == -1) {
484 		close(fd);
485 		return NULL;
486 	}
487 	if (!S_ISREG(st.st_mode)) {
488 		logit("User %s %s %s is not a regular file",
489 		    pw->pw_name, file_type, file);
490 		close(fd);
491 		return NULL;
492 	}
493 	unset_nonblock(fd);
494 	if ((f = fdopen(fd, "r")) == NULL) {
495 		close(fd);
496 		return NULL;
497 	}
498 	if (strict_modes &&
499 	    safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) {
500 		fclose(f);
501 		logit("Authentication refused: %s", line);
502 		auth_debug_add("Ignored %s: %s", file_type, line);
503 		return NULL;
504 	}
505 
506 	return f;
507 }
508 
509 
510 FILE *
511 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
512 {
513 	return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
514 }
515 
516 FILE *
517 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
518 {
519 	return auth_openfile(file, pw, strict_modes, 0,
520 	    "authorized principals");
521 }
522 
523 struct passwd *
524 getpwnamallow(struct ssh *ssh, const char *user)
525 {
526 #ifdef HAVE_LOGIN_CAP
527 	extern login_cap_t *lc;
528 #ifdef HAVE_AUTH_HOSTOK
529 	const char *from_host, *from_ip;
530 #endif
531 #ifdef BSD_AUTH
532 	auth_session_t *as;
533 #endif
534 #endif
535 	struct passwd *pw;
536 	struct connection_info *ci;
537 	u_int i;
538 
539 	ci = get_connection_info(ssh, 1, options.use_dns);
540 	ci->user = user;
541 	parse_server_match_config(&options, &includes, ci);
542 	log_change_level(options.log_level);
543 	log_verbose_reset();
544 	for (i = 0; i < options.num_log_verbose; i++)
545 		log_verbose_add(options.log_verbose[i]);
546 	process_permitopen(ssh, &options);
547 
548 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
549 	aix_setauthdb(user);
550 #endif
551 
552 	pw = getpwnam(user);
553 
554 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
555 	aix_restoreauthdb();
556 #endif
557 	if (pw == NULL) {
558 		BLACKLIST_NOTIFY(ssh, BLACKLIST_BAD_USER, user);
559 		logit("Invalid user %.100s from %.100s port %d",
560 		    user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
561 #ifdef CUSTOM_FAILED_LOGIN
562 		record_failed_login(ssh, user,
563 		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
564 #endif
565 #ifdef SSH_AUDIT_EVENTS
566 		audit_event(ssh, SSH_INVALID_USER);
567 #endif /* SSH_AUDIT_EVENTS */
568 		return (NULL);
569 	}
570 	if (!allowed_user(ssh, pw))
571 		return (NULL);
572 #ifdef HAVE_LOGIN_CAP
573 	if ((lc = login_getpwclass(pw)) == NULL) {
574 		debug("unable to get login class: %s", user);
575 		return (NULL);
576 	}
577 #ifdef HAVE_AUTH_HOSTOK
578 	from_host = auth_get_canonical_hostname(ssh, options.use_dns);
579 	from_ip = ssh_remote_ipaddr(ssh);
580 	if (!auth_hostok(lc, from_host, from_ip)) {
581 		debug("Denied connection for %.200s from %.200s [%.200s].",
582 		    pw->pw_name, from_host, from_ip);
583 		return (NULL);
584 	}
585 #endif /* HAVE_AUTH_HOSTOK */
586 #ifdef HAVE_AUTH_TIMEOK
587 	if (!auth_timeok(lc, time(NULL))) {
588 		debug("LOGIN %.200s REFUSED (TIME)", pw->pw_name);
589 		return (NULL);
590 	}
591 #endif /* HAVE_AUTH_TIMEOK */
592 #ifdef BSD_AUTH
593 	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
594 	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
595 		debug("Approval failure for %s", user);
596 		pw = NULL;
597 	}
598 	if (as != NULL)
599 		auth_close(as);
600 #endif
601 #endif
602 	if (pw != NULL)
603 		return (pwcopy(pw));
604 	return (NULL);
605 }
606 
607 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
608 int
609 auth_key_is_revoked(struct sshkey *key)
610 {
611 	char *fp = NULL;
612 	int r;
613 
614 	if (options.revoked_keys_file == NULL)
615 		return 0;
616 	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
617 	    SSH_FP_DEFAULT)) == NULL) {
618 		r = SSH_ERR_ALLOC_FAIL;
619 		error_fr(r, "fingerprint key");
620 		goto out;
621 	}
622 
623 	r = sshkey_check_revoked(key, options.revoked_keys_file);
624 	switch (r) {
625 	case 0:
626 		break; /* not revoked */
627 	case SSH_ERR_KEY_REVOKED:
628 		error("Authentication key %s %s revoked by file %s",
629 		    sshkey_type(key), fp, options.revoked_keys_file);
630 		goto out;
631 	default:
632 		error_r(r, "Error checking authentication key %s %s in "
633 		    "revoked keys file %s", sshkey_type(key), fp,
634 		    options.revoked_keys_file);
635 		goto out;
636 	}
637 
638 	/* Success */
639 	r = 0;
640 
641  out:
642 	free(fp);
643 	return r == 0 ? 0 : 1;
644 }
645 
646 void
647 auth_debug_add(const char *fmt,...)
648 {
649 	char buf[1024];
650 	va_list args;
651 	int r;
652 
653 	if (auth_debug == NULL)
654 		return;
655 
656 	va_start(args, fmt);
657 	vsnprintf(buf, sizeof(buf), fmt, args);
658 	va_end(args);
659 	if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0)
660 		fatal_fr(r, "sshbuf_put_cstring");
661 }
662 
663 void
664 auth_debug_send(struct ssh *ssh)
665 {
666 	char *msg;
667 	int r;
668 
669 	if (auth_debug == NULL)
670 		return;
671 	while (sshbuf_len(auth_debug) != 0) {
672 		if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0)
673 			fatal_fr(r, "sshbuf_get_cstring");
674 		ssh_packet_send_debug(ssh, "%s", msg);
675 		free(msg);
676 	}
677 }
678 
679 void
680 auth_debug_reset(void)
681 {
682 	if (auth_debug != NULL)
683 		sshbuf_reset(auth_debug);
684 	else if ((auth_debug = sshbuf_new()) == NULL)
685 		fatal_f("sshbuf_new failed");
686 }
687 
688 struct passwd *
689 fakepw(void)
690 {
691 	static int done = 0;
692 	static struct passwd fake;
693 	const char hashchars[] = "./ABCDEFGHIJKLMNOPQRSTUVWXYZ"
694 	    "abcdefghijklmnopqrstuvwxyz0123456789"; /* from bcrypt.c */
695 	char *cp;
696 
697 	if (done)
698 		return (&fake);
699 
700 	memset(&fake, 0, sizeof(fake));
701 	fake.pw_name = "NOUSER";
702 	fake.pw_passwd = xstrdup("$2a$10$"
703 	    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
704 	for (cp = fake.pw_passwd + 7; *cp != '\0'; cp++)
705 		*cp = hashchars[arc4random_uniform(sizeof(hashchars) - 1)];
706 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
707 	fake.pw_gecos = "NOUSER";
708 #endif
709 	fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
710 	fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
711 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
712 	fake.pw_class = "";
713 #endif
714 	fake.pw_dir = "/nonexist";
715 	fake.pw_shell = "/nonexist";
716 	done = 1;
717 
718 	return (&fake);
719 }
720 
721 /*
722  * Returns the remote DNS hostname as a string. The returned string must not
723  * be freed. NB. this will usually trigger a DNS query the first time it is
724  * called.
725  * This function does additional checks on the hostname to mitigate some
726  * attacks on based on conflation of hostnames and IP addresses.
727  */
728 
729 static char *
730 remote_hostname(struct ssh *ssh)
731 {
732 	struct sockaddr_storage from;
733 	socklen_t fromlen;
734 	struct addrinfo hints, *ai, *aitop;
735 	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
736 	const char *ntop = ssh_remote_ipaddr(ssh);
737 
738 	/* Get IP address of client. */
739 	fromlen = sizeof(from);
740 	memset(&from, 0, sizeof(from));
741 	if (getpeername(ssh_packet_get_connection_in(ssh),
742 	    (struct sockaddr *)&from, &fromlen) == -1) {
743 		debug("getpeername failed: %.100s", strerror(errno));
744 		return xstrdup(ntop);
745 	}
746 
747 	ipv64_normalise_mapped(&from, &fromlen);
748 	if (from.ss_family == AF_INET6)
749 		fromlen = sizeof(struct sockaddr_in6);
750 
751 	debug3("Trying to reverse map address %.100s.", ntop);
752 	/* Map the IP address to a host name. */
753 	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
754 	    NULL, 0, NI_NAMEREQD) != 0) {
755 		/* Host name not found.  Use ip address. */
756 		return xstrdup(ntop);
757 	}
758 
759 	/*
760 	 * if reverse lookup result looks like a numeric hostname,
761 	 * someone is trying to trick us by PTR record like following:
762 	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
763 	 */
764 	memset(&hints, 0, sizeof(hints));
765 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
766 	hints.ai_flags = AI_NUMERICHOST;
767 	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
768 		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
769 		    name, ntop);
770 		freeaddrinfo(ai);
771 		return xstrdup(ntop);
772 	}
773 
774 	/* Names are stored in lowercase. */
775 	lowercase(name);
776 
777 	/*
778 	 * Map it back to an IP address and check that the given
779 	 * address actually is an address of this host.  This is
780 	 * necessary because anyone with access to a name server can
781 	 * define arbitrary names for an IP address. Mapping from
782 	 * name to IP address can be trusted better (but can still be
783 	 * fooled if the intruder has access to the name server of
784 	 * the domain).
785 	 */
786 	memset(&hints, 0, sizeof(hints));
787 	hints.ai_family = from.ss_family;
788 	hints.ai_socktype = SOCK_STREAM;
789 	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
790 		logit("reverse mapping checking getaddrinfo for %.700s "
791 		    "[%s] failed.", name, ntop);
792 		return xstrdup(ntop);
793 	}
794 	/* Look for the address from the list of addresses. */
795 	for (ai = aitop; ai; ai = ai->ai_next) {
796 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
797 		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
798 		    (strcmp(ntop, ntop2) == 0))
799 				break;
800 	}
801 	freeaddrinfo(aitop);
802 	/* If we reached the end of the list, the address was not there. */
803 	if (ai == NULL) {
804 		/* Address not found for the host name. */
805 		logit("Address %.100s maps to %.600s, but this does not "
806 		    "map back to the address.", ntop, name);
807 		return xstrdup(ntop);
808 	}
809 	return xstrdup(name);
810 }
811 
812 /*
813  * Return the canonical name of the host in the other side of the current
814  * connection.  The host name is cached, so it is efficient to call this
815  * several times.
816  */
817 
818 const char *
819 auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
820 {
821 	static char *dnsname;
822 
823 	if (!use_dns)
824 		return ssh_remote_ipaddr(ssh);
825 	else if (dnsname != NULL)
826 		return dnsname;
827 	else {
828 		dnsname = remote_hostname(ssh);
829 		return dnsname;
830 	}
831 }
832 
833 /* These functions link key/cert options to the auth framework */
834 
835 /* Log sshauthopt options locally and (optionally) for remote transmission */
836 void
837 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
838 {
839 	int do_env = options.permit_user_env && opts->nenv > 0;
840 	int do_permitopen = opts->npermitopen > 0 &&
841 	    (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
842 	int do_permitlisten = opts->npermitlisten > 0 &&
843 	    (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0;
844 	size_t i;
845 	char msg[1024], buf[64];
846 
847 	snprintf(buf, sizeof(buf), "%d", opts->force_tun_device);
848 	/* Try to keep this alphabetically sorted */
849 	snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
850 	    opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
851 	    opts->force_command == NULL ? "" : " command",
852 	    do_env ?  " environment" : "",
853 	    opts->valid_before == 0 ? "" : "expires",
854 	    opts->no_require_user_presence ? " no-touch-required" : "",
855 	    do_permitopen ?  " permitopen" : "",
856 	    do_permitlisten ?  " permitlisten" : "",
857 	    opts->permit_port_forwarding_flag ? " port-forwarding" : "",
858 	    opts->cert_principals == NULL ? "" : " principals",
859 	    opts->permit_pty_flag ? " pty" : "",
860 	    opts->require_verify ? " uv" : "",
861 	    opts->force_tun_device == -1 ? "" : " tun=",
862 	    opts->force_tun_device == -1 ? "" : buf,
863 	    opts->permit_user_rc ? " user-rc" : "",
864 	    opts->permit_x11_forwarding_flag ? " x11-forwarding" : "");
865 
866 	debug("%s: %s", loc, msg);
867 	if (do_remote)
868 		auth_debug_add("%s: %s", loc, msg);
869 
870 	if (options.permit_user_env) {
871 		for (i = 0; i < opts->nenv; i++) {
872 			debug("%s: environment: %s", loc, opts->env[i]);
873 			if (do_remote) {
874 				auth_debug_add("%s: environment: %s",
875 				    loc, opts->env[i]);
876 			}
877 		}
878 	}
879 
880 	/* Go into a little more details for the local logs. */
881 	if (opts->valid_before != 0) {
882 		format_absolute_time(opts->valid_before, buf, sizeof(buf));
883 		debug("%s: expires at %s", loc, buf);
884 	}
885 	if (opts->cert_principals != NULL) {
886 		debug("%s: authorized principals: \"%s\"",
887 		    loc, opts->cert_principals);
888 	}
889 	if (opts->force_command != NULL)
890 		debug("%s: forced command: \"%s\"", loc, opts->force_command);
891 	if (do_permitopen) {
892 		for (i = 0; i < opts->npermitopen; i++) {
893 			debug("%s: permitted open: %s",
894 			    loc, opts->permitopen[i]);
895 		}
896 	}
897 	if (do_permitlisten) {
898 		for (i = 0; i < opts->npermitlisten; i++) {
899 			debug("%s: permitted listen: %s",
900 			    loc, opts->permitlisten[i]);
901 		}
902 	}
903 }
904 
905 /* Activate a new set of key/cert options; merging with what is there. */
906 int
907 auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
908 {
909 	struct sshauthopt *old = auth_opts;
910 	const char *emsg = NULL;
911 
912 	debug_f("setting new authentication options");
913 	if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
914 		error("Inconsistent authentication options: %s", emsg);
915 		return -1;
916 	}
917 	return 0;
918 }
919 
920 /* Disable forwarding, etc for the session */
921 void
922 auth_restrict_session(struct ssh *ssh)
923 {
924 	struct sshauthopt *restricted;
925 
926 	debug_f("restricting session");
927 
928 	/* A blank sshauthopt defaults to permitting nothing */
929 	restricted = sshauthopt_new();
930 	restricted->permit_pty_flag = 1;
931 	restricted->restricted = 1;
932 
933 	if (auth_activate_options(ssh, restricted) != 0)
934 		fatal_f("failed to restrict session");
935 	sshauthopt_free(restricted);
936 }
937 
938 int
939 auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw,
940     struct sshauthopt *opts, int allow_cert_authority, const char *loc)
941 {
942 	const char *remote_ip = ssh_remote_ipaddr(ssh);
943 	const char *remote_host = auth_get_canonical_hostname(ssh,
944 	    options.use_dns);
945 	time_t now = time(NULL);
946 	char buf[64];
947 
948 	/*
949 	 * Check keys/principals file expiry time.
950 	 * NB. validity interval in certificate is handled elsewhere.
951 	 */
952 	if (opts->valid_before && now > 0 &&
953 	    opts->valid_before < (uint64_t)now) {
954 		format_absolute_time(opts->valid_before, buf, sizeof(buf));
955 		debug("%s: entry expired at %s", loc, buf);
956 		auth_debug_add("%s: entry expired at %s", loc, buf);
957 		return -1;
958 	}
959 	/* Consistency checks */
960 	if (opts->cert_principals != NULL && !opts->cert_authority) {
961 		debug("%s: principals on non-CA key", loc);
962 		auth_debug_add("%s: principals on non-CA key", loc);
963 		/* deny access */
964 		return -1;
965 	}
966 	/* cert-authority flag isn't valid in authorized_principals files */
967 	if (!allow_cert_authority && opts->cert_authority) {
968 		debug("%s: cert-authority flag invalid here", loc);
969 		auth_debug_add("%s: cert-authority flag invalid here", loc);
970 		/* deny access */
971 		return -1;
972 	}
973 
974 	/* Perform from= checks */
975 	if (opts->required_from_host_keys != NULL) {
976 		switch (match_host_and_ip(remote_host, remote_ip,
977 		    opts->required_from_host_keys )) {
978 		case 1:
979 			/* Host name matches. */
980 			break;
981 		case -1:
982 		default:
983 			debug("%s: invalid from criteria", loc);
984 			auth_debug_add("%s: invalid from criteria", loc);
985 			/* FALLTHROUGH */
986 		case 0:
987 			logit("%s: Authentication tried for %.100s with "
988 			    "correct key but not from a permitted "
989 			    "host (host=%.200s, ip=%.200s, required=%.200s).",
990 			    loc, pw->pw_name, remote_host, remote_ip,
991 			    opts->required_from_host_keys);
992 			auth_debug_add("%s: Your host '%.200s' is not "
993 			    "permitted to use this key for login.",
994 			    loc, remote_host);
995 			/* deny access */
996 			return -1;
997 		}
998 	}
999 	/* Check source-address restriction from certificate */
1000 	if (opts->required_from_host_cert != NULL) {
1001 		switch (addr_match_cidr_list(remote_ip,
1002 		    opts->required_from_host_cert)) {
1003 		case 1:
1004 			/* accepted */
1005 			break;
1006 		case -1:
1007 		default:
1008 			/* invalid */
1009 			error("%s: Certificate source-address invalid", loc);
1010 			/* FALLTHROUGH */
1011 		case 0:
1012 			logit("%s: Authentication tried for %.100s with valid "
1013 			    "certificate but not from a permitted source "
1014 			    "address (%.200s).", loc, pw->pw_name, remote_ip);
1015 			auth_debug_add("%s: Your address '%.200s' is not "
1016 			    "permitted to use this certificate for login.",
1017 			    loc, remote_ip);
1018 			return -1;
1019 		}
1020 	}
1021 	/*
1022 	 *
1023 	 * XXX this is spammy. We should report remotely only for keys
1024 	 *     that are successful in actual auth attempts, and not PK_OK
1025 	 *     tests.
1026 	 */
1027 	auth_log_authopts(loc, opts, 1);
1028 
1029 	return 0;
1030 }
1031