Denial of Service and DDoS
Confidentiality and integrity attacks want something from your system. A denial-of-service (DoS) attack only wants it to stop working for everyone else: the shop that cannot take orders on its busiest day, the login server that times out, the DNS name that no longer resolves. It hits the A of the CIA triad, and it is often the cheapest attack to buy. This lesson explains the three layers at which a service can be exhausted, simulates the most useful defence in software, a rate limiter, and lists how floods are spotted and absorbed. Nothing here sends traffic anywhere: the traffic is a list inside the example.
Mechanism: exhaust something finite
Every service has a bottleneck: link bandwidth, packets per second a router can forward, connection-table slots, threads, database connections, CPU per request. A DoS attack drives one of them to its limit, so legitimate requests queue or are dropped. A distributed DoS (DDoS) does it from many sources at once, usually a botnet of compromised devices or rented cloud machines, so blocking one address does not help.
| Layer | What is exhausted | Examples | Measured in |
|---|---|---|---|
| Volumetric | the bandwidth of the link | UDP floods, reflection and amplification | bits per second |
| Protocol | state in servers, firewalls, load balancers | SYN floods (half-open connections), fragment floods | packets per second |
| Application | the work behind each request | floods of search or login requests, slow requests that hold connections open (slowloris-style) | requests per second |
Some DoS is not a flood at all: a single crafted request that makes a regular expression backtrack for minutes (ReDoS), a decompression bomb, or an API call that returns a million rows. Those are bugs, fixed in code, and they show why input limits belong in secure coding.
Reflection and amplification
The volumetric trick of the last decade: the attacker sends small UDP requests to many open servers (resolvers, old time and status services) with the victim's address forged as the source. Each server dutifully sends its much larger answer to the victim. The attacker's bandwidth is multiplied by the ratio of answer to request size, the amplification factor, and the traffic arrives from thousands of legitimate servers, not from the attacker.
The arithmetic is a single division. The sizes below are illustrative, not measurements of any particular service:
# Amplification: the attacker sends small requests with the VICTIM's address as the source;
# open servers send their large answers to the victim. Illustrative sizes in bytes.
services = {"DNS (large answer)": (64, 3000), "old UDP status query": (50, 10000), "well-behaved echo": (64, 64)}
uplink_mbit = 100 # what the attacker can send
for name, (req, resp) in services.items():
factor = resp / req
print(f"{name:20} factor {factor:6.1f} -> {uplink_mbit * factor / 1000:6.1f} Gbit/s at the victim")DNS (large answer) factor 46.9 -> 4.7 Gbit/s at the victim
old UDP status query factor 200.0 -> 20.0 Gbit/s at the victim
well-behaved echo factor 1.0 -> 0.1 Gbit/s at the victim
The cure for reflection is upstream: networks that drop packets with forged source addresses (ingress filtering, BCP 38, RFC 2827), and servers that are not open to the whole Internet or that answer small requests with small answers. The victim alone cannot filter its way out of a full link; the traffic has to be stopped before it reaches the link, which is what upstream scrubbing services do.
Application floods and the token bucket
At the application layer, every request looks legitimate on its own. The standard first defence is a rate limiter per client (per address, API key or account), and the standard algorithm is the token bucket: each client has a bucket that fills with tokens at rate per second up to burst; a request takes one token or is refused with 429 Too Many Requests. Bursts are allowed, sustained floods are not.
The program simulates ten seconds of traffic to a lab web app that can serve 100 requests per second: 20 normal clients at 2 requests per second and 5 flooding clients at 200. When the app is overloaded it serves only its fair share of what reaches it.
class TokenBucket:
"""Allow `rate` requests per second on average, with bursts up to `burst`."""
def __init__(self, rate, burst):
self.rate, self.burst = rate, burst
self.tokens, self.last = burst, 0.0
def allow(self, now):
self.tokens = min(self.burst, self.tokens + (now - self.last) * self.rate)
self.last = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
# Ten seconds of synthetic traffic to a lab web app that can serve 100 requests/s.
# 20 normal clients send 2 requests/s each; 5 flooding clients send 200/s each.
CAPACITY, SECONDS = 100, 10
clients = {f"10.10.0.{20 + i}": 2 for i in range(20)}
clients.update({f"203.0.113.{50 + i}": 200 for i in range(5)})
arrivals = sorted((k / rate, src) for src, rate in clients.items()
for k in range(rate * SECONDS))
def run(limit):
buckets = {src: TokenBucket(rate=5, burst=10) for src in clients}
passed = {"legit": 0, "flood": 0}
for t, src in arrivals:
if limit and not buckets[src].allow(t):
continue # answered with 429 Too Many Requests
passed["legit" if src.startswith("10.10.") else "flood"] += 1
offered = (passed["legit"] + passed["flood"]) / SECONDS
share = min(1.0, CAPACITY / offered) # the server serves this fraction of what reaches it
legit_sent = 2 * 20 * SECONDS
print(f"limit={'on ' if limit else 'off'} reaching the app {offered:6.1f}/s "
f"legit requests served {passed['legit'] * share:5.0f} of {legit_sent} "
f"({passed['legit'] * share / legit_sent:.0%})")
run(limit=False)
run(limit=True)limit=off reaching the app 1040.0/s legit requests served 38 of 400 (10%)
limit=on reaching the app 69.5/s legit requests served 400 of 400 (100%)
Without the limiter, 1,040 requests per second arrive and normal users get about one answer in ten. With a bucket of 5 per second (burst 10) per client, each flooder is held to about 6 per second over the ten seconds, everything that reaches the app fits in its capacity, and every normal request is served. Now picture the same flood from 5,000 addresses at 2 requests per second each: every one of them looks exactly like a normal client, and a per-address limit does nothing. That is why large DDoS defence moves to the network edge and to behaviour-based filtering.
How it is detected
- Baselines and their breaks: requests per second, bits and packets per second, new connections per second, error rate (5xx, 429), latency percentiles. An attack is a sudden departure from the usual daily curve.
- Shape of the traffic: many half-open connections (SYN_RCVD) for a SYN flood; UDP from source port 53 or other service ports that you never queried for reflection; one URL or user agent dominating the request log for an application flood.
- Source spread: thousands of new source addresses or networks within minutes points to a botnet.
- Distinguish it from success: a sale or a news mention also brings a spike, with normal behaviour per client. Check before blocking.
How it is mitigated
- Capacity and architecture: a CDN or anycast network in front of the service, auto-scaling, caching of everything that can be cached, and no single small origin exposed directly.
- Upstream scrubbing: a DDoS protection service or the ISP filters volumetric floods before they reach your link; agree on it and test it before you need it.
- Protocol hardening: SYN cookies so a SYN flood cannot fill the connection backlog (the TCP handshake lab shows it), connection and header timeouts, limits on request size.
- Application controls: per-client rate limits, queues with timeouts, cheap answers for expensive operations (pagination, caching), and a "degraded mode" that keeps the core working.
- A runbook: who calls the provider, which features can be switched off, how customers are told. Availability incidents follow the incident-response process of the Blue Team.
Pitfalls
- Testing your own resilience against production without a contract. Load tests and DDoS simulations against a provider's network need the provider's written approval, and against anything you do not own they are a crime in most countries (Law and Ethics).
- Rate limiting only by IP address. Many real users share one address (offices, mobile carrier NAT), and attackers spread across many.
- Forgetting dependencies. The DNS provider, the payment API and the login service are each a single point of failure.
- Treating DoS as "only availability". Floods are also used as a distraction while another attack happens.
Practice
1. A request of 40 bytes produces an answer of 4,000 bytes. What is the amplification factor, and what does an attacker with a 50 Mbit/s uplink send to the victim?
Factor , so about Mbit/s, that is 5 Gbit/s, if enough open servers answer.
2. In the simulation, set the bucket to rate=20, burst=40. Are all legitimate requests still served?
Each flooder now passes about 24 per second (20 per second plus the starting burst of 40 spread over 10 s), so requests per second reach an app with capacity 100, and the program reports 251 of 400 normal requests served (63 %). A limit has to sit above what a real client needs and low enough that the flooders you expect, added together, stay under capacity.
3. Your login endpoint has 80 % CPU at normal load and every request costs a slow password hash. Why is it a DoS risk, and what helps?
An attacker can make the server compute many slow hashes cheaply. Rate-limit per account and per source before hashing, add a cheap proof of work or a CAPTCHA only when the rate is high, and scale the login service separately from the rest of the site.
Test yourself
A flood of half-open TCP connections fills a server's connection backlog. Which layer of DoS is this?
- Volumetric
- Protocol
- Application
- Physical
Why does the victim of a reflection attack see traffic from thousands of legitimate servers?
- The servers are infected
- The attacker forged the victim's address as the source of the requests
- DNS always answers everyone
- The victim's firewall forwards it
In the token-bucket simulation, why did the limiter restore service for every normal client?
- It blocked all addresses outside 10.10.0.0/24
- It held each flooding client to about 5 requests per second, so the total fit within capacity
- It made the app faster
- It dropped every 10th request
Which measure stops reflection attacks closest to their origin?
- A bigger web server
- Ingress filtering of forged source addresses (BCP 38)
- Longer passwords
- HSTS