Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
*/
package org.apache.shiro.authc.credential;

import java.util.Optional;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;

/**
* A credentials matcher that always returns {@code true} when matching credentials no matter what arguments
Expand All @@ -40,4 +42,9 @@ public class AllowAllCredentialsMatcher implements CredentialsMatcher {
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
return true;
}

@Override
public Optional<AuthenticationInfo> createSimulatedCredentials() {
return Optional.of(new SimpleAuthenticationInfo("user", "password", "realm"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
package org.apache.shiro.authc.credential;

import java.util.Optional;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;

Expand Down Expand Up @@ -51,4 +52,15 @@ public interface CredentialsMatcher {
*/
boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info);

/**
* Create simulated credentials in case of a non-existent user trying to log in.
*
* <p>Implementations must make sure to use an algorithm which is also used by users, which
* roughly takes the same amount of time as checking a real user's AuthenticationInfo.</p>
* <p>They must also make sure to return AuthenticationInfo which can never be validated.</p>
* @return simulated AuthenticationInfo, created for non-existent users.
*/
default Optional<AuthenticationInfo> createSimulatedCredentials() {
return Optional.empty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/
package org.apache.shiro.authc.credential;

import java.util.Optional;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.crypto.hash.Hash;
Expand All @@ -32,7 +33,6 @@
* @since 1.2
*/
public class PasswordMatcher implements CredentialsMatcher {

private PasswordService passwordService;

public PasswordMatcher() {
Expand Down Expand Up @@ -68,6 +68,11 @@ private HashingPasswordService assertHashingPasswordService(PasswordService serv
throw new IllegalStateException(msg);
}

@Override
public Optional<AuthenticationInfo> createSimulatedCredentials() {
return SimpleCredentialsMatcher.makeSimulatedAuthenticationInfo(ensurePasswordService());
}

private PasswordService ensurePasswordService() {
PasswordService service = getPasswordService();
if (service == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,17 @@
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.crypto.hash.format.Shiro1CryptFormat;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.codec.CodecSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Optional;


/**
Expand All @@ -42,6 +48,8 @@
public class SimpleCredentialsMatcher extends CodecSupport implements CredentialsMatcher {

private static final Logger log = LoggerFactory.getLogger(SimpleCredentialsMatcher.class);
/** Default number of bytes for a simulated password. */
private static final int DEFAULT_PASSWORD_BYTES = 18;

/**
* Returns the {@code token}'s credentials.
Expand Down Expand Up @@ -129,4 +137,31 @@ public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo
return equals(tokenCredentials, accountCredentials);
}

@Override
public Optional<AuthenticationInfo> createSimulatedCredentials() {
return SimpleCredentialsMatcher.makeSimulatedAuthenticationInfo(null);
}

/**
* default implementation which creates a simulated AuthenticationInfo with a random password
* NOTE: the returned AuthenticationInfo must never validate successfully
* NOTE: make sure this is not called from performance-critical paths, as it uses SecureRandom
* @return simulated AuthenticationInfo, created for non-existent users.
*/
static Optional<AuthenticationInfo> makeSimulatedAuthenticationInfo(PasswordService passwordService) {
final SecureRandom random = new SecureRandom();
final byte[] bytes = new byte[DEFAULT_PASSWORD_BYTES];
random.nextBytes(bytes);
final byte[] encode = Base64.encode(bytes);

Object parsedPassword;
if (passwordService == null) {
parsedPassword = encode;
} else {
parsedPassword = new Shiro1CryptFormat().parse(passwordService.encryptPassword(encode));
}

return Optional.of(
new SimpleAuthenticationInfo("__principal__", parsedPassword, ""));
}
}
90 changes: 76 additions & 14 deletions core/src/main/java/org/apache/shiro/realm/AuthenticatingRealm.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
*/
package org.apache.shiro.realm;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
Expand All @@ -28,13 +31,12 @@
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.util.Initializable;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.Initializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;


/**
* A top-level abstract implementation of the <tt>Realm</tt> interface that only implements authentication support
Expand Down Expand Up @@ -110,6 +112,7 @@
*
* @since 0.2
*/
@SuppressWarnings("checkstyle:MethodCount")
public abstract class AuthenticatingRealm extends CachingRealm implements Initializable {

//TODO - complete JavaDoc
Expand All @@ -125,6 +128,12 @@ public abstract class AuthenticatingRealm extends CachingRealm implements Initia
*/
private static final String DEFAULT_AUTHENTICATION_CACHE_SUFFIX = ".authenticationCache";

/**
* Simulated authentication info, should only be set once to avoid wasting useless CPU cycles.
*/
private final AtomicReference<AuthenticationInfo> simulatedAuthenticationInfo =
new AtomicReference<>();

/**
* Credentials matcher used to determine if the provided credentials match the credentials stored in the data store.
*/
Expand Down Expand Up @@ -580,9 +589,49 @@ public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)
if (info != null) {
assertCredentialsMatch(token, info);
} else {
log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}]. Returning null.", token);
simulateFailedLogin(token);
}

return info;
}

private void simulateFailedLogin(AuthenticationToken token) {
try {
AuthenticationInfo simulated = ensureSimulatedAuthenticationInfo();
if (simulated != null && assertCredentialsMatchWithoutException(token, simulated)) {
String msg = "Submitted credentials for token [" + token + "] matched the simulated credentials. "
+ "This indicates a misconfiguration of the realm's "
+ "CredentialsMatcher or simulated credentials. Please review your configuration.";
throw new IncorrectCredentialsException(msg);
}
} catch (AuthenticationException authenticationException) {
// should not happen as the auth info comes directly from the credential service,
// but log to ensure implementations can find their flaw.
log.error(
"CredentialsMatcher [{}] threw exception on method 'doCredentialsMatch'",
getCredentialsMatcher(), authenticationException);
}
}

/**
* Make sure some AuthenticationInfo for simulated checks does exist. If not, it will be generated.
* @return simulated AuthenticationInfo
*/
AuthenticationInfo ensureSimulatedAuthenticationInfo() {
AuthenticationInfo info = simulatedAuthenticationInfo.get();
if (info == null) {
Optional<AuthenticationInfo> simulated =
getCredentialsMatcher().createSimulatedCredentials();

if (simulated.isPresent()) {
simulatedAuthenticationInfo.set(simulated.get());
} else {
log.warn(
"CredentialsMatcher [{}] did not supply simulated credentials. Please update the implementation.",
getCredentialsMatcher());
}
return simulatedAuthenticationInfo.get();
}
return info;
}

Expand All @@ -595,17 +644,10 @@ public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)
* @throws AuthenticationException if the token's credentials do not match the stored account credentials.
*/
protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
CredentialsMatcher cm = getCredentialsMatcher();
if (cm != null) {
if (!cm.doCredentialsMatch(token, info)) {
//not successful - throw an exception to indicate this:
String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";
throw new IncorrectCredentialsException(msg);
}
} else {
throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " +
"credentials during authentication. If you do not wish for credentials to be examined, you " +
"can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
if (!assertCredentialsMatchWithoutException(token, info)) {
//not successful - throw an exception to indicate this:
String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";
throw new IncorrectCredentialsException(msg);
}
}

Expand Down Expand Up @@ -712,4 +754,24 @@ protected void clearCachedAuthenticationInfo(PrincipalCollection principals) {
*/
protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException;

/**
* Asserts that the submitted {@code AuthenticationToken}'s credentials match the stored account
* needed for simulated checks that do not need to throw exceptions.
*
* @param token the submitted authentication token
* @param info the AuthenticationInfo corresponding to the given {@code token}
* @return true if the token's credentials match the stored account credentials, false otherwise.
* @throws AuthenticationException only for configuration problems.
*/
private boolean assertCredentialsMatchWithoutException(AuthenticationToken token,
AuthenticationInfo info) throws AuthenticationException {
CredentialsMatcher cm = getCredentialsMatcher();
if (cm != null) {
return cm.doCredentialsMatch(token, info);
} else {
throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify "
+ "credentials during authentication. If you do not wish for credentials to be examined, you "
+ "can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ class AuthenticatingRealmTest {

def token = createStrictMock(AuthenticationToken)
def info = createStrictMock(AuthenticationInfo)
expect(token.getCredentials()).andReturn(null).anyTimes()

replay token, info

Expand Down
Loading
Loading