feat(securityhub): standards subscriptions (#6979)

* feat(securityhub): standards subscriptions

BatchEnableStandards, BatchDisableStandards, GetEnabledStandards and
DescribeStandards, so Terraform's aws_securityhub_standards_subscription
(and cloudposse's security-hub module) can enable CIS, AFSBP and NIST
800-53. EnableSecurityHub now subscribes AWS's default standards (AFSBP
and CIS 1.2.0) unless EnableDefaultStandards is false, as AWS does.
Subscriptions are READY at once; controls and findings are not evaluated.

Found applying kthw-on-floci's account-baseline: every standards
subscription failed with UnknownOperationException (POST
/standards/register).

BatchDisableStandards checks every ARN before removing any, so a batch
naming one unknown subscription changes nothing (before, the removals ahead
of it stuck in memory without being saved, and came back after a
restart). GetEnabledStandards reads the subscriptions under the same lock
the writers hold.

* fix(securityhub): reject a non-boolean EnableDefaultStandards

EnableSecurityHub coerced EnableDefaultStandards with asBoolean(true), so a
string "false" skipped the defaults and an object enabled them, and the
hub was enabled either way. The botocore model types the member boolean.
Reject it with InvalidInputException before any state changes, as
UpdateSecurityHubConfiguration does for AutoEnableControls.

* fix(securityhub): offer CIS v5.0.0 and take ARN partitions from the region resolver

Add CIS AWS Foundations Benchmark v5.0.0 (standards/cis-aws-foundations-benchmark/v/5.0.0,
regional, not enabled by default) to the standards Security Hub offers.

Mint every Security Hub ARN through RegionResolver: the global CIS 1.2.0 ARN takes
partitionForRegion and the regional ARNs use buildArn, so a region the catalog cannot
place keeps the deployment's partition instead of falling back to aws.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-29 23:37:48 -04:00
1 parent c8143b9c38
commit 0a3efd65fe
6 files changed
+293 -10

No files matched your search

+1 -1
View File
@@ -56,7 +56,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Amazon Macie](macie2.md) | `/admin`, `/macie`, `/admin/configuration` | REST JSON | 8 |
| [Amazon Inspector](inspector2.md) | `/delegatedadminaccounts/*`, `/status/batch/get`, `/enable`, `/organizationconfiguration/*` | REST JSON | 7 |
| [Amazon Verified Permissions](verifiedpermissions.md) | `POST /` + `X-Amz-Target: VerifiedPermissions.*` | JSON 1.0 | 34 |
| [Security Hub](securityhub.md) | `/organization/*`, `/accounts`, `/findingAggregator/*`, `/configurationPolicy*`, `/tags/*` | REST JSON | 22 |
| [Security Hub](securityhub.md) | `/organization/*`, `/accounts`, `/findingAggregator/*`, `/configurationPolicy*`, `/standards*`, `/tags/*` | REST JSON | 26 |
| [Amazon Detective](detective.md) | `/orgs/*`, `/graphs/list`, `/graph/*` | REST JSON | 8 |
| [Amazon Connect](connect.md) | `/instance`, `/instance/{instanceId}/*`, `/tags/*` | REST JSON | 15 |
| [Amazon AppIntegrations](appintegrations.md) | `/eventIntegrations/*`, `/dataIntegrations/*`, `/tags/*` | REST JSON | 14 |
+4
View File
@@ -16,6 +16,10 @@ Floci implements the AWS Security Hub CSPM organization and central-configuratio
| `DescribeHub` | - |
| `EnableSecurityHub` | - |
| `UpdateSecurityHubConfiguration` | - |
| `DescribeStandards` | Lists the standards Security Hub offers: CIS 1.2.0, 1.4.0, 3.0.0 and 5.0.0, AFSBP, NIST 800-53 Rev5, PCI DSS 3.2.1 and 4.0.1, and the resource tagging standard |
| `BatchEnableStandards` | Subscribes standards (`READY` at once); an unknown standards ARN is `InvalidInputException`, a disabled hub `InvalidAccessException`. `EnableSecurityHub` subscribes AFSBP and CIS 1.2.0 unless `EnableDefaultStandards` is false |
| `BatchDisableStandards` | Removes subscriptions, answered as `DELETING`; an unknown one is `ResourceNotFoundException`, and then none of the batch is removed |
| `GetEnabledStandards` | Lists subscriptions, all or the named ones. Controls and findings are not evaluated |
| `ListFindingAggregators` | - |
| `CreateFindingAggregator` | - |
| `GetFindingAggregator` | - |
@@ -110,6 +110,55 @@ public class SecurityHubController {
return empty();
}
@GET
@Path("/standards")
public Response describeStandards(@Context HttpHeaders headers) {
String region = region(headers);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode standards = response.putArray("Standards");
for (SecurityHubService.Standard standard : SecurityHubService.STANDARDS) {
ObjectNode item = standards.addObject()
.put("StandardsArn", securityHubService.standardsArn(region, standard))
.put("Name", standard.name())
.put("Description", standard.name())
.put("EnabledByDefault", standard.enabledByDefault());
item.putObject("StandardsManagedBy").put("Company", "AWS").put("Product", "Security Hub");
}
return Response.ok(response).build();
}
@POST
@Path("/standards/register")
public Response batchEnableStandards(@Context HttpHeaders headers, String body) {
return subscriptions(securityHubService.enableStandards(region(headers), readTree(body)), "READY");
}
@POST
@Path("/standards/deregister")
public Response batchDisableStandards(@Context HttpHeaders headers, String body) {
return subscriptions(securityHubService.disableStandards(region(headers), readTree(body)), "DELETING");
}
@POST
@Path("/standards/get")
public Response getEnabledStandards(@Context HttpHeaders headers, String body) {
return subscriptions(securityHubService.enabledStandards(region(headers), readTree(body)), "READY");
}
private Response subscriptions(Map<String, String> subscriptions, String status) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode items = response.putArray("StandardsSubscriptions");
subscriptions.forEach((subscriptionArn, standardsArn) -> {
ObjectNode item = items.addObject()
.put("StandardsSubscriptionArn", subscriptionArn)
.put("StandardsArn", standardsArn)
.put("StandardsStatus", status)
.put("StandardsControlsUpdatable", "READY_FOR_UPDATES");
item.putObject("StandardsInput");
});
return Response.ok(response).build();
}
@GET
@Path("/findingAggregator/list")
public Response listFindingAggregators(@Context HttpHeaders headers,
@@ -97,14 +97,130 @@ public class SecurityHubService implements Resettable {
throw invalid("ControlFindingGenerator must be SECURITY_CONTROL or STANDARD_CONTROL.");
}
validateTags(request == null ? null : request.get("Tags"));
JsonNode defaults = request == null ? null : request.get("EnableDefaultStandards");
if (defaults != null && !defaults.isNull() && !defaults.isBoolean()) {
throw invalid("EnableDefaultStandards must be a boolean.");
}
state.setEnabled(true);
if (controlFindingGenerator != null) {
state.setControlFindingGenerator(controlFindingGenerator);
}
state.setHubTags(readTags(request == null ? null : request.get("Tags")));
// EnableDefaultStandards is true unless the caller says otherwise, as on AWS.
if (defaults == null || defaults.isNull() || defaults.booleanValue()) {
for (Standard standard : STANDARDS) {
if (standard.enabledByDefault()) {
state.getStandardsSubscriptions().put(subscriptionArn(region, standard), standardsArn(region, standard));
}
}
}
save(region, state);
}
// ── Standards ─────────────────────────────────────────────────────────────
/** A standard Security Hub offers: its path after the ARN's resource type, name, and scope. */
public record Standard(String path, String name, boolean global, boolean enabledByDefault) {}
public static final List<Standard> STANDARDS = List.of(
new Standard("ruleset/cis-aws-foundations-benchmark/v/1.2.0",
"CIS AWS Foundations Benchmark v1.2.0", true, true),
new Standard("standards/aws-foundational-security-best-practices/v/1.0.0",
"AWS Foundational Security Best Practices v1.0.0", false, true),
new Standard("standards/cis-aws-foundations-benchmark/v/1.4.0",
"CIS AWS Foundations Benchmark v1.4.0", false, false),
new Standard("standards/cis-aws-foundations-benchmark/v/3.0.0",
"CIS AWS Foundations Benchmark v3.0.0", false, false),
new Standard("standards/cis-aws-foundations-benchmark/v/5.0.0",
"CIS AWS Foundations Benchmark v5.0.0", false, false),
new Standard("standards/nist-800-53/v/5.0.0",
"NIST Special Publication 800-53 Revision 5", false, false),
new Standard("standards/pci-dss/v/3.2.1", "PCI DSS v3.2.1", false, false),
new Standard("standards/pci-dss/v/4.0.1", "PCI DSS v4.0.1", false, false),
new Standard("standards/aws-resource-tagging-standard/v/1.0.0",
"AWS Resource Tagging Standard v1.0.0", false, false));
public String standardsArn(String region, Standard standard) {
return standard.global()
? AwsArnUtils.Arn.global(regionResolver.partitionForRegion(region), "securityhub", "", standard.path()).toString()
: regionResolver.buildArn("securityhub", region, "", standard.path());
}
public String subscriptionArn(String region, Standard standard) {
return regionResolver.buildArn("securityhub", region,
"subscription/" + standard.path().substring(standard.path().indexOf('/') + 1));
}
/** BatchEnableStandards: subscribes each requested standard; enabling one twice is not an error. */
public synchronized Map<String, String> enableStandards(String region, JsonNode request) {
SecurityHubState state = requireSubscribed(region);
JsonNode requests = request == null ? null : request.get("StandardsSubscriptionRequests");
if (requests == null || !requests.isArray() || requests.isEmpty() || requests.size() > 25) {
throw invalid("StandardsSubscriptionRequests must hold 1 to 25 requests.");
}
Map<String, String> enabled = new LinkedHashMap<>();
for (JsonNode entry : requests) {
String arn = text(entry, "StandardsArn");
Standard standard = STANDARDS.stream().filter(s -> standardsArn(region, s).equals(arn)).findFirst()
.orElseThrow(() -> invalid("StandardsArn " + arn + " is not a standard Security Hub offers in "
+ region + "."));
enabled.put(subscriptionArn(region, standard), arn);
}
state.getStandardsSubscriptions().putAll(enabled);
save(region, state);
return enabled;
}
/** BatchDisableStandards: removes the named subscriptions and reports each as DELETING. */
public synchronized Map<String, String> disableStandards(String region, JsonNode request) {
SecurityHubState state = requireSubscribed(region);
JsonNode arns = request == null ? null : request.get("StandardsSubscriptionArns");
if (arns == null || !arns.isArray() || arns.isEmpty() || arns.size() > 25) {
throw invalid("StandardsSubscriptionArns must hold 1 to 25 ARNs.");
}
// Every ARN is checked before any is removed: the state is the live stored object, so a
// removal before a later ARN failed would stick in memory without ever being saved.
Map<String, String> removed = new LinkedHashMap<>();
for (JsonNode arn : arns) {
String standardsArn = state.getStandardsSubscriptions().get(arn.asText());
if (standardsArn == null) {
throw new AwsException("ResourceNotFoundException",
"Standards subscription " + arn.asText() + " was not found.", 404);
}
removed.put(arn.asText(), standardsArn);
}
removed.keySet().forEach(state.getStandardsSubscriptions()::remove);
save(region, state);
return removed;
}
/** GetEnabledStandards: every subscription, or only the named ones. */
public synchronized Map<String, String> enabledStandards(String region, JsonNode request) {
SecurityHubState state = requireSubscribed(region);
JsonNode arns = request == null ? null : request.get("StandardsSubscriptionArns");
Map<String, String> result = new LinkedHashMap<>();
state.getStandardsSubscriptions().forEach((subscription, standard) -> {
boolean wanted = arns == null || !arns.isArray() || arns.isEmpty();
if (!wanted) {
for (JsonNode arn : arns) {
wanted |= subscription.equals(arn.asText());
}
}
if (wanted) {
result.put(subscription, standard);
}
});
return result;
}
private SecurityHubState requireSubscribed(String region) {
SecurityHubState state = state(region);
if (!state.isEnabled()) {
throw invalidAccess("Account " + regionResolver.getAccountId() + " is not subscribed to AWS Security Hub");
}
return state;
}
public synchronized void updateSecurityHubConfiguration(String region, JsonNode request) {
requireEnabled(region);
SecurityHubState state = state(region);
@@ -150,8 +266,8 @@ public class SecurityHubService implements Resettable {
}
String mode = requireLinkingMode(request);
JsonNode regions = validateAggregatorRegions(mode, request.get("Regions"));
state.setAggregatorArn(AwsArnUtils.Arn.of("securityhub", region, regionResolver.getAccountId(),
"finding-aggregator/" + UUID.randomUUID()).toString());
state.setAggregatorArn(regionResolver.buildArn("securityhub", region,
"finding-aggregator/" + UUID.randomUUID()));
state.setRegionLinkingMode(mode);
state.setRegions(regions);
save(region, state);
@@ -520,11 +636,11 @@ public class SecurityHubService implements Resettable {
}
public String hubArn(String region) {
return AwsArnUtils.Arn.of("securityhub", region, regionResolver.getAccountId(), "hub/default").toString();
return regionResolver.buildArn("securityhub", region, "hub/default");
}
public String policyArn(String region, String id) {
return AwsArnUtils.Arn.of("securityhub", region, regionResolver.getAccountId(), "configuration-policy/" + id).toString();
return regionResolver.buildArn("securityhub", region, "configuration-policy/" + id);
}
private static SecurityHubState copyConfigurationState(SecurityHubState source) {
@@ -26,11 +26,17 @@ public class SecurityHubState {
private int organizationConfigurationPendingPollsRemaining;
private Map<String, JsonNode> policies = new LinkedHashMap<>();
private Map<String, SecurityHubAssociation> associations = new LinkedHashMap<>();
/** Enabled standards: subscription ARN to standards ARN. */
private Map<String, String> standardsSubscriptions = new LinkedHashMap<>();
public String getAdminAccountId() { return adminAccountId; }
public void setAdminAccountId(String adminAccountId) { this.adminAccountId = adminAccountId; }
public String getAdminFeature() { return adminFeature; }
public void setAdminFeature(String adminFeature) { this.adminFeature = adminFeature; }
public Map<String, String> getStandardsSubscriptions() { return standardsSubscriptions; }
public void setStandardsSubscriptions(Map<String, String> value) {
standardsSubscriptions = value == null ? new LinkedHashMap<>() : value;
}
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
public boolean isAutoEnable() { return autoEnable; }
@@ -10,13 +10,13 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class SecurityHubServiceTest {
private static final String REGION = "us-east-1";
@@ -27,10 +27,8 @@ class SecurityHubServiceTest {
@BeforeEach
void setUp() {
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn(ACCOUNT_ID);
when(regionResolver.getPartition()).thenReturn("aws");
service = new SecurityHubService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID), regionResolver,
service = new SecurityHubService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID),
new RegionResolver(REGION, ACCOUNT_ID),
mock(OrganizationsService.class));
}
@@ -49,6 +47,116 @@ class SecurityHubServiceTest {
assertEquals(Map.of("env", "test"), service.tagsForResource(REGION, service.hubArn(REGION)));
}
@Test
void enablingTheHubSubscribesTheDefaultStandardsUnlessToldNotTo() throws Exception {
service.enableSecurityHub(REGION, objectMapper.readTree("{}"));
assertEquals(Set.of(
"arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0",
"arn:aws:securityhub:us-east-1::standards/aws-foundational-security-best-practices/v/1.0.0"),
Set.copyOf(service.enabledStandards(REGION, null).values()));
}
@Test
void aNonBooleanEnableDefaultStandardsIsRejectedAndLeavesTheHubDisabled() throws Exception {
for (String value : new String[] {"\"false\"", "{}", "0"}) {
AwsException error = assertThrows(AwsException.class, () -> service.enableSecurityHub(REGION,
objectMapper.readTree("{\"EnableDefaultStandards\": " + value + "}")), value);
assertEquals("InvalidInputException", error.getErrorCode(), value);
assertFalse(service.state(REGION).isEnabled(), value);
}
}
@Test
void anExplicitlyTrueOrNullEnableDefaultStandardsSubscribesTheDefaults() throws Exception {
for (String value : new String[] {"true", "null"}) {
service.clear();
service.enableSecurityHub(REGION, objectMapper.readTree("{\"EnableDefaultStandards\": " + value + "}"));
assertEquals(2, service.enabledStandards(REGION, null).size(), value);
}
}
@Test
void aBatchDisableWithAnUnknownArnRemovesNothing() throws Exception {
service.enableSecurityHub(REGION, objectMapper.readTree("{}"));
Map<String, String> before = service.enabledStandards(REGION, null);
String valid = before.keySet().iterator().next();
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class, () -> service.disableStandards(
REGION, objectMapper.readTree("{\"StandardsSubscriptionArns\": [\"" + valid + "\", \"arn:aws:"
+ "securityhub:us-east-1:" + ACCOUNT_ID + ":subscription/made-up/v/1.0.0\"]}")))
.getErrorCode());
assertEquals(before, service.enabledStandards(REGION, null), "the valid subscription is still there");
}
@Test
void standardsSubscriptionsCanBeEnabledListedAndDisabled() throws Exception {
assertEquals("InvalidAccessException", assertThrows(AwsException.class,
() -> service.enabledStandards(REGION, null)).getErrorCode(), "the hub must be enabled first");
service.enableSecurityHub(REGION, objectMapper.readTree("{\"EnableDefaultStandards\": false}"));
assertTrue(service.enabledStandards(REGION, null).isEmpty());
String nist = "arn:aws:securityhub:us-east-1::standards/nist-800-53/v/5.0.0";
Map<String, String> enabled = service.enableStandards(REGION, objectMapper.readTree(
"{\"StandardsSubscriptionRequests\": [{\"StandardsArn\": \"" + nist + "\"}]}"));
String subscription = "arn:aws:securityhub:us-east-1:" + ACCOUNT_ID + ":subscription/nist-800-53/v/5.0.0";
assertEquals(Map.of(subscription, nist), enabled);
assertEquals(Map.of(subscription, nist), service.enabledStandards(REGION, objectMapper.readTree(
"{\"StandardsSubscriptionArns\": [\"" + subscription + "\"]}")));
assertEquals("InvalidInputException", assertThrows(AwsException.class, () -> service.enableStandards(REGION,
objectMapper.readTree("{\"StandardsSubscriptionRequests\": [{\"StandardsArn\": \"arn:aws:securityhub:"
+ "us-east-1::standards/made-up/v/1.0.0\"}]}"))).getErrorCode());
assertEquals(Map.of(subscription, nist), service.disableStandards(REGION, objectMapper.readTree(
"{\"StandardsSubscriptionArns\": [\"" + subscription + "\"]}")));
assertTrue(service.enabledStandards(REGION, null).isEmpty());
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class, () -> service.disableStandards(
REGION, objectMapper.readTree("{\"StandardsSubscriptionArns\": [\"" + subscription + "\"]}")))
.getErrorCode());
}
@Test
void cisFiveCanBeEnabledListedAndDisabledButIsNotADefault() throws Exception {
service.enableSecurityHub(REGION, objectMapper.readTree("{}"));
String cis5 = "arn:aws:securityhub:us-east-1::standards/cis-aws-foundations-benchmark/v/5.0.0";
assertFalse(service.enabledStandards(REGION, null).containsValue(cis5));
Map<String, String> enabled = service.enableStandards(REGION, objectMapper.readTree(
"{\"StandardsSubscriptionRequests\": [{\"StandardsArn\": \"" + cis5 + "\"}]}"));
String subscription = "arn:aws:securityhub:us-east-1:" + ACCOUNT_ID
+ ":subscription/cis-aws-foundations-benchmark/v/5.0.0";
assertEquals(Map.of(subscription, cis5), enabled);
assertEquals(cis5, service.enabledStandards(REGION, null).get(subscription));
assertEquals(Map.of(subscription, cis5), service.disableStandards(REGION, objectMapper.readTree(
"{\"StandardsSubscriptionArns\": [\"" + subscription + "\"]}")));
assertFalse(service.enabledStandards(REGION, null).containsKey(subscription));
}
/** A region the catalog cannot place keeps the deployment's partition, not {@code aws}. */
@Test
void arnsTakeTheDeploymentPartitionForAnUnknownRegion() throws Exception {
SecurityHubService china = new SecurityHubService(AccountAwareStorageBackend.inMemory(ACCOUNT_ID),
new RegionResolver("cn-north-1", ACCOUNT_ID), mock(OrganizationsService.class));
String region = "local-1";
china.enableSecurityHub(region, objectMapper.readTree("{\"Tags\": {\"env\": \"test\"}}"));
String cis12 = "arn:aws-cn:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0";
assertEquals(Map.of(
"arn:aws-cn:securityhub:local-1:" + ACCOUNT_ID + ":subscription/cis-aws-foundations-benchmark/v/1.2.0",
cis12,
"arn:aws-cn:securityhub:local-1:" + ACCOUNT_ID
+ ":subscription/aws-foundational-security-best-practices/v/1.0.0",
"arn:aws-cn:securityhub:local-1::standards/aws-foundational-security-best-practices/v/1.0.0"),
china.enabledStandards(region, null));
String hub = "arn:aws-cn:securityhub:local-1:" + ACCOUNT_ID + ":hub/default";
assertEquals(hub, china.hubArn(region));
assertEquals(Map.of("env", "test"), china.tagsForResource(region, hub), "the hub's own ARN resolves");
assertEquals(1, china.enableStandards(region, objectMapper.readTree(
"{\"StandardsSubscriptionRequests\": [{\"StandardsArn\": \"" + cis12 + "\"}]}")).size());
}
/** An account id is scoped to its partition: a China ARN of the same account names nothing here. */
@Test
void aResourceArnFromAnotherPartitionIsNotFound() throws Exception {