terraform.aws.security.aws-ec2-has-public-ip.aws-ec2-has-public-ip

profile photo of semgrepsemgrep
Author
unknown
Download Count*

EC2 instances should not have a public IP address attached in order to block public access to the instances. To fix this, set your associate_public_ip_address to "false".

Run Locally

Run in CI

Defintion

rules:
  - id: aws-ec2-has-public-ip
    patterns:
      - pattern-either:
          - pattern: |
              resource "aws_instance" $ANYTHING {
                ...
                associate_public_ip_address = true
                ...
              }
          - pattern: |
              resource "aws_launch_template" $ANYTHING {
                ...
                network_interfaces {
                  ...
                  associate_public_ip_address = true
                  ...
                }
                ...
              }
    message: EC2 instances should not have a public IP address attached in order to
      block public access to the instances. To fix this, set your
      `associate_public_ip_address` to `"false"`.
    metadata:
      category: security
      technology:
        - terraform
        - aws
      owasp:
        - A05:2017 - Broken Access Control
        - A01:2021 - Broken Access Control
      cwe:
        - "CWE-284: Improper Access Control"
      references:
        - https://owasp.org/Top10/A01_2021-Broken_Access_Control
      subcategory:
        - vuln
      likelihood: LOW
      impact: MEDIUM
      confidence: MEDIUM
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
      vulnerability_class:
        - Improper Authorization
    languages:
      - hcl
    severity: WARNING

Examples

aws-ec2-has-public-ip.tf

# pass

# EC2 instance

resource "aws_instance" "default" {
  ami           = "ami-12345"
  instance_type = "t3.micro"
}

resource "aws_instance" "private" {
  ami           = "ami-12345"
  instance_type = "t3.micro"

  associate_public_ip_address = false
}

# launch template

resource "aws_launch_template" "default" {
  image_id      = "ami-12345"
  instance_type = "t3.micro"
}

resource "aws_launch_template" "private" {
  image_id      = "ami-12345"
  instance_type = "t3.micro"

  network_interfaces {
    associate_public_ip_address = false
  }
}

# fail

# EC2 instance
# ruleid: aws-ec2-has-public-ip
resource "aws_instance" "public" {
  ami           = "ami-12345"
  instance_type = "t3.micro"

  associate_public_ip_address = true
}

# launch template
# ruleid: aws-ec2-has-public-ip
resource "aws_launch_template" "public" {
  image_id      = "ami-12345"
  instance_type = "t3.micro"

  network_interfaces {
    associate_public_ip_address = true
  }
}