Skip to content

DDoS Protection, Firewalls, VPCs & Network Segmentation ​

"A DDoS attack is an attack in which multiple compromised systems try to flood a target with traffic. A DDoS attack can prevent legitimate end users from accessing the target services and can cause the target to crash due to overwhelming traffic volume." — AWS documentation, How AWS Shield and Shield Advanced work, AWS WAF Developer Guide

Summary: Network security is two jobs: keep the bad traffic from using up your capacity (DDoS defence: absorb it far away from your servers, drop it cheaply, make every request that reaches your code cost little), and keep the good traffic on the paths you meant (firewalls, VPC layout, segmentation: nothing talks to anything it does not have to). Focus: DDoS taxonomy (volumetric, protocol, L7) with cited record sizes, reflection and amplification, SYN floods and SYN cookies, Slowloris and slow POST, HTTP floods and cache busting, bots, anycast scrubbing networks (Cloudflare, Akamai, AWS Shield, Cloud Armor), RTBH and flowspec, WAF and bot management, challenges, caching to absorb, autoscaling cost and economic denial of sustainability, origin protection, stateless vs stateful firewalls, security groups vs NACLs, egress filtering, VPC design (public and private subnets, NAT gateway, route tables, peering, transit gateway, PrivateLink, bastion vs SSM), segmentation and micro-segmentation (Kubernetes NetworkPolicy, service mesh authorization), IDS/IPS and flow logs, testing, runbooks, and Go and Laravel code. Learning goal: Classify an attack from its symptoms, name the layer that can stop it and the one that cannot, design a VPC where a compromised web server cannot reach the database or the internet freely, harden a Go or Laravel origin so that slow, large and cache-busting requests cost little, and run the first hour of an attack from a written runbook.

This chapter sits in the Security group after OWASP Top 10 and before Mutual TLS & Securing Service-to-Service Traffic. It owns the system-level decisions and the numbers. Neighbours keep their depth: Firewalls: iptables/nftables, Security Groups, Network ACLs, Egress Control owns the host firewall mechanics; VPNs & Tunnels owns WireGuard and SSH tunnels; Kubernetes Networking owns CNI and NetworkPolicy mechanics; NAT, PAT & Port Forwarding owns NAT; Ports, Sockets & Connections owns the accept queue, backlog and conntrack; TLS in Practice owns the handshake; Rate Limiting owns the algorithms (this page uses them as one layer of defence); Load Shedding owns whole-system overload; CDNs and Caching own the absorbing layers; IP, DNS, GeoDNS owns authoritative DNS and anycast routing; TCP & UDP owns the protocols that are being abused; Authorization Models: RBAC, ABAC, ReBAC & Zero Trust owns identity-based access; Secure SDLC, DevSecOps, Logging, Incident Response, Compliance & Breaches owns the incident process this page plugs a DDoS playbook into.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why a bigger server is never the answerWhy it exists
1996 SYN floods to 7.3 TbpsWhere it comes from
UDP floods and carpet bombingVolumetric attacks
DNS, NTP, memcached amplification and spoofingReflection and amplification
SYN flood, ACK flood, fragmentation, SYN cookiesProtocol attacks
Slowloris, slow POSTSlow attacks
HTTP flood, cache busting, Rapid Reset, expensive endpointsApplication-layer floods
Botnets, scrapers, credential stuffingBots
Cloudflare, Akamai, AWS Shield, Cloud ArmorScrubbing networks
RTBH, flowspec, blackholingRTBH and flowspec
WAF, bot management, JS challenge, CAPTCHAWAF and challenges
Per-IP limits, connection limits, timeoutsLimits at the origin
Cache hit ratio as a shieldCaching to absorb
The autoscaling billAutoscaling and EDoS
Hiding the originOrigin protection
Stateless vs stateful, SG vs NACL, WAF vs network firewallFirewalls
SSRF and exfiltrationEgress filtering
Subnets, NAT gateway, route tablesVPC design
Peering, transit gateway, PrivateLink, endpointsConnecting networks
Bastion vs SSM Session ManagerAdmin access
Tiers, micro-segmentation, NetworkPolicy, mesh authzSegmentation
DNS as a target and as a shieldDNS layer
TLS exhaustion, HTTP/2 limitsTLS and edge
Suricata, Zeek, VPC Flow LogsIDS, IPS and flow logs
Is a test legalTesting
The first hourRunbook
Formulas, knobs, error signalsMechanics
CodeGo, Laravel
Eight classic failuresSolving the classic problems
What to buy and where to blockChoosing
Monolith to multi-regionIn architecture
Simulation and experimentsLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The three attack classes.

ClassWhat it exhaustsExamplesUnitWhere it must be stopped
Volumetric (L3/L4)The network link and routersUDP flood, DNS/NTP/memcached amplification, carpet bombingGbps, Tbps, MppsUpstream: scrubbing network, ISP (RTBH, flowspec)
Protocol (L4)Connection state in servers, load balancers, firewallsSYN flood, ACK flood, fragmentation attackPackets per second, half-open connectionsEdge with SYN cookies or a SYN proxy, stateless filters
Application (L7)CPU, workers, database, third-party quotasHTTP flood, cache busting, Slowloris, slow POST, expensive endpointsRequests per secondWAF, rate limits, challenges, caching, your own server limits

Who stops what. The last column is the honest answer to "will this alone save me?".

LayerStopsCannot stop
Your firewall or security groupUnwanted ports, lateral movementA flood that fills the link before it arrives
Anycast scrubbing (Cloudflare, Akamai, AWS Shield, Cloud Armor)Volumetric, protocol, much of L7An attack on an origin IP the attacker found, if the origin accepts everyone
WAF and bot managementKnown bad payloads, bad bots, floods that look different from usersA flood of perfectly valid, distinct requests from a million real-looking clients
CDN cacheRepeated reads of the same objectCache-busting queries, POSTs, personalised responses
Per-IP rate limitOne noisy clientA botnet with one request per address
Server timeouts and body capsSlowloris, slow POST, giant bodiesFast, well-formed floods
AutoscalingHonest growthAn attack, which it turns into a bill

Record sizes, each from the operator who measured it.

WhenSizeKindSource
Feb 20181.35 Tbps, 126.9 million packets per secondmemcached amplification against GitHubGitHub incident report
Aug 2023398 million requests per second (largest L7 attack Google reported)HTTP/2 Rapid ResetGoogle Cloud blog
2023Just above 201 million requests per secondHTTP/2 Rapid ResetCloudflare blog
May 20257.3 Tbps, 37.4 TB in 45 seconds; the largest attack Cloudflare had recorded at that dateMultivector, 99.996% UDP floodCloudflare blog

Records are broken every year; check the current Cloudflare DDoS threat report before you quote a number.

The four numbers to know about your own system. Peak legitimate request rate, the rate the origin can serve before latency doubles, the bandwidth of your uplink, and the cost per hour of your autoscaled fleet at maximum size. The runbook depends on all four.

Volumetric (L3 / L4)Protocol (L4)Application (L7)Goal: fill the pipeUDP flood, carpet bombingDNS / NTP / memcachedamplification (spoofed src)Unit: Gbps, Tbps, MppsStopped byAnycast scrubbing networkRTBH / BGP flowspec at ISPNot by your firewall: thelink is already fullGoal: exhaust stateSYN flood, ACK floodFragmentation attacksConnection-table exhaustionUnit: packets / s, connsStopped bySYN cookies (RFC 4987)Stateless filtering at edgeConnection limits, LB withSYN proxy (NLB, Shield)Goal: exhaust the appHTTP flood, cache bustingSlowloris, slow POSTExpensive endpoints, botsUnit: requests / sStopped byWAF, rate limits, challengesCaching, bot managementServer timeouts, body caps,connection limits (your code)Left: huge volume, nothing to parseRight: few requests, costly to serve, needs your app

Why it exists ​

Every public service offers a cheap request and an expensive response. A request is a few hundred bytes; the response can be a database query, a template render, a TLS handshake, a megabyte of JSON. A denial-of-service attack is any way of making that ratio work for the attacker. Distribution (the first D) removes the one defence that works against a single machine, blocking its address.

WeakerStrongerThe trade-off
Block by IPScore by behaviourBehaviour needs data and risks false positives; IP lists are cheap and wrong behind NAT
Drop everything unknownChallenge unknownChallenges cost real users a second and break API clients
One big originMany small edgesEdges need caching, stateless design and a trust boundary
Public origin with a firewallOrigin reachable only from the edgeYou depend on the edge's availability
Autoscale to surviveCap and shedAutoscale keeps the site up and the bill unbounded; a cap protects money and loses requests
Flat networkSegmented networkSegmentation costs rules to maintain and debugging time

An everyday picture. A shop has one door. A crowd of people who do not want to buy anything stands in the doorway, and real customers cannot get in. You can hire a bigger shop (more servers), but the crowd grows. You can put a bouncer a block away who lets only people with a ticket through (a scrubbing network). You can make the door so narrow that only one person per second enters (rate limiting). You can lock the back door, because the crowd will find it (origin protection). And separately, you can make sure that someone who gets inside the shop cannot walk into the stock room (segmentation). This chapter is the bouncer, the door and the stock-room locks.

Three common misunderstandings, up front ​

  1. "A firewall protects me from DDoS." A firewall decides what to accept after the packet has arrived; a volumetric flood has done its damage on the link before the firewall sees it, and a stateful firewall's connection table is itself a target.
  2. "Autoscaling makes me DDoS-proof." It turns an availability attack into a billing attack, and it cannot add bandwidth to a saturated link (Autoscaling and EDoS).
  3. "Private subnet means private." A private subnet only has no route from the internet gateway; whatever runs inside can still call out through the NAT gateway, so without egress filtering a compromised host can exfiltrate data and fetch malware (Egress filtering).

Where it comes from ​

  • 1996: SYN floods. RFC 4987 (2007) states "The SYN flooding attack was first publicized in 1996" and describes SYN cookies as allocating "no state at all for connections in SYN-RECEIVED".
  • 2000: ingress filtering. RFC 2827 (BCP 38) asked every provider to drop packets whose source address does not belong to the customer sending them. Reflection attacks still work in 2025 because many networks do not do this.
  • 2009: RTBH. RFC 5635 describes Remotely Triggered Black Hole filtering with uRPF: a route to a null interface, triggered by a BGP announcement, drops traffic to a victim address at the provider's edge.
  • 2014: amplification becomes routine. CISA alert TA14-017A lists bandwidth amplification factors: DNS 28 to 54, NTP 556.9.
  • 2018: memcached. GitHub took 1.35 Tbps for about nine minutes by moving to Akamai; the amplification factor was "up to 51,000".
  • 2020: flowspec. RFC 8955 defines a BGP encoding for traffic filter rules (match on destination prefix, port, TCP flags, packet length; action: rate limit, discard, redirect) that a provider can accept from a customer.
  • 2023: HTTP/2 Rapid Reset. Google and Cloudflare reported attacks (CVE-2023-44487) that opened streams and cancelled them with RST_STREAM at once; the largest reached 398 million requests per second.
  • 2025: 7.3 Tbps. Cloudflare mitigated it autonomously in 477 data centers across 293 locations.

The concept catalogue ​

The blocks run from the attack to the defence, then to the network design that limits the damage when defence fails.

Volumetric floods and carpet bombing Must-know ​

In plain words: The attacker sends more bytes per second than your connection can carry, so real requests never get through the full pipe.

Common misunderstanding: "My server has 64 cores, so it can take it." The link, the router and the first firewall fail before the CPU is involved.

Definition: A volumetric attack saturates bandwidth (bits per second) or packet-processing capacity (packets per second) at layer 3 or 4. A UDP flood sends UDP packets to random or specific ports. Carpet bombing spreads the flood across many destination ports and addresses so that per-port thresholds never trip; Cloudflare reported the 7.3 Tbps attack hit an average of 21,925 destination ports of one IP.

Link: 10 Gbps uplink, 1 Gbps of legitimate traffic
1  t=0     attack starts: 40 Gbps of UDP to random ports
2  t=0+    router queue fills; tail drop applies to all flows, good and bad alike
3  t=5s    legitimate TCP flows see loss, retransmit, back off
4  t=30s   your firewall dashboards show 0.3% of the packets it received
5  result  the server is idle at 2% CPU and the site is down

Real scenario: A hosting provider customer is hit with a UDP flood at 400 Gbps and the provider null-routes the victim IP to protect its other customers. A game server with a public IP is flooded by a rival. An API behind a single 1 Gbps cloud NIC loses to a 5 Gbps flood from rented bots.

What provides protectionHowLimit
Scrubbing network with anycastAbsorbs and filters in many placesNeeds your prefix or DNS pointed at it
Cloud provider default protection (AWS Shield Standard, Google Cloud's network)Always-on L3/L4 filtering for resources in the providerResources that sit outside the provider's network get nothing
ISPRTBH, flowspecCoarse; RTBH completes the attack against the victim IP
Bigger uplinkDelays the failureAttackers rent more than you buy

Fix: Do not try to fix a volumetric flood on the host. Put the service behind a network that has more capacity than the attack (Scrubbing networks) and do not expose origin IPs (Origin protection).

Reflection and amplification Must-know ​

In plain words: The attacker sends a tiny request to thousands of open servers and writes the victim's address as the sender; every server replies to the victim with a much bigger answer.

Common misunderstanding: "The attack comes from the IP addresses in my logs, so I can block them." Those addresses are innocent reflectors; blocking them blocks real DNS resolvers and NTP servers, and the real source never appears.

Definition: A reflection attack uses a third party that answers whoever the packet says sent it. Amplification means the answer is larger than the request. It works over UDP because UDP does not verify the source address, the CISA alert notes. The ratio is the bandwidth amplification factor (BAF).

attacker --UDP "get stats" (src=victim, 15 B)--> open memcached server
open memcached server --UDP 51 KB reply--------> victim
BAF = reply / request: up to 51,000 (GitHub incident report, 2018)
AttackerReflectors (open servers)Victimbotnet or one hostthat can spoofsource addressesOpen DNS resolversNTP monlist (old)memcached on UDP 11211CLDAP, SSDP, QOTD, RIPv1Each answers whoever thesource address sayssees 1000s of honestservers, not theattackersmall requestsrc = victim IPreply up to 51,000xbigger (memcached)Fix at the source: BCP 38 ingress filtering. Fix on the reflector: close UDP. Fix at the victim: scrub upstream.
ProtocolPortAmplificationFix at the reflector
DNS amplificationUDP 5328 to 54 (CISA)Do not run open recursive resolvers; response rate limiting
NTP amplificationUDP 123556.9 (CISA, monlist)Patch (CVE-2013-5211), disable monlist, restrict queries
memcached amplificationUDP 11211up to 51,000 (GitHub)Bind to localhost, disable UDP (-U 0), never expose
CLDAP, SSDP, mDNS, Portmap, RIPv1, QOTD, EchovariousvariousDo not expose to the internet (the 7.3 Tbps attack used several)

Real scenario: The 2018 GitHub attack came from "over a thousand different autonomous systems (ASNs) across tens of thousands of unique endpoints" and none of them was the attacker. A company that runs a forgotten memcached with UDP open on a public cloud address becomes an amplifier, and gets an abuse notice from its provider.

What prevents it: At the source network, BCP 38 ingress filtering (RFC 2827). On your servers, do not expose UDP services you do not need, and if you run DNS, make resolvers recursive only for your own clients. At the victim, scrubbing. A Go and Laravel service is not an amplifier, but a VM next to it can be: scan your own address space.

Fix / how to use it: From the outside, check that you are not a reflector.

# expected, not run: from a machine outside your network, against a documentation-range address
$ nmap -sU -p 53,123,1900,11211 --open 203.0.113.0/28
# any "open" line is an amplifier waiting to be used against someone else

SYN flood, SYN cookies, ACK flood and fragmentation attacks Must-know ​

In plain words: TCP makes the server remember every half-opened connection; an attacker opens millions of them and never finishes, until the server's memory for new connections is full.

Common misunderstanding: "SYN floods are a 1990s problem." Cloudflare's 7.3 Tbps attack was UDP, but AWS documents the TCP SYN flood as the standard example of a protocol attack that exhausts connection state "on resources like servers, load balancers, or firewalls".

Definition: The client sends SYN (often with a spoofed source); the server allocates a transmission control block, replies SYN-ACK and waits. A SYN flood fills the backlog of half-open connections. SYN cookies (RFC 4987, section 3.6) "allocate no state at all for connections in SYN-RECEIVED": the server encodes what it needs in the sequence number of the SYN-ACK and rebuilds the state only if a valid ACK comes back. An ACK flood sends ACK packets with no connection behind them to burn CPU in stateful devices; a fragmentation attack sends many IP fragments (or overlapping or incomplete ones) so that the reassembly buffer is exhausted.

Normal                          SYN flood without cookies
client  SYN        --> server   attacker  SYN (spoofed src) x 100000 --> server
client  <-- SYN-ACK    server   server    allocates state x 100000, backlog full
client  ACK        --> server   client    SYN --> dropped: "connection refused" or timeout
With SYN cookies: no state until the ACK arrives and the cookie in it validates
Product or settingWhat it does
Linux net.ipv4.tcp_syncookies=1 (default on most distributions)Sends cookies when the SYN backlog overflows
Linux net.ipv4.tcp_max_syn_backlog, somaxconnSize of the half-open and accept queues (see ports and sockets)
AWS Shield"TCP SYN proxy" sends SYN cookies, is stateless, available on CloudFront, Route 53 and Global Accelerator
Cloud load balancers (AWS ALB, Google Cloud global external Application Load Balancer)Terminate TCP in the provider network, so your instance never sees the flood

Real scenario: A self-hosted API on a single VM with a public IP stops accepting connections; ss -s shows tens of thousands in SYN-RECV and dmesg says "TCP: request_sock_TCP: Possible SYN flooding on port 443. Sending cookies." (plus a pointer to the SNMP counters) That message means cookies are protecting you; the CPU is the next limit.

Fix / how to use it: Do not run a public TCP service on a bare VM. Put a managed load balancer or CDN in front, keep SYN cookies on, and filter fragments and unused protocols (ICMP types, UDP) at the edge with a stateless rule.

Slowloris and slow POST Must-know ​

In plain words: The attacker connects and then sends the request one byte at a time, very slowly, so each connection ties up a worker for minutes while using almost no bandwidth.

Common misunderstanding: "Low traffic means no attack." A Slowloris attack looks like a quiet day on every bandwidth graph and takes the site down because the connection pool is full.

Definition: OWASP's Denial of Service cheat sheet: "Slow HTTP attacks deliver HTTP requests very slow and fragmented, one at a time. Until the HTTP request was fully delivered, the server will keep resources stalled while waiting for the missing incoming data." Slowloris drips the header block (never sends the final blank line); slow POST (R-U-Dead-Yet) sends a large Content-Length and then the body at a few bytes a second; slow read does the same on the response side.

Slowloris against a server with 1000 worker slots and no ReadHeaderTimeout
1  attacker opens 1000 connections, sends "GET / HTTP/1.1\r\nHost: x\r\n"
2  every 10 s: sends "X-a: b\r\n" on each one (never the final blank line)
3  server: 1000 of 1000 slots busy waiting for the headers to finish
4  real user: connection accepted by the kernel, never served
ServerHeader and body timeout knobsNotes
Go net/httpReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout, MaxHeaderBytesZero means no timeout; http.ListenAndServe sets none
NGINXclient_header_timeout, client_body_timeout, send_timeout, limit_connEvent-driven, so idle connections are cheap, but still bounded by worker_connections
Apache httpdmod_reqtimeout (RequestReadTimeout with minrate), MaxRequestWorkersProcess or thread per connection: the classic victim
HAProxytimeout http-request, timeout clientTerminates and buffers; protects the app behind it
Envoyrequest_headers_timeout, stream_idle_timeout, request_timeoutPer listener or route
PHP-FPM behind NGINXNGINX absorbs the slow client, FPM sees the request only when it is completeWhy PHP apps should never face the internet without NGINX or a CDN

Real scenario: A Go service that used http.ListenAndServe(":8080", mux) is held open by 2,000 sockets from one laptop. The fix is a four-line struct literal; see The Go code.

Fix / how to use it: Set every timeout on every server; put a reverse proxy that buffers requests in front; cap total connections per client (Limits at the origin). OWASP adds: "Define a minimum ingress data rate with request-read timeouts" and warns that a minimum rate set too high "can reject legitimate slow clients".

HTTP floods, cache busting, expensive endpoints and Rapid Reset Must-know ​

In plain words: The attacker sends perfectly legal web requests, in huge numbers or aimed at the one page that costs the most.

Common misunderstanding: "Every request in an L7 attack is malicious-looking." In an HTTP flood each request is valid; only the volume, the cost or the pattern is wrong, so signature-based filtering alone has little to match.

Definition: An HTTP flood is an L7 attack that exhausts CPU, workers, database connections or a third-party API quota with valid requests. Cache busting appends random query strings (?x=8f3a) so every request misses the CDN and reaches the origin. Expensive endpoint abuse targets search, report export, login (password hashing), password reset (sends email), or GraphQL queries with deep nesting. HTTP/2 Rapid Reset (CVE-2023-44487) opens streams and cancels them immediately with RST_STREAM, so the server starts the work and the client does not wait for it: Google's report states the attack "relies on the ability for an endpoint to send a RST_STREAM frame immediately after sending a request frame".

Cache busting against a CDN with 95% hit ratio
1  normal:  1000 req/s from users -> 50 req/s reach the origin
2  attack:  1000 req/s of GET /search?q=shoes&_=<random> -> 0% hit ratio
3  origin:  1000 req/s of full-text queries instead of 50 req/s
4  fix:     ignore unknown query parameters in the CDN cache key; cache negative results too
AttackWhy it is cheap for the attackerDefence
Plain GET flood of the home pageStatic page, bandwidth onlyCDN cache, scrubbing
Cache-busting GETDefeats the CDNNormalise the cache key, allowlist query parameters, rate limit per client
Search or export endpointOne request costs the DB secondsPer-endpoint limits, timeouts, result caching, a queue, authentication
Login and password resetPassword hashing is deliberately slow; email costs moneyTight per-IP and per-account limits, challenge, CAPTCHA
POST with large bodyParsing, upload, virus scanBody size cap, auth before upload
HTTP/2 Rapid ResetServer does work for cancelled streamsPatch; cap streams reset per connection; CDN absorbs
GraphQL deep queriesSingle request, exponential workQuery depth and cost limits (GraphQL)

Real scenario: A shop's search endpoint runs a full-text scan. A competitor's bot requests random words at 300 requests per second from 5,000 addresses. Each address is far below any per-IP limit; the database is saturated. Per-IP limits did not apply, a global ceiling on the endpoint, a cache keyed on normalised query and a challenge on that route did.

Fix: Go and Laravel code in Go and Laravel.

Bots and botnets Important ​

In plain words: A botnet is a pile of hijacked or rented devices that the attacker commands; "bot" traffic also includes scrapers and credential-stuffing scripts that are not attacking you on purpose.

Common misunderstanding: "Block bad bots and the attack ends." The same fleet that floods you can send each address's traffic at a trickle, so per-address rules see nothing wrong.

Definition: A botnet is a set of compromised or rented machines. The 7.3 Tbps attack came from 122,145 source IPs in 5,433 autonomous systems and 161 countries (Cloudflare); Cloudflare also runs a free DDoS Botnet Threat Feed that tells hosting providers which of their addresses attack. Bot management classifies clients as humans, good bots (search crawlers) or bad bots with signals such as TLS and HTTP/2 fingerprints, behaviour and reputation, and then allows, challenges or blocks them.

Bot typeLooks likeSignalsResponse
DDoS botnetMany addresses, valid requestsBurst across addresses, same fingerprintScrubbing, challenge, global ceiling
ScraperSteady, ordered crawlingSequential IDs, missing assetsRate limit, require login, honeypot
Credential stufferLogin POSTs with different accountsFailed login ratioPer-account limit, MFA, challenge
Good bot (Googlebot)Declares itselfReverse DNS verificationAllow after verification

Anycast scrubbing networks Must-know ​

In plain words: One IP address is announced from a hundred cities; each attacker's traffic lands at the nearest city, where it is filtered, and only clean traffic travels on to you.

Common misunderstanding: "Anycast is a load balancer." It is a routing trick: the same prefix is announced by many sites and BGP delivers each packet to the closest. It spreads an attack the way it spreads users, and is what lets a provider with more capacity than the attack take it.

Definition: A scrubbing centre (or scrubbing network) is infrastructure that receives your traffic, drops what matches attack fingerprints and forwards the rest. Cloudflare says that with global anycast "the attack packets that targeted the IP were routed to the closest Cloudflare data center", which "allows us to spread the attack traffic and use its distributed nature against it". Detection is automatic: Cloudflare samples packets in the kernel with eBPF in XDP and its dosd daemon finds common header patterns, then installs rules.

Always-on (reverse proxy)                  On-demand / BGP (Magic Transit style)
DNS www -> CDN anycast IP                  your /24 announced by the provider
CDN pulls from origin (private)            attack: traffic diverted to scrubbing
origin sees only CDN addresses             clean traffic returns over GRE or interconnect
Botnet, AsiaBotnet, EuropeLegit usersPoP A (scrubs)PoP B (scrubs)PoP C (scrubs)Your origin40% of attack45% of attackfew Mbpssame anycast addresssame anycast addresssame anycast addressaccepts only the scrubber'sranges (security group)private interconnect or tunnelclean only
ProductModelWhat the vendor documents
CloudflareReverse proxy for HTTP (DNS points at it); Magic Transit for whole IP prefixesEvery service runs in every data center; 7.3 Tbps stopped autonomously
AkamaiCDN and a scrubbing service; GitHub moved its BGP announcements to Akamai during the 2018 attackAbsorbed the 1.35 Tbps memcached attack for GitHub
AWS Shield Standard / AdvancedBuilt into CloudFront, Route 53, Global Accelerator, ELB, Elastic IPPacket validation, ACLs and shapers, suspicion scoring, TCP SYN proxy, rate distribution; Advanced adds SRT support and WAF cost coverage
Google Cloud ArmorSecurity policies on global external Application Load Balancers and othersPreconfigured WAF rules, rate limiting, Adaptive Protection
Azure DDoS ProtectionNetwork and IP protection tiersNot covered here; read the vendor docs

Real scenario: GitHub's 2018 incident: at 17:21 UTC the monitoring saw an anomaly in the ratio of ingress to egress; at 17:26 the operators withdrew BGP announcements over transit providers and announced the prefix only over Akamai; at 17:30 recovery was complete.

Fix / how to use it: Always-on proxy for HTTP/S; on-demand BGP diversion if you own IP space; and in both cases lock the origin (Origin protection).

RTBH, BGP blackholing and flowspec Important ​

In plain words: When an attack is bigger than you can handle, you can tell your provider "drop all traffic to this address"; it saves the rest of your network and finishes the job of the attacker for that address.

Common misunderstanding: "Blackholing stops the attack." It stops the traffic to the victim IP, legitimate users included. It is a last-resort sacrifice, like cutting off a branch to save the tree.

Definition: RTBH (Remotely Triggered Black Hole, RFC 5635) is a technique where a route for the victim address is announced with a next hop that is a null interface, usually via a BGP community the provider recognises (the RFC's examples use a route to Null0). BGP flowspec (RFC 8955) is a BGP extension for distributing traffic filters: match on destination and source prefix, IP protocol, ports, TCP flags, packet length, and apply an action such as rate limit, discard or redirect. Where RTBH is all-or-nothing for an address, flowspec can say "drop UDP from source port 11211 to this /32".

TechniqueGranularityCollateralNeeds
RTBH (destination-based)Whole destination addressAll traffic to it, including goodA provider offering a blackhole community
Source-based RTBH with uRPFSource addressesLittle, if sources are knownuRPF on edge routers
BGP flowspec5-tuple, flags, lengthSmallA provider or router that accepts flowspec routes from you
Scrubbing diversionEverything, then filterAdded latencyContract and BGP/GRE setup

Fix: Agree with the provider in advance which community triggers a blackhole and who may announce it. Rehearse it. Prefer the scrubbing path and keep RTBH for protecting the rest of the infrastructure.

WAF, bot management, JS challenge and CAPTCHA Must-know ​

In plain words: A web application firewall reads the HTTP request and applies rules; a challenge asks the client to prove it is a real browser before it gets through.

Common misunderstanding: "A CAPTCHA stops a DDoS." OWASP's cheat sheet says puzzles "serve a purpose against functionality abuse but this kind of technology will not help defend against DoS attacks". A challenge page also has to be served by something that survives the flood.

Definition: A WAF inspects layer 7 traffic: signatures for SQL injection and XSS (see OWASP Top 10), rate-based rules, geo and ASN rules, managed rule sets. Bot management scores requests. A JS challenge makes the client run JavaScript (and optionally a proof of work) and returns a cookie. CAPTCHA needs a human. Actions are typically allow, block, count (log only), challenge and CAPTCHA.

ProductRule engineChallengeNotes
Cloudflare WAF and Bot ManagementManaged rules, custom rules, rate limitingJS challenge, Managed Challenge, TurnstileRuns at the edge, before your origin
AWS WAFWeb ACLs, rule groups, rate-based rulesCAPTCHA and Challenge actions, Bot ControlAttach to CloudFront, ALB, API Gateway; Bot Control, CAPTCHA and large bodies cost extra
Google Cloud ArmorSecurity policies, preconfigured WAF rules, rate limitingreCAPTCHA integrationAdaptive Protection learns a baseline
NGINX with ModSecurity and the OWASP Core Rule SetOpen-source rule engineNone built inYou run and tune it

What to do in an attack: Put rules in count mode first and compare with legitimate traffic; then block. Rate-based rules with an aggregation key (IP, header, JA3/JA4 fingerprint) are the quickest lever. Challenge only the targeted routes so that API clients and the mobile app are not locked out.

Fix / how to use it: A stateless challenge in Go is in the Go code: an HMAC-signed puzzle bound to the client address and User-Agent, a proof-of-work the browser solves, and a signed cookie. It is a teaching version of what an edge product does with far more signals.

Limits at the origin: per-IP rate limits, connection limits, timeouts Must-know ​

In plain words: Your own servers need three cheap defences that work even if everything upstream is missing: a limit on how fast one client can ask, a limit on how many sockets one client can hold, and a timeout on every wait.

Common misunderstanding: "I rate limit, so I am protected." A per-IP limit stops one noisy client and does nothing against a botnet in which every address stays below the limit; the rate limiting chapter is explicit about this.

Definition: Rate limiting controls requests per time per key (algorithms in Rate Limiting). A connection limit caps simultaneous connections, per client or total: NGINX limit_conn_zone and limit_conn, Envoy circuit-breaker max_connections, Go netutil.LimitListener. A timeout bounds every phase: header read, body read, response write, idle keep-alive.

DefenceProtects againstGoLaravel / PHPNGINX
Per-IP token bucketOne heavy clientperip.Middleware (this page)RateLimiter::for + throttle:namelimit_req_zone + limit_req
Global ceilingA botnet below per-IP limitsSecond perip bucket with a constant keyA Limit::perSecond(200)->by('global')limit_req with a constant key
Connection limitMany sockets from one source, FD exhaustionnetutil.LimitListenerNGINX in frontlimit_conn
Header timeoutSlowlorisReadHeaderTimeoutclient_header_timeout in NGINXclient_header_timeout
Body idle timeoutSlow POSThttp.ResponseController.SetReadDeadlineclient_body_timeoutclient_body_timeout
Body size capGiant uploadshttp.MaxBytesReaderpost_max_size, client_max_body_sizeclient_max_body_size
Execution time capSlow endpoints holding workerscontext.WithTimeoutOctane max_execution_timeproxy_read_timeout

Fix: The whole stack in Go is hardened.Chain in the Go code; in Laravel it is the named limiters and TrustProxies in the Laravel code.

Caching to absorb Important ​

In plain words: If the answer is the same for everyone, compute it once and let a cache hand it out; the attacker then hits the cache, not your database.

Common misunderstanding: "We have a CDN, so floods hit the CDN." Only when the requests are cacheable: random query strings, cookies and POSTs bypass it.

Definition: Caching in the DDoS context means (a) a CDN cache hit ratio as capacity multiplier, (b) normalising the cache key (drop unknown query parameters, ignore tracking cookies), (c) caching expensive results briefly even when they are "dynamic" (1 to 30 seconds is enough to flatten a flood), (d) request coalescing so one miss triggers one origin fetch, and (e) serving stale content when the origin is struggling (stale-while-revalidate, stale-if-error). See CDNs and Caching.

ToolSettingEffect during an attack
CDN (Cloudflare, CloudFront, Fastly, Akamai)Cache key allowlist for query parametersCache busting stops working
CDN"Always online" or serve-staleSite shows content while origin is down
LaravelCache::flexible($key, [30, 90], ...)Stale-while-revalidate: one rebuild per key
Gosingleflight.Group around the missOne query per key at a time
NGINXproxy_cache_lock on, proxy_cache_use_stale updatingCoalescing and stale serving

Autoscaling and economic denial of sustainability Must-know ​

In plain words: If your system grows to meet any load, an attacker can make it grow, and you pay for the growth.

Common misunderstanding: "Autoscaling is a DDoS defence." It is a defence against honest growth. Against an attack it either follows the attack into a large bill, or stops at its maximum and fails anyway.

Definition: Economic denial of sustainability (EDoS, also called a denial-of-wallet attack) is an attack whose damage is the resource bill, not the outage. The autoscaling cost also includes per-request pricing (serverless invocations, WAF requests, egress bandwidth, log ingestion). AWS says its aim is that you "avoid unnecessary direct costs when your infrastructure must scale in response to an attack", and Shield Advanced offers coverage for scaling charges; read the current terms before relying on it.

Cost of one hour of attack: 10,000 req/s hitting an autoscaled /search
1  autoscaler adds 40 instances over 6 minutes; database at 100% anyway
2  egress and WAF request fees rise with traffic; log pipeline ingests 10,000 lines/s
3  after the attack: the fleet scales in slowly; the bill arrives next month
4  design target: fixed maximum, shed above it, edge blocks before the meter runs
ControlWhereEffect
Maximum instance count and budget alarmAuto Scaling group, Kubernetes HPA maxReplicas, cloud budgetsBill is bounded
Scale on a latency or queue signal, not raw requestsAutoscalerDoes not follow attack traffic blindly
Block before meteringCDN or WAF in frontBlocked requests are cheaper than served ones
Cap serverless concurrencyLambda reserved concurrency, Cloud Run max instancesDownstream database is protected
Sample logs under attackLog pipelineLog ingestion cost is bounded

Origin protection Must-know ​

In plain words: If the attacker learns your server's real IP address, they can go around the protection in front of it.

Common misunderstanding: "Nobody knows our origin IP." It leaks through old DNS records, certificate transparency logs, email headers, a staging host and cloud address ranges that attackers can scan.

Definition: Origin protection means the origin accepts connections only from the edge: a security group or firewall that allows only the CDN's published ranges (Cloudflare publishes them at its IP ranges page), an authenticated origin pull (mutual TLS or a secret header), or a private connection (a tunnel, Direct Connect, PrivateLink). On top, rotate the origin IP after you adopt a CDN and never serve content from the same IP that is directly reachable.

MethodStrengthLimitation
Security group allowing only CDN rangesStrong at L3/L4Ranges change; automate refresh; other tenants of the same CDN can reach you
Secret header from the CDNCheap second lockLeaks if logged; not a replacement for the network rule
Authenticated origin pull (mTLS)StrongCertificate management
Tunnel from origin to edge (outbound only)Origin has no public listenerEdge outage means outage
Laravel OriginLock middlewareApplication-level second lockRuns after the request is accepted

Firewalls: stateless vs stateful, security groups vs NACLs, WAF vs network firewall Must-know ​

In plain words: A firewall is a list of allow and deny rules for network traffic; the difference is whether it remembers connections.

Common misunderstanding: "A security group and a network ACL are the same thing at different sizes." They differ in what they attach to, whether they remember, and how rules are evaluated.

Definition: A stateless firewall judges each packet alone, so the reply to an allowed request needs its own rule. A stateful firewall keeps a connection table: if the request is allowed, the reply is allowed automatically (NIST SP 800-41 Rev. 1 describes "several types of firewall technologies" with their "relative advantages and disadvantages", from packet filtering to proxies, and gives recommendations for firewall policy). AWS: "NACLs are stateless ... Security groups are stateful", and AWS recommends: "Use security groups as the primary mechanism for controlling network access to your VPCs. When necessary, use network ACLs to provide stateless, coarse-grain network control."

PropertySecurity group (AWS)Network ACL (AWS)Host firewall (iptables/nftables)WAF
Attached toNetwork interface (instance, ENI)SubnetThe hostLoad balancer, CDN, API gateway
StateStatefulStatelessStateful with conntrackPer HTTP request
Rule typesAllow onlyAllow and deny, numbered, lowest firstAllow and dropAllow, block, count, challenge
Can referenceOther security groupsCIDRs onlyAddresses, setsHeaders, URIs, bodies, IP sets, rate
Typical useTier-to-tier accessBlock a hostile range; subnet guard railLast line on the boxSQLi, XSS, bots, L7 floods
Sees TLS contentNoNoNoYes, after termination

See Firewalls for rule syntax. The rule of thumb: security groups for who may talk to whom, NACLs only for subnet-wide deny lists and as a guard rail "in case an instance is ever launched without the correct security group", a WAF for what is inside HTTP, and a network firewall (AWS Network Firewall, Cloud NGFW, a Palo Alto or pfSense appliance) for deep inspection of traffic that passes between VPCs, or to the internet.

Egress filtering and allowlists Must-know ​

In plain words: Most teams block what comes in and allow everything that goes out; attackers use that outbound path to download tools and send data away.

Common misunderstanding: "A private subnet cannot be reached, so it is safe." It cannot be reached from the internet. It can reach the internet through the NAT gateway, and so can malware inside it.

Definition: Egress filtering restricts outbound traffic to a short allowlist of destinations (by security group egress rules, a proxy, DNS firewall or Network Firewall domain lists). It limits server-side request forgery (SSRF: the server is tricked into fetching an attacker's URL, often the cloud metadata address 169.254.169.254), command-and-control and data exfiltration. OWASP Top 10 covers SSRF itself.

SSRF with and without egress control
1  attacker  POST /import {"url":"http://169.254.169.254/latest/meta-data/iam/security-credentials/"}
2  app       fetches the URL from inside the VPC
3  without egress rules: credentials returned to the attacker
4  with an egress allowlist + IMDSv2 + no route to metadata from the app proxy: connection blocked, alert
ControlMechanism
Security group egressRemove the default allow-all outbound rule; allow only the database SG and the endpoint SG
Forward proxy with allowlistApp can only reach the proxy; proxy allows listed hosts (Forward vs Reverse Proxies)
DNS firewallResolver refuses names outside a list (Route 53 Resolver DNS Firewall, CoreDNS plugins)
Network Firewall domain allowlistSNI and HTTP host inspection
Kubernetes NetworkPolicy egressPods may reach only named pods and namespaces
Metadata hardeningIMDSv2 required, hop limit 1, block 169.254.169.254 from containers that do not need it

VPC design: subnets, NAT gateway, route tables Must-know ​

In plain words: A VPC is your own private network in the cloud; you cut it into subnets and write the routes that decide which ones can talk to the internet.

Common misunderstanding: "Public and private subnets are properties of the subnet." They are properties of its route table: a public subnet has a route to an internet gateway, a private subnet does not.

Definition: AWS: "Use separate VPCs to isolate infrastructure by workload or organizational entity ... Use subnets to isolate the tiers of your application (for example, web, application, and database) within a single VPC. Use private subnets for your instances if they should not be accessed directly from the internet." A route table maps destination prefixes to targets (local, internet gateway, NAT gateway, transit gateway, VPC endpoint, peering connection). A NAT gateway lets instances in a private subnet "connect to services outside your VPC but external services can't initiate a connection with those instances"; a public NAT gateway sits in a public subnet with an Elastic IP.

VPC 10.0.0.0/16, two availability zonesPublic subnets 10.0.0.0/24, 10.0.1.0/24Private app subnets 10.0.10.0/24, 10.0.11.0/24Private data subnets 10.0.20.0/24, 10.0.21.0/24Internet gatewayVPC endpointsAdmin accessALB (sg-lb: 443 from CDN ranges)NAT gateway (egress only, one per AZ)App tasks (sg-app: 8080 from sg-lb only)no public IP, default route to NATPostgreSQL (sg-db: 5432 from sg-app only)no route to the internet at all0.0.0.0/0 routeS3 gateway endpointInterface endpoints:ECR, Secrets ManagerSSM Session Manager,no inbound port 22
Route tableDestinationTargetMeaning
Public subnets10.0.0.0/16localIntra-VPC traffic
Public subnets0.0.0.0/0Internet gatewayPublic: reachable and able to reach out
Private app subnets10.0.0.0/16localIntra-VPC traffic
Private app subnets0.0.0.0/0NAT gateway in the same AZOutbound only; AZ-local NAT avoids a single AZ dependency and cross-AZ fees
Private app subnetspl-xxxx (S3 prefix list)Gateway endpointS3 without NAT
Private data subnets10.0.0.0/16localNo default route: cannot reach the internet
DecisionRecommendationReason
Where do load balancers goPublic subnetsThey need an internet-facing address
Where do app servers goPrivate subnetsNot directly reachable; traffic only via the load balancer
Where do databases goPrivate data subnets with no default routeA compromised app cannot be used as a bridge to the internet through the database tier
NAT per AZYes for productionA single NAT is a single point of failure and a cross-AZ cost
IPv6 egressEgress-only internet gatewayOutbound only, like NAT
CIDR planNon-overlapping ranges across VPCs and on-premisesPeering and transit gateway cannot route overlapping CIDRs

Connecting networks: peering, transit gateway, PrivateLink, VPN Important ​

In plain words: Once you have several networks, you decide whether they can see each other completely, or only see one service.

Common misunderstanding: "Peering connects my networks, so routing is transitive." VPC peering is point-to-point and not transitive; a hub needs a transit gateway.

Definition: VPC peering connects two VPCs, without transitive routing. A transit gateway is a regional hub: each VPC, VPN and Direct Connect attaches once, and route tables on the gateway decide who may reach whom. PrivateLink "connect[s] your VPC to services and resources as if they were in your VPC. You do not need to use an internet gateway, NAT device, public IP address, Direct Connect connection, or AWS Site-to-Site VPN connection". A VPC endpoint is the consumer side: a gateway endpoint (S3, DynamoDB) is a route table target; an interface endpoint (a private endpoint) is a network interface with a private IP in your subnet. A VPN (Site-to-Site or Client VPN; WireGuard in VPNs & Tunnels) joins networks over the internet.

OptionExposesTransitiveBest for
VPC peeringThe whole other VPC (limited by routes and SGs)NoTwo VPCs, small
Transit gatewayWhatever the route tables allowYesMany VPCs, hub-and-spoke, on-premises
PrivateLink (endpoint service)One service behind a load balancerN/ASaaS, shared services, no CIDR coordination
Gateway endpointS3, DynamoDBN/AFree, no NAT cost for S3
Interface endpointOne AWS or partner serviceN/AAWS APIs (Secrets Manager, ECR) without NAT
Site-to-Site VPN, Client VPNWhole network or userDependsOn-premises, remote work
Direct ConnectPrivate fibreDependsStable bandwidth

Admin access: bastion hosts vs SSM Session Manager Important ​

In plain words: Someone needs a shell on a server in a private subnet; the old way is a jump machine with SSH open to the world, the better way has no open inbound port at all.

Common misunderstanding: "A bastion with key-only SSH is secure enough." It is a public, long-lived, attackable host and its keys are shared and hard to audit.

Definition: A bastion host (jump host) is a hardened machine in a public subnet through which admins reach private hosts (see SSH ProxyJump). AWS Systems Manager Session Manager (SSM Session Manager) gives shell access through an agent that connects outbound to the SSM service, authorised by IAM, with no inbound port, no SSH key and an audit log in CloudWatch or S3. Google Cloud's Identity-Aware Proxy TCP forwarding and Azure Bastion are the equivalents.

PropertyBastion + SSHSSM Session Manager
Inbound port22 on the bastionNone
IdentitySSH keysIAM identities, MFA
AuditWhatever you collectSession logging to CloudWatch Logs or S3
Private instance needsReachable from bastionAgent plus an outbound path (NAT or interface endpoints)
CostA hostEndpoints if no NAT

Segmentation and micro-segmentation Must-know ​

In plain words: Divide the network into zones so that if one part is taken over, the attacker cannot walk everywhere.

Common misunderstanding: "We have a firewall at the edge, so inside everyone is trusted." That is a hard shell with a soft interior; one compromised pod becomes a tour of the whole cluster.

Definition: Segmentation splits the network by tier (public, application, data, management) and by environment (production, staging). Micro-segmentation goes down to the workload: each service may talk only to the services it needs, enforced by security groups that reference other security groups, Kubernetes NetworkPolicy, or a service mesh authorization policy (Istio AuthorizationPolicy, Linkerd Server and AuthorizationPolicy, Envoy RBAC), which also checks identity from mutual TLS (mTLS). It is the network half of zero trust (Authorization Models).

Kubernetes: pods are non-isolated until a NetworkPolicy selects them
1  no policy: any pod can reach any pod, and the internet
2  apply default-deny ingress and egress to namespace "shop"
3  add allow: web -> api:8080, api -> db:5432, api -> dns, api -> payments API CIDR
4  a compromised web pod cannot reach db: connection times out
LayerToolEnforcesNeeds
VPCSecurity groups referencing SGsL3/L4 between tiersCloud-native
SubnetNACLsSubnet-wide denyCloud-native
KubernetesNetworkPolicy (Kubernetes Networking)L3/L4 between podsA CNI that enforces it (Calico, Cilium); Kubernetes docs: policies are additive and "by default, a pod is non-isolated for egress"
MeshIstio AuthorizationPolicy, Linkerd policyL7 and identitySidecars or ambient mode; see Service Mesh
Hostiptables, nftables, eBPFPer hostAgent

The DNS layer Important ​

In plain words: Your site is unreachable if nobody can look up its name; DNS is a target, and also a lever.

Common misunderstanding: "DNS is just a record, not an attack surface." Authoritative servers get UDP floods, random-subdomain (water torture) queries that bypass resolver caches, and are used as reflectors.

Definition: Protections: a managed authoritative DNS on anycast (Route 53, Cloudflare DNS, Google Cloud DNS), several providers for resilience, response rate limiting on any server you run, DNSSEC with care for its extra response size (amplification), and a short TTL where you may need to move traffic (TTL is a trade-off; see IP, DNS, GeoDNS). During an attack, DNS is also how you pivot: change the record to point at a scrubbing service, which only works as fast as the old TTL expires.

RiskDefence
UDP flood to authoritative serversAnycast managed DNS; Shield Standard protects Route 53
Random-subdomain attackAnycast capacity, rate limits on NXDOMAIN per client
Being a reflectorDisable open recursion; response rate limiting
Long TTL blocks the pivotTTL 60 to 300 s on the records you may need to move
Registrar account takeoverRegistry lock, MFA

TLS and edge protections Good to know ​

In plain words: The first message of a secure connection costs the server much more than it costs the client, which attackers exploit.

Common misunderstanding: "HTTPS floods are the same as HTTP floods." They carry the extra CPU cost of handshakes, and a scrubbing network cannot inspect payloads unless it terminates TLS.

Definition: TLS handshake floods (many new connections, or renegotiation) burn CPU on asymmetric crypto. Mitigations: terminate TLS at the edge, enable session resumption, keep TLS 1.3 and HTTP/2 or HTTP/3 limits on streams and header sizes, and patch for known protocol flaws (Rapid Reset). The wire-level handshake is in TLS in Practice.

ControlProduct setting
Terminate at the edgeCDN or load balancer (ALB, NLB TLS listener, Cloud Load Balancing)
Limit HTTP/2 concurrent streamsNGINX http2_max_concurrent_streams, Envoy max_concurrent_streams
Header and request size capsNGINX large_client_header_buffers, Go MaxHeaderBytes
Disable client renegotiationDefault off in TLS 1.3

IDS, IPS and flow logs Important ​

In plain words: You cannot respond to what you cannot see: sensors tell you who is talking to whom, and some can block it.

Common misunderstanding: "Flow logs show the content of the attack." They record metadata only: addresses, ports, bytes, packets, accept or reject.

Definition: An IDS (intrusion detection system) alerts on suspicious traffic; an IPS (intrusion prevention system) sits in line and blocks. Suricata is an open-source IDS/IPS and network security monitoring engine; Zeek is a network security monitor that produces structured logs of connections and protocols rather than relying on signatures. VPC Flow Logs "capture information about the IP traffic going to and from network interfaces in your VPC", published to CloudWatch Logs, S3 or Data Firehose, "collected outside of the path of your network traffic, and therefore does not affect network throughput or latency". Google Cloud has VPC Flow Logs and Azure has NSG flow logs.

sql
-- Athena over VPC Flow Logs in S3: who is sending the most rejected packets to port 443?
SELECT srcaddr, sum(packets) AS pkts, sum(bytes) AS bytes
FROM vpc_flow_logs
WHERE action = 'REJECT' AND dstport = 443
  AND from_unixtime(start) > now() - interval '15' minute
GROUP BY srcaddr ORDER BY pkts DESC LIMIT 20;
ToolDoesFits
VPC Flow LogsMetadata per flowAlways on; attack triage, "who talked to the database"
AWS Traffic Mirroring, GCP Packet MirroringCopies packets to a sensorSuricata or Zeek analysis
SuricataSignature and protocol IDS/IPSPerimeter, east-west
ZeekStructured protocol logs, scriptingForensics, anomaly detection
GuardDuty (AWS)Managed detection on flow and DNS logsCheap first line

Testing and legality Good to know ​

In plain words: Do not point a flood at anything you do not own, and tell your provider before you point one at what you do.

Common misunderstanding: "It is my own server, so I can test anything." If it runs on a cloud provider's network, the provider's policy applies, and your flood crosses networks you do not own.

Definition: Flooding third-party systems is illegal in most jurisdictions. For your own systems, cloud providers have their own policies. AWS's DDoS Simulation Testing Policy says simulation "must be performed by an AWS Partner Network (APN) Partner that has been pre-approved by AWS", the target must be a protected resource of an account subscribed to Shield Advanced (or an edge-optimized API Gateway endpoint in such an account), volume may not exceed 20 gigabits per second, 50,000 requests per second, or 5 million packets per second against CloudFront (50,000 for other resources), and the test may not originate from an AWS resource or simulate amplification. Read the current policy before you plan anything. Commercial load tools (k6, Locust, Gatling, vegeta) are for load tests, not floods; "booter" or "stresser" services are criminal. Test with a written scope, a time window, a kill switch and your provider's approval.

TestAllowed how
Load test of your app at 3x peakYour own accounts, announce to the provider if large
L7 abuse test of your own WAF rulesStaging environment, rate-limited generator
Volumetric simulationOnly through a provider-approved partner and inside the provider's volume caps
Game day for the runbookTabletop plus a controlled drill (Chaos Engineering & Game Days)

Capacity planning and the runbook Must-know ​

In plain words: Decide before the attack who does what, in which order, with which switches.

Common misunderstanding: "We will work it out when it happens." During an attack the dashboards are slow, people are stressed and the person with the DNS login is on a plane.

Definition: A DDoS runbook is a numbered procedure with owners, thresholds, access paths and rollback. It plugs into the general incident response process. Capacity planning for attacks asks four questions: how much traffic can the edge absorb (contract), how much can the origin serve (load test), what is the maximum bill (budget cap), and how long until we notice (alert).

Runbook: suspected DDoS (first 60 minutes)
1  0-5    declare incident; one commander, one scribe; open the channel
2  5-10   classify: bandwidth graphs (volumetric), SYN-RECV counts (protocol), request rate by path and ASN (L7)
3  10-15  check the edge: are we behind the CDN or scrubbing service? is the origin IP being hit directly?
4  15-25  turn on stronger mode: under-attack or challenge on the hot path; WAF rate rules in block; cache TTLs up
5  25-35  protect the origin: security group to edge ranges only; global ceiling; shed non-critical features
6  35-45  call the provider and the scrubbing vendor; agree RTBH or diversion if volume exceeds contract
7  45-60  status page and customer message; keep logs; do not scale up blindly
8  after  roll back temporary rules; post-incident review; update thresholds
SignalLikely classFirst move
Inbound Mbps and packets at link limit, CPU idleVolumetricScrubbing, call the ISP
Many SYN-RECV, few establishedProtocolSYN cookies, edge proxy
High request rate, one path, CPU at 100%L7 floodWAF, rate rule, challenge, cache
Few requests, all workers busySlow attackTimeouts, proxy buffering
Cost alarm, normal traffic graphsEDoSMax caps, find the metered path

Mechanics ​

Formulas and numbers ​

QuantityFormulaExample
Amplification factorresponse bytes / request bytes51,000 for memcached; 28 to 54 for DNS
Reflector trafficattacker bandwidth x factor100 Mbps x 556.9 is about 55.7 Gbps of NTP
Packets per second at line ratebits per second / (8 x frame bytes)10 Gbps of 64-byte frames is about 14.9 Mpps
Slowloris capacityworker slots / (header timeout / drip interval)1000 slots held by 1000 sockets sending a byte every 10 s
Safe per-IP burstlegitimate peak per client x 220 requests for a page that loads 10 resources
Cache hit ratio effectorigin load = requests x (1 - hit ratio)10,000 req/s at 95% hit: 500 req/s; at 0%: 10,000
Challenge cost to attacker2 to the power of difficulty bits hashes18 bits is about 262,144 hashes per request

Product knobs ​

ProductKnobDefault or note
Go net/httpReadHeaderTimeout0 = none (if ReadTimeout is also 0)
Go net/httpMaxHeaderBytesDefaultMaxHeaderBytes is 1 MB
Gonetutil.LimitListener(l, n)Accept at most n simultaneous connections
Gohttp.MaxBytesReader(w, r.Body, n)Fails the read with an error once n bytes are exceeded
NGINXlimit_conn_zone $binary_remote_addr zone=addr:10m; limit_conn addr 10;503 by default (limit_conn_status)
NGINXclient_header_timeout, client_body_timeout60 s each
Linuxnet.ipv4.tcp_syncookies1 on most distributions
LaraveltrustProxies(at: [...]) in bootstrap/app.phpWithout it, $request->ip() is the proxy
Laravel Octanemax_execution_time in config/octane.php30 seconds
AWSSecurity group inbound rule sourceCIDR, prefix list or another security group
AWSVPC Flow Logs log-formatDefault fields: srcaddr, dstaddr, srcport, dstport, protocol, packets, bytes, action
KubernetesNetworkPolicy policyTypes: [Ingress, Egress]A pod selected by any policy is isolated for that direction

Error messages and signals you will actually see ​

WhereSignalMeaning
Linux kernel logTCP: request_sock_TCP: Possible SYN flooding on port 443. Sending cookies. (the kernel appends more text)The SYN queue overflowed; cookies are active
ss -sThousands in synrecvSYN flood or an overloaded app that does not accept
NGINX error loglimiting connections by zone "addr"limit_conn is rejecting
NGINX error logclient timed out (110: Connection timed out) while reading client request headersA slow client was cut
Gohttp: Server closed idle connection, context deadline exceeded, http: request body too largeTimeouts and MaxBytesReader at work
HTTP429 Too Many Requests with Retry-AfterYour rate limiter
HTTP503 from NGINX limit_req defaultRate limit in NGINX
HTTP403 with a challenge pageWAF or bot management
CloudflareError 1020 (access denied), 1015 (rate limited)A rule matched
AWSREJECT in a VPC Flow LogSecurity group or NACL blocked it
KubernetesConnection timeout (not refused) between podsNetworkPolicy dropping

Go ​

Before ​

The server below works in a demo. It has no timeouts, no connection cap, no body cap, and its "per-IP" limit is keyed on the left-most X-Forwarded-For entry, which the client writes.

go
// Before: a server that works in a demo and falls over in the first week of
// real traffic. No timeouts, no connection cap, no body cap, and a "rate
// limit" keyed on a header the client writes itself.
package main

import (
	"io"
	"net/http"
	"strings"
	"sync"
	"time"
)

var (
	mu    sync.Mutex
	count = map[string]int{}
)

func main() {
	go func() { // resets the counters every minute: a fixed window per "IP"
		for range time.Tick(time.Minute) {
			mu.Lock()
			count = map[string]int{}
			mu.Unlock()
		}
	}()

	http.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
		// The left-most X-Forwarded-For entry is whatever the client typed.
		ip := strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0]
		if ip == "" {
			ip = r.RemoteAddr
		}
		mu.Lock()
		count[ip]++
		n := count[ip]
		mu.Unlock()
		if n > 100 {
			http.Error(w, "slow down", http.StatusTooManyRequests)
			return
		}
		body, _ := io.ReadAll(r.Body) // unbounded read of an unbounded body
		_ = body
		w.Write([]byte("ok"))
	})

	// http.ListenAndServe uses a zero-value http.Server: ReadHeaderTimeout,
	// ReadTimeout, WriteTimeout and IdleTimeout are all zero, which means "no
	// timeout". One socket that sends a header byte every minute is held
	// for as long as the attacker likes.
	http.ListenAndServe(":8080", nil)
}

After ​

Five small packages, each with tests that run without sleeping where possible. clientip decides who the client is (trust the TCP peer; believe X-Forwarded-For only from your own proxies and take the right-most untrusted hop).

go
// Package clientip decides which IP address a request really came from.
// The rule: the TCP peer is the only address nobody can forge. A forwarding
// header is believed only when the peer is a proxy you operate (or Cloudflare,
// a CDN you configured), and then only the right-most hop that is not itself
// a trusted proxy is used, because proxies append on the right and the
// left-most entries are written by the client.
package clientip

import (
	"fmt"
	"net"
	"net/http"
	"net/netip"
	"strings"
)

// ParsePrefixes parses CIDR strings such as "203.0.113.0/24" or "2001:db8::/32".
func ParsePrefixes(cidrs ...string) ([]netip.Prefix, error) {
	out := make([]netip.Prefix, 0, len(cidrs))
	for _, c := range cidrs {
		p, err := netip.ParsePrefix(strings.TrimSpace(c))
		if err != nil {
			return nil, fmt.Errorf("clientip: bad prefix %q: %w", c, err)
		}
		out = append(out, p.Masked())
	}
	return out, nil
}

func trusted(a netip.Addr, set []netip.Prefix) bool {
	for _, p := range set {
		if p.Contains(a) {
			return true
		}
	}
	return false
}

// From returns the client address for r. proxies is the list of networks whose
// X-Forwarded-For header may be believed. An empty list means "no proxy in
// front of me": the peer address is the answer.
func From(r *http.Request, proxies []netip.Prefix) netip.Addr {
	host, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		host = r.RemoteAddr
	}
	peer, err := netip.ParseAddr(host)
	if err != nil {
		return netip.Addr{}
	}
	peer = peer.Unmap()
	if !trusted(peer, proxies) {
		return peer
	}
	hops := strings.Split(strings.Join(r.Header.Values("X-Forwarded-For"), ","), ",")
	for i := len(hops) - 1; i >= 0; i-- {
		a, err := netip.ParseAddr(strings.TrimSpace(hops[i]))
		if err != nil {
			return peer // malformed chain: blame the proxy, never the header
		}
		a = a.Unmap()
		if !trusted(a, proxies) {
			return a
		}
	}
	return peer // every hop was a trusted proxy
}

// Key is the rate-limit bucket for an address: IPv4 as /32, IPv6 as /64,
// because one IPv6 subscriber usually owns a whole /64 and can rotate inside it.
func Key(a netip.Addr) string {
	if !a.IsValid() {
		return "invalid"
	}
	if a.Is4() {
		return a.String()
	}
	p, _ := a.Prefix(64)
	return p.String()
}
go
package clientip

import (
	"net/http"
	"net/netip"
	"testing"
)

func req(remote string, xff ...string) *http.Request {
	r := &http.Request{RemoteAddr: remote, Header: http.Header{}}
	for _, v := range xff {
		r.Header.Add("X-Forwarded-For", v)
	}
	return r
}

func TestFrom(t *testing.T) {
	proxies, err := ParsePrefixes("198.51.100.0/24", "2001:db8:f::/48")
	if err != nil {
		t.Fatal(err)
	}
	cases := []struct {
		name string
		r    *http.Request
		want string
	}{
		{"direct client, no proxy", req("192.0.2.10:5555"), "192.0.2.10"},
		{"direct client forges XFF", req("192.0.2.10:5555", "203.0.113.9"), "192.0.2.10"},
		{"proxy appends the real client", req("198.51.100.7:443", "192.0.2.10"), "192.0.2.10"},
		{"client prepends a forged entry", req("198.51.100.7:443", "203.0.113.9, 192.0.2.10"), "192.0.2.10"},
		{"two proxies in a chain", req("198.51.100.7:443", "192.0.2.10, 198.51.100.8"), "192.0.2.10"},
		{"two header lines are joined", req("198.51.100.7:443", "203.0.113.9", "192.0.2.10"), "192.0.2.10"},
		{"garbage in the chain blames the proxy", req("198.51.100.7:443", "not-an-ip"), "198.51.100.7"},
		{"proxy without XFF", req("198.51.100.7:443"), "198.51.100.7"},
		{"IPv4-mapped IPv6 peer is unmapped", req("[::ffff:192.0.2.10]:80"), "192.0.2.10"},
		{"IPv6 proxy", req("[2001:db8:f::1]:443", "192.0.2.10"), "192.0.2.10"},
	}
	for _, c := range cases {
		if got := From(c.r, proxies).String(); got != c.want {
			t.Errorf("%s: got %s, want %s", c.name, got, c.want)
		}
	}
}

func TestKey(t *testing.T) {
	a := netip.MustParseAddr("2001:db8:1:2:aaaa:bbbb:cccc:dddd")
	b := netip.MustParseAddr("2001:db8:1:2:1111:2222:3333:4444")
	if Key(a) != Key(b) {
		t.Fatalf("same /64 must share a key: %s vs %s", Key(a), Key(b))
	}
	if got := Key(netip.MustParseAddr("192.0.2.1")); got != "192.0.2.1" {
		t.Fatalf("IPv4 key = %s", got)
	}
	if Key(netip.Addr{}) != "invalid" {
		t.Fatal("zero Addr must map to the invalid bucket")
	}
}

func TestParsePrefixesError(t *testing.T) {
	if _, err := ParsePrefixes("192.0.2.0/33"); err == nil {
		t.Fatal("want error for /33")
	}
}

perip is the token bucket per client, with a bounded table, a shared overflow bucket when a botnet fills it, and an injectable clock.

go
// Package perip is a per-key token bucket for L7 floods: bounded memory,
// a shared overflow bucket when a botnet fills the table, and a fake-able clock.
package perip

import (
	"math"
	"net/http"
	"strconv"
	"sync"
	"time"
)

type bucket struct {
	tokens float64
	last   time.Time
}

// Limiter holds one bucket per key. Rate is tokens per second, Burst the bucket size.
type Limiter struct {
	mu         sync.Mutex
	rate       float64
	burst      float64
	maxKeys    int
	now        func() time.Time
	buckets    map[string]*bucket
	overflow   bucket
	overflowOn bool
}

// New returns a limiter. maxKeys bounds memory: 0 means 100000 keys.
// now may be nil (time.Now); tests pass a fake clock.
func New(rate float64, burst int, maxKeys int, now func() time.Time) *Limiter {
	if now == nil {
		now = time.Now
	}
	if maxKeys <= 0 {
		maxKeys = 100_000
	}
	return &Limiter{rate: rate, burst: float64(burst), maxKeys: maxKeys, now: now, buckets: map[string]*bucket{}}
}

func (l *Limiter) take(b *bucket, now time.Time) (bool, time.Duration) {
	if delta := now.Sub(b.last).Seconds(); delta > 0 { // lazy refill, ignores a clock that went back
		b.tokens = math.Min(l.burst, b.tokens+delta*l.rate)
	}
	b.last = now
	if b.tokens >= 1 {
		b.tokens--
		return true, 0
	}
	return false, time.Duration((1 - b.tokens) / l.rate * float64(time.Second))
}

// Allow reports whether key may proceed and, if not, how long to wait.
func (l *Limiter) Allow(key string) (bool, time.Duration) {
	l.mu.Lock()
	defer l.mu.Unlock()
	now := l.now()
	b, ok := l.buckets[key]
	if !ok {
		if len(l.buckets) >= l.maxKeys {
			l.sweepLocked(now)
		}
		if len(l.buckets) >= l.maxKeys {
			// The table is full of live, busy keys: this is what a botnet with
			// a million addresses looks like. All newcomers share one bucket,
			// so memory stays flat and the origin still sees a bounded rate.
			if !l.overflowOn {
				l.overflow = bucket{tokens: l.burst, last: now}
				l.overflowOn = true
			}
			return l.take(&l.overflow, now)
		}
		b = &bucket{tokens: l.burst, last: now}
		l.buckets[key] = b
	}
	return l.take(b, now)
}

// sweepLocked deletes buckets that have refilled completely: forgetting them
// changes no decision, because a new bucket starts full too.
func (l *Limiter) sweepLocked(now time.Time) {
	for k, b := range l.buckets {
		if b.tokens+now.Sub(b.last).Seconds()*l.rate >= l.burst {
			delete(l.buckets, k)
		}
	}
}

// Len returns the number of tracked keys.
func (l *Limiter) Len() int {
	l.mu.Lock()
	defer l.mu.Unlock()
	return len(l.buckets)
}

// Middleware rejects with 429 and Retry-After. key derives the bucket from the
// request (use clientip.Key(clientip.From(r, proxies))).
func Middleware(l *Limiter, key func(*http.Request) string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if ok, wait := l.Allow(key(r)); !ok {
				secs := int(math.Ceil(wait.Seconds()))
				if secs < 1 {
					secs = 1
				}
				w.Header().Set("Retry-After", strconv.Itoa(secs))
				http.Error(w, "too many requests", http.StatusTooManyRequests)
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}
go
package perip

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"
)

type fakeClock struct{ t time.Time }

func (c *fakeClock) now() time.Time          { return c.t }
func (c *fakeClock) advance(d time.Duration) { c.t = c.t.Add(d) }

func TestBurstThenRate(t *testing.T) {
	c := &fakeClock{t: time.Unix(1_700_000_000, 0)}
	l := New(10, 5, 0, c.now) // 10 per second, bursts of 5
	for i := 0; i < 5; i++ {
		if ok, _ := l.Allow("a"); !ok {
			t.Fatalf("request %d inside the burst was refused", i)
		}
	}
	ok, wait := l.Allow("a")
	if ok || wait != 100*time.Millisecond {
		t.Fatalf("6th request: ok=%v wait=%v, want refused with 100ms", ok, wait)
	}
	c.advance(100 * time.Millisecond)
	if ok, _ := l.Allow("a"); !ok {
		t.Fatal("one token should have refilled after 100ms")
	}
	if ok, _ := l.Allow("b"); !ok {
		t.Fatal("another key has its own bucket")
	}
}

func TestSweepAndOverflow(t *testing.T) {
	c := &fakeClock{t: time.Unix(1_700_000_000, 0)}
	l := New(1, 2, 3, c.now) // at most 3 tracked keys
	for i := 0; i < 3; i++ {
		l.Allow(fmt.Sprintf("k%d", i))
	}
	// Table full of keys that are still draining: a newcomer shares the overflow bucket.
	admitted := 0
	for i := 0; i < 50; i++ {
		if ok, _ := l.Allow(fmt.Sprintf("bot%d", i)); ok {
			admitted++
		}
	}
	if admitted != 2 {
		t.Fatalf("overflow bucket admitted %d of 50 botnet newcomers, want its burst of 2", admitted)
	}
	if l.Len() != 3 {
		t.Fatalf("table grew to %d keys, must stay at 3", l.Len())
	}
	// After the buckets refill, a sweep frees space and a new key gets its own bucket.
	c.advance(10 * time.Second)
	if ok, _ := l.Allow("fresh"); !ok {
		t.Fatal("fresh key refused after sweep")
	}
	if l.Len() != 1 {
		t.Fatalf("after sweep want 1 key, got %d", l.Len())
	}
}

func TestMiddleware429(t *testing.T) {
	c := &fakeClock{t: time.Unix(1_700_000_000, 0)}
	l := New(1, 1, 0, c.now)
	h := Middleware(l, func(r *http.Request) string { return r.RemoteAddr })(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }))
	do := func() *httptest.ResponseRecorder {
		rec := httptest.NewRecorder()
		req := httptest.NewRequest("GET", "/", nil)
		req.RemoteAddr = "192.0.2.1:1234"
		h.ServeHTTP(rec, req)
		return rec
	}
	if got := do().Code; got != 200 {
		t.Fatalf("first = %d", got)
	}
	rec := do()
	if rec.Code != 429 || rec.Header().Get("Retry-After") != "1" {
		t.Fatalf("second = %d Retry-After=%q", rec.Code, rec.Header().Get("Retry-After"))
	}
}

hardened sets every server timeout, caps header and body size, ends slow POST with a per-read deadline, and wraps the listener with netutil.LimitListener. The tests use real loopback sockets: one drips header bytes (Slowloris), one stalls a body, one holds the only connection slot.

go
// Package hardened holds the connection-level defences that sit below any
// rate limiter: server timeouts that end Slowloris, a per-read deadline that
// ends slow POST, a request-body cap, and a cap on simultaneous connections.
package hardened

import (
	"net"
	"net/http"
	"time"

	"golang.org/x/net/netutil"
)

// Config holds the knobs. Zero values pick the defaults noted per field.
type Config struct {
	Addr              string
	ReadHeaderTimeout time.Duration // default 5s: the whole header block must arrive in this time (Slowloris)
	ReadTimeout       time.Duration // default 30s: header + body, hard ceiling
	WriteTimeout      time.Duration // default 30s: response must be written in this time (slow reader)
	IdleTimeout       time.Duration // default 60s: keep-alive connection with no request
	MaxHeaderBytes    int           // default 16 KiB (net/http default is 1 MiB)
	MaxConns          int           // 0 = unlimited; otherwise x/net/netutil.LimitListener
}

func (c Config) withDefaults() Config {
	if c.ReadHeaderTimeout == 0 {
		c.ReadHeaderTimeout = 5 * time.Second
	}
	if c.ReadTimeout == 0 {
		c.ReadTimeout = 30 * time.Second
	}
	if c.WriteTimeout == 0 {
		c.WriteTimeout = 30 * time.Second
	}
	if c.IdleTimeout == 0 {
		c.IdleTimeout = 60 * time.Second
	}
	if c.MaxHeaderBytes == 0 {
		c.MaxHeaderBytes = 16 << 10
	}
	return c
}

// NewServer returns an http.Server with every timeout set.
func NewServer(h http.Handler, c Config) *http.Server {
	c = c.withDefaults()
	return &http.Server{
		Addr:              c.Addr,
		Handler:           h,
		ReadHeaderTimeout: c.ReadHeaderTimeout,
		ReadTimeout:       c.ReadTimeout,
		WriteTimeout:      c.WriteTimeout,
		IdleTimeout:       c.IdleTimeout,
		MaxHeaderBytes:    c.MaxHeaderBytes,
	}
}

// Listen opens a TCP listener and, when maxConns > 0, wraps it so that at most
// maxConns connections are being served at once. Excess connections wait in
// the kernel accept queue (and are dropped when it is full) instead of
// consuming goroutines and file descriptors.
func Listen(addr string, maxConns int) (net.Listener, error) {
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		return nil, err
	}
	if maxConns > 0 {
		ln = netutil.LimitListener(ln, maxConns)
	}
	return ln, nil
}

// Chain applies middleware so that the first one listed is the outermost.
func Chain(h http.Handler, mws ...func(http.Handler) http.Handler) http.Handler {
	for i := len(mws) - 1; i >= 0; i-- {
		h = mws[i](h)
	}
	return h
}

// BodyLimit rejects bodies larger than n bytes: a declared Content-Length
// above n gets 413 at once, and a streamed body is cut by http.MaxBytesReader.
func BodyLimit(n int64) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.ContentLength > n {
				http.Error(w, "request body too large", http.StatusRequestEntityTooLarge)
				return
			}
			r.Body = http.MaxBytesReader(w, r.Body, n)
			next.ServeHTTP(w, r)
		})
	}
}

type idleReader struct {
	rc   *http.ResponseController
	body interface{ Read([]byte) (int, error) }
	idle time.Duration
}

func (r idleReader) Read(p []byte) (int, error) {
	// Push the read deadline forward before every read: a client may be slow
	// overall, but must deliver something at least every idle interval.
	_ = r.rc.SetReadDeadline(time.Now().Add(r.idle))
	return r.body.Read(p)
}

type bodyCloser struct {
	idleReader
	closer func() error
}

func (b bodyCloser) Close() error { return b.closer() }

// BodyIdleTimeout ends slow POST: the body must make progress at least every
// idle, however large the total timeout is. Needs HTTP/1.x or HTTP/2 with
// a ResponseWriter that supports http.ResponseController deadlines.
func BodyIdleTimeout(idle time.Duration) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			rc := http.NewResponseController(w)
			r.Body = bodyCloser{idleReader{rc: rc, body: r.Body, idle: idle}, r.Body.Close}
			next.ServeHTTP(w, r)
		})
	}
}
go
package hardened

import (
	"bufio"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

func TestNewServerSetsEveryTimeout(t *testing.T) {
	s := NewServer(http.NotFoundHandler(), Config{Addr: ":0"})
	if s.ReadHeaderTimeout == 0 || s.ReadTimeout == 0 || s.WriteTimeout == 0 || s.IdleTimeout == 0 {
		t.Fatalf("a zero timeout means no timeout: %+v", s)
	}
	if s.MaxHeaderBytes != 16<<10 {
		t.Fatalf("MaxHeaderBytes = %d", s.MaxHeaderBytes)
	}
}

func serve(t *testing.T, h http.Handler, c Config, maxConns int) string {
	t.Helper()
	ln, err := Listen("127.0.0.1:0", maxConns)
	if err != nil {
		t.Fatal(err)
	}
	srv := NewServer(h, c)
	go srv.Serve(ln)
	t.Cleanup(func() { srv.Close() })
	return ln.Addr().String()
}

// Slowloris: send a header byte now and then, never finish the header block.
func TestSlowlorisIsCutByReadHeaderTimeout(t *testing.T) {
	addr := serve(t, http.NotFoundHandler(), Config{ReadHeaderTimeout: 150 * time.Millisecond}, 0)
	c, err := net.Dial("tcp", addr)
	if err != nil {
		t.Fatal(err)
	}
	defer c.Close()
	start := time.Now()
	io.WriteString(c, "GET / HTTP/1.1\r\nHost: x\r\nX-a: ")
	closed := make(chan struct{})
	go func() { io.Copy(io.Discard, c); close(closed) }() // returns when the server closes
	tick := time.NewTicker(50 * time.Millisecond)
	defer tick.Stop()
	for {
		select {
		case <-closed:
			if d := time.Since(start); d > 2*time.Second {
				t.Fatalf("closed after %v, too late", d)
			}
			return
		case <-tick.C:
			io.WriteString(c, "b") // a drip is not enough: the deadline is for the whole header block
		case <-time.After(3 * time.Second):
			t.Fatal("server never closed the slow connection")
		}
	}
}

func TestBodyLimit(t *testing.T) {
	h := BodyLimit(10)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if _, err := io.ReadAll(r.Body); err != nil {
			http.Error(w, "too big", http.StatusRequestEntityTooLarge)
			return
		}
		w.WriteHeader(200)
	}))
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest("POST", "/", strings.NewReader("0123456789ABC")))
	if rec.Code != http.StatusRequestEntityTooLarge {
		t.Fatalf("declared 13 bytes with limit 10: got %d", rec.Code)
	}
	rec = httptest.NewRecorder()
	r := httptest.NewRequest("POST", "/", strings.NewReader("0123456789ABC"))
	r.ContentLength = -1 // chunked: unknown length, so MaxBytesReader must stop it
	h.ServeHTTP(rec, r)
	if rec.Code != http.StatusRequestEntityTooLarge {
		t.Fatalf("chunked body over the limit: got %d", rec.Code)
	}
	rec = httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest("POST", "/", strings.NewReader("tiny")))
	if rec.Code != 200 {
		t.Fatalf("small body: got %d", rec.Code)
	}
}

// Slow POST: Content-Length 100, one byte sent, then silence.
func TestSlowPostIsCutByBodyIdleTimeout(t *testing.T) {
	got := make(chan error, 1)
	h := BodyIdleTimeout(150 * time.Millisecond)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, err := io.ReadAll(r.Body)
		got <- err
	}))
	addr := serve(t, h, Config{ReadTimeout: time.Minute}, 0) // the hard ceiling alone would hold the socket for a minute
	c, err := net.Dial("tcp", addr)
	if err != nil {
		t.Fatal(err)
	}
	defer c.Close()
	io.WriteString(c, "POST / HTTP/1.1\r\nHost: x\r\nContent-Length: 100\r\n\r\nx")
	select {
	case err := <-got:
		if err == nil {
			t.Fatal("handler read the whole body from a stalled client?")
		}
	case <-time.After(3 * time.Second):
		t.Fatal("stalled body was never cut")
	}
}

// LimitListener: with n=1, a second connection is not served while the first is open.
func TestLimitListener(t *testing.T) {
	addr := serve(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok") }), Config{}, 1)
	first, err := net.Dial("tcp", addr)
	if err != nil {
		t.Fatal(err)
	}
	defer first.Close()
	io.WriteString(first, "GET / HTTP/1.1\r\nHost: x\r\n\r\n")
	if _, err := http.ReadResponse(bufio.NewReader(first), nil); err != nil {
		t.Fatal(err) // first connection is served and stays open (keep-alive)
	}
	second, err := net.Dial("tcp", addr) // the kernel completes the handshake...
	if err != nil {
		t.Fatal(err)
	}
	defer second.Close()
	io.WriteString(second, "GET / HTTP/1.1\r\nHost: x\r\n\r\n")
	second.SetReadDeadline(time.Now().Add(300 * time.Millisecond))
	if _, err := bufio.NewReader(second).ReadByte(); err == nil {
		t.Fatal("...but nobody may serve it while the first connection holds the only slot")
	}
	first.Close() // slot released
	second.SetReadDeadline(time.Now().Add(3 * time.Second))
	resp, err := http.ReadResponse(bufio.NewReader(second), nil)
	if err != nil {
		t.Fatalf("second connection never served after the slot freed: %v", err)
	}
	resp.Body.Close()
}

func TestChainOrder(t *testing.T) {
	var order []string
	mk := func(n string) func(http.Handler) http.Handler {
		return func(next http.Handler) http.Handler {
			return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				order = append(order, n)
				next.ServeHTTP(w, r)
			})
		}
	}
	Chain(http.NotFoundHandler(), mk("a"), mk("b")).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
	if strings.Join(order, "") != "ab" {
		t.Fatalf("order = %v", order)
	}
}

challenge is the stateless proof-of-work gate and the signed pass cookie.

go
// Package challenge is a stateless "prove you are a browser that can do work"
// gate, the shape behind Cloudflare's JS challenge and Turnstile, reduced to
// its mechanism: the server hands out an HMAC-signed puzzle bound to the
// client network and User-Agent, the client burns CPU to solve it (cheap for
// one visitor, expensive for a million requests per second), and a signed
// cookie then lets the visitor through for a while.
// It stops naive HTTP flooders. It does not stop a headless browser, and it
// is not accessibility-friendly on its own: offer an alternative path.
package challenge

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"math/bits"
	"net/http"
	"strconv"
	"strings"
	"time"
)

const (
	cookieName = "ddos_ok"
	verifyPath = "/__challenge/verify"
)

// Gate issues and verifies challenges.
type Gate struct {
	Secret     []byte
	Difficulty int           // leading zero bits required in sha256(nonce:counter); 18 is ~0.3 s in a browser
	PuzzleTTL  time.Duration // how long a puzzle is valid (default 2 min)
	PassTTL    time.Duration // how long the cookie is valid (default 30 min)
	Now        func() time.Time
	// Client returns the rate-limit identity of the request (clientip.Key of the real IP).
	Client func(*http.Request) string
}

func (g *Gate) now() time.Time {
	if g.Now != nil {
		return g.Now()
	}
	return time.Now()
}

func (g *Gate) mac(parts ...string) string {
	m := hmac.New(sha256.New, g.Secret)
	m.Write([]byte(strings.Join(parts, "|")))
	return hex.EncodeToString(m.Sum(nil)[:16])
}

func uaHash(r *http.Request) string {
	s := sha256.Sum256([]byte(r.UserAgent()))
	return hex.EncodeToString(s[:6])
}

// Puzzle returns a nonce the client must solve: expiry "." mac.
func (g *Gate) Puzzle(r *http.Request) string {
	ttl := g.PuzzleTTL
	if ttl == 0 {
		ttl = 2 * time.Minute
	}
	exp := strconv.FormatInt(g.now().Add(ttl).Unix(), 10)
	return exp + "." + g.mac("p", exp, g.Client(r), uaHash(r))
}

func leadingZeroBits(sum [32]byte) int {
	n := 0
	for _, b := range sum {
		if b == 0 {
			n += 8
			continue
		}
		return n + bits.LeadingZeros8(b)
	}
	return n
}

// Solve is what the browser JavaScript does; it is here so tests (and a load
// generator) can play the client.
func Solve(nonce string, difficulty int) uint64 {
	for c := uint64(0); ; c++ {
		if leadingZeroBits(sha256.Sum256([]byte(nonce+":"+strconv.FormatUint(c, 10)))) >= difficulty {
			return c
		}
	}
}

// Verify checks nonce authenticity, expiry and the proof of work.
func (g *Gate) Verify(r *http.Request, nonce, counter string) error {
	exp, mac, ok := strings.Cut(nonce, ".")
	if !ok {
		return fmt.Errorf("challenge: malformed nonce")
	}
	if !hmac.Equal([]byte(mac), []byte(g.mac("p", exp, g.Client(r), uaHash(r)))) {
		return fmt.Errorf("challenge: nonce was not issued to this client")
	}
	if ts, err := strconv.ParseInt(exp, 10, 64); err != nil || g.now().Unix() > ts {
		return fmt.Errorf("challenge: nonce expired")
	}
	if leadingZeroBits(sha256.Sum256([]byte(nonce+":"+counter))) < g.Difficulty {
		return fmt.Errorf("challenge: proof of work too weak")
	}
	return nil
}

// Pass returns the cookie that a solved challenge earns.
func (g *Gate) Pass(r *http.Request) *http.Cookie {
	ttl := g.PassTTL
	if ttl == 0 {
		ttl = 30 * time.Minute
	}
	exp := strconv.FormatInt(g.now().Add(ttl).Unix(), 10)
	return &http.Cookie{
		Name: cookieName, Value: exp + "." + g.mac("c", exp, g.Client(r), uaHash(r)),
		Path: "/", MaxAge: int(ttl.Seconds()), HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode,
	}
}

// HasPass reports whether the request carries a valid, unexpired cookie for this client.
func (g *Gate) HasPass(r *http.Request) bool {
	c, err := r.Cookie(cookieName)
	if err != nil {
		return false
	}
	exp, mac, ok := strings.Cut(c.Value, ".")
	if !ok || !hmac.Equal([]byte(mac), []byte(g.mac("c", exp, g.Client(r), uaHash(r)))) {
		return false
	}
	ts, err := strconv.ParseInt(exp, 10, 64)
	return err == nil && g.now().Unix() <= ts
}

const page = `<!doctype html><meta charset="utf-8"><title>Checking your browser</title>
<noscript>JavaScript is required for this check. Contact support if you cannot enable it.</noscript>
<p>Checking your browser, one moment.</p>
<script>
(async () => {
  const nonce = %q, bits = %d, enc = new TextEncoder();
  const zeros = (h) => { let n = 0; for (const b of new Uint8Array(h)) { if (b === 0) { n += 8; continue; } return n + Math.clz32(b) - 24; } return n; };
  for (let c = 0; ; c++) {
    const h = await crypto.subtle.digest("SHA-256", enc.encode(nonce + ":" + c));
    if (zeros(h) >= bits) {
      location = %q + "?n=" + encodeURIComponent(nonce) + "&c=" + c + "&back=" + encodeURIComponent(location.pathname + location.search);
      return;
    }
  }
})();
</script>`

// Middleware lets a request through when needChallenge says it is fine or it
// holds a valid pass; otherwise it answers 403 with the puzzle page. It also
// serves the verification endpoint itself.
func (g *Gate) Middleware(needChallenge func(*http.Request) bool) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.URL.Path == verifyPath {
				q := r.URL.Query()
				if err := g.Verify(r, q.Get("n"), q.Get("c")); err != nil {
					http.Error(w, "challenge failed", http.StatusForbidden)
					return
				}
				http.SetCookie(w, g.Pass(r))
				back := q.Get("back")
				if !strings.HasPrefix(back, "/") || strings.HasPrefix(back, "//") {
					back = "/" // never redirect off-site
				}
				http.Redirect(w, r, back, http.StatusSeeOther)
				return
			}
			if !needChallenge(r) || g.HasPass(r) {
				next.ServeHTTP(w, r)
				return
			}
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			w.Header().Set("Cache-Control", "no-store")
			w.WriteHeader(http.StatusForbidden)
			fmt.Fprintf(w, page, g.Puzzle(r), g.Difficulty, verifyPath)
		})
	}
}
go
package challenge

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strconv"
	"testing"
	"time"
)

func gate(now *time.Time) *Gate {
	return &Gate{
		Secret: []byte("test-secret-not-for-production"), Difficulty: 10,
		Now:    func() time.Time { return *now },
		Client: func(r *http.Request) string { return r.RemoteAddr },
	}
}

func get(h http.Handler, target string, cookie *http.Cookie) *httptest.ResponseRecorder {
	r := httptest.NewRequest("GET", target, nil)
	r.RemoteAddr = "192.0.2.1"
	r.Header.Set("User-Agent", "test-browser")
	if cookie != nil {
		r.AddCookie(cookie)
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, r)
	return rec
}

func TestFullFlow(t *testing.T) {
	now := time.Unix(1_700_000_000, 0)
	g := gate(&now)
	h := g.Middleware(func(*http.Request) bool { return true })(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("secret page")) }))

	if rec := get(h, "/account", nil); rec.Code != 403 {
		t.Fatalf("unchallenged client must get 403, got %d", rec.Code)
	}
	r := httptest.NewRequest("GET", "/", nil)
	r.RemoteAddr = "192.0.2.1"
	r.Header.Set("User-Agent", "test-browser")
	nonce := g.Puzzle(r)
	counter := Solve(nonce, g.Difficulty)

	q := url.Values{"n": {nonce}, "c": {itoa(counter)}, "back": {"/account"}}
	rec := get(h, "/__challenge/verify?"+q.Encode(), nil)
	if rec.Code != 303 || rec.Header().Get("Location") != "/account" {
		t.Fatalf("verify = %d -> %q", rec.Code, rec.Header().Get("Location"))
	}
	cookies := rec.Result().Cookies()
	if len(cookies) != 1 || !cookies[0].HttpOnly || !cookies[0].Secure {
		t.Fatalf("cookie flags: %+v", cookies)
	}
	if rec := get(h, "/account", cookies[0]); rec.Code != 200 {
		t.Fatalf("with the pass: %d", rec.Code)
	}
	now = now.Add(31 * time.Minute)
	if rec := get(h, "/account", cookies[0]); rec.Code != 403 {
		t.Fatalf("expired pass must be refused, got %d", rec.Code)
	}
}

func TestRejects(t *testing.T) {
	now := time.Unix(1_700_000_000, 0)
	g := gate(&now)
	r := httptest.NewRequest("GET", "/", nil)
	r.RemoteAddr = "192.0.2.1"
	nonce := g.Puzzle(r)
	good := itoa(Solve(nonce, g.Difficulty))

	if err := g.Verify(r, nonce, good); err != nil {
		t.Fatal(err)
	}
	if g.Verify(r, nonce, "not-a-solution") == nil {
		t.Fatal("bad counter accepted")
	}
	other := httptest.NewRequest("GET", "/", nil)
	other.RemoteAddr = "192.0.2.99"
	if g.Verify(other, nonce, good) == nil {
		t.Fatal("a puzzle solved by one client must not work for another address")
	}
	now = now.Add(3 * time.Minute)
	if g.Verify(r, nonce, good) == nil {
		t.Fatal("expired puzzle accepted")
	}
}

func TestOpenRedirectBlocked(t *testing.T) {
	now := time.Unix(1_700_000_000, 0)
	g := gate(&now)
	h := g.Middleware(func(*http.Request) bool { return true })(http.NotFoundHandler())
	r := httptest.NewRequest("GET", "/", nil)
	r.RemoteAddr = "192.0.2.1"
	nonce := g.Puzzle(r)
	q := url.Values{"n": {nonce}, "c": {itoa(Solve(nonce, g.Difficulty))}, "back": {"//evil.example"}}
	req := httptest.NewRequest("GET", "/__challenge/verify?"+q.Encode(), nil)
	req.RemoteAddr = "192.0.2.1"
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	if rec.Header().Get("Location") != "/" {
		t.Fatalf("redirect target = %q", rec.Header().Get("Location"))
	}
}

func itoa(n uint64) string { return strconv.FormatUint(n, 10) }

cmd/server wires them in the order a request meets them; cmd/attacksim replays a flood for the lab.

go
// Command server wires the defences in the order a request meets them.
// Run: DDOS_SECRET=$(openssl rand -hex 32) go run ./cmd/server
package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	"academy/ddos-network-security/challenge"
	"academy/ddos-network-security/clientip"
	"academy/ddos-network-security/hardened"
	"academy/ddos-network-security/perip"
)

func main() {
	secret := os.Getenv("DDOS_SECRET")
	if len(secret) < 32 {
		log.Fatal("set DDOS_SECRET to at least 32 characters")
	}
	// The networks your own load balancer or CDN connects from. Cloudflare
	// publishes its ranges at https://www.cloudflare.com/ips/ ; load them from
	// config, never from the request.
	proxies, err := clientip.ParsePrefixes("198.51.100.0/24", "2001:db8:f::/48")
	if err != nil {
		log.Fatal(err)
	}
	key := func(r *http.Request) string { return clientip.Key(clientip.From(r, proxies)) }

	limiter := perip.New(5, 20, 200_000, nil) // 5 req/s per client, bursts of 20
	gate := &challenge.Gate{Secret: []byte(secret), Difficulty: 18, Client: key}

	mux := http.NewServeMux()
	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "ok") })
	mux.HandleFunc("GET /search", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "results") })
	mux.HandleFunc("POST /upload", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "stored") })

	// Only /search is expensive: only it sits behind the proof-of-work gate.
	expensive := func(r *http.Request) bool { return strings.HasPrefix(r.URL.Path, "/search") }

	handler := hardened.Chain(mux,
		perip.Middleware(limiter, key),           // 1. cheapest check first: one map lookup
		gate.Middleware(expensive),               // 2. challenge only the costly paths
		hardened.BodyLimit(1<<20),                // 3. 1 MiB request bodies
		hardened.BodyIdleTimeout(10*time.Second), // 4. a body must keep moving
	)

	srv := hardened.NewServer(handler, hardened.Config{Addr: ":8080", MaxConns: 10_000})
	ln, err := hardened.Listen(srv.Addr, 10_000) // LimitListener: at most 10k connections served at once
	if err != nil {
		log.Fatal(err)
	}
	log.Fatal(srv.Serve(ln))
}
go
// Command attacksim replays an L7 flood against the per-IP limiter with a
// fake clock: 1 attacker address sending 1000 req/s, 5000 botnet addresses
// sending 2 req/s each, and 200 legitimate clients sending 1 req/s each,
// against a 5 req/s, burst 20 policy. The only knob is the key-table size:
// go run ./cmd/attacksim 2000   then   go run ./cmd/attacksim 20000
package main

import (
	"fmt"
	"os"
	"strconv"
	"time"

	"academy/ddos-network-security/perip"
)

func main() {
	maxKeys := 2000
	if len(os.Args) > 1 {
		if n, err := strconv.Atoi(os.Args[1]); err == nil {
			maxKeys = n
		}
	}
	clock := time.Unix(1_700_000_000, 0)
	l := perip.New(5, 20, maxKeys, func() time.Time { return clock })

	type tally struct{ ok, no int }
	var attacker, bots, legit tally
	for sec := 0; sec < 30; sec++ {
		for ms := 0; ms < 1000; ms++ {
			clock = time.Unix(1_700_000_000, 0).Add(time.Duration(sec*1000+ms) * time.Millisecond)
			if ok, _ := l.Allow("attacker"); ok { // 1 request per ms = 1000 req/s
				attacker.ok++
			} else {
				attacker.no++
			}
			if ms%500 == 0 { // 2 req/s from each of 5000 bots
				for b := 0; b < 5000; b++ {
					if ok, _ := l.Allow(fmt.Sprintf("bot%d", b)); ok {
						bots.ok++
					} else {
						bots.no++
					}
				}
			}
			if ms == 0 { // 1 req/s from each of 200 legitimate clients
				for c := 0; c < 200; c++ {
					if ok, _ := l.Allow(fmt.Sprintf("user%d", c)); ok {
						legit.ok++
					} else {
						legit.no++
					}
				}
			}
		}
	}
	fmt.Printf("attacker (1 IP, 1000 req/s)   served %6d  refused %6d\n", attacker.ok, attacker.no)
	fmt.Printf("botnet (5000 IPs, 2 req/s)    served %6d  refused %6d\n", bots.ok, bots.no)
	fmt.Printf("legitimate (200 IPs, 1 req/s) served %6d  refused %6d\n", legit.ok, legit.no)
	fmt.Printf("tracked keys: %d (cap %d)\n", l.Len(), maxKeys)
}

The Go angle ​

  • http.Server has five time limits and every one of them defaults to zero, which means "no timeout". ReadHeaderTimeout is the one that ends Slowloris, because it covers the whole header block, not the gap between bytes. Go's docs note that after the headers are read "the connection's read deadline is reset ... and the Handler can decide what is considered too slow for the body", which is why BodyIdleTimeout exists.
  • netutil.LimitListener(l, n) "returns a Listener that accepts at most n simultaneous connections from the provided Listener". It limits the total, not per client; a per-client connection limit belongs in NGINX (limit_conn) or a proxy.
  • http.MaxBytesReader enforces the cap even for chunked bodies where Content-Length is unknown; the middleware also rejects a declared oversize at once with 413.
  • A rate limiter keyed on r.RemoteAddr behind a load balancer sees one address; a limiter keyed on the left-most X-Forwarded-For sees whatever the client typed. clientip.From is the correct middle path; the same logic exists in Rate Limiting.
  • Go's net/http is not a substitute for a scrubbing network: it makes the origin cheap to attack-proof at L7, it adds nothing against a 40 Gbps flood.

Laravel ​

Before ​

An expensive public endpoint, a client-chosen cache key and a raw X-Forwarded-For header.

php
<?php

namespace App\Http\Controllers\Before;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

// Before: an expensive public endpoint with nothing in front of it.
class SearchController
{
    public function __invoke(Request $request)
    {
        // The client chooses the cache-busting query string and the work:
        // ?q=<random> misses every cache layer and runs a full-text scan.
        $q = (string) $request->query('q');

        // Trusting a header the client writes: the "per-IP" log and any
        // limiter built on it can be dodged by sending a new value each time.
        $ip = $request->header('X-Forwarded-For') ?: $request->server('REMOTE_ADDR');

        logger()->info('search', ['ip' => $ip, 'q' => $q]);

        // Unbounded work, unbounded page size, no timeout.
        return DB::table('products')
            ->whereRaw("to_tsvector('simple', description) @@ plainto_tsquery('simple', ?)", [$q])
            ->limit((int) $request->query('limit', 1000))
            ->get();
    }
}

After ​

bootstrap/app.php sets trustProxies (the Laravel 13 name for the TrustProxies middleware configuration), the Redis-backed throttle and the origin lock.

php
<?php

use App\Http\Middleware\OriginLock;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        health: '/up', // answered before the app boots: cheap for load balancer probes
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // Trust forwarding headers only from the networks that connect to you:
        // your load balancer, or the CDN's published ranges (Cloudflare lists
        // them at https://www.cloudflare.com/ips/). Documentation ranges below.
        // Never use at: '*' on a server that is reachable from the internet
        // directly: any client could then choose its own "IP".
        $middleware->trustProxies(
            at: ['198.51.100.0/24', '2001:db8:f::/48'],
            headers: Request::HEADER_X_FORWARDED_FOR
                | Request::HEADER_X_FORWARDED_HOST
                | Request::HEADER_X_FORWARDED_PORT
                | Request::HEADER_X_FORWARDED_PROTO,
        );

        // Atomic counters in Redis instead of the cache-based check-then-hit.
        $middleware->throttleWithRedis();

        // Run the origin lock before routing, so a request that bypassed the CDN
        // is refused before any application work.
        $middleware->prepend(OriginLock::class);
    })
    ->create();

Named limiters: a per-IP limit and a global ceiling for the expensive route.

php
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Expensive endpoint: tight per-IP limit, plus a global ceiling that
        // protects the database no matter how many addresses the attacker has.
        // Order matters: the first limit that is exceeded answers.
        RateLimiter::for('search', function (Request $request) {
            return [
                Limit::perSecond(200)->by('search-global'),
                Limit::perMinute(30)->by('search-ip:'.$request->ip()),
            ];
        });

        // Cheap endpoint: loose limit, only to stop one client from hogging workers.
        RateLimiter::for('page', fn (Request $request) => Limit::perMinute(300)->by('page-ip:'.$request->ip()));

        // A custom body for the refusal, with Retry-After kept.
        RateLimiter::for('login', fn (Request $request) => Limit::perMinute(10)
            ->by('login-ip:'.$request->ip())
            ->response(fn (Request $request, array $headers) => response('Too many attempts', 429, $headers)));
    }
}

The route and the controller with a normalised cache key and Cache::flexible.

php
<?php

use App\Http\Controllers\SearchController;
use Illuminate\Support\Facades\Route;

// The expensive route gets its own limiter; the shell page gets a loose one.
Route::get('/search', SearchController::class)->middleware('throttle:search');
Route::get('/', fn () => view('home'))->middleware('throttle:page');
php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

// After: bounded input, a normalised cache key, and one rebuild per key.
class SearchController
{
    public function __invoke(Request $request)
    {
        $q = mb_strtolower(trim((string) $request->query('q', '')));

        if ($q === '' || mb_strlen($q) > 64) {
            abort(422, 'q must be 1 to 64 characters');
        }

        $limit = min(max((int) $request->query('limit', 20), 1), 50);

        // Only q and limit take part in the key: ?q=shoes&cb=123 and every other
        // cache-busting parameter map to the same entry, which is the point.
        $key = 'search:'.hash('xxh128', $q.'|'.$limit);

        // Fresh for 30 s, served stale for 60 s more while one request rebuilds
        // in the background (the stale-while-revalidate pattern in Laravel's
        // Cache::flexible), so a popular expired key does not stampede the database.
        $rows = Cache::flexible($key, [30, 90], function () use ($q, $limit) {
            return DB::table('products')
                ->whereRaw("to_tsvector('simple', description) @@ plainto_tsquery('simple', ?)", [$q])
                ->limit($limit)
                ->get(['id', 'name', 'price']);
        });

        return response()->json($rows)->header('Cache-Control', 'public, max-age=30');
    }
}

The origin lock middleware, the Octane timeout excerpt and a feature test.

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

// Origin lockdown: the CDN adds a secret header (a Cloudflare Transform Rule,
// a CloudFront origin custom header). A direct hit on the origin IP, which
// bypasses the scrubbing network, lacks it and is refused. Pair it with a
// security group that admits only the CDN's ranges; the header alone is a
// second lock, not the first.
class OriginLock
{
    public function handle(Request $request, Closure $next): Response
    {
        $expected = (string) config('services.edge.secret');

        if ($expected !== '' && ! hash_equals($expected, (string) $request->header('X-Origin-Auth'))) {
            // 421 Misdirected Request would also fit; 403 reveals the least.
            abort(403);
        }

        return $next($request);
    }
}
php
<?php

// Excerpt of config/octane.php. Two settings matter under attack.
return [
    // A request that runs longer than this is killed (default 30). A flood of
    // expensive requests occupies a worker for this long each, so lower it to
    // the real worst case of your slowest legitimate endpoint. Restart Octane
    // after changing it.
    'max_execution_time' => 10,
];

// Worker recycling is a command-line flag, not a config key:
//   php artisan octane:start --workers=8 --max-requests=500
// Upstream timeouts belong to the reverse proxy in front (NGINX
// client_header_timeout, client_body_timeout, send_timeout, limit_conn).
php
<?php

namespace Tests\Feature;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class DdosDefenceTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        Cache::flush();
    }

    public function test_search_is_limited_per_ip_with_retry_after(): void
    {
        $this->freezeTime();

        foreach (range(1, 30) as $i) {
            $this->get('/search?q=shoes')->assertOk();
        }

        $this->get('/search?q=shoes')->assertStatus(429)->assertHeader('Retry-After');

        // Another address has its own counter.
        $this->withServerVariables(['REMOTE_ADDR' => '203.0.113.5'])
            ->get('/search?q=shoes')->assertOk();
    }

    public function test_cache_busting_parameters_share_one_cache_entry(): void
    {
        $this->get('/search?q=Shoes&cb=1')->assertOk();
        $queries = 0;
        DB::listen(function () use (&$queries) { $queries++; });

        $this->get('/search?q=shoes&cb=2')->assertOk();
        $this->get('/search?q=SHOES&utm=3')->assertOk();

        $this->assertSame(0, $queries, 'cache busting parameters must not reach the database');
    }

    public function test_oversized_query_is_rejected_before_any_work(): void
    {
        $this->get('/search?q='.str_repeat('a', 65))->assertStatus(422);
    }

    public function test_direct_origin_hits_are_refused(): void
    {
        config(['services.edge.secret' => 's3cret']);

        $this->get('/')->assertForbidden();
        $this->get('/', ['X-Origin-Auth' => 's3cret'])->assertOk();
    }
}

The Laravel angle ​

  • trustProxies: Laravel's documentation introduces it for apps behind a load balancer that terminates TLS (so generated links are HTTPS), and the same trusted forwarding headers decide what $request->ip() returns; without it the address is the proxy's. List the proxies in at:; for AWS Elastic Load Balancing the docs say to use Request::HEADER_X_FORWARDED_AWS_ELB for headers:. at: '*' is documented for cloud load balancers whose addresses you do not know, and is dangerous when the server can also be reached directly, because anyone can then choose their own address.
  • throttle:name and RateLimiter::for: return one Limit or an array; the first exceeded limit answers 429 with Retry-After. ->by() sets the key; ->response() customises the answer. The default cache-based throttle is check-then-hit, so under concurrency it can overshoot slightly; throttleWithRedis() uses atomic Redis scripts.
  • Cache::flexible($key, [fresh, stale], $callback) is Laravel's stale-while-revalidate: it serves a stale value while it recomputes in the background, which flattens an expired-key stampede on the database.
  • Maintenance mode: php artisan down --retry=60 --refresh=15 serves a static maintenance page with a Retry-After header; --secret lets operators bypass it. It is a panic button that turns your PHP into a static response, and it does not help if the flood is at the network layer.
  • Octane: workers are long-lived, so one slow request ties up one worker. max_execution_time (default 30 s) and --max-requests (default 500) bound that. NGINX or a load balancer in front must absorb slow clients before they reach Octane.
  • PHP-FPM: request_terminate_timeout and pm.max_children bound the worker pool; never expose FPM or Octane's port to the internet.
  • PHP and Laravel give you the rules per route and per user; they are not where the volumetric defence lives.

Solving the classic problems ​

The origin IP leaked and the attack goes around the CDN ​

  1. Change the origin IP (new Elastic IP or load balancer), because the old one is burnt.
  2. Allow only the CDN's published ranges in the security group; automate the refresh.
  3. Add authenticated origin pull and the OriginLock secret header.
  4. Remove old DNS records and check certificate transparency logs and mail headers for the old address.

Per-IP limits do nothing against a botnet ​

A botnet sends 2 requests per second from each of 5,000 addresses; a 5 per second per-IP limit passes all of it (Lab). Add a global ceiling on the expensive route, a cache, a challenge for clients without a pass, and let the edge's bot scoring act. Shed non-essential features (Load Shedding).

One slow attacker holds every worker ​

Set ReadHeaderTimeout, a body idle timeout and a total ReadTimeout; put NGINX or a CDN in front; limit connections per source. Verify with a Slowloris test against staging.

Cache busting makes the CDN useless ​

Allowlist query parameters in the cache key, lower-case and sort the ones that stay, ignore tracking parameters, cache 404s and empty results for a short time, and rate limit uncached requests from the same client at the edge.

Autoscaling follows the attack ​

Set a maximum, scale on latency and queue depth, put the edge block before the meter, and alarm on spend per hour, not per month. Decide in advance which features to turn off at maximum scale.

A compromised web server reaches the database and the internet ​

Segment tiers with security groups that reference each other, give the data tier no default route, remove allow-all egress, use VPC endpoints for AWS APIs, and log flows. See VPC design and Segmentation.

An admin SSH port is attacked daily ​

Remove inbound port 22, use SSM Session Manager (or IAP) with IAM and MFA, and keep session logs. If a bastion is unavoidable, restrict it to a VPN range.

The challenge page itself is the bottleneck ​

Serve it from the edge, make it cacheable and stateless (the HMAC puzzle in challenge needs no storage), keep the difficulty adaptive, and verify on the cheapest path. Offer an accessible alternative so legitimate users with disabilities are not locked out.

Choosing ​

What to buy ​

SituationRecommendationExtra techniqueReason
Small web app, one regionCDN with free or low-tier DDoS and WAF (Cloudflare, CloudFront with Shield Standard)Lock the origin; cacheAbsorbs most L3/L4 and common L7 cheaply
API with logins on AWSCloudFront or ALB with AWS WAF and Shield Standard; consider Shield AdvancedRate-based rules, CAPTCHA on loginL7 rules at the edge; Shield Advanced adds cost protection and SRT
Own IP space, game servers, UDPMagic Transit style BGP diversion or Shield Advanced on Elastic IPsflowspec with your ISPCDN proxies do not carry arbitrary UDP
GCPCloud Armor on global external Application Load BalancersAdaptive ProtectionPolicies at Google's edge
Regulated or high-value targetTwo providers, DNS on a separate providerRunbook drillsSingle-vendor outage is a risk
Cost-sensitive startupCap autoscaling, cache hard, Cloudflare free tierBudget alarmBill is the larger risk

Where to block ​

TrafficBlock atWhy
Terabit floodsScrubbing network, then ISPNothing smaller can
Spoofed SYNsEdge SYN proxy or SYN cookiesState exhaustion
Known bad payloadWAFNeeds the HTTP request
Abusive clientEdge rate rule, then origin limiterCheapest first
Slow clientsReverse proxy and server timeoutsNeeds buffering
Lateral movementSegmentation, NetworkPolicyInside the network
Data theftEgress filtering, DNS firewallOutbound path

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One server behind NGINX or a CDN. DDoS: CDN in front, origin locked to its ranges, NGINX with timeouts and limit_req and limit_conn, the app with per-route throttles and a cache. Network: one VPC, a public subnet with the load balancer, a private subnet with the app and the database, SSM for shell access.

Modular monolith: boundaries without the network ​

Still one process, so the network gives no help: the expensive module (search, export, reports) is protected by its own limiter and, in a queue-backed design, by a bounded worker pool, so a flood on one module cannot starve the rest. Database credentials per module reduce the damage of SQL injection.

Microservices: every arrow is a decision ​

The edge is the only public entry (the API gateway). Each service lives in a private subnet or namespace with default-deny NetworkPolicy and allows only its callers; the mesh authenticates callers with mTLS and applies authorization policies. Per-service rate limits stop a retry storm from one caller from becoming an internal DDoS (Cascading Failures). Egress is allowlisted per service, so only the payment service can call the payment provider.

Distributed data: replicas, caches, regions ​

Replicas and caches live in the data tier with no internet route; cross-region replication runs over transit gateway or private links, not the public internet. DNS or anycast steers users to the healthy region; a regional attack is absorbed by diverting traffic away from that region. A cache hit ratio is a security metric: when it drops during an attack, the database is the next target.

Scaling path: 1x, 10x, 100x ​

ScaleEdgeOriginNetworkProcess
1xFree CDN tier, WAF defaultsTimeouts, per-IP limitsOne VPC, three tiers, SSMA short runbook in the wiki
10xPaid WAF and bot management, rate rulesGlobal ceilings, caching, queuesEndpoints, NAT per AZ, flow logsQuarterly game day
100xDedicated scrubbing contract, own prefixes, two vendorsCell-based architecture, per-tenant quotasTransit gateway, segmentation by account, Network Firewall24/7 on-call, provider hotline, drills

Lab: replaying a flood and cutting a slow client ​

Expected, not run, unless a line says it was run. The Go tests and the simulation were run on the host.

# Run on the host (real output): all Go packages
$ cd docs/snippets/system-design/ddos-network-security/go
$ gofmt -l . && go vet ./... && go test ./...
# ok  academy/ddos-network-security/challenge
# ok  academy/ddos-network-security/clientip
# ok  academy/ddos-network-security/hardened
# ok  academy/ddos-network-security/perip

Experiment 1: per-IP limits, a botnet and a full key table (run).

$ go run ./cmd/attacksim 2000
attacker (1 IP, 1000 req/s)   served    169  refused  29831
botnet (5000 IPs, 2 req/s)    served 120107  refused 179893
legitimate (200 IPs, 1 req/s) served      0  refused   6000
tracked keys: 2000 (cap 2000)
$ go run ./cmd/attacksim 20000
attacker (1 IP, 1000 req/s)   served    169  refused  29831
botnet (5000 IPs, 2 req/s)    served 300000  refused      0
legitimate (200 IPs, 1 req/s) served   6000  refused      0
tracked keys: 5201 (cap 20000)

What it shows: the attacker at 1000 requests per second is cut to 169 requests in 30 seconds (the burst of 20 plus 5 per second). The botnet at 2 requests per second per address is never limited: per-IP limiting does not touch it. And with a key table of 2,000 for 5,200 active clients, the overflow bucket is shared, so legitimate users are refused, because the bots filled the table first. The cap protects memory, not fairness: size it for the realistic number of active clients and add the global ceiling and the challenge.

Experiment 2: Slowloris against a server without timeouts (staging only, expected, not run).

$ python3 slowloris.py 198.51.100.20 -p 8080 -s 800   # your own staging host, documentation address here
# before: curl -m 3 http://198.51.100.20:8080/healthz  -> times out
$ ss -tn state established '( sport = :8080 )' | wc -l
# 800
# after deploying hardened.NewServer (ReadHeaderTimeout 5s)
$ ss -tn state established '( sport = :8080 )' | wc -l
# 0 within 5 seconds, healthz answers

Experiment 3: SYN cookies (expected, not run).

$ sysctl net.ipv4.tcp_syncookies
# net.ipv4.tcp_syncookies = 1
$ sudo hping3 -S -p 443 --flood 198.51.100.20     # only against your own lab VM
$ ss -s | grep -i synrecv
# synrecv 1024
$ dmesg | tail -1
# TCP: request_sock_TCP: Possible SYN flooding on port 443. Sending cookies.

Experiment 4: security groups and the data tier (expected, not run).

$ aws ec2 describe-security-groups --group-ids sg-db --query 'SecurityGroups[].IpPermissions'
# [{"FromPort":5432,"ToPort":5432,"UserIdGroupPairs":[{"GroupId":"sg-app"}]}]   <- no CIDR, only the app group
$ aws ec2 describe-route-tables --filters Name=association.subnet-id,Values=subnet-data \
    --query 'RouteTables[].Routes[].DestinationCidrBlock'
# ["10.0.0.0/16"]    <- no 0.0.0.0/0: the data tier has no route to the internet

Experiment 5: Laravel (expected, not run).

$ php artisan test --filter=DdosDefenceTest
# PASS  Tests\Feature\DdosDefenceTest
# ✓ search is limited per ip with retry after
# ✓ cache busting parameters share one cache entry
# ✓ oversized query is rejected before any work
# ✓ direct origin hits are refused

Common misconceptions ​

BeliefReality
A firewall stops DDoSIt acts after arrival; floods fill the link first and stateful tables are targets themselves
Autoscaling makes me safeIt converts an outage into a bill and cannot add bandwidth
Blocking the source IPs in my logs ends a reflection attackThose are reflectors; the real source is spoofed
A CAPTCHA is a DDoS defenceIt protects functionality (forms), not capacity
Private subnet means no outbound riskThe NAT gateway gives outbound access; use egress rules
NACLs and security groups are interchangeableNACLs are stateless and per subnet; security groups are stateful and per interface
VPC peering is transitiveIt is not; use a transit gateway
A bigger server fixes a volumetric attackThe link or router fails first
Per-IP rate limits stop botnetsEach bot stays under the limit
Blackholing the victim IP saves the serviceIt completes the attack for that address
Hiding the origin IP is enoughWithout an origin allowlist it leaks and gets found
Flow logs show the payloadThey show metadata only

Cheat sheet ​

TopicRemember
ClassesVolumetric (link), protocol (state), L7 (CPU and DB)
AmplificationDNS 28 to 54, NTP 556.9, memcached up to 51,000; fix with BCP 38 and closed UDP
SYN floodSYN cookies, edge SYN proxy; no state until ACK
Slow attacksReadHeaderTimeout, body idle timeout, proxy buffering
L7 floodsNormalise cache key, cache short, global ceiling, challenge
Scale of defenceAnycast scrubbing or nothing; your firewall cannot fix a full link
RTBHDrops the victim address for everyone; last resort
flowspecFine-grained BGP filters, needs provider support
AutoscalingCap it, scale on latency, alarm on spend
OriginAllow only the edge, rotate IP, secret header, mTLS
FirewallsSG stateful allow-only on ENI; NACL stateless, numbered, per subnet
VPCPublic = route to IGW; app and data private; data has no default route
EgressAllowlist outbound; IMDSv2; endpoints instead of NAT
AdminSSM Session Manager, no inbound 22
SegmentationTiers, default-deny NetworkPolicy, mesh authorization
VisibilityVPC Flow Logs always on; Suricata or Zeek for payload-level
RunbookOne commander, classify, edge, origin, provider, communicate

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why can a firewall on your server not stop a 100 Gbps UDP flood? Must-know ​

Answer

Answer: The flood saturates the link and upstream routers before packets reach the firewall; only a network with more capacity (scrubbing, ISP filtering) can drop it earlier.

2 — What is the difference between reflection and amplification? Must-know ​

Answer

Answer: Reflection means the attacker spoofs the victim's address so third-party servers reply to the victim; amplification means the reply is larger than the request. DNS, NTP and memcached are both.

3 — How do SYN cookies avoid state? Important ​

Answer

Answer: The server encodes the connection parameters in the SYN-ACK sequence number and allocates nothing until a valid ACK returns (RFC 4987, section 3.6).

4 — Which Go setting ends Slowloris, and why is ReadTimeout alone not ideal? Important ​

Answer

Answer: ReadHeaderTimeout bounds the whole header block. ReadTimeout also covers the body and cannot be decided per request; set both.

5 — Why does a per-IP limit not stop a botnet, and what do you add? Must-know ​

Answer

Answer: Each address stays below the limit. Add a global ceiling on the expensive route, caching, a challenge and edge bot scoring.

6 — Define a public subnet in AWS. Must-know ​

Answer

Answer: A subnet whose route table has a route to an internet gateway; a private subnet has none.

7 — Name three differences between a security group and a network ACL. Important ​

Answer

Answer: Security group: stateful, on the network interface, allow rules only and can reference other groups. NACL: stateless, on the subnet, numbered allow and deny rules, CIDRs only.

8 — Why is VPC peering not enough for ten VPCs? Important ​

Answer

Answer: It is point to point and not transitive, so you need many connections and non-overlapping CIDRs; a transit gateway gives a hub with route tables.

9 — What does egress filtering stop that ingress rules cannot? Important ​

Answer

Answer: Outbound command and control, data exfiltration and SSRF to internal addresses from a compromised or tricked server.

10 — Why prefer SSM Session Manager to a bastion host? Important ​

Answer

Answer: No inbound port or keys, IAM identity and MFA, session logging; the bastion is a public attack target.

11 — What does RTBH do and what does it cost you? Good to know ​

Answer

Answer: It drops all traffic to the victim address at the provider edge, protecting the rest of the network, and also drops legitimate traffic to that address.

12 — What is economic denial of sustainability? Good to know ​

Answer

Answer: An attack whose goal is a large resource bill rather than an outage, exploiting autoscaling and per-request pricing.

Glossary ​

TermMeaning
DDoSDistributed denial of service: many sources exhaust a target's capacity
DoSDenial of service from a single source
Volumetric attackFloods bandwidth or packets per second
AmplificationReply is larger than the request
ReflectionThird-party servers send replies to a spoofed victim address
DNS amplificationReflection with open DNS resolvers, UDP 53
NTP amplificationReflection with NTP monlist, UDP 123
memcached amplificationReflection with memcached over UDP 11211, factor up to 51,000
SYN floodMany SYNs that never complete the handshake
SYN cookiesStateless handshake encoding the state in the sequence number
ACK floodACK packets with no connection, burning stateful devices
Fragmentation attackFlood of IP fragments exhausting reassembly
SlowlorisSlow, never-finished HTTP headers that hold connections
Slow POSTSlow body delivery with a large Content-Length
HTTP floodMany valid HTTP requests
Cache bustingRandom query strings to bypass caches
BotAutomated client
BotnetSet of controlled machines
L7 attackApplication-layer attack
Scrubbing centreInfrastructure that filters attack traffic and forwards clean traffic
AnycastOne address announced from many places; traffic goes to the nearest
BGP blackholingDropping traffic to an address via a BGP route
RTBHRemotely Triggered Black Hole filtering (RFC 5635)
flowspecBGP Flow Specification (RFC 8955) filter distribution
CloudflareCDN, DNS, WAF and DDoS provider
AkamaiCDN and scrubbing provider
AWS ShieldAWS managed DDoS protection, Standard and Advanced
Cloud ArmorGoogle Cloud WAF and DDoS service
WAFWeb application firewall
Bot managementClassification and control of automated clients
JS challengeBrowser must run JavaScript to prove itself
CAPTCHAChallenge that needs a human
Rate limitingCap on requests per time per key
Connection limitCap on simultaneous connections
Economic denial of sustainabilityAttack aimed at the bill
Autoscaling costSpend caused by automatic scale-out
Stateless firewallJudges each packet alone
Stateful firewallTracks connections
Security groupStateful per-interface allow rules in AWS
NACLStateless per-subnet allow and deny rules in AWS
Egress filteringRestricting outbound traffic
AllowlistExplicit list of permitted destinations or sources
VPCVirtual private cloud
Public subnetSubnet with a route to an internet gateway
Private subnetSubnet without a route to an internet gateway
NAT gatewayManaged outbound-only address translation
Route tablePrefix-to-target mapping for a subnet
VPC peeringNon-transitive link between two VPCs
Transit gatewayRegional routing hub
PrivateLinkPrivate access to a service through endpoints
Private endpointInterface endpoint with a private IP in your subnet
BastionPublic jump host for admin access
SSM Session ManagerAgent-based shell access via IAM, no inbound port
VPNEncrypted tunnel between networks or users
SegmentationDividing a network into zones
Micro-segmentationWorkload-level allow rules
TierLayer such as web, app, data
NetworkPolicyKubernetes pod traffic rules
Service mesh authorizationIdentity-aware L7 allow rules between services
IDSIntrusion detection system
IPSIntrusion prevention system
VPC Flow LogsPer-flow metadata for a VPC
SuricataOpen-source IDS/IPS engine
ZeekNetwork security monitor with structured logs
RunbookWritten step-by-step incident procedure
Incident responseOrganised handling of a security or availability incident
LimitListenerGo function capping simultaneous connections
ReadHeaderTimeoutGo server field bounding header read time
TrustProxiesLaravel middleware that trusts forwarding headers from listed proxies

References ​

Built by Morteza Negahi