xref: /freebsd/crypto/openssh/auth.c (revision a3266ba2697a383d2ede56803320d941866c7e76)
1 /* $OpenBSD: auth.c,v 1.133 2018/09/12 01:19:12 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 #include <sys/wait.h>
33 
34 #include <netinet/in.h>
35 
36 #include <errno.h>
37 #include <fcntl.h>
38 #ifdef HAVE_PATHS_H
39 # include <paths.h>
40 #endif
41 #include <pwd.h>
42 #ifdef HAVE_LOGIN_H
43 #include <login.h>
44 #endif
45 #ifdef USE_SHADOW
46 #include <shadow.h>
47 #endif
48 #include <stdarg.h>
49 #include <stdio.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <limits.h>
53 #include <netdb.h>
54 
55 #include "xmalloc.h"
56 #include "match.h"
57 #include "groupaccess.h"
58 #include "log.h"
59 #include "sshbuf.h"
60 #include "misc.h"
61 #include "servconf.h"
62 #include "sshkey.h"
63 #include "hostfile.h"
64 #include "auth.h"
65 #include "auth-options.h"
66 #include "canohost.h"
67 #include "uidswap.h"
68 #include "packet.h"
69 #include "loginrec.h"
70 #ifdef GSSAPI
71 #include "ssh-gss.h"
72 #endif
73 #include "authfile.h"
74 #include "monitor_wrap.h"
75 #include "authfile.h"
76 #include "ssherr.h"
77 #include "compat.h"
78 #include "channels.h"
79 #include "blacklist_client.h"
80 
81 /* import */
82 extern ServerOptions options;
83 extern int use_privsep;
84 extern struct sshbuf *loginmsg;
85 extern struct passwd *privsep_pw;
86 extern struct sshauthopt *auth_opts;
87 
88 /* Debugging messages */
89 static struct sshbuf *auth_debug;
90 
91 /*
92  * Check if the user is allowed to log in via ssh. If user is listed
93  * in DenyUsers or one of user's groups is listed in DenyGroups, false
94  * will be returned. If AllowUsers isn't empty and user isn't listed
95  * there, or if AllowGroups isn't empty and one of user's groups isn't
96  * listed there, false will be returned.
97  * If the user's shell is not executable, false will be returned.
98  * Otherwise true is returned.
99  */
100 int
101 allowed_user(struct passwd * pw)
102 {
103 	struct ssh *ssh = active_state; /* XXX */
104 	struct stat st;
105 	const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
106 	u_int i;
107 	int r;
108 #ifdef USE_SHADOW
109 	struct spwd *spw = NULL;
110 #endif
111 
112 	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
113 	if (!pw || !pw->pw_name)
114 		return 0;
115 
116 #ifdef USE_SHADOW
117 	if (!options.use_pam)
118 		spw = getspnam(pw->pw_name);
119 #ifdef HAS_SHADOW_EXPIRE
120 	if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
121 		return 0;
122 #endif /* HAS_SHADOW_EXPIRE */
123 #endif /* USE_SHADOW */
124 
125 	/* grab passwd field for locked account check */
126 	passwd = pw->pw_passwd;
127 #ifdef USE_SHADOW
128 	if (spw != NULL)
129 #ifdef USE_LIBIAF
130 		passwd = get_iaf_password(pw);
131 #else
132 		passwd = spw->sp_pwdp;
133 #endif /* USE_LIBIAF */
134 #endif
135 
136 	/* check for locked account */
137 	if (!options.use_pam && passwd && *passwd) {
138 		int locked = 0;
139 
140 #ifdef LOCKED_PASSWD_STRING
141 		if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
142 			 locked = 1;
143 #endif
144 #ifdef LOCKED_PASSWD_PREFIX
145 		if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
146 		    strlen(LOCKED_PASSWD_PREFIX)) == 0)
147 			 locked = 1;
148 #endif
149 #ifdef LOCKED_PASSWD_SUBSTR
150 		if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
151 			locked = 1;
152 #endif
153 #ifdef USE_LIBIAF
154 		free((void *) passwd);
155 #endif /* USE_LIBIAF */
156 		if (locked) {
157 			logit("User %.100s not allowed because account is locked",
158 			    pw->pw_name);
159 			return 0;
160 		}
161 	}
162 
163 	/*
164 	 * Deny if shell does not exist or is not executable unless we
165 	 * are chrooting.
166 	 */
167 	if (options.chroot_directory == NULL ||
168 	    strcasecmp(options.chroot_directory, "none") == 0) {
169 		char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
170 		    _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
171 
172 		if (stat(shell, &st) != 0) {
173 			logit("User %.100s not allowed because shell %.100s "
174 			    "does not exist", pw->pw_name, shell);
175 			free(shell);
176 			return 0;
177 		}
178 		if (S_ISREG(st.st_mode) == 0 ||
179 		    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
180 			logit("User %.100s not allowed because shell %.100s "
181 			    "is not executable", pw->pw_name, shell);
182 			free(shell);
183 			return 0;
184 		}
185 		free(shell);
186 	}
187 
188 	if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
189 	    options.num_deny_groups > 0 || options.num_allow_groups > 0) {
190 		hostname = auth_get_canonical_hostname(ssh, options.use_dns);
191 		ipaddr = ssh_remote_ipaddr(ssh);
192 	}
193 
194 	/* Return false if user is listed in DenyUsers */
195 	if (options.num_deny_users > 0) {
196 		for (i = 0; i < options.num_deny_users; i++) {
197 			r = match_user(pw->pw_name, hostname, ipaddr,
198 			    options.deny_users[i]);
199 			if (r < 0) {
200 				fatal("Invalid DenyUsers pattern \"%.100s\"",
201 				    options.deny_users[i]);
202 			} else if (r != 0) {
203 				logit("User %.100s from %.100s not allowed "
204 				    "because listed in DenyUsers",
205 				    pw->pw_name, hostname);
206 				return 0;
207 			}
208 		}
209 	}
210 	/* Return false if AllowUsers isn't empty and user isn't listed there */
211 	if (options.num_allow_users > 0) {
212 		for (i = 0; i < options.num_allow_users; i++) {
213 			r = match_user(pw->pw_name, hostname, ipaddr,
214 			    options.allow_users[i]);
215 			if (r < 0) {
216 				fatal("Invalid AllowUsers pattern \"%.100s\"",
217 				    options.allow_users[i]);
218 			} else if (r == 1)
219 				break;
220 		}
221 		/* i < options.num_allow_users iff we break for loop */
222 		if (i >= options.num_allow_users) {
223 			logit("User %.100s from %.100s not allowed because "
224 			    "not listed in AllowUsers", pw->pw_name, hostname);
225 			return 0;
226 		}
227 	}
228 	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
229 		/* Get the user's group access list (primary and supplementary) */
230 		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
231 			logit("User %.100s from %.100s not allowed because "
232 			    "not in any group", pw->pw_name, hostname);
233 			return 0;
234 		}
235 
236 		/* Return false if one of user's groups is listed in DenyGroups */
237 		if (options.num_deny_groups > 0)
238 			if (ga_match(options.deny_groups,
239 			    options.num_deny_groups)) {
240 				ga_free();
241 				logit("User %.100s from %.100s not allowed "
242 				    "because a group is listed in DenyGroups",
243 				    pw->pw_name, hostname);
244 				return 0;
245 			}
246 		/*
247 		 * Return false if AllowGroups isn't empty and one of user's groups
248 		 * isn't listed there
249 		 */
250 		if (options.num_allow_groups > 0)
251 			if (!ga_match(options.allow_groups,
252 			    options.num_allow_groups)) {
253 				ga_free();
254 				logit("User %.100s from %.100s not allowed "
255 				    "because none of user's groups are listed "
256 				    "in AllowGroups", pw->pw_name, hostname);
257 				return 0;
258 			}
259 		ga_free();
260 	}
261 
262 #ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
263 	if (!sys_auth_allowed_user(pw, &loginmsg))
264 		return 0;
265 #endif
266 
267 	/* We found no reason not to let this user try to log on... */
268 	return 1;
269 }
270 
271 /*
272  * Formats any key left in authctxt->auth_method_key for inclusion in
273  * auth_log()'s message. Also includes authxtct->auth_method_info if present.
274  */
275 static char *
276 format_method_key(Authctxt *authctxt)
277 {
278 	const struct sshkey *key = authctxt->auth_method_key;
279 	const char *methinfo = authctxt->auth_method_info;
280 	char *fp, *cafp, *ret = NULL;
281 
282 	if (key == NULL)
283 		return NULL;
284 
285 	if (sshkey_is_cert(key)) {
286 		fp = sshkey_fingerprint(key,
287 		    options.fingerprint_hash, SSH_FP_DEFAULT);
288 		cafp = sshkey_fingerprint(key->cert->signature_key,
289 		    options.fingerprint_hash, SSH_FP_DEFAULT);
290 		xasprintf(&ret, "%s %s ID %s (serial %llu) CA %s %s%s%s",
291 		    sshkey_type(key), fp == NULL ? "(null)" : fp,
292 		    key->cert->key_id,
293 		    (unsigned long long)key->cert->serial,
294 		    sshkey_type(key->cert->signature_key),
295 		    cafp == NULL ? "(null)" : cafp,
296 		    methinfo == NULL ? "" : ", ",
297 		    methinfo == NULL ? "" : methinfo);
298 		free(fp);
299 		free(cafp);
300 	} else {
301 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
302 		    SSH_FP_DEFAULT);
303 		xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
304 		    fp == NULL ? "(null)" : fp,
305 		    methinfo == NULL ? "" : ", ",
306 		    methinfo == NULL ? "" : methinfo);
307 		free(fp);
308 	}
309 	return ret;
310 }
311 
312 void
313 auth_log(Authctxt *authctxt, int authenticated, int partial,
314     const char *method, const char *submethod)
315 {
316 	struct ssh *ssh = active_state; /* XXX */
317 	int level = SYSLOG_LEVEL_VERBOSE;
318 	const char *authmsg;
319 	char *extra = NULL;
320 
321 	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
322 		return;
323 
324 	/* Raise logging level */
325 	if (authenticated == 1 ||
326 	    !authctxt->valid ||
327 	    authctxt->failures >= options.max_authtries / 2 ||
328 	    strcmp(method, "password") == 0)
329 		level = SYSLOG_LEVEL_INFO;
330 
331 	if (authctxt->postponed)
332 		authmsg = "Postponed";
333 	else if (partial)
334 		authmsg = "Partial";
335 	else {
336 		authmsg = authenticated ? "Accepted" : "Failed";
337 		if (authenticated)
338 			BLACKLIST_NOTIFY(BLACKLIST_AUTH_OK, "ssh");
339 	}
340 
341 	if ((extra = format_method_key(authctxt)) == NULL) {
342 		if (authctxt->auth_method_info != NULL)
343 			extra = xstrdup(authctxt->auth_method_info);
344 	}
345 
346 	do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
347 	    authmsg,
348 	    method,
349 	    submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
350 	    authctxt->valid ? "" : "invalid user ",
351 	    authctxt->user,
352 	    ssh_remote_ipaddr(ssh),
353 	    ssh_remote_port(ssh),
354 	    extra != NULL ? ": " : "",
355 	    extra != NULL ? extra : "");
356 
357 	free(extra);
358 
359 #ifdef CUSTOM_FAILED_LOGIN
360 	if (authenticated == 0 && !authctxt->postponed &&
361 	    (strcmp(method, "password") == 0 ||
362 	    strncmp(method, "keyboard-interactive", 20) == 0 ||
363 	    strcmp(method, "challenge-response") == 0))
364 		record_failed_login(authctxt->user,
365 		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
366 # ifdef WITH_AIXAUTHENTICATE
367 	if (authenticated)
368 		sys_auth_record_login(authctxt->user,
369 		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh",
370 		    &loginmsg);
371 # endif
372 #endif
373 #ifdef SSH_AUDIT_EVENTS
374 	if (authenticated == 0 && !authctxt->postponed)
375 		audit_event(audit_classify_auth(method));
376 #endif
377 }
378 
379 
380 void
381 auth_maxtries_exceeded(Authctxt *authctxt)
382 {
383 	struct ssh *ssh = active_state; /* XXX */
384 
385 	error("maximum authentication attempts exceeded for "
386 	    "%s%.100s from %.200s port %d ssh2",
387 	    authctxt->valid ? "" : "invalid user ",
388 	    authctxt->user,
389 	    ssh_remote_ipaddr(ssh),
390 	    ssh_remote_port(ssh));
391 	packet_disconnect("Too many authentication failures");
392 	/* NOTREACHED */
393 }
394 
395 /*
396  * Check whether root logins are disallowed.
397  */
398 int
399 auth_root_allowed(struct ssh *ssh, const char *method)
400 {
401 	switch (options.permit_root_login) {
402 	case PERMIT_YES:
403 		return 1;
404 	case PERMIT_NO_PASSWD:
405 		if (strcmp(method, "publickey") == 0 ||
406 		    strcmp(method, "hostbased") == 0 ||
407 		    strcmp(method, "gssapi-with-mic") == 0)
408 			return 1;
409 		break;
410 	case PERMIT_FORCED_ONLY:
411 		if (auth_opts->force_command != NULL) {
412 			logit("Root login accepted for forced command.");
413 			return 1;
414 		}
415 		break;
416 	}
417 	logit("ROOT LOGIN REFUSED FROM %.200s port %d",
418 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
419 	return 0;
420 }
421 
422 
423 /*
424  * Given a template and a passwd structure, build a filename
425  * by substituting % tokenised options. Currently, %% becomes '%',
426  * %h becomes the home directory and %u the username.
427  *
428  * This returns a buffer allocated by xmalloc.
429  */
430 char *
431 expand_authorized_keys(const char *filename, struct passwd *pw)
432 {
433 	char *file, uidstr[32], ret[PATH_MAX];
434 	int i;
435 
436 	snprintf(uidstr, sizeof(uidstr), "%llu",
437 	    (unsigned long long)pw->pw_uid);
438 	file = percent_expand(filename, "h", pw->pw_dir,
439 	    "u", pw->pw_name, "U", uidstr, (char *)NULL);
440 
441 	/*
442 	 * Ensure that filename starts anchored. If not, be backward
443 	 * compatible and prepend the '%h/'
444 	 */
445 	if (*file == '/')
446 		return (file);
447 
448 	i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
449 	if (i < 0 || (size_t)i >= sizeof(ret))
450 		fatal("expand_authorized_keys: path too long");
451 	free(file);
452 	return (xstrdup(ret));
453 }
454 
455 char *
456 authorized_principals_file(struct passwd *pw)
457 {
458 	if (options.authorized_principals_file == NULL)
459 		return NULL;
460 	return expand_authorized_keys(options.authorized_principals_file, pw);
461 }
462 
463 /* return ok if key exists in sysfile or userfile */
464 HostStatus
465 check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
466     const char *sysfile, const char *userfile)
467 {
468 	char *user_hostfile;
469 	struct stat st;
470 	HostStatus host_status;
471 	struct hostkeys *hostkeys;
472 	const struct hostkey_entry *found;
473 
474 	hostkeys = init_hostkeys();
475 	load_hostkeys(hostkeys, host, sysfile);
476 	if (userfile != NULL) {
477 		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
478 		if (options.strict_modes &&
479 		    (stat(user_hostfile, &st) == 0) &&
480 		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
481 		    (st.st_mode & 022) != 0)) {
482 			logit("Authentication refused for %.100s: "
483 			    "bad owner or modes for %.200s",
484 			    pw->pw_name, user_hostfile);
485 			auth_debug_add("Ignored %.200s: bad ownership or modes",
486 			    user_hostfile);
487 		} else {
488 			temporarily_use_uid(pw);
489 			load_hostkeys(hostkeys, host, user_hostfile);
490 			restore_uid();
491 		}
492 		free(user_hostfile);
493 	}
494 	host_status = check_key_in_hostkeys(hostkeys, key, &found);
495 	if (host_status == HOST_REVOKED)
496 		error("WARNING: revoked key for %s attempted authentication",
497 		    found->host);
498 	else if (host_status == HOST_OK)
499 		debug("%s: key for %s found at %s:%ld", __func__,
500 		    found->host, found->file, found->line);
501 	else
502 		debug("%s: key for host %s not found", __func__, host);
503 
504 	free_hostkeys(hostkeys);
505 
506 	return host_status;
507 }
508 
509 static FILE *
510 auth_openfile(const char *file, struct passwd *pw, int strict_modes,
511     int log_missing, char *file_type)
512 {
513 	char line[1024];
514 	struct stat st;
515 	int fd;
516 	FILE *f;
517 
518 	if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
519 		if (log_missing || errno != ENOENT)
520 			debug("Could not open %s '%s': %s", file_type, file,
521 			   strerror(errno));
522 		return NULL;
523 	}
524 
525 	if (fstat(fd, &st) < 0) {
526 		close(fd);
527 		return NULL;
528 	}
529 	if (!S_ISREG(st.st_mode)) {
530 		logit("User %s %s %s is not a regular file",
531 		    pw->pw_name, file_type, file);
532 		close(fd);
533 		return NULL;
534 	}
535 	unset_nonblock(fd);
536 	if ((f = fdopen(fd, "r")) == NULL) {
537 		close(fd);
538 		return NULL;
539 	}
540 	if (strict_modes &&
541 	    safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) {
542 		fclose(f);
543 		logit("Authentication refused: %s", line);
544 		auth_debug_add("Ignored %s: %s", file_type, line);
545 		return NULL;
546 	}
547 
548 	return f;
549 }
550 
551 
552 FILE *
553 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
554 {
555 	return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
556 }
557 
558 FILE *
559 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
560 {
561 	return auth_openfile(file, pw, strict_modes, 0,
562 	    "authorized principals");
563 }
564 
565 struct passwd *
566 getpwnamallow(const char *user)
567 {
568 	struct ssh *ssh = active_state; /* XXX */
569 #ifdef HAVE_LOGIN_CAP
570 	extern login_cap_t *lc;
571 #ifdef HAVE_AUTH_HOSTOK
572 	const char *from_host, *from_ip;
573 #endif
574 #ifdef BSD_AUTH
575 	auth_session_t *as;
576 #endif
577 #endif
578 	struct passwd *pw;
579 	struct connection_info *ci = get_connection_info(1, options.use_dns);
580 
581 	ci->user = user;
582 	parse_server_match_config(&options, ci);
583 	log_change_level(options.log_level);
584 	process_permitopen(ssh, &options);
585 
586 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
587 	aix_setauthdb(user);
588 #endif
589 
590 	pw = getpwnam(user);
591 
592 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
593 	aix_restoreauthdb();
594 #endif
595 #ifdef HAVE_CYGWIN
596 	/*
597 	 * Windows usernames are case-insensitive.  To avoid later problems
598 	 * when trying to match the username, the user is only allowed to
599 	 * login if the username is given in the same case as stored in the
600 	 * user database.
601 	 */
602 	if (pw != NULL && strcmp(user, pw->pw_name) != 0) {
603 		logit("Login name %.100s does not match stored username %.100s",
604 		    user, pw->pw_name);
605 		pw = NULL;
606 	}
607 #endif
608 	if (pw == NULL) {
609 		BLACKLIST_NOTIFY(BLACKLIST_BAD_USER, user);
610 		logit("Invalid user %.100s from %.100s port %d",
611 		    user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
612 #ifdef CUSTOM_FAILED_LOGIN
613 		record_failed_login(user,
614 		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
615 #endif
616 #ifdef SSH_AUDIT_EVENTS
617 		audit_event(SSH_INVALID_USER);
618 #endif /* SSH_AUDIT_EVENTS */
619 		return (NULL);
620 	}
621 	if (!allowed_user(pw))
622 		return (NULL);
623 #ifdef HAVE_LOGIN_CAP
624 	if ((lc = login_getpwclass(pw)) == NULL) {
625 		debug("unable to get login class: %s", user);
626 		return (NULL);
627 	}
628 #ifdef HAVE_AUTH_HOSTOK
629 	from_host = auth_get_canonical_hostname(ssh, options.use_dns);
630 	from_ip = ssh_remote_ipaddr(ssh);
631 	if (!auth_hostok(lc, from_host, from_ip)) {
632 		debug("Denied connection for %.200s from %.200s [%.200s].",
633 		    pw->pw_name, from_host, from_ip);
634 		return (NULL);
635 	}
636 #endif /* HAVE_AUTH_HOSTOK */
637 #ifdef HAVE_AUTH_TIMEOK
638 	if (!auth_timeok(lc, time(NULL))) {
639 		debug("LOGIN %.200s REFUSED (TIME)", pw->pw_name);
640 		return (NULL);
641 	}
642 #endif /* HAVE_AUTH_TIMEOK */
643 #ifdef BSD_AUTH
644 	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
645 	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
646 		debug("Approval failure for %s", user);
647 		pw = NULL;
648 	}
649 	if (as != NULL)
650 		auth_close(as);
651 #endif
652 #endif
653 	if (pw != NULL)
654 		return (pwcopy(pw));
655 	return (NULL);
656 }
657 
658 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
659 int
660 auth_key_is_revoked(struct sshkey *key)
661 {
662 	char *fp = NULL;
663 	int r;
664 
665 	if (options.revoked_keys_file == NULL)
666 		return 0;
667 	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
668 	    SSH_FP_DEFAULT)) == NULL) {
669 		r = SSH_ERR_ALLOC_FAIL;
670 		error("%s: fingerprint key: %s", __func__, ssh_err(r));
671 		goto out;
672 	}
673 
674 	r = sshkey_check_revoked(key, options.revoked_keys_file);
675 	switch (r) {
676 	case 0:
677 		break; /* not revoked */
678 	case SSH_ERR_KEY_REVOKED:
679 		error("Authentication key %s %s revoked by file %s",
680 		    sshkey_type(key), fp, options.revoked_keys_file);
681 		goto out;
682 	default:
683 		error("Error checking authentication key %s %s in "
684 		    "revoked keys file %s: %s", sshkey_type(key), fp,
685 		    options.revoked_keys_file, ssh_err(r));
686 		goto out;
687 	}
688 
689 	/* Success */
690 	r = 0;
691 
692  out:
693 	free(fp);
694 	return r == 0 ? 0 : 1;
695 }
696 
697 void
698 auth_debug_add(const char *fmt,...)
699 {
700 	char buf[1024];
701 	va_list args;
702 	int r;
703 
704 	if (auth_debug == NULL)
705 		return;
706 
707 	va_start(args, fmt);
708 	vsnprintf(buf, sizeof(buf), fmt, args);
709 	va_end(args);
710 	if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0)
711 		fatal("%s: sshbuf_put_cstring: %s", __func__, ssh_err(r));
712 }
713 
714 void
715 auth_debug_send(void)
716 {
717 	struct ssh *ssh = active_state;		/* XXX */
718 	char *msg;
719 	int r;
720 
721 	if (auth_debug == NULL)
722 		return;
723 	while (sshbuf_len(auth_debug) != 0) {
724 		if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0)
725 			fatal("%s: sshbuf_get_cstring: %s",
726 			    __func__, ssh_err(r));
727 		ssh_packet_send_debug(ssh, "%s", msg);
728 		free(msg);
729 	}
730 }
731 
732 void
733 auth_debug_reset(void)
734 {
735 	if (auth_debug != NULL)
736 		sshbuf_reset(auth_debug);
737 	else if ((auth_debug = sshbuf_new()) == NULL)
738 		fatal("%s: sshbuf_new failed", __func__);
739 }
740 
741 struct passwd *
742 fakepw(void)
743 {
744 	static struct passwd fake;
745 
746 	memset(&fake, 0, sizeof(fake));
747 	fake.pw_name = "NOUSER";
748 	fake.pw_passwd =
749 	    "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
750 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
751 	fake.pw_gecos = "NOUSER";
752 #endif
753 	fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
754 	fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
755 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
756 	fake.pw_class = "";
757 #endif
758 	fake.pw_dir = "/nonexist";
759 	fake.pw_shell = "/nonexist";
760 
761 	return (&fake);
762 }
763 
764 /*
765  * Returns the remote DNS hostname as a string. The returned string must not
766  * be freed. NB. this will usually trigger a DNS query the first time it is
767  * called.
768  * This function does additional checks on the hostname to mitigate some
769  * attacks on legacy rhosts-style authentication.
770  * XXX is RhostsRSAAuthentication vulnerable to these?
771  * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
772  */
773 
774 static char *
775 remote_hostname(struct ssh *ssh)
776 {
777 	struct sockaddr_storage from;
778 	socklen_t fromlen;
779 	struct addrinfo hints, *ai, *aitop;
780 	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
781 	const char *ntop = ssh_remote_ipaddr(ssh);
782 
783 	/* Get IP address of client. */
784 	fromlen = sizeof(from);
785 	memset(&from, 0, sizeof(from));
786 	if (getpeername(ssh_packet_get_connection_in(ssh),
787 	    (struct sockaddr *)&from, &fromlen) < 0) {
788 		debug("getpeername failed: %.100s", strerror(errno));
789 		return strdup(ntop);
790 	}
791 
792 	ipv64_normalise_mapped(&from, &fromlen);
793 	if (from.ss_family == AF_INET6)
794 		fromlen = sizeof(struct sockaddr_in6);
795 
796 	debug3("Trying to reverse map address %.100s.", ntop);
797 	/* Map the IP address to a host name. */
798 	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
799 	    NULL, 0, NI_NAMEREQD) != 0) {
800 		/* Host name not found.  Use ip address. */
801 		return strdup(ntop);
802 	}
803 
804 	/*
805 	 * if reverse lookup result looks like a numeric hostname,
806 	 * someone is trying to trick us by PTR record like following:
807 	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
808 	 */
809 	memset(&hints, 0, sizeof(hints));
810 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
811 	hints.ai_flags = AI_NUMERICHOST;
812 	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
813 		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
814 		    name, ntop);
815 		freeaddrinfo(ai);
816 		return strdup(ntop);
817 	}
818 
819 	/* Names are stored in lowercase. */
820 	lowercase(name);
821 
822 	/*
823 	 * Map it back to an IP address and check that the given
824 	 * address actually is an address of this host.  This is
825 	 * necessary because anyone with access to a name server can
826 	 * define arbitrary names for an IP address. Mapping from
827 	 * name to IP address can be trusted better (but can still be
828 	 * fooled if the intruder has access to the name server of
829 	 * the domain).
830 	 */
831 	memset(&hints, 0, sizeof(hints));
832 	hints.ai_family = from.ss_family;
833 	hints.ai_socktype = SOCK_STREAM;
834 	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
835 		logit("reverse mapping checking getaddrinfo for %.700s "
836 		    "[%s] failed.", name, ntop);
837 		return strdup(ntop);
838 	}
839 	/* Look for the address from the list of addresses. */
840 	for (ai = aitop; ai; ai = ai->ai_next) {
841 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
842 		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
843 		    (strcmp(ntop, ntop2) == 0))
844 				break;
845 	}
846 	freeaddrinfo(aitop);
847 	/* If we reached the end of the list, the address was not there. */
848 	if (ai == NULL) {
849 		/* Address not found for the host name. */
850 		logit("Address %.100s maps to %.600s, but this does not "
851 		    "map back to the address.", ntop, name);
852 		return strdup(ntop);
853 	}
854 	return strdup(name);
855 }
856 
857 /*
858  * Return the canonical name of the host in the other side of the current
859  * connection.  The host name is cached, so it is efficient to call this
860  * several times.
861  */
862 
863 const char *
864 auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
865 {
866 	static char *dnsname;
867 
868 	if (!use_dns)
869 		return ssh_remote_ipaddr(ssh);
870 	else if (dnsname != NULL)
871 		return dnsname;
872 	else {
873 		dnsname = remote_hostname(ssh);
874 		return dnsname;
875 	}
876 }
877 
878 /*
879  * Runs command in a subprocess with a minimal environment.
880  * Returns pid on success, 0 on failure.
881  * The child stdout and stderr maybe captured, left attached or sent to
882  * /dev/null depending on the contents of flags.
883  * "tag" is prepended to log messages.
884  * NB. "command" is only used for logging; the actual command executed is
885  * av[0].
886  */
887 pid_t
888 subprocess(const char *tag, struct passwd *pw, const char *command,
889     int ac, char **av, FILE **child, u_int flags)
890 {
891 	FILE *f = NULL;
892 	struct stat st;
893 	int fd, devnull, p[2], i;
894 	pid_t pid;
895 	char *cp, errmsg[512];
896 	u_int envsize;
897 	char **child_env;
898 
899 	if (child != NULL)
900 		*child = NULL;
901 
902 	debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__,
903 	    tag, command, pw->pw_name, flags);
904 
905 	/* Check consistency */
906 	if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
907 	    (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
908 		error("%s: inconsistent flags", __func__);
909 		return 0;
910 	}
911 	if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
912 		error("%s: inconsistent flags/output", __func__);
913 		return 0;
914 	}
915 
916 	/*
917 	 * If executing an explicit binary, then verify the it exists
918 	 * and appears safe-ish to execute
919 	 */
920 	if (*av[0] != '/') {
921 		error("%s path is not absolute", tag);
922 		return 0;
923 	}
924 	temporarily_use_uid(pw);
925 	if (stat(av[0], &st) < 0) {
926 		error("Could not stat %s \"%s\": %s", tag,
927 		    av[0], strerror(errno));
928 		restore_uid();
929 		return 0;
930 	}
931 	if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
932 		error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
933 		restore_uid();
934 		return 0;
935 	}
936 	/* Prepare to keep the child's stdout if requested */
937 	if (pipe(p) != 0) {
938 		error("%s: pipe: %s", tag, strerror(errno));
939 		restore_uid();
940 		return 0;
941 	}
942 	restore_uid();
943 
944 	switch ((pid = fork())) {
945 	case -1: /* error */
946 		error("%s: fork: %s", tag, strerror(errno));
947 		close(p[0]);
948 		close(p[1]);
949 		return 0;
950 	case 0: /* child */
951 		/* Prepare a minimal environment for the child. */
952 		envsize = 5;
953 		child_env = xcalloc(sizeof(*child_env), envsize);
954 		child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
955 		child_set_env(&child_env, &envsize, "USER", pw->pw_name);
956 		child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
957 		child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
958 		if ((cp = getenv("LANG")) != NULL)
959 			child_set_env(&child_env, &envsize, "LANG", cp);
960 
961 		for (i = 0; i < NSIG; i++)
962 			signal(i, SIG_DFL);
963 
964 		if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
965 			error("%s: open %s: %s", tag, _PATH_DEVNULL,
966 			    strerror(errno));
967 			_exit(1);
968 		}
969 		if (dup2(devnull, STDIN_FILENO) == -1) {
970 			error("%s: dup2: %s", tag, strerror(errno));
971 			_exit(1);
972 		}
973 
974 		/* Set up stdout as requested; leave stderr in place for now. */
975 		fd = -1;
976 		if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
977 			fd = p[1];
978 		else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
979 			fd = devnull;
980 		if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
981 			error("%s: dup2: %s", tag, strerror(errno));
982 			_exit(1);
983 		}
984 		closefrom(STDERR_FILENO + 1);
985 
986 		/* Don't use permanently_set_uid() here to avoid fatal() */
987 		if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0) {
988 			error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
989 			    strerror(errno));
990 			_exit(1);
991 		}
992 		if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0) {
993 			error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
994 			    strerror(errno));
995 			_exit(1);
996 		}
997 		/* stdin is pointed to /dev/null at this point */
998 		if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
999 		    dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
1000 			error("%s: dup2: %s", tag, strerror(errno));
1001 			_exit(1);
1002 		}
1003 
1004 		execve(av[0], av, child_env);
1005 		error("%s exec \"%s\": %s", tag, command, strerror(errno));
1006 		_exit(127);
1007 	default: /* parent */
1008 		break;
1009 	}
1010 
1011 	close(p[1]);
1012 	if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
1013 		close(p[0]);
1014 	else if ((f = fdopen(p[0], "r")) == NULL) {
1015 		error("%s: fdopen: %s", tag, strerror(errno));
1016 		close(p[0]);
1017 		/* Don't leave zombie child */
1018 		kill(pid, SIGTERM);
1019 		while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
1020 			;
1021 		return 0;
1022 	}
1023 	/* Success */
1024 	debug3("%s: %s pid %ld", __func__, tag, (long)pid);
1025 	if (child != NULL)
1026 		*child = f;
1027 	return pid;
1028 }
1029 
1030 /* These functions link key/cert options to the auth framework */
1031 
1032 /* Log sshauthopt options locally and (optionally) for remote transmission */
1033 void
1034 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
1035 {
1036 	int do_env = options.permit_user_env && opts->nenv > 0;
1037 	int do_permitopen = opts->npermitopen > 0 &&
1038 	    (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
1039 	int do_permitlisten = opts->npermitlisten > 0 &&
1040 	    (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0;
1041 	size_t i;
1042 	char msg[1024], buf[64];
1043 
1044 	snprintf(buf, sizeof(buf), "%d", opts->force_tun_device);
1045 	/* Try to keep this alphabetically sorted */
1046 	snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s",
1047 	    opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
1048 	    opts->force_command == NULL ? "" : " command",
1049 	    do_env ?  " environment" : "",
1050 	    opts->valid_before == 0 ? "" : "expires",
1051 	    do_permitopen ?  " permitopen" : "",
1052 	    do_permitlisten ?  " permitlisten" : "",
1053 	    opts->permit_port_forwarding_flag ? " port-forwarding" : "",
1054 	    opts->cert_principals == NULL ? "" : " principals",
1055 	    opts->permit_pty_flag ? " pty" : "",
1056 	    opts->force_tun_device == -1 ? "" : " tun=",
1057 	    opts->force_tun_device == -1 ? "" : buf,
1058 	    opts->permit_user_rc ? " user-rc" : "",
1059 	    opts->permit_x11_forwarding_flag ? " x11-forwarding" : "");
1060 
1061 	debug("%s: %s", loc, msg);
1062 	if (do_remote)
1063 		auth_debug_add("%s: %s", loc, msg);
1064 
1065 	if (options.permit_user_env) {
1066 		for (i = 0; i < opts->nenv; i++) {
1067 			debug("%s: environment: %s", loc, opts->env[i]);
1068 			if (do_remote) {
1069 				auth_debug_add("%s: environment: %s",
1070 				    loc, opts->env[i]);
1071 			}
1072 		}
1073 	}
1074 
1075 	/* Go into a little more details for the local logs. */
1076 	if (opts->valid_before != 0) {
1077 		format_absolute_time(opts->valid_before, buf, sizeof(buf));
1078 		debug("%s: expires at %s", loc, buf);
1079 	}
1080 	if (opts->cert_principals != NULL) {
1081 		debug("%s: authorized principals: \"%s\"",
1082 		    loc, opts->cert_principals);
1083 	}
1084 	if (opts->force_command != NULL)
1085 		debug("%s: forced command: \"%s\"", loc, opts->force_command);
1086 	if (do_permitopen) {
1087 		for (i = 0; i < opts->npermitopen; i++) {
1088 			debug("%s: permitted open: %s",
1089 			    loc, opts->permitopen[i]);
1090 		}
1091 	}
1092 	if (do_permitlisten) {
1093 		for (i = 0; i < opts->npermitlisten; i++) {
1094 			debug("%s: permitted listen: %s",
1095 			    loc, opts->permitlisten[i]);
1096 		}
1097 	}
1098 }
1099 
1100 /* Activate a new set of key/cert options; merging with what is there. */
1101 int
1102 auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
1103 {
1104 	struct sshauthopt *old = auth_opts;
1105 	const char *emsg = NULL;
1106 
1107 	debug("%s: setting new authentication options", __func__);
1108 	if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
1109 		error("Inconsistent authentication options: %s", emsg);
1110 		return -1;
1111 	}
1112 	return 0;
1113 }
1114 
1115 /* Disable forwarding, etc for the session */
1116 void
1117 auth_restrict_session(struct ssh *ssh)
1118 {
1119 	struct sshauthopt *restricted;
1120 
1121 	debug("%s: restricting session", __func__);
1122 
1123 	/* A blank sshauthopt defaults to permitting nothing */
1124 	restricted = sshauthopt_new();
1125 	restricted->permit_pty_flag = 1;
1126 	restricted->restricted = 1;
1127 
1128 	if (auth_activate_options(ssh, restricted) != 0)
1129 		fatal("%s: failed to restrict session", __func__);
1130 	sshauthopt_free(restricted);
1131 }
1132 
1133 int
1134 auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw,
1135     struct sshauthopt *opts, int allow_cert_authority, const char *loc)
1136 {
1137 	const char *remote_ip = ssh_remote_ipaddr(ssh);
1138 	const char *remote_host = auth_get_canonical_hostname(ssh,
1139 	    options.use_dns);
1140 	time_t now = time(NULL);
1141 	char buf[64];
1142 
1143 	/*
1144 	 * Check keys/principals file expiry time.
1145 	 * NB. validity interval in certificate is handled elsewhere.
1146 	 */
1147 	if (opts->valid_before && now > 0 &&
1148 	    opts->valid_before < (uint64_t)now) {
1149 		format_absolute_time(opts->valid_before, buf, sizeof(buf));
1150 		debug("%s: entry expired at %s", loc, buf);
1151 		auth_debug_add("%s: entry expired at %s", loc, buf);
1152 		return -1;
1153 	}
1154 	/* Consistency checks */
1155 	if (opts->cert_principals != NULL && !opts->cert_authority) {
1156 		debug("%s: principals on non-CA key", loc);
1157 		auth_debug_add("%s: principals on non-CA key", loc);
1158 		/* deny access */
1159 		return -1;
1160 	}
1161 	/* cert-authority flag isn't valid in authorized_principals files */
1162 	if (!allow_cert_authority && opts->cert_authority) {
1163 		debug("%s: cert-authority flag invalid here", loc);
1164 		auth_debug_add("%s: cert-authority flag invalid here", loc);
1165 		/* deny access */
1166 		return -1;
1167 	}
1168 
1169 	/* Perform from= checks */
1170 	if (opts->required_from_host_keys != NULL) {
1171 		switch (match_host_and_ip(remote_host, remote_ip,
1172 		    opts->required_from_host_keys )) {
1173 		case 1:
1174 			/* Host name matches. */
1175 			break;
1176 		case -1:
1177 		default:
1178 			debug("%s: invalid from criteria", loc);
1179 			auth_debug_add("%s: invalid from criteria", loc);
1180 			/* FALLTHROUGH */
1181 		case 0:
1182 			logit("%s: Authentication tried for %.100s with "
1183 			    "correct key but not from a permitted "
1184 			    "host (host=%.200s, ip=%.200s, required=%.200s).",
1185 			    loc, pw->pw_name, remote_host, remote_ip,
1186 			    opts->required_from_host_keys);
1187 			auth_debug_add("%s: Your host '%.200s' is not "
1188 			    "permitted to use this key for login.",
1189 			    loc, remote_host);
1190 			/* deny access */
1191 			return -1;
1192 		}
1193 	}
1194 	/* Check source-address restriction from certificate */
1195 	if (opts->required_from_host_cert != NULL) {
1196 		switch (addr_match_cidr_list(remote_ip,
1197 		    opts->required_from_host_cert)) {
1198 		case 1:
1199 			/* accepted */
1200 			break;
1201 		case -1:
1202 		default:
1203 			/* invalid */
1204 			error("%s: Certificate source-address invalid",
1205 			    loc);
1206 			/* FALLTHROUGH */
1207 		case 0:
1208 			logit("%s: Authentication tried for %.100s with valid "
1209 			    "certificate but not from a permitted source "
1210 			    "address (%.200s).", loc, pw->pw_name, remote_ip);
1211 			auth_debug_add("%s: Your address '%.200s' is not "
1212 			    "permitted to use this certificate for login.",
1213 			    loc, remote_ip);
1214 			return -1;
1215 		}
1216 	}
1217 	/*
1218 	 *
1219 	 * XXX this is spammy. We should report remotely only for keys
1220 	 *     that are successful in actual auth attempts, and not PK_OK
1221 	 *     tests.
1222 	 */
1223 	auth_log_authopts(loc, opts, 1);
1224 
1225 	return 0;
1226 }
1227