AWSTemplateFormatVersion: '2010-09-09' Description: > SpikeCatcher — single account install. Creates a read-only IAM role (Signal 2) and EventBridge forwarding rules across all enabled regions (Signal 1). Deploy this in each account you want SpikeCatcher to monitor. # ===== BEGIN SECURITY AND DATA SCOPE (shared text, identical in every install template; tests/test_template_comments.py) ===== # # What this template does, for a security review: # # 1. READ ROLE (Signal 2). Creates SpikeCatcherReadOnlyRole. It can read billing, usage and resource # CONFIGURATION metadata so SpikeCatcher can detect cost anomalies and find savings. Every permission is an # explicit action in the allow-list below (no wildcards such as ce:* or ReadOnlyAccess) and each group has a # comment saying why it is needed. The role cannot create, change or delete anything, cannot read S3 objects, # secrets, parameters, log contents or database contents, and has no write access to your resources. # 2. TRUST. Only roles named CostAnomaly* or cost-anomaly-* inside SpikeCatcher's AWS account (804838452645) can # assume the role, and only with your ExternalId (confused-deputy protection). The ExternalId is generated per # customer and passed to this template as a NoEcho parameter. An IAM user in SpikeCatcher's account cannot # assume the role even if it knew the ExternalId. Every assumption appears in your CloudTrail. # 3. EVENT FORWARDING (Signal 1). Creates EventBridge rules in each enabled region that copy matching AWS API # events to SpikeCatcher's central event bus (us-east-1) so cost-driving and security-relevant changes are # seen in minutes instead of on the next billing refresh. What is forwarded, and why: # - Write/mutating API calls (readOnly = false; read calls are never sent) for the services listed in the # rule: resource creation and changes that drive cost (EC2, RDS, Bedrock, SageMaker, ...), and # credential, key and access changes (IAM, STS, KMS, Secrets Manager, CloudTrail, Lambda, S3) that show a # compromised account running up spend. # - Console sign-in events: used to flag logins from a new country or unusual source IP. # - AssumeRole calls made directly by a person or program (not by an AWS service, and not by SpikeCatcher # itself): used to flag unexpected role assumption. # - GuardDuty findings (severity 4 and above) and Security Hub findings (HIGH/CRITICAL, NEW, ACTIVE): used to # relate a cost spike to an active threat. Only findings that already exist in your account are forwarded. # - Defense-evasion API calls (for example DeleteDetector, StopConfigurationRecorder, DeleteLogGroup, # LeaveOrganization): attackers disable monitoring before mining or exfiltrating. # Each forwarded event is a CloudTrail record. It can include the caller identity (ARN and type), source IP, # resource identifiers and the request parameters. It does not include secret values, object contents, or # log contents. SpikeCatcher stores these records per customer; retention depends on your plan (30 days to # unlimited) and everything is deleted within 30 days of cancellation. Details and sub-processors: # https://spikecatcher.com/security # 4. CODE. The Lambda that creates the rules is inline (ZipFile) in this template, so you can read every line # before deploying. Nothing is downloaded at deploy time. # 5. REMOVAL. Deleting the CloudFormation stack deletes the role and every rule, in every region. # # To narrow the scope, deploy to a test account first and inspect the rules named spikecatcher-signal1-*. # # ===== END SECURITY AND DATA SCOPE ===== Parameters: ExternalId: Type: String NoEcho: true MinLength: 8 Description: > Pre-filled by SpikeCatcher — do not change. This unique ID secures the trust relationship between your account and SpikeCatcher (confused deputy prevention). SpikeCatcherAccountId: Type: String Default: '804838452645' AllowedValues: - '804838452645' Description: AWS account ID of the SpikeCatcher SaaS service — do not change. SpikeCatcherCentralBusArn: Type: String Default: 'arn:aws:events:us-east-1:804838452645:event-bus/cost-anomaly-central-production' AllowedValues: - 'arn:aws:events:us-east-1:804838452645:event-bus/cost-anomaly-central-production' Description: ARN of the SpikeCatcher central EventBridge bus — do not change. EnableLambdaChecks: Type: String Default: 'false' AllowedValues: ['false', 'true'] Description: > Optional. Set to 'true' to let SpikeCatcher list your Lambda functions so it can recommend moving x86_64 functions to arm64. AWS has no Lambda list permission that hides environment variables, so enabling this lets SpikeCatcher read them. Leave 'false' unless you want that recommendation. Conditions: LambdaChecksEnabled: !Equals [!Ref EnableLambdaChecks, 'true'] Resources: # ── Signal 2: Cross-account IAM role ──────────────────────────────────────── # SpikeCatcher assumes this role to call Cost Explorer in your account daily. SpikeCatcherRole: Type: AWS::IAM::Role Properties: RoleName: SpikeCatcherReadOnlyRole Description: Read-only role for SpikeCatcher anomaly detection (Signal 2 - Cost Explorer) AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: AWS: !Sub 'arn:aws:iam::${SpikeCatcherAccountId}:root' Action: sts:AssumeRole Condition: StringEquals: sts:ExternalId: !Ref ExternalId # Only SpikeCatcher's application roles (Lambda execution roles) may assume this role. An IAM user or # any other identity in the SpikeCatcher account cannot, even holding the ExternalId. ArnLike: aws:PrincipalArn: - !Sub 'arn:aws:iam::${SpikeCatcherAccountId}:role/CostAnomaly*' - !Sub 'arn:aws:iam::${SpikeCatcherAccountId}:role/cost-anomaly-*' Tags: - Key: spikecatcher:template-version Value: '66' Policies: - PolicyName: SpikeCatcherReadOnly PolicyDocument: Version: '2012-10-17' Statement: # Billing and usage data (Cost Explorer). Core of anomaly detection. Explicit actions only. - Sid: CostExplorerRead Effect: Allow Action: - ce:GetCostAndUsage - ce:GetCostAndUsageWithResources - ce:GetCostForecast - ce:GetDimensionValues - ce:GetReservationUtilization - ce:GetReservationPurchaseRecommendation - ce:GetRightsizingRecommendation - ce:GetSavingsPlansPurchaseRecommendation - ce:GetSavingsPlansUtilization - ce:GetTags - ce:ListCostAllocationTags Resource: '*' # Savings Plan and Reserved Instance coverage and utilization, to find unused commitments. - Sid: CommitmentsRead Effect: Allow Action: - ce:GetSavingsPlansCoverage - ce:GetReservationCoverage - ce:GetSavingsPlansUtilizationDetails - ce:ListSavingsPlansPurchaseRecommendationGeneration - redshift:DescribeReservedNodes - es:DescribeReservedElasticsearchInstances - es:DescribeReservedInstances Resource: '*' # Metrics only (CPU, network, ...) to find idle resources. No log access. - Sid: CloudWatchReadMetrics Effect: Allow Action: - cloudwatch:GetMetricStatistics - cloudwatch:ListMetrics Resource: '*' # Account and organization names/structure so findings are labelled with the right account. Names only. - Sid: AccountRead Effect: Allow Action: - iam:GetAccountSummary - organizations:DescribeAccount - organizations:ListAccounts - organizations:ListAccountsForParent - organizations:ListRoots Resource: '*' # Describe/List calls on resource configuration (type, size, state). cloudtrail:DescribeTrails and GetEventSelectors read trail settings only, to find duplicate trails that cost money. They do not read log contents. - Sid: ResourceDescribe Effect: Allow Action: - ec2:DescribeInstances - ec2:DescribeInstanceTypes - ec2:DescribeVolumes - ec2:DescribeAddresses - ec2:DescribeNatGateways - ec2:DescribeReservedInstances - ec2:DescribeSnapshots - ec2:DescribeRegions - rds:DescribeDBInstances - rds:DescribeDBClusters - rds:DescribeReservedDBInstances - rds:DescribeDBSnapshots - elasticache:DescribeCacheClusters - elasticache:DescribeReplicationGroups - elasticache:DescribeReservedCacheNodes - savingsplans:DescribeSavingsPlans - savingsplans:DescribeSavingsPlanRates - es:ListDomainNames - es:DescribeElasticsearchDomain - es:DescribeDomain - cloudtrail:DescribeTrails - cloudtrail:GetEventSelectors - ecs:DescribeServices - ecs:DescribeClusters - ecs:ListServices - ecs:ListClusters Resource: '*' # Bucket-level settings (lifecycle, tiering, versioning, location) to find storage savings. Cannot read or list objects. - Sid: S3OptimizationRead Effect: Allow Action: - s3:ListAllMyBuckets - s3:GetBucketLocation - s3:GetLifecycleConfiguration - s3:GetIntelligentTieringConfiguration - s3:GetBucketVersioning Resource: '*' # Lets SpikeCatcher check that its own spikecatcher-signal1-* rules exist. Scoped to those rule names. - Sid: Signal1RuleHealthCheck Effect: Allow Action: - events:DescribeRule - events:ListRules Resource: 'arn:aws:events:*:*:rule/spikecatcher-signal1-*' # Trusted Advisor cost-optimization check results. - Sid: TrustedAdvisorRead Effect: Allow Action: - support:DescribeTrustedAdvisorChecks - support:DescribeTrustedAdvisorCheckResult Resource: '*' # IAM credential report: one CSV of users, key ages, last use and MFA status, used for security hygiene findings. It contains no passwords, secret keys or key IDs. - Sid: IamHygieneRead Effect: Allow Action: - iam:GenerateCredentialReport - iam:GetCredentialReport Resource: '*' # Compute Optimizer rightsizing recommendations (read only). - Sid: ComputeOptimizerRead Effect: Allow Action: - compute-optimizer:GetEC2InstanceRecommendations - compute-optimizer:GetEBSVolumeRecommendations - compute-optimizer:GetLambdaFunctionRecommendations - compute-optimizer:GetRDSDatabaseRecommendations - compute-optimizer:GetECSServiceRecommendations - compute-optimizer:GetEnrollmentStatus Resource: '*' # Lets SpikeCatcher read the version tag on its own role to tell you when a template update is available. - Sid: TemplateVersionProbe Effect: Allow Action: - iam:GetRole Resource: 'arn:aws:iam::*:role/SpikeCatcherReadOnlyRole' - !If - LambdaChecksEnabled - Sid: LambdaOptimizationRead Effect: Allow Action: - lambda:ListFunctions - lambda:ListProvisionedConcurrencyConfigs Resource: '*' - !Ref AWS::NoValue # ── Signal 1: EventBridge forwarding role (used by rules in every region) ─── SpikeCatcherForwarderRole: Type: AWS::IAM::Role Properties: RoleName: SpikeCatcherEventBridgeForwarderRole Description: Allows EventBridge to forward cost events to SpikeCatcher central bus (all regions) AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: events.amazonaws.com Action: sts:AssumeRole Policies: - PolicyName: PutEventsToSpikeCatcherBus PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: events:PutEvents Resource: !Ref SpikeCatcherCentralBusArn # ── Signal 1: Custom Resource Lambda role ─────────────────────────────────── SignalOneDeployerRole: Type: AWS::IAM::Role Properties: RoleName: SpikeCatcherSignal1DeployerRole Description: Allows the Signal 1 deployer Lambda to create EventBridge rules in all enabled regions AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: lambda.amazonaws.com Action: sts:AssumeRole Policies: - PolicyName: Signal1DeployerPolicy PolicyDocument: Version: '2012-10-17' Statement: - Sid: EventBridgeRules Effect: Allow Action: - events:PutRule - events:PutTargets - events:DeleteRule - events:RemoveTargets - events:DescribeRule - events:ListTargetsByRule Resource: 'arn:aws:events:*:*:rule/spikecatcher-signal1-*' # Lists enabled regions so every region is covered. - Sid: DescribeRegions Effect: Allow Action: - ec2:DescribeRegions Resource: '*' - Sid: PassForwarderRole Effect: Allow Action: - iam:PassRole Resource: !GetAtt SpikeCatcherForwarderRole.Arn - Sid: CloudWatchLogs Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: '*' # ── Signal 1: Custom Resource Lambda ──────────────────────────────────────── SignalOneDeployerFunction: Type: AWS::Lambda::Function Properties: FunctionName: SpikeCatcherSignal1Deployer Description: Custom Resource — deploys EventBridge forwarding rules in all enabled regions Runtime: python3.12 Handler: index.handler Role: !GetAtt SignalOneDeployerRole.Arn Timeout: 300 Environment: Variables: CENTRAL_BUS_ARN: !Ref SpikeCatcherCentralBusArn FORWARDER_ROLE_ARN: !GetAtt SpikeCatcherForwarderRole.Arn Code: ZipFile: | import json import os import urllib.request import boto3 RULE_NAME_PREFIX = 'spikecatcher-signal1-' # BEGIN GENERATED from infra/signal1_sources.yaml by scripts/build_templates.py (do not edit by hand) EVENT_PATTERN = json.dumps({ "source": [ "aws.ec2", "aws.rds", "aws.elasticache", "aws.ecs", "aws.eks", "aws.es", "aws.sagemaker", "aws.redshift", "aws.kinesis", "aws.elasticloadbalancing", "aws.dms", "aws.kafka", "aws.emr", "aws.apprunner", "aws.batch", "aws.groundstation", "aws.memorydb", "aws.bedrock", "aws.fsx", "aws.airflow", "aws.grafana", "aws.globalaccelerator", "aws.appstream", "aws.elasticfilesystem", "aws.aoss", "aws.medialive", "aws.network-firewall", "aws.transfer", "aws.workspaces", "aws.directconnect", "aws.managedblockchain", "aws.cloudfront", "aws.wafv2", "aws.apigateway", "aws.route53", "aws.cloudtrail", "aws.iam", "aws.sts", "aws.lambda", "aws.ses", "aws.secretsmanager", "aws.s3", "aws.kms", "aws.ssm", "aws.glue", "aws.savingsplans" ], "detail-type": ["AWS API Call via CloudTrail"], "detail": { "readOnly": [False], "eventName": [{"anything-but": "AssumeRole"}] } }, separators=(',', ':')) EVASION_PATTERN = json.dumps({ "source": ["aws.guardduty", "aws.config", "aws.securityhub", "aws.logs", "aws.organizations"], "detail-type": ["AWS API Call via CloudTrail"], "detail": {"$or": [ {"eventSource": ["guardduty.amazonaws.com"], "eventName": ["DeleteDetector", "UpdateDetector"]}, {"eventSource": ["config.amazonaws.com"], "eventName": ["StopConfigurationRecorder", "DeleteConfigurationRecorder", "DeleteDeliveryChannel"]}, {"eventSource": ["securityhub.amazonaws.com"], "eventName": ["DisableSecurityHub", "BatchDisableStandards"]}, {"eventSource": ["logs.amazonaws.com"], "eventName": ["DeleteLogGroup"]}, {"eventSource": ["organizations.amazonaws.com"], "eventName": ["LeaveOrganization", "RemoveAccountFromOrganization", "DeleteOrganization"]} ]} }, separators=(',', ':')) # END GENERATED ASSUME_ROLE_PATTERN = json.dumps({ "source": ["aws.sts"], "detail-type": ["AWS API Call via CloudTrail"], "detail": { "eventName": ["AssumeRole"], "userIdentity": { "invokedBy": [{"exists": False}], "accountId": [{"anything-but": "804838452645"}] } } }, separators=(',', ':')) SIGNIN_PATTERN = json.dumps({ "source": ["aws.signin"], "detail-type": ["AWS Console Sign In via CloudTrail"] }, separators=(',', ':')) GUARDDUTY_PATTERN = json.dumps({ "source": ["aws.guardduty"], "detail-type": ["GuardDuty Finding"], "detail": {"severity": [{"numeric": [">=", 4]}]} }, separators=(',', ':')) SECURITYHUB_PATTERN = json.dumps({ "source": ["aws.securityhub"], "detail-type": ["Security Hub Findings - Imported"], "detail": {"findings": {"Severity": {"Label": ["HIGH", "CRITICAL"]}, "Workflow": {"Status": ["NEW"]}, "RecordState": ["ACTIVE"]}} }, separators=(',', ':')) def get_enabled_regions(): ec2 = boto3.client('ec2', region_name='us-east-1') resp = ec2.describe_regions(Filters=[{'Name': 'opt-in-status', 'Values': ['opt-in-not-required', 'opted-in']}]) return [r['RegionName'] for r in resp['Regions']] def put_rule(region, central_bus_arn, forwarder_role_arn): client = boto3.client('events', region_name=region) for name, pattern in [ (f'{RULE_NAME_PREFIX}{region}', EVENT_PATTERN), (f'{RULE_NAME_PREFIX}assumerole-{region}', ASSUME_ROLE_PATTERN), (f'{RULE_NAME_PREFIX}signin-{region}', SIGNIN_PATTERN), (f'{RULE_NAME_PREFIX}guardduty-{region}', GUARDDUTY_PATTERN), (f'{RULE_NAME_PREFIX}securityhub-{region}', SECURITYHUB_PATTERN), (f'{RULE_NAME_PREFIX}evasion-{region}', EVASION_PATTERN), ]: client.put_rule( Name=name, Description='SpikeCatcher Signal 1 — forwards cost-relevant CloudTrail events to central bus', EventPattern=pattern, State='ENABLED' ) client.put_targets( Rule=name, Targets=[{ 'Id': 'SpikeCatcherCentralBus', 'Arn': central_bus_arn, 'RoleArn': forwarder_role_arn }] ) def delete_rule(region): client = boto3.client('events', region_name=region) for rule_name in [f'{RULE_NAME_PREFIX}{region}', f'{RULE_NAME_PREFIX}assumerole-{region}', f'{RULE_NAME_PREFIX}signin-{region}', f'{RULE_NAME_PREFIX}guardduty-{region}', f'{RULE_NAME_PREFIX}securityhub-{region}', f'{RULE_NAME_PREFIX}evasion-{region}']: try: client.remove_targets(Rule=rule_name, Ids=['SpikeCatcherCentralBus']) except client.exceptions.ResourceNotFoundException: pass except Exception: pass try: client.delete_rule(Name=rule_name) except client.exceptions.ResourceNotFoundException: pass except Exception: pass def send_response(event, context, status, data, physical_id, reason=''): body = json.dumps({ 'Status': status, 'Reason': reason or f'See CloudWatch log stream: {context.log_stream_name}', 'PhysicalResourceId': physical_id, 'StackId': event['StackId'], 'RequestId': event['RequestId'], 'LogicalResourceId': event['LogicalResourceId'], 'Data': data }).encode('utf-8') req = urllib.request.Request( url=event['ResponseURL'], data=body, headers={'Content-Type': '', 'Content-Length': len(body)}, method='PUT' ) urllib.request.urlopen(req) def handler(event, context): print(json.dumps(event)) request_type = event['RequestType'] central_bus_arn = os.environ['CENTRAL_BUS_ARN'] forwarder_role_arn = os.environ['FORWARDER_ROLE_ARN'] try: if request_type in ('Create', 'Update'): regions = get_enabled_regions() errors = [] for region in regions: try: put_rule(region, central_bus_arn, forwarder_role_arn) except Exception as e: errors.append(f'{region}: {e}') print(f'WARN: skipping {region}: {e}') # The physical id must NEVER change on Update. CloudFormation treats a different id as a replacement and then # sends Delete for the OLD id, which would remove the rules this very Update just wrote (for example after a # region was opted in). The id only records the regions that existed at Create; Delete also covers later ones. previous_id = event.get('PhysicalResourceId') physical_id = previous_id if request_type == 'Update' and previous_id else ','.join(regions) send_response(event, context, 'SUCCESS', {'RegionCount': len(regions), 'Regions': ','.join(regions)}, physical_id) elif request_type == 'Delete': physical_id = event.get('PhysicalResourceId', '') regions = [r for r in physical_id.split(',') if r] try: regions += [r for r in get_enabled_regions() if r not in regions] except Exception as e: print(f'WARN: could not list enabled regions, deleting rules in recorded regions only: {e}') for region in regions: delete_rule(region) send_response(event, context, 'SUCCESS', {}, physical_id) except Exception as e: print(f'ERROR: {e}') send_response(event, context, 'FAILED', {}, event.get('PhysicalResourceId', 'error'), str(e)) # ── Signal 1: Custom Resource invocation ──────────────────────────────────── SignalOneMultiRegionRules: Type: AWS::CloudFormation::CustomResource DependsOn: - SpikeCatcherForwarderRole - SignalOneDeployerFunction Properties: ServiceToken: !GetAtt SignalOneDeployerFunction.Arn # CloudFormation only re-invokes a custom resource when its own Properties # change — updating SignalOneDeployerFunction's code alone does NOT # re-trigger this. Bump this whenever EVENT_PATTERN changes so customer # stacks re-deploy the rule with the latest pattern. EventPatternVersion: 67 Outputs: RoleArn: Description: Paste this ARN into the SpikeCatcher onboarding wizard to complete setup Value: !GetAtt SpikeCatcherRole.Arn Export: Name: SpikeCatcherRoleArn SignalOneRegions: Description: Number of enabled regions covered by Signal 1 EventBridge rules Value: !GetAtt SignalOneMultiRegionRules.RegionCount