fix(iam): use SecureRandom for secret credentials and tokens (#3960)

This commit is contained in:
danielvanza authored and GitHub committed 2026-09-20 16:17:50 -04:00
1 parent a03b00ce89
commit 94976360ac
7 files changed
+191 -7

No files matched your search

@@ -34,6 +34,7 @@ import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
@@ -90,6 +91,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
/** Guards the read-modify-write in the OIDC provider mutators. */
private final Object oidcProviderLock = new Object();
/** CSPRNG for long-term secret access keys; ordinary resource IDs keep using {@link ThreadLocalRandom}. */
private final SecureRandom secureRandom = new SecureRandom();
private static final String SERVICE_LINKED_ROLE_PATH = "/aws-service-role/";
private static final String SERVICE_LINKED_ROLE_NAME_PREFIX = "AWSServiceRoleFor";
private static final Map<String, String> SERVICE_LINKED_ROLE_NAMES = Map.of(
@@ -2590,11 +2594,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return sb.toString();
}
private static String randomSecret(int length) {
private String randomSecret(int length) {
String secretChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append(secretChars.charAt(ThreadLocalRandom.current().nextInt(secretChars.length())));
sb.append(secretChars.charAt(secureRandom.nextInt(secretChars.length())));
}
return sb.toString();
}
@@ -21,6 +21,7 @@ import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.security.SecureRandom;
import java.security.interfaces.RSAPublicKey;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
@@ -52,6 +53,9 @@ public class StsQueryHandler {
private final SAMLProviderService samlProviderService;
private final SAMLTrustPolicyEvaluator samlTrustEvaluator;
/** CSPRNG for session secret keys and session tokens; ordinary IDs keep using {@link ThreadLocalRandom}. */
private final SecureRandom secureRandom = new SecureRandom();
@Context
HttpHeaders headers;
@@ -488,10 +492,10 @@ public class StsQueryHandler {
return sb.toString();
}
private static String randomSecret(int length) {
private String randomSecret(int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append(CHARS.charAt(ThreadLocalRandom.current().nextInt(CHARS.length())));
sb.append(CHARS.charAt(secureRandom.nextInt(CHARS.length())));
}
return sb.toString();
}
@@ -31,7 +31,6 @@ import java.security.*;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.RAW;
@@ -404,7 +403,7 @@ public class KmsService implements ResourceProvider {
requireNotPendingDeletion(key);
String grantId = UUID.randomUUID().toString();
byte[] tokenBytes = new byte[32];
ThreadLocalRandom.current().nextBytes(tokenBytes);
secureRandom.nextBytes(tokenBytes);
KmsGrant grant = new KmsGrant();
grant.setGrantId(grantId);
@@ -1762,7 +1761,7 @@ public class KmsService implements ResourceProvider {
int len = keySpec == null ? numberOfBytes : "AES_128".equals(keySpec) ? 16 : 32;
byte[] plaintext = new byte[len];
ThreadLocalRandom.current().nextBytes(plaintext);
secureRandom.nextBytes(plaintext);
EncryptResult encrypted = encrypt(keyId, plaintext, encryptionContext, null, region, operation);
@@ -915,6 +915,18 @@ class IamServiceTest {
assertEquals(1, keys.size());
}
@Test
void accessKeySecretsAreFortyCharsAndUnique() {
iamService.createUser("alice", "/");
iamService.createUser("bob", "/");
AccessKey first = iamService.createAccessKey("alice");
AccessKey second = iamService.createAccessKey("bob");
assertEquals(40, first.getSecretAccessKey().length());
assertEquals(40, second.getSecretAccessKey().length());
assertNotEquals(first.getSecretAccessKey(), second.getSecretAccessKey());
}
@Test
void createThirdAccessKeyFails() {
iamService.createUser("alice", "/");
@@ -0,0 +1,70 @@
package io.github.hectorvent.floci.services.iam;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Guards the security-material generators against regressing to a non-CSPRNG source. Ordinary
* resource IDs may keep using {@code ThreadLocalRandom}; credentials, session tokens, grant tokens,
* and data keys must not.
*/
class SecurityMaterialRandomnessTest {
private static final Path IAM_SERVICE =
Path.of("src/main/java/io/github/hectorvent/floci/services/iam/IamService.java");
private static final Path STS_HANDLER =
Path.of("src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java");
private static final Path KMS_SERVICE =
Path.of("src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java");
private static final Pattern RANDOM_SECRET_DECLARATION =
Pattern.compile("private\\s+String\\s+randomSecret\\s*\\(int\\s+length\\)");
@Test
void iamAndStsSecretGeneratorsDoNotUseThreadLocalRandom() throws IOException {
assertSecretGeneratorUsesSecureRandom(IAM_SERVICE);
assertSecretGeneratorUsesSecureRandom(STS_HANDLER);
}
@Test
void kmsServiceDoesNotImportThreadLocalRandom() throws IOException {
assertFalse(Files.readString(KMS_SERVICE).contains("ThreadLocalRandom"),
"KMS security material must come from SecureRandom, not ThreadLocalRandom");
}
private static void assertSecretGeneratorUsesSecureRandom(Path file) throws IOException {
String source = Files.readString(file);
Matcher declaration = RANDOM_SECRET_DECLARATION.matcher(source);
assertTrue(declaration.find(), "no randomSecret(int length) declaration in " + file);
int bodyStart = source.indexOf('{', declaration.end());
assertTrue(bodyStart >= 0, "no body for randomSecret in " + file);
String body = source.substring(bodyStart, matchingBrace(source, bodyStart) + 1);
assertTrue(body.contains("secureRandom"),
"randomSecret in " + file + " must draw from the SecureRandom field");
assertFalse(body.contains("ThreadLocalRandom"),
"randomSecret in " + file + " must use SecureRandom, not ThreadLocalRandom");
}
private static int matchingBrace(String source, int openIndex) {
int depth = 0;
for (int i = openIndex; i < source.length(); i++) {
char c = source.charAt(i);
if (c == '{') {
depth++;
} else if (c == '}') {
depth--;
if (depth == 0) {
return i;
}
}
}
throw new IllegalArgumentException("unbalanced braces from index " + openIndex);
}
}
@@ -0,0 +1,71 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
class StsQueryHandlerTest {
private static final String REGION = "us-east-1";
private static final Pattern SECRET_ACCESS_KEY =
Pattern.compile("<SecretAccessKey>([^<]+)</SecretAccessKey>");
private static final Pattern SESSION_TOKEN =
Pattern.compile("<SessionToken>([^<]+)</SessionToken>");
private static StsQueryHandler newHandler() {
return new StsQueryHandler(
mock(IamService.class),
mock(AccountResolver.class),
new RegionResolver(REGION, "000000000000"),
mock(EmulatorConfig.class),
mock(AssumeRolePolicyEvaluator.class),
mock(WebIdentityTrustPolicyEvaluator.class),
mock(WebIdentityTokenVerifier.class),
mock(OidcIssuerKeyLookup.class),
mock(SAMLProviderService.class),
mock(SAMLTrustPolicyEvaluator.class));
}
@Test
void getSessionTokenIssuesFortyCharSecretAndTwoHundredCharToken() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
Response response = newHandler().handle("GetSessionToken", params);
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertEquals(40, extract(SECRET_ACCESS_KEY, body).length());
assertEquals(200, extract(SESSION_TOKEN, body).length());
}
@Test
void getSessionTokensAreUniqueAcrossCalls() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
String firstBody = (String) newHandler().handle("GetSessionToken", params).getEntity();
String secondBody = (String) newHandler().handle("GetSessionToken", params).getEntity();
assertNotEquals(extract(SECRET_ACCESS_KEY, firstBody), extract(SECRET_ACCESS_KEY, secondBody));
assertNotEquals(extract(SESSION_TOKEN, firstBody), extract(SESSION_TOKEN, secondBody));
}
private static String extract(Pattern pattern, String body) {
Matcher matcher = pattern.matcher(body);
assertTrue(matcher.find(), "expected " + pattern + " in " + body);
return matcher.group(1);
}
}
@@ -195,6 +195,30 @@ class KmsServiceTest {
assertEquals(false, result.get("Truncated"));
}
@Test
void grantTokensAreUniqueUrlSafeBase64Of32Bytes() {
KmsKey key = kmsService.createKey("csprng grant key", REGION);
KmsGrant first = kmsService.createGrant(key.getKeyId(),
"arn:aws:iam::000000000000:user/grantee", List.of("Encrypt"), REGION);
KmsGrant second = kmsService.createGrant(key.getKeyId(),
"arn:aws:iam::000000000000:user/grantee", List.of("Encrypt"), REGION);
assertEquals(43, first.getGrantToken().length());
assertNotEquals(first.getGrantToken(), second.getGrantToken());
}
@Test
void generatedDataKeyPlaintextsAreUniqueAndRequestedLength() {
KmsKey key = kmsService.createKey("csprng data key", REGION);
byte[] first = (byte[]) kmsService.generateDataKey(key.getKeyId(), "AES_256", null, REGION).get("Plaintext");
byte[] second = (byte[]) kmsService.generateDataKey(key.getKeyId(), "AES_256", null, REGION).get("Plaintext");
assertEquals(32, first.length);
assertFalse(Arrays.equals(first, second));
}
@Test
void createGrantMissingKeyIdThrowsValidation() {
AwsException ex = assertThrows(AwsException.class, () ->