From c7b259733758f7b3e80c556277b533b5b9c3f73f Mon Sep 17 00:00:00 2001 From: Brian Ojeda <9335829+sgtoj@users.noreply.github.com> Date: Wed, 26 Nov 2025 17:08:22 -0500 Subject: [PATCH] feat: create inital module implementation --- .github/.dependabot.yml | 6 + .github/workflows/release.yml | 34 ++++ .github/workflows/semantic-check.yml | 28 +++ .github/workflows/test.yml | 71 +++++++ .gitignore | 49 +++++ .tflint.hcl | 50 +++++ LICENSE | 21 ++ README.md | 219 +++++++++++++++++++++ assets/lambda-function/Dockerfile | 31 +++ context.tf | 277 +++++++++++++++++++++++++++ examples/complete/README.md | 96 ++++++++++ examples/complete/main.tf | 96 ++++++++++ examples/complete/outputs.tf | 19 ++ examples/complete/variables.tf | 45 +++++ main.tf | 222 +++++++++++++++++++++ outputs.tf | 54 ++++++ variables.tf | 171 +++++++++++++++++ version.tf | 10 + 18 files changed, 1499 insertions(+) create mode 100644 .github/.dependabot.yml create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/semantic-check.yml create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 .tflint.hcl create mode 100644 LICENSE create mode 100644 assets/lambda-function/Dockerfile create mode 100644 context.tf create mode 100644 examples/complete/README.md create mode 100644 examples/complete/main.tf create mode 100644 examples/complete/outputs.tf create mode 100644 examples/complete/variables.tf create mode 100644 main.tf create mode 100644 outputs.tf create mode 100644 variables.tf create mode 100644 version.tf diff --git a/.github/.dependabot.yml b/.github/.dependabot.yml new file mode 100644 index 0000000..1230149 --- /dev/null +++ b/.github/.dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..6bf1aee --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,34 @@ +name: release + +on: + push: + branches: + - main + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-latest + steps: + - name: Checkout Code + # v6.0.0 + uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 + + - name: Bump Version + id: tag_version + # v6.2 + uses: mathieudutour/github-tag-action@d28fa2ccfbd16e871a4bdf35e11b3ad1bd56c0c1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + default_bump: minor + custom_release_rules: bug:patch:Fixes,chore:patch:Chores,docs:patch:Documentation,feat:minor:Features,refactor:minor:Refactors,test:patch:Tests,ci:patch:Development,dev:patch:Development + + - name: Create Release + # v1.20.0 + uses: ncipollo/release-action@b7eabc95ff50cbeeedec83973935c8f306dfcd0b + with: + tag: ${{ steps.tag_version.outputs.new_tag }} + name: ${{ steps.tag_version.outputs.new_tag }} + body: ${{ steps.tag_version.outputs.changelog }} diff --git a/.github/workflows/semantic-check.yml b/.github/workflows/semantic-check.yml new file mode 100644 index 0000000..d68d1c7 --- /dev/null +++ b/.github/workflows/semantic-check.yml @@ -0,0 +1,28 @@ +name: semantic-check +on: + pull_request_target: + types: + - opened + - edited + - synchronize + +permissions: + contents: read + pull-requests: read + +jobs: + main: + name: Semantic Commit Message Check + runs-on: ubuntu-latest + steps: + - name: Checkout Code + # v6.0.0 + uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 + - name: Check PR for Semantic Commit Message + # v6.1.1 + uses: amannn/action-semantic-pull-request@48f256284bd46cdaab1048c3721360e808335d50 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + requireScope: false + validateSingleCommit: true diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..1b7eee6 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,71 @@ +name: test + +on: + pull_request: + branches: [ main ] + push: + branches: [ main ] + +permissions: + contents: read + pull-requests: write + +env: + TF_IN_AUTOMATION: true + +jobs: + lint: + name: lint + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 + + - name: setup terraform + uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3.1.2 + + - name: Cache Terraform Plugins + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ${{ runner.temp }}/.terraform.d/plugin-cache + key: tf-plugins-${{ runner.os }}-${{ hashFiles('**/.terraform.lock.hcl') }} + + - name: Initialize Terraform + run: terraform init + + - name: Suggest Terraform Format + if: github.event_name == 'pull_request' + uses: reviewdog/action-suggester@fc4b06f8697e1e66bd66703f660005079be0b3dc # v1.24.0 + with: + tool_name: terraform-fmt + level: warning + github_token: ${{ secrets.GITHUB_TOKEN }} + fail_level: error + + - name: Check Terraform Format + if: github.event_name == 'push' + run: terraform fmt -recursive -check + + - name: Validate Terraform + uses: reviewdog/action-terraform-validate@6f4d41dfe9cf0c095aec3d341110eadb4c90c360 # v1.16.1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + reporter: github-pr-review + level: warning + fail_level: error + + # - name: Lint Terraform + # uses: reviewdog/action-tflint@9cbfc0aeae4af75fb73e8d5b6efbcd82e9483532 # v1.25.0 + # with: + # reporter: github-pr-review + # filter_mode: nofilter + # fail_level: error + + - name: Lint GitHub Actions + uses: reviewdog/action-actionlint@2ca4336c1821eaff87db1f72fd3923b3250e0427 # v1.69.0 + with: + reporter: github-pr-check + fail_level: error + filter_mode: nofilter + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2aff888 --- /dev/null +++ b/.gitignore @@ -0,0 +1,49 @@ +# Local .terraform directories +**/.terraform/* + +# .tfstate files +*.tfstate +*.tfstate.* + +# Crash log files +crash.log +crash.*.log + +# Exclude all .tfvars files, which are likely to contain sensitive data +*.tfvars +*.tfvars.json + +# Ignore override files as they are usually used to override resources locally +override.tf +override.tf.json +*_override.tf +*_override.tf.json + +# Include override files you do wish to add to version control using negated pattern +# !example_override.tf + +# Include tfplan files to ignore the plan output of command: terraform plan -out=tfplan +*tfplan* + +# Ignore CLI configuration files +.terraformrc +terraform.rc + +# IDE +.idea/ +.vscode/ +*.swp +*.swo +*~ + +# OS +.DS_Store +Thumbs.db + +# Environment variables +.env +.env.local + +# Build artifacts +dist/ +*.zip diff --git a/.tflint.hcl b/.tflint.hcl new file mode 100644 index 0000000..2c3fcd8 --- /dev/null +++ b/.tflint.hcl @@ -0,0 +1,50 @@ +plugin "terraform" { + enabled = true + preset = "recommended" +} + +plugin "aws" { + enabled = true + version = "0.35.0" + source = "github.com/terraform-linters/tflint-ruleset-aws" +} + +rule "terraform_naming_convention" { + enabled = true +} + +rule "terraform_documented_variables" { + enabled = true +} + +rule "terraform_documented_outputs" { + enabled = true +} + +rule "terraform_typed_variables" { + enabled = true +} + +rule "terraform_unused_declarations" { + enabled = true +} + +rule "terraform_comment_syntax" { + enabled = true +} + +rule "terraform_deprecated_index" { + enabled = true +} + +rule "terraform_deprecated_interpolation" { + enabled = true +} + +rule "terraform_required_version" { + enabled = true +} + +rule "terraform_required_providers" { + enabled = true +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..895c8d4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 CruxStack LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index a1048c7..92a074e 100644 --- a/README.md +++ b/README.md @@ -1 +1,220 @@ # Terraform AWS SecurityHub v2 Bot + +Terraform module that deploys an AWS Lambda function to automatically process +[AWS Security Hub v2 findings](https://docs.aws.amazon.com/securityhub/latest/userguide/ocsf-findings.html) +(OCSF format) with configurable automation rules and optional Slack +notifications. + +## About the Bot + +This Terraform module deploys the [aws-securityhubv2-bot](https://github.com/cruxstack/aws-securityhubv2-bot), +a Go-based Lambda function that automatically processes AWS Security Hub +findings in the OCSF (Open Cybersecurity Schema Framework) format. The bot can +suppress, resolve, or archive findings based on configurable rules and +optionally send notifications to Slack with rich context. + +The bot is built and packaged automatically during `terraform apply` using +Docker from the source repository. You can specify a specific version or use +`latest` to deploy from the main branch. + +## Features + +- Automatically suppress or resolve findings based on configurable rules + (severity, type, tags, accounts, regions) +- Store rules inline (environment variables) or in S3 for large rule sets +- Optional Slack notifications with rich context and remediation links +- Supports GuardDuty, Inspector, Macie, IAM Access Analyzer, and Security Hub + findings +- EventBridge-triggered serverless architecture + +## Usage + +### Basic Example + +```hcl +module "securityhub_bot" { + source = "github.com/cruxstack/terraform-aws-securityhubv2-bot?ref=v1.0.0" + + name = "securityhub-bot" + bot_version = "v0.1.0" # or "latest" for main branch + + rules = [ + { + name = "suppress-low-severity-dev" + enabled = true + filters = { + severity = ["Low"] + accounts = ["123456789012"] + } + action = { + status_id = 3 # suppressed + comment = "Auto-suppressed: Low severity in dev account" + } + skip_notification = true + } + ] + + context = module.this.context +} +``` + +### Complete Example with Slack and S3 + +See the [complete example](./examples/complete) for a full configuration with +Slack notifications and S3 rule storage. + +```hcl +module "securityhub_bot" { + source = "cruxstack/securityhubv2-bot/aws" + + name = "securityhub-bot" + bot_version = "v0.1.0" + + rules = [] + + rules_s3_bucket = { + enabled = true + create = true # create s3 bucket for rules + name = "my-securityhub-rules" + prefix = "rules/" + } + + slack_config = { + enabled = true + token = var.slack_bot_token + channel = "C000XXXXXXX" + } + + aws_console_config = { + access_portal_url = "https://mycompany.awsapps.com/start" + access_role_name = "SecurityAuditor" + securityhub_region = "us-east-1" + } + + context = module.this.context +} +``` + +## Prerequisites + +**Docker** must be installed and running on the machine executing Terraform. +The module automatically builds the Lambda function from the +[aws-securityhubv2-bot](https://github.com/cruxstack/aws-securityhubv2-bot) +repository using Docker during `terraform apply`. + +## Automation Rules + +See [aws-securityhubv2-bot](https://github.com/cruxstack/aws-securityhubv2-bot) +documentation for more information on rules. + +### Rule Configuration + +Rules are defined using the `rules` variable. For large rule sets (>3KB), +enable S3 storage: + +```hcl + rules = [{ + name = "suppress-dev-low-severity" + enabled = true + filters = { + severity = ["Low"] + accounts = ["123456789012"] + } + action = { + status_id = 3 # suppressed + comment = "Auto-suppressed: Low severity in dev" + } + skip_notification = true + }] + + # optional: enable s3 for large rule sets + rules_s3_bucket = { + enabled = true + create = true # set true to create bucket, false to use existing + name = "my-rules-bucket" + prefix = "rules/" + } +``` + +When `create = true`, the module automatically: +- Creates an S3 bucket with versioning and encryption enabled +- Uploads rules defined in the `rules` variable to S3 as individual JSON + files +- Configures appropriate IAM permissions for the Lambda function + +You can also use an existing S3 bucket by setting `create = false` and +providing the bucket name. + +### Filter Options + +| Filter | Type | Example | +|------------------|--------------|-----------------------------------------------| +| `finding_types` | list(string) | `["Execution:Runtime/NewBinaryExecuted"]` | +| `severity` | list(string) | `["Critical", "High", "Medium", "Low"]` | +| `product_name` | list(string) | `["GuardDuty", "Inspector"]` | +| `resource_types` | list(string) | `["AWS::EC2::Instance"]` | +| `resource_tags` | list(object) | `[{name = "Environment", value = "dev"}]` | +| `accounts` | list(string) | `["123456789012"]` | +| `regions` | list(string) | `["us-east-1"]` | + +### OCSF Status IDs + +Based on [OCSF 1.6.0 specification](https://schema.ocsf.io/1.6.0/classes/detection_finding): + +| ID | Status | Description | +| --- | ------------- | -------------------------------------------------------------------------------- | +| 0 | Unknown | The status is unknown | +| 1 | New | The finding is new and yet to be reviewed | +| 2 | In Progress | The finding is under review | +| 3 | Suppressed | The finding was reviewed, determined to be benign or false positive, suppressed | +| 4 | Resolved | The finding was reviewed, remediated and is now considered resolved | +| 5 | Archived | The finding was archived | +| 6 | Deleted | The finding was deleted (e.g., created in error) | +| 99 | Other | The status is not mapped (see status attribute for source-specific value) | + +Common usage: `status_id: 5` (Archived) for accepted behavior, `status_id: 4` (Resolved) for remediated issues, `status_id: 3` (Suppressed) for false positives. + +## Inputs + +| Name | Description | Type | Default | Required | +|---------------------------|--------------------------------------------------------------------------------------------------------------------|--------|---------|----------| +| bot_version | Version of the SecurityHub bot to use. Use 'latest' for the main branch or a specific version tag like 'v0.1.0'. | string | "latest" | no | +| bot_repo | GitHub repository URL for the SecurityHub bot source code. | string | "https://github.com/cruxstack/aws-securityhubv2-bot.git" | no | +| bot_force_rebuild_id | ID to force rebuilding the Lambda function source code. Increment this value to trigger a rebuild. | number | 1 | no | +| lambda_config | Configuration for the SecurityHub bot Lambda function (memory_size, timeout, runtime, architecture, reserved_concurrent_executions). | object | {} | no | +| lambda_log_retention_days | Number of days to retain Lambda function logs in CloudWatch Logs. | number | 30 | no | +| rules | List of automation rules for Security Hub findings. Each rule defines filters, actions, and notification settings. | list(object) | [] | no | +| rules_s3_bucket | S3 bucket configuration for storing automation rules. Set create=true to create a new bucket, or provide an existing bucket name. | object | {enabled = false, create = false} | no | +| slack_config | Slack integration configuration for sending notifications (enabled, token, channel). | object | {} | no | +| aws_console_config | AWS Console URL configuration for generating finding links (base_url, access_portal_url, access_role_name, securityhub_region). | object | {} | no | +| debug_enabled | Enable debug logging in the Lambda function. | bool | false | no | +| eventbridge_rule_config | Configuration for the EventBridge rule that triggers the Lambda function (enabled, event_pattern). | object | {enabled = true, event_pattern = {...}} | no | + +Additional CloudPosse context variables (`namespace`, `environment`, `stage`, `name`, `enabled`, `delimiter`, `attributes`, `tags`, etc.) are inherited from the `cloudposse/label/null` module. See [context.tf](./context.tf) for details. + +## Outputs + +| Name | Description | +|------------------------------|------------------------------------------------------------| +| lambda_function_arn | ARN of the SecurityHub v2 bot Lambda function | +| lambda_function_name | Name of the SecurityHub v2 bot Lambda function | +| lambda_function_qualified_arn | Qualified ARN of the SecurityHub v2 bot Lambda function | +| lambda_role_arn | ARN of the IAM role used by the Lambda function | +| lambda_role_name | Name of the IAM role used by the Lambda function | +| eventbridge_rule_arn | ARN of the EventBridge rule that triggers the Lambda function | +| eventbridge_rule_name | Name of the EventBridge rule that triggers the Lambda function | +| cloudwatch_log_group_name | Name of the CloudWatch Log Group for Lambda function logs | +| cloudwatch_log_group_arn | ARN of the CloudWatch Log Group for Lambda function logs | +| rules_s3_bucket_id | ID of the S3 bucket for rules (if created) | +| rules_s3_bucket_arn | ARN of the S3 bucket for rules (if created) | + +## License + +This module is licensed under the MIT License. See [LICENSE](./LICENSE) for +details. + +## References + +- [AWS Security Hub v2 (OCSF) Documentation](https://docs.aws.amazon.com/securityhub/latest/userguide/ocsf-findings.html) +- [OCSF Schema Specification](https://schema.ocsf.io/1.6.0/classes/detection_finding) +- [Bot Source Repository](https://github.com/cruxstack/aws-securityhubv2-bot) diff --git a/assets/lambda-function/Dockerfile b/assets/lambda-function/Dockerfile new file mode 100644 index 0000000..e80b9e2 --- /dev/null +++ b/assets/lambda-function/Dockerfile @@ -0,0 +1,31 @@ +# --------------------------------------------------------------------- base --- + +FROM golang:1.24-alpine AS base + +ARG BOT_VERSION=latest +ARG BOT_REPO=https://github.com/cruxstack/aws-securityhubv2-bot.git + +WORKDIR /build + +RUN apk add --no-cache git make zip + +RUN if [ "${BOT_VERSION}" = "latest" ]; then \ + git clone --depth 1 ${BOT_REPO} .; \ + else \ + git clone --depth 1 --branch ${BOT_VERSION} ${BOT_REPO} .; \ + fi + +RUN GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build \ + -ldflags="-s -w" \ + -o bootstrap \ + ./cmd/lambda + +# ------------------------------------------------------------------ package --- + +FROM alpine:latest AS package + +COPY --from=base /build/bootstrap /opt/app/dist/bootstrap + +RUN apk add zip \ + && cd /opt/app/dist \ + && zip -r /tmp/package.zip . diff --git a/context.tf b/context.tf new file mode 100644 index 0000000..873244c --- /dev/null +++ b/context.tf @@ -0,0 +1,277 @@ +# +# ONLY EDIT THIS FILE IN github.com/cloudposse/terraform-null-label +# All other instances of this file should be a copy of that one +# +# +# Copy this file from https://github.com/cloudposse/terraform-null-label/blob/master/exports/context.tf +# and then place it in your Terraform module to automatically get +# Cloud Posse's standard configuration inputs suitable for passing +# to Cloud Posse modules. +# +# curl -sL https://raw.githubusercontent.com/cloudposse/terraform-null-label/master/exports/context.tf -o context.tf +# +# Modules should access the whole context as `module.this.context` +# to get the input variables with nulls for defaults, +# for example `context = module.this.context`, +# and access individual variables as `module.this.`, +# with final values filled in. +# +# For example, when using defaults, `module.this.context.delimiter` +# will be null, and `module.this.delimiter` will be `-` (hyphen). +# + +module "this" { + source = "cloudposse/label/null" + version = "0.25.0" # requires Terraform >= 0.13.0 + + enabled = var.enabled + namespace = var.namespace + tenant = var.tenant + environment = var.environment + stage = var.stage + name = var.name + delimiter = var.delimiter + attributes = var.attributes + tags = var.tags + additional_tag_map = var.additional_tag_map + label_order = var.label_order + regex_replace_chars = var.regex_replace_chars + id_length_limit = var.id_length_limit + label_key_case = var.label_key_case + label_value_case = var.label_value_case + descriptor_formats = var.descriptor_formats + labels_as_tags = var.labels_as_tags + + context = var.context +} + +# Copy contents of cloudposse/terraform-null-label/variables.tf here + +variable "context" { + type = any + default = { + enabled = true + namespace = null + tenant = null + environment = null + stage = null + name = null + delimiter = null + attributes = [] + tags = {} + additional_tag_map = {} + regex_replace_chars = null + label_order = [] + id_length_limit = null + label_key_case = null + label_value_case = null + descriptor_formats = {} + # Note: we have to use [] instead of null for unset lists due to + # https://github.com/hashicorp/terraform/issues/28137 + # which was not fixed until Terraform 1.0.0, + # but we want the default to be all the labels in `label_order` + # and we want users to be able to prevent all tag generation + # by setting `labels_as_tags` to `[]`, so we need + # a different sentinel to indicate "default" + labels_as_tags = ["unset"] + } + description = <<-EOT + Single object for setting entire context at once. + See description of individual variables for details. + Leave string and numeric variables as `null` to use default value. + Individual variable settings (non-null) override settings in context object, + except for attributes, tags, and additional_tag_map, which are merged. + EOT + + validation { + condition = lookup(var.context, "label_key_case", null) == null ? true : contains(["lower", "title", "upper"], var.context["label_key_case"]) + error_message = "Allowed values: `lower`, `title`, `upper`." + } + + validation { + condition = lookup(var.context, "label_value_case", null) == null ? true : contains(["lower", "title", "upper", "none"], var.context["label_value_case"]) + error_message = "Allowed values: `lower`, `title`, `upper`, `none`." + } +} + +variable "enabled" { + type = bool + default = null + description = "Set to false to prevent the module from creating any resources" +} + +variable "namespace" { + type = string + default = null + description = "ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique" +} + +variable "tenant" { + type = string + default = null + description = "ID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is for" +} + +variable "environment" { + type = string + default = null + description = "ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'" +} + +variable "stage" { + type = string + default = null + description = "ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'" +} + +variable "name" { + type = string + default = null + description = <<-EOT + ID element. Usually the component or solution name, e.g. 'app' or 'jenkins'. + This is the only ID element not also included as a `tag`. + The "name" tag is set to the full `id` string. There is no tag with the value of the `name` input. + EOT +} + +variable "delimiter" { + type = string + default = null + description = <<-EOT + Delimiter to be used between ID elements. + Defaults to `-` (hyphen). Set to `""` to use no delimiter at all. + EOT +} + +variable "attributes" { + type = list(string) + default = [] + description = <<-EOT + ID element. Additional attributes (e.g. `workers` or `cluster`) to add to `id`, + in the order they appear in the list. New attributes are appended to the + end of the list. The elements of the list are joined by the `delimiter` + and treated as a single ID element. + EOT +} + +variable "labels_as_tags" { + type = set(string) + default = ["default"] + description = <<-EOT + Set of labels (ID elements) to include as tags in the `tags` output. + Default is to include all labels. + Tags with empty values will not be included in the `tags` output. + Set to `[]` to suppress all generated tags. + **Notes:** + The value of the `name` tag, if included, will be the `id`, not the `name`. + Unlike other `null-label` inputs, the initial setting of `labels_as_tags` cannot be + changed in later chained modules. Attempts to change it will be silently ignored. + EOT +} + +variable "tags" { + type = map(string) + default = {} + description = <<-EOT + Additional tags (e.g. `{'BusinessUnit': 'XYZ'}`). + Neither the tag keys nor the tag values will be modified by this module. + EOT +} + +variable "additional_tag_map" { + type = map(string) + default = {} + description = <<-EOT + Additional key-value pairs to add to each map in `tags_as_list_of_maps`. Not added to `tags` or `id`. + This is for some rare cases where resources want additional configuration of tags + and therefore take a list of maps with tag key, value, and additional configuration. + EOT +} + +variable "label_order" { + type = list(string) + default = null + description = <<-EOT + The order in which the labels (ID elements) appear in the `id`. + Defaults to ["namespace", "environment", "stage", "name", "attributes"]. + You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present. + EOT +} + +variable "regex_replace_chars" { + type = string + default = null + description = <<-EOT + Terraform regular expression (regex) string. + Characters matching the regex will be removed from the ID elements. + If not set, `"/[^a-zA-Z0-9-]/"` is used to remove all characters other than hyphens, letters and digits. + EOT +} + +variable "id_length_limit" { + type = number + default = null + description = <<-EOT + Limit `id` to this many characters (minimum 6). + Set to `0` for unlimited length. + Set to `null` for keep the existing setting, which defaults to `0`. + Does not affect `id_full`. + EOT + validation { + condition = var.id_length_limit == null ? true : var.id_length_limit >= 6 || var.id_length_limit == 0 + error_message = "The id_length_limit must be >= 6 if supplied (not null), or 0 for unlimited length." + } +} + +variable "label_key_case" { + type = string + default = null + description = <<-EOT + Controls the letter case of the `tags` keys (label names) for tags generated by this module. + Does not affect keys of tags passed in via the `tags` input. + Possible values: `lower`, `title`, `upper`. + Default value: `title`. + EOT + + validation { + condition = var.label_key_case == null ? true : contains(["lower", "title", "upper"], var.label_key_case) + error_message = "Allowed values: `lower`, `title`, `upper`." + } +} + +variable "label_value_case" { + type = string + default = null + description = <<-EOT + Controls the letter case of ID elements (labels) as included in `id`, + set as tag values, and output by this module individually. + Does not affect values of tags passed in via the `tags` input. + Possible values: `lower`, `title`, `upper` and `none` (no transformation). + Set this to `title` and set `delimiter` to `""` to yield Pascal Case IDs. + Default value: `lower`. + EOT + + validation { + condition = var.label_value_case == null ? true : contains(["lower", "title", "upper", "none"], var.label_value_case) + error_message = "Allowed values: `lower`, `title`, `upper`, `none`." + } +} + +variable "descriptor_formats" { + type = any + default = {} + description = <<-EOT + Describe additional descriptors to be output in the `descriptors` output map. + Map of maps. Keys are names of descriptors. Values are maps of the form + `{ + format = string + labels = list(string) + }` + (Type is `any` so the map values can later be enhanced to provide additional options.) + `format` is a Terraform format string to be passed to the `format()` function. + `labels` is a list of labels, in order, to pass to `format()` function. + Label values will be normalized before being passed to `format()` so they will be + identical to how they appear in `id`. + Default is `{}` (`descriptors` output will be empty). + EOT +} \ No newline at end of file diff --git a/examples/complete/README.md b/examples/complete/README.md new file mode 100644 index 0000000..2b86fd6 --- /dev/null +++ b/examples/complete/README.md @@ -0,0 +1,96 @@ +# Complete Example + +This example demonstrates a full-featured deployment of the SecurityHub v2 bot. + +- Automation rules defined in Terraform (automatically stored in S3) +- Slack notifications enabled +- Custom AWS console configuration for federated access +- EventBridge filtering for high-severity findings only +- Extended log retention (90 days) + +## Prerequisites + +**Slack App**: Create a Slack app with `chat:write` scope and get: +- Bot token (starts with `xoxb-`) +- Channel ID (e.g., `C000XXXXXXX`) + +## Usage + +```bash +# Set required variables +export TF_VAR_rules_s3_bucket="your-rules-bucket" +export TF_VAR_slack_bot_token="xoxb-your-token" +export TF_VAR_slack_channel_id="C000XXXXXXX" + +# Initialize and apply +terraform init +terraform plan +terraform apply +``` + +## Testing + +After deployment, you can test the bot by: + +1. **Trigger a test finding**: Generate a Security Hub finding or wait for one + to be imported +2. **Check CloudWatch Logs**: View logs at `/aws/lambda/ex-prod-securityhub-bot` +3. **Verify Slack notifications**: Check your configured Slack channel +4. **Inspect Security Hub**: Confirm findings matching rules are updated + +## Customization + +### Add More Automation Rules + +```hcl +rules = [ + { + name = "suppress-specific-finding" + enabled = true + filters = { + finding_types = ["Software and Configuration Checks/AWS Security Best Practices"] + resource_types = ["AwsEc2Instance"] + resource_tags = [ + { + name = "Environment" + value = "dev" + } + ] + } + action = { + status_id = 3 + comment = "Auto-suppressed: Dev environment" + } + skip_notification = true + } +] +``` + +### Filter for Specific AWS Services + +```hcl +eventbridge_rule_config = { + enabled = true + event_pattern = { + source = ["aws.securityhub"] + detail-type = ["Findings Imported V2"] + detail = { + findings = { + metadata = { + product = { + name = ["GuardDuty", "Inspector"] + } + } + } + } + } +} +``` + +## Cleanup + +```bash +terraform destroy +``` + +Note: If you created the S3 bucket with `rules_s3_bucket.create = true`, you may need to manually delete the bucket contents before destroying if Terraform cannot empty it automatically. diff --git a/examples/complete/main.tf b/examples/complete/main.tf new file mode 100644 index 0000000..92eb831 --- /dev/null +++ b/examples/complete/main.tf @@ -0,0 +1,96 @@ +module "securityhub_bot" { + source = "../.." + + lambda_config = { + memory_size = 512 + timeout = 120 + } + + bot_version = "latest" + + # Define automation rules directly in Terraform + # The module will automatically create these as objects in the S3 bucket + rules = [ + { + name = "suppress-low-severity-dev" + enabled = true + filters = { + severity = ["Low"] + accounts = ["123456789012"] + } + action = { + status_id = 3 + comment = "Auto-suppressed: Low severity in dev account" + } + skip_notification = true + }, + { + name = "suppress-informational" + enabled = true + filters = { + severity = ["Informational"] + } + action = { + status_id = 3 + comment = "Auto-suppressed: Informational findings" + } + skip_notification = true + } + ] + + rules_s3_bucket = { + enabled = true + create = true + name = var.rules_s3_bucket + prefix = "securityhub-rules/" + } + + slack_config = { + enabled = true + token = var.slack_bot_token + channel = var.slack_channel_id + } + + aws_console_config = { + base_url = "https://console.aws.amazon.com" + access_portal_url = var.aws_access_portal_url + access_role_name = var.aws_access_role_name + securityhub_region = "us-east-1" + } + + debug_enabled = false + lambda_log_retention_days = 90 + + eventbridge_rule_config = { + enabled = true + # Only process Critical and High severity findings + event_pattern = { + source = ["aws.securityhub"] + detail-type = ["Findings Imported V2"] + detail = { + findings = { + severity = ["Critical", "High"] + } + } + } + } + + context = module.this.context +} + +module "this" { + source = "cloudposse/label/null" + version = "0.25.0" + + namespace = var.namespace + environment = var.environment + stage = var.stage + name = "securityhub-bot" + delimiter = "-" + + tags = { + Terraform = "true" + Module = "terraform-aws-securityhubv2-bot" + Example = "complete" + } +} diff --git a/examples/complete/outputs.tf b/examples/complete/outputs.tf new file mode 100644 index 0000000..838a7e3 --- /dev/null +++ b/examples/complete/outputs.tf @@ -0,0 +1,19 @@ +output "lambda_function_arn" { + description = "ARN of the SecurityHub v2 bot Lambda function" + value = module.securityhub_bot.lambda_function_arn +} + +output "lambda_function_name" { + description = "Name of the SecurityHub v2 bot Lambda function" + value = module.securityhub_bot.lambda_function_name +} + +output "eventbridge_rule_arn" { + description = "ARN of the EventBridge rule" + value = module.securityhub_bot.eventbridge_rule_arn +} + +output "cloudwatch_log_group_name" { + description = "Name of the CloudWatch Log Group" + value = module.securityhub_bot.cloudwatch_log_group_name +} diff --git a/examples/complete/variables.tf b/examples/complete/variables.tf new file mode 100644 index 0000000..18186b8 --- /dev/null +++ b/examples/complete/variables.tf @@ -0,0 +1,45 @@ +variable "namespace" { + description = "Namespace for resource naming" + type = string + default = "ex" +} + +variable "environment" { + description = "Environment name" + type = string + default = "prod" +} + +variable "stage" { + description = "Stage name" + type = string + default = "" +} + +variable "rules_s3_bucket" { + description = "S3 bucket containing automation rules" + type = string +} + +variable "slack_bot_token" { + description = "Slack bot token (requires chat:write scope)" + type = string + sensitive = true +} + +variable "slack_channel_id" { + description = "Slack channel ID (e.g., C000XXXXXXX)" + type = string +} + +variable "aws_access_portal_url" { + description = "AWS SSO/Identity Center access portal URL" + type = string + default = "" +} + +variable "aws_access_role_name" { + description = "IAM role name for federated access" + type = string + default = "SecurityAuditor" +} diff --git a/main.tf b/main.tf new file mode 100644 index 0000000..ff25b3b --- /dev/null +++ b/main.tf @@ -0,0 +1,222 @@ +# =================================================================== locals === + +locals { + enabled = module.this.enabled + + aws_account_id = data.aws_caller_identity.current.account_id + aws_region_name = data.aws_region.current.region + aws_partition = data.aws_partition.current.partition + + rules_s3_bucket_name = var.rules_s3_bucket.enabled ? ( + var.rules_s3_bucket.create ? module.rules_s3_bucket[0].bucket_id : var.rules_s3_bucket.name + ) : "" + + lambda_environment = { + APP_DEBUG_ENABLED = tostring(var.debug_enabled) + APP_AUTO_CLOSE_RULES = length(var.rules) > 0 ? jsonencode(var.rules) : null + APP_AUTO_CLOSE_RULES_S3_BUCKET = local.rules_s3_bucket_name + APP_AUTO_CLOSE_RULES_S3_PREFIX = var.rules_s3_bucket.enabled ? var.rules_s3_bucket.prefix : "" + APP_SLACK_TOKEN = var.slack_config.enabled ? var.slack_config.token : "" + APP_SLACK_CHANNEL = var.slack_config.enabled ? var.slack_config.channel : "" + APP_AWS_CONSOLE_URL = var.aws_console_config.base_url + APP_AWS_ACCESS_PORTAL_URL = var.aws_console_config.access_portal_url + APP_AWS_ACCESS_ROLE_NAME = var.aws_console_config.access_role_name + APP_AWS_SECURITYHUBV2_REGION = coalesce(var.aws_console_config.securityhub_region, local.aws_region_name) + } +} + +data "aws_caller_identity" "current" {} +data "aws_region" "current" {} +data "aws_partition" "current" {} + +# ===================================================================== s3 === + +module "rules_s3_bucket" { + source = "cloudposse/s3-bucket/aws" + version = "4.5.0" + + count = local.enabled && var.rules_s3_bucket.enabled && var.rules_s3_bucket.create ? 1 : 0 + + bucket_name = var.rules_s3_bucket.name + versioning_enabled = true + sse_algorithm = "AES256" + force_destroy = false + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true + + context = module.this.context +} + +resource "aws_s3_object" "rules" { + for_each = local.enabled && var.rules_s3_bucket.enabled && length(var.rules) > 0 ? { + for idx, rule in var.rules : rule.name => rule + } : {} + + bucket = local.rules_s3_bucket_name + key = "${var.rules_s3_bucket.prefix}${each.key}.json" + content = jsonencode([each.value]) + content_type = "application/json" + etag = md5(jsonencode([each.value])) + + depends_on = [module.rules_s3_bucket] +} + +# ================================================================== lambda === + +module "bot_artifact" { + source = "github.com/cruxstack/terraform-docker-artifact-packager?ref=v1.4.0" + + count = local.enabled ? 1 : 0 + + attributes = ["lambda"] + artifact_src_path = "/tmp/package.zip" + artifact_dst_directory = "${path.module}/dist" + docker_build_context = abspath("${path.module}/assets/lambda-function") + docker_build_target = "package" + force_rebuild_id = var.bot_force_rebuild_id + + docker_build_args = { + BOT_VERSION = var.bot_version + BOT_REPO = var.bot_repo + } + + context = module.this.context +} + +resource "aws_lambda_function" "this" { + count = local.enabled ? 1 : 0 + + function_name = module.this.id + description = "Processes AWS Security Hub v2 findings with automation rules and optional Slack notifications" + role = aws_iam_role.this[0].arn + handler = "bootstrap" + runtime = var.lambda_config.runtime + memory_size = var.lambda_config.memory_size + timeout = var.lambda_config.timeout + reserved_concurrent_executions = var.lambda_config.reserved_concurrent_executions + architectures = [var.lambda_config.architecture] + + filename = module.bot_artifact[0].artifact_package_path + source_code_hash = filebase64sha256(module.bot_artifact[0].artifact_package_path) + + environment { + variables = local.lambda_environment + } + + depends_on = [ + aws_cloudwatch_log_group.lambda, + aws_iam_role_policy.this + ] + + tags = module.this.tags +} + +resource "aws_cloudwatch_log_group" "lambda" { + count = local.enabled ? 1 : 0 + + name = "/aws/lambda/${module.this.id}" + retention_in_days = var.lambda_log_retention_days + tags = module.this.tags +} + +# --------------------------------------------------------------- eventbridge --- + +resource "aws_cloudwatch_event_rule" "securityhub" { + count = local.enabled && var.eventbridge_rule_config.enabled ? 1 : 0 + + name = module.this.id + description = "Trigger SecurityHub v2 bot on findings imported" + event_pattern = jsonencode(var.eventbridge_rule_config.event_pattern) + tags = module.this.tags +} + +resource "aws_cloudwatch_event_target" "lambda" { + count = local.enabled && var.eventbridge_rule_config.enabled ? 1 : 0 + + rule = aws_cloudwatch_event_rule.securityhub[0].name + target_id = "SecurityHubV2BotLambda" + arn = aws_lambda_function.this[0].arn +} + +resource "aws_lambda_permission" "eventbridge" { + count = local.enabled && var.eventbridge_rule_config.enabled ? 1 : 0 + + statement_id = "AllowExecutionFromEventBridge" + action = "lambda:InvokeFunction" + function_name = aws_lambda_function.this[0].function_name + principal = "events.amazonaws.com" + source_arn = aws_cloudwatch_event_rule.securityhub[0].arn +} + +# ---------------------------------------------------------------------- iam --- + +resource "aws_iam_role" "this" { + count = local.enabled ? 1 : 0 + + name = module.this.id + description = "" + + assume_role_policy = jsonencode({ + Version = "2012-10-17", + Statement = [{ + Effect = "Allow" + Principal = { "Service" : "lambda.amazonaws.com" } + Action = ["sts:AssumeRole", "sts:TagSession"] + }] + }) + + tags = module.this.tags +} + +data "aws_iam_policy_document" "this" { + count = local.enabled ? 1 : 0 + + statement { + sid = "CloudWatchLogsAccess" + effect = "Allow" + actions = [ + "logs:CreateLogGroup", + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + resources = ["arn:${local.aws_partition}:logs:${local.aws_region_name}:${local.aws_account_id}:log-group:/aws/lambda/${module.this.id}:*"] + } + + statement { + sid = "SecurityHubAccess" + effect = "Allow" + actions = [ + "securityhub:BatchUpdateFindings", + "securityhub:BatchUpdateFindingsV2" + ] + resources = ["*"] + } + + dynamic "statement" { + for_each = var.rules_s3_bucket.enabled ? [1] : [] + + content { + sid = "S3RulesAccess" + effect = "Allow" + actions = [ + "s3:GetObject", + "s3:ListBucket" + ] + resources = [ + "arn:${local.aws_partition}:s3:::${local.rules_s3_bucket_name}", + "arn:${local.aws_partition}:s3:::${local.rules_s3_bucket_name}/*" + ] + } + } +} + +resource "aws_iam_role_policy" "this" { + count = local.enabled ? 1 : 0 + + name = module.this.id + role = aws_iam_role.this[0].id + policy = data.aws_iam_policy_document.this[0].json +} + diff --git a/outputs.tf b/outputs.tf new file mode 100644 index 0000000..94ea7d4 --- /dev/null +++ b/outputs.tf @@ -0,0 +1,54 @@ +output "lambda_function_arn" { + description = "ARN of the SecurityHub v2 bot Lambda function" + value = try(aws_lambda_function.this[0].arn, null) +} + +output "lambda_function_name" { + description = "Name of the SecurityHub v2 bot Lambda function" + value = try(aws_lambda_function.this[0].function_name, null) +} + +output "lambda_function_qualified_arn" { + description = "Qualified ARN of the SecurityHub v2 bot Lambda function" + value = try(aws_lambda_function.this[0].qualified_arn, null) +} + +output "lambda_role_arn" { + description = "ARN of the IAM role used by the Lambda function" + value = try(aws_iam_role.this[0].arn, null) +} + +output "lambda_role_name" { + description = "Name of the IAM role used by the Lambda function" + value = try(aws_iam_role.this[0].name, null) +} + +output "eventbridge_rule_arn" { + description = "ARN of the EventBridge rule that triggers the Lambda function" + value = try(aws_cloudwatch_event_rule.securityhub[0].arn, null) +} + +output "eventbridge_rule_name" { + description = "Name of the EventBridge rule that triggers the Lambda function" + value = try(aws_cloudwatch_event_rule.securityhub[0].name, null) +} + +output "cloudwatch_log_group_name" { + description = "Name of the CloudWatch Log Group for Lambda function logs" + value = try(aws_cloudwatch_log_group.lambda[0].name, null) +} + +output "cloudwatch_log_group_arn" { + description = "ARN of the CloudWatch Log Group for Lambda function logs" + value = try(aws_cloudwatch_log_group.lambda[0].arn, null) +} + +output "rules_s3_bucket_id" { + description = "ID of the S3 bucket for rules (if created)" + value = try(module.rules_s3_bucket[0].bucket_id, null) +} + +output "rules_s3_bucket_arn" { + description = "ARN of the S3 bucket for rules (if created)" + value = try(module.rules_s3_bucket[0].bucket_arn, null) +} diff --git a/variables.tf b/variables.tf new file mode 100644 index 0000000..514bc2a --- /dev/null +++ b/variables.tf @@ -0,0 +1,171 @@ +# ================================================================== general === + +variable "bot_version" { + + description = "Version of the SecurityHub bot to use. Use 'latest' for the main branch or a specific version tag like 'v0.1.0'." + type = string + default = "latest" +} + +variable "bot_repo" { + description = "GitHub repository URL for the SecurityHub bot source code." + type = string + default = "https://github.com/cruxstack/aws-securityhubv2-bot.git" +} + +variable "bot_force_rebuild_id" { + description = "ID to force rebuilding the Lambda function source code. Increment this value to trigger a rebuild." + type = string + default = "" +} + +# ------------------------------------------------------------------- lambda --- + +variable "lambda_config" { + description = "Configuration for the SecurityHub bot Lambda function." + type = object({ + memory_size = optional(number, 256) + timeout = optional(number, 60) + runtime = optional(string, "provided.al2023") + architecture = optional(string, "x86_64") + reserved_concurrent_executions = optional(number, -1) + }) + default = {} + + validation { + condition = var.lambda_config.memory_size >= 128 && var.lambda_config.memory_size <= 10240 + error_message = "Lambda memory_size must be between 128 and 10240 MB." + } + + validation { + condition = var.lambda_config.timeout >= 1 && var.lambda_config.timeout <= 900 + error_message = "Lambda timeout must be between 1 and 900 seconds." + } +} + +variable "lambda_log_retention_days" { + description = "Number of days to retain Lambda function logs in CloudWatch Logs." + type = number + default = 30 + + validation { + condition = contains([0, 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653], var.lambda_log_retention_days) + error_message = "Lambda log retention days must be a valid CloudWatch Logs retention period." + } +} + +# ------------------------------------------------------------------- rules --- + +variable "rules" { + description = "List of automation rules for Security Hub findings. Each rule defines filters, actions, and notification settings." + type = list(object({ + name = string + enabled = bool + filters = object({ + finding_types = optional(list(string)) + severity = optional(list(string)) + product_name = optional(list(string)) + resource_types = optional(list(string)) + resource_tags = optional(list(object({ + name = string + value = string + }))) + accounts = optional(list(string)) + regions = optional(list(string)) + }) + action = object({ + status_id = number + comment = string + }) + skip_notification = optional(bool, false) + })) + default = [] + + validation { + condition = alltrue([ + for rule in var.rules : contains([0, 1, 2, 3, 4, 5, 6, 99], rule.action.status_id) + ]) + error_message = "Rule action status_id must be a valid OCSF status (0-6, 99): 0=Unknown, 1=New, 2=In Progress, 3=Suppressed, 4=Resolved, 5=Archived, 6=Deleted, 99=Other." + } + + validation { + condition = !var.rules_s3_bucket.enabled ? length(var.rules) == 0 || length(jsonencode(var.rules)) <= 3276 : true + error_message = "When S3 storage is disabled, the JSON-encoded rules must not exceed 3.2KB (3276 bytes) to stay within Lambda environment variable limits. Current size: ${length(jsonencode(var.rules))} bytes. Consider enabling S3 storage for larger rule sets." + } +} + +variable "rules_s3_bucket" { + description = "S3 bucket configuration for storing automation rules. Set create=true to create a new bucket, or provide an existing bucket name." + type = object({ + enabled = bool + create = optional(bool, false) + name = optional(string) + prefix = optional(string, "rules/") + }) + default = { + enabled = false + create = false + } + + validation { + condition = !var.rules_s3_bucket.enabled || var.rules_s3_bucket.name != null + error_message = "When rules_s3_bucket.enabled is true, name must be specified." + } + + validation { + condition = !var.rules_s3_bucket.create || var.rules_s3_bucket.enabled + error_message = "When rules_s3_bucket.create is true, enabled must also be true." + } +} + +# ------------------------------------------------------------------- slack --- + +variable "slack_config" { + description = "Slack integration configuration for sending notifications." + sensitive = true + type = object({ + enabled = optional(bool, false) + token = optional(string, "") + channel = optional(string, "") + }) + default = {} + + validation { + condition = !var.slack_config.enabled || (var.slack_config.token != null && var.slack_config.channel != null) + error_message = "When slack_config.enabled is true, both token and channel must be specified." + } +} + +# ----------------------------------------------------------------- console --- + +variable "aws_console_config" { + description = "AWS Console URL configuration for generating finding links." + type = object({ + base_url = optional(string, "https://console.aws.amazon.com") + access_portal_url = optional(string, "") + access_role_name = optional(string, "") + securityhub_region = optional(string, "") + }) + default = {} +} + +variable "debug_enabled" { + description = "Enable debug logging in the Lambda function." + type = bool + default = false +} + +variable "eventbridge_rule_config" { + description = "Configuration for the EventBridge rule that triggers the Lambda function." + type = object({ + enabled = optional(bool, true) + event_pattern = any + }) + default = { + event_pattern = { + source = ["aws.securityhub"] + detail-type = ["Findings Imported V2"] + } + } +} + diff --git a/version.tf b/version.tf new file mode 100644 index 0000000..88fefa8 --- /dev/null +++ b/version.tf @@ -0,0 +1,10 @@ +terraform { + required_version = ">= 1.3" + + required_providers { + aws = { + source = "hashicorp/aws" + version = ">= 6.0" + } + } +}