AWSTemplateFormatVersion: "2010-09-09"
Description: >-
  Sends to Overwing Radar, through a Firehose, the CloudTrail API calls that show what a stolen
  credential does: calls on S3, Secrets Manager and Parameter Store, IAM and identity calls, reads of
  configuration that carries secrets, and every call that was refused. A starting point, written from AWS's documentation and not run in an account of
  Overwing's: read it before you deploy it. It reads nothing but CloudTrail's own events and creates
  no access to your data. Guide: https://overwing.ai/radar/intrusion-response

# Before this is useful:
#   1. A CloudTrail trail must be logging in this region. Object-level S3 calls (GetObject, PutObject,
#      DeleteObject) are data events: they are logged only for the buckets a trail is told to log
#      data events for. Without that, Radar sees listings of buckets and nothing inside them.
#   2. Use an Overwing key of scope "swarm": it can send events and nothing else.
#   3. AWS delivers the calls of its global services (IAM, Organizations, and STS through its global
#      endpoint) to EventBridge in us-east-1. A stack in another region does not see them: deploy this
#      one in us-east-1 as well as in the regions your stores are in.
#   4. Only the calls the connector reads become events and count against your month. The rest of what
#      the rule matches is delivered and skipped.
#
# What it creates: one Firehose delivery stream with an HTTP endpoint destination, one bucket that
# holds deliveries that failed (emptied after seven days), one EventBridge rule, and the two roles
# they need. To remove all of it, delete the stack.

Parameters:
  OverwingKey:
    Type: String
    NoEcho: true
    MinLength: 20
    Description: An Overwing API key of scope swarm. Sent to Overwing as the Firehose access key.
  OverwingUrl:
    Type: String
    Default: https://overwing.ai/api/v1/swarm/connectors/aws
    AllowedPattern: "^https://.+"
    Description: The connector's address.

Resources:
  FailedDeliveries:
    Type: AWS::S3::Bucket
    Properties:
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      LifecycleConfiguration:
        Rules:
          - Id: expire-failed-deliveries
            Status: Enabled
            ExpirationInDays: 7

  FirehoseRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: firehose.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: write-failed-deliveries
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - s3:AbortMultipartUpload
                  - s3:GetBucketLocation
                  - s3:ListBucket
                  - s3:ListBucketMultipartUploads
                  - s3:PutObject
                Resource:
                  - !GetAtt FailedDeliveries.Arn
                  - !Sub "${FailedDeliveries.Arn}/*"

  ToOverwing:
    Type: AWS::KinesisFirehose::DeliveryStream
    Properties:
      DeliveryStreamType: DirectPut
      HttpEndpointDestinationConfiguration:
        EndpointConfiguration:
          Name: overwing-radar
          Url: !Ref OverwingUrl
          AccessKey: !Ref OverwingKey
        # The shortest wait and the smallest buffer: a finding follows the call by one to two minutes.
        BufferingHints:
          IntervalInSeconds: 60
          SizeInMBs: 1
        RequestConfiguration:
          ContentEncoding: NONE
        RetryOptions:
          DurationInSeconds: 300
        RoleARN: !GetAtt FirehoseRole.Arn
        S3BackupMode: FailedDataOnly
        S3Configuration:
          BucketARN: !GetAtt FailedDeliveries.Arn
          RoleARN: !GetAtt FirehoseRole.Arn

  EventsRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: events.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: put-to-firehose
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - firehose:PutRecord
                  - firehose:PutRecordBatch
                Resource: !GetAtt ToOverwing.Arn

  StoreCalls:
    Type: AWS::Events::Rule
    Properties:
      Description: CloudTrail API calls that show what a stolen credential does, to Overwing Radar.
      # Most of what this matches is read-only (GetSecretValue, GetParameter, GetCallerIdentity, every List and
      # Describe). Read-only management calls reach EventBridge only in this state: with plain ENABLED the rule
      # would see writes and nothing an intruder does while it is looking around. Leave the state as it is.
      State: ENABLED_WITH_ALL_CLOUDTRAIL_MANAGEMENT_EVENTS
      EventPattern:
        detail-type:
          - AWS API Call via CloudTrail
        detail:
          # One rule with alternatives, not several rules: a call that fits two of them is delivered once.
          $or:
            # 1. The stores. Every call on S3, Secrets Manager and Parameter Store: reads, writes, deletes and
            #    listings of entries become events, so the sweep detector and your decoys cover them.
            - eventSource:
                - s3.amazonaws.com
                - secretsmanager.amazonaws.com
                - ssm.amazonaws.com
            # 2. Identities. Every IAM and Organizations call: looking through users, roles and policies, and
            #    the changes that make access last (a new access key, a new user, a role's trust policy, an
            #    attached policy, a new identity provider).
            - eventSource:
                - iam.amazonaws.com
                - organizations.amazonaws.com
            # 3. STS, by name: the identity call ("whose key is this?"), the two calls that mint temporary
            #    credentials from a key, and a session opened with an identity provider's token. Plain
            #    AssumeRole is left out: your own services make it constantly and Radar does not read it.
            - eventSource:
                - sts.amazonaws.com
              eventName:
                - GetCallerIdentity
                - GetSessionToken
                - GetFederationToken
                - AssumeRoleWithWebIdentity
            # 4. Reads of configuration that carries secrets in passing: an instance's start-up script, a
            #    function's environment, a task definition, a build project, a stack's template and parameters.
            #    Lambda's records put the date of the API version after the name, hence the prefix; the
            #    connector reads GetFunction and GetFunctionConfiguration and skips the rest.
            - eventSource:
                - ec2.amazonaws.com
              eventName:
                - DescribeInstanceAttribute
            - eventSource:
                - lambda.amazonaws.com
              eventName:
                - prefix: GetFunction
            - eventSource:
                - ecs.amazonaws.com
              eventName:
                - DescribeTaskDefinition
            - eventSource:
                - codebuild.amazonaws.com
              eventName:
                - BatchGetProjects
            - eventSource:
                - cloudformation.amazonaws.com
              eventName:
                - GetTemplate
                - DescribeStacks
            # 5. Any call of any service that was refused for want of permission, and any dry run. A stolen
            #    key is refused on most of what it tries: this is what the denial_burst detector counts.
            - errorCode:
                - AccessDenied
                - AccessDeniedException
                - UnauthorizedOperation
                - Client.UnauthorizedOperation
                - AuthorizationError
                - ForbiddenException
                - Client.DryRunOperation
                - wildcard: "*AccessDenied*"
                - wildcard: "*Unauthorized*"
      Targets:
        - Id: overwing-radar
          Arn: !GetAtt ToOverwing.Arn
          RoleArn: !GetAtt EventsRole.Arn

Outputs:
  DeliveryStream:
    Description: The Firehose that delivers to Overwing. Its monitoring tab shows deliveries and failures.
    Value: !Ref ToOverwing
  FailedDeliveriesBucket:
    Description: Where a delivery Overwing did not accept is kept for seven days.
    Value: !Ref FailedDeliveries
