AlgoViz

Load balancer security

medium 26 min

A load balancer is the front gate of a system.

Video lesson · Chapter 1 of 5

Which side of the proxy can read the request

0:00 / 3:07

The gate guard: load balancer security in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

All public traffic meets the load balancer first. That makes it a good place for checks that should apply to every request: encryption, allowed addresses, request limits, known bad patterns and the size of a message.

Load balancer security means two things. The balancer protects the servers behind it, and the balancer itself must be protected: its keys, its settings and its capacity.

Why it exists

Checks in one place are easier to keep correct than the same checks in fifty services. A bad request that is refused at the gate costs the servers nothing.

The gate is not enough alone. It does not know whether this user may see that invoice, it can be wrong about what is harmful, and a flood bigger than its network link never reaches its rules. So we use defence in depth: several layers that each stop part of the trouble.

A short history

  1. May 2000

    RFC 2827 asks networks to drop packets whose source address cannot be true. Forged addresses are what make many floods possible.

  2. August 2007

    RFC 4987 gathers the known defences against SYN floods, including SYN cookies.

  3. April 2012

    RFC 6585 defines status 429, Too Many Requests.

  4. December 2015

    Let's Encrypt opens its public beta. Free, automatic certificates make HTTPS normal.

  5. August 2018

    TLS 1.3 is published as RFC 8446.

  6. March 2021

    RFC 8996 says TLS 1.0 and 1.1 must not be used.

Words to know

TLS
Transport Layer Security: encryption and proof of identity for a connection. SSL is the old name of its broken ancestors.
TLS termination
The encrypted connection ends at the balancer, which can read the request.
mTLS
Mutual TLS: both sides show a certificate.
WAF
Web application firewall: rules that inspect HTTP requests.
DDoS
Distributed denial of service: many sources try to make a service unavailable.
SYN flood
Many half-open TCP connections, meant to fill memory.
Rate limit
How many requests a client may make in a time.
False positive
A good request that is blocked by mistake.

How it works

Step through the idea, or press Play.

Step 1 of 3

At the connection. Address rules, connection limits, SYN protection

Understand it

Start here

The castle guard story

Imagine a castle with a moat and a drawbridge. The gate is where everyone must pass, so that is where the guard stands. A wise castle also has a barrier on the road far outside.

The drawbridge guard
Nobody checks

The moat slows crowds, the gate checks, the guard inspects, the list decides and the sign limits.

Overview

What it protects against

Threats in words

ThreatWhat it triesMain defence
SQL injectionMake input be read as a database commandPrepared statements in the service. The firewall is a second net
Cross-site scriptingMake a page run someone else's scriptEscape output. Content Security Policy. Firewall second
Path traversalReach files outside the allowed folderSafe file handling, clean paths
Command injectionMake input be run by a shellDo not call a shell with input
Cross-site request forgeryUse a logged-in browser without consentTokens and SameSite cookies. A firewall helps little
Person in the middleRead or change trafficTLS with checked certificates
FloodsUse up bandwidth, memory or workersUpstream filtering, limits, spare capacity
Bots and scrapersTake data or try stolen passwordsRate limits, bot detection, multi-factor login

Defence in depth

Users outside reach an edge network that filters floods. Inside our system is a load balancer that ends TLS and applies limits, then a web application firewall, then two servers. The servers check authorisation.
Each layer stops what the next should not have to handle. Some products run the firewall inside the balancer or at the edge network.

Jobs of the gate

  • End TLS

    Encrypt the public side and hold the certificates.

  • Firewall

    Inspect requests for known bad patterns.

  • Absorb floods

    SYN protection, timeouts and limits.

  • Limit rates

    Per client, key or endpoint.

  • Address rules

    Allow lists and block lists.

  • Clean headers

    Remove or replace headers that only we may set.

TLS

Three places TLS can end

ChoiceBetween balancer and serverCan inspect?Notes
TerminationPlain HTTPYesLeast server work, certificates in one place, inside traffic readable
PassthroughThe client's own TLSNoBalancer holds no key, servers do the work, no path rules or firewall
Re-encryption (bridging)A second TLS connectionYesInside traffic encrypted, more processing, two sets of certificates
Re-encryption is not end to end: the balancer sees the plain request for a moment. Only passthrough keeps the client's encryption up to the server.

The three choices

Re-encryption

A client opens TLS to a load balancer, whose certificate and key come from a key store. The balancer opens a second TLS connection to a server inside its own machine box.
Two separate encrypted connections. The balancer must check the server's certificate too.

Good TLS habits

  1. 1

    Offer TLS 1.3 and 1.2 only

    TLS 1.0 and 1.1 must not be used (RFC 8996). TLS 1.3 also needs one round trip less for a new connection than TLS 1.2.

  2. 2

    Use a maintained cipher list

    Take the provider's current policy or your standard, and do not invent one.

  3. 3

    Renew automatically

    Automate certificates and alert well before the end date. Short lifetimes limit the harm of a lost key.

  4. 4

    Guard the keys

    Keep them in a key store or hardware module with few readers. Never in code or images.

  5. 5

    Redirect to HTTPS

    And send HSTS once every part of the site works over HTTPS.

  6. 6

    Check the inside too

    With re-encryption, verify the server's certificate. Use mTLS when servers must be sure who calls.

Order

Which check can come first?

A check can only use what can already be read. Before TLS ends, the balancer knows the connection's address and perhaps the requested host name. Headers, paths and API keys come later.

A request through the gate

Cheap checks first. Log every refusal with its rule.

WAF

Web application firewall

A WAF reads HTTP requests, so TLS must end before it. Rules look at the path, query, headers and body. Some describe what is bad (a block pattern). Others describe what is allowed (methods, sizes, formats) and refuse the rest.

What a rule can do

ActionEffectUse
BlockRefuse, often with 403A rule you trust
ChallengeAsk the browser or person to prove itselfSuspicious but not certain
Count or logLet it pass and record itTesting a new rule
Rate limitSlow or refuse repeated requestsLogin and search pages
Text
endpoint  /ordersmethods   GET, POSTbody      JSON, at most 32 KBpath      already in its normal formfields    item: integer, quantity: 1 to 20otherwise count first, then block

The OWASP CRS is a free set of generic rules for ModSecurity and compatible firewalls. Broad patterns also match honest text: a book titled "Select from the Union" looks a little like a database command.

Why good rules still block good people

990990+4995≈16.5%\frac{990}{990 + 4995} \approx 16.5\%
Suppose 1,000,000 requests hold 1,000 bad ones. A rule catches 99% of bad (990) and wrongly flags 0.5% of the 999,000 good (4,995). Only about one flag in six is right. So test rules in count mode and tune them.

WAF in practice

From counting to blocking

The life of a rule

Every arrow back to counting is cheaper than refusing customers.

Rolling out a rule

  1. 1

    Count

    Record matches for days, including a busy one.

  2. 2

    Read

    Look at samples and write narrow exceptions.

  3. 3

    Challenge or block

    Start with one endpoint or a few percent.

  4. 4

    Watch

    Compare errors, sign-ups and support messages.

Floods

Denial of service

KindExamplesProtection
Network, layer 3UDP and ICMP floods, amplificationUpstream scrubbing, anycast networks, drop what you do not serve
Transport, layer 4SYN floodsSYN cookies, connection limits, short handshake timeouts
Application, layer 7HTTP floods, very slow requests, costly API callsRate limits, header and body timeouts, caching, challenges, bot detection

When local rules cannot help

link=10 Gb/s,flood=100 Gb/s;⇒;at most 10% of packets fit\text{link} = 10\,\text{Gb/s},\quad \text{flood} = 100\,\text{Gb/s} ;\Rightarrow; \text{at most } 10\%\text{ of packets fit}
The link is full before any rule runs. Someone with more capacity must filter upstream.

SYN cookies

Memory is used only after the client proves it receives replies. A forged address never sends the last step.

Limits

Three rate limiting ways

WayRuleWatch out
Fixed window100 requests per minute, resets on the minute200 can pass around the reset
Sliding window100 in any 60 secondsMore memory, or an approximation
Token bucketBursts up to the bucket, then a steady refillChoose both numbers
The details live in rate limiting. With several balancers, share the counters or divide the limit.

Most requests a token bucket can pass

N(t)≤B+r tB=20,;r=2/s,;t=60 s:;140N(t) \le B + r\,t \qquad B = 20,; r = 2/\text{s},; t = 60\,\text{s}:; 140
Bucket of 20, refilled at 2 a second, in one minute.

Answer with 429 and, if you can, a Retry-After header. Check your product: NGINX's limit_req answers 503 unless you set another status. An API gateway often holds limits per key or customer.

The gate itself

Protect the balancer

Do

  • Separate the admin network from the public one
  • Change settings through reviewed code
  • Update promptly
  • Let servers accept traffic only from the balancer
  • Run more than one, in different zones
  • Alert on odd traffic, login failures, blocks and certificate dates

Do not

  • Expose the admin page to the internet
  • Share one administrator login
  • Leave servers reachable around the gate
  • Write secrets or whole bodies to logs
  • Block countries or Tor without a reason
  • Treat a reputation list as always right

Address reputation lists can block known bad sources, but addresses are shared and change hands. Give every block an end date and a way to ask for review.

Best practice

The short list

  1. 1

    Modern TLS

    1.3 and 1.2, current policy.

  2. 2

    Defence in depth

    Edge network, flood protection, firewall, balancer, servers. Each checks something different.

  3. 3

    Monitor and alert

    Traffic shape, failed logins, refusals by rule, and good requests that were blocked.

  4. 4

    Automatic certificates

    Renew early and alert on failure.

  5. 5

    Reputation with care

    Feeds as one signal, with an end date.

Summary

The whole topic in one minute.

Put the checks in an order that is possible. Address rules and connection limits come first, then TLS ends, and only then can the balancer read headers, apply a firewall and limit by user or endpoint.

Choose where TLS ends, keep keys safe and renew certificates automatically. Start firewall rules in count mode. Plan for floods larger than your link with a provider in front. Keep authorisation and input checks in the services, because the gate is one layer, not all of them.

  • The balancer is a gate. Services still check permission and input.
  • Order matters: connection checks, TLS, limits, firewall, forward.
  • Termination, passthrough and re-encryption differ in who can read.
  • Test firewall rules in count mode.
  • A flood larger than your link must be stopped upstream.

Sources