xref: /freebsd/crypto/openssh/auth.c (revision 4f52dfbb8d6c4d446500c5b097e3806ec219fbd4)
1 /* $OpenBSD: auth.c,v 1.124 2017/09/12 06:32:07 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 __RCSID("$FreeBSD$");
28 
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/socket.h>
32 
33 #include <netinet/in.h>
34 
35 #include <errno.h>
36 #include <fcntl.h>
37 #ifdef HAVE_PATHS_H
38 # include <paths.h>
39 #endif
40 #include <pwd.h>
41 #ifdef HAVE_LOGIN_H
42 #include <login.h>
43 #endif
44 #ifdef USE_SHADOW
45 #include <shadow.h>
46 #endif
47 #include <stdarg.h>
48 #include <stdio.h>
49 #include <string.h>
50 #include <unistd.h>
51 #include <limits.h>
52 #include <netdb.h>
53 
54 #include "xmalloc.h"
55 #include "match.h"
56 #include "groupaccess.h"
57 #include "log.h"
58 #include "buffer.h"
59 #include "misc.h"
60 #include "servconf.h"
61 #include "key.h"
62 #include "hostfile.h"
63 #include "auth.h"
64 #include "auth-options.h"
65 #include "canohost.h"
66 #include "uidswap.h"
67 #include "packet.h"
68 #include "loginrec.h"
69 #ifdef GSSAPI
70 #include "ssh-gss.h"
71 #endif
72 #include "authfile.h"
73 #include "monitor_wrap.h"
74 #include "authfile.h"
75 #include "ssherr.h"
76 #include "compat.h"
77 #include "blacklist_client.h"
78 
79 /* import */
80 extern ServerOptions options;
81 extern int use_privsep;
82 extern Buffer loginmsg;
83 extern struct passwd *privsep_pw;
84 
85 /* Debugging messages */
86 Buffer auth_debug;
87 int auth_debug_init;
88 
89 /*
90  * Check if the user is allowed to log in via ssh. If user is listed
91  * in DenyUsers or one of user's groups is listed in DenyGroups, false
92  * will be returned. If AllowUsers isn't empty and user isn't listed
93  * there, or if AllowGroups isn't empty and one of user's groups isn't
94  * listed there, false will be returned.
95  * If the user's shell is not executable, false will be returned.
96  * Otherwise true is returned.
97  */
98 int
99 allowed_user(struct passwd * pw)
100 {
101 	struct ssh *ssh = active_state; /* XXX */
102 	struct stat st;
103 	const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
104 	u_int i;
105 	int r;
106 #ifdef USE_SHADOW
107 	struct spwd *spw = NULL;
108 #endif
109 
110 	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
111 	if (!pw || !pw->pw_name)
112 		return 0;
113 
114 #ifdef USE_SHADOW
115 	if (!options.use_pam)
116 		spw = getspnam(pw->pw_name);
117 #ifdef HAS_SHADOW_EXPIRE
118 	if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
119 		return 0;
120 #endif /* HAS_SHADOW_EXPIRE */
121 #endif /* USE_SHADOW */
122 
123 	/* grab passwd field for locked account check */
124 	passwd = pw->pw_passwd;
125 #ifdef USE_SHADOW
126 	if (spw != NULL)
127 #ifdef USE_LIBIAF
128 		passwd = get_iaf_password(pw);
129 #else
130 		passwd = spw->sp_pwdp;
131 #endif /* USE_LIBIAF */
132 #endif
133 
134 	/* check for locked account */
135 	if (!options.use_pam && passwd && *passwd) {
136 		int locked = 0;
137 
138 #ifdef LOCKED_PASSWD_STRING
139 		if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
140 			 locked = 1;
141 #endif
142 #ifdef LOCKED_PASSWD_PREFIX
143 		if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
144 		    strlen(LOCKED_PASSWD_PREFIX)) == 0)
145 			 locked = 1;
146 #endif
147 #ifdef LOCKED_PASSWD_SUBSTR
148 		if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
149 			locked = 1;
150 #endif
151 #ifdef USE_LIBIAF
152 		free((void *) passwd);
153 #endif /* USE_LIBIAF */
154 		if (locked) {
155 			logit("User %.100s not allowed because account is locked",
156 			    pw->pw_name);
157 			return 0;
158 		}
159 	}
160 
161 	/*
162 	 * Deny if shell does not exist or is not executable unless we
163 	 * are chrooting.
164 	 */
165 	if (options.chroot_directory == NULL ||
166 	    strcasecmp(options.chroot_directory, "none") == 0) {
167 		char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
168 		    _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
169 
170 		if (stat(shell, &st) != 0) {
171 			logit("User %.100s not allowed because shell %.100s "
172 			    "does not exist", pw->pw_name, shell);
173 			free(shell);
174 			return 0;
175 		}
176 		if (S_ISREG(st.st_mode) == 0 ||
177 		    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
178 			logit("User %.100s not allowed because shell %.100s "
179 			    "is not executable", pw->pw_name, shell);
180 			free(shell);
181 			return 0;
182 		}
183 		free(shell);
184 	}
185 
186 	if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
187 	    options.num_deny_groups > 0 || options.num_allow_groups > 0) {
188 		hostname = auth_get_canonical_hostname(ssh, options.use_dns);
189 		ipaddr = ssh_remote_ipaddr(ssh);
190 	}
191 
192 	/* Return false if user is listed in DenyUsers */
193 	if (options.num_deny_users > 0) {
194 		for (i = 0; i < options.num_deny_users; i++) {
195 			r = match_user(pw->pw_name, hostname, ipaddr,
196 			    options.deny_users[i]);
197 			if (r < 0) {
198 				fatal("Invalid DenyUsers pattern \"%.100s\"",
199 				    options.deny_users[i]);
200 			} else if (r != 0) {
201 				logit("User %.100s from %.100s not allowed "
202 				    "because listed in DenyUsers",
203 				    pw->pw_name, hostname);
204 				return 0;
205 			}
206 		}
207 	}
208 	/* Return false if AllowUsers isn't empty and user isn't listed there */
209 	if (options.num_allow_users > 0) {
210 		for (i = 0; i < options.num_allow_users; i++) {
211 			r = match_user(pw->pw_name, hostname, ipaddr,
212 			    options.allow_users[i]);
213 			if (r < 0) {
214 				fatal("Invalid AllowUsers pattern \"%.100s\"",
215 				    options.allow_users[i]);
216 			} else if (r == 1)
217 				break;
218 		}
219 		/* i < options.num_allow_users iff we break for loop */
220 		if (i >= options.num_allow_users) {
221 			logit("User %.100s from %.100s not allowed because "
222 			    "not listed in AllowUsers", pw->pw_name, hostname);
223 			return 0;
224 		}
225 	}
226 	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
227 		/* Get the user's group access list (primary and supplementary) */
228 		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
229 			logit("User %.100s from %.100s not allowed because "
230 			    "not in any group", pw->pw_name, hostname);
231 			return 0;
232 		}
233 
234 		/* Return false if one of user's groups is listed in DenyGroups */
235 		if (options.num_deny_groups > 0)
236 			if (ga_match(options.deny_groups,
237 			    options.num_deny_groups)) {
238 				ga_free();
239 				logit("User %.100s from %.100s not allowed "
240 				    "because a group is listed in DenyGroups",
241 				    pw->pw_name, hostname);
242 				return 0;
243 			}
244 		/*
245 		 * Return false if AllowGroups isn't empty and one of user's groups
246 		 * isn't listed there
247 		 */
248 		if (options.num_allow_groups > 0)
249 			if (!ga_match(options.allow_groups,
250 			    options.num_allow_groups)) {
251 				ga_free();
252 				logit("User %.100s from %.100s not allowed "
253 				    "because none of user's groups are listed "
254 				    "in AllowGroups", pw->pw_name, hostname);
255 				return 0;
256 			}
257 		ga_free();
258 	}
259 
260 #ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
261 	if (!sys_auth_allowed_user(pw, &loginmsg))
262 		return 0;
263 #endif
264 
265 	/* We found no reason not to let this user try to log on... */
266 	return 1;
267 }
268 
269 /*
270  * Formats any key left in authctxt->auth_method_key for inclusion in
271  * auth_log()'s message. Also includes authxtct->auth_method_info if present.
272  */
273 static char *
274 format_method_key(Authctxt *authctxt)
275 {
276 	const struct sshkey *key = authctxt->auth_method_key;
277 	const char *methinfo = authctxt->auth_method_info;
278 	char *fp, *ret = NULL;
279 
280 	if (key == NULL)
281 		return NULL;
282 
283 	if (key_is_cert(key)) {
284 		fp = sshkey_fingerprint(key->cert->signature_key,
285 		    options.fingerprint_hash, SSH_FP_DEFAULT);
286 		xasprintf(&ret, "%s ID %s (serial %llu) CA %s %s%s%s",
287 		    sshkey_type(key), key->cert->key_id,
288 		    (unsigned long long)key->cert->serial,
289 		    sshkey_type(key->cert->signature_key),
290 		    fp == NULL ? "(null)" : fp,
291 		    methinfo == NULL ? "" : ", ",
292 		    methinfo == NULL ? "" : methinfo);
293 		free(fp);
294 	} else {
295 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
296 		    SSH_FP_DEFAULT);
297 		xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
298 		    fp == NULL ? "(null)" : fp,
299 		    methinfo == NULL ? "" : ", ",
300 		    methinfo == NULL ? "" : methinfo);
301 		free(fp);
302 	}
303 	return ret;
304 }
305 
306 void
307 auth_log(Authctxt *authctxt, int authenticated, int partial,
308     const char *method, const char *submethod)
309 {
310 	struct ssh *ssh = active_state; /* XXX */
311 	void (*authlog) (const char *fmt,...) = verbose;
312 	const char *authmsg;
313 	char *extra = NULL;
314 
315 	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
316 		return;
317 
318 	/* Raise logging level */
319 	if (authenticated == 1 ||
320 	    !authctxt->valid ||
321 	    authctxt->failures >= options.max_authtries / 2 ||
322 	    strcmp(method, "password") == 0)
323 		authlog = logit;
324 
325 	if (authctxt->postponed)
326 		authmsg = "Postponed";
327 	else if (partial)
328 		authmsg = "Partial";
329 	else {
330 		authmsg = authenticated ? "Accepted" : "Failed";
331 		if (authenticated)
332 			BLACKLIST_NOTIFY(BLACKLIST_AUTH_OK, "ssh");
333 	}
334 
335 	if ((extra = format_method_key(authctxt)) == NULL) {
336 		if (authctxt->auth_method_info != NULL)
337 			extra = xstrdup(authctxt->auth_method_info);
338 	}
339 
340 	authlog("%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
341 	    authmsg,
342 	    method,
343 	    submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
344 	    authctxt->valid ? "" : "invalid user ",
345 	    authctxt->user,
346 	    ssh_remote_ipaddr(ssh),
347 	    ssh_remote_port(ssh),
348 	    extra != NULL ? ": " : "",
349 	    extra != NULL ? extra : "");
350 
351 	free(extra);
352 
353 #ifdef CUSTOM_FAILED_LOGIN
354 	if (authenticated == 0 && !authctxt->postponed &&
355 	    (strcmp(method, "password") == 0 ||
356 	    strncmp(method, "keyboard-interactive", 20) == 0 ||
357 	    strcmp(method, "challenge-response") == 0))
358 		record_failed_login(authctxt->user,
359 		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
360 # ifdef WITH_AIXAUTHENTICATE
361 	if (authenticated)
362 		sys_auth_record_login(authctxt->user,
363 		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh",
364 		    &loginmsg);
365 # endif
366 #endif
367 #ifdef SSH_AUDIT_EVENTS
368 	if (authenticated == 0 && !authctxt->postponed)
369 		audit_event(audit_classify_auth(method));
370 #endif
371 }
372 
373 
374 void
375 auth_maxtries_exceeded(Authctxt *authctxt)
376 {
377 	struct ssh *ssh = active_state; /* XXX */
378 
379 	error("maximum authentication attempts exceeded for "
380 	    "%s%.100s from %.200s port %d ssh2",
381 	    authctxt->valid ? "" : "invalid user ",
382 	    authctxt->user,
383 	    ssh_remote_ipaddr(ssh),
384 	    ssh_remote_port(ssh));
385 	packet_disconnect("Too many authentication failures");
386 	/* NOTREACHED */
387 }
388 
389 /*
390  * Check whether root logins are disallowed.
391  */
392 int
393 auth_root_allowed(const char *method)
394 {
395 	struct ssh *ssh = active_state; /* XXX */
396 
397 	switch (options.permit_root_login) {
398 	case PERMIT_YES:
399 		return 1;
400 	case PERMIT_NO_PASSWD:
401 		if (strcmp(method, "publickey") == 0 ||
402 		    strcmp(method, "hostbased") == 0 ||
403 		    strcmp(method, "gssapi-with-mic") == 0)
404 			return 1;
405 		break;
406 	case PERMIT_FORCED_ONLY:
407 		if (forced_command) {
408 			logit("Root login accepted for forced command.");
409 			return 1;
410 		}
411 		break;
412 	}
413 	logit("ROOT LOGIN REFUSED FROM %.200s port %d",
414 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
415 	return 0;
416 }
417 
418 
419 /*
420  * Given a template and a passwd structure, build a filename
421  * by substituting % tokenised options. Currently, %% becomes '%',
422  * %h becomes the home directory and %u the username.
423  *
424  * This returns a buffer allocated by xmalloc.
425  */
426 char *
427 expand_authorized_keys(const char *filename, struct passwd *pw)
428 {
429 	char *file, ret[PATH_MAX];
430 	int i;
431 
432 	file = percent_expand(filename, "h", pw->pw_dir,
433 	    "u", pw->pw_name, (char *)NULL);
434 
435 	/*
436 	 * Ensure that filename starts anchored. If not, be backward
437 	 * compatible and prepend the '%h/'
438 	 */
439 	if (*file == '/')
440 		return (file);
441 
442 	i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
443 	if (i < 0 || (size_t)i >= sizeof(ret))
444 		fatal("expand_authorized_keys: path too long");
445 	free(file);
446 	return (xstrdup(ret));
447 }
448 
449 char *
450 authorized_principals_file(struct passwd *pw)
451 {
452 	if (options.authorized_principals_file == NULL)
453 		return NULL;
454 	return expand_authorized_keys(options.authorized_principals_file, pw);
455 }
456 
457 /* return ok if key exists in sysfile or userfile */
458 HostStatus
459 check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
460     const char *sysfile, const char *userfile)
461 {
462 	char *user_hostfile;
463 	struct stat st;
464 	HostStatus host_status;
465 	struct hostkeys *hostkeys;
466 	const struct hostkey_entry *found;
467 
468 	hostkeys = init_hostkeys();
469 	load_hostkeys(hostkeys, host, sysfile);
470 	if (userfile != NULL) {
471 		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
472 		if (options.strict_modes &&
473 		    (stat(user_hostfile, &st) == 0) &&
474 		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
475 		    (st.st_mode & 022) != 0)) {
476 			logit("Authentication refused for %.100s: "
477 			    "bad owner or modes for %.200s",
478 			    pw->pw_name, user_hostfile);
479 			auth_debug_add("Ignored %.200s: bad ownership or modes",
480 			    user_hostfile);
481 		} else {
482 			temporarily_use_uid(pw);
483 			load_hostkeys(hostkeys, host, user_hostfile);
484 			restore_uid();
485 		}
486 		free(user_hostfile);
487 	}
488 	host_status = check_key_in_hostkeys(hostkeys, key, &found);
489 	if (host_status == HOST_REVOKED)
490 		error("WARNING: revoked key for %s attempted authentication",
491 		    found->host);
492 	else if (host_status == HOST_OK)
493 		debug("%s: key for %s found at %s:%ld", __func__,
494 		    found->host, found->file, found->line);
495 	else
496 		debug("%s: key for host %s not found", __func__, host);
497 
498 	free_hostkeys(hostkeys);
499 
500 	return host_status;
501 }
502 
503 static FILE *
504 auth_openfile(const char *file, struct passwd *pw, int strict_modes,
505     int log_missing, char *file_type)
506 {
507 	char line[1024];
508 	struct stat st;
509 	int fd;
510 	FILE *f;
511 
512 	if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
513 		if (log_missing || errno != ENOENT)
514 			debug("Could not open %s '%s': %s", file_type, file,
515 			   strerror(errno));
516 		return NULL;
517 	}
518 
519 	if (fstat(fd, &st) < 0) {
520 		close(fd);
521 		return NULL;
522 	}
523 	if (!S_ISREG(st.st_mode)) {
524 		logit("User %s %s %s is not a regular file",
525 		    pw->pw_name, file_type, file);
526 		close(fd);
527 		return NULL;
528 	}
529 	unset_nonblock(fd);
530 	if ((f = fdopen(fd, "r")) == NULL) {
531 		close(fd);
532 		return NULL;
533 	}
534 	if (strict_modes &&
535 	    safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) {
536 		fclose(f);
537 		logit("Authentication refused: %s", line);
538 		auth_debug_add("Ignored %s: %s", file_type, line);
539 		return NULL;
540 	}
541 
542 	return f;
543 }
544 
545 
546 FILE *
547 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
548 {
549 	return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
550 }
551 
552 FILE *
553 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
554 {
555 	return auth_openfile(file, pw, strict_modes, 0,
556 	    "authorized principals");
557 }
558 
559 struct passwd *
560 getpwnamallow(const char *user)
561 {
562 	struct ssh *ssh = active_state; /* XXX */
563 #ifdef HAVE_LOGIN_CAP
564 	extern login_cap_t *lc;
565 #ifdef BSD_AUTH
566 	auth_session_t *as;
567 #endif
568 #endif
569 	struct passwd *pw;
570 	struct connection_info *ci = get_connection_info(1, options.use_dns);
571 
572 	ci->user = user;
573 	parse_server_match_config(&options, ci);
574 	log_change_level(options.log_level);
575 	process_permitopen(ssh, &options);
576 
577 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
578 	aix_setauthdb(user);
579 #endif
580 
581 	pw = getpwnam(user);
582 
583 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
584 	aix_restoreauthdb();
585 #endif
586 #ifdef HAVE_CYGWIN
587 	/*
588 	 * Windows usernames are case-insensitive.  To avoid later problems
589 	 * when trying to match the username, the user is only allowed to
590 	 * login if the username is given in the same case as stored in the
591 	 * user database.
592 	 */
593 	if (pw != NULL && strcmp(user, pw->pw_name) != 0) {
594 		logit("Login name %.100s does not match stored username %.100s",
595 		    user, pw->pw_name);
596 		pw = NULL;
597 	}
598 #endif
599 	if (pw == NULL) {
600 		BLACKLIST_NOTIFY(BLACKLIST_BAD_USER, user);
601 		logit("Invalid user %.100s from %.100s port %d",
602 		    user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
603 #ifdef CUSTOM_FAILED_LOGIN
604 		record_failed_login(user,
605 		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
606 #endif
607 #ifdef SSH_AUDIT_EVENTS
608 		audit_event(SSH_INVALID_USER);
609 #endif /* SSH_AUDIT_EVENTS */
610 		return (NULL);
611 	}
612 	if (!allowed_user(pw))
613 		return (NULL);
614 #ifdef HAVE_LOGIN_CAP
615 	if ((lc = login_getpwclass(pw)) == NULL) {
616 		debug("unable to get login class: %s", user);
617 		return (NULL);
618 	}
619 #ifdef BSD_AUTH
620 	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
621 	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
622 		debug("Approval failure for %s", user);
623 		pw = NULL;
624 	}
625 	if (as != NULL)
626 		auth_close(as);
627 #endif
628 #endif
629 	if (pw != NULL)
630 		return (pwcopy(pw));
631 	return (NULL);
632 }
633 
634 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
635 int
636 auth_key_is_revoked(struct sshkey *key)
637 {
638 	char *fp = NULL;
639 	int r;
640 
641 	if (options.revoked_keys_file == NULL)
642 		return 0;
643 	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
644 	    SSH_FP_DEFAULT)) == NULL) {
645 		r = SSH_ERR_ALLOC_FAIL;
646 		error("%s: fingerprint key: %s", __func__, ssh_err(r));
647 		goto out;
648 	}
649 
650 	r = sshkey_check_revoked(key, options.revoked_keys_file);
651 	switch (r) {
652 	case 0:
653 		break; /* not revoked */
654 	case SSH_ERR_KEY_REVOKED:
655 		error("Authentication key %s %s revoked by file %s",
656 		    sshkey_type(key), fp, options.revoked_keys_file);
657 		goto out;
658 	default:
659 		error("Error checking authentication key %s %s in "
660 		    "revoked keys file %s: %s", sshkey_type(key), fp,
661 		    options.revoked_keys_file, ssh_err(r));
662 		goto out;
663 	}
664 
665 	/* Success */
666 	r = 0;
667 
668  out:
669 	free(fp);
670 	return r == 0 ? 0 : 1;
671 }
672 
673 void
674 auth_debug_add(const char *fmt,...)
675 {
676 	char buf[1024];
677 	va_list args;
678 
679 	if (!auth_debug_init)
680 		return;
681 
682 	va_start(args, fmt);
683 	vsnprintf(buf, sizeof(buf), fmt, args);
684 	va_end(args);
685 	buffer_put_cstring(&auth_debug, buf);
686 }
687 
688 void
689 auth_debug_send(void)
690 {
691 	char *msg;
692 
693 	if (!auth_debug_init)
694 		return;
695 	while (buffer_len(&auth_debug)) {
696 		msg = buffer_get_string(&auth_debug, NULL);
697 		packet_send_debug("%s", msg);
698 		free(msg);
699 	}
700 }
701 
702 void
703 auth_debug_reset(void)
704 {
705 	if (auth_debug_init)
706 		buffer_clear(&auth_debug);
707 	else {
708 		buffer_init(&auth_debug);
709 		auth_debug_init = 1;
710 	}
711 }
712 
713 struct passwd *
714 fakepw(void)
715 {
716 	static struct passwd fake;
717 
718 	memset(&fake, 0, sizeof(fake));
719 	fake.pw_name = "NOUSER";
720 	fake.pw_passwd =
721 	    "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
722 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
723 	fake.pw_gecos = "NOUSER";
724 #endif
725 	fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
726 	fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
727 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
728 	fake.pw_class = "";
729 #endif
730 	fake.pw_dir = "/nonexist";
731 	fake.pw_shell = "/nonexist";
732 
733 	return (&fake);
734 }
735 
736 /*
737  * Returns the remote DNS hostname as a string. The returned string must not
738  * be freed. NB. this will usually trigger a DNS query the first time it is
739  * called.
740  * This function does additional checks on the hostname to mitigate some
741  * attacks on legacy rhosts-style authentication.
742  * XXX is RhostsRSAAuthentication vulnerable to these?
743  * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
744  */
745 
746 static char *
747 remote_hostname(struct ssh *ssh)
748 {
749 	struct sockaddr_storage from;
750 	socklen_t fromlen;
751 	struct addrinfo hints, *ai, *aitop;
752 	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
753 	const char *ntop = ssh_remote_ipaddr(ssh);
754 
755 	/* Get IP address of client. */
756 	fromlen = sizeof(from);
757 	memset(&from, 0, sizeof(from));
758 	if (getpeername(ssh_packet_get_connection_in(ssh),
759 	    (struct sockaddr *)&from, &fromlen) < 0) {
760 		debug("getpeername failed: %.100s", strerror(errno));
761 		return strdup(ntop);
762 	}
763 
764 	ipv64_normalise_mapped(&from, &fromlen);
765 	if (from.ss_family == AF_INET6)
766 		fromlen = sizeof(struct sockaddr_in6);
767 
768 	debug3("Trying to reverse map address %.100s.", ntop);
769 	/* Map the IP address to a host name. */
770 	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
771 	    NULL, 0, NI_NAMEREQD) != 0) {
772 		/* Host name not found.  Use ip address. */
773 		return strdup(ntop);
774 	}
775 
776 	/*
777 	 * if reverse lookup result looks like a numeric hostname,
778 	 * someone is trying to trick us by PTR record like following:
779 	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
780 	 */
781 	memset(&hints, 0, sizeof(hints));
782 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
783 	hints.ai_flags = AI_NUMERICHOST;
784 	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
785 		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
786 		    name, ntop);
787 		freeaddrinfo(ai);
788 		return strdup(ntop);
789 	}
790 
791 	/* Names are stored in lowercase. */
792 	lowercase(name);
793 
794 	/*
795 	 * Map it back to an IP address and check that the given
796 	 * address actually is an address of this host.  This is
797 	 * necessary because anyone with access to a name server can
798 	 * define arbitrary names for an IP address. Mapping from
799 	 * name to IP address can be trusted better (but can still be
800 	 * fooled if the intruder has access to the name server of
801 	 * the domain).
802 	 */
803 	memset(&hints, 0, sizeof(hints));
804 	hints.ai_family = from.ss_family;
805 	hints.ai_socktype = SOCK_STREAM;
806 	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
807 		logit("reverse mapping checking getaddrinfo for %.700s "
808 		    "[%s] failed.", name, ntop);
809 		return strdup(ntop);
810 	}
811 	/* Look for the address from the list of addresses. */
812 	for (ai = aitop; ai; ai = ai->ai_next) {
813 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
814 		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
815 		    (strcmp(ntop, ntop2) == 0))
816 				break;
817 	}
818 	freeaddrinfo(aitop);
819 	/* If we reached the end of the list, the address was not there. */
820 	if (ai == NULL) {
821 		/* Address not found for the host name. */
822 		logit("Address %.100s maps to %.600s, but this does not "
823 		    "map back to the address.", ntop, name);
824 		return strdup(ntop);
825 	}
826 	return strdup(name);
827 }
828 
829 /*
830  * Return the canonical name of the host in the other side of the current
831  * connection.  The host name is cached, so it is efficient to call this
832  * several times.
833  */
834 
835 const char *
836 auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
837 {
838 	static char *dnsname;
839 
840 	if (!use_dns)
841 		return ssh_remote_ipaddr(ssh);
842 	else if (dnsname != NULL)
843 		return dnsname;
844 	else {
845 		dnsname = remote_hostname(ssh);
846 		return dnsname;
847 	}
848 }
849