diff --git a/docs/services/index.md b/docs/services/index.md index a4bb65dc5e..f5d52dddfe 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -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 | diff --git a/docs/services/securityhub.md b/docs/services/securityhub.md index 167eb8fc4a..94094a8360 100644 --- a/docs/services/securityhub.md +++ b/docs/services/securityhub.md @@ -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` | - | diff --git a/src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubController.java b/src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubController.java index f322b9613f..a95261097b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubController.java +++ b/src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubController.java @@ -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 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, diff --git a/src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubService.java b/src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubService.java index 3043a0d82c..99c79b17c7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubService.java +++ b/src/main/java/io/github/hectorvent/floci/services/securityhub/SecurityHubService.java @@ -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 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 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 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 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 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 enabledStandards(String region, JsonNode request) { + SecurityHubState state = requireSubscribed(region); + JsonNode arns = request == null ? null : request.get("StandardsSubscriptionArns"); + Map 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) { diff --git a/src/main/java/io/github/hectorvent/floci/services/securityhub/model/SecurityHubState.java b/src/main/java/io/github/hectorvent/floci/services/securityhub/model/SecurityHubState.java index 17cba4fc6c..9785b07974 100644 --- a/src/main/java/io/github/hectorvent/floci/services/securityhub/model/SecurityHubState.java +++ b/src/main/java/io/github/hectorvent/floci/services/securityhub/model/SecurityHubState.java @@ -26,11 +26,17 @@ public class SecurityHubState { private int organizationConfigurationPendingPollsRemaining; private Map policies = new LinkedHashMap<>(); private Map associations = new LinkedHashMap<>(); + /** Enabled standards: subscription ARN to standards ARN. */ + private Map 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 getStandardsSubscriptions() { return standardsSubscriptions; } + public void setStandardsSubscriptions(Map 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; } diff --git a/src/test/java/io/github/hectorvent/floci/services/securityhub/SecurityHubServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/securityhub/SecurityHubServiceTest.java index 9814e520bf..4f1ab84762 100644 --- a/src/test/java/io/github/hectorvent/floci/services/securityhub/SecurityHubServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/securityhub/SecurityHubServiceTest.java @@ -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 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 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 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 {