auth.c revision 98684
1/*
2 * Copyright (c) 2000 Markus Friedl.  All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 */
24
25#include "includes.h"
26RCSID("$OpenBSD: auth.c,v 1.43 2002/05/17 14:27:55 millert Exp $");
27RCSID("$FreeBSD: head/crypto/openssh/auth.c 98684 2002-06-23 16:09:08Z des $");
28
29#include <libgen.h>
30
31#include "xmalloc.h"
32#include "match.h"
33#include "groupaccess.h"
34#include "log.h"
35#include "servconf.h"
36#include "auth.h"
37#include "auth-options.h"
38#include "canohost.h"
39#include "buffer.h"
40#include "bufaux.h"
41#include "uidswap.h"
42#include "tildexpand.h"
43#include "misc.h"
44#include "bufaux.h"
45#include "packet.h"
46
47/* import */
48extern ServerOptions options;
49
50/* Debugging messages */
51Buffer auth_debug;
52int auth_debug_init;
53
54/*
55 * Check if the user is allowed to log in via ssh. If user is listed
56 * in DenyUsers or one of user's groups is listed in DenyGroups, false
57 * will be returned. If AllowUsers isn't empty and user isn't listed
58 * there, or if AllowGroups isn't empty and one of user's groups isn't
59 * listed there, false will be returned.
60 * If the user's shell is not executable, false will be returned.
61 * Otherwise true is returned.
62 */
63int
64allowed_user(struct passwd * pw)
65{
66	struct stat st;
67	const char *hostname = NULL, *ipaddr = NULL;
68	char *shell;
69	int i;
70
71	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
72	if (!pw || !pw->pw_name)
73		return 0;
74
75	/*
76	 * Get the shell from the password data.  An empty shell field is
77	 * legal, and means /bin/sh.
78	 */
79	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
80
81	/* deny if shell does not exists or is not executable */
82	if (stat(shell, &st) != 0) {
83		log("User %.100s not allowed because shell %.100s does not exist",
84		    pw->pw_name, shell);
85		return 0;
86	}
87	if (S_ISREG(st.st_mode) == 0 ||
88	    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
89		log("User %.100s not allowed because shell %.100s is not executable",
90		    pw->pw_name, shell);
91		return 0;
92	}
93
94	if (options.num_deny_users > 0 || options.num_allow_users > 0) {
95		hostname = get_canonical_hostname(options.verify_reverse_mapping);
96		ipaddr = get_remote_ipaddr();
97	}
98
99	/* Return false if user is listed in DenyUsers */
100	if (options.num_deny_users > 0) {
101		for (i = 0; i < options.num_deny_users; i++)
102			if (match_user(pw->pw_name, hostname, ipaddr,
103			    options.deny_users[i])) {
104				log("User %.100s not allowed because listed in DenyUsers",
105				    pw->pw_name);
106				return 0;
107			}
108	}
109	/* Return false if AllowUsers isn't empty and user isn't listed there */
110	if (options.num_allow_users > 0) {
111		for (i = 0; i < options.num_allow_users; i++)
112			if (match_user(pw->pw_name, hostname, ipaddr,
113			    options.allow_users[i]))
114				break;
115		/* i < options.num_allow_users iff we break for loop */
116		if (i >= options.num_allow_users) {
117			log("User %.100s not allowed because not listed in AllowUsers",
118			    pw->pw_name);
119			return 0;
120		}
121	}
122	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
123		/* Get the user's group access list (primary and supplementary) */
124		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
125			log("User %.100s not allowed because not in any group",
126			    pw->pw_name);
127			return 0;
128		}
129
130		/* Return false if one of user's groups is listed in DenyGroups */
131		if (options.num_deny_groups > 0)
132			if (ga_match(options.deny_groups,
133			    options.num_deny_groups)) {
134				ga_free();
135				log("User %.100s not allowed because a group is listed in DenyGroups",
136				    pw->pw_name);
137				return 0;
138			}
139		/*
140		 * Return false if AllowGroups isn't empty and one of user's groups
141		 * isn't listed there
142		 */
143		if (options.num_allow_groups > 0)
144			if (!ga_match(options.allow_groups,
145			    options.num_allow_groups)) {
146				ga_free();
147				log("User %.100s not allowed because none of user's groups are listed in AllowGroups",
148				    pw->pw_name);
149				return 0;
150			}
151		ga_free();
152	}
153	/* We found no reason not to let this user try to log on... */
154	return 1;
155}
156
157Authctxt *
158authctxt_new(void)
159{
160	Authctxt *authctxt = xmalloc(sizeof(*authctxt));
161	memset(authctxt, 0, sizeof(*authctxt));
162	return authctxt;
163}
164
165void
166auth_log(Authctxt *authctxt, int authenticated, char *method, char *info)
167{
168	void (*authlog) (const char *fmt,...) = verbose;
169	char *authmsg;
170
171	/* Raise logging level */
172	if (authenticated == 1 ||
173	    !authctxt->valid ||
174	    authctxt->failures >= AUTH_FAIL_LOG ||
175	    strcmp(method, "password") == 0)
176		authlog = log;
177
178	if (authctxt->postponed)
179		authmsg = "Postponed";
180	else
181		authmsg = authenticated ? "Accepted" : "Failed";
182
183	authlog("%s %s for %s%.100s from %.200s port %d%s",
184	    authmsg,
185	    method,
186	    authctxt->valid ? "" : "illegal user ",
187	    authctxt->user,
188	    get_remote_ipaddr(),
189	    get_remote_port(),
190	    info);
191}
192
193/*
194 * Check whether root logins are disallowed.
195 */
196int
197auth_root_allowed(char *method)
198{
199	switch (options.permit_root_login) {
200	case PERMIT_YES:
201		return 1;
202		break;
203	case PERMIT_NO_PASSWD:
204		if (strcmp(method, "password") != 0)
205			return 1;
206		break;
207	case PERMIT_FORCED_ONLY:
208		if (forced_command) {
209			log("Root login accepted for forced command.");
210			return 1;
211		}
212		break;
213	}
214	log("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr());
215	return 0;
216}
217
218
219/*
220 * Given a template and a passwd structure, build a filename
221 * by substituting % tokenised options. Currently, %% becomes '%',
222 * %h becomes the home directory and %u the username.
223 *
224 * This returns a buffer allocated by xmalloc.
225 */
226char *
227expand_filename(const char *filename, struct passwd *pw)
228{
229	Buffer buffer;
230	char *file;
231	const char *cp;
232
233	/*
234	 * Build the filename string in the buffer by making the appropriate
235	 * substitutions to the given file name.
236	 */
237	buffer_init(&buffer);
238	for (cp = filename; *cp; cp++) {
239		if (cp[0] == '%' && cp[1] == '%') {
240			buffer_append(&buffer, "%", 1);
241			cp++;
242			continue;
243		}
244		if (cp[0] == '%' && cp[1] == 'h') {
245			buffer_append(&buffer, pw->pw_dir, strlen(pw->pw_dir));
246			cp++;
247			continue;
248		}
249		if (cp[0] == '%' && cp[1] == 'u') {
250			buffer_append(&buffer, pw->pw_name,
251			    strlen(pw->pw_name));
252			cp++;
253			continue;
254		}
255		buffer_append(&buffer, cp, 1);
256	}
257	buffer_append(&buffer, "\0", 1);
258
259	/*
260	 * Ensure that filename starts anchored. If not, be backward
261	 * compatible and prepend the '%h/'
262	 */
263	file = xmalloc(MAXPATHLEN);
264	cp = buffer_ptr(&buffer);
265	if (*cp != '/')
266		snprintf(file, MAXPATHLEN, "%s/%s", pw->pw_dir, cp);
267	else
268		strlcpy(file, cp, MAXPATHLEN);
269
270	buffer_free(&buffer);
271	return file;
272}
273
274char *
275authorized_keys_file(struct passwd *pw)
276{
277	return expand_filename(options.authorized_keys_file, pw);
278}
279
280char *
281authorized_keys_file2(struct passwd *pw)
282{
283	return expand_filename(options.authorized_keys_file2, pw);
284}
285
286/* return ok if key exists in sysfile or userfile */
287HostStatus
288check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
289    const char *sysfile, const char *userfile)
290{
291	Key *found;
292	char *user_hostfile;
293	struct stat st;
294	HostStatus host_status;
295
296	/* Check if we know the host and its host key. */
297	found = key_new(key->type);
298	host_status = check_host_in_hostfile(sysfile, host, key, found, NULL);
299
300	if (host_status != HOST_OK && userfile != NULL) {
301		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
302		if (options.strict_modes &&
303		    (stat(user_hostfile, &st) == 0) &&
304		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
305		    (st.st_mode & 022) != 0)) {
306			log("Authentication refused for %.100s: "
307			    "bad owner or modes for %.200s",
308			    pw->pw_name, user_hostfile);
309		} else {
310			temporarily_use_uid(pw);
311			host_status = check_host_in_hostfile(user_hostfile,
312			    host, key, found, NULL);
313			restore_uid();
314		}
315		xfree(user_hostfile);
316	}
317	key_free(found);
318
319	debug2("check_key_in_hostfiles: key %s for %s", host_status == HOST_OK ?
320	    "ok" : "not found", host);
321	return host_status;
322}
323
324
325/*
326 * Check a given file for security. This is defined as all components
327 * of the path to the file must either be owned by either the owner of
328 * of the file or root and no directories must be group or world writable.
329 *
330 * XXX Should any specific check be done for sym links ?
331 *
332 * Takes an open file descriptor, the file name, a uid and and
333 * error buffer plus max size as arguments.
334 *
335 * Returns 0 on success and -1 on failure
336 */
337int
338secure_filename(FILE *f, const char *file, struct passwd *pw,
339    char *err, size_t errlen)
340{
341	uid_t uid = pw->pw_uid;
342	char buf[MAXPATHLEN], homedir[MAXPATHLEN];
343	char *cp;
344	struct stat st;
345
346	if (realpath(file, buf) == NULL) {
347		snprintf(err, errlen, "realpath %s failed: %s", file,
348		    strerror(errno));
349		return -1;
350	}
351	if (realpath(pw->pw_dir, homedir) == NULL) {
352		snprintf(err, errlen, "realpath %s failed: %s", pw->pw_dir,
353		    strerror(errno));
354		return -1;
355	}
356
357	/* check the open file to avoid races */
358	if (fstat(fileno(f), &st) < 0 ||
359	    (st.st_uid != 0 && st.st_uid != uid) ||
360	    (st.st_mode & 022) != 0) {
361		snprintf(err, errlen, "bad ownership or modes for file %s",
362		    buf);
363		return -1;
364	}
365
366	/* for each component of the canonical path, walking upwards */
367	for (;;) {
368		if ((cp = dirname(buf)) == NULL) {
369			snprintf(err, errlen, "dirname() failed");
370			return -1;
371		}
372		strlcpy(buf, cp, sizeof(buf));
373
374		debug3("secure_filename: checking '%s'", buf);
375		if (stat(buf, &st) < 0 ||
376		    (st.st_uid != 0 && st.st_uid != uid) ||
377		    (st.st_mode & 022) != 0) {
378			snprintf(err, errlen,
379			    "bad ownership or modes for directory %s", buf);
380			return -1;
381		}
382
383		/* If are passed the homedir then we can stop */
384		if (strcmp(homedir, buf) == 0) {
385			debug3("secure_filename: terminating check at '%s'",
386			    buf);
387			break;
388		}
389		/*
390		 * dirname should always complete with a "/" path,
391		 * but we can be paranoid and check for "." too
392		 */
393		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
394			break;
395	}
396	return 0;
397}
398
399struct passwd *
400getpwnamallow(const char *user)
401{
402#ifdef HAVE_LOGIN_CAP
403	extern login_cap_t *lc;
404#ifdef BSD_AUTH
405	auth_session_t *as;
406#endif
407#endif
408	struct passwd *pw;
409
410	pw = getpwnam(user);
411	if (pw == NULL || !allowed_user(pw))
412		return (NULL);
413#ifdef HAVE_LOGIN_CAP
414	if ((lc = login_getclass(pw->pw_class)) == NULL) {
415		debug("unable to get login class: %s", user);
416		return (NULL);
417	}
418#ifdef BSD_AUTH
419	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
420	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
421		debug("Approval failure for %s", user);
422		pw = NULL;
423	}
424	if (as != NULL)
425		auth_close(as);
426#endif
427#endif
428	if (pw != NULL)
429		return (pwcopy(pw));
430	return (NULL);
431}
432
433void
434auth_debug_add(const char *fmt,...)
435{
436	char buf[1024];
437	va_list args;
438
439	if (!auth_debug_init)
440		return;
441
442	va_start(args, fmt);
443	vsnprintf(buf, sizeof(buf), fmt, args);
444	va_end(args);
445	buffer_put_cstring(&auth_debug, buf);
446}
447
448void
449auth_debug_send(void)
450{
451	char *msg;
452
453	if (!auth_debug_init)
454		return;
455	while (buffer_len(&auth_debug)) {
456		msg = buffer_get_string(&auth_debug, NULL);
457		packet_send_debug("%s", msg);
458		xfree(msg);
459	}
460}
461
462void
463auth_debug_reset(void)
464{
465	if (auth_debug_init)
466		buffer_clear(&auth_debug);
467	else {
468		buffer_init(&auth_debug);
469		auth_debug_init = 1;
470	}
471}
472