auth.c revision 126277
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.51 2003/11/21 11:57:02 djm Exp $");
27RCSID("$FreeBSD: head/crypto/openssh/auth.c 126277 2004-02-26 10:52:33Z des $");
28
29#ifdef HAVE_LOGIN_H
30#include <login.h>
31#endif
32#ifdef USE_SHADOW
33#include <shadow.h>
34#endif
35
36#ifdef HAVE_LIBGEN_H
37#include <libgen.h>
38#endif
39
40#include "xmalloc.h"
41#include "match.h"
42#include "groupaccess.h"
43#include "log.h"
44#include "servconf.h"
45#include "auth.h"
46#include "auth-options.h"
47#include "canohost.h"
48#include "buffer.h"
49#include "bufaux.h"
50#include "uidswap.h"
51#include "tildexpand.h"
52#include "misc.h"
53#include "bufaux.h"
54#include "packet.h"
55
56/* import */
57extern ServerOptions options;
58extern Buffer loginmsg;
59
60/* Debugging messages */
61Buffer auth_debug;
62int auth_debug_init;
63
64/*
65 * Check if the user is allowed to log in via ssh. If user is listed
66 * in DenyUsers or one of user's groups is listed in DenyGroups, false
67 * will be returned. If AllowUsers isn't empty and user isn't listed
68 * there, or if AllowGroups isn't empty and one of user's groups isn't
69 * listed there, false will be returned.
70 * If the user's shell is not executable, false will be returned.
71 * Otherwise true is returned.
72 */
73int
74allowed_user(struct passwd * pw)
75{
76	struct stat st;
77	const char *hostname = NULL, *ipaddr = NULL, *passwd = NULL;
78	char *shell;
79	int i;
80#ifdef USE_SHADOW
81	struct spwd *spw = NULL;
82#endif
83
84	/* Shouldn't be called if pw is NULL, but better safe than sorry... */
85	if (!pw || !pw->pw_name)
86		return 0;
87
88#ifdef USE_SHADOW
89	if (!options.use_pam)
90		spw = getspnam(pw->pw_name);
91#ifdef HAS_SHADOW_EXPIRE
92	if (!options.use_pam && spw != NULL && auth_shadow_acctexpired(spw))
93		return 0;
94#endif /* HAS_SHADOW_EXPIRE */
95#endif /* USE_SHADOW */
96
97	/* grab passwd field for locked account check */
98#ifdef USE_SHADOW
99	if (spw != NULL)
100		passwd = spw->sp_pwdp;
101#else
102	passwd = pw->pw_passwd;
103#endif
104
105	/* check for locked account */
106	if (!options.use_pam && passwd && *passwd) {
107		int locked = 0;
108
109#ifdef LOCKED_PASSWD_STRING
110		if (strcmp(passwd, LOCKED_PASSWD_STRING) == 0)
111			 locked = 1;
112#endif
113#ifdef LOCKED_PASSWD_PREFIX
114		if (strncmp(passwd, LOCKED_PASSWD_PREFIX,
115		    strlen(LOCKED_PASSWD_PREFIX)) == 0)
116			 locked = 1;
117#endif
118#ifdef LOCKED_PASSWD_SUBSTR
119		if (strstr(passwd, LOCKED_PASSWD_SUBSTR))
120			locked = 1;
121#endif
122		if (locked) {
123			logit("User %.100s not allowed because account is locked",
124			    pw->pw_name);
125			return 0;
126		}
127	}
128
129	/*
130	 * Get the shell from the password data.  An empty shell field is
131	 * legal, and means /bin/sh.
132	 */
133	shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
134
135	/* deny if shell does not exists or is not executable */
136	if (stat(shell, &st) != 0) {
137		logit("User %.100s not allowed because shell %.100s does not exist",
138		    pw->pw_name, shell);
139		return 0;
140	}
141	if (S_ISREG(st.st_mode) == 0 ||
142	    (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
143		logit("User %.100s not allowed because shell %.100s is not executable",
144		    pw->pw_name, shell);
145		return 0;
146	}
147
148	if (options.num_deny_users > 0 || options.num_allow_users > 0) {
149		hostname = get_canonical_hostname(options.use_dns);
150		ipaddr = get_remote_ipaddr();
151	}
152
153	/* Return false if user is listed in DenyUsers */
154	if (options.num_deny_users > 0) {
155		for (i = 0; i < options.num_deny_users; i++)
156			if (match_user(pw->pw_name, hostname, ipaddr,
157			    options.deny_users[i])) {
158				logit("User %.100s not allowed because listed in DenyUsers",
159				    pw->pw_name);
160				return 0;
161			}
162	}
163	/* Return false if AllowUsers isn't empty and user isn't listed there */
164	if (options.num_allow_users > 0) {
165		for (i = 0; i < options.num_allow_users; i++)
166			if (match_user(pw->pw_name, hostname, ipaddr,
167			    options.allow_users[i]))
168				break;
169		/* i < options.num_allow_users iff we break for loop */
170		if (i >= options.num_allow_users) {
171			logit("User %.100s not allowed because not listed in AllowUsers",
172			    pw->pw_name);
173			return 0;
174		}
175	}
176	if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
177		/* Get the user's group access list (primary and supplementary) */
178		if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
179			logit("User %.100s not allowed because not in any group",
180			    pw->pw_name);
181			return 0;
182		}
183
184		/* Return false if one of user's groups is listed in DenyGroups */
185		if (options.num_deny_groups > 0)
186			if (ga_match(options.deny_groups,
187			    options.num_deny_groups)) {
188				ga_free();
189				logit("User %.100s not allowed because a group is listed in DenyGroups",
190				    pw->pw_name);
191				return 0;
192			}
193		/*
194		 * Return false if AllowGroups isn't empty and one of user's groups
195		 * isn't listed there
196		 */
197		if (options.num_allow_groups > 0)
198			if (!ga_match(options.allow_groups,
199			    options.num_allow_groups)) {
200				ga_free();
201				logit("User %.100s not allowed because none of user's groups are listed in AllowGroups",
202				    pw->pw_name);
203				return 0;
204			}
205		ga_free();
206	}
207
208#ifdef WITH_AIXAUTHENTICATE
209	/*
210	 * Don't check loginrestrictions() for root account (use
211	 * PermitRootLogin to control logins via ssh), or if running as
212	 * non-root user (since loginrestrictions will always fail).
213	 */
214	if ((pw->pw_uid != 0) && (geteuid() == 0)) {
215		char *msg;
216
217		if (loginrestrictions(pw->pw_name, S_RLOGIN, NULL, &msg) != 0) {
218			int loginrestrict_errno = errno;
219
220			if (msg && *msg) {
221				buffer_append(&loginmsg, msg, strlen(msg));
222				aix_remove_embedded_newlines(msg);
223				logit("Login restricted for %s: %.100s",
224				    pw->pw_name, msg);
225			}
226			/* Don't fail if /etc/nologin  set */
227			if (!(loginrestrict_errno == EPERM &&
228			    stat(_PATH_NOLOGIN, &st) == 0))
229				return 0;
230		}
231	}
232#endif /* WITH_AIXAUTHENTICATE */
233
234	/* We found no reason not to let this user try to log on... */
235	return 1;
236}
237
238void
239auth_log(Authctxt *authctxt, int authenticated, char *method, char *info)
240{
241	void (*authlog) (const char *fmt,...) = verbose;
242	char *authmsg;
243
244	/* Raise logging level */
245	if (authenticated == 1 ||
246	    !authctxt->valid ||
247	    authctxt->failures >= AUTH_FAIL_LOG ||
248	    strcmp(method, "password") == 0)
249		authlog = logit;
250
251	if (authctxt->postponed)
252		authmsg = "Postponed";
253	else
254		authmsg = authenticated ? "Accepted" : "Failed";
255
256	authlog("%s %s for %s%.100s from %.200s port %d%s",
257	    authmsg,
258	    method,
259	    authctxt->valid ? "" : "illegal user ",
260	    authctxt->user,
261	    get_remote_ipaddr(),
262	    get_remote_port(),
263	    info);
264
265#ifdef CUSTOM_FAILED_LOGIN
266	if (authenticated == 0 && strcmp(method, "password") == 0)
267		record_failed_login(authctxt->user, "ssh");
268#endif
269}
270
271/*
272 * Check whether root logins are disallowed.
273 */
274int
275auth_root_allowed(char *method)
276{
277	switch (options.permit_root_login) {
278	case PERMIT_YES:
279		return 1;
280		break;
281	case PERMIT_NO_PASSWD:
282		if (strcmp(method, "password") != 0)
283			return 1;
284		break;
285	case PERMIT_FORCED_ONLY:
286		if (forced_command) {
287			logit("Root login accepted for forced command.");
288			return 1;
289		}
290		break;
291	}
292	logit("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr());
293	return 0;
294}
295
296
297/*
298 * Given a template and a passwd structure, build a filename
299 * by substituting % tokenised options. Currently, %% becomes '%',
300 * %h becomes the home directory and %u the username.
301 *
302 * This returns a buffer allocated by xmalloc.
303 */
304char *
305expand_filename(const char *filename, struct passwd *pw)
306{
307	Buffer buffer;
308	char *file;
309	const char *cp;
310
311	/*
312	 * Build the filename string in the buffer by making the appropriate
313	 * substitutions to the given file name.
314	 */
315	buffer_init(&buffer);
316	for (cp = filename; *cp; cp++) {
317		if (cp[0] == '%' && cp[1] == '%') {
318			buffer_append(&buffer, "%", 1);
319			cp++;
320			continue;
321		}
322		if (cp[0] == '%' && cp[1] == 'h') {
323			buffer_append(&buffer, pw->pw_dir, strlen(pw->pw_dir));
324			cp++;
325			continue;
326		}
327		if (cp[0] == '%' && cp[1] == 'u') {
328			buffer_append(&buffer, pw->pw_name,
329			    strlen(pw->pw_name));
330			cp++;
331			continue;
332		}
333		buffer_append(&buffer, cp, 1);
334	}
335	buffer_append(&buffer, "\0", 1);
336
337	/*
338	 * Ensure that filename starts anchored. If not, be backward
339	 * compatible and prepend the '%h/'
340	 */
341	file = xmalloc(MAXPATHLEN);
342	cp = buffer_ptr(&buffer);
343	if (*cp != '/')
344		snprintf(file, MAXPATHLEN, "%s/%s", pw->pw_dir, cp);
345	else
346		strlcpy(file, cp, MAXPATHLEN);
347
348	buffer_free(&buffer);
349	return file;
350}
351
352char *
353authorized_keys_file(struct passwd *pw)
354{
355	return expand_filename(options.authorized_keys_file, pw);
356}
357
358char *
359authorized_keys_file2(struct passwd *pw)
360{
361	return expand_filename(options.authorized_keys_file2, pw);
362}
363
364/* return ok if key exists in sysfile or userfile */
365HostStatus
366check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
367    const char *sysfile, const char *userfile)
368{
369	Key *found;
370	char *user_hostfile;
371	struct stat st;
372	HostStatus host_status;
373
374	/* Check if we know the host and its host key. */
375	found = key_new(key->type);
376	host_status = check_host_in_hostfile(sysfile, host, key, found, NULL);
377
378	if (host_status != HOST_OK && userfile != NULL) {
379		user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
380		if (options.strict_modes &&
381		    (stat(user_hostfile, &st) == 0) &&
382		    ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
383		    (st.st_mode & 022) != 0)) {
384			logit("Authentication refused for %.100s: "
385			    "bad owner or modes for %.200s",
386			    pw->pw_name, user_hostfile);
387		} else {
388			temporarily_use_uid(pw);
389			host_status = check_host_in_hostfile(user_hostfile,
390			    host, key, found, NULL);
391			restore_uid();
392		}
393		xfree(user_hostfile);
394	}
395	key_free(found);
396
397	debug2("check_key_in_hostfiles: key %s for %s", host_status == HOST_OK ?
398	    "ok" : "not found", host);
399	return host_status;
400}
401
402
403/*
404 * Check a given file for security. This is defined as all components
405 * of the path to the file must be owned by either the owner of
406 * of the file or root and no directories must be group or world writable.
407 *
408 * XXX Should any specific check be done for sym links ?
409 *
410 * Takes an open file descriptor, the file name, a uid and and
411 * error buffer plus max size as arguments.
412 *
413 * Returns 0 on success and -1 on failure
414 */
415int
416secure_filename(FILE *f, const char *file, struct passwd *pw,
417    char *err, size_t errlen)
418{
419	uid_t uid = pw->pw_uid;
420	char buf[MAXPATHLEN], homedir[MAXPATHLEN];
421	char *cp;
422	int comparehome = 0;
423	struct stat st;
424
425	if (realpath(file, buf) == NULL) {
426		snprintf(err, errlen, "realpath %s failed: %s", file,
427		    strerror(errno));
428		return -1;
429	}
430	if (realpath(pw->pw_dir, homedir) != NULL)
431		comparehome = 1;
432
433	/* check the open file to avoid races */
434	if (fstat(fileno(f), &st) < 0 ||
435	    (st.st_uid != 0 && st.st_uid != uid) ||
436	    (st.st_mode & 022) != 0) {
437		snprintf(err, errlen, "bad ownership or modes for file %s",
438		    buf);
439		return -1;
440	}
441
442	/* for each component of the canonical path, walking upwards */
443	for (;;) {
444		if ((cp = dirname(buf)) == NULL) {
445			snprintf(err, errlen, "dirname() failed");
446			return -1;
447		}
448		strlcpy(buf, cp, sizeof(buf));
449
450		debug3("secure_filename: checking '%s'", buf);
451		if (stat(buf, &st) < 0 ||
452		    (st.st_uid != 0 && st.st_uid != uid) ||
453		    (st.st_mode & 022) != 0) {
454			snprintf(err, errlen,
455			    "bad ownership or modes for directory %s", buf);
456			return -1;
457		}
458
459		/* If are passed the homedir then we can stop */
460		if (comparehome && strcmp(homedir, buf) == 0) {
461			debug3("secure_filename: terminating check at '%s'",
462			    buf);
463			break;
464		}
465		/*
466		 * dirname should always complete with a "/" path,
467		 * but we can be paranoid and check for "." too
468		 */
469		if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
470			break;
471	}
472	return 0;
473}
474
475struct passwd *
476getpwnamallow(const char *user)
477{
478#ifdef HAVE_LOGIN_CAP
479	extern login_cap_t *lc;
480#ifdef BSD_AUTH
481	auth_session_t *as;
482#endif
483#endif
484	struct passwd *pw;
485
486	pw = getpwnam(user);
487	if (pw == NULL) {
488		logit("Illegal user %.100s from %.100s",
489		    user, get_remote_ipaddr());
490#ifdef CUSTOM_FAILED_LOGIN
491		record_failed_login(user, "ssh");
492#endif
493		return (NULL);
494	}
495	if (!allowed_user(pw))
496		return (NULL);
497#ifdef HAVE_LOGIN_CAP
498	if ((lc = login_getpwclass(pw)) == NULL) {
499		debug("unable to get login class: %s", user);
500		return (NULL);
501	}
502#ifdef BSD_AUTH
503	if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
504	    auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
505		debug("Approval failure for %s", user);
506		pw = NULL;
507	}
508	if (as != NULL)
509		auth_close(as);
510#endif
511#endif
512	if (pw != NULL)
513		return (pwcopy(pw));
514	return (NULL);
515}
516
517void
518auth_debug_add(const char *fmt,...)
519{
520	char buf[1024];
521	va_list args;
522
523	if (!auth_debug_init)
524		return;
525
526	va_start(args, fmt);
527	vsnprintf(buf, sizeof(buf), fmt, args);
528	va_end(args);
529	buffer_put_cstring(&auth_debug, buf);
530}
531
532void
533auth_debug_send(void)
534{
535	char *msg;
536
537	if (!auth_debug_init)
538		return;
539	while (buffer_len(&auth_debug)) {
540		msg = buffer_get_string(&auth_debug, NULL);
541		packet_send_debug("%s", msg);
542		xfree(msg);
543	}
544}
545
546void
547auth_debug_reset(void)
548{
549	if (auth_debug_init)
550		buffer_clear(&auth_debug);
551	else {
552		buffer_init(&auth_debug);
553		auth_debug_init = 1;
554	}
555}
556
557struct passwd *
558fakepw(void)
559{
560	static struct passwd fake;
561
562	memset(&fake, 0, sizeof(fake));
563	fake.pw_name = "NOUSER";
564	fake.pw_passwd =
565	    "$2a$06$r3.juUaHZDlIbQaO2dS9FuYxL1W9M81R1Tc92PoSNmzvpEqLkLGrK";
566	fake.pw_gecos = "NOUSER";
567	fake.pw_uid = -1;
568	fake.pw_gid = -1;
569#ifdef HAVE_PW_CLASS_IN_PASSWD
570	fake.pw_class = "";
571#endif
572	fake.pw_dir = "/nonexist";
573	fake.pw_shell = "/nonexist";
574
575	return (&fake);
576}
577