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