2 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
26 RCSID("$OpenBSD: auth.c,v 1.46 2002/11/04 10:07:53 markus Exp $");
31 #if defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW)
33 #endif /* defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW) */
41 #include "groupaccess.h"
45 #include "auth-options.h"
50 #include "tildexpand.h"
56 extern ServerOptions options;
58 /* Debugging messages */
63 * Check if the user is allowed to log in via ssh. If user is listed
64 * in DenyUsers or one of user's groups is listed in DenyGroups, false
65 * will be returned. If AllowUsers isn't empty and user isn't listed
66 * there, or if AllowGroups isn't empty and one of user's groups isn't
67 * listed there, false will be returned.
68 * If the user's shell is not executable, false will be returned.
69 * Otherwise true is returned.
72 allowed_user(struct passwd * pw)
75 const char *hostname = NULL, *ipaddr = NULL, *passwd;
78 #ifdef WITH_AIXAUTHENTICATE
80 #endif /* WITH_AIXAUTHENTICATE */
81 #if defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW)
83 #if !defined(USE_PAM) && defined(HAS_SHADOW_EXPIRE)
88 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
89 if (!pw || !pw->pw_name)
92 /* Grab the password for locked account checking */
93 #if defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW)
94 spw = getspnam(pw->pw_name);
97 passwd = spw->sp_pwdp;
99 passwd = pw->pw_passwd;
102 /* check for locked account */
103 if (strcmp(passwd, "*LK*") == 0 || passwd[0] == '!') {
104 log("User %.100s not allowed because account is locked",
109 #if !defined(USE_PAM) && defined(HAVE_SHADOW_H) && \
110 !defined(DISABLE_SHADOW) && defined(HAS_SHADOW_EXPIRE)
111 #define DAY (24L * 60 * 60) /* 1 day in seconds */
112 today = time(NULL) / DAY;
113 debug3("allowed_user: today %d sp_expire %d sp_lstchg %d"
114 " sp_max %d", (int)today, (int)spw->sp_expire,
115 (int)spw->sp_lstchg, (int)spw->sp_max);
118 * We assume account and password expiration occurs the
119 * day after the day specified.
121 if (spw->sp_expire != -1 && today > spw->sp_expire) {
122 log("Account %.100s has expired", pw->pw_name);
126 if (spw->sp_lstchg == 0) {
127 log("User %.100s password has expired (root forced)",
132 if (spw->sp_max != -1 &&
133 today > spw->sp_lstchg + spw->sp_max) {
134 log("User %.100s password has expired (password aged)",
141 * Get the shell from the password data. An empty shell field is
142 * legal, and means /bin/sh.
144 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
146 /* deny if shell does not exists or is not executable */
147 if (stat(shell, &st) != 0) {
148 log("User %.100s not allowed because shell %.100s does not exist",
152 if (S_ISREG(st.st_mode) == 0 ||
153 (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)) == 0) {
154 log("User %.100s not allowed because shell %.100s is not executable",
159 if (options.num_deny_users > 0 || options.num_allow_users > 0) {
160 hostname = get_canonical_hostname(options.verify_reverse_mapping);
161 ipaddr = get_remote_ipaddr();
164 /* Return false if user is listed in DenyUsers */
165 if (options.num_deny_users > 0) {
166 for (i = 0; i < options.num_deny_users; i++)
167 if (match_user(pw->pw_name, hostname, ipaddr,
168 options.deny_users[i])) {
169 log("User %.100s not allowed because listed in DenyUsers",
174 /* Return false if AllowUsers isn't empty and user isn't listed there */
175 if (options.num_allow_users > 0) {
176 for (i = 0; i < options.num_allow_users; i++)
177 if (match_user(pw->pw_name, hostname, ipaddr,
178 options.allow_users[i]))
180 /* i < options.num_allow_users iff we break for loop */
181 if (i >= options.num_allow_users) {
182 log("User %.100s not allowed because not listed in AllowUsers",
187 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
188 /* Get the user's group access list (primary and supplementary) */
189 if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
190 log("User %.100s not allowed because not in any group",
195 /* Return false if one of user's groups is listed in DenyGroups */
196 if (options.num_deny_groups > 0)
197 if (ga_match(options.deny_groups,
198 options.num_deny_groups)) {
200 log("User %.100s not allowed because a group is listed in DenyGroups",
205 * Return false if AllowGroups isn't empty and one of user's groups
208 if (options.num_allow_groups > 0)
209 if (!ga_match(options.allow_groups,
210 options.num_allow_groups)) {
212 log("User %.100s not allowed because none of user's groups are listed in AllowGroups",
219 #ifdef WITH_AIXAUTHENTICATE
221 * Don't check loginrestrictions() for root account (use
222 * PermitRootLogin to control logins via ssh), or if running as
223 * non-root user (since loginrestrictions will always fail).
225 if ( (pw->pw_uid != 0) && (geteuid() == 0) &&
226 loginrestrictions(pw->pw_name, S_RLOGIN, NULL, &loginmsg) != 0) {
227 int loginrestrict_errno = errno;
229 if (loginmsg && *loginmsg) {
230 /* Remove embedded newlines (if any) */
232 for (p = loginmsg; *p; p++) {
236 /* Remove trailing newline */
238 log("Login restricted for %s: %.100s", pw->pw_name,
241 /* Don't fail if /etc/nologin set */
242 if (!(loginrestrict_errno == EPERM &&
243 stat(_PATH_NOLOGIN, &st) == 0))
246 #endif /* WITH_AIXAUTHENTICATE */
248 /* We found no reason not to let this user try to log on... */
255 Authctxt *authctxt = xmalloc(sizeof(*authctxt));
256 memset(authctxt, 0, sizeof(*authctxt));
261 auth_log(Authctxt *authctxt, int authenticated, char *method, char *info)
263 void (*authlog) (const char *fmt,...) = verbose;
266 /* Raise logging level */
267 if (authenticated == 1 ||
269 authctxt->failures >= AUTH_FAIL_LOG ||
270 strcmp(method, "password") == 0)
273 if (authctxt->postponed)
274 authmsg = "Postponed";
276 authmsg = authenticated ? "Accepted" : "Failed";
278 authlog("%s %s for %s%.100s from %.200s port %d%s",
281 authctxt->valid ? "" : "illegal user ",
287 #ifdef WITH_AIXAUTHENTICATE
288 if (authenticated == 0 && strcmp(method, "password") == 0)
289 loginfailed(authctxt->user,
290 get_canonical_hostname(options.verify_reverse_mapping),
292 #endif /* WITH_AIXAUTHENTICATE */
297 * Check whether root logins are disallowed.
300 auth_root_allowed(char *method)
302 switch (options.permit_root_login) {
306 case PERMIT_NO_PASSWD:
307 if (strcmp(method, "password") != 0)
310 case PERMIT_FORCED_ONLY:
311 if (forced_command) {
312 log("Root login accepted for forced command.");
317 log("ROOT LOGIN REFUSED FROM %.200s", get_remote_ipaddr());
323 * Given a template and a passwd structure, build a filename
324 * by substituting % tokenised options. Currently, %% becomes '%',
325 * %h becomes the home directory and %u the username.
327 * This returns a buffer allocated by xmalloc.
330 expand_filename(const char *filename, struct passwd *pw)
337 * Build the filename string in the buffer by making the appropriate
338 * substitutions to the given file name.
340 buffer_init(&buffer);
341 for (cp = filename; *cp; cp++) {
342 if (cp[0] == '%' && cp[1] == '%') {
343 buffer_append(&buffer, "%", 1);
347 if (cp[0] == '%' && cp[1] == 'h') {
348 buffer_append(&buffer, pw->pw_dir, strlen(pw->pw_dir));
352 if (cp[0] == '%' && cp[1] == 'u') {
353 buffer_append(&buffer, pw->pw_name,
354 strlen(pw->pw_name));
358 buffer_append(&buffer, cp, 1);
360 buffer_append(&buffer, "\0", 1);
363 * Ensure that filename starts anchored. If not, be backward
364 * compatible and prepend the '%h/'
366 file = xmalloc(MAXPATHLEN);
367 cp = buffer_ptr(&buffer);
369 snprintf(file, MAXPATHLEN, "%s/%s", pw->pw_dir, cp);
371 strlcpy(file, cp, MAXPATHLEN);
373 buffer_free(&buffer);
378 authorized_keys_file(struct passwd *pw)
380 return expand_filename(options.authorized_keys_file, pw);
384 authorized_keys_file2(struct passwd *pw)
386 return expand_filename(options.authorized_keys_file2, pw);
389 /* return ok if key exists in sysfile or userfile */
391 check_key_in_hostfiles(struct passwd *pw, Key *key, const char *host,
392 const char *sysfile, const char *userfile)
397 HostStatus host_status;
399 /* Check if we know the host and its host key. */
400 found = key_new(key->type);
401 host_status = check_host_in_hostfile(sysfile, host, key, found, NULL);
403 if (host_status != HOST_OK && userfile != NULL) {
404 user_hostfile = tilde_expand_filename(userfile, pw->pw_uid);
405 if (options.strict_modes &&
406 (stat(user_hostfile, &st) == 0) &&
407 ((st.st_uid != 0 && st.st_uid != pw->pw_uid) ||
408 (st.st_mode & 022) != 0)) {
409 log("Authentication refused for %.100s: "
410 "bad owner or modes for %.200s",
411 pw->pw_name, user_hostfile);
413 temporarily_use_uid(pw);
414 host_status = check_host_in_hostfile(user_hostfile,
415 host, key, found, NULL);
418 xfree(user_hostfile);
422 debug2("check_key_in_hostfiles: key %s for %s", host_status == HOST_OK ?
423 "ok" : "not found", host);
429 * Check a given file for security. This is defined as all components
430 * of the path to the file must be owned by either the owner of
431 * of the file or root and no directories must be group or world writable.
433 * XXX Should any specific check be done for sym links ?
435 * Takes an open file descriptor, the file name, a uid and and
436 * error buffer plus max size as arguments.
438 * Returns 0 on success and -1 on failure
441 secure_filename(FILE *f, const char *file, struct passwd *pw,
442 char *err, size_t errlen)
444 uid_t uid = pw->pw_uid;
445 char buf[MAXPATHLEN], homedir[MAXPATHLEN];
450 if (realpath(file, buf) == NULL) {
451 snprintf(err, errlen, "realpath %s failed: %s", file,
455 if (realpath(pw->pw_dir, homedir) != NULL)
458 /* check the open file to avoid races */
459 if (fstat(fileno(f), &st) < 0 ||
460 (st.st_uid != 0 && st.st_uid != uid) ||
461 (st.st_mode & 022) != 0) {
462 snprintf(err, errlen, "bad ownership or modes for file %s",
467 /* for each component of the canonical path, walking upwards */
469 if ((cp = dirname(buf)) == NULL) {
470 snprintf(err, errlen, "dirname() failed");
473 strlcpy(buf, cp, sizeof(buf));
475 debug3("secure_filename: checking '%s'", buf);
476 if (stat(buf, &st) < 0 ||
477 (st.st_uid != 0 && st.st_uid != uid) ||
478 (st.st_mode & 022) != 0) {
479 snprintf(err, errlen,
480 "bad ownership or modes for directory %s", buf);
484 /* If are passed the homedir then we can stop */
485 if (comparehome && strcmp(homedir, buf) == 0) {
486 debug3("secure_filename: terminating check at '%s'",
491 * dirname should always complete with a "/" path,
492 * but we can be paranoid and check for "." too
494 if ((strcmp("/", buf) == 0) || (strcmp(".", buf) == 0))
501 getpwnamallow(const char *user)
503 #ifdef HAVE_LOGIN_CAP
504 extern login_cap_t *lc;
513 log("Illegal user %.100s from %.100s",
514 user, get_remote_ipaddr());
515 #ifdef WITH_AIXAUTHENTICATE
517 get_canonical_hostname(options.verify_reverse_mapping),
522 if (!allowed_user(pw))
524 #ifdef HAVE_LOGIN_CAP
525 if ((lc = login_getclass(pw->pw_class)) == NULL) {
526 debug("unable to get login class: %s", user);
530 if ((as = auth_open()) == NULL || auth_setpwd(as, pw) != 0 ||
531 auth_approval(as, lc, pw->pw_name, "ssh") <= 0) {
532 debug("Approval failure for %s", user);
545 auth_debug_add(const char *fmt,...)
550 if (!auth_debug_init)
554 vsnprintf(buf, sizeof(buf), fmt, args);
556 buffer_put_cstring(&auth_debug, buf);
560 auth_debug_send(void)
564 if (!auth_debug_init)
566 while (buffer_len(&auth_debug)) {
567 msg = buffer_get_string(&auth_debug, NULL);
568 packet_send_debug("%s", msg);
574 auth_debug_reset(void)
577 buffer_clear(&auth_debug);
579 buffer_init(&auth_debug);