xref: /openssh-portable/auth.c (revision 08f66d9f)
1 /* $OpenBSD: auth.c,v 1.138 2019/01/19 21:41:18 djm Exp $ */
2 /*
3  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 
26 #include "includes.h"
27 
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <sys/socket.h>
31 #include <sys/wait.h>
32 
33 #include <netinet/in.h>
34 
35 #include <errno.h>
36 #include <fcntl.h>
37 #ifdef HAVE_PATHS_H
38 # include <paths.h>
39 #endif
40 #include <pwd.h>
41 #ifdef HAVE_LOGIN_H
42 #include <login.h>
43 #endif
44 #ifdef USE_SHADOW
45 #include <shadow.h>
46 #endif
47 #include <stdarg.h>
48 #include <stdio.h>
49 #include <string.h>
50 #include <unistd.h>
51 #include <limits.h>
52 #include <netdb.h>
53 #include <time.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 
80 /* import */
81 extern ServerOptions options;
82 extern int use_privsep;
83 extern struct sshbuf *loginmsg;
84 extern struct passwd *privsep_pw;
85 extern struct sshauthopt *auth_opts;
86 
87 /* Debugging messages */
88 static struct sshbuf *auth_debug;
89 
90 /*
91  * Check if the user is allowed to log in via ssh. If user is listed
92  * in DenyUsers or one of user's groups is listed in DenyGroups, false
93  * will be returned. If AllowUsers isn't empty and user isn't listed
94  * there, or if AllowGroups isn't empty and one of user's groups isn't
95  * listed there, false will be returned.
96  * If the user's shell is not executable, false will be returned.
97  * Otherwise true is returned.
98  */
99 int
100 allowed_user(struct ssh *ssh, struct passwd * pw)
101 {
102 	struct stat st;
103 	const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
104 	u_int i;
105 	int r;
106 #ifdef USE_SHADOW
107 	struct spwd *spw = NULL;
108 #endif
109 
110 	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
111 	if (!pw || !pw->pw_name)
112 		return 0;
113 
114 #ifdef USE_SHADOW
115 	if (!options.use_pam)
116 		spw = getspnam(pw->pw_name);
117 #ifdef HAS_SHADOW_EXPIRE
118 	if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
119 		return 0;
120 #endif /* HAS_SHADOW_EXPIRE */
121 #endif /* USE_SHADOW */
122 
123 	/* grab passwd field for locked account check */
124 	passwd = pw->pw_passwd;
125 #ifdef USE_SHADOW
126 	if (spw != NULL)
127 #ifdef USE_LIBIAF
128 		passwd = get_iaf_password(pw);
129 #else
130 		passwd = spw->sp_pwdp;
131 #endif /* USE_LIBIAF */
132 #endif
133 
134 	/* check for locked account */
135 	if (!options.use_pam && passwd && *passwd) {
136 		int locked = 0;
137 
138 #ifdef LOCKED_PASSWD_STRING
139 		if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
140 			 locked = 1;
141 #endif
142 #ifdef LOCKED_PASSWD_PREFIX
143 		if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
144 		    strlen(LOCKED_PASSWD_PREFIX)) == 0)
145 			 locked = 1;
146 #endif
147 #ifdef LOCKED_PASSWD_SUBSTR
148 		if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
149 			locked = 1;
150 #endif
151 #ifdef USE_LIBIAF
152 		free((void *) passwd);
153 #endif /* USE_LIBIAF */
154 		if (locked) {
155 			logit("User %.100s not allowed because account is locked",
156 			    pw->pw_name);
157 			return 0;
158 		}
159 	}
160 
161 	/*
162 	 * Deny if shell does not exist or is not executable unless we
163 	 * are chrooting.
164 	 */
165 	if (options.chroot_directory == NULL ||
166 	    strcasecmp(options.chroot_directory, "none") == 0) {
167 		char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
168 		    _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
169 
170 		if (stat(shell, &st) != 0) {
171 			logit("User %.100s not allowed because shell %.100s "
172 			    "does not exist", pw->pw_name, shell);
173 			free(shell);
174 			return 0;
175 		}
176 		if (S_ISREG(st.st_mode) == 0 ||
177 		    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
178 			logit("User %.100s not allowed because shell %.100s "
179 			    "is not executable", pw->pw_name, shell);
180 			free(shell);
181 			return 0;
182 		}
183 		free(shell);
184 	}
185 
186 	if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
187 	    options.num_deny_groups > 0 || options.num_allow_groups > 0) {
188 		hostname = auth_get_canonical_hostname(ssh, options.use_dns);
189 		ipaddr = ssh_remote_ipaddr(ssh);
190 	}
191 
192 	/* Return false if user is listed in DenyUsers */
193 	if (options.num_deny_users > 0) {
194 		for (i = 0; i < options.num_deny_users; i++) {
195 			r = match_user(pw->pw_name, hostname, ipaddr,
196 			    options.deny_users[i]);
197 			if (r < 0) {
198 				fatal("Invalid DenyUsers pattern \"%.100s\"",
199 				    options.deny_users[i]);
200 			} else if (r != 0) {
201 				logit("User %.100s from %.100s not allowed "
202 				    "because listed in DenyUsers",
203 				    pw->pw_name, hostname);
204 				return 0;
205 			}
206 		}
207 	}
208 	/* Return false if AllowUsers isn't empty and user isn't listed there */
209 	if (options.num_allow_users > 0) {
210 		for (i = 0; i < options.num_allow_users; i++) {
211 			r = match_user(pw->pw_name, hostname, ipaddr,
212 			    options.allow_users[i]);
213 			if (r < 0) {
214 				fatal("Invalid AllowUsers pattern \"%.100s\"",
215 				    options.allow_users[i]);
216 			} else if (r == 1)
217 				break;
218 		}
219 		/* i < options.num_allow_users iff we break for loop */
220 		if (i >= options.num_allow_users) {
221 			logit("User %.100s from %.100s not allowed because "
222 			    "not listed in AllowUsers", pw->pw_name, hostname);
223 			return 0;
224 		}
225 	}
226 	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
227 		/* Get the user's group access list (primary and supplementary) */
228 		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
229 			logit("User %.100s from %.100s not allowed because "
230 			    "not in any group", pw->pw_name, hostname);
231 			return 0;
232 		}
233 
234 		/* Return false if one of user's groups is listed in DenyGroups */
235 		if (options.num_deny_groups > 0)
236 			if (ga_match(options.deny_groups,
237 			    options.num_deny_groups)) {
238 				ga_free();
239 				logit("User %.100s from %.100s not allowed "
240 				    "because a group is listed in DenyGroups",
241 				    pw->pw_name, hostname);
242 				return 0;
243 			}
244 		/*
245 		 * Return false if AllowGroups isn't empty and one of user's groups
246 		 * isn't listed there
247 		 */
248 		if (options.num_allow_groups > 0)
249 			if (!ga_match(options.allow_groups,
250 			    options.num_allow_groups)) {
251 				ga_free();
252 				logit("User %.100s from %.100s not allowed "
253 				    "because none of user's groups are listed "
254 				    "in AllowGroups", pw->pw_name, hostname);
255 				return 0;
256 			}
257 		ga_free();
258 	}
259 
260 #ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
261 	if (!sys_auth_allowed_user(pw, loginmsg))
262 		return 0;
263 #endif
264 
265 	/* We found no reason not to let this user try to log on... */
266 	return 1;
267 }
268 
269 /*
270  * Formats any key left in authctxt->auth_method_key for inclusion in
271  * auth_log()'s message. Also includes authxtct->auth_method_info if present.
272  */
273 static char *
274 format_method_key(Authctxt *authctxt)
275 {
276 	const struct sshkey *key = authctxt->auth_method_key;
277 	const char *methinfo = authctxt->auth_method_info;
278 	char *fp, *cafp, *ret = NULL;
279 
280 	if (key == NULL)
281 		return NULL;
282 
283 	if (sshkey_is_cert(key)) {
284 		fp = sshkey_fingerprint(key,
285 		    options.fingerprint_hash, SSH_FP_DEFAULT);
286 		cafp = sshkey_fingerprint(key->cert->signature_key,
287 		    options.fingerprint_hash, SSH_FP_DEFAULT);
288 		xasprintf(&ret, "%s %s ID %s (serial %llu) CA %s %s%s%s",
289 		    sshkey_type(key), fp == NULL ? "(null)" : fp,
290 		    key->cert->key_id,
291 		    (unsigned long long)key->cert->serial,
292 		    sshkey_type(key->cert->signature_key),
293 		    cafp == NULL ? "(null)" : cafp,
294 		    methinfo == NULL ? "" : ", ",
295 		    methinfo == NULL ? "" : methinfo);
296 		free(fp);
297 		free(cafp);
298 	} else {
299 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
300 		    SSH_FP_DEFAULT);
301 		xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
302 		    fp == NULL ? "(null)" : fp,
303 		    methinfo == NULL ? "" : ", ",
304 		    methinfo == NULL ? "" : methinfo);
305 		free(fp);
306 	}
307 	return ret;
308 }
309 
310 void
311 auth_log(struct ssh *ssh, int authenticated, int partial,
312     const char *method, const char *submethod)
313 {
314 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
315 	int level = SYSLOG_LEVEL_VERBOSE;
316 	const char *authmsg;
317 	char *extra = NULL;
318 
319 	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
320 		return;
321 
322 	/* Raise logging level */
323 	if (authenticated == 1 ||
324 	    !authctxt->valid ||
325 	    authctxt->failures >= options.max_authtries / 2 ||
326 	    strcmp(method, "password") == 0)
327 		level = SYSLOG_LEVEL_INFO;
328 
329 	if (authctxt->postponed)
330 		authmsg = "Postponed";
331 	else if (partial)
332 		authmsg = "Partial";
333 	else
334 		authmsg = authenticated ? "Accepted" : "Failed";
335 
336 	if ((extra = format_method_key(authctxt)) == NULL) {
337 		if (authctxt->auth_method_info != NULL)
338 			extra = xstrdup(authctxt->auth_method_info);
339 	}
340 
341 	do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
342 	    authmsg,
343 	    method,
344 	    submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
345 	    authctxt->valid ? "" : "invalid user ",
346 	    authctxt->user,
347 	    ssh_remote_ipaddr(ssh),
348 	    ssh_remote_port(ssh),
349 	    extra != NULL ? ": " : "",
350 	    extra != NULL ? extra : "");
351 
352 	free(extra);
353 
354 #ifdef CUSTOM_FAILED_LOGIN
355 	if (authenticated == 0 && !authctxt->postponed &&
356 	    (strcmp(method, "password") == 0 ||
357 	    strncmp(method, "keyboard-interactive", 20) == 0 ||
358 	    strcmp(method, "challenge-response") == 0))
359 		record_failed_login(ssh, authctxt->user,
360 		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
361 # ifdef WITH_AIXAUTHENTICATE
362 	if (authenticated)
363 		sys_auth_record_login(ssh, authctxt->user,
364 		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh",
365 		    loginmsg);
366 # endif
367 #endif
368 #ifdef SSH_AUDIT_EVENTS
369 	if (authenticated == 0 && !authctxt->postponed)
370 		audit_event(audit_classify_auth(method));
371 #endif
372 }
373 
374 
375 void
376 auth_maxtries_exceeded(struct ssh *ssh)
377 {
378 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
379 
380 	error("maximum authentication attempts exceeded for "
381 	    "%s%.100s from %.200s port %d ssh2",
382 	    authctxt->valid ? "" : "invalid user ",
383 	    authctxt->user,
384 	    ssh_remote_ipaddr(ssh),
385 	    ssh_remote_port(ssh));
386 	ssh_packet_disconnect(ssh, "Too many authentication failures");
387 	/* NOTREACHED */
388 }
389 
390 /*
391  * Check whether root logins are disallowed.
392  */
393 int
394 auth_root_allowed(struct ssh *ssh, const char *method)
395 {
396 	switch (options.permit_root_login) {
397 	case PERMIT_YES:
398 		return 1;
399 	case PERMIT_NO_PASSWD:
400 		if (strcmp(method, "publickey") == 0 ||
401 		    strcmp(method, "hostbased") == 0 ||
402 		    strcmp(method, "gssapi-with-mic") == 0)
403 			return 1;
404 		break;
405 	case PERMIT_FORCED_ONLY:
406 		if (auth_opts->force_command != NULL) {
407 			logit("Root login accepted for forced command.");
408 			return 1;
409 		}
410 		break;
411 	}
412 	logit("ROOT LOGIN REFUSED FROM %.200s port %d",
413 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
414 	return 0;
415 }
416 
417 
418 /*
419  * Given a template and a passwd structure, build a filename
420  * by substituting % tokenised options. Currently, %% becomes '%',
421  * %h becomes the home directory and %u the username.
422  *
423  * This returns a buffer allocated by xmalloc.
424  */
425 char *
426 expand_authorized_keys(const char *filename, struct passwd *pw)
427 {
428 	char *file, uidstr[32], ret[PATH_MAX];
429 	int i;
430 
431 	snprintf(uidstr, sizeof(uidstr), "%llu",
432 	    (unsigned long long)pw->pw_uid);
433 	file = percent_expand(filename, "h", pw->pw_dir,
434 	    "u", pw->pw_name, "U", uidstr, (char *)NULL);
435 
436 	/*
437 	 * Ensure that filename starts anchored. If not, be backward
438 	 * compatible and prepend the '%h/'
439 	 */
440 	if (path_absolute(file))
441 		return (file);
442 
443 	i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
444 	if (i < 0 || (size_t)i >= sizeof(ret))
445 		fatal("expand_authorized_keys: path too long");
446 	free(file);
447 	return (xstrdup(ret));
448 }
449 
450 char *
451 authorized_principals_file(struct passwd *pw)
452 {
453 	if (options.authorized_principals_file == NULL)
454 		return NULL;
455 	return expand_authorized_keys(options.authorized_principals_file, pw);
456 }
457 
458 /* return ok if key exists in sysfile or userfile */
459 HostStatus
460 check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
461     const char *sysfile, const char *userfile)
462 {
463 	char *user_hostfile;
464 	struct stat st;
465 	HostStatus host_status;
466 	struct hostkeys *hostkeys;
467 	const struct hostkey_entry *found;
468 
469 	hostkeys = init_hostkeys();
470 	load_hostkeys(hostkeys, host, sysfile);
471 	if (userfile != NULL) {
472 		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
473 		if (options.strict_modes &&
474 		    (stat(user_hostfile, &st) == 0) &&
475 		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
476 		    (st.st_mode & 022) != 0)) {
477 			logit("Authentication refused for %.100s: "
478 			    "bad owner or modes for %.200s",
479 			    pw->pw_name, user_hostfile);
480 			auth_debug_add("Ignored %.200s: bad ownership or modes",
481 			    user_hostfile);
482 		} else {
483 			temporarily_use_uid(pw);
484 			load_hostkeys(hostkeys, host, user_hostfile);
485 			restore_uid();
486 		}
487 		free(user_hostfile);
488 	}
489 	host_status = check_key_in_hostkeys(hostkeys, key, &found);
490 	if (host_status == HOST_REVOKED)
491 		error("WARNING: revoked key for %s attempted authentication",
492 		    found->host);
493 	else if (host_status == HOST_OK)
494 		debug("%s: key for %s found at %s:%ld", __func__,
495 		    found->host, found->file, found->line);
496 	else
497 		debug("%s: key for host %s not found", __func__, host);
498 
499 	free_hostkeys(hostkeys);
500 
501 	return host_status;
502 }
503 
504 static FILE *
505 auth_openfile(const char *file, struct passwd *pw, int strict_modes,
506     int log_missing, char *file_type)
507 {
508 	char line[1024];
509 	struct stat st;
510 	int fd;
511 	FILE *f;
512 
513 	if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
514 		if (log_missing || errno != ENOENT)
515 			debug("Could not open %s '%s': %s", file_type, file,
516 			   strerror(errno));
517 		return NULL;
518 	}
519 
520 	if (fstat(fd, &st) < 0) {
521 		close(fd);
522 		return NULL;
523 	}
524 	if (!S_ISREG(st.st_mode)) {
525 		logit("User %s %s %s is not a regular file",
526 		    pw->pw_name, file_type, file);
527 		close(fd);
528 		return NULL;
529 	}
530 	unset_nonblock(fd);
531 	if ((f = fdopen(fd, "r")) == NULL) {
532 		close(fd);
533 		return NULL;
534 	}
535 	if (strict_modes &&
536 	    safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) {
537 		fclose(f);
538 		logit("Authentication refused: %s", line);
539 		auth_debug_add("Ignored %s: %s", file_type, line);
540 		return NULL;
541 	}
542 
543 	return f;
544 }
545 
546 
547 FILE *
548 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
549 {
550 	return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
551 }
552 
553 FILE *
554 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
555 {
556 	return auth_openfile(file, pw, strict_modes, 0,
557 	    "authorized principals");
558 }
559 
560 struct passwd *
561 getpwnamallow(struct ssh *ssh, const char *user)
562 {
563 #ifdef HAVE_LOGIN_CAP
564 	extern login_cap_t *lc;
565 #ifdef BSD_AUTH
566 	auth_session_t *as;
567 #endif
568 #endif
569 	struct passwd *pw;
570 	struct connection_info *ci;
571 
572 	ci = get_connection_info(ssh, 1, options.use_dns);
573 	ci->user = user;
574 	parse_server_match_config(&options, ci);
575 	log_change_level(options.log_level);
576 	process_permitopen(ssh, &options);
577 
578 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
579 	aix_setauthdb(user);
580 #endif
581 
582 	pw = getpwnam(user);
583 
584 #if defined(_AIX) && defined(HAVE_SETAUTHDB)
585 	aix_restoreauthdb();
586 #endif
587 #ifdef HAVE_CYGWIN
588 	/*
589 	 * Windows usernames are case-insensitive.  To avoid later problems
590 	 * when trying to match the username, the user is only allowed to
591 	 * login if the username is given in the same case as stored in the
592 	 * user database.
593 	 */
594 	if (pw != NULL && strcmp(user, pw->pw_name) != 0) {
595 		logit("Login name %.100s does not match stored username %.100s",
596 		    user, pw->pw_name);
597 		pw = NULL;
598 	}
599 #endif
600 	if (pw == NULL) {
601 		logit("Invalid user %.100s from %.100s port %d",
602 		    user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
603 #ifdef CUSTOM_FAILED_LOGIN
604 		record_failed_login(ssh, user,
605 		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
606 #endif
607 #ifdef SSH_AUDIT_EVENTS
608 		audit_event(SSH_INVALID_USER);
609 #endif /* SSH_AUDIT_EVENTS */
610 		return (NULL);
611 	}
612 	if (!allowed_user(ssh, pw))
613 		return (NULL);
614 #ifdef HAVE_LOGIN_CAP
615 	if ((lc = login_getclass(pw->pw_class)) == NULL) {
616 		debug("unable to get login class: %s", user);
617 		return (NULL);
618 	}
619 #ifdef BSD_AUTH
620 	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
621 	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
622 		debug("Approval failure for %s", user);
623 		pw = NULL;
624 	}
625 	if (as != NULL)
626 		auth_close(as);
627 #endif
628 #endif
629 	if (pw != NULL)
630 		return (pwcopy(pw));
631 	return (NULL);
632 }
633 
634 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
635 int
636 auth_key_is_revoked(struct sshkey *key)
637 {
638 	char *fp = NULL;
639 	int r;
640 
641 	if (options.revoked_keys_file == NULL)
642 		return 0;
643 	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
644 	    SSH_FP_DEFAULT)) == NULL) {
645 		r = SSH_ERR_ALLOC_FAIL;
646 		error("%s: fingerprint key: %s", __func__, ssh_err(r));
647 		goto out;
648 	}
649 
650 	r = sshkey_check_revoked(key, options.revoked_keys_file);
651 	switch (r) {
652 	case 0:
653 		break; /* not revoked */
654 	case SSH_ERR_KEY_REVOKED:
655 		error("Authentication key %s %s revoked by file %s",
656 		    sshkey_type(key), fp, options.revoked_keys_file);
657 		goto out;
658 	default:
659 		error("Error checking authentication key %s %s in "
660 		    "revoked keys file %s: %s", sshkey_type(key), fp,
661 		    options.revoked_keys_file, ssh_err(r));
662 		goto out;
663 	}
664 
665 	/* Success */
666 	r = 0;
667 
668  out:
669 	free(fp);
670 	return r == 0 ? 0 : 1;
671 }
672 
673 void
674 auth_debug_add(const char *fmt,...)
675 {
676 	char buf[1024];
677 	va_list args;
678 	int r;
679 
680 	if (auth_debug == NULL)
681 		return;
682 
683 	va_start(args, fmt);
684 	vsnprintf(buf, sizeof(buf), fmt, args);
685 	va_end(args);
686 	if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0)
687 		fatal("%s: sshbuf_put_cstring: %s", __func__, ssh_err(r));
688 }
689 
690 void
691 auth_debug_send(struct ssh *ssh)
692 {
693 	char *msg;
694 	int r;
695 
696 	if (auth_debug == NULL)
697 		return;
698 	while (sshbuf_len(auth_debug) != 0) {
699 		if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0)
700 			fatal("%s: sshbuf_get_cstring: %s",
701 			    __func__, ssh_err(r));
702 		ssh_packet_send_debug(ssh, "%s", msg);
703 		free(msg);
704 	}
705 }
706 
707 void
708 auth_debug_reset(void)
709 {
710 	if (auth_debug != NULL)
711 		sshbuf_reset(auth_debug);
712 	else if ((auth_debug = sshbuf_new()) == NULL)
713 		fatal("%s: sshbuf_new failed", __func__);
714 }
715 
716 struct passwd *
717 fakepw(void)
718 {
719 	static struct passwd fake;
720 
721 	memset(&fake, 0, sizeof(fake));
722 	fake.pw_name = "NOUSER";
723 	fake.pw_passwd =
724 	    "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
725 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
726 	fake.pw_gecos = "NOUSER";
727 #endif
728 	fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
729 	fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
730 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
731 	fake.pw_class = "";
732 #endif
733 	fake.pw_dir = "/nonexist";
734 	fake.pw_shell = "/nonexist";
735 
736 	return (&fake);
737 }
738 
739 /*
740  * Returns the remote DNS hostname as a string. The returned string must not
741  * be freed. NB. this will usually trigger a DNS query the first time it is
742  * called.
743  * This function does additional checks on the hostname to mitigate some
744  * attacks on legacy rhosts-style authentication.
745  * XXX is RhostsRSAAuthentication vulnerable to these?
746  * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
747  */
748 
749 static char *
750 remote_hostname(struct ssh *ssh)
751 {
752 	struct sockaddr_storage from;
753 	socklen_t fromlen;
754 	struct addrinfo hints, *ai, *aitop;
755 	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
756 	const char *ntop = ssh_remote_ipaddr(ssh);
757 
758 	/* Get IP address of client. */
759 	fromlen = sizeof(from);
760 	memset(&from, 0, sizeof(from));
761 	if (getpeername(ssh_packet_get_connection_in(ssh),
762 	    (struct sockaddr *)&from, &fromlen) < 0) {
763 		debug("getpeername failed: %.100s", strerror(errno));
764 		return strdup(ntop);
765 	}
766 
767 	ipv64_normalise_mapped(&from, &fromlen);
768 	if (from.ss_family == AF_INET6)
769 		fromlen = sizeof(struct sockaddr_in6);
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 with 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 (!path_absolute(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 		if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0) {
963 			error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
964 			    strerror(errno));
965 			_exit(1);
966 		}
967 		if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0) {
968 			error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
969 			    strerror(errno));
970 			_exit(1);
971 		}
972 		/* stdin is pointed to /dev/null at this point */
973 		if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
974 		    dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
975 			error("%s: dup2: %s", tag, strerror(errno));
976 			_exit(1);
977 		}
978 
979 		execve(av[0], av, child_env);
980 		error("%s exec \"%s\": %s", tag, command, strerror(errno));
981 		_exit(127);
982 	default: /* parent */
983 		break;
984 	}
985 
986 	close(p[1]);
987 	if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
988 		close(p[0]);
989 	else if ((f = fdopen(p[0], "r")) == NULL) {
990 		error("%s: fdopen: %s", tag, strerror(errno));
991 		close(p[0]);
992 		/* Don't leave zombie child */
993 		kill(pid, SIGTERM);
994 		while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
995 			;
996 		return 0;
997 	}
998 	/* Success */
999 	debug3("%s: %s pid %ld", __func__, tag, (long)pid);
1000 	if (child != NULL)
1001 		*child = f;
1002 	return pid;
1003 }
1004 
1005 /* These functions link key/cert options to the auth framework */
1006 
1007 /* Log sshauthopt options locally and (optionally) for remote transmission */
1008 void
1009 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
1010 {
1011 	int do_env = options.permit_user_env && opts->nenv > 0;
1012 	int do_permitopen = opts->npermitopen > 0 &&
1013 	    (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
1014 	int do_permitlisten = opts->npermitlisten > 0 &&
1015 	    (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0;
1016 	size_t i;
1017 	char msg[1024], buf[64];
1018 
1019 	snprintf(buf, sizeof(buf), "%d", opts->force_tun_device);
1020 	/* Try to keep this alphabetically sorted */
1021 	snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s",
1022 	    opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
1023 	    opts->force_command == NULL ? "" : " command",
1024 	    do_env ?  " environment" : "",
1025 	    opts->valid_before == 0 ? "" : "expires",
1026 	    do_permitopen ?  " permitopen" : "",
1027 	    do_permitlisten ?  " permitlisten" : "",
1028 	    opts->permit_port_forwarding_flag ? " port-forwarding" : "",
1029 	    opts->cert_principals == NULL ? "" : " principals",
1030 	    opts->permit_pty_flag ? " pty" : "",
1031 	    opts->force_tun_device == -1 ? "" : " tun=",
1032 	    opts->force_tun_device == -1 ? "" : buf,
1033 	    opts->permit_user_rc ? " user-rc" : "",
1034 	    opts->permit_x11_forwarding_flag ? " x11-forwarding" : "");
1035 
1036 	debug("%s: %s", loc, msg);
1037 	if (do_remote)
1038 		auth_debug_add("%s: %s", loc, msg);
1039 
1040 	if (options.permit_user_env) {
1041 		for (i = 0; i < opts->nenv; i++) {
1042 			debug("%s: environment: %s", loc, opts->env[i]);
1043 			if (do_remote) {
1044 				auth_debug_add("%s: environment: %s",
1045 				    loc, opts->env[i]);
1046 			}
1047 		}
1048 	}
1049 
1050 	/* Go into a little more details for the local logs. */
1051 	if (opts->valid_before != 0) {
1052 		format_absolute_time(opts->valid_before, buf, sizeof(buf));
1053 		debug("%s: expires at %s", loc, buf);
1054 	}
1055 	if (opts->cert_principals != NULL) {
1056 		debug("%s: authorized principals: \"%s\"",
1057 		    loc, opts->cert_principals);
1058 	}
1059 	if (opts->force_command != NULL)
1060 		debug("%s: forced command: \"%s\"", loc, opts->force_command);
1061 	if (do_permitopen) {
1062 		for (i = 0; i < opts->npermitopen; i++) {
1063 			debug("%s: permitted open: %s",
1064 			    loc, opts->permitopen[i]);
1065 		}
1066 	}
1067 	if (do_permitlisten) {
1068 		for (i = 0; i < opts->npermitlisten; i++) {
1069 			debug("%s: permitted listen: %s",
1070 			    loc, opts->permitlisten[i]);
1071 		}
1072 	}
1073 }
1074 
1075 /* Activate a new set of key/cert options; merging with what is there. */
1076 int
1077 auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
1078 {
1079 	struct sshauthopt *old = auth_opts;
1080 	const char *emsg = NULL;
1081 
1082 	debug("%s: setting new authentication options", __func__);
1083 	if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
1084 		error("Inconsistent authentication options: %s", emsg);
1085 		return -1;
1086 	}
1087 	return 0;
1088 }
1089 
1090 /* Disable forwarding, etc for the session */
1091 void
1092 auth_restrict_session(struct ssh *ssh)
1093 {
1094 	struct sshauthopt *restricted;
1095 
1096 	debug("%s: restricting session", __func__);
1097 
1098 	/* A blank sshauthopt defaults to permitting nothing */
1099 	restricted = sshauthopt_new();
1100 	restricted->permit_pty_flag = 1;
1101 	restricted->restricted = 1;
1102 
1103 	if (auth_activate_options(ssh, restricted) != 0)
1104 		fatal("%s: failed to restrict session", __func__);
1105 	sshauthopt_free(restricted);
1106 }
1107 
1108 int
1109 auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw,
1110     struct sshauthopt *opts, int allow_cert_authority, const char *loc)
1111 {
1112 	const char *remote_ip = ssh_remote_ipaddr(ssh);
1113 	const char *remote_host = auth_get_canonical_hostname(ssh,
1114 	    options.use_dns);
1115 	time_t now = time(NULL);
1116 	char buf[64];
1117 
1118 	/*
1119 	 * Check keys/principals file expiry time.
1120 	 * NB. validity interval in certificate is handled elsewhere.
1121 	 */
1122 	if (opts->valid_before && now > 0 &&
1123 	    opts->valid_before < (uint64_t)now) {
1124 		format_absolute_time(opts->valid_before, buf, sizeof(buf));
1125 		debug("%s: entry expired at %s", loc, buf);
1126 		auth_debug_add("%s: entry expired at %s", loc, buf);
1127 		return -1;
1128 	}
1129 	/* Consistency checks */
1130 	if (opts->cert_principals != NULL && !opts->cert_authority) {
1131 		debug("%s: principals on non-CA key", loc);
1132 		auth_debug_add("%s: principals on non-CA key", loc);
1133 		/* deny access */
1134 		return -1;
1135 	}
1136 	/* cert-authority flag isn't valid in authorized_principals files */
1137 	if (!allow_cert_authority && opts->cert_authority) {
1138 		debug("%s: cert-authority flag invalid here", loc);
1139 		auth_debug_add("%s: cert-authority flag invalid here", loc);
1140 		/* deny access */
1141 		return -1;
1142 	}
1143 
1144 	/* Perform from= checks */
1145 	if (opts->required_from_host_keys != NULL) {
1146 		switch (match_host_and_ip(remote_host, remote_ip,
1147 		    opts->required_from_host_keys )) {
1148 		case 1:
1149 			/* Host name matches. */
1150 			break;
1151 		case -1:
1152 		default:
1153 			debug("%s: invalid from criteria", loc);
1154 			auth_debug_add("%s: invalid from criteria", loc);
1155 			/* FALLTHROUGH */
1156 		case 0:
1157 			logit("%s: Authentication tried for %.100s with "
1158 			    "correct key but not from a permitted "
1159 			    "host (host=%.200s, ip=%.200s, required=%.200s).",
1160 			    loc, pw->pw_name, remote_host, remote_ip,
1161 			    opts->required_from_host_keys);
1162 			auth_debug_add("%s: Your host '%.200s' is not "
1163 			    "permitted to use this key for login.",
1164 			    loc, remote_host);
1165 			/* deny access */
1166 			return -1;
1167 		}
1168 	}
1169 	/* Check source-address restriction from certificate */
1170 	if (opts->required_from_host_cert != NULL) {
1171 		switch (addr_match_cidr_list(remote_ip,
1172 		    opts->required_from_host_cert)) {
1173 		case 1:
1174 			/* accepted */
1175 			break;
1176 		case -1:
1177 		default:
1178 			/* invalid */
1179 			error("%s: Certificate source-address invalid",
1180 			    loc);
1181 			/* FALLTHROUGH */
1182 		case 0:
1183 			logit("%s: Authentication tried for %.100s with valid "
1184 			    "certificate but not from a permitted source "
1185 			    "address (%.200s).", loc, pw->pw_name, remote_ip);
1186 			auth_debug_add("%s: Your address '%.200s' is not "
1187 			    "permitted to use this certificate for login.",
1188 			    loc, remote_ip);
1189 			return -1;
1190 		}
1191 	}
1192 	/*
1193 	 *
1194 	 * XXX this is spammy. We should report remotely only for keys
1195 	 *     that are successful in actual auth attempts, and not PK_OK
1196 	 *     tests.
1197 	 */
1198 	auth_log_authopts(loc, opts, 1);
1199 
1200 	return 0;
1201 }
1202