Skip to main content
Technology & EngineeringNetworking Infrastructure353 lines

Network Security

Network security patterns including firewalls, DDoS protection, WAFs, and intrusion detection

Quick Summary8 lines
You are an expert in network security for building reliable networked systems.

## Key Points

- **Apply the principle of least privilege** — security groups should allow only the exact ports and source ranges needed. Never use `0.0.0.0/0` for database or admin ports.
- **Layer defenses** — combine DDoS protection (edge), WAF (L7), network firewalls (L3/L4), and host firewalls. No single layer catches everything.
skilldb get networking-infrastructure-skills/Network SecurityFull skill: 353 lines
Paste into your CLAUDE.md or agent config

Network Security — Networking & Infrastructure

You are an expert in network security for building reliable networked systems.

Core Philosophy

Overview

Network security encompasses the tools, configurations, and patterns that protect infrastructure from unauthorized access, data exfiltration, and denial-of-service attacks. This skill covers firewall configuration (host-based and cloud), Web Application Firewalls (WAFs), DDoS mitigation, intrusion detection, network segmentation, and security monitoring.

Core Concepts

Defense in Depth

Internet
    │
    ▼
┌─ DDoS Protection (Cloudflare, AWS Shield) ─┐
│                                              │
│  ┌─ WAF (OWASP rules, rate limiting) ────┐  │
│  │                                        │  │
│  │  ┌─ Load Balancer (TLS termination) ┐  │  │
│  │  │                                   │  │  │
│  │  │  ┌─ Network Firewall ──────────┐  │  │  │
│  │  │  │  (Security Groups / NACLs)  │  │  │  │
│  │  │  │                             │  │  │  │
│  │  │  │  ┌─ Host Firewall ───────┐  │  │  │  │
│  │  │  │  │  (iptables / nftables)│  │  │  │  │
│  │  │  │  │                       │  │  │  │  │
│  │  │  │  │  ┌─ Application ───┐  │  │  │  │  │
│  │  │  │  │  │  (auth, input   │  │  │  │  │  │
│  │  │  │  │  │   validation)   │  │  │  │  │  │
│  │  │  │  │  └─────────────────┘  │  │  │  │  │
│  │  │  │  └───────────────────────┘  │  │  │  │
│  │  │  └─────────────────────────────┘  │  │  │
│  │  └───────────────────────────────────┘  │  │
│  └─────────────────────────────────────────┘  │
└───────────────────────────────────────────────┘

Firewall Types

TypeLayerScopeExamples
Host-basedL3-L4Single machineiptables, nftables, Windows Firewall
Network firewallL3-L4Subnet/VPCAWS Security Groups, NACLs, GCP Firewall Rules
WAFL7HTTP trafficAWS WAF, Cloudflare WAF, ModSecurity
Next-gen firewallL3-L7Network edgePalo Alto, Fortinet, pfSense

Security Groups vs NACLs (AWS)

FeatureSecurity GroupNACL
LevelInstance/ENISubnet
StateStateful (return traffic auto-allowed)Stateless (must allow both directions)
RulesAllow onlyAllow and Deny
EvaluationAll rules evaluatedRules evaluated in order
DefaultDeny all inbound, allow all outboundAllow all

Implementation Patterns

iptables / nftables Configuration

# iptables — basic server hardening
# Flush existing rules
iptables -F
iptables -X

# Default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Allow loopback
iptables -A INPUT -i lo -j ACCEPT

# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow SSH (rate limited)
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 --name SSH -j DROP
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow ICMP (ping)
iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT

# Log dropped packets
iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables-dropped: "

# Save rules
iptables-save > /etc/iptables/rules.v4
# nftables — modern replacement
nft add table inet filter
nft add chain inet filter input '{ type filter hook input priority 0; policy drop; }'
nft add chain inet filter forward '{ type filter hook forward priority 0; policy drop; }'
nft add chain inet filter output '{ type filter hook output priority 0; policy accept; }'

nft add rule inet filter input iif lo accept
nft add rule inet filter input ct state established,related accept
nft add rule inet filter input tcp dport { 22, 80, 443 } accept
nft add rule inet filter input ip protocol icmp limit rate 1/second accept
nft add rule inet filter input counter drop

AWS Security Groups (Terraform)

# Web tier — accepts public HTTP/HTTPS
resource "aws_security_group" "web" {
  name   = "web-sg"
  vpc_id = aws_vpc.main.id

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# App tier — only accepts traffic from web tier
resource "aws_security_group" "app" {
  name   = "app-sg"
  vpc_id = aws_vpc.main.id

  ingress {
    from_port       = 8080
    to_port         = 8080
    protocol        = "tcp"
    security_groups = [aws_security_group.web.id]
  }
}

# Database tier — only accepts traffic from app tier
resource "aws_security_group" "db" {
  name   = "db-sg"
  vpc_id = aws_vpc.main.id

  ingress {
    from_port       = 5432
    to_port         = 5432
    protocol        = "tcp"
    security_groups = [aws_security_group.app.id]
  }
}

AWS WAF Configuration

resource "aws_wafv2_web_acl" "main" {
  name  = "main-waf"
  scope = "REGIONAL"

  default_action {
    allow {}
  }

  # AWS Managed Rules — OWASP Top 10
  rule {
    name     = "aws-managed-common"
    priority = 1
    override_action { none {} }

    statement {
      managed_rule_group_statement {
        vendor_name = "AWS"
        name        = "AWSManagedRulesCommonRuleSet"
      }
    }

    visibility_config {
      sampled_requests_enabled   = true
      cloudwatch_metrics_enabled = true
      metric_name                = "CommonRules"
    }
  }

  # Rate limiting
  rule {
    name     = "rate-limit"
    priority = 2
    action { block {} }

    statement {
      rate_based_statement {
        limit              = 2000
        aggregate_key_type = "IP"
      }
    }

    visibility_config {
      sampled_requests_enabled   = true
      cloudwatch_metrics_enabled = true
      metric_name                = "RateLimit"
    }
  }

  # Block known bad IPs
  rule {
    name     = "ip-reputation"
    priority = 3
    override_action { none {} }

    statement {
      managed_rule_group_statement {
        vendor_name = "AWS"
        name        = "AWSManagedRulesAmazonIpReputationList"
      }
    }

    visibility_config {
      sampled_requests_enabled   = true
      cloudwatch_metrics_enabled = true
      metric_name                = "IPReputation"
    }
  }

  # SQL injection protection
  rule {
    name     = "sqli-protection"
    priority = 4
    override_action { none {} }

    statement {
      managed_rule_group_statement {
        vendor_name = "AWS"
        name        = "AWSManagedRulesSQLiRuleSet"
      }
    }

    visibility_config {
      sampled_requests_enabled   = true
      cloudwatch_metrics_enabled = true
      metric_name                = "SQLiProtection"
    }
  }

  visibility_config {
    sampled_requests_enabled   = true
    cloudwatch_metrics_enabled = true
    metric_name                = "MainWAF"
  }
}

Fail2Ban (Intrusion Prevention)

# /etc/fail2ban/jail.local
[DEFAULT]
bantime  = 3600
findtime = 600
maxretry = 5
banaction = iptables-multiport

[sshd]
enabled = true
port    = ssh
filter  = sshd
logpath = /var/log/auth.log
maxretry = 3

[nginx-http-auth]
enabled  = true
filter   = nginx-http-auth
port     = http,https
logpath  = /var/log/nginx/error.log
maxretry = 3

[nginx-limit-req]
enabled  = true
filter   = nginx-limit-req
port     = http,https
logpath  = /var/log/nginx/error.log
maxretry = 5

Cloudflare DDoS Protection Configuration

# Cloudflare API — create firewall rule to block countries
curl -X POST "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/firewall/rules" \
  -H "Authorization: Bearer ${CF_TOKEN}" \
  -H "Content-Type: application/json" \
  --data '[{
    "filter": {
      "expression": "(ip.geoip.country in {\"CN\" \"RU\"}) and not cf.bot_management.verified_bot",
      "description": "Block high-risk countries except verified bots"
    },
    "action": "challenge",
    "description": "Geo challenge rule"
  }]'

# Enable Under Attack Mode via API
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/settings/security_level" \
  -H "Authorization: Bearer ${CF_TOKEN}" \
  -H "Content-Type: application/json" \
  --data '{"value":"under_attack"}'

Best Practices

  • Apply the principle of least privilege — security groups should allow only the exact ports and source ranges needed. Never use 0.0.0.0/0 for database or admin ports.
  • Layer defenses — combine DDoS protection (edge), WAF (L7), network firewalls (L3/L4), and host firewalls. No single layer catches everything.
  • Log and monitor all denied traffic — firewall logs, WAF logs, and intrusion detection alerts should feed into a centralized SIEM (CloudWatch, Datadog, Splunk) with alerting on anomalous patterns.

Common Pitfalls

  • Overly permissive egress rules: Many teams focus on inbound rules but leave all outbound traffic open. This allows compromised servers to exfiltrate data or join botnets. Restrict egress to required destinations and ports.
  • Security group sprawl: Without naming conventions and regular audits, security groups accumulate unused rules and orphaned groups. Use infrastructure-as-code and periodically audit for rules that reference decommissioned services.

Anti-Patterns

Over-engineering for hypothetical requirements. Building for scenarios that may never materialize adds complexity without value. Solve the problem in front of you first.

Ignoring the existing ecosystem. Reinventing functionality that mature libraries already provide wastes time and introduces risk.

Premature abstraction. Creating elaborate frameworks before having enough concrete cases to know what the abstraction should look like produces the wrong abstraction.

Neglecting error handling at system boundaries. Internal code can trust its inputs, but boundaries with external systems require defensive validation.

Skipping documentation. What is obvious to you today will not be obvious to your colleague next month or to you next year.

Install this skill directly: skilldb add networking-infrastructure-skills

Get CLI access →