“The safest infra is the one with no forgotten parts — and nothing unnecessary still running.”
Infrastructure is the part of the attack surface you build yourself, whether or not you meant to. Every enabled service, listening daemon, management API and build runner is something an attacker can use, and most of them were not chosen deliberately. They arrived with an account default, a template, or a migration that never finished.
Infrastructure and Runtime ASR means shrinking that set on purpose: fewer ways in, fewer paths between systems, fewer things still running that nobody can explain.
1. Expose Nothing by Default
Default deny belongs everywhere: ports, API endpoints, service access, egress. If it is not needed and documented, block it.
Network Segmentation
The problem: Most networks are still flat. Once you are inside one, you can reach everything, which is all the lateral movement an attacker needs.
The solution: Segment, and start from deny-all:
# Terraform example: Deny-all security group
resource "aws_security_group" "default_deny" {
name = "default-deny"
description = "Default deny all traffic"
vpc_id = aws_vpc.main.id
# No ingress rules - all blocked by default
# Minimal egress for updates only
egress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
description = "HTTPS for package updates only"
}
}
Then explicitly open only what’s needed:
resource "aws_security_group_rule" "web_server_https" {
type = "ingress"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = [var.load_balancer_cidr]
security_group_id = aws_security_group.web_servers.id
description = "HTTPS from load balancer only"
}
Block Unnecessary Egress
Outbound traffic gets less scrutiny than inbound, and it is the path exfiltration takes.
Web servers have no business reaching arbitrary internet addresses. Database servers need no internet access at all. Application servers reach the APIs they call, and nothing else.
# iptables example: Whitelist-only egress
iptables -P OUTPUT DROP # Default drop all outbound
iptables -A OUTPUT -d 10.0.0.0/8 -j ACCEPT # Internal network
iptables -A OUTPUT -d api.trusted-service.com -p tcp --dport 443 -j ACCEPT
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
Isolation Strategies
Implementation patterns:
- Private subnets for databases and application servers
- VPNs or bastion hosts for administrative access, time-limited
- Service mesh with mTLS between microservices
- Separate environments for separate trust levels (dev/staging/prod)
Runtime Daemon Audit
Then audit what is listening on it:
# Linux: Check listening ports
ss -tulpn | grep LISTEN
# Check for unexpected daemons
systemctl list-units --type=service --state=running
# Disable unnecessary services
systemctl disable cups.service # Printing service on a server?
systemctl disable bluetooth.service # Bluetooth on a cloud instance?
Real-World Impact
The Equifax breach exploited an unpatched Apache Struts vulnerability, but lateral movement was possible because internal segmentation was insufficient.
Supabase ran the smaller, more common version of this in 2026. The OpenAPI spec at the Data API root listed every table and column in a project’s exposed schema, and it answered anyone holding the anon key — the key that ships inside client code. So they removed the access instead of documenting it, after measuring that fewer than 0.1% of projects had called it in a day.
Case studies: Target’s HVAC vendor credentials reached the payment network · CISA ordered agencies to take management interfaces off the internet · PrintNightmare’s official fix was to turn the print spooler off · Supabase removed schema access from the key that ships in every browser
Further reading:
- NIST SP 800-41: Guidelines on Firewalls and Firewall Policy
- CIS Controls: Network Infrastructure Management
- AWS VPC Security Best Practices
- Zero Trust Architecture - NIST SP 800-207
2. Reduce Control Plane & Runtime Complexity
Every service you enable, every management API you expose, every agent you install is another thing to configure correctly and another thing to patch.
The Multi-Cloud Trap
The problem: Multi-cloud is usually adopted “for resilience” and arrives as several IAM systems to secure, several security models to learn, the same service bought from two vendors, and a support matrix nobody can hold in their head.
The reality: Most multi-cloud setups are multi-cloud by accident. Unless you have a specific architectural reason, stay on one provider and learn its security model properly.
When multi-cloud makes sense:
- Geographic compliance requirements (data residency)
- True disaster recovery across providers
- Using a capability only one provider has (e.g., AWS SageMaker and Azure AD)
When it doesn’t:
- “We might want to switch someday”
- “We don’t want vendor lock-in” (you’re trading vendor lock-in for complexity)
- “Different teams prefer different clouds”
Disable Unused Services and APIs
Cloud providers turn services on by default. Each one is another configuration to get right.
# AWS: Audit enabled services
aws service-quotas list-services | jq -r '.Services[].ServiceName'
# Disable unused AWS services at the organization level
# Example: If you don't use AWS IoT
aws organizations create-policy \
--content '{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"iot:*","Resource":"*"}]}' \
--description "Disable IoT services" \
--name "DenyIoT" \
--type SERVICE_CONTROL_POLICY
Audit runtime agents: Many systems ship agents nobody asked for — monitoring collectors gathering more than the job needs, APM tools with full system access, log shippers running as root, vulnerability scanners that never run.
# Check what's really running
ps aux | grep -E 'agent|daemon' | grep -v grep
# Review installed packages
dpkg -l | grep -E 'agent|monitor' # Debian/Ubuntu
rpm -qa | grep -E 'agent|monitor' # RedHat/CentOS
Avoid Serverless Sprawl
Serverless is not automatically more secure. It moves the problem: 100+ small functions instead of 5 services, an IAM role per function, tracing nobody can follow, and cold-start code that runs before your handler does.
Ask before going serverless:
- Would a simple API server be clearer?
- Can we use 1 function instead of 10?
- Have we audited each function’s IAM permissions?
Runtime Security Hardening
Use modern kernel security features to limit what processes can do:
# Docker Compose example: Hardened container
services:
webapp:
image: myapp:latest
security_opt:
- no-new-privileges:true # Prevent privilege escalation
- seccomp:path/to/seccomp-profile.json # Limit syscalls
cap_drop:
- ALL # Drop all capabilities
cap_add:
- NET_BIND_SERVICE # Only add what's needed
read_only: true # Read-only root filesystem
user: "1000:1000" # Non-root user
tmpfs:
- /tmp # Temporary writable space
AppArmor profile example:
# Restrict what the application can access
profile myapp {
#include <abstractions/base>
/usr/bin/myapp mr,
/etc/myapp/** r,
/var/log/myapp/** w,
# Deny everything else
deny /** wx,
}
Real-World Example
Case studies:
- Kaseya’s VSA agent carried one compromise into 1,500 businesses
- Prime Video cut its monitoring cost 90% by collapsing the service into one process
- Blue moved off Render and AWS Aurora onto dedicated servers
- GOV.UK retired the Rails app that had been behind every page
- Netflix retired the ad-serving metadata registry instead of scaling it
Further reading:
- CIS Docker Benchmark
- Kubernetes Security Best Practices
- Seccomp Profile Guide
- Linux Kernel Security Features
3. Minimalism at the Image and Execution Level
An image should hold what the application needs to run and nothing else. Everything left in it is attack surface you shipped on purpose.
Minimal Base Images
The problem: A full OS base (Ubuntu, CentOS) brings hundreds of packages the application never calls:
# Size comparison
docker images
ubuntu:latest 470MB
alpine:latest 5.6MB
scratch:latest 0MB (empty!)
The solution: Use a minimal base:
# BAD: Full Ubuntu with kitchen sink
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y \
python3 python3-pip curl wget git vim \
&& pip3 install -r requirements.txt
# GOOD: Distroless Python
FROM python:3.11-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user -r requirements.txt
FROM gcr.io/distroless/python3-debian11
COPY --from=builder /root/.local /root/.local
COPY app.py /app/
WORKDIR /app
CMD ["app.py"]
Benefits of distroless: No shell for docker exec to land in, no package manager to install tools with after a compromise, fewer packages so fewer CVEs, and less to escape a container with.
Strip Unnecessary Tools
Production images still ship the build’s leftovers: curl and wget for moving data in and out, bash and sh for running what you pull, nc for a reverse shell, apt or yum for installing whatever is missing.
# Multi-stage build: Keep build tools out of final image
FROM golang:1.21 AS builder
WORKDIR /src
COPY . .
RUN CGO_ENABLED=0 go build -o app
FROM scratch # Literally empty
COPY --from=builder /src/app /app
ENTRYPOINT ["/app"]
# This image has NOTHING but your binary
Static Binaries
When possible, compile static binaries that need no dependencies:
# Go: Static compilation
CGO_ENABLED=0 GOOS=linux go build -a -ldflags '-extldflags "-static"' -o myapp
# Rust: Static compilation
cargo build --release --target x86_64-unknown-linux-musl
# Result: Single binary, no dependencies
ldd myapp
# not a dynamically linked executable
Container Runtime Best Practices
# Kubernetes Pod Security
apiVersion: v1
kind: Pod
metadata:
name: secure-app
spec:
securityContext:
runAsNonRoot: true
runAsUser: 10000
fsGroup: 10000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: myapp:latest
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
volumeMounts:
- name: tmp
mountPath: /tmp
- name: cache
mountPath: /app/cache
volumes:
- name: tmp
emptyDir: {}
- name: cache
emptyDir: {}
Secrets and Configuration
Bad practice: Secrets in environment variables or config files
# DON'T DO THIS
ENV DATABASE_PASSWORD=super_secret_123
Good practice: Runtime secret injection
# Kubernetes: Use secrets and mount them
env:
- name: DATABASE_PASSWORD
valueFrom:
secretKeyRef:
name: db-credentials
key: password
# Better: Use secret management
# AWS Secrets Manager, HashiCorp Vault, etc.
Real-World Impact
Bloated base images carry their whole toolchain into production: package managers, compilers, shells, and whatever the build left behind. Nothing in that list was chosen for the running service, and every item is a patch you now owe someone.
Hinge Health moved a production fleet of TypeScript, Go, Python and Ruby services off Debian and Alpine base images onto distroless ones, and reported total container CVEs falling from thousands to hundreds, OS-layer CVEs to near zero, and images about 26% smaller. The cost was incident tooling: distroless images have almost no shell, so structured logging, tracing and debug sidecars had to land before the migration rather than alongside it.
Case studies: Tinfoil replaced a million lines of virtual-machine firmware with about 300 lines of assembly · Hinge Health moved a fleet to distroless base images and about 80% of its container CVEs went with the OS layer
Further reading:
- Distroless Container Images - Google
- Docker Security Best Practices - OWASP
- CIS Docker Benchmark v1.6
- Container Security Guide - NIST SP 800-190
4. Prune Zombie Infra & Orphaned Services
Every account has a graveyard: the instance someone started for a test, the bucket from a project that ended, the DNS record still pointing at a host that is gone. Each one is a way in.
The Zombie Problem
Common zombies:
- Old EC2 instances someone spun up for “testing”
- S3 buckets from abandoned projects
- RDS databases from previous versions
- Load balancers pointing to deleted instances
- DNS records for decommissioned services
- Container images from 3 years ago
- Staging environments that became “production-like”
Why they’re dangerous: They drop out of the patch cycle, some still accept default credentials, some hold data from when they mattered, and in an incident nobody can say what they are for. They bill every month and carry obligations nobody tracks.
None of the deletion steps work on a system nobody wrote down. South Australia’s Auditor-General put a number on that in June 2026: across ten agencies, half the hardware and a quarter of the applications were legacy, and several of the agencies could not produce a complete inventory of what they run.
Case studies:
- GAO found 11 federal legacy systems, aged 23 to 60, still waiting to be retired
- The Postal Service marked 4,336 applications retired and left their servers and user accounts on the network
- Marisstella deleted the code for a cluster it had already switched off, after 212 files kept running in CI
- Let’s Encrypt switched off a four-billion-request-a-day certificate service and deleted its subscribers’ email addresses
- TIGTA found the IRS had deleted the decommissioning process from its own policy
- North Dakota HHS still runs a mainframe at $400,000 a month because the remnant data never left
- South Australia’s auditor found 49% of the hardware legacy, and inventories that could not keep up with it
- Railway’s shared build system was the way in, and endpoints nobody had used in years gave the attacker away
Discovery and Cleanup
AWS cleanup script example:
#!/bin/bash
# Find instances not tagged or not accessed in 90 days
# Untagged EC2 instances
aws ec2 describe-instances \
--query 'Reservations[].Instances[?!Tags].[InstanceId]' \
--output text
# S3 buckets with no access in 90 days
aws s3api list-buckets --query 'Buckets[].[Name]' --output text | \
while read bucket; do
last_access=$(aws s3api head-bucket --bucket "$bucket" 2>&1)
echo "Bucket: $bucket - Check logs for last access"
done
# Unused EBS volumes
aws ec2 describe-volumes \
--filters Name=status,Values=available \
--query 'Volumes[*].[VolumeId,Size,CreateTime]' \
--output table
Kubernetes cleanup:
# Find old unused resources
kubectl get pods --all-namespaces -o json | \
jq -r '.items[] | select(.status.phase == "Failed" or .status.phase == "Unknown") |
"\(.metadata.namespace) \(.metadata.name)"'
# Check for old deployments with 0 replicas
kubectl get deployments --all-namespaces -o json | \
jq -r '.items[] | select(.spec.replicas == 0) |
"\(.metadata.namespace) \(.metadata.name) \(.metadata.creationTimestamp)"'
Implement Resource Tagging
Mandatory tags policy:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Deny",
"Action": ["ec2:RunInstances"],
"Resource": ["arn:aws:ec2:*:*:instance/*"],
"Condition": {
"StringNotLike": {
"aws:RequestTag/Owner": "*",
"aws:RequestTag/Project": "*",
"aws:RequestTag/Environment": ["prod", "staging", "dev"]
}
}
}]
}
Automated cleanup based on tags:
# Example: Delete resources tagged for deletion
import boto3
from datetime import datetime, timedelta
ec2 = boto3.client('ec2')
# Find instances tagged "DeleteAfter"
instances = ec2.describe_instances(
Filters=[
{'Name': 'tag-key', 'Values': ['DeleteAfter']}
]
)
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
for tag in instance['Tags']:
if tag['Key'] == 'DeleteAfter':
delete_date = datetime.fromisoformat(tag['Value'])
if datetime.now() > delete_date:
print(f"Terminating {instance['InstanceId']}")
ec2.terminate_instances(InstanceIds=[instance['InstanceId']])
Sidecar and Agent Audit
Many systems accumulate monitoring and logging sidecars:
# Kubernetes: Check sidecar containers
kubectl get pods --all-namespaces -o json | \
jq -r '.items[] |
select(.spec.containers | length > 1) |
"\(.metadata.namespace)/\(.metadata.name): \(.spec.containers | length) containers"'
# Ask: Do we need all these?
# Common cruft: Old metrics exporters, unused log shippers, abandoned debug containers
Real-World Example
The 2019 Capital One breach involved a misconfigured firewall on infrastructure that was part of a migration. The old infrastructure wasn’t fully decommissioned, creating a security gap.
Decommissioning usually stalls on something that is not engineering. Canada’s Auditor General found nine legacy systems still in operation twenty months after their replacement went live, partly because the legal requirements for retaining the data they held had never been identified.
Case studies:
- Austin counted 1,005 applications and retired more than 230
- Shopify moved inventory reservations out of Redis and into MySQL
- Cook County put its 1970s mainframe read-only, then retired it
- Microsoft decommissioned 1.4 million unused Entra applications and retired Azure Service Manager
- Lumen retired about 50 mainframe applications and decommissioned about 90 switches
- Loadsmart scored 44 microservices and removed 12
- Michigan retired its final five Unisys mainframes, ending a decade of moves
- Canada’s border agency left nine legacy systems running after its replacement deployed
Further reading:
- AWS Well-Architected Framework: Cost Optimization
- Cloud Asset Inventory Management
- Azure Resource Graph for Cleanup
5. Reduce Lateral Movement Paths
After initial access comes lateral movement: more systems to reach, data to find, a place to persist.
Network Segmentation (Deep Dive)
Zero Trust principle: “Never trust, always verify”
Implement micro-segmentation where every service-to-service connection is authenticated and authorized:
# Kubernetes Network Policy: Default deny
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: production
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
---
# Then explicitly allow only required connections
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-webapp-to-api
namespace: production
spec:
podSelector:
matchLabels:
app: webapp
policyTypes:
- Egress
egress:
- to:
- podSelector:
matchLabels:
app: api
ports:
- protocol: TCP
port: 8080
Block Inter-Service Communication by Default
Service mesh approach (Istio, Linkerd):
# Istio: Require mTLS for all traffic
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: production
spec:
mtls:
mode: STRICT
---
# Authorization: Only API can access database
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
name: db-access-policy
namespace: production
spec:
selector:
matchLabels:
app: database
action: ALLOW
rules:
- from:
- source:
principals: ["cluster.local/ns/production/sa/api-service"]
No Wildcard IAM Permissions
Bad IAM policy:
{
"Effect": "Allow",
"Action": "*",
"Resource": "*"
}
Good IAM policy (scoped):
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-specific-bucket/app-uploads/*"
}
Audit for wildcards:
# AWS: Find policies with wildcard actions
aws iam list-policies --scope Local --query 'Policies[*].[PolicyName,Arn]' --output text | \
while read name arn; do
aws iam get-policy-version --policy-arn "$arn" \
--version-id $(aws iam get-policy --policy-arn "$arn" --query 'Policy.DefaultVersionId' --output text) \
--query 'PolicyVersion.Document' | \
grep -q '"Action":\s*"\*"' && echo "Wildcard found in: $name"
done
Secure Build Systems
CI/CD systems hold production access, build secrets and the ability to deploy, and they usually get less monitoring than production does. That combination is why they get targeted.
Secure CI/CD practices:
# GitHub Actions: Minimal permissions
name: Deploy
on: [push]
permissions:
contents: read # Only read code
id-token: write # For OIDC
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# Use OIDC instead of static credentials
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/GitHubActionsRole
aws-region: us-east-1
role-session-name: GitHubActions
# Deploy with scoped permissions
- name: Deploy
run: ./deploy.sh
Ephemeral CI/CD environments:
- Use short-lived credentials (OIDC tokens)
- Build in isolated, disposable environments
- Don’t persist secrets between builds
- Audit all CI/CD plugins and actions
Real-World Impact
Case studies: SolarWinds distributed a compromised update to 18,000 customers · Codecov’s modified uploader lifted the secrets out of customer build pipelines · CISA gave agencies eighteen months to get end-of-support edge devices off the network
Further reading:
- NIST Zero Trust Architecture
- MITRE ATT&CK: Lateral Movement
- CISA: Securing the Software Supply Chain
- SLSA Framework
6. Runtime Cleanup & Reboot Culture
Left running, systems accumulate zombie processes, connections that never closed, leaked memory, and temp files from a job that ran once. Restarting clears what nobody bothered to clean up.
Auto-Restart and Self-Healing
Kubernetes: Embrace ephemeral infrastructure
apiVersion: apps/v1
kind: Deployment
metadata:
name: webapp
spec:
replicas: 3
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
template:
spec:
containers:
- name: app
image: myapp:latest
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
periodSeconds: 5
Auto-scaling triggers restarts:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: webapp-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: webapp
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
Reboot After Patching
Scheduled reboots:
# Systemd timer for monthly reboots
# /etc/systemd/system/monthly-reboot.timer
[Unit]
Description=Monthly reboot for cleanup
[Timer]
OnCalendar=monthly
Persistent=true
[Install]
WantedBy=timers.target
# /etc/systemd/system/monthly-reboot.service
[Unit]
Description=Reboot system
[Service]
Type=oneshot
ExecStart=/sbin/reboot
Cleanup Zombie Processes
Monitor process table:
# Find zombie processes
ps aux | awk '$8=="Z" {print}'
# Clean up orphaned processes
# In systemd
systemctl restart systemd-journald # Restart logging
systemctl daemon-reexec # Reload systemd
# Find long-running processes
ps -eo pid,etime,cmd --sort=-etime | head -20
Disable Debug Flags
Configuration management to ensure production hardening:
# Ansible playbook example
- name: Ensure debug flags are disabled in production
hosts: production
tasks:
- name: Check application config
lineinfile:
path: /etc/myapp/config.yaml
regexp: '^debug:'
line: 'debug: false'
state: present
- name: Ensure verbose logging is off
lineinfile:
path: /etc/myapp/config.yaml
regexp: '^log_level:'
line: 'log_level: warn'
state: present
- name: Restart service
systemd:
name: myapp
state: restarted
Immutable infrastructure: Don’t patch a running system. Build a new image, deploy new instances, terminate the old ones. No box accumulates cruft, and none drifts from the image it was built from.
Real-World Benefit
The Heartbleed vulnerability (2014) stayed live for months after it was fixed. Administrators patched the library on disk and left the services that had already loaded the vulnerable one running, so the fix sat there until the next restart.
Many compromises live only in memory, and a restart clears them. That is why the oldest remediation step still works.
OpenAI put a price on the other half of that in November 2026. A prototype pipeline found and reproduced 1,724 Linux kernel vulnerabilities and produced 948 working local privilege escalation exploits against a stock desktop distribution in a single run, at $1,279 per exploit, and drew the conclusion a defender should act on: “having access to a low-privileged account on an operating system, that isn’t up-to-date on its latest available patches should be considered functionally equivalent to root access for a well-resourced threat actor.” (OpenAI, ‘A thousand fewer paths to root’, 4 November 2026)
Case studies: Buffer found seven background workers still running five years after the feature they served was replaced
Further reading:
7. Infrastructure-as-Code & Deployment Discipline
Infrastructure code is applied to every environment that consumes it, including the parts nobody read.
IaC Must Be Explicit
Bad IaC (implicit, unclear):
# What does this actually allow?
resource "aws_security_group" "app" {
name = "app-sg"
ingress {
from_port = 0
to_port = 65535
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
Good IaC (explicit, documented):
# HTTPS only from load balancer
resource "aws_security_group" "app" {
name = "app-servers"
description = "Allow HTTPS from ALB only"
vpc_id = aws_vpc.main.id
ingress {
description = "HTTPS from ALB security group"
from_port = 443
to_port = 443
protocol = "tcp"
security_groups = [aws_security_group.alb.id]
}
egress {
description = "HTTPS to RDS only"
from_port = 5432
to_port = 5432
protocol = "tcp"
security_groups = [aws_security_group.rds.id]
}
tags = {
Name = "app-servers"
Environment = "production"
ManagedBy = "terraform"
}
}
No Insecure Defaults
Terraform security scanning:
# Use tfsec to scan for security issues
tfsec .
# Example issues it catches:
# - Public S3 buckets
# - Unencrypted storage
# - Overly permissive security groups
# - Missing logging
Policy as Code:
# OPA policy: Deny public S3 buckets
package terraform.s3
deny[msg] {
resource := input.resource.aws_s3_bucket[name]
resource.acl == "public-read"
msg := sprintf("S3 bucket '%s' has public-read ACL", [name])
}
deny[msg] {
resource := input.resource.aws_s3_bucket[name]
not resource.versioning[_].enabled
msg := sprintf("S3 bucket '%s' does not have versioning enabled", [name])
}
Remove Unused Modules
IaC codebases accumulate unused modules and configurations:
# Find unused Terraform modules
grep -r "module\s*\"" . | awk '{print $2}' | sort | uniq > used_modules.txt
ls -d modules/*/ | awk -F/ '{print $2}' | sort > all_modules.txt
comm -13 used_modules.txt all_modules.txt # Shows unused modules
Only Deploy What You Understand
Pre-deployment checklist:
- Can you explain what this infrastructure does?
- Have you reviewed all security group rules?
- Are all IAM policies scoped to minimum necessary?
- Is logging enabled for audit trails?
- Are secrets stored securely (not hardcoded)?
- Is there a rollback plan?
Automated policy enforcement:
# GitHub Actions: Policy check before apply
name: Terraform
on: [pull_request]
jobs:
policy-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Terraform
uses: hashicorp/setup-terraform@v3
- name: Terraform Init
run: terraform init
- name: Terraform Plan
run: terraform plan -out=tfplan
- name: Security Scan
run: tfsec .
- name: Policy Check
uses: open-policy-agent/opa-action@v2
with:
policy: policies/
input: tfplan
Real-World Impact
IaC templates make a mistake repeatable: a default that is wrong in one template becomes wrong in every environment built from it. Common issues:
- Default admin passwords in templates
- Public exposure set as default
- Missing encryption configurations
- Overly permissive IAM in examples
Further reading:
- Terraform Security Best Practices
- tfsec - Terraform Security Scanner
- Checkov - IaC Security Scanner
- OPA - Open Policy Agent
- NIST SP 800-204: Security for Microservices
8. Guidelines for Infra + Runtime ASR
| Area | ASR Practice | Implementation |
|---|---|---|
| Network | Deny by default, isolate services | Security groups with explicit allowlists; network policies; private subnets |
| Containers | Run minimal images, non-root, limit capabilities | Distroless bases; drop ALL caps; read-only filesystem; seccomp profiles |
| Secrets | Don’t mount unused secrets, rotate often | Secret managers (Vault, AWS Secrets); short-lived credentials; OIDC |
| Agents | Audit or remove sidecars and runtime daemons | Regular review of ps output; remove unused monitoring agents |
| Infra Bloat | Delete what’s stale or shadowed | Tag-based cleanup automation; monthly audits; cost reports |
| Build Infra | Keep CI/CD isolated and short-lived | Ephemeral build environments; scoped credentials; SLSA compliance |
| Runtime State | Restart regularly, audit logs and zombie processes | Immutable infrastructure; automated restarts; process monitoring |
| IaC | Simplify, document, and trim templates regularly | Security scanning (tfsec); policy enforcement (OPA); code review |
9. Final Thought
“Every port closed, every daemon killed, every stale node decommissioned — that’s risk erased.”
This is not a monitoring problem. It is an architecture problem: less exposed, less running, less reachable, and less to do once an attacker is inside.
The ASR infrastructure audit (quarterly):
- Network audit: Can anything talk to anything? Fix it.
- Image audit: Are we running bloated containers? Slim them.
- Zombie audit: What’s running that shouldn’t be? Kill it.
- Permission audit: Who/what has more access than needed? Scope it.
- Agent audit: What’s running on our boxes? Justify or remove.
Pick one service, one container, one environment. Apply this to that, then expand.
The infrastructure you don’t deploy can’t be exploited. The service you don’t run can’t be compromised.