xref: /openbsd-src/usr.bin/ssh/auth.c (revision d4741794dd2f512d997014f8bd85fbb24d935059)
1 /* $OpenBSD: auth.c,v 1.119 2016/12/15 21:29:05 dtucker 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 
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <libgen.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 void
199 auth_info(Authctxt *authctxt, const char *fmt, ...)
200 {
201 	va_list ap;
202         int i;
203 
204 	free(authctxt->info);
205 	authctxt->info = NULL;
206 
207 	va_start(ap, fmt);
208 	i = vasprintf(&authctxt->info, fmt, ap);
209 	va_end(ap);
210 
211 	if (i < 0 || authctxt->info == NULL)
212 		fatal("vasprintf failed");
213 }
214 
215 void
216 auth_log(Authctxt *authctxt, int authenticated, int partial,
217     const char *method, const char *submethod)
218 {
219 	struct ssh *ssh = active_state; /* XXX */
220 	void (*authlog) (const char *fmt,...) = verbose;
221 	char *authmsg;
222 
223 	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
224 		return;
225 
226 	/* Raise logging level */
227 	if (authenticated == 1 ||
228 	    !authctxt->valid ||
229 	    authctxt->failures >= options.max_authtries / 2 ||
230 	    strcmp(method, "password") == 0)
231 		authlog = logit;
232 
233 	if (authctxt->postponed)
234 		authmsg = "Postponed";
235 	else if (partial)
236 		authmsg = "Partial";
237 	else
238 		authmsg = authenticated ? "Accepted" : "Failed";
239 
240 	authlog("%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
241 	    authmsg,
242 	    method,
243 	    submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
244 	    authctxt->valid ? "" : "invalid user ",
245 	    authctxt->user,
246 	    ssh_remote_ipaddr(ssh),
247 	    ssh_remote_port(ssh),
248 	    authctxt->info != NULL ? ": " : "",
249 	    authctxt->info != NULL ? authctxt->info : "");
250 	free(authctxt->info);
251 	authctxt->info = NULL;
252 }
253 
254 void
255 auth_maxtries_exceeded(Authctxt *authctxt)
256 {
257 	struct ssh *ssh = active_state; /* XXX */
258 
259 	error("maximum authentication attempts exceeded for "
260 	    "%s%.100s from %.200s port %d ssh2",
261 	    authctxt->valid ? "" : "invalid user ",
262 	    authctxt->user,
263 	    ssh_remote_ipaddr(ssh),
264 	    ssh_remote_port(ssh));
265 	packet_disconnect("Too many authentication failures");
266 	/* NOTREACHED */
267 }
268 
269 /*
270  * Check whether root logins are disallowed.
271  */
272 int
273 auth_root_allowed(const char *method)
274 {
275 	struct ssh *ssh = active_state; /* XXX */
276 
277 	switch (options.permit_root_login) {
278 	case PERMIT_YES:
279 		return 1;
280 	case PERMIT_NO_PASSWD:
281 		if (strcmp(method, "publickey") == 0 ||
282 		    strcmp(method, "hostbased") == 0 ||
283 		    strcmp(method, "gssapi-with-mic") == 0)
284 			return 1;
285 		break;
286 	case PERMIT_FORCED_ONLY:
287 		if (forced_command) {
288 			logit("Root login accepted for forced command.");
289 			return 1;
290 		}
291 		break;
292 	}
293 	logit("ROOT LOGIN REFUSED FROM %.200s port %d",
294 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
295 	return 0;
296 }
297 
298 
299 /*
300  * Given a template and a passwd structure, build a filename
301  * by substituting % tokenised options. Currently, %% becomes '%',
302  * %h becomes the home directory and %u the username.
303  *
304  * This returns a buffer allocated by xmalloc.
305  */
306 char *
307 expand_authorized_keys(const char *filename, struct passwd *pw)
308 {
309 	char *file, ret[PATH_MAX];
310 	int i;
311 
312 	file = percent_expand(filename, "h", pw->pw_dir,
313 	    "u", pw->pw_name, (char *)NULL);
314 
315 	/*
316 	 * Ensure that filename starts anchored. If not, be backward
317 	 * compatible and prepend the '%h/'
318 	 */
319 	if (*file == '/')
320 		return (file);
321 
322 	i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
323 	if (i < 0 || (size_t)i >= sizeof(ret))
324 		fatal("expand_authorized_keys: path too long");
325 	free(file);
326 	return (xstrdup(ret));
327 }
328 
329 char *
330 authorized_principals_file(struct passwd *pw)
331 {
332 	if (options.authorized_principals_file == NULL)
333 		return NULL;
334 	return expand_authorized_keys(options.authorized_principals_file, pw);
335 }
336 
337 /* return ok if key exists in sysfile or userfile */
338 HostStatus
339 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
340     const char *sysfile, const char *userfile)
341 {
342 	char *user_hostfile;
343 	struct stat st;
344 	HostStatus host_status;
345 	struct hostkeys *hostkeys;
346 	const struct hostkey_entry *found;
347 
348 	hostkeys = init_hostkeys();
349 	load_hostkeys(hostkeys, host, sysfile);
350 	if (userfile != NULL) {
351 		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
352 		if (options.strict_modes &&
353 		    (stat(user_hostfile, &st) == 0) &&
354 		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
355 		    (st.st_mode & 022) != 0)) {
356 			logit("Authentication refused for %.100s: "
357 			    "bad owner or modes for %.200s",
358 			    pw->pw_name, user_hostfile);
359 			auth_debug_add("Ignored %.200s: bad ownership or modes",
360 			    user_hostfile);
361 		} else {
362 			temporarily_use_uid(pw);
363 			load_hostkeys(hostkeys, host, user_hostfile);
364 			restore_uid();
365 		}
366 		free(user_hostfile);
367 	}
368 	host_status = check_key_in_hostkeys(hostkeys, key, &found);
369 	if (host_status == HOST_REVOKED)
370 		error("WARNING: revoked key for %s attempted authentication",
371 		    found->host);
372 	else if (host_status == HOST_OK)
373 		debug("%s: key for %s found at %s:%ld", __func__,
374 		    found->host, found->file, found->line);
375 	else
376 		debug("%s: key for host %s not found", __func__, host);
377 
378 	free_hostkeys(hostkeys);
379 
380 	return host_status;
381 }
382 
383 /*
384  * Check a given path for security. This is defined as all components
385  * of the path to the file must be owned by either the owner of
386  * of the file or root and no directories must be group or world writable.
387  *
388  * XXX Should any specific check be done for sym links ?
389  *
390  * Takes a file name, its stat information (preferably from fstat() to
391  * avoid races), the uid of the expected owner, their home directory and an
392  * error buffer plus max size as arguments.
393  *
394  * Returns 0 on success and -1 on failure
395  */
396 int
397 auth_secure_path(const char *name, struct stat *stp, const char *pw_dir,
398     uid_t uid, char *err, size_t errlen)
399 {
400 	char buf[PATH_MAX], homedir[PATH_MAX];
401 	char *cp;
402 	int comparehome = 0;
403 	struct stat st;
404 
405 	if (realpath(name, buf) == NULL) {
406 		snprintf(err, errlen, "realpath %s failed: %s", name,
407 		    strerror(errno));
408 		return -1;
409 	}
410 	if (pw_dir != NULL && realpath(pw_dir, homedir) != NULL)
411 		comparehome = 1;
412 
413 	if (!S_ISREG(stp->st_mode)) {
414 		snprintf(err, errlen, "%s is not a regular file", buf);
415 		return -1;
416 	}
417 	if ((stp->st_uid != 0 && stp->st_uid != uid) ||
418 	    (stp->st_mode & 022) != 0) {
419 		snprintf(err, errlen, "bad ownership or modes for file %s",
420 		    buf);
421 		return -1;
422 	}
423 
424 	/* for each component of the canonical path, walking upwards */
425 	for (;;) {
426 		if ((cp = dirname(buf)) == NULL) {
427 			snprintf(err, errlen, "dirname() failed");
428 			return -1;
429 		}
430 		strlcpy(buf, cp, sizeof(buf));
431 
432 		if (stat(buf, &st) < 0 ||
433 		    (st.st_uid != 0 && st.st_uid != uid) ||
434 		    (st.st_mode & 022) != 0) {
435 			snprintf(err, errlen,
436 			    "bad ownership or modes for directory %s", buf);
437 			return -1;
438 		}
439 
440 		/* If are past the homedir then we can stop */
441 		if (comparehome && strcmp(homedir, buf) == 0)
442 			break;
443 
444 		/*
445 		 * dirname should always complete with a "/" path,
446 		 * but we can be paranoid and check for "." too
447 		 */
448 		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
449 			break;
450 	}
451 	return 0;
452 }
453 
454 /*
455  * Version of secure_path() that accepts an open file descriptor to
456  * avoid races.
457  *
458  * Returns 0 on success and -1 on failure
459  */
460 static int
461 secure_filename(FILE *f, const char *file, struct passwd *pw,
462     char *err, size_t errlen)
463 {
464 	struct stat st;
465 
466 	/* check the open file to avoid races */
467 	if (fstat(fileno(f), &st) < 0) {
468 		snprintf(err, errlen, "cannot stat file %s: %s",
469 		    file, strerror(errno));
470 		return -1;
471 	}
472 	return auth_secure_path(file, &st, pw->pw_dir, pw->pw_uid, err, errlen);
473 }
474 
475 static FILE *
476 auth_openfile(const char *file, struct passwd *pw, int strict_modes,
477     int log_missing, char *file_type)
478 {
479 	char line[1024];
480 	struct stat st;
481 	int fd;
482 	FILE *f;
483 
484 	if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
485 		if (log_missing || errno != ENOENT)
486 			debug("Could not open %s '%s': %s", file_type, file,
487 			   strerror(errno));
488 		return NULL;
489 	}
490 
491 	if (fstat(fd, &st) < 0) {
492 		close(fd);
493 		return NULL;
494 	}
495 	if (!S_ISREG(st.st_mode)) {
496 		logit("User %s %s %s is not a regular file",
497 		    pw->pw_name, file_type, file);
498 		close(fd);
499 		return NULL;
500 	}
501 	unset_nonblock(fd);
502 	if ((f = fdopen(fd, "r")) == NULL) {
503 		close(fd);
504 		return NULL;
505 	}
506 	if (strict_modes &&
507 	    secure_filename(f, file, pw, line, sizeof(line)) != 0) {
508 		fclose(f);
509 		logit("Authentication refused: %s", line);
510 		auth_debug_add("Ignored %s: %s", file_type, line);
511 		return NULL;
512 	}
513 
514 	return f;
515 }
516 
517 
518 FILE *
519 auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
520 {
521 	return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
522 }
523 
524 FILE *
525 auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
526 {
527 	return auth_openfile(file, pw, strict_modes, 0,
528 	    "authorized principals");
529 }
530 
531 struct passwd *
532 getpwnamallow(const char *user)
533 {
534 	struct ssh *ssh = active_state; /* XXX */
535 	extern login_cap_t *lc;
536 	auth_session_t *as;
537 	struct passwd *pw;
538 	struct connection_info *ci = get_connection_info(1, options.use_dns);
539 
540 	ci->user = user;
541 	parse_server_match_config(&options, ci);
542 
543 	pw = getpwnam(user);
544 	if (pw == NULL) {
545 		logit("Invalid user %.100s from %.100s port %d",
546 		    user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
547 		return (NULL);
548 	}
549 	if (!allowed_user(pw))
550 		return (NULL);
551 	if ((lc = login_getclass(pw->pw_class)) == NULL) {
552 		debug("unable to get login class: %s", user);
553 		return (NULL);
554 	}
555 	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
556 	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
557 		debug("Approval failure for %s", user);
558 		pw = NULL;
559 	}
560 	if (as != NULL)
561 		auth_close(as);
562 	if (pw != NULL)
563 		return (pwcopy(pw));
564 	return (NULL);
565 }
566 
567 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
568 int
569 auth_key_is_revoked(Key *key)
570 {
571 	char *fp = NULL;
572 	int r;
573 
574 	if (options.revoked_keys_file == NULL)
575 		return 0;
576 	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
577 	    SSH_FP_DEFAULT)) == NULL) {
578 		r = SSH_ERR_ALLOC_FAIL;
579 		error("%s: fingerprint key: %s", __func__, ssh_err(r));
580 		goto out;
581 	}
582 
583 	r = sshkey_check_revoked(key, options.revoked_keys_file);
584 	switch (r) {
585 	case 0:
586 		break; /* not revoked */
587 	case SSH_ERR_KEY_REVOKED:
588 		error("Authentication key %s %s revoked by file %s",
589 		    sshkey_type(key), fp, options.revoked_keys_file);
590 		goto out;
591 	default:
592 		error("Error checking authentication key %s %s in "
593 		    "revoked keys file %s: %s", sshkey_type(key), fp,
594 		    options.revoked_keys_file, ssh_err(r));
595 		goto out;
596 	}
597 
598 	/* Success */
599 	r = 0;
600 
601  out:
602 	free(fp);
603 	return r == 0 ? 0 : 1;
604 }
605 
606 void
607 auth_debug_add(const char *fmt,...)
608 {
609 	char buf[1024];
610 	va_list args;
611 
612 	if (!auth_debug_init)
613 		return;
614 
615 	va_start(args, fmt);
616 	vsnprintf(buf, sizeof(buf), fmt, args);
617 	va_end(args);
618 	buffer_put_cstring(&auth_debug, buf);
619 }
620 
621 void
622 auth_debug_send(void)
623 {
624 	char *msg;
625 
626 	if (!auth_debug_init)
627 		return;
628 	while (buffer_len(&auth_debug)) {
629 		msg = buffer_get_string(&auth_debug, NULL);
630 		packet_send_debug("%s", msg);
631 		free(msg);
632 	}
633 }
634 
635 void
636 auth_debug_reset(void)
637 {
638 	if (auth_debug_init)
639 		buffer_clear(&auth_debug);
640 	else {
641 		buffer_init(&auth_debug);
642 		auth_debug_init = 1;
643 	}
644 }
645 
646 struct passwd *
647 fakepw(void)
648 {
649 	static struct passwd fake;
650 
651 	memset(&fake, 0, sizeof(fake));
652 	fake.pw_name = "NOUSER";
653 	fake.pw_passwd =
654 	    "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
655 	fake.pw_gecos = "NOUSER";
656 	fake.pw_uid = (uid_t)-1;
657 	fake.pw_gid = (gid_t)-1;
658 	fake.pw_class = "";
659 	fake.pw_dir = "/nonexist";
660 	fake.pw_shell = "/nonexist";
661 
662 	return (&fake);
663 }
664 
665 /*
666  * Returns the remote DNS hostname as a string. The returned string must not
667  * be freed. NB. this will usually trigger a DNS query the first time it is
668  * called.
669  * This function does additional checks on the hostname to mitigate some
670  * attacks on legacy rhosts-style authentication.
671  * XXX is RhostsRSAAuthentication vulnerable to these?
672  * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
673  */
674 
675 static char *
676 remote_hostname(struct ssh *ssh)
677 {
678 	struct sockaddr_storage from;
679 	socklen_t fromlen;
680 	struct addrinfo hints, *ai, *aitop;
681 	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
682 	const char *ntop = ssh_remote_ipaddr(ssh);
683 
684 	/* Get IP address of client. */
685 	fromlen = sizeof(from);
686 	memset(&from, 0, sizeof(from));
687 	if (getpeername(ssh_packet_get_connection_in(ssh),
688 	    (struct sockaddr *)&from, &fromlen) < 0) {
689 		debug("getpeername failed: %.100s", strerror(errno));
690 		return strdup(ntop);
691 	}
692 
693 	debug3("Trying to reverse map address %.100s.", ntop);
694 	/* Map the IP address to a host name. */
695 	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
696 	    NULL, 0, NI_NAMEREQD) != 0) {
697 		/* Host name not found.  Use ip address. */
698 		return strdup(ntop);
699 	}
700 
701 	/*
702 	 * if reverse lookup result looks like a numeric hostname,
703 	 * someone is trying to trick us by PTR record like following:
704 	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
705 	 */
706 	memset(&hints, 0, sizeof(hints));
707 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
708 	hints.ai_flags = AI_NUMERICHOST;
709 	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
710 		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
711 		    name, ntop);
712 		freeaddrinfo(ai);
713 		return strdup(ntop);
714 	}
715 
716 	/* Names are stored in lowercase. */
717 	lowercase(name);
718 
719 	/*
720 	 * Map it back to an IP address and check that the given
721 	 * address actually is an address of this host.  This is
722 	 * necessary because anyone with access to a name server can
723 	 * define arbitrary names for an IP address. Mapping from
724 	 * name to IP address can be trusted better (but can still be
725 	 * fooled if the intruder has access to the name server of
726 	 * the domain).
727 	 */
728 	memset(&hints, 0, sizeof(hints));
729 	hints.ai_family = from.ss_family;
730 	hints.ai_socktype = SOCK_STREAM;
731 	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
732 		logit("reverse mapping checking getaddrinfo for %.700s "
733 		    "[%s] failed.", name, ntop);
734 		return strdup(ntop);
735 	}
736 	/* Look for the address from the list of addresses. */
737 	for (ai = aitop; ai; ai = ai->ai_next) {
738 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
739 		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
740 		    (strcmp(ntop, ntop2) == 0))
741 				break;
742 	}
743 	freeaddrinfo(aitop);
744 	/* If we reached the end of the list, the address was not there. */
745 	if (ai == NULL) {
746 		/* Address not found for the host name. */
747 		logit("Address %.100s maps to %.600s, but this does not "
748 		    "map back to the address.", ntop, name);
749 		return strdup(ntop);
750 	}
751 	return strdup(name);
752 }
753 
754 /*
755  * Return the canonical name of the host in the other side of the current
756  * connection.  The host name is cached, so it is efficient to call this
757  * several times.
758  */
759 
760 const char *
761 auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
762 {
763 	static char *dnsname;
764 
765 	if (!use_dns)
766 		return ssh_remote_ipaddr(ssh);
767 	else if (dnsname != NULL)
768 		return dnsname;
769 	else {
770 		dnsname = remote_hostname(ssh);
771 		return dnsname;
772 	}
773 }
774