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