Fairy
Resources

How to Avoid: Security Group Open to 0.0.0.0/0 on Sensitive Ports

August 4, 2026 · 7-minute read · Fairy

The short answer

To prevent security groups open to 0.0.0.0/0 on sensitive ports in AI-generated code, explicitly specify allowed CIDR blocks in your prompts, use infrastructure policy tools like OPA or Checkov to block overly permissive rules, and require bastion host patterns for database and SSH access. Never accept AI-generated security groups without validating ingress rules against your network architecture.

The Direct Answer: Constrain Your Prompts and Validate Every Ingress Rule

Security groups open to 0.0.0.0/0 on sensitive ports represent one of the most dangerous AI code generation failures. To prevent this vulnerability:

  1. Never accept AI-generated security groups without reviewing ingress rules
  2. Explicitly specify allowed CIDR blocks in your prompts — "restrict SSH to 10.0.0.0/8" not "add SSH access"
  3. Enforce bastion host patterns for database and administrative access
  4. Run policy-as-code tools (Checkov, tfsec, OPA) in CI/CD to block overly permissive rules before deployment

This failure mode consistently appears in AI-generated infrastructure code because training data is saturated with tutorials that prioritize "getting it working" over production security. The fix requires explicit constraints at prompt time and automated validation before deployment.

What This Vulnerability Looks Like

When AI generates infrastructure-as-code for resources that need network access, it frequently produces security groups like this:

# AI-GENERATED — DANGEROUS
resource "aws_security_group" "database" {
  name        = "database-sg"
  description = "Allow database access"
  vpc_id      = aws_vpc.main.id

  ingress {
    from_port   = 5432
    to_port     = 5432
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]  # Exposes PostgreSQL to entire internet
  }

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]  # SSH open to everyone
  }
}

This configuration exposes your PostgreSQL database to every IP address on the internet. Automated scanners continuously probe these ports. Once discovered, attackers attempt credential stuffing, exploit known vulnerabilities, or launch brute-force attacks.

The sensitive ports most commonly exposed:

PortServiceRisk When Exposed
22SSHRemote shell access, credential brute-forcing
3389RDPWindows remote access, ransomware entry point
3306MySQLDatabase exfiltration, privilege escalation
5432PostgreSQLFull database access, lateral movement
6379RedisUnauthenticated access (default), data theft
27017MongoDBNo auth by default in older versions, full DB access

Why AI Produces This Failure

AI models generate overly permissive security groups for predictable reasons:

Training Data Bias Toward Tutorials

Most publicly available infrastructure code comes from tutorials, blog posts, and quick-start guides. These sources prioritize getting something working over production hardening. When the prompt is "create a security group for my PostgreSQL database," the model draws from examples where 0.0.0.0/0 was acceptable for learning purposes.

Missing Network Context

AI has no knowledge of your VPC topology, existing bastion hosts, VPN CIDR ranges, or network segmentation strategy. Without this context, it cannot generate appropriate CIDR restrictions. The model cannot ask clarifying questions, so it defaults to the most permissive option that guarantees functionality.

Conflation of Availability with Correctness

AI optimizes for code that will work. From the model's perspective, 0.0.0.0/0 works in all network configurations. A restricted CIDR might fail if it doesn't match your actual network. The model chooses guaranteed functionality over secure-by-default.

Incomplete Security Modeling

This issue connects to broader patterns in AI-generated code. Similar to how AI-generated Supabase tables often lack Row Level Security, AI-generated infrastructure consistently omits defense-in-depth measures. The model produces functionally correct code that lacks the security layers production systems require.

How to Detect This Vulnerability

Static Analysis in CI/CD

Integrate infrastructure security scanners that explicitly flag 0.0.0.0/0 on sensitive ports:

Checkov example:

checkov -d ./terraform --check CKV_AWS_24  # SSH open to internet
checkov -d ./terraform --check CKV_AWS_23  # Security groups allow ingress from 0.0.0.0/0

tfsec example:

tfsec ./terraform --include-passed
# Flags: aws-vpc-no-public-ingress-sgr

Custom OPA Policies

For granular control, write Open Policy Agent rules that match your specific requirements:

package terraform.security_group

sensitive_ports := [22, 3389, 3306, 5432, 6379, 27017]

deny[msg] {
    resource := input.resource.aws_security_group[name]
    ingress := resource.ingress[_]
    ingress.cidr_blocks[_] == "0.0.0.0/0"
    ingress.from_port <= sensitive_ports[_]
    ingress.to_port >= sensitive_ports[_]
    msg := sprintf("Security group '%s' exposes port %d to 0.0.0.0/0", [name, ingress.from_port])
}

Pre-Commit Hooks

Catch issues before they enter version control:

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.83.0
    hooks:
      - id: terraform_checkov
        args: ['--check', 'CKV_AWS_24', '--check', 'CKV_AWS_23']

The Correct Pattern: Principle of Least Privilege

For SSH Access: Bastion Host Pattern

Never allow SSH directly to application or database servers. Use a bastion host:

# Bastion host — SSH only from known admin IPs
resource "aws_security_group" "bastion" {
  name        = "bastion-sg"
  vpc_id      = aws_vpc.main.id

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = var.admin_cidr_blocks  # ["203.0.113.0/24"] — your office/VPN
  }
}

# Database server — SSH only from bastion
resource "aws_security_group" "database" {
  name        = "database-sg"
  vpc_id      = aws_vpc.main.id

  ingress {
    from_port       = 22
    to_port         = 22
    protocol        = "tcp"
    security_groups = [aws_security_group.bastion.id]  # Only bastion can SSH
  }
  
  ingress {
    from_port       = 5432
    to_port         = 5432
    protocol        = "tcp"
    security_groups = [aws_security_group.application.id]  # Only app servers
  }
}

For Database Access: Security Group References

Databases should only accept connections from application security groups, not CIDR blocks:

resource "aws_security_group" "redis" {
  name        = "redis-sg"
  vpc_id      = aws_vpc.main.id

  ingress {
    from_port       = 6379
    to_port         = 6379
    protocol        = "tcp"
    security_groups = [
      aws_security_group.application.id,
      aws_security_group.worker.id
    ]
  }
  
  # No egress to internet — Redis doesn't need it
  egress {
    from_port       = 0
    to_port         = 0
    protocol        = "-1"
    security_groups = [aws_security_group.application.id]
  }
}

Variable-Driven CIDR Restrictions

When CIDR blocks are necessary, use variables with validation:

variable "allowed_ssh_cidrs" {
  type        = list(string)
  description = "CIDR blocks allowed to SSH. Never use 0.0.0.0/0"
  
  validation {
    condition     = !contains(var.allowed_ssh_cidrs, "0.0.0.0/0")
    error_message = "SSH access cannot be open to 0.0.0.0/0"
  }
}

How to Prompt AI for Secure Security Groups

The quality of AI-generated infrastructure depends heavily on prompt specificity. Compare these prompts:

Weak prompt:

Create a security group for my PostgreSQL RDS instance

Strong prompt:

Create a Terraform security group for PostgreSQL RDS with these constraints:

  • Port 5432 ingress only from security group "app-servers-sg"
  • No SSH access (managed via AWS Systems Manager)
  • No direct internet ingress on any port
  • Include a validation that blocks 0.0.0.0/0 on any ingress rule

The strong prompt explicitly excludes the failure mode. AI can follow constraints; it just needs them stated.

Automation: Making the Failure Impossible

Beyond detection, architect your infrastructure to prevent this class of vulnerability:

AWS Service Control Policies

Block overly permissive security groups at the organization level:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyOpenSecurityGroups",
      "Effect": "Deny",
      "Action": [
        "ec2:AuthorizeSecurityGroupIngress",
        "ec2:CreateSecurityGroup"
      ],
      "Resource": "*",
      "Condition": {
        "ForAnyValue:IpAddress": {
          "ec2:Cidr": "0.0.0.0/0"
        }
      }
    }
  ]
}

AWS Config Rules

Continuous compliance monitoring:

# AWS Config rule — alerts on non-compliant security groups
Resources:
  RestrictedSSHRule:
    Type: AWS::Config::ConfigRule
    Properties:
      ConfigRuleName: restricted-ssh
      Source:
        Owner: AWS
        SourceIdentifier: INCOMING_SSH_DISABLED

Integrating Human Verification for AI-Generated Infrastructure

Static analysis catches known patterns, but infrastructure security requires judgment calls that tools cannot make:

This is where expert code review provides value beyond automated scanning. Human reviewers verify that security groups fit coherently into your architecture, not just that they pass rule checks.

For teams deploying AI-generated infrastructure regularly, Fairy's verification layer ensures that security groups and other critical resources receive expert sign-off before reaching production. The combination of automated policy enforcement and human verification catches both the obvious 0.0.0.0/0 mistakes and the subtle architectural issues that rules miss.

Summary: Defense in Depth Against Network AI Bugs

Preventing security groups open to 0.0.0.0/0 on sensitive ports requires multiple layers:

  1. Prompt engineering: Explicitly constrain AI output with specific CIDR requirements
  2. Static analysis: Run Checkov, tfsec, or OPA in CI/CD to block known-bad patterns
  3. Infrastructure policies: Use SCPs or Azure Policy to prevent creation of overly permissive rules
  4. Architecture patterns: Default to bastion hosts and security group references instead of CIDR blocks
  5. Human verification: Expert review for infrastructure that controls network boundaries

AI generates this vulnerability because its training data optimizes for functionality, not security. Your defense must assume AI will produce permissive defaults and build systems that catch and correct them before deployment.

Frequently asked questions

Which ports should never be open to 0.0.0.0/0?

SSH (22), RDP (3389), database ports (3306 for MySQL, 5432 for PostgreSQL, 6379 for Redis, 27017 for MongoDB), and administrative interfaces should never be exposed to the entire internet. These ports should be restricted to known CIDR ranges, VPN addresses, or accessed through bastion hosts.

Why does AI generate security groups with 0.0.0.0/0?

AI models optimize for working examples and often lack context about your specific network topology. Training data frequently includes tutorials and quick-start guides that use 0.0.0.0/0 for simplicity. Without explicit constraints in your prompt, AI defaults to the most permissive configuration.

How do I scan Terraform for open security groups?

Use static analysis tools like Checkov, tfsec, or Open Policy Agent (OPA) with Conftest. These tools can be integrated into CI/CD pipelines to automatically block deployments containing security groups with 0.0.0.0/0 on sensitive ports.

What is the bastion host pattern for database access?

A bastion host (jump box) sits in a public subnet with restricted SSH access. Database security groups only allow connections from the bastion's security group. Users SSH into the bastion, then connect to databases on private subnets. This eliminates direct internet exposure.

Can AI-generated CloudFormation have the same issue?

Yes. This vulnerability appears across all infrastructure-as-code formats including CloudFormation, Terraform, Pulumi, and CDK. The underlying issue is AI defaulting to permissive network rules regardless of the specific IaC tool being used.


Have AI-generated work you’d want verified? Connect with a Fairy → or run a free check with Scout.

More resources