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