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