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 @@ -23,10 +23,8 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Predicate;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.RE;
import org.apache.druid.java.util.common.RetryUtils;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.security.basic.authentication.entity.BasicAuthenticatorUser;
import org.apache.druid.security.basic.authorization.entity.BasicAuthorizerGroupMapping;
import org.apache.druid.security.basic.authorization.entity.BasicAuthorizerRole;
Expand All @@ -35,21 +33,15 @@
import org.apache.druid.security.basic.authorization.entity.UserAndRoleMap;

import javax.annotation.Nullable;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;

public class BasicAuthUtils
{

private static final Logger log = new Logger(BasicAuthUtils.class);
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
public static final String ADMIN_NAME = "admin";
public static final String ADMIN_GROUP_MAPPING_NAME = "adminGroupMapping";
Expand All @@ -66,8 +58,6 @@ public class BasicAuthUtils
public static final int DEFAULT_CREDENTIAL_VERIFY_DURATION_SECONDS = 600;
public static final int DEFAULT_CREDENTIAL_MAX_DURATION_SECONDS = 3600;
public static final int DEFAULT_CREDENTIAL_CACHE_SIZE = 100;
public static final int KEY_LENGTH = 512;
public static final String ALGORITHM = "PBKDF2WithHmacSHA512";
public static final int MAX_INIT_RETRIES = 2;
public static final Predicate<Throwable> SHOULD_RETRY_INIT =
(throwable) -> throwable instanceof BasicSecurityDBResourceException;
Expand Down Expand Up @@ -102,30 +92,6 @@ public class BasicAuthUtils
{
};

public static byte[] hashPassword(final char[] password, final byte[] salt, final int iterations)
{
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey key = keyFactory.generateSecret(
new PBEKeySpec(
password,
salt,
iterations,
KEY_LENGTH
)
);
return key.getEncoded();
}
catch (InvalidKeySpecException ikse) {
log.error("Invalid keyspec");
throw new RuntimeException("Invalid keyspec", ikse);
}
catch (NoSuchAlgorithmException nsae) {
log.error("%s not supported on this system.", ALGORITHM);
throw new RE(nsae, "%s not supported on this system.", ALGORITHM);
}
}

public static byte[] generateSalt()
{
byte[] salt = new byte[SALT_LENGTH];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
import com.google.common.annotations.VisibleForTesting;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.security.basic.BasicAuthUtils;
import org.apache.druid.security.basic.authentication.entity.BasicAuthenticatorCredentials;
import org.apache.druid.security.basic.authentication.validator.PasswordHashGenerator;

import javax.naming.directory.SearchResult;
import java.security.Principal;
Expand Down Expand Up @@ -94,7 +94,7 @@ public Instant getLastVerified()

public boolean hasSameCredentials(char[] password)
{
byte[] recalculatedHash = BasicAuthUtils.hashPassword(
byte[] recalculatedHash = PasswordHashGenerator.computePasswordHash(
password,
this.credentials.getSalt(),
this.credentials.getIterations()
Expand Down Expand Up @@ -138,6 +138,7 @@ public String toString()
name,
searchResult,
createdAt,
lastVerified);
lastVerified
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import org.apache.druid.security.basic.BasicAuthUtils;
import org.apache.druid.security.basic.authentication.validator.PasswordHashGenerator;

import java.util.Arrays;

Expand Down Expand Up @@ -50,7 +51,7 @@ public BasicAuthenticatorCredentials(BasicAuthenticatorCredentialUpdate update)
{
this.iterations = update.getIterations();
this.salt = BasicAuthUtils.generateSalt();
this.hash = BasicAuthUtils.hashPassword(update.getPassword().toCharArray(), salt, iterations);
this.hash = PasswordHashGenerator.computePasswordHash(update.getPassword().toCharArray(), salt, iterations);
}

@JsonProperty
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.LdapName;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
Expand All @@ -60,6 +59,7 @@ public class LDAPCredentialsValidator implements CredentialsValidator
private static final ReentrantLock LOCK = new ReentrantLock();

private final LruBlockCache cache;
private final PasswordHashGenerator hashGenerator = new PasswordHashGenerator();

private final BasicAuthLDAPConfig ldapConfig;
// Custom overrides that can be passed via tests
Expand Down Expand Up @@ -199,7 +199,7 @@ public AuthenticationResult validateCredentials(
}

byte[] salt = BasicAuthUtils.generateSalt();
byte[] hash = BasicAuthUtils.hashPassword(password, salt, this.ldapConfig.getCredentialIterations());
byte[] hash = hashGenerator.getOrComputePasswordHash(password, salt, this.ldapConfig.getCredentialIterations());
LdapUserPrincipal newPrincipal = new LdapUserPrincipal(
username,
new BasicAuthenticatorCredentials(salt, hash, this.ldapConfig.getCredentialIterations()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import com.google.inject.Provider;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.security.basic.BasicAuthUtils;
import org.apache.druid.security.basic.BasicSecurityAuthenticationException;
import org.apache.druid.security.basic.authentication.db.cache.BasicAuthenticatorCacheManager;
import org.apache.druid.security.basic.authentication.entity.BasicAuthenticatorCredentials;
Expand All @@ -42,6 +41,7 @@ public class MetadataStoreCredentialsValidator implements CredentialsValidator
{
private static final Logger LOG = new Logger(MetadataStoreCredentialsValidator.class);
private final Provider<BasicAuthenticatorCacheManager> cacheManager;
private final PasswordHashGenerator hashGenerator = new PasswordHashGenerator();

@JsonCreator
public MetadataStoreCredentialsValidator(
Expand Down Expand Up @@ -74,7 +74,7 @@ public AuthenticationResult validateCredentials(
return null;
}

byte[] recalculatedHash = BasicAuthUtils.hashPassword(
byte[] recalculatedHash = hashGenerator.getOrComputePasswordHash(
password,
credentials.getSalt(),
credentials.getIterations()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.druid.security.basic.authentication.validator;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheStats;
import com.google.common.hash.Hashing;
import org.apache.druid.error.DruidException;
import org.apache.druid.java.util.common.RE;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.security.basic.BasicAuthUtils;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.time.Duration;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.ExecutionException;

/**
* Generates a hash of passwords using the {@link #HASH_ALGORITHM}. Multiple
* iterations may be used to enhance security of the generated hash.
* <p>
* Hashes once computed are cached for an hour so that they need not be recomputed
* for every API invocation.
*/
public class PasswordHashGenerator
{
private static final Logger log = new Logger(PasswordHashGenerator.class);

public static final int KEY_LENGTH = 512;
public static final String HASH_ALGORITHM = "PBKDF2WithHmacSHA512";

/**
* Salt used to compute a quick sha-256 hash of the password for the cache.
*/
private final byte[] shaSalt = BasicAuthUtils.generateSalt();

private final Cache<CacheKey, byte[]> cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.recordStats()
.expireAfterAccess(Duration.ofMinutes(60))
.build();

/**
* Hashes the given password using the {@link #HASH_ALGORITHM}.
*/
public byte[] getOrComputePasswordHash(char[] password, byte[] salt, int numIterations)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

did you run some local test to how much runs-per-second you get with "getOrComputePasswordHash" and with "computePasswordHash"? Just to make sure that we do see perf gains. By benchmark, I really mean just a simple test method calling these functions in a loop

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the newly added test PasswordHashGeneratorTest does a bit of comparison of the two methods.

{
try {
return cache.get(
CacheKey.of(password, salt, numIterations, shaSalt),
() -> computePasswordHash(password, salt, numIterations)
);
}
catch (ExecutionException e) {
throw DruidException.defensive().build(e, "Could not compute hash of password");
}
}

public CacheStats getCacheStats()
{
return cache.stats();
}

/**
* Utility method to compuate hash of the given password using the {@link #HASH_ALGORITHM}.
* Callers should use the non-static method instead to leverage caching.
*/
public static byte[] computePasswordHash(final char[] password, final byte[] salt, final int iterations)
{
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(HASH_ALGORITHM);
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(password, salt, iterations, KEY_LENGTH));
return key.getEncoded();
}
catch (InvalidKeySpecException ikse) {
log.error("Invalid keyspec");
throw new RuntimeException("Invalid keyspec", ikse);
}
catch (NoSuchAlgorithmException nsae) {
log.error("Hash algorithm[%s] is not supported on this system.", HASH_ALGORITHM);
throw new RE(nsae, "Hash algorithm[%s] is not supported on this system.", HASH_ALGORITHM);
}
}

/**
* Key used in the {@link #cache}. An SHA-256 hash of the password is used
* instead of the actual string so that the passwords are never exposed, even
* in a heap dump.
*/
private static class CacheKey
{
final byte[] passwordSha;
final byte[] salt;
final int numIterations;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need numIterations in CacheKey?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that is because the final hash value can change if numIterations changes. Also, it doesn't seem like we use the same number of iterations for every credential as it is configurable. But let me double check to be sure.


CacheKey(byte[] passwordSha, byte[] salt, int numIterations)
{
this.passwordSha = passwordSha;
this.salt = salt;
this.numIterations = numIterations;
}

static CacheKey of(char[] password, byte[] salt, int numIterations, byte[] md5Salt)
{
@SuppressWarnings("UnstableApiUsage")
byte[] passwordSha = Hashing.sha256().newHasher()
.putBytes(StringUtils.toUtf8(new String(password)))
.putBytes(md5Salt)
.hash()
.asBytes();

return new CacheKey(passwordSha, salt, numIterations);
}

@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CacheKey cacheKey = (CacheKey) o;
return numIterations == cacheKey.numIterations
&& Arrays.equals(passwordSha, cacheKey.passwordSha)
&& Arrays.equals(salt, cacheKey.salt);
}

@Override
public int hashCode()
{
int result = Objects.hash(numIterations);
result = 31 * result + Arrays.hashCode(passwordSha);
result = 31 * result + Arrays.hashCode(salt);
return result;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,6 @@

public class BasicAuthUtilsTest
{
@Test
public void testHashPassword()
{
char[] password = "HELLO".toCharArray();
int iterations = BasicAuthUtils.DEFAULT_KEY_ITERATIONS;
byte[] salt = BasicAuthUtils.generateSalt();
byte[] hash = BasicAuthUtils.hashPassword(password, salt, iterations);

Assert.assertEquals(BasicAuthUtils.SALT_LENGTH, salt.length);
Assert.assertEquals(BasicAuthUtils.KEY_LENGTH / 8, hash.length);
}

@Test
public void testPermissionSerdeIsChillAboutUnknownEnumStuffs() throws JsonProcessingException
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.apache.druid.security.basic.authentication.entity.BasicAuthenticatorCredentialUpdate;
import org.apache.druid.security.basic.authentication.entity.BasicAuthenticatorCredentials;
import org.apache.druid.security.basic.authentication.entity.BasicAuthenticatorUser;
import org.apache.druid.security.basic.authentication.validator.PasswordHashGenerator;
import org.apache.druid.server.security.AuthenticatorMapper;
import org.junit.After;
import org.junit.Assert;
Expand Down Expand Up @@ -163,7 +164,7 @@ public void setCredentials()
);
BasicAuthenticatorCredentials credentials = userMap.get("druid").getCredentials();

byte[] recalculatedHash = BasicAuthUtils.hashPassword(
byte[] recalculatedHash = PasswordHashGenerator.computePasswordHash(
"helloworld".toCharArray(),
credentials.getSalt(),
credentials.getIterations()
Expand Down
Loading