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