TExcelTAD

TLS & HTTP/2 in HAProxy

HAProxy can handle TLS in three ways: terminate it (decrypt, route on HTTP, talk plain HTTP to servers), re-encrypt (terminate, then open TLS to the servers), or pass it through untouched and route on the SNI name in the handshake, so the servers keep their own certificates. This lesson does all three, with certificates from a session CA.

Certificates: one PEM file per site

HAProxy expects the certificate, any intermediates and the private key in one file, and picks the certificate by SNI when a bind line points at several files or a directory:

text
global
  ssl-default-bind-options ssl-min-ver TLSv1.2
  ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305

frontend fe_https
  bind :443 ssl crt /etc/haproxy/certs/ alpn h2,http/1.1     # every .pem in the folder, chosen by SNI
  http-response set-header Strict-Transport-Security "max-age=31536000"

The first file (alphabetically, for a directory) is the default for clients that send no SNI or an unknown name; strict-sni refuses those instead. alpn h2,http/1.1 enables HTTP/2 for clients that offer it.

Terminating TLS for two sites

bash · try it yourself
ec="-newkey ec -pkeyopt ec_paramgen_curve:P-256"
openssl req -x509 -new -noenc $ec -keyout ca.key -out ca.crt -days 365 -subj "/CN=TAD Lab Root CA" 2>/dev/null
mkdir certs
for site in shop api; do
  openssl req -new -noenc $ec -keyout $site.key -out $site.csr -subj "/CN=$site.example.test" 2>/dev/null
  openssl x509 -req -in $site.csr -CA ca.crt -CAkey ca.key -set_serial 1 -days 90 -out $site.crt \
    -extfile <(printf "subjectAltName=DNS:$site.example.test\n") 2>/dev/null
  cat $site.crt $site.key > certs/$site.pem              # certificate (+ chain) + key in one file
done
cat > app.py <<'EOF'
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.end_headers()
        self.wfile.write(f"app: host={self.headers['Host']} proto={self.headers.get('X-Forwarded-Proto')}\n".encode())
    def log_message(self, *a): pass
HTTPServer(("127.0.0.1", 9000), H).serve_forever()
EOF
python3 app.py &
for i in $(seq 50); do curl -s 127.0.0.1:9000/ > /dev/null && break; sleep 0.1; done
cat > haproxy.cfg <<'EOF'
global
  pidfile haproxy.pid
  ssl-default-bind-options ssl-min-ver TLSv1.2
defaults
  mode http
  timeout connect 2s
  timeout client 10s
  timeout server 10s
frontend fe_http
  bind 127.0.0.1:8080
  http-request redirect scheme https code 301
frontend fe_https
  bind 127.0.0.1:8443 ssl crt "${HOME}/certs/" alpn h2,http/1.1
  http-request set-header X-Forwarded-Proto https
  http-response set-header Strict-Transport-Security "max-age=31536000"
  default_backend be_app
backend be_app
  server app 127.0.0.1:9000
EOF
haproxy -c -f haproxy.cfg && haproxy -D -f haproxy.cfg
R="--resolve shop.example.test:8443:127.0.0.1 --resolve api.example.test:8443:127.0.0.1 --resolve shop.example.test:8080:127.0.0.1"
curl -s -o /dev/null -w 'http  -> %{http_code} %{redirect_url}\n' $R http://shop.example.test:8080/cart
for site in shop api; do
  curl -s $R --cacert ca.crt -w "        (HTTP/%{http_version})\n" https://$site.example.test:8443/
  openssl s_client -connect 127.0.0.1:8443 -servername $site.example.test < /dev/null 2>/dev/null | grep -m1 '^subject=' | sed 's/^/        certificate /'
done
curl -s -D - -o /dev/null $R --cacert ca.crt https://shop.example.test:8443/ | grep -i strict | tr -d '\r'
kill $(cat haproxy.pid) %1
Configuration file is valid
http  -> 301 https://shop.example.test:8080/cart
app: host=shop.example.test:8443 proto=https
        (HTTP/2)
        certificate subject=CN = shop.example.test
app: host=api.example.test:8443 proto=https
        (HTTP/2)
        certificate subject=CN = api.example.test
strict-transport-security: max-age=31536000

The redirect keeps the Host header as the client sent it, port included (in production on port 443 that is simply the site name). Each name got its own certificate from the folder, both negotiated HTTP/2 with the client, and the backend received plain HTTP/1.1 with X-Forwarded-Proto: https. Adding a site is dropping a PEM file in the folder and reloading, or, without a reload, new ssl cert / set ssl cert / commit ssl cert and add ssl crt-list through the Runtime API.

Passthrough: routing on SNI without decrypting

In mode tcp, HAProxy can wait for the TLS ClientHello, read the SNI name from it, and forward the still-encrypted connection to the right server. The servers hold their own certificates; HAProxy never sees a key. This suits Kubernetes API servers, services that need end-to-end TLS (or client certificates) and multi-tenant platforms:

bash · try it yourself
ec="-newkey ec -pkeyopt ec_paramgen_curve:P-256"
openssl req -x509 -new -noenc $ec -keyout ca.key -out ca.crt -days 365 -subj "/CN=TAD Lab Root CA" 2>/dev/null
for site in shop api; do
  openssl req -new -noenc $ec -keyout $site.key -out $site.csr -subj "/CN=$site.example.test" 2>/dev/null
  openssl x509 -req -in $site.csr -CA ca.crt -CAkey ca.key -set_serial 1 -days 90 -out $site.crt \
    -extfile <(printf "subjectAltName=DNS:$site.example.test\n") 2>/dev/null
done
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
  access_log off;
  server { listen 127.0.0.1:9443 ssl; ssl_certificate shop.crt; ssl_certificate_key shop.key; return 200 "shop backend terminated TLS itself\n"; }
  server { listen 127.0.0.1:9444 ssl; ssl_certificate api.crt;  ssl_certificate_key api.key;  return 200 "api backend terminated TLS itself\n"; }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
cat > haproxy.cfg <<'EOF'
global
  pidfile haproxy.pid
defaults
  mode tcp
  timeout connect 2s
  timeout client 10s
  timeout server 10s
frontend fe_tls_passthrough
  bind 127.0.0.1:8443
  tcp-request inspect-delay 5s
  tcp-request content accept if { req.ssl_hello_type 1 }
  use_backend be_api if { req.ssl_sni -i api.example.test }
  default_backend be_shop
backend be_shop
  server shop 127.0.0.1:9443
backend be_api
  server api 127.0.0.1:9444
EOF
haproxy -c -f haproxy.cfg && haproxy -D -f haproxy.cfg
for site in shop api; do
  curl -s --resolve $site.example.test:8443:127.0.0.1 --cacert ca.crt https://$site.example.test:8443/
done
kill $(cat haproxy.pid); nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
Configuration file is valid
shop backend terminated TLS itself
api backend terminated TLS itself

tcp-request inspect-delay lets HAProxy buffer the start of the connection; req.ssl_hello_type 1 confirms a ClientHello arrived; req.ssl_sni reads the name. The trade-off: HAProxy can't see paths, headers or cookies, can't add X-Forwarded-For (use the PROXY protocol with send-proxy-v2 if the servers support it), and can't do HTTP-level health checks or retries.

Re-encrypting to the servers

When the network between HAProxy and the servers isn't trusted, terminate and re-encrypt, and verify the server certificates:

text
backend be_app
  server app1 10.0.1.11:8443 ssl verify required ca-file /etc/haproxy/internal-ca.pem sni str(app.internal) check check-sni app.internal
  # optional mTLS towards the server: crt /etc/haproxy/client.pem

verify required with a ca-file is essential: ssl verify none encrypts but accepts any certificate, so a man in the middle goes unnoticed. HAProxy defaults to verifying: a server line with ssl and no ca-file is a fatal configuration error ("verify is enabled by default but no CA file specified"), and the message suggests verify none. Resist that suggestion outside a lab.

HTTP/3

Ubuntu's HAProxy 2.8 is built with QUIC support using the OpenSSL compatibility layer (haproxy -vv shows +QUIC and QUIC_OPENSSL_COMPAT), so it can serve HTTP/3. The sandbox has no HTTP/3 client, but haproxy -c shows what the configuration needs: a QUIC listener next to the TCP one, an alt-svc header to announce it, and, with this OpenSSL, the limited-quic global option:

bash · try it yourself
openssl req -x509 -new -noenc -newkey ec -pkeyopt ec_paramgen_curve:P-256 -keyout site.key -out site.crt -days 30 -subj "/CN=shop.example.test" 2>/dev/null
cat site.crt site.key > site.pem
cat > haproxy.cfg <<'EOF'
global
  limited-quic                                  # required with the OpenSSL compatibility layer
defaults
  mode http
  timeout connect 2s
  timeout client 10s
  timeout server 10s
frontend fe_https
  bind 127.0.0.1:8443 ssl crt "${HOME}/site.pem" alpn h2,http/1.1
  bind quic4@127.0.0.1:8443 ssl crt "${HOME}/site.pem" alpn h3
  http-response set-header alt-svc "h3=\":8443\"; ma=86400"
EOF
haproxy -c -f haproxy.cfg
sed -i '/limited-quic/d' haproxy.cfg
haproxy -c -f haproxy.cfg 2>&1 | grep ALERT | sed -E 's/^\[ALERT\] *\([0-9]+\) : //'
Configuration file is valid
config : Binding [haproxy.cfg:9] for frontend fe_https: this SSL library does not support the QUIC protocol. A limited compatibility layer may be enabled using the "limited-quic" global option if desired.
config : Fatal errors found in configuration.

On a production host, open UDP 443 in the firewall too, or browsers never get past the alt-svc announcement (HTTP/3 & QUIC).

Test yourself

What must a PEM file referenced by HAProxy's crt contain?

  1. Only the certificate
  2. The certificate, its intermediate chain and the private key in one file
  3. Only the key
  4. The CA root

In TLS passthrough mode, how does HAProxy choose the backend?

  1. From the URL path
  2. From the SNI name in the TLS ClientHello, read with req.ssl_sni in TCP mode
  3. From the Host header
  4. Randomly

Why is ssl verify none on a server line risky?

  1. It disables encryption
  2. Traffic is encrypted, but HAProxy accepts any certificate, so an attacker in the path can impersonate the server
  3. It is slower
  4. It breaks HTTP/2