xref: /openbsd-src/usr.bin/ssh/auth.c (revision ae3cb403620ab940fbaabb3055fac045a63d56b7)
1 /* $OpenBSD: auth.c,v 1.125 2018/01/08 15:21:49 markus 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 
66 /* import */
67 extern ServerOptions options;
68 extern int use_privsep;
69 
70 /* Debugging messages */
71 Buffer auth_debug;
72 int auth_debug_init;
73 
74 /*
75  * Check if the user is allowed to log in via ssh. If user is listed
76  * in DenyUsers or one of user's groups is listed in DenyGroups, false
77  * will be returned. If AllowUsers isn't empty and user isn't listed
78  * there, or if AllowGroups isn't empty and one of user's groups isn't
79  * listed there, false will be returned.
80  * If the user's shell is not executable, false will be returned.
81  * Otherwise true is returned.
82  */
83 int
84 allowed_user(struct passwd * pw)
85 {
86 	struct ssh *ssh = active_state; /* XXX */
87 	struct stat st;
88 	const char *hostname = NULL, *ipaddr = NULL;
89 	int r;
90 	u_int i;
91 
92 	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
93 	if (!pw || !pw->pw_name)
94 		return 0;
95 
96 	/*
97 	 * Deny if shell does not exist or is not executable unless we
98 	 * are chrooting.
99 	 */
100 	if (options.chroot_directory == NULL ||
101 	    strcasecmp(options.chroot_directory, "none") == 0) {
102 		char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
103 		    _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
104 
105 		if (stat(shell, &st) != 0) {
106 			logit("User %.100s not allowed because shell %.100s "
107 			    "does not exist", pw->pw_name, shell);
108 			free(shell);
109 			return 0;
110 		}
111 		if (S_ISREG(st.st_mode) == 0 ||
112 		    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
113 			logit("User %.100s not allowed because shell %.100s "
114 			    "is not executable", pw->pw_name, shell);
115 			free(shell);
116 			return 0;
117 		}
118 		free(shell);
119 	}
120 
121 	if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
122 	    options.num_deny_groups > 0 || options.num_allow_groups > 0) {
123 		hostname = auth_get_canonical_hostname(ssh, options.use_dns);
124 		ipaddr = ssh_remote_ipaddr(ssh);
125 	}
126 
127 	/* Return false if user is listed in DenyUsers */
128 	if (options.num_deny_users > 0) {
129 		for (i = 0; i < options.num_deny_users; i++) {
130 			r = match_user(pw->pw_name, hostname, ipaddr,
131 			    options.deny_users[i]);
132 			if (r < 0) {
133 				fatal("Invalid DenyUsers pattern \"%.100s\"",
134 				    options.deny_users[i]);
135 			} else if (r != 0) {
136 				logit("User %.100s from %.100s not allowed "
137 				    "because listed in DenyUsers",
138 				    pw->pw_name, hostname);
139 				return 0;
140 			}
141 		}
142 	}
143 	/* Return false if AllowUsers isn't empty and user isn't listed there */
144 	if (options.num_allow_users > 0) {
145 		for (i = 0; i < options.num_allow_users; i++) {
146 			r = match_user(pw->pw_name, hostname, ipaddr,
147 			    options.allow_users[i]);
148 			if (r < 0) {
149 				fatal("Invalid AllowUsers pattern \"%.100s\"",
150 				    options.allow_users[i]);
151 			} else if (r == 1)
152 				break;
153 		}
154 		/* i < options.num_allow_users iff we break for loop */
155 		if (i >= options.num_allow_users) {
156 			logit("User %.100s from %.100s not allowed because "
157 			    "not listed in AllowUsers", pw->pw_name, hostname);
158 			return 0;
159 		}
160 	}
161 	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
162 		/* Get the user's group access list (primary and supplementary) */
163 		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
164 			logit("User %.100s from %.100s not allowed because "
165 			    "not in any group", pw->pw_name, hostname);
166 			return 0;
167 		}
168 
169 		/* Return false if one of user's groups is listed in DenyGroups */
170 		if (options.num_deny_groups > 0)
171 			if (ga_match(options.deny_groups,
172 			    options.num_deny_groups)) {
173 				ga_free();
174 				logit("User %.100s from %.100s not allowed "
175 				    "because a group is listed in DenyGroups",
176 				    pw->pw_name, hostname);
177 				return 0;
178 			}
179 		/*
180 		 * Return false if AllowGroups isn't empty and one of user's groups
181 		 * isn't listed there
182 		 */
183 		if (options.num_allow_groups > 0)
184 			if (!ga_match(options.allow_groups,
185 			    options.num_allow_groups)) {
186 				ga_free();
187 				logit("User %.100s from %.100s not allowed "
188 				    "because none of user's groups are listed "
189 				    "in AllowGroups", pw->pw_name, hostname);
190 				return 0;
191 			}
192 		ga_free();
193 	}
194 	/* We found no reason not to let this user try to log on... */
195 	return 1;
196 }
197 
198 /*
199  * Formats any key left in authctxt->auth_method_key for inclusion in
200  * auth_log()'s message. Also includes authxtct->auth_method_info if present.
201  */
202 static char *
203 format_method_key(Authctxt *authctxt)
204 {
205 	const struct sshkey *key = authctxt->auth_method_key;
206 	const char *methinfo = authctxt->auth_method_info;
207 	char *fp, *ret = NULL;
208 
209 	if (key == NULL)
210 		return NULL;
211 
212 	if (key_is_cert(key)) {
213 		fp = sshkey_fingerprint(key->cert->signature_key,
214 		    options.fingerprint_hash, SSH_FP_DEFAULT);
215 		xasprintf(&ret, "%s ID %s (serial %llu) CA %s %s%s%s",
216 		    sshkey_type(key), key->cert->key_id,
217 		    (unsigned long long)key->cert->serial,
218 		    sshkey_type(key->cert->signature_key),
219 		    fp == NULL ? "(null)" : fp,
220 		    methinfo == NULL ? "" : ", ",
221 		    methinfo == NULL ? "" : methinfo);
222 		free(fp);
223 	} else {
224 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
225 		    SSH_FP_DEFAULT);
226 		xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
227 		    fp == NULL ? "(null)" : fp,
228 		    methinfo == NULL ? "" : ", ",
229 		    methinfo == NULL ? "" : methinfo);
230 		free(fp);
231 	}
232 	return ret;
233 }
234 
235 void
236 auth_log(Authctxt *authctxt, int authenticated, int partial,
237     const char *method, const char *submethod)
238 {
239 	struct ssh *ssh = active_state; /* XXX */
240 	void (*authlog) (const char *fmt,...) = verbose;
241 	const char *authmsg;
242 	char *extra = NULL;
243 
244 	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
245 		return;
246 
247 	/* Raise logging level */
248 	if (authenticated == 1 ||
249 	    !authctxt->valid ||
250 	    authctxt->failures >= options.max_authtries / 2 ||
251 	    strcmp(method, "password") == 0)
252 		authlog = logit;
253 
254 	if (authctxt->postponed)
255 		authmsg = "Postponed";
256 	else if (partial)
257 		authmsg = "Partial";
258 	else
259 		authmsg = authenticated ? "Accepted" : "Failed";
260 
261 	if ((extra = format_method_key(authctxt)) == NULL) {
262 		if (authctxt->auth_method_info != NULL)
263 			extra = xstrdup(authctxt->auth_method_info);
264 	}
265 
266 	authlog("%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
267 	    authmsg,
268 	    method,
269 	    submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
270 	    authctxt->valid ? "" : "invalid user ",
271 	    authctxt->user,
272 	    ssh_remote_ipaddr(ssh),
273 	    ssh_remote_port(ssh),
274 	    extra != NULL ? ": " : "",
275 	    extra != NULL ? extra : "");
276 
277 	free(extra);
278 }
279 
280 void
281 auth_maxtries_exceeded(Authctxt *authctxt)
282 {
283 	struct ssh *ssh = active_state; /* XXX */
284 
285 	error("maximum authentication attempts exceeded for "
286 	    "%s%.100s from %.200s port %d ssh2",
287 	    authctxt->valid ? "" : "invalid user ",
288 	    authctxt->user,
289 	    ssh_remote_ipaddr(ssh),
290 	    ssh_remote_port(ssh));
291 	packet_disconnect("Too many authentication failures");
292 	/* NOTREACHED */
293 }
294 
295 /*
296  * Check whether root logins are disallowed.
297  */
298 int
299 auth_root_allowed(const char *method)
300 {
301 	struct ssh *ssh = active_state; /* XXX */
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 (forced_command) {
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