xref: /openssh-portable/auth.c (revision f65cf116)
1 /* $OpenBSD: auth.c,v 1.144 2019/12/16 13:58:53 tobhe 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 <stdlib.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #ifdef HAVE_PATHS_H
39 # include <paths.h>
40 #endif
41 #include <pwd.h>
42 #ifdef HAVE_LOGIN_H
43 #include <login.h>
44 #endif
45 #ifdef USE_SHADOW
46 #include <shadow.h>
47 #endif
48 #include <stdarg.h>
49 #include <stdio.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <limits.h>
53 #include <netdb.h>
54 #include <time.h>
55 
56 #include "xmalloc.h"
57 #include "match.h"
58 #include "groupaccess.h"
59 #include "log.h"
60 #include "sshbuf.h"
61 #include "misc.h"
62 #include "servconf.h"
63 #include "sshkey.h"
64 #include "hostfile.h"
65 #include "auth.h"
66 #include "auth-options.h"
67 #include "canohost.h"
68 #include "uidswap.h"
69 #include "packet.h"
70 #include "loginrec.h"
71 #ifdef GSSAPI
72 #include "ssh-gss.h"
73 #endif
74 #include "authfile.h"
75 #include "monitor_wrap.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) == -1) {
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(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(ssh, 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 		    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) == -1) {
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 	if (pw == NULL) {
588 		logit("Invalid user %.100s from %.100s port %d",
589 		    user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
590 #ifdef CUSTOM_FAILED_LOGIN
591 		record_failed_login(ssh, user,
592 		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
593 #endif
594 #ifdef SSH_AUDIT_EVENTS
595 		audit_event(ssh, SSH_INVALID_USER);
596 #endif /* SSH_AUDIT_EVENTS */
597 		return (NULL);
598 	}
599 	if (!allowed_user(ssh, pw))
600 		return (NULL);
601 #ifdef HAVE_LOGIN_CAP
602 	if ((lc = login_getclass(pw->pw_class)) == NULL) {
603 		debug("unable to get login class: %s", user);
604 		return (NULL);
605 	}
606 #ifdef BSD_AUTH
607 	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
608 	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
609 		debug("Approval failure for %s", user);
610 		pw = NULL;
611 	}
612 	if (as != NULL)
613 		auth_close(as);
614 #endif
615 #endif
616 	if (pw != NULL)
617 		return (pwcopy(pw));
618 	return (NULL);
619 }
620 
621 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
622 int
623 auth_key_is_revoked(struct sshkey *key)
624 {
625 	char *fp = NULL;
626 	int r;
627 
628 	if (options.revoked_keys_file == NULL)
629 		return 0;
630 	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
631 	    SSH_FP_DEFAULT)) == NULL) {
632 		r = SSH_ERR_ALLOC_FAIL;
633 		error("%s: fingerprint key: %s", __func__, ssh_err(r));
634 		goto out;
635 	}
636 
637 	r = sshkey_check_revoked(key, options.revoked_keys_file);
638 	switch (r) {
639 	case 0:
640 		break; /* not revoked */
641 	case SSH_ERR_KEY_REVOKED:
642 		error("Authentication key %s %s revoked by file %s",
643 		    sshkey_type(key), fp, options.revoked_keys_file);
644 		goto out;
645 	default:
646 		error("Error checking authentication key %s %s in "
647 		    "revoked keys file %s: %s", sshkey_type(key), fp,
648 		    options.revoked_keys_file, ssh_err(r));
649 		goto out;
650 	}
651 
652 	/* Success */
653 	r = 0;
654 
655  out:
656 	free(fp);
657 	return r == 0 ? 0 : 1;
658 }
659 
660 void
661 auth_debug_add(const char *fmt,...)
662 {
663 	char buf[1024];
664 	va_list args;
665 	int r;
666 
667 	if (auth_debug == NULL)
668 		return;
669 
670 	va_start(args, fmt);
671 	vsnprintf(buf, sizeof(buf), fmt, args);
672 	va_end(args);
673 	if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0)
674 		fatal("%s: sshbuf_put_cstring: %s", __func__, ssh_err(r));
675 }
676 
677 void
678 auth_debug_send(struct ssh *ssh)
679 {
680 	char *msg;
681 	int r;
682 
683 	if (auth_debug == NULL)
684 		return;
685 	while (sshbuf_len(auth_debug) != 0) {
686 		if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0)
687 			fatal("%s: sshbuf_get_cstring: %s",
688 			    __func__, ssh_err(r));
689 		ssh_packet_send_debug(ssh, "%s", msg);
690 		free(msg);
691 	}
692 }
693 
694 void
695 auth_debug_reset(void)
696 {
697 	if (auth_debug != NULL)
698 		sshbuf_reset(auth_debug);
699 	else if ((auth_debug = sshbuf_new()) == NULL)
700 		fatal("%s: sshbuf_new failed", __func__);
701 }
702 
703 struct passwd *
704 fakepw(void)
705 {
706 	static struct passwd fake;
707 
708 	memset(&fake, 0, sizeof(fake));
709 	fake.pw_name = "NOUSER";
710 	fake.pw_passwd =
711 	    "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
712 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
713 	fake.pw_gecos = "NOUSER";
714 #endif
715 	fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
716 	fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
717 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
718 	fake.pw_class = "";
719 #endif
720 	fake.pw_dir = "/nonexist";
721 	fake.pw_shell = "/nonexist";
722 
723 	return (&fake);
724 }
725 
726 /*
727  * Returns the remote DNS hostname as a string. The returned string must not
728  * be freed. NB. this will usually trigger a DNS query the first time it is
729  * called.
730  * This function does additional checks on the hostname to mitigate some
731  * attacks on legacy rhosts-style authentication.
732  * XXX is RhostsRSAAuthentication vulnerable to these?
733  * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
734  */
735 
736 static char *
737 remote_hostname(struct ssh *ssh)
738 {
739 	struct sockaddr_storage from;
740 	socklen_t fromlen;
741 	struct addrinfo hints, *ai, *aitop;
742 	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
743 	const char *ntop = ssh_remote_ipaddr(ssh);
744 
745 	/* Get IP address of client. */
746 	fromlen = sizeof(from);
747 	memset(&from, 0, sizeof(from));
748 	if (getpeername(ssh_packet_get_connection_in(ssh),
749 	    (struct sockaddr *)&from, &fromlen) == -1) {
750 		debug("getpeername failed: %.100s", strerror(errno));
751 		return xstrdup(ntop);
752 	}
753 
754 	ipv64_normalise_mapped(&from, &fromlen);
755 	if (from.ss_family == AF_INET6)
756 		fromlen = sizeof(struct sockaddr_in6);
757 
758 	debug3("Trying to reverse map address %.100s.", ntop);
759 	/* Map the IP address to a host name. */
760 	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
761 	    NULL, 0, NI_NAMEREQD) != 0) {
762 		/* Host name not found.  Use ip address. */
763 		return xstrdup(ntop);
764 	}
765 
766 	/*
767 	 * if reverse lookup result looks like a numeric hostname,
768 	 * someone is trying to trick us by PTR record like following:
769 	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
770 	 */
771 	memset(&hints, 0, sizeof(hints));
772 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
773 	hints.ai_flags = AI_NUMERICHOST;
774 	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
775 		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
776 		    name, ntop);
777 		freeaddrinfo(ai);
778 		return xstrdup(ntop);
779 	}
780 
781 	/* Names are stored in lowercase. */
782 	lowercase(name);
783 
784 	/*
785 	 * Map it back to an IP address and check that the given
786 	 * address actually is an address of this host.  This is
787 	 * necessary because anyone with access to a name server can
788 	 * define arbitrary names for an IP address. Mapping from
789 	 * name to IP address can be trusted better (but can still be
790 	 * fooled if the intruder has access to the name server of
791 	 * the domain).
792 	 */
793 	memset(&hints, 0, sizeof(hints));
794 	hints.ai_family = from.ss_family;
795 	hints.ai_socktype = SOCK_STREAM;
796 	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
797 		logit("reverse mapping checking getaddrinfo for %.700s "
798 		    "[%s] failed.", name, ntop);
799 		return xstrdup(ntop);
800 	}
801 	/* Look for the address from the list of addresses. */
802 	for (ai = aitop; ai; ai = ai->ai_next) {
803 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
804 		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
805 		    (strcmp(ntop, ntop2) == 0))
806 				break;
807 	}
808 	freeaddrinfo(aitop);
809 	/* If we reached the end of the list, the address was not there. */
810 	if (ai == NULL) {
811 		/* Address not found for the host name. */
812 		logit("Address %.100s maps to %.600s, but this does not "
813 		    "map back to the address.", ntop, name);
814 		return xstrdup(ntop);
815 	}
816 	return xstrdup(name);
817 }
818 
819 /*
820  * Return the canonical name of the host in the other side of the current
821  * connection.  The host name is cached, so it is efficient to call this
822  * several times.
823  */
824 
825 const char *
826 auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
827 {
828 	static char *dnsname;
829 
830 	if (!use_dns)
831 		return ssh_remote_ipaddr(ssh);
832 	else if (dnsname != NULL)
833 		return dnsname;
834 	else {
835 		dnsname = remote_hostname(ssh);
836 		return dnsname;
837 	}
838 }
839 
840 /*
841  * Runs command in a subprocess with a minimal environment.
842  * Returns pid on success, 0 on failure.
843  * The child stdout and stderr maybe captured, left attached or sent to
844  * /dev/null depending on the contents of flags.
845  * "tag" is prepended to log messages.
846  * NB. "command" is only used for logging; the actual command executed is
847  * av[0].
848  */
849 pid_t
850 subprocess(const char *tag, struct passwd *pw, const char *command,
851     int ac, char **av, FILE **child, u_int flags)
852 {
853 	FILE *f = NULL;
854 	struct stat st;
855 	int fd, devnull, p[2], i;
856 	pid_t pid;
857 	char *cp, errmsg[512];
858 	u_int envsize;
859 	char **child_env;
860 
861 	if (child != NULL)
862 		*child = NULL;
863 
864 	debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__,
865 	    tag, command, pw->pw_name, flags);
866 
867 	/* Check consistency */
868 	if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
869 	    (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
870 		error("%s: inconsistent flags", __func__);
871 		return 0;
872 	}
873 	if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
874 		error("%s: inconsistent flags/output", __func__);
875 		return 0;
876 	}
877 
878 	/*
879 	 * If executing an explicit binary, then verify the it exists
880 	 * and appears safe-ish to execute
881 	 */
882 	if (!path_absolute(av[0])) {
883 		error("%s path is not absolute", tag);
884 		return 0;
885 	}
886 	temporarily_use_uid(pw);
887 	if (stat(av[0], &st) == -1) {
888 		error("Could not stat %s \"%s\": %s", tag,
889 		    av[0], strerror(errno));
890 		restore_uid();
891 		return 0;
892 	}
893 	if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
894 		error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
895 		restore_uid();
896 		return 0;
897 	}
898 	/* Prepare to keep the child's stdout if requested */
899 	if (pipe(p) == -1) {
900 		error("%s: pipe: %s", tag, strerror(errno));
901 		restore_uid();
902 		return 0;
903 	}
904 	restore_uid();
905 
906 	switch ((pid = fork())) {
907 	case -1: /* error */
908 		error("%s: fork: %s", tag, strerror(errno));
909 		close(p[0]);
910 		close(p[1]);
911 		return 0;
912 	case 0: /* child */
913 		/* Prepare a minimal environment for the child. */
914 		envsize = 5;
915 		child_env = xcalloc(sizeof(*child_env), envsize);
916 		child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
917 		child_set_env(&child_env, &envsize, "USER", pw->pw_name);
918 		child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
919 		child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
920 		if ((cp = getenv("LANG")) != NULL)
921 			child_set_env(&child_env, &envsize, "LANG", cp);
922 
923 		for (i = 0; i < NSIG; i++)
924 			signal(i, SIG_DFL);
925 
926 		if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
927 			error("%s: open %s: %s", tag, _PATH_DEVNULL,
928 			    strerror(errno));
929 			_exit(1);
930 		}
931 		if (dup2(devnull, STDIN_FILENO) == -1) {
932 			error("%s: dup2: %s", tag, strerror(errno));
933 			_exit(1);
934 		}
935 
936 		/* Set up stdout as requested; leave stderr in place for now. */
937 		fd = -1;
938 		if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
939 			fd = p[1];
940 		else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
941 			fd = devnull;
942 		if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
943 			error("%s: dup2: %s", tag, strerror(errno));
944 			_exit(1);
945 		}
946 		closefrom(STDERR_FILENO + 1);
947 
948 		/* Don't use permanently_set_uid() here to avoid fatal() */
949 		if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
950 			error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
951 			    strerror(errno));
952 			_exit(1);
953 		}
954 		if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
955 			error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
956 			    strerror(errno));
957 			_exit(1);
958 		}
959 		/* stdin is pointed to /dev/null at this point */
960 		if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
961 		    dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
962 			error("%s: dup2: %s", tag, strerror(errno));
963 			_exit(1);
964 		}
965 
966 		execve(av[0], av, child_env);
967 		error("%s exec \"%s\": %s", tag, command, strerror(errno));
968 		_exit(127);
969 	default: /* parent */
970 		break;
971 	}
972 
973 	close(p[1]);
974 	if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
975 		close(p[0]);
976 	else if ((f = fdopen(p[0], "r")) == NULL) {
977 		error("%s: fdopen: %s", tag, strerror(errno));
978 		close(p[0]);
979 		/* Don't leave zombie child */
980 		kill(pid, SIGTERM);
981 		while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
982 			;
983 		return 0;
984 	}
985 	/* Success */
986 	debug3("%s: %s pid %ld", __func__, tag, (long)pid);
987 	if (child != NULL)
988 		*child = f;
989 	return pid;
990 }
991 
992 /* These functions link key/cert options to the auth framework */
993 
994 /* Log sshauthopt options locally and (optionally) for remote transmission */
995 void
996 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
997 {
998 	int do_env = options.permit_user_env && opts->nenv > 0;
999 	int do_permitopen = opts->npermitopen > 0 &&
1000 	    (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
1001 	int do_permitlisten = opts->npermitlisten > 0 &&
1002 	    (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0;
1003 	size_t i;
1004 	char msg[1024], buf[64];
1005 
1006 	snprintf(buf, sizeof(buf), "%d", opts->force_tun_device);
1007 	/* Try to keep this alphabetically sorted */
1008 	snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
1009 	    opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
1010 	    opts->force_command == NULL ? "" : " command",
1011 	    do_env ?  " environment" : "",
1012 	    opts->valid_before == 0 ? "" : "expires",
1013 	    do_permitopen ?  " permitopen" : "",
1014 	    do_permitlisten ?  " permitlisten" : "",
1015 	    opts->permit_port_forwarding_flag ? " port-forwarding" : "",
1016 	    opts->cert_principals == NULL ? "" : " principals",
1017 	    opts->permit_pty_flag ? " pty" : "",
1018 	    opts->force_tun_device == -1 ? "" : " tun=",
1019 	    opts->force_tun_device == -1 ? "" : buf,
1020 	    opts->permit_user_rc ? " user-rc" : "",
1021 	    opts->permit_x11_forwarding_flag ? " x11-forwarding" : "",
1022 	    opts->no_require_user_presence ? " no-touch-required" : "");
1023 
1024 	debug("%s: %s", loc, msg);
1025 	if (do_remote)
1026 		auth_debug_add("%s: %s", loc, msg);
1027 
1028 	if (options.permit_user_env) {
1029 		for (i = 0; i < opts->nenv; i++) {
1030 			debug("%s: environment: %s", loc, opts->env[i]);
1031 			if (do_remote) {
1032 				auth_debug_add("%s: environment: %s",
1033 				    loc, opts->env[i]);
1034 			}
1035 		}
1036 	}
1037 
1038 	/* Go into a little more details for the local logs. */
1039 	if (opts->valid_before != 0) {
1040 		format_absolute_time(opts->valid_before, buf, sizeof(buf));
1041 		debug("%s: expires at %s", loc, buf);
1042 	}
1043 	if (opts->cert_principals != NULL) {
1044 		debug("%s: authorized principals: \"%s\"",
1045 		    loc, opts->cert_principals);
1046 	}
1047 	if (opts->force_command != NULL)
1048 		debug("%s: forced command: \"%s\"", loc, opts->force_command);
1049 	if (do_permitopen) {
1050 		for (i = 0; i < opts->npermitopen; i++) {
1051 			debug("%s: permitted open: %s",
1052 			    loc, opts->permitopen[i]);
1053 		}
1054 	}
1055 	if (do_permitlisten) {
1056 		for (i = 0; i < opts->npermitlisten; i++) {
1057 			debug("%s: permitted listen: %s",
1058 			    loc, opts->permitlisten[i]);
1059 		}
1060 	}
1061 }
1062 
1063 /* Activate a new set of key/cert options; merging with what is there. */
1064 int
1065 auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
1066 {
1067 	struct sshauthopt *old = auth_opts;
1068 	const char *emsg = NULL;
1069 
1070 	debug("%s: setting new authentication options", __func__);
1071 	if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
1072 		error("Inconsistent authentication options: %s", emsg);
1073 		return -1;
1074 	}
1075 	return 0;
1076 }
1077 
1078 /* Disable forwarding, etc for the session */
1079 void
1080 auth_restrict_session(struct ssh *ssh)
1081 {
1082 	struct sshauthopt *restricted;
1083 
1084 	debug("%s: restricting session", __func__);
1085 
1086 	/* A blank sshauthopt defaults to permitting nothing */
1087 	restricted = sshauthopt_new();
1088 	restricted->permit_pty_flag = 1;
1089 	restricted->restricted = 1;
1090 
1091 	if (auth_activate_options(ssh, restricted) != 0)
1092 		fatal("%s: failed to restrict session", __func__);
1093 	sshauthopt_free(restricted);
1094 }
1095 
1096 int
1097 auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw,
1098     struct sshauthopt *opts, int allow_cert_authority, const char *loc)
1099 {
1100 	const char *remote_ip = ssh_remote_ipaddr(ssh);
1101 	const char *remote_host = auth_get_canonical_hostname(ssh,
1102 	    options.use_dns);
1103 	time_t now = time(NULL);
1104 	char buf[64];
1105 
1106 	/*
1107 	 * Check keys/principals file expiry time.
1108 	 * NB. validity interval in certificate is handled elsewhere.
1109 	 */
1110 	if (opts->valid_before && now > 0 &&
1111 	    opts->valid_before < (uint64_t)now) {
1112 		format_absolute_time(opts->valid_before, buf, sizeof(buf));
1113 		debug("%s: entry expired at %s", loc, buf);
1114 		auth_debug_add("%s: entry expired at %s", loc, buf);
1115 		return -1;
1116 	}
1117 	/* Consistency checks */
1118 	if (opts->cert_principals != NULL && !opts->cert_authority) {
1119 		debug("%s: principals on non-CA key", loc);
1120 		auth_debug_add("%s: principals on non-CA key", loc);
1121 		/* deny access */
1122 		return -1;
1123 	}
1124 	/* cert-authority flag isn't valid in authorized_principals files */
1125 	if (!allow_cert_authority && opts->cert_authority) {
1126 		debug("%s: cert-authority flag invalid here", loc);
1127 		auth_debug_add("%s: cert-authority flag invalid here", loc);
1128 		/* deny access */
1129 		return -1;
1130 	}
1131 
1132 	/* Perform from= checks */
1133 	if (opts->required_from_host_keys != NULL) {
1134 		switch (match_host_and_ip(remote_host, remote_ip,
1135 		    opts->required_from_host_keys )) {
1136 		case 1:
1137 			/* Host name matches. */
1138 			break;
1139 		case -1:
1140 		default:
1141 			debug("%s: invalid from criteria", loc);
1142 			auth_debug_add("%s: invalid from criteria", loc);
1143 			/* FALLTHROUGH */
1144 		case 0:
1145 			logit("%s: Authentication tried for %.100s with "
1146 			    "correct key but not from a permitted "
1147 			    "host (host=%.200s, ip=%.200s, required=%.200s).",
1148 			    loc, pw->pw_name, remote_host, remote_ip,
1149 			    opts->required_from_host_keys);
1150 			auth_debug_add("%s: Your host '%.200s' is not "
1151 			    "permitted to use this key for login.",
1152 			    loc, remote_host);
1153 			/* deny access */
1154 			return -1;
1155 		}
1156 	}
1157 	/* Check source-address restriction from certificate */
1158 	if (opts->required_from_host_cert != NULL) {
1159 		switch (addr_match_cidr_list(remote_ip,
1160 		    opts->required_from_host_cert)) {
1161 		case 1:
1162 			/* accepted */
1163 			break;
1164 		case -1:
1165 		default:
1166 			/* invalid */
1167 			error("%s: Certificate source-address invalid",
1168 			    loc);
1169 			/* FALLTHROUGH */
1170 		case 0:
1171 			logit("%s: Authentication tried for %.100s with valid "
1172 			    "certificate but not from a permitted source "
1173 			    "address (%.200s).", loc, pw->pw_name, remote_ip);
1174 			auth_debug_add("%s: Your address '%.200s' is not "
1175 			    "permitted to use this certificate for login.",
1176 			    loc, remote_ip);
1177 			return -1;
1178 		}
1179 	}
1180 	/*
1181 	 *
1182 	 * XXX this is spammy. We should report remotely only for keys
1183 	 *     that are successful in actual auth attempts, and not PK_OK
1184 	 *     tests.
1185 	 */
1186 	auth_log_authopts(loc, opts, 1);
1187 
1188 	return 0;
1189 }
1190