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