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