xref: /openbsd/usr.bin/ssh/auth.c (revision 15d7c2bc)
1 /* $OpenBSD: auth.c,v 1.160 2023/03/05 05:34:09 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 #include <sys/wait.h>
30 
31 #include <stdlib.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <login_cap.h>
35 #include <paths.h>
36 #include <pwd.h>
37 #include <stdarg.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <limits.h>
42 #include <netdb.h>
43 #include <time.h>
44 
45 #include "xmalloc.h"
46 #include "match.h"
47 #include "groupaccess.h"
48 #include "log.h"
49 #include "sshbuf.h"
50 #include "misc.h"
51 #include "servconf.h"
52 #include "sshkey.h"
53 #include "hostfile.h"
54 #include "auth.h"
55 #include "auth-options.h"
56 #include "canohost.h"
57 #include "uidswap.h"
58 #include "packet.h"
59 #ifdef GSSAPI
60 #include "ssh-gss.h"
61 #endif
62 #include "authfile.h"
63 #include "monitor_wrap.h"
64 #include "ssherr.h"
65 #include "channels.h"
66 
67 /* import */
68 extern ServerOptions options;
69 extern struct include_list includes;
70 extern int use_privsep;
71 extern struct sshauthopt *auth_opts;
72 
73 /* Debugging messages */
74 static struct sshbuf *auth_debug;
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
allowed_user(struct ssh * ssh,struct passwd * pw)86 allowed_user(struct ssh *ssh, struct passwd * pw)
87 {
88 	struct stat st;
89 	const char *hostname = NULL, *ipaddr = NULL;
90 	int r;
91 	u_int i;
92 
93 	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
94 	if (!pw || !pw->pw_name)
95 		return 0;
96 
97 	/*
98 	 * Deny if shell does not exist or is not executable unless we
99 	 * are chrooting.
100 	 */
101 	if (options.chroot_directory == NULL ||
102 	    strcasecmp(options.chroot_directory, "none") == 0) {
103 		char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
104 		    _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
105 
106 		if (stat(shell, &st) == -1) {
107 			logit("User %.100s not allowed because shell %.100s "
108 			    "does not exist", pw->pw_name, shell);
109 			free(shell);
110 			return 0;
111 		}
112 		if (S_ISREG(st.st_mode) == 0 ||
113 		    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
114 			logit("User %.100s not allowed because shell %.100s "
115 			    "is not executable", pw->pw_name, shell);
116 			free(shell);
117 			return 0;
118 		}
119 		free(shell);
120 	}
121 
122 	if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
123 	    options.num_deny_groups > 0 || options.num_allow_groups > 0) {
124 		hostname = auth_get_canonical_hostname(ssh, options.use_dns);
125 		ipaddr = ssh_remote_ipaddr(ssh);
126 	}
127 
128 	/* Return false if user is listed in DenyUsers */
129 	if (options.num_deny_users > 0) {
130 		for (i = 0; i < options.num_deny_users; i++) {
131 			r = match_user(pw->pw_name, hostname, ipaddr,
132 			    options.deny_users[i]);
133 			if (r < 0) {
134 				fatal("Invalid DenyUsers pattern \"%.100s\"",
135 				    options.deny_users[i]);
136 			} else if (r != 0) {
137 				logit("User %.100s from %.100s not allowed "
138 				    "because listed in DenyUsers",
139 				    pw->pw_name, hostname);
140 				return 0;
141 			}
142 		}
143 	}
144 	/* Return false if AllowUsers isn't empty and user isn't listed there */
145 	if (options.num_allow_users > 0) {
146 		for (i = 0; i < options.num_allow_users; i++) {
147 			r = match_user(pw->pw_name, hostname, ipaddr,
148 			    options.allow_users[i]);
149 			if (r < 0) {
150 				fatal("Invalid AllowUsers pattern \"%.100s\"",
151 				    options.allow_users[i]);
152 			} else if (r == 1)
153 				break;
154 		}
155 		/* i < options.num_allow_users iff we break for loop */
156 		if (i >= options.num_allow_users) {
157 			logit("User %.100s from %.100s not allowed because "
158 			    "not listed in AllowUsers", pw->pw_name, hostname);
159 			return 0;
160 		}
161 	}
162 	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
163 		/* Get the user's group access list (primary and supplementary) */
164 		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
165 			logit("User %.100s from %.100s not allowed because "
166 			    "not in any group", pw->pw_name, hostname);
167 			return 0;
168 		}
169 
170 		/* Return false if one of user's groups is listed in DenyGroups */
171 		if (options.num_deny_groups > 0)
172 			if (ga_match(options.deny_groups,
173 			    options.num_deny_groups)) {
174 				ga_free();
175 				logit("User %.100s from %.100s not allowed "
176 				    "because a group is listed in DenyGroups",
177 				    pw->pw_name, hostname);
178 				return 0;
179 			}
180 		/*
181 		 * Return false if AllowGroups isn't empty and one of user's groups
182 		 * isn't listed there
183 		 */
184 		if (options.num_allow_groups > 0)
185 			if (!ga_match(options.allow_groups,
186 			    options.num_allow_groups)) {
187 				ga_free();
188 				logit("User %.100s from %.100s not allowed "
189 				    "because none of user's groups are listed "
190 				    "in AllowGroups", pw->pw_name, hostname);
191 				return 0;
192 			}
193 		ga_free();
194 	}
195 	/* We found no reason not to let this user try to log on... */
196 	return 1;
197 }
198 
199 /*
200  * Formats any key left in authctxt->auth_method_key for inclusion in
201  * auth_log()'s message. Also includes authxtct->auth_method_info if present.
202  */
203 static char *
format_method_key(Authctxt * authctxt)204 format_method_key(Authctxt *authctxt)
205 {
206 	const struct sshkey *key = authctxt->auth_method_key;
207 	const char *methinfo = authctxt->auth_method_info;
208 	char *fp, *cafp, *ret = NULL;
209 
210 	if (key == NULL)
211 		return NULL;
212 
213 	if (sshkey_is_cert(key)) {
214 		fp = sshkey_fingerprint(key,
215 		    options.fingerprint_hash, SSH_FP_DEFAULT);
216 		cafp = sshkey_fingerprint(key->cert->signature_key,
217 		    options.fingerprint_hash, SSH_FP_DEFAULT);
218 		xasprintf(&ret, "%s %s ID %s (serial %llu) CA %s %s%s%s",
219 		    sshkey_type(key), fp == NULL ? "(null)" : fp,
220 		    key->cert->key_id,
221 		    (unsigned long long)key->cert->serial,
222 		    sshkey_type(key->cert->signature_key),
223 		    cafp == NULL ? "(null)" : cafp,
224 		    methinfo == NULL ? "" : ", ",
225 		    methinfo == NULL ? "" : methinfo);
226 		free(fp);
227 		free(cafp);
228 	} else {
229 		fp = sshkey_fingerprint(key, options.fingerprint_hash,
230 		    SSH_FP_DEFAULT);
231 		xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
232 		    fp == NULL ? "(null)" : fp,
233 		    methinfo == NULL ? "" : ", ",
234 		    methinfo == NULL ? "" : methinfo);
235 		free(fp);
236 	}
237 	return ret;
238 }
239 
240 void
auth_log(struct ssh * ssh,int authenticated,int partial,const char * method,const char * submethod)241 auth_log(struct ssh *ssh, int authenticated, int partial,
242     const char *method, const char *submethod)
243 {
244 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
245 	int level = SYSLOG_LEVEL_VERBOSE;
246 	const char *authmsg;
247 	char *extra = NULL;
248 
249 	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
250 		return;
251 
252 	/* Raise logging level */
253 	if (authenticated == 1 ||
254 	    !authctxt->valid ||
255 	    authctxt->failures >= options.max_authtries / 2 ||
256 	    strcmp(method, "password") == 0)
257 		level = SYSLOG_LEVEL_INFO;
258 
259 	if (authctxt->postponed)
260 		authmsg = "Postponed";
261 	else if (partial)
262 		authmsg = "Partial";
263 	else
264 		authmsg = authenticated ? "Accepted" : "Failed";
265 
266 	if ((extra = format_method_key(authctxt)) == NULL) {
267 		if (authctxt->auth_method_info != NULL)
268 			extra = xstrdup(authctxt->auth_method_info);
269 	}
270 
271 	do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
272 	    authmsg,
273 	    method,
274 	    submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
275 	    authctxt->valid ? "" : "invalid user ",
276 	    authctxt->user,
277 	    ssh_remote_ipaddr(ssh),
278 	    ssh_remote_port(ssh),
279 	    extra != NULL ? ": " : "",
280 	    extra != NULL ? extra : "");
281 
282 	free(extra);
283 }
284 
285 void
auth_maxtries_exceeded(struct ssh * ssh)286 auth_maxtries_exceeded(struct ssh *ssh)
287 {
288 	Authctxt *authctxt = (Authctxt *)ssh->authctxt;
289 
290 	error("maximum authentication attempts exceeded for "
291 	    "%s%.100s from %.200s port %d ssh2",
292 	    authctxt->valid ? "" : "invalid user ",
293 	    authctxt->user,
294 	    ssh_remote_ipaddr(ssh),
295 	    ssh_remote_port(ssh));
296 	ssh_packet_disconnect(ssh, "Too many authentication failures");
297 	/* NOTREACHED */
298 }
299 
300 /*
301  * Check whether root logins are disallowed.
302  */
303 int
auth_root_allowed(struct ssh * ssh,const char * method)304 auth_root_allowed(struct ssh *ssh, const char *method)
305 {
306 	switch (options.permit_root_login) {
307 	case PERMIT_YES:
308 		return 1;
309 	case PERMIT_NO_PASSWD:
310 		if (strcmp(method, "publickey") == 0 ||
311 		    strcmp(method, "hostbased") == 0 ||
312 		    strcmp(method, "gssapi-with-mic") == 0)
313 			return 1;
314 		break;
315 	case PERMIT_FORCED_ONLY:
316 		if (auth_opts->force_command != NULL) {
317 			logit("Root login accepted for forced command.");
318 			return 1;
319 		}
320 		break;
321 	}
322 	logit("ROOT LOGIN REFUSED FROM %.200s port %d",
323 	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
324 	return 0;
325 }
326 
327 
328 /*
329  * Given a template and a passwd structure, build a filename
330  * by substituting % tokenised options. Currently, %% becomes '%',
331  * %h becomes the home directory and %u the username.
332  *
333  * This returns a buffer allocated by xmalloc.
334  */
335 char *
expand_authorized_keys(const char * filename,struct passwd * pw)336 expand_authorized_keys(const char *filename, struct passwd *pw)
337 {
338 	char *file, uidstr[32], ret[PATH_MAX];
339 	int i;
340 
341 	snprintf(uidstr, sizeof(uidstr), "%llu",
342 	    (unsigned long long)pw->pw_uid);
343 	file = percent_expand(filename, "h", pw->pw_dir,
344 	    "u", pw->pw_name, "U", uidstr, (char *)NULL);
345 
346 	/*
347 	 * Ensure that filename starts anchored. If not, be backward
348 	 * compatible and prepend the '%h/'
349 	 */
350 	if (path_absolute(file))
351 		return (file);
352 
353 	i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
354 	if (i < 0 || (size_t)i >= sizeof(ret))
355 		fatal("expand_authorized_keys: path too long");
356 	free(file);
357 	return (xstrdup(ret));
358 }
359 
360 char *
authorized_principals_file(struct passwd * pw)361 authorized_principals_file(struct passwd *pw)
362 {
363 	if (options.authorized_principals_file == NULL)
364 		return NULL;
365 	return expand_authorized_keys(options.authorized_principals_file, pw);
366 }
367 
368 /* return ok if key exists in sysfile or userfile */
369 HostStatus
check_key_in_hostfiles(struct passwd * pw,struct sshkey * key,const char * host,const char * sysfile,const char * userfile)370 check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
371     const char *sysfile, const char *userfile)
372 {
373 	char *user_hostfile;
374 	struct stat st;
375 	HostStatus host_status;
376 	struct hostkeys *hostkeys;
377 	const struct hostkey_entry *found;
378 
379 	hostkeys = init_hostkeys();
380 	load_hostkeys(hostkeys, host, sysfile, 0);
381 	if (userfile != NULL) {
382 		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
383 		if (options.strict_modes &&
384 		    (stat(user_hostfile, &st) == 0) &&
385 		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
386 		    (st.st_mode & 022) != 0)) {
387 			logit("Authentication refused for %.100s: "
388 			    "bad owner or modes for %.200s",
389 			    pw->pw_name, user_hostfile);
390 			auth_debug_add("Ignored %.200s: bad ownership or modes",
391 			    user_hostfile);
392 		} else {
393 			temporarily_use_uid(pw);
394 			load_hostkeys(hostkeys, host, user_hostfile, 0);
395 			restore_uid();
396 		}
397 		free(user_hostfile);
398 	}
399 	host_status = check_key_in_hostkeys(hostkeys, key, &found);
400 	if (host_status == HOST_REVOKED)
401 		error("WARNING: revoked key for %s attempted authentication",
402 		    host);
403 	else if (host_status == HOST_OK)
404 		debug_f("key for %s found at %s:%ld",
405 		    found->host, found->file, found->line);
406 	else
407 		debug_f("key for host %s not found", host);
408 
409 	free_hostkeys(hostkeys);
410 
411 	return host_status;
412 }
413 
414 struct passwd *
getpwnamallow(struct ssh * ssh,const char * user)415 getpwnamallow(struct ssh *ssh, const char *user)
416 {
417 	extern login_cap_t *lc;
418 	auth_session_t *as;
419 	struct passwd *pw;
420 	struct connection_info *ci;
421 	u_int i;
422 
423 	ci = get_connection_info(ssh, 1, options.use_dns);
424 	ci->user = user;
425 	parse_server_match_config(&options, &includes, ci);
426 	log_change_level(options.log_level);
427 	log_verbose_reset();
428 	for (i = 0; i < options.num_log_verbose; i++)
429 		log_verbose_add(options.log_verbose[i]);
430 	process_permitopen(ssh, &options);
431 
432 	pw = getpwnam(user);
433 	if (pw == NULL) {
434 		logit("Invalid user %.100s from %.100s port %d",
435 		    user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
436 		return (NULL);
437 	}
438 	if (!allowed_user(ssh, pw))
439 		return (NULL);
440 	if ((lc = login_getclass(pw->pw_class)) == NULL) {
441 		debug("unable to get login class: %s", user);
442 		return (NULL);
443 	}
444 	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
445 	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
446 		debug("Approval failure for %s", user);
447 		pw = NULL;
448 	}
449 	if (as != NULL)
450 		auth_close(as);
451 	if (pw != NULL)
452 		return (pwcopy(pw));
453 	return (NULL);
454 }
455 
456 /* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
457 int
auth_key_is_revoked(struct sshkey * key)458 auth_key_is_revoked(struct sshkey *key)
459 {
460 	char *fp = NULL;
461 	int r;
462 
463 	if (options.revoked_keys_file == NULL)
464 		return 0;
465 	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
466 	    SSH_FP_DEFAULT)) == NULL) {
467 		r = SSH_ERR_ALLOC_FAIL;
468 		error_fr(r, "fingerprint key");
469 		goto out;
470 	}
471 
472 	r = sshkey_check_revoked(key, options.revoked_keys_file);
473 	switch (r) {
474 	case 0:
475 		break; /* not revoked */
476 	case SSH_ERR_KEY_REVOKED:
477 		error("Authentication key %s %s revoked by file %s",
478 		    sshkey_type(key), fp, options.revoked_keys_file);
479 		goto out;
480 	default:
481 		error_r(r, "Error checking authentication key %s %s in "
482 		    "revoked keys file %s", sshkey_type(key), fp,
483 		    options.revoked_keys_file);
484 		goto out;
485 	}
486 
487 	/* Success */
488 	r = 0;
489 
490  out:
491 	free(fp);
492 	return r == 0 ? 0 : 1;
493 }
494 
495 void
auth_debug_add(const char * fmt,...)496 auth_debug_add(const char *fmt,...)
497 {
498 	char buf[1024];
499 	va_list args;
500 	int r;
501 
502 	va_start(args, fmt);
503 	vsnprintf(buf, sizeof(buf), fmt, args);
504 	va_end(args);
505 	debug3("%s", buf);
506 	if (auth_debug != NULL)
507 		if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0)
508 			fatal_fr(r, "sshbuf_put_cstring");
509 }
510 
511 void
auth_debug_send(struct ssh * ssh)512 auth_debug_send(struct ssh *ssh)
513 {
514 	char *msg;
515 	int r;
516 
517 	if (auth_debug == NULL)
518 		return;
519 	while (sshbuf_len(auth_debug) != 0) {
520 		if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0)
521 			fatal_fr(r, "sshbuf_get_cstring");
522 		ssh_packet_send_debug(ssh, "%s", msg);
523 		free(msg);
524 	}
525 }
526 
527 void
auth_debug_reset(void)528 auth_debug_reset(void)
529 {
530 	if (auth_debug != NULL)
531 		sshbuf_reset(auth_debug);
532 	else if ((auth_debug = sshbuf_new()) == NULL)
533 		fatal_f("sshbuf_new failed");
534 }
535 
536 struct passwd *
fakepw(void)537 fakepw(void)
538 {
539 	static int done = 0;
540 	static struct passwd fake;
541 	const char hashchars[] = "./ABCDEFGHIJKLMNOPQRSTUVWXYZ"
542 	    "abcdefghijklmnopqrstuvwxyz0123456789"; /* from bcrypt.c */
543 	char *cp;
544 
545 	if (done)
546 		return (&fake);
547 
548 	memset(&fake, 0, sizeof(fake));
549 	fake.pw_name = "NOUSER";
550 	fake.pw_passwd = xstrdup("$2a$10$"
551 	    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
552 	for (cp = fake.pw_passwd + 7; *cp != '\0'; cp++)
553 		*cp = hashchars[arc4random_uniform(sizeof(hashchars) - 1)];
554 	fake.pw_gecos = "NOUSER";
555 	fake.pw_uid = (uid_t)-1;
556 	fake.pw_gid = (gid_t)-1;
557 	fake.pw_class = "";
558 	fake.pw_dir = "/nonexist";
559 	fake.pw_shell = "/nonexist";
560 	done = 1;
561 
562 	return (&fake);
563 }
564 
565 /*
566  * Returns the remote DNS hostname as a string. The returned string must not
567  * be freed. NB. this will usually trigger a DNS query the first time it is
568  * called.
569  * This function does additional checks on the hostname to mitigate some
570  * attacks on based on conflation of hostnames and IP addresses.
571  */
572 
573 static char *
remote_hostname(struct ssh * ssh)574 remote_hostname(struct ssh *ssh)
575 {
576 	struct sockaddr_storage from;
577 	socklen_t fromlen;
578 	struct addrinfo hints, *ai, *aitop;
579 	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
580 	const char *ntop = ssh_remote_ipaddr(ssh);
581 
582 	/* Get IP address of client. */
583 	fromlen = sizeof(from);
584 	memset(&from, 0, sizeof(from));
585 	if (getpeername(ssh_packet_get_connection_in(ssh),
586 	    (struct sockaddr *)&from, &fromlen) == -1) {
587 		debug("getpeername failed: %.100s", strerror(errno));
588 		return xstrdup(ntop);
589 	}
590 
591 	debug3("Trying to reverse map address %.100s.", ntop);
592 	/* Map the IP address to a host name. */
593 	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
594 	    NULL, 0, NI_NAMEREQD) != 0) {
595 		/* Host name not found.  Use ip address. */
596 		return xstrdup(ntop);
597 	}
598 
599 	/*
600 	 * if reverse lookup result looks like a numeric hostname,
601 	 * someone is trying to trick us by PTR record like following:
602 	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
603 	 */
604 	memset(&hints, 0, sizeof(hints));
605 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
606 	hints.ai_flags = AI_NUMERICHOST;
607 	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
608 		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
609 		    name, ntop);
610 		freeaddrinfo(ai);
611 		return xstrdup(ntop);
612 	}
613 
614 	/* Names are stored in lowercase. */
615 	lowercase(name);
616 
617 	/*
618 	 * Map it back to an IP address and check that the given
619 	 * address actually is an address of this host.  This is
620 	 * necessary because anyone with access to a name server can
621 	 * define arbitrary names for an IP address. Mapping from
622 	 * name to IP address can be trusted better (but can still be
623 	 * fooled if the intruder has access to the name server of
624 	 * the domain).
625 	 */
626 	memset(&hints, 0, sizeof(hints));
627 	hints.ai_family = from.ss_family;
628 	hints.ai_socktype = SOCK_STREAM;
629 	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
630 		logit("reverse mapping checking getaddrinfo for %.700s "
631 		    "[%s] failed.", name, ntop);
632 		return xstrdup(ntop);
633 	}
634 	/* Look for the address from the list of addresses. */
635 	for (ai = aitop; ai; ai = ai->ai_next) {
636 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
637 		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
638 		    (strcmp(ntop, ntop2) == 0))
639 				break;
640 	}
641 	freeaddrinfo(aitop);
642 	/* If we reached the end of the list, the address was not there. */
643 	if (ai == NULL) {
644 		/* Address not found for the host name. */
645 		logit("Address %.100s maps to %.600s, but this does not "
646 		    "map back to the address.", ntop, name);
647 		return xstrdup(ntop);
648 	}
649 	return xstrdup(name);
650 }
651 
652 /*
653  * Return the canonical name of the host in the other side of the current
654  * connection.  The host name is cached, so it is efficient to call this
655  * several times.
656  */
657 
658 const char *
auth_get_canonical_hostname(struct ssh * ssh,int use_dns)659 auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
660 {
661 	static char *dnsname;
662 
663 	if (!use_dns)
664 		return ssh_remote_ipaddr(ssh);
665 	else if (dnsname != NULL)
666 		return dnsname;
667 	else {
668 		dnsname = remote_hostname(ssh);
669 		return dnsname;
670 	}
671 }
672 
673 /* These functions link key/cert options to the auth framework */
674 
675 /* Log sshauthopt options locally and (optionally) for remote transmission */
676 void
auth_log_authopts(const char * loc,const struct sshauthopt * opts,int do_remote)677 auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
678 {
679 	int do_env = options.permit_user_env && opts->nenv > 0;
680 	int do_permitopen = opts->npermitopen > 0 &&
681 	    (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
682 	int do_permitlisten = opts->npermitlisten > 0 &&
683 	    (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0;
684 	size_t i;
685 	char msg[1024], buf[64];
686 
687 	snprintf(buf, sizeof(buf), "%d", opts->force_tun_device);
688 	/* Try to keep this alphabetically sorted */
689 	snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
690 	    opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
691 	    opts->force_command == NULL ? "" : " command",
692 	    do_env ?  " environment" : "",
693 	    opts->valid_before == 0 ? "" : "expires",
694 	    opts->no_require_user_presence ? " no-touch-required" : "",
695 	    do_permitopen ?  " permitopen" : "",
696 	    do_permitlisten ?  " permitlisten" : "",
697 	    opts->permit_port_forwarding_flag ? " port-forwarding" : "",
698 	    opts->cert_principals == NULL ? "" : " principals",
699 	    opts->permit_pty_flag ? " pty" : "",
700 	    opts->require_verify ? " uv" : "",
701 	    opts->force_tun_device == -1 ? "" : " tun=",
702 	    opts->force_tun_device == -1 ? "" : buf,
703 	    opts->permit_user_rc ? " user-rc" : "",
704 	    opts->permit_x11_forwarding_flag ? " x11-forwarding" : "");
705 
706 	debug("%s: %s", loc, msg);
707 	if (do_remote)
708 		auth_debug_add("%s: %s", loc, msg);
709 
710 	if (options.permit_user_env) {
711 		for (i = 0; i < opts->nenv; i++) {
712 			debug("%s: environment: %s", loc, opts->env[i]);
713 			if (do_remote) {
714 				auth_debug_add("%s: environment: %s",
715 				    loc, opts->env[i]);
716 			}
717 		}
718 	}
719 
720 	/* Go into a little more details for the local logs. */
721 	if (opts->valid_before != 0) {
722 		format_absolute_time(opts->valid_before, buf, sizeof(buf));
723 		debug("%s: expires at %s", loc, buf);
724 	}
725 	if (opts->cert_principals != NULL) {
726 		debug("%s: authorized principals: \"%s\"",
727 		    loc, opts->cert_principals);
728 	}
729 	if (opts->force_command != NULL)
730 		debug("%s: forced command: \"%s\"", loc, opts->force_command);
731 	if (do_permitopen) {
732 		for (i = 0; i < opts->npermitopen; i++) {
733 			debug("%s: permitted open: %s",
734 			    loc, opts->permitopen[i]);
735 		}
736 	}
737 	if (do_permitlisten) {
738 		for (i = 0; i < opts->npermitlisten; i++) {
739 			debug("%s: permitted listen: %s",
740 			    loc, opts->permitlisten[i]);
741 		}
742 	}
743 }
744 
745 /* Activate a new set of key/cert options; merging with what is there. */
746 int
auth_activate_options(struct ssh * ssh,struct sshauthopt * opts)747 auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
748 {
749 	struct sshauthopt *old = auth_opts;
750 	const char *emsg = NULL;
751 
752 	debug_f("setting new authentication options");
753 	if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
754 		error("Inconsistent authentication options: %s", emsg);
755 		return -1;
756 	}
757 	return 0;
758 }
759 
760 /* Disable forwarding, etc for the session */
761 void
auth_restrict_session(struct ssh * ssh)762 auth_restrict_session(struct ssh *ssh)
763 {
764 	struct sshauthopt *restricted;
765 
766 	debug_f("restricting session");
767 
768 	/* A blank sshauthopt defaults to permitting nothing */
769 	if ((restricted = sshauthopt_new()) == NULL)
770 		fatal_f("sshauthopt_new failed");
771 	restricted->permit_pty_flag = 1;
772 	restricted->restricted = 1;
773 
774 	if (auth_activate_options(ssh, restricted) != 0)
775 		fatal_f("failed to restrict session");
776 	sshauthopt_free(restricted);
777 }
778