1/* $OpenBSD: auth.c,v 1.133 2018/09/12 01:19:12 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__RCSID("$FreeBSD$");
28
29#include <sys/types.h>
30#include <sys/stat.h>
31#include <sys/socket.h>
32#include <sys/wait.h>
33
34#include <netinet/in.h>
35
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
55#include "xmalloc.h"
56#include "match.h"
57#include "groupaccess.h"
58#include "log.h"
59#include "sshbuf.h"
60#include "misc.h"
61#include "servconf.h"
62#include "sshkey.h"
63#include "hostfile.h"
64#include "auth.h"
65#include "auth-options.h"
66#include "canohost.h"
67#include "uidswap.h"
68#include "packet.h"
69#include "loginrec.h"
70#ifdef GSSAPI
71#include "ssh-gss.h"
72#endif
73#include "authfile.h"
74#include "monitor_wrap.h"
75#include "authfile.h"
76#include "ssherr.h"
77#include "compat.h"
78#include "channels.h"
79#include "blacklist_client.h"
80
81/* import */
82extern ServerOptions options;
83extern int use_privsep;
84extern struct sshbuf *loginmsg;
85extern struct passwd *privsep_pw;
86extern struct sshauthopt *auth_opts;
87
88/* Debugging messages */
89static struct sshbuf *auth_debug;
90
91/*
92 * Check if the user is allowed to log in via ssh. If user is listed
93 * in DenyUsers or one of user's groups is listed in DenyGroups, false
94 * will be returned. If AllowUsers isn't empty and user isn't listed
95 * there, or if AllowGroups isn't empty and one of user's groups isn't
96 * listed there, false will be returned.
97 * If the user's shell is not executable, false will be returned.
98 * Otherwise true is returned.
99 */
100int
101allowed_user(struct passwd * pw)
102{
103	struct ssh *ssh = active_state; /* XXX */
104	struct stat st;
105	const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
106	u_int i;
107	int r;
108#ifdef USE_SHADOW
109	struct spwd *spw = NULL;
110#endif
111
112	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
113	if (!pw || !pw->pw_name)
114		return 0;
115
116#ifdef USE_SHADOW
117	if (!options.use_pam)
118		spw = getspnam(pw->pw_name);
119#ifdef HAS_SHADOW_EXPIRE
120	if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
121		return 0;
122#endif /* HAS_SHADOW_EXPIRE */
123#endif /* USE_SHADOW */
124
125	/* grab passwd field for locked account check */
126	passwd = pw->pw_passwd;
127#ifdef USE_SHADOW
128	if (spw != NULL)
129#ifdef USE_LIBIAF
130		passwd = get_iaf_password(pw);
131#else
132		passwd = spw->sp_pwdp;
133#endif /* USE_LIBIAF */
134#endif
135
136	/* check for locked account */
137	if (!options.use_pam && passwd && *passwd) {
138		int locked = 0;
139
140#ifdef LOCKED_PASSWD_STRING
141		if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
142			 locked = 1;
143#endif
144#ifdef LOCKED_PASSWD_PREFIX
145		if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
146		    strlen(LOCKED_PASSWD_PREFIX)) == 0)
147			 locked = 1;
148#endif
149#ifdef LOCKED_PASSWD_SUBSTR
150		if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
151			locked = 1;
152#endif
153#ifdef USE_LIBIAF
154		free((void *) passwd);
155#endif /* USE_LIBIAF */
156		if (locked) {
157			logit("User %.100s not allowed because account is locked",
158			    pw->pw_name);
159			return 0;
160		}
161	}
162
163	/*
164	 * Deny if shell does not exist or is not executable unless we
165	 * are chrooting.
166	 */
167	if (options.chroot_directory == NULL ||
168	    strcasecmp(options.chroot_directory, "none") == 0) {
169		char *shell = xstrdup((pw->pw_shell[0] == '\0') ?
170		    _PATH_BSHELL : pw->pw_shell); /* empty = /bin/sh */
171
172		if (stat(shell, &st) != 0) {
173			logit("User %.100s not allowed because shell %.100s "
174			    "does not exist", pw->pw_name, shell);
175			free(shell);
176			return 0;
177		}
178		if (S_ISREG(st.st_mode) == 0 ||
179		    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
180			logit("User %.100s not allowed because shell %.100s "
181			    "is not executable", pw->pw_name, shell);
182			free(shell);
183			return 0;
184		}
185		free(shell);
186	}
187
188	if (options.num_deny_users > 0 || options.num_allow_users > 0 ||
189	    options.num_deny_groups > 0 || options.num_allow_groups > 0) {
190		hostname = auth_get_canonical_hostname(ssh, options.use_dns);
191		ipaddr = ssh_remote_ipaddr(ssh);
192	}
193
194	/* Return false if user is listed in DenyUsers */
195	if (options.num_deny_users > 0) {
196		for (i = 0; i < options.num_deny_users; i++) {
197			r = match_user(pw->pw_name, hostname, ipaddr,
198			    options.deny_users[i]);
199			if (r < 0) {
200				fatal("Invalid DenyUsers pattern \"%.100s\"",
201				    options.deny_users[i]);
202			} else if (r != 0) {
203				logit("User %.100s from %.100s not allowed "
204				    "because listed in DenyUsers",
205				    pw->pw_name, hostname);
206				return 0;
207			}
208		}
209	}
210	/* Return false if AllowUsers isn't empty and user isn't listed there */
211	if (options.num_allow_users > 0) {
212		for (i = 0; i < options.num_allow_users; i++) {
213			r = match_user(pw->pw_name, hostname, ipaddr,
214			    options.allow_users[i]);
215			if (r < 0) {
216				fatal("Invalid AllowUsers pattern \"%.100s\"",
217				    options.allow_users[i]);
218			} else if (r == 1)
219				break;
220		}
221		/* i < options.num_allow_users iff we break for loop */
222		if (i >= options.num_allow_users) {
223			logit("User %.100s from %.100s not allowed because "
224			    "not listed in AllowUsers", pw->pw_name, hostname);
225			return 0;
226		}
227	}
228	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
229		/* Get the user's group access list (primary and supplementary) */
230		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
231			logit("User %.100s from %.100s not allowed because "
232			    "not in any group", pw->pw_name, hostname);
233			return 0;
234		}
235
236		/* Return false if one of user's groups is listed in DenyGroups */
237		if (options.num_deny_groups > 0)
238			if (ga_match(options.deny_groups,
239			    options.num_deny_groups)) {
240				ga_free();
241				logit("User %.100s from %.100s not allowed "
242				    "because a group is listed in DenyGroups",
243				    pw->pw_name, hostname);
244				return 0;
245			}
246		/*
247		 * Return false if AllowGroups isn't empty and one of user's groups
248		 * isn't listed there
249		 */
250		if (options.num_allow_groups > 0)
251			if (!ga_match(options.allow_groups,
252			    options.num_allow_groups)) {
253				ga_free();
254				logit("User %.100s from %.100s not allowed "
255				    "because none of user's groups are listed "
256				    "in AllowGroups", pw->pw_name, hostname);
257				return 0;
258			}
259		ga_free();
260	}
261
262#ifdef CUSTOM_SYS_AUTH_ALLOWED_USER
263	if (!sys_auth_allowed_user(pw, &loginmsg))
264		return 0;
265#endif
266
267	/* We found no reason not to let this user try to log on... */
268	return 1;
269}
270
271/*
272 * Formats any key left in authctxt->auth_method_key for inclusion in
273 * auth_log()'s message. Also includes authxtct->auth_method_info if present.
274 */
275static char *
276format_method_key(Authctxt *authctxt)
277{
278	const struct sshkey *key = authctxt->auth_method_key;
279	const char *methinfo = authctxt->auth_method_info;
280	char *fp, *cafp, *ret = NULL;
281
282	if (key == NULL)
283		return NULL;
284
285	if (sshkey_is_cert(key)) {
286		fp = sshkey_fingerprint(key,
287		    options.fingerprint_hash, SSH_FP_DEFAULT);
288		cafp = sshkey_fingerprint(key->cert->signature_key,
289		    options.fingerprint_hash, SSH_FP_DEFAULT);
290		xasprintf(&ret, "%s %s ID %s (serial %llu) CA %s %s%s%s",
291		    sshkey_type(key), fp == NULL ? "(null)" : fp,
292		    key->cert->key_id,
293		    (unsigned long long)key->cert->serial,
294		    sshkey_type(key->cert->signature_key),
295		    cafp == NULL ? "(null)" : cafp,
296		    methinfo == NULL ? "" : ", ",
297		    methinfo == NULL ? "" : methinfo);
298		free(fp);
299		free(cafp);
300	} else {
301		fp = sshkey_fingerprint(key, options.fingerprint_hash,
302		    SSH_FP_DEFAULT);
303		xasprintf(&ret, "%s %s%s%s", sshkey_type(key),
304		    fp == NULL ? "(null)" : fp,
305		    methinfo == NULL ? "" : ", ",
306		    methinfo == NULL ? "" : methinfo);
307		free(fp);
308	}
309	return ret;
310}
311
312void
313auth_log(Authctxt *authctxt, int authenticated, int partial,
314    const char *method, const char *submethod)
315{
316	struct ssh *ssh = active_state; /* XXX */
317	int level = SYSLOG_LEVEL_VERBOSE;
318	const char *authmsg;
319	char *extra = NULL;
320
321	if (use_privsep && !mm_is_monitor() && !authctxt->postponed)
322		return;
323
324	/* Raise logging level */
325	if (authenticated == 1 ||
326	    !authctxt->valid ||
327	    authctxt->failures >= options.max_authtries / 2 ||
328	    strcmp(method, "password") == 0)
329		level = SYSLOG_LEVEL_INFO;
330
331	if (authctxt->postponed)
332		authmsg = "Postponed";
333	else if (partial)
334		authmsg = "Partial";
335	else {
336		authmsg = authenticated ? "Accepted" : "Failed";
337		if (authenticated)
338			BLACKLIST_NOTIFY(BLACKLIST_AUTH_OK, "ssh");
339	}
340
341	if ((extra = format_method_key(authctxt)) == NULL) {
342		if (authctxt->auth_method_info != NULL)
343			extra = xstrdup(authctxt->auth_method_info);
344	}
345
346	do_log2(level, "%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
347	    authmsg,
348	    method,
349	    submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
350	    authctxt->valid ? "" : "invalid user ",
351	    authctxt->user,
352	    ssh_remote_ipaddr(ssh),
353	    ssh_remote_port(ssh),
354	    extra != NULL ? ": " : "",
355	    extra != NULL ? extra : "");
356
357	free(extra);
358
359#ifdef CUSTOM_FAILED_LOGIN
360	if (authenticated == 0 && !authctxt->postponed &&
361	    (strcmp(method, "password") == 0 ||
362	    strncmp(method, "keyboard-interactive", 20) == 0 ||
363	    strcmp(method, "challenge-response") == 0))
364		record_failed_login(authctxt->user,
365		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
366# ifdef WITH_AIXAUTHENTICATE
367	if (authenticated)
368		sys_auth_record_login(authctxt->user,
369		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh",
370		    &loginmsg);
371# endif
372#endif
373#ifdef SSH_AUDIT_EVENTS
374	if (authenticated == 0 && !authctxt->postponed)
375		audit_event(audit_classify_auth(method));
376#endif
377}
378
379
380void
381auth_maxtries_exceeded(Authctxt *authctxt)
382{
383	struct ssh *ssh = active_state; /* XXX */
384
385	error("maximum authentication attempts exceeded for "
386	    "%s%.100s from %.200s port %d ssh2",
387	    authctxt->valid ? "" : "invalid user ",
388	    authctxt->user,
389	    ssh_remote_ipaddr(ssh),
390	    ssh_remote_port(ssh));
391	packet_disconnect("Too many authentication failures");
392	/* NOTREACHED */
393}
394
395/*
396 * Check whether root logins are disallowed.
397 */
398int
399auth_root_allowed(struct ssh *ssh, const char *method)
400{
401	switch (options.permit_root_login) {
402	case PERMIT_YES:
403		return 1;
404	case PERMIT_NO_PASSWD:
405		if (strcmp(method, "publickey") == 0 ||
406		    strcmp(method, "hostbased") == 0 ||
407		    strcmp(method, "gssapi-with-mic") == 0)
408			return 1;
409		break;
410	case PERMIT_FORCED_ONLY:
411		if (auth_opts->force_command != NULL) {
412			logit("Root login accepted for forced command.");
413			return 1;
414		}
415		break;
416	}
417	logit("ROOT LOGIN REFUSED FROM %.200s port %d",
418	    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
419	return 0;
420}
421
422
423/*
424 * Given a template and a passwd structure, build a filename
425 * by substituting % tokenised options. Currently, %% becomes '%',
426 * %h becomes the home directory and %u the username.
427 *
428 * This returns a buffer allocated by xmalloc.
429 */
430char *
431expand_authorized_keys(const char *filename, struct passwd *pw)
432{
433	char *file, uidstr[32], ret[PATH_MAX];
434	int i;
435
436	snprintf(uidstr, sizeof(uidstr), "%llu",
437	    (unsigned long long)pw->pw_uid);
438	file = percent_expand(filename, "h", pw->pw_dir,
439	    "u", pw->pw_name, "U", uidstr, (char *)NULL);
440
441	/*
442	 * Ensure that filename starts anchored. If not, be backward
443	 * compatible and prepend the '%h/'
444	 */
445	if (*file == '/')
446		return (file);
447
448	i = snprintf(ret, sizeof(ret), "%s/%s", pw->pw_dir, file);
449	if (i < 0 || (size_t)i >= sizeof(ret))
450		fatal("expand_authorized_keys: path too long");
451	free(file);
452	return (xstrdup(ret));
453}
454
455char *
456authorized_principals_file(struct passwd *pw)
457{
458	if (options.authorized_principals_file == NULL)
459		return NULL;
460	return expand_authorized_keys(options.authorized_principals_file, pw);
461}
462
463/* return ok if key exists in sysfile or userfile */
464HostStatus
465check_key_in_hostfiles(struct passwd *pw, struct sshkey *key, const char *host,
466    const char *sysfile, const char *userfile)
467{
468	char *user_hostfile;
469	struct stat st;
470	HostStatus host_status;
471	struct hostkeys *hostkeys;
472	const struct hostkey_entry *found;
473
474	hostkeys = init_hostkeys();
475	load_hostkeys(hostkeys, host, sysfile);
476	if (userfile != NULL) {
477		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
478		if (options.strict_modes &&
479		    (stat(user_hostfile, &st) == 0) &&
480		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
481		    (st.st_mode & 022) != 0)) {
482			logit("Authentication refused for %.100s: "
483			    "bad owner or modes for %.200s",
484			    pw->pw_name, user_hostfile);
485			auth_debug_add("Ignored %.200s: bad ownership or modes",
486			    user_hostfile);
487		} else {
488			temporarily_use_uid(pw);
489			load_hostkeys(hostkeys, host, user_hostfile);
490			restore_uid();
491		}
492		free(user_hostfile);
493	}
494	host_status = check_key_in_hostkeys(hostkeys, key, &found);
495	if (host_status == HOST_REVOKED)
496		error("WARNING: revoked key for %s attempted authentication",
497		    found->host);
498	else if (host_status == HOST_OK)
499		debug("%s: key for %s found at %s:%ld", __func__,
500		    found->host, found->file, found->line);
501	else
502		debug("%s: key for host %s not found", __func__, host);
503
504	free_hostkeys(hostkeys);
505
506	return host_status;
507}
508
509static FILE *
510auth_openfile(const char *file, struct passwd *pw, int strict_modes,
511    int log_missing, char *file_type)
512{
513	char line[1024];
514	struct stat st;
515	int fd;
516	FILE *f;
517
518	if ((fd = open(file, O_RDONLY|O_NONBLOCK)) == -1) {
519		if (log_missing || errno != ENOENT)
520			debug("Could not open %s '%s': %s", file_type, file,
521			   strerror(errno));
522		return NULL;
523	}
524
525	if (fstat(fd, &st) < 0) {
526		close(fd);
527		return NULL;
528	}
529	if (!S_ISREG(st.st_mode)) {
530		logit("User %s %s %s is not a regular file",
531		    pw->pw_name, file_type, file);
532		close(fd);
533		return NULL;
534	}
535	unset_nonblock(fd);
536	if ((f = fdopen(fd, "r")) == NULL) {
537		close(fd);
538		return NULL;
539	}
540	if (strict_modes &&
541	    safe_path_fd(fileno(f), file, pw, line, sizeof(line)) != 0) {
542		fclose(f);
543		logit("Authentication refused: %s", line);
544		auth_debug_add("Ignored %s: %s", file_type, line);
545		return NULL;
546	}
547
548	return f;
549}
550
551
552FILE *
553auth_openkeyfile(const char *file, struct passwd *pw, int strict_modes)
554{
555	return auth_openfile(file, pw, strict_modes, 1, "authorized keys");
556}
557
558FILE *
559auth_openprincipals(const char *file, struct passwd *pw, int strict_modes)
560{
561	return auth_openfile(file, pw, strict_modes, 0,
562	    "authorized principals");
563}
564
565struct passwd *
566getpwnamallow(const char *user)
567{
568	struct ssh *ssh = active_state; /* XXX */
569#ifdef HAVE_LOGIN_CAP
570	extern login_cap_t *lc;
571#ifdef BSD_AUTH
572	auth_session_t *as;
573#endif
574#endif
575	struct passwd *pw;
576	struct connection_info *ci = get_connection_info(1, options.use_dns);
577
578	ci->user = user;
579	parse_server_match_config(&options, ci);
580	log_change_level(options.log_level);
581	process_permitopen(ssh, &options);
582
583#if defined(_AIX) && defined(HAVE_SETAUTHDB)
584	aix_setauthdb(user);
585#endif
586
587	pw = getpwnam(user);
588
589#if defined(_AIX) && defined(HAVE_SETAUTHDB)
590	aix_restoreauthdb();
591#endif
592#ifdef HAVE_CYGWIN
593	/*
594	 * Windows usernames are case-insensitive.  To avoid later problems
595	 * when trying to match the username, the user is only allowed to
596	 * login if the username is given in the same case as stored in the
597	 * user database.
598	 */
599	if (pw != NULL && strcmp(user, pw->pw_name) != 0) {
600		logit("Login name %.100s does not match stored username %.100s",
601		    user, pw->pw_name);
602		pw = NULL;
603	}
604#endif
605	if (pw == NULL) {
606		BLACKLIST_NOTIFY(BLACKLIST_BAD_USER, user);
607		logit("Invalid user %.100s from %.100s port %d",
608		    user, ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
609#ifdef CUSTOM_FAILED_LOGIN
610		record_failed_login(user,
611		    auth_get_canonical_hostname(ssh, options.use_dns), "ssh");
612#endif
613#ifdef SSH_AUDIT_EVENTS
614		audit_event(SSH_INVALID_USER);
615#endif /* SSH_AUDIT_EVENTS */
616		return (NULL);
617	}
618	if (!allowed_user(pw))
619		return (NULL);
620#ifdef HAVE_LOGIN_CAP
621	if ((lc = login_getpwclass(pw)) == NULL) {
622		debug("unable to get login class: %s", user);
623		return (NULL);
624	}
625#ifdef BSD_AUTH
626	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
627	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
628		debug("Approval failure for %s", user);
629		pw = NULL;
630	}
631	if (as != NULL)
632		auth_close(as);
633#endif
634#endif
635	if (pw != NULL)
636		return (pwcopy(pw));
637	return (NULL);
638}
639
640/* Returns 1 if key is revoked by revoked_keys_file, 0 otherwise */
641int
642auth_key_is_revoked(struct sshkey *key)
643{
644	char *fp = NULL;
645	int r;
646
647	if (options.revoked_keys_file == NULL)
648		return 0;
649	if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
650	    SSH_FP_DEFAULT)) == NULL) {
651		r = SSH_ERR_ALLOC_FAIL;
652		error("%s: fingerprint key: %s", __func__, ssh_err(r));
653		goto out;
654	}
655
656	r = sshkey_check_revoked(key, options.revoked_keys_file);
657	switch (r) {
658	case 0:
659		break; /* not revoked */
660	case SSH_ERR_KEY_REVOKED:
661		error("Authentication key %s %s revoked by file %s",
662		    sshkey_type(key), fp, options.revoked_keys_file);
663		goto out;
664	default:
665		error("Error checking authentication key %s %s in "
666		    "revoked keys file %s: %s", sshkey_type(key), fp,
667		    options.revoked_keys_file, ssh_err(r));
668		goto out;
669	}
670
671	/* Success */
672	r = 0;
673
674 out:
675	free(fp);
676	return r == 0 ? 0 : 1;
677}
678
679void
680auth_debug_add(const char *fmt,...)
681{
682	char buf[1024];
683	va_list args;
684	int r;
685
686	if (auth_debug == NULL)
687		return;
688
689	va_start(args, fmt);
690	vsnprintf(buf, sizeof(buf), fmt, args);
691	va_end(args);
692	if ((r = sshbuf_put_cstring(auth_debug, buf)) != 0)
693		fatal("%s: sshbuf_put_cstring: %s", __func__, ssh_err(r));
694}
695
696void
697auth_debug_send(void)
698{
699	struct ssh *ssh = active_state;		/* XXX */
700	char *msg;
701	int r;
702
703	if (auth_debug == NULL)
704		return;
705	while (sshbuf_len(auth_debug) != 0) {
706		if ((r = sshbuf_get_cstring(auth_debug, &msg, NULL)) != 0)
707			fatal("%s: sshbuf_get_cstring: %s",
708			    __func__, ssh_err(r));
709		ssh_packet_send_debug(ssh, "%s", msg);
710		free(msg);
711	}
712}
713
714void
715auth_debug_reset(void)
716{
717	if (auth_debug != NULL)
718		sshbuf_reset(auth_debug);
719	else if ((auth_debug = sshbuf_new()) == NULL)
720		fatal("%s: sshbuf_new failed", __func__);
721}
722
723struct passwd *
724fakepw(void)
725{
726	static struct passwd fake;
727
728	memset(&fake, 0, sizeof(fake));
729	fake.pw_name = "NOUSER";
730	fake.pw_passwd =
731	    "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
732#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
733	fake.pw_gecos = "NOUSER";
734#endif
735	fake.pw_uid = privsep_pw == NULL ? (uid_t)-1 : privsep_pw->pw_uid;
736	fake.pw_gid = privsep_pw == NULL ? (gid_t)-1 : privsep_pw->pw_gid;
737#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
738	fake.pw_class = "";
739#endif
740	fake.pw_dir = "/nonexist";
741	fake.pw_shell = "/nonexist";
742
743	return (&fake);
744}
745
746/*
747 * Returns the remote DNS hostname as a string. The returned string must not
748 * be freed. NB. this will usually trigger a DNS query the first time it is
749 * called.
750 * This function does additional checks on the hostname to mitigate some
751 * attacks on legacy rhosts-style authentication.
752 * XXX is RhostsRSAAuthentication vulnerable to these?
753 * XXX Can we remove these checks? (or if not, remove RhostsRSAAuthentication?)
754 */
755
756static char *
757remote_hostname(struct ssh *ssh)
758{
759	struct sockaddr_storage from;
760	socklen_t fromlen;
761	struct addrinfo hints, *ai, *aitop;
762	char name[NI_MAXHOST], ntop2[NI_MAXHOST];
763	const char *ntop = ssh_remote_ipaddr(ssh);
764
765	/* Get IP address of client. */
766	fromlen = sizeof(from);
767	memset(&from, 0, sizeof(from));
768	if (getpeername(ssh_packet_get_connection_in(ssh),
769	    (struct sockaddr *)&from, &fromlen) < 0) {
770		debug("getpeername failed: %.100s", strerror(errno));
771		return strdup(ntop);
772	}
773
774	ipv64_normalise_mapped(&from, &fromlen);
775	if (from.ss_family == AF_INET6)
776		fromlen = sizeof(struct sockaddr_in6);
777
778	debug3("Trying to reverse map address %.100s.", ntop);
779	/* Map the IP address to a host name. */
780	if (getnameinfo((struct sockaddr *)&from, fromlen, name, sizeof(name),
781	    NULL, 0, NI_NAMEREQD) != 0) {
782		/* Host name not found.  Use ip address. */
783		return strdup(ntop);
784	}
785
786	/*
787	 * if reverse lookup result looks like a numeric hostname,
788	 * someone is trying to trick us by PTR record like following:
789	 *	1.1.1.10.in-addr.arpa.	IN PTR	2.3.4.5
790	 */
791	memset(&hints, 0, sizeof(hints));
792	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
793	hints.ai_flags = AI_NUMERICHOST;
794	if (getaddrinfo(name, NULL, &hints, &ai) == 0) {
795		logit("Nasty PTR record \"%s\" is set up for %s, ignoring",
796		    name, ntop);
797		freeaddrinfo(ai);
798		return strdup(ntop);
799	}
800
801	/* Names are stored in lowercase. */
802	lowercase(name);
803
804	/*
805	 * Map it back to an IP address and check that the given
806	 * address actually is an address of this host.  This is
807	 * necessary because anyone with access to a name server can
808	 * define arbitrary names for an IP address. Mapping from
809	 * name to IP address can be trusted better (but can still be
810	 * fooled if the intruder has access to the name server of
811	 * the domain).
812	 */
813	memset(&hints, 0, sizeof(hints));
814	hints.ai_family = from.ss_family;
815	hints.ai_socktype = SOCK_STREAM;
816	if (getaddrinfo(name, NULL, &hints, &aitop) != 0) {
817		logit("reverse mapping checking getaddrinfo for %.700s "
818		    "[%s] failed.", name, ntop);
819		return strdup(ntop);
820	}
821	/* Look for the address from the list of addresses. */
822	for (ai = aitop; ai; ai = ai->ai_next) {
823		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop2,
824		    sizeof(ntop2), NULL, 0, NI_NUMERICHOST) == 0 &&
825		    (strcmp(ntop, ntop2) == 0))
826				break;
827	}
828	freeaddrinfo(aitop);
829	/* If we reached the end of the list, the address was not there. */
830	if (ai == NULL) {
831		/* Address not found for the host name. */
832		logit("Address %.100s maps to %.600s, but this does not "
833		    "map back to the address.", ntop, name);
834		return strdup(ntop);
835	}
836	return strdup(name);
837}
838
839/*
840 * Return the canonical name of the host in the other side of the current
841 * connection.  The host name is cached, so it is efficient to call this
842 * several times.
843 */
844
845const char *
846auth_get_canonical_hostname(struct ssh *ssh, int use_dns)
847{
848	static char *dnsname;
849
850	if (!use_dns)
851		return ssh_remote_ipaddr(ssh);
852	else if (dnsname != NULL)
853		return dnsname;
854	else {
855		dnsname = remote_hostname(ssh);
856		return dnsname;
857	}
858}
859
860/*
861 * Runs command in a subprocess with a minimal environment.
862 * Returns pid on success, 0 on failure.
863 * The child stdout and stderr maybe captured, left attached or sent to
864 * /dev/null depending on the contents of flags.
865 * "tag" is prepended to log messages.
866 * NB. "command" is only used for logging; the actual command executed is
867 * av[0].
868 */
869pid_t
870subprocess(const char *tag, struct passwd *pw, const char *command,
871    int ac, char **av, FILE **child, u_int flags)
872{
873	FILE *f = NULL;
874	struct stat st;
875	int fd, devnull, p[2], i;
876	pid_t pid;
877	char *cp, errmsg[512];
878	u_int envsize;
879	char **child_env;
880
881	if (child != NULL)
882		*child = NULL;
883
884	debug3("%s: %s command \"%s\" running as %s (flags 0x%x)", __func__,
885	    tag, command, pw->pw_name, flags);
886
887	/* Check consistency */
888	if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
889	    (flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
890		error("%s: inconsistent flags", __func__);
891		return 0;
892	}
893	if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
894		error("%s: inconsistent flags/output", __func__);
895		return 0;
896	}
897
898	/*
899	 * If executing an explicit binary, then verify the it exists
900	 * and appears safe-ish to execute
901	 */
902	if (*av[0] != '/') {
903		error("%s path is not absolute", tag);
904		return 0;
905	}
906	temporarily_use_uid(pw);
907	if (stat(av[0], &st) < 0) {
908		error("Could not stat %s \"%s\": %s", tag,
909		    av[0], strerror(errno));
910		restore_uid();
911		return 0;
912	}
913	if (safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
914		error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
915		restore_uid();
916		return 0;
917	}
918	/* Prepare to keep the child's stdout if requested */
919	if (pipe(p) != 0) {
920		error("%s: pipe: %s", tag, strerror(errno));
921		restore_uid();
922		return 0;
923	}
924	restore_uid();
925
926	switch ((pid = fork())) {
927	case -1: /* error */
928		error("%s: fork: %s", tag, strerror(errno));
929		close(p[0]);
930		close(p[1]);
931		return 0;
932	case 0: /* child */
933		/* Prepare a minimal environment for the child. */
934		envsize = 5;
935		child_env = xcalloc(sizeof(*child_env), envsize);
936		child_set_env(&child_env, &envsize, "PATH", _PATH_STDPATH);
937		child_set_env(&child_env, &envsize, "USER", pw->pw_name);
938		child_set_env(&child_env, &envsize, "LOGNAME", pw->pw_name);
939		child_set_env(&child_env, &envsize, "HOME", pw->pw_dir);
940		if ((cp = getenv("LANG")) != NULL)
941			child_set_env(&child_env, &envsize, "LANG", cp);
942
943		for (i = 0; i < NSIG; i++)
944			signal(i, SIG_DFL);
945
946		if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
947			error("%s: open %s: %s", tag, _PATH_DEVNULL,
948			    strerror(errno));
949			_exit(1);
950		}
951		if (dup2(devnull, STDIN_FILENO) == -1) {
952			error("%s: dup2: %s", tag, strerror(errno));
953			_exit(1);
954		}
955
956		/* Set up stdout as requested; leave stderr in place for now. */
957		fd = -1;
958		if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
959			fd = p[1];
960		else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
961			fd = devnull;
962		if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
963			error("%s: dup2: %s", tag, strerror(errno));
964			_exit(1);
965		}
966		closefrom(STDERR_FILENO + 1);
967
968		/* Don't use permanently_set_uid() here to avoid fatal() */
969		if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) != 0) {
970			error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
971			    strerror(errno));
972			_exit(1);
973		}
974		if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) != 0) {
975			error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
976			    strerror(errno));
977			_exit(1);
978		}
979		/* stdin is pointed to /dev/null at this point */
980		if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
981		    dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
982			error("%s: dup2: %s", tag, strerror(errno));
983			_exit(1);
984		}
985
986		execve(av[0], av, child_env);
987		error("%s exec \"%s\": %s", tag, command, strerror(errno));
988		_exit(127);
989	default: /* parent */
990		break;
991	}
992
993	close(p[1]);
994	if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
995		close(p[0]);
996	else if ((f = fdopen(p[0], "r")) == NULL) {
997		error("%s: fdopen: %s", tag, strerror(errno));
998		close(p[0]);
999		/* Don't leave zombie child */
1000		kill(pid, SIGTERM);
1001		while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
1002			;
1003		return 0;
1004	}
1005	/* Success */
1006	debug3("%s: %s pid %ld", __func__, tag, (long)pid);
1007	if (child != NULL)
1008		*child = f;
1009	return pid;
1010}
1011
1012/* These functions link key/cert options to the auth framework */
1013
1014/* Log sshauthopt options locally and (optionally) for remote transmission */
1015void
1016auth_log_authopts(const char *loc, const struct sshauthopt *opts, int do_remote)
1017{
1018	int do_env = options.permit_user_env && opts->nenv > 0;
1019	int do_permitopen = opts->npermitopen > 0 &&
1020	    (options.allow_tcp_forwarding & FORWARD_LOCAL) != 0;
1021	int do_permitlisten = opts->npermitlisten > 0 &&
1022	    (options.allow_tcp_forwarding & FORWARD_REMOTE) != 0;
1023	size_t i;
1024	char msg[1024], buf[64];
1025
1026	snprintf(buf, sizeof(buf), "%d", opts->force_tun_device);
1027	/* Try to keep this alphabetically sorted */
1028	snprintf(msg, sizeof(msg), "key options:%s%s%s%s%s%s%s%s%s%s%s%s%s",
1029	    opts->permit_agent_forwarding_flag ? " agent-forwarding" : "",
1030	    opts->force_command == NULL ? "" : " command",
1031	    do_env ?  " environment" : "",
1032	    opts->valid_before == 0 ? "" : "expires",
1033	    do_permitopen ?  " permitopen" : "",
1034	    do_permitlisten ?  " permitlisten" : "",
1035	    opts->permit_port_forwarding_flag ? " port-forwarding" : "",
1036	    opts->cert_principals == NULL ? "" : " principals",
1037	    opts->permit_pty_flag ? " pty" : "",
1038	    opts->force_tun_device == -1 ? "" : " tun=",
1039	    opts->force_tun_device == -1 ? "" : buf,
1040	    opts->permit_user_rc ? " user-rc" : "",
1041	    opts->permit_x11_forwarding_flag ? " x11-forwarding" : "");
1042
1043	debug("%s: %s", loc, msg);
1044	if (do_remote)
1045		auth_debug_add("%s: %s", loc, msg);
1046
1047	if (options.permit_user_env) {
1048		for (i = 0; i < opts->nenv; i++) {
1049			debug("%s: environment: %s", loc, opts->env[i]);
1050			if (do_remote) {
1051				auth_debug_add("%s: environment: %s",
1052				    loc, opts->env[i]);
1053			}
1054		}
1055	}
1056
1057	/* Go into a little more details for the local logs. */
1058	if (opts->valid_before != 0) {
1059		format_absolute_time(opts->valid_before, buf, sizeof(buf));
1060		debug("%s: expires at %s", loc, buf);
1061	}
1062	if (opts->cert_principals != NULL) {
1063		debug("%s: authorized principals: \"%s\"",
1064		    loc, opts->cert_principals);
1065	}
1066	if (opts->force_command != NULL)
1067		debug("%s: forced command: \"%s\"", loc, opts->force_command);
1068	if (do_permitopen) {
1069		for (i = 0; i < opts->npermitopen; i++) {
1070			debug("%s: permitted open: %s",
1071			    loc, opts->permitopen[i]);
1072		}
1073	}
1074	if (do_permitlisten) {
1075		for (i = 0; i < opts->npermitlisten; i++) {
1076			debug("%s: permitted listen: %s",
1077			    loc, opts->permitlisten[i]);
1078		}
1079	}
1080}
1081
1082/* Activate a new set of key/cert options; merging with what is there. */
1083int
1084auth_activate_options(struct ssh *ssh, struct sshauthopt *opts)
1085{
1086	struct sshauthopt *old = auth_opts;
1087	const char *emsg = NULL;
1088
1089	debug("%s: setting new authentication options", __func__);
1090	if ((auth_opts = sshauthopt_merge(old, opts, &emsg)) == NULL) {
1091		error("Inconsistent authentication options: %s", emsg);
1092		return -1;
1093	}
1094	return 0;
1095}
1096
1097/* Disable forwarding, etc for the session */
1098void
1099auth_restrict_session(struct ssh *ssh)
1100{
1101	struct sshauthopt *restricted;
1102
1103	debug("%s: restricting session", __func__);
1104
1105	/* A blank sshauthopt defaults to permitting nothing */
1106	restricted = sshauthopt_new();
1107	restricted->permit_pty_flag = 1;
1108	restricted->restricted = 1;
1109
1110	if (auth_activate_options(ssh, restricted) != 0)
1111		fatal("%s: failed to restrict session", __func__);
1112	sshauthopt_free(restricted);
1113}
1114
1115int
1116auth_authorise_keyopts(struct ssh *ssh, struct passwd *pw,
1117    struct sshauthopt *opts, int allow_cert_authority, const char *loc)
1118{
1119	const char *remote_ip = ssh_remote_ipaddr(ssh);
1120	const char *remote_host = auth_get_canonical_hostname(ssh,
1121	    options.use_dns);
1122	time_t now = time(NULL);
1123	char buf[64];
1124
1125	/*
1126	 * Check keys/principals file expiry time.
1127	 * NB. validity interval in certificate is handled elsewhere.
1128	 */
1129	if (opts->valid_before && now > 0 &&
1130	    opts->valid_before < (uint64_t)now) {
1131		format_absolute_time(opts->valid_before, buf, sizeof(buf));
1132		debug("%s: entry expired at %s", loc, buf);
1133		auth_debug_add("%s: entry expired at %s", loc, buf);
1134		return -1;
1135	}
1136	/* Consistency checks */
1137	if (opts->cert_principals != NULL && !opts->cert_authority) {
1138		debug("%s: principals on non-CA key", loc);
1139		auth_debug_add("%s: principals on non-CA key", loc);
1140		/* deny access */
1141		return -1;
1142	}
1143	/* cert-authority flag isn't valid in authorized_principals files */
1144	if (!allow_cert_authority && opts->cert_authority) {
1145		debug("%s: cert-authority flag invalid here", loc);
1146		auth_debug_add("%s: cert-authority flag invalid here", loc);
1147		/* deny access */
1148		return -1;
1149	}
1150
1151	/* Perform from= checks */
1152	if (opts->required_from_host_keys != NULL) {
1153		switch (match_host_and_ip(remote_host, remote_ip,
1154		    opts->required_from_host_keys )) {
1155		case 1:
1156			/* Host name matches. */
1157			break;
1158		case -1:
1159		default:
1160			debug("%s: invalid from criteria", loc);
1161			auth_debug_add("%s: invalid from criteria", loc);
1162			/* FALLTHROUGH */
1163		case 0:
1164			logit("%s: Authentication tried for %.100s with "
1165			    "correct key but not from a permitted "
1166			    "host (host=%.200s, ip=%.200s, required=%.200s).",
1167			    loc, pw->pw_name, remote_host, remote_ip,
1168			    opts->required_from_host_keys);
1169			auth_debug_add("%s: Your host '%.200s' is not "
1170			    "permitted to use this key for login.",
1171			    loc, remote_host);
1172			/* deny access */
1173			return -1;
1174		}
1175	}
1176	/* Check source-address restriction from certificate */
1177	if (opts->required_from_host_cert != NULL) {
1178		switch (addr_match_cidr_list(remote_ip,
1179		    opts->required_from_host_cert)) {
1180		case 1:
1181			/* accepted */
1182			break;
1183		case -1:
1184		default:
1185			/* invalid */
1186			error("%s: Certificate source-address invalid",
1187			    loc);
1188			/* FALLTHROUGH */
1189		case 0:
1190			logit("%s: Authentication tried for %.100s with valid "
1191			    "certificate but not from a permitted source "
1192			    "address (%.200s).", loc, pw->pw_name, remote_ip);
1193			auth_debug_add("%s: Your address '%.200s' is not "
1194			    "permitted to use this certificate for login.",
1195			    loc, remote_ip);
1196			return -1;
1197		}
1198	}
1199	/*
1200	 *
1201	 * XXX this is spammy. We should report remotely only for keys
1202	 *     that are successful in actual auth attempts, and not PK_OK
1203	 *     tests.
1204	 */
1205	auth_log_authopts(loc, opts, 1);
1206
1207	return 0;
1208}
1209