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