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 for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why a bigger server is never the answer | Why it exists |
| 1996 SYN floods to 7.3 Tbps | Where it comes from |
| UDP floods and carpet bombing | Volumetric attacks |
| DNS, NTP, memcached amplification and spoofing | Reflection and amplification |
| SYN flood, ACK flood, fragmentation, SYN cookies | Protocol attacks |
| Slowloris, slow POST | Slow attacks |
| HTTP flood, cache busting, Rapid Reset, expensive endpoints | Application-layer floods |
| Botnets, scrapers, credential stuffing | Bots |
| Cloudflare, Akamai, AWS Shield, Cloud Armor | Scrubbing networks |
| RTBH, flowspec, blackholing | RTBH and flowspec |
| WAF, bot management, JS challenge, CAPTCHA | WAF and challenges |
| Per-IP limits, connection limits, timeouts | Limits at the origin |
| Cache hit ratio as a shield | Caching to absorb |
| The autoscaling bill | Autoscaling and EDoS |
| Hiding the origin | Origin protection |
| Stateless vs stateful, SG vs NACL, WAF vs network firewall | Firewalls |
| SSRF and exfiltration | Egress filtering |
| Subnets, NAT gateway, route tables | VPC design |
| Peering, transit gateway, PrivateLink, endpoints | Connecting networks |
| Bastion vs SSM Session Manager | Admin access |
| Tiers, micro-segmentation, NetworkPolicy, mesh authz | Segmentation |
| DNS as a target and as a shield | DNS layer |
| TLS exhaustion, HTTP/2 limits | TLS and edge |
| Suricata, Zeek, VPC Flow Logs | IDS, IPS and flow logs |
| Is a test legal | Testing |
| The first hour | Runbook |
| Formulas, knobs, error signals | Mechanics |
| Code | Go, Laravel |
| Eight classic failures | Solving the classic problems |
| What to buy and where to block | Choosing |
| Monolith to multi-region | In architecture |
| Simulation and experiments | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The three attack classes.
| Class | What it exhausts | Examples | Unit | Where it must be stopped |
|---|---|---|---|---|
| Volumetric (L3/L4) | The network link and routers | UDP flood, DNS/NTP/memcached amplification, carpet bombing | Gbps, Tbps, Mpps | Upstream: scrubbing network, ISP (RTBH, flowspec) |
| Protocol (L4) | Connection state in servers, load balancers, firewalls | SYN flood, ACK flood, fragmentation attack | Packets per second, half-open connections | Edge with SYN cookies or a SYN proxy, stateless filters |
| Application (L7) | CPU, workers, database, third-party quotas | HTTP flood, cache busting, Slowloris, slow POST, expensive endpoints | Requests per second | WAF, rate limits, challenges, caching, your own server limits |
Who stops what. The last column is the honest answer to "will this alone save me?".
| Layer | Stops | Cannot stop |
|---|---|---|
| Your firewall or security group | Unwanted ports, lateral movement | A flood that fills the link before it arrives |
| Anycast scrubbing (Cloudflare, Akamai, AWS Shield, Cloud Armor) | Volumetric, protocol, much of L7 | An attack on an origin IP the attacker found, if the origin accepts everyone |
| WAF and bot management | Known bad payloads, bad bots, floods that look different from users | A flood of perfectly valid, distinct requests from a million real-looking clients |
| CDN cache | Repeated reads of the same object | Cache-busting queries, POSTs, personalised responses |
| Per-IP rate limit | One noisy client | A botnet with one request per address |
| Server timeouts and body caps | Slowloris, slow POST, giant bodies | Fast, well-formed floods |
| Autoscaling | Honest growth | An attack, which it turns into a bill |
Record sizes, each from the operator who measured it.
| When | Size | Kind | Source |
|---|---|---|---|
| Feb 2018 | 1.35 Tbps, 126.9 million packets per second | memcached amplification against GitHub | GitHub incident report |
| Aug 2023 | 398 million requests per second (largest L7 attack Google reported) | HTTP/2 Rapid Reset | Google Cloud blog |
| 2023 | Just above 201 million requests per second | HTTP/2 Rapid Reset | Cloudflare blog |
| May 2025 | 7.3 Tbps, 37.4 TB in 45 seconds; the largest attack Cloudflare had recorded at that date | Multivector, 99.996% UDP flood | Cloudflare 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.
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.
| Weaker | Stronger | The trade-off |
|---|---|---|
| Block by IP | Score by behaviour | Behaviour needs data and risks false positives; IP lists are cheap and wrong behind NAT |
| Drop everything unknown | Challenge unknown | Challenges cost real users a second and break API clients |
| One big origin | Many small edges | Edges need caching, stateless design and a trust boundary |
| Public origin with a firewall | Origin reachable only from the edge | You depend on the edge's availability |
| Autoscale to survive | Cap and shed | Autoscale keeps the site up and the bill unbounded; a cap protects money and loses requests |
| Flat network | Segmented network | Segmentation 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
- "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.
- "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).
- "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 downReal 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 protection | How | Limit |
|---|---|---|
| Scrubbing network with anycast | Absorbs and filters in many places | Needs 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 provider | Resources that sit outside the provider's network get nothing |
| ISP | RTBH, flowspec | Coarse; RTBH completes the attack against the victim IP |
| Bigger uplink | Delays the failure | Attackers 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)| Protocol | Port | Amplification | Fix at the reflector |
|---|---|---|---|
| DNS amplification | UDP 53 | 28 to 54 (CISA) | Do not run open recursive resolvers; response rate limiting |
| NTP amplification | UDP 123 | 556.9 (CISA, monlist) | Patch (CVE-2013-5211), disable monlist, restrict queries |
| memcached amplification | UDP 11211 | up to 51,000 (GitHub) | Bind to localhost, disable UDP (-U 0), never expose |
| CLDAP, SSDP, mDNS, Portmap, RIPv1, QOTD, Echo | various | various | Do 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 elseSYN 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 setting | What 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, somaxconn | Size 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| Server | Header and body timeout knobs | Notes |
|---|---|---|
Go net/http | ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout, MaxHeaderBytes | Zero means no timeout; http.ListenAndServe sets none |
| NGINX | client_header_timeout, client_body_timeout, send_timeout, limit_conn | Event-driven, so idle connections are cheap, but still bounded by worker_connections |
| Apache httpd | mod_reqtimeout (RequestReadTimeout with minrate), MaxRequestWorkers | Process or thread per connection: the classic victim |
| HAProxy | timeout http-request, timeout client | Terminates and buffers; protects the app behind it |
| Envoy | request_headers_timeout, stream_idle_timeout, request_timeout | Per listener or route |
| PHP-FPM behind NGINX | NGINX absorbs the slow client, FPM sees the request only when it is complete | Why 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| Attack | Why it is cheap for the attacker | Defence |
|---|---|---|
| Plain GET flood of the home page | Static page, bandwidth only | CDN cache, scrubbing |
| Cache-busting GET | Defeats the CDN | Normalise the cache key, allowlist query parameters, rate limit per client |
| Search or export endpoint | One request costs the DB seconds | Per-endpoint limits, timeouts, result caching, a queue, authentication |
| Login and password reset | Password hashing is deliberately slow; email costs money | Tight per-IP and per-account limits, challenge, CAPTCHA |
| POST with large body | Parsing, upload, virus scan | Body size cap, auth before upload |
| HTTP/2 Rapid Reset | Server does work for cancelled streams | Patch; cap streams reset per connection; CDN absorbs |
| GraphQL deep queries | Single request, exponential work | Query 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 type | Looks like | Signals | Response |
|---|---|---|---|
| DDoS botnet | Many addresses, valid requests | Burst across addresses, same fingerprint | Scrubbing, challenge, global ceiling |
| Scraper | Steady, ordered crawling | Sequential IDs, missing assets | Rate limit, require login, honeypot |
| Credential stuffer | Login POSTs with different accounts | Failed login ratio | Per-account limit, MFA, challenge |
| Good bot (Googlebot) | Declares itself | Reverse DNS verification | Allow 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| Product | Model | What the vendor documents |
|---|---|---|
| Cloudflare | Reverse proxy for HTTP (DNS points at it); Magic Transit for whole IP prefixes | Every service runs in every data center; 7.3 Tbps stopped autonomously |
| Akamai | CDN and a scrubbing service; GitHub moved its BGP announcements to Akamai during the 2018 attack | Absorbed the 1.35 Tbps memcached attack for GitHub |
| AWS Shield Standard / Advanced | Built into CloudFront, Route 53, Global Accelerator, ELB, Elastic IP | Packet validation, ACLs and shapers, suspicion scoring, TCP SYN proxy, rate distribution; Advanced adds SRT support and WAF cost coverage |
| Google Cloud Armor | Security policies on global external Application Load Balancers and others | Preconfigured WAF rules, rate limiting, Adaptive Protection |
| Azure DDoS Protection | Network and IP protection tiers | Not 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".
| Technique | Granularity | Collateral | Needs |
|---|---|---|---|
| RTBH (destination-based) | Whole destination address | All traffic to it, including good | A provider offering a blackhole community |
| Source-based RTBH with uRPF | Source addresses | Little, if sources are known | uRPF on edge routers |
| BGP flowspec | 5-tuple, flags, length | Small | A provider or router that accepts flowspec routes from you |
| Scrubbing diversion | Everything, then filter | Added latency | Contract 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.
| Product | Rule engine | Challenge | Notes |
|---|---|---|---|
| Cloudflare WAF and Bot Management | Managed rules, custom rules, rate limiting | JS challenge, Managed Challenge, Turnstile | Runs at the edge, before your origin |
| AWS WAF | Web ACLs, rule groups, rate-based rules | CAPTCHA and Challenge actions, Bot Control | Attach to CloudFront, ALB, API Gateway; Bot Control, CAPTCHA and large bodies cost extra |
| Google Cloud Armor | Security policies, preconfigured WAF rules, rate limiting | reCAPTCHA integration | Adaptive Protection learns a baseline |
| NGINX with ModSecurity and the OWASP Core Rule Set | Open-source rule engine | None built in | You 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.
| Defence | Protects against | Go | Laravel / PHP | NGINX |
|---|---|---|---|---|
| Per-IP token bucket | One heavy client | perip.Middleware (this page) | RateLimiter::for + throttle:name | limit_req_zone + limit_req |
| Global ceiling | A botnet below per-IP limits | Second perip bucket with a constant key | A Limit::perSecond(200)->by('global') | limit_req with a constant key |
| Connection limit | Many sockets from one source, FD exhaustion | netutil.LimitListener | NGINX in front | limit_conn |
| Header timeout | Slowloris | ReadHeaderTimeout | client_header_timeout in NGINX | client_header_timeout |
| Body idle timeout | Slow POST | http.ResponseController.SetReadDeadline | client_body_timeout | client_body_timeout |
| Body size cap | Giant uploads | http.MaxBytesReader | post_max_size, client_max_body_size | client_max_body_size |
| Execution time cap | Slow endpoints holding workers | context.WithTimeout | Octane max_execution_time | proxy_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.
| Tool | Setting | Effect during an attack |
|---|---|---|
| CDN (Cloudflare, CloudFront, Fastly, Akamai) | Cache key allowlist for query parameters | Cache busting stops working |
| CDN | "Always online" or serve-stale | Site shows content while origin is down |
| Laravel | Cache::flexible($key, [30, 90], ...) | Stale-while-revalidate: one rebuild per key |
| Go | singleflight.Group around the miss | One query per key at a time |
| NGINX | proxy_cache_lock on, proxy_cache_use_stale updating | Coalescing 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| Control | Where | Effect |
|---|---|---|
| Maximum instance count and budget alarm | Auto Scaling group, Kubernetes HPA maxReplicas, cloud budgets | Bill is bounded |
| Scale on a latency or queue signal, not raw requests | Autoscaler | Does not follow attack traffic blindly |
| Block before metering | CDN or WAF in front | Blocked requests are cheaper than served ones |
| Cap serverless concurrency | Lambda reserved concurrency, Cloud Run max instances | Downstream database is protected |
| Sample logs under attack | Log pipeline | Log 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.
| Method | Strength | Limitation |
|---|---|---|
| Security group allowing only CDN ranges | Strong at L3/L4 | Ranges change; automate refresh; other tenants of the same CDN can reach you |
| Secret header from the CDN | Cheap second lock | Leaks if logged; not a replacement for the network rule |
| Authenticated origin pull (mTLS) | Strong | Certificate management |
| Tunnel from origin to edge (outbound only) | Origin has no public listener | Edge outage means outage |
Laravel OriginLock middleware | Application-level second lock | Runs 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."
| Property | Security group (AWS) | Network ACL (AWS) | Host firewall (iptables/nftables) | WAF |
|---|---|---|---|---|
| Attached to | Network interface (instance, ENI) | Subnet | The host | Load balancer, CDN, API gateway |
| State | Stateful | Stateless | Stateful with conntrack | Per HTTP request |
| Rule types | Allow only | Allow and deny, numbered, lowest first | Allow and drop | Allow, block, count, challenge |
| Can reference | Other security groups | CIDRs only | Addresses, sets | Headers, URIs, bodies, IP sets, rate |
| Typical use | Tier-to-tier access | Block a hostile range; subnet guard rail | Last line on the box | SQLi, XSS, bots, L7 floods |
| Sees TLS content | No | No | No | Yes, 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| Control | Mechanism |
|---|---|
| Security group egress | Remove the default allow-all outbound rule; allow only the database SG and the endpoint SG |
| Forward proxy with allowlist | App can only reach the proxy; proxy allows listed hosts (Forward vs Reverse Proxies) |
| DNS firewall | Resolver refuses names outside a list (Route 53 Resolver DNS Firewall, CoreDNS plugins) |
| Network Firewall domain allowlist | SNI and HTTP host inspection |
| Kubernetes NetworkPolicy egress | Pods may reach only named pods and namespaces |
| Metadata hardening | IMDSv2 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.
| Route table | Destination | Target | Meaning |
|---|---|---|---|
| Public subnets | 10.0.0.0/16 | local | Intra-VPC traffic |
| Public subnets | 0.0.0.0/0 | Internet gateway | Public: reachable and able to reach out |
| Private app subnets | 10.0.0.0/16 | local | Intra-VPC traffic |
| Private app subnets | 0.0.0.0/0 | NAT gateway in the same AZ | Outbound only; AZ-local NAT avoids a single AZ dependency and cross-AZ fees |
| Private app subnets | pl-xxxx (S3 prefix list) | Gateway endpoint | S3 without NAT |
| Private data subnets | 10.0.0.0/16 | local | No default route: cannot reach the internet |
| Decision | Recommendation | Reason |
|---|---|---|
| Where do load balancers go | Public subnets | They need an internet-facing address |
| Where do app servers go | Private subnets | Not directly reachable; traffic only via the load balancer |
| Where do databases go | Private data subnets with no default route | A compromised app cannot be used as a bridge to the internet through the database tier |
| NAT per AZ | Yes for production | A single NAT is a single point of failure and a cross-AZ cost |
| IPv6 egress | Egress-only internet gateway | Outbound only, like NAT |
| CIDR plan | Non-overlapping ranges across VPCs and on-premises | Peering 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.
| Option | Exposes | Transitive | Best for |
|---|---|---|---|
| VPC peering | The whole other VPC (limited by routes and SGs) | No | Two VPCs, small |
| Transit gateway | Whatever the route tables allow | Yes | Many VPCs, hub-and-spoke, on-premises |
| PrivateLink (endpoint service) | One service behind a load balancer | N/A | SaaS, shared services, no CIDR coordination |
| Gateway endpoint | S3, DynamoDB | N/A | Free, no NAT cost for S3 |
| Interface endpoint | One AWS or partner service | N/A | AWS APIs (Secrets Manager, ECR) without NAT |
| Site-to-Site VPN, Client VPN | Whole network or user | Depends | On-premises, remote work |
| Direct Connect | Private fibre | Depends | Stable 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.
| Property | Bastion + SSH | SSM Session Manager |
|---|---|---|
| Inbound port | 22 on the bastion | None |
| Identity | SSH keys | IAM identities, MFA |
| Audit | Whatever you collect | Session logging to CloudWatch Logs or S3 |
| Private instance needs | Reachable from bastion | Agent plus an outbound path (NAT or interface endpoints) |
| Cost | A host | Endpoints 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| Layer | Tool | Enforces | Needs |
|---|---|---|---|
| VPC | Security groups referencing SGs | L3/L4 between tiers | Cloud-native |
| Subnet | NACLs | Subnet-wide deny | Cloud-native |
| Kubernetes | NetworkPolicy (Kubernetes Networking) | L3/L4 between pods | A CNI that enforces it (Calico, Cilium); Kubernetes docs: policies are additive and "by default, a pod is non-isolated for egress" |
| Mesh | Istio AuthorizationPolicy, Linkerd policy | L7 and identity | Sidecars or ambient mode; see Service Mesh |
| Host | iptables, nftables, eBPF | Per host | Agent |
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.
| Risk | Defence |
|---|---|
| UDP flood to authoritative servers | Anycast managed DNS; Shield Standard protects Route 53 |
| Random-subdomain attack | Anycast capacity, rate limits on NXDOMAIN per client |
| Being a reflector | Disable open recursion; response rate limiting |
| Long TTL blocks the pivot | TTL 60 to 300 s on the records you may need to move |
| Registrar account takeover | Registry 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.
| Control | Product setting |
|---|---|
| Terminate at the edge | CDN or load balancer (ALB, NLB TLS listener, Cloud Load Balancing) |
| Limit HTTP/2 concurrent streams | NGINX http2_max_concurrent_streams, Envoy max_concurrent_streams |
| Header and request size caps | NGINX large_client_header_buffers, Go MaxHeaderBytes |
| Disable client renegotiation | Default 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.
-- 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;| Tool | Does | Fits |
|---|---|---|
| VPC Flow Logs | Metadata per flow | Always on; attack triage, "who talked to the database" |
| AWS Traffic Mirroring, GCP Packet Mirroring | Copies packets to a sensor | Suricata or Zeek analysis |
| Suricata | Signature and protocol IDS/IPS | Perimeter, east-west |
| Zeek | Structured protocol logs, scripting | Forensics, anomaly detection |
| GuardDuty (AWS) | Managed detection on flow and DNS logs | Cheap 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.
| Test | Allowed how |
|---|---|
| Load test of your app at 3x peak | Your own accounts, announce to the provider if large |
| L7 abuse test of your own WAF rules | Staging environment, rate-limited generator |
| Volumetric simulation | Only through a provider-approved partner and inside the provider's volume caps |
| Game day for the runbook | Tabletop 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| Signal | Likely class | First move |
|---|---|---|
| Inbound Mbps and packets at link limit, CPU idle | Volumetric | Scrubbing, call the ISP |
| Many SYN-RECV, few established | Protocol | SYN cookies, edge proxy |
| High request rate, one path, CPU at 100% | L7 flood | WAF, rate rule, challenge, cache |
| Few requests, all workers busy | Slow attack | Timeouts, proxy buffering |
| Cost alarm, normal traffic graphs | EDoS | Max caps, find the metered path |
Mechanics
Formulas and numbers
| Quantity | Formula | Example |
|---|---|---|
| Amplification factor | response bytes / request bytes | 51,000 for memcached; 28 to 54 for DNS |
| Reflector traffic | attacker bandwidth x factor | 100 Mbps x 556.9 is about 55.7 Gbps of NTP |
| Packets per second at line rate | bits per second / (8 x frame bytes) | 10 Gbps of 64-byte frames is about 14.9 Mpps |
| Slowloris capacity | worker slots / (header timeout / drip interval) | 1000 slots held by 1000 sockets sending a byte every 10 s |
| Safe per-IP burst | legitimate peak per client x 2 | 20 requests for a page that loads 10 resources |
| Cache hit ratio effect | origin load = requests x (1 - hit ratio) | 10,000 req/s at 95% hit: 500 req/s; at 0%: 10,000 |
| Challenge cost to attacker | 2 to the power of difficulty bits hashes | 18 bits is about 262,144 hashes per request |
Product knobs
| Product | Knob | Default or note |
|---|---|---|
| Go net/http | ReadHeaderTimeout | 0 = none (if ReadTimeout is also 0) |
| Go net/http | MaxHeaderBytes | DefaultMaxHeaderBytes is 1 MB |
| Go | netutil.LimitListener(l, n) | Accept at most n simultaneous connections |
| Go | http.MaxBytesReader(w, r.Body, n) | Fails the read with an error once n bytes are exceeded |
| NGINX | limit_conn_zone $binary_remote_addr zone=addr:10m; limit_conn addr 10; | 503 by default (limit_conn_status) |
| NGINX | client_header_timeout, client_body_timeout | 60 s each |
| Linux | net.ipv4.tcp_syncookies | 1 on most distributions |
| Laravel | trustProxies(at: [...]) in bootstrap/app.php | Without it, $request->ip() is the proxy |
| Laravel Octane | max_execution_time in config/octane.php | 30 seconds |
| AWS | Security group inbound rule source | CIDR, prefix list or another security group |
| AWS | VPC Flow Logs log-format | Default fields: srcaddr, dstaddr, srcport, dstport, protocol, packets, bytes, action |
| Kubernetes | NetworkPolicy policyTypes: [Ingress, Egress] | A pod selected by any policy is isolated for that direction |
Error messages and signals you will actually see
| Where | Signal | Meaning |
|---|---|---|
| Linux kernel log | TCP: request_sock_TCP: Possible SYN flooding on port 443. Sending cookies. (the kernel appends more text) | The SYN queue overflowed; cookies are active |
ss -s | Thousands in synrecv | SYN flood or an overloaded app that does not accept |
| NGINX error log | limiting connections by zone "addr" | limit_conn is rejecting |
| NGINX error log | client timed out (110: Connection timed out) while reading client request headers | A slow client was cut |
| Go | http: Server closed idle connection, context deadline exceeded, http: request body too large | Timeouts and MaxBytesReader at work |
| HTTP | 429 Too Many Requests with Retry-After | Your rate limiter |
| HTTP | 503 from NGINX limit_req default | Rate limit in NGINX |
| HTTP | 403 with a challenge page | WAF or bot management |
| Cloudflare | Error 1020 (access denied), 1015 (rate limited) | A rule matched |
| AWS | REJECT in a VPC Flow Log | Security group or NACL blocked it |
| Kubernetes | Connection timeout (not refused) between pods | NetworkPolicy 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.
// 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).
// 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()
}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.
// 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)
})
}
}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.
// 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)
})
}
}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.
// 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)
})
}
}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.
// 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))
}// 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.Serverhas five time limits and every one of them defaults to zero, which means "no timeout".ReadHeaderTimeoutis 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 whyBodyIdleTimeoutexists.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.MaxBytesReaderenforces the cap even for chunked bodies whereContent-Lengthis unknown; the middleware also rejects a declared oversize at once with 413.- A rate limiter keyed on
r.RemoteAddrbehind a load balancer sees one address; a limiter keyed on the left-mostX-Forwarded-Forsees whatever the client typed.clientip.Fromis 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
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
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
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
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
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
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
// 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
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 inat:; for AWS Elastic Load Balancing the docs say to useRequest::HEADER_X_FORWARDED_AWS_ELBforheaders:.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:nameandRateLimiter::for: return oneLimitor an array; the first exceeded limit answers 429 withRetry-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=15serves a static maintenance page with aRetry-Afterheader;--secretlets 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_timeoutandpm.max_childrenbound 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
- Change the origin IP (new Elastic IP or load balancer), because the old one is burnt.
- Allow only the CDN's published ranges in the security group; automate the refresh.
- Add authenticated origin pull and the
OriginLocksecret header. - 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
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Small web app, one region | CDN with free or low-tier DDoS and WAF (Cloudflare, CloudFront with Shield Standard) | Lock the origin; cache | Absorbs most L3/L4 and common L7 cheaply |
| API with logins on AWS | CloudFront or ALB with AWS WAF and Shield Standard; consider Shield Advanced | Rate-based rules, CAPTCHA on login | L7 rules at the edge; Shield Advanced adds cost protection and SRT |
| Own IP space, game servers, UDP | Magic Transit style BGP diversion or Shield Advanced on Elastic IPs | flowspec with your ISP | CDN proxies do not carry arbitrary UDP |
| GCP | Cloud Armor on global external Application Load Balancers | Adaptive Protection | Policies at Google's edge |
| Regulated or high-value target | Two providers, DNS on a separate provider | Runbook drills | Single-vendor outage is a risk |
| Cost-sensitive startup | Cap autoscaling, cache hard, Cloudflare free tier | Budget alarm | Bill is the larger risk |
Where to block
| Traffic | Block at | Why |
|---|---|---|
| Terabit floods | Scrubbing network, then ISP | Nothing smaller can |
| Spoofed SYNs | Edge SYN proxy or SYN cookies | State exhaustion |
| Known bad payload | WAF | Needs the HTTP request |
| Abusive client | Edge rate rule, then origin limiter | Cheapest first |
| Slow clients | Reverse proxy and server timeouts | Needs buffering |
| Lateral movement | Segmentation, NetworkPolicy | Inside the network |
| Data theft | Egress filtering, DNS firewall | Outbound 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
| Scale | Edge | Origin | Network | Process |
|---|---|---|---|---|
| 1x | Free CDN tier, WAF defaults | Timeouts, per-IP limits | One VPC, three tiers, SSM | A short runbook in the wiki |
| 10x | Paid WAF and bot management, rate rules | Global ceilings, caching, queues | Endpoints, NAT per AZ, flow logs | Quarterly game day |
| 100x | Dedicated scrubbing contract, own prefixes, two vendors | Cell-based architecture, per-tenant quotas | Transit gateway, segmentation by account, Network Firewall | 24/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/peripExperiment 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 answersExperiment 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 internetExperiment 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 refusedCommon misconceptions
| Belief | Reality |
|---|---|
| A firewall stops DDoS | It acts after arrival; floods fill the link first and stateful tables are targets themselves |
| Autoscaling makes me safe | It converts an outage into a bill and cannot add bandwidth |
| Blocking the source IPs in my logs ends a reflection attack | Those are reflectors; the real source is spoofed |
| A CAPTCHA is a DDoS defence | It protects functionality (forms), not capacity |
| Private subnet means no outbound risk | The NAT gateway gives outbound access; use egress rules |
| NACLs and security groups are interchangeable | NACLs are stateless and per subnet; security groups are stateful and per interface |
| VPC peering is transitive | It is not; use a transit gateway |
| A bigger server fixes a volumetric attack | The link or router fails first |
| Per-IP rate limits stop botnets | Each bot stays under the limit |
| Blackholing the victim IP saves the service | It completes the attack for that address |
| Hiding the origin IP is enough | Without an origin allowlist it leaks and gets found |
| Flow logs show the payload | They show metadata only |
Cheat sheet
| Topic | Remember |
|---|---|
| Classes | Volumetric (link), protocol (state), L7 (CPU and DB) |
| Amplification | DNS 28 to 54, NTP 556.9, memcached up to 51,000; fix with BCP 38 and closed UDP |
| SYN flood | SYN cookies, edge SYN proxy; no state until ACK |
| Slow attacks | ReadHeaderTimeout, body idle timeout, proxy buffering |
| L7 floods | Normalise cache key, cache short, global ceiling, challenge |
| Scale of defence | Anycast scrubbing or nothing; your firewall cannot fix a full link |
| RTBH | Drops the victim address for everyone; last resort |
| flowspec | Fine-grained BGP filters, needs provider support |
| Autoscaling | Cap it, scale on latency, alarm on spend |
| Origin | Allow only the edge, rotate IP, secret header, mTLS |
| Firewalls | SG stateful allow-only on ENI; NACL stateless, numbered, per subnet |
| VPC | Public = route to IGW; app and data private; data has no default route |
| Egress | Allowlist outbound; IMDSv2; endpoints instead of NAT |
| Admin | SSM Session Manager, no inbound 22 |
| Segmentation | Tiers, default-deny NetworkPolicy, mesh authorization |
| Visibility | VPC Flow Logs always on; Suricata or Zeek for payload-level |
| Runbook | One commander, classify, edge, origin, provider, communicate |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| DDoS | Distributed denial of service: many sources exhaust a target's capacity |
| DoS | Denial of service from a single source |
| Volumetric attack | Floods bandwidth or packets per second |
| Amplification | Reply is larger than the request |
| Reflection | Third-party servers send replies to a spoofed victim address |
| DNS amplification | Reflection with open DNS resolvers, UDP 53 |
| NTP amplification | Reflection with NTP monlist, UDP 123 |
| memcached amplification | Reflection with memcached over UDP 11211, factor up to 51,000 |
| SYN flood | Many SYNs that never complete the handshake |
| SYN cookies | Stateless handshake encoding the state in the sequence number |
| ACK flood | ACK packets with no connection, burning stateful devices |
| Fragmentation attack | Flood of IP fragments exhausting reassembly |
| Slowloris | Slow, never-finished HTTP headers that hold connections |
| Slow POST | Slow body delivery with a large Content-Length |
| HTTP flood | Many valid HTTP requests |
| Cache busting | Random query strings to bypass caches |
| Bot | Automated client |
| Botnet | Set of controlled machines |
| L7 attack | Application-layer attack |
| Scrubbing centre | Infrastructure that filters attack traffic and forwards clean traffic |
| Anycast | One address announced from many places; traffic goes to the nearest |
| BGP blackholing | Dropping traffic to an address via a BGP route |
| RTBH | Remotely Triggered Black Hole filtering (RFC 5635) |
| flowspec | BGP Flow Specification (RFC 8955) filter distribution |
| Cloudflare | CDN, DNS, WAF and DDoS provider |
| Akamai | CDN and scrubbing provider |
| AWS Shield | AWS managed DDoS protection, Standard and Advanced |
| Cloud Armor | Google Cloud WAF and DDoS service |
| WAF | Web application firewall |
| Bot management | Classification and control of automated clients |
| JS challenge | Browser must run JavaScript to prove itself |
| CAPTCHA | Challenge that needs a human |
| Rate limiting | Cap on requests per time per key |
| Connection limit | Cap on simultaneous connections |
| Economic denial of sustainability | Attack aimed at the bill |
| Autoscaling cost | Spend caused by automatic scale-out |
| Stateless firewall | Judges each packet alone |
| Stateful firewall | Tracks connections |
| Security group | Stateful per-interface allow rules in AWS |
| NACL | Stateless per-subnet allow and deny rules in AWS |
| Egress filtering | Restricting outbound traffic |
| Allowlist | Explicit list of permitted destinations or sources |
| VPC | Virtual private cloud |
| Public subnet | Subnet with a route to an internet gateway |
| Private subnet | Subnet without a route to an internet gateway |
| NAT gateway | Managed outbound-only address translation |
| Route table | Prefix-to-target mapping for a subnet |
| VPC peering | Non-transitive link between two VPCs |
| Transit gateway | Regional routing hub |
| PrivateLink | Private access to a service through endpoints |
| Private endpoint | Interface endpoint with a private IP in your subnet |
| Bastion | Public jump host for admin access |
| SSM Session Manager | Agent-based shell access via IAM, no inbound port |
| VPN | Encrypted tunnel between networks or users |
| Segmentation | Dividing a network into zones |
| Micro-segmentation | Workload-level allow rules |
| Tier | Layer such as web, app, data |
| NetworkPolicy | Kubernetes pod traffic rules |
| Service mesh authorization | Identity-aware L7 allow rules between services |
| IDS | Intrusion detection system |
| IPS | Intrusion prevention system |
| VPC Flow Logs | Per-flow metadata for a VPC |
| Suricata | Open-source IDS/IPS engine |
| Zeek | Network security monitor with structured logs |
| Runbook | Written step-by-step incident procedure |
| Incident response | Organised handling of a security or availability incident |
| LimitListener | Go function capping simultaneous connections |
| ReadHeaderTimeout | Go server field bounding header read time |
| TrustProxies | Laravel middleware that trusts forwarding headers from listed proxies |
References
- AWS WAF Developer Guide, How AWS Shield and Shield Advanced work: https://docs.aws.amazon.com/waf/latest/developerguide/ddos-overview.html
- AWS Shield mitigation features: https://docs.aws.amazon.com/waf/latest/developerguide/ddos-event-mitigation-features.html
- AWS Shield Advanced summary (cost coverage): https://docs.aws.amazon.com/waf/latest/developerguide/ddos-advanced-summary.html
- AWS Best Practices for DDoS Resiliency: https://docs.aws.amazon.com/whitepapers/latest/aws-best-practices-ddos-resiliency/aws-best-practices-ddos-resiliency.html
- Google Cloud Armor overview: https://cloud.google.com/armor/docs/cloud-armor-overview
- Google Cloud Armor rate limiting: https://cloud.google.com/armor/docs/rate-limiting-overview
- AWS WAF, CAPTCHA and Challenge: https://docs.aws.amazon.com/waf/latest/developerguide/waf-captcha-and-challenge.html
- AWS DDoS Simulation Testing Policy: https://aws.amazon.com/security/ddos-simulation-testing/
- Cloudflare blog, 7.3 Tbps: https://blog.cloudflare.com/defending-the-internet-how-cloudflare-blocked-a-monumental-7-3-tbps-ddos/
- Cloudflare blog, HTTP/2 Rapid Reset: https://blog.cloudflare.com/technical-breakdown-http2-rapid-reset-ddos-attack/
- Cloudflare blog, Memcrashed: https://blog.cloudflare.com/memcrashed-major-amplification-attacks-from-port-11211/
- Cloudflare IP ranges: https://www.cloudflare.com/ips/
- Google Cloud blog, HTTP/2 Rapid Reset: https://cloud.google.com/blog/products/identity-security/how-it-works-the-novel-http2-rapid-reset-ddos-attack
- GitHub, February 28th DDoS incident report: https://github.blog/news-insights/company-news/ddos-incident-report/
- CISA TA14-017A, UDP-based amplification attacks: https://www.cisa.gov/news-events/alerts/2014/01/17/udp-based-amplification-attacks
- RFC 4987, TCP SYN Flooding Attacks and Common Mitigations: https://www.rfc-editor.org/rfc/rfc4987.txt
- RFC 5635, RTBH Filtering with uRPF: https://www.rfc-editor.org/rfc/rfc5635.txt
- RFC 8955, Dissemination of Flow Specification Rules: https://www.rfc-editor.org/rfc/rfc8955.txt
- RFC 2827 (BCP 38), Network Ingress Filtering: https://www.rfc-editor.org/rfc/rfc2827.txt
- OWASP Denial of Service Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Denial_of_Service_Cheat_Sheet.html
- NIST SP 800-41 Rev. 1, Guidelines on Firewalls and Firewall Policy: https://csrc.nist.gov/pubs/sp/800/41/r1/final
- AWS VPC, infrastructure security (security groups and NACLs): https://docs.aws.amazon.com/vpc/latest/userguide/infrastructure-security.html
- AWS VPC, security groups: https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html
- AWS VPC, network ACLs: https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html
- AWS VPC, route tables: https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html
- AWS VPC, NAT gateways: https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html
- AWS VPC, flow logs: https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html
- AWS VPC peering: https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html
- AWS Transit Gateway: https://docs.aws.amazon.com/vpc/latest/tgw/what-is-transit-gateway.html
- AWS PrivateLink: https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html
- AWS Systems Manager Session Manager: https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html
- Kubernetes NetworkPolicy: https://kubernetes.io/docs/concepts/services-networking/network-policies/
- Istio security concepts: https://istio.io/latest/docs/concepts/security/
- Suricata: https://docs.suricata.io/en/latest/what-is-suricata.html
- Zeek: https://docs.zeek.org/en/master/about.html
- NGINX limit_conn module: https://nginx.org/en/docs/http/ngx_http_limit_conn_module.html
- NGINX HTTP/2 module: https://nginx.org/en/docs/http/ngx_http_v2_module.html
- NGINX core module (client timeouts): https://nginx.org/en/docs/http/ngx_http_core_module.html
- Go net/http: https://pkg.go.dev/net/http
- Go x/net/netutil: https://pkg.go.dev/golang.org/x/net/netutil
- Laravel 13 rate limiting: https://laravel.com/docs/13.x/rate-limiting
- Laravel 13 requests (trusted proxies): https://laravel.com/docs/13.x/requests
- Laravel 13 Octane: https://laravel.com/docs/13.x/octane
- Laravel 13 cache: https://laravel.com/docs/13.x/cache
- Laravel 13 configuration (maintenance mode): https://laravel.com/docs/13.x/configuration