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