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