Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

pingora-edge

TLS edge proxy built on Pingora and BoringSSL. It terminates HTTPS for many hostnames, gets their certificates, drops bad clients before the TLS handshake, then proxies, serves static files or redirects.

Running in production, rough edges and all.

Source and issues: github.com/itzngga/pingora-edge (MIT)

Getting started

Download

Linux binaries (x86_64 and arm64, glibc 2.34+) are on the releases page. Each archive also has proxy.example.toml and the systemd unit.

VER=v0.6.0 ARCH=x86_64  # or aarch64
NAME=pingora-edge-$VER-$ARCH-unknown-linux-gnu
curl -LO https://github.com/itzngga/pingora-edge/releases/download/$VER/$NAME.tar.gz
curl -LO https://github.com/itzngga/pingora-edge/releases/download/$VER/$NAME.tar.gz.sha256
sha256sum -c $NAME.tar.gz.sha256
tar -xzf $NAME.tar.gz
sudo install $NAME/pingora-edge /usr/local/bin/

Build

Or build it yourself. BoringSSL builds from source, so you need cmake, clang, Go and a C/C++ compiler.

cargo build --release

The binary ends up in target/release/pingora-edge. For a static Linux build with cargo zigbuild, see the notes in .cargo/config.toml.

Run

cp proxy.example.toml proxy.toml

Set acme.email, acme.storage and your routes, then:

pingora-edge --check proxy.toml
sudo pingora-edge proxy.toml

Built it yourself? Use ./target/release/pingora-edge instead.

It binds :80 and :443 on all addresses, plus 127.0.0.1:4443, 127.0.0.1:8080 and metrics_listen (default 127.0.0.1:9090). On Linux you need root or CAP_NET_BIND_SERVICE.

For ACME, your hostnames must already point at the server and port 80 must be open.

systemd

There’s an example unit in deploy/pingora-edge.service. It runs as its own user with CAP_NET_BIND_SERVICE, and systemctl reload sends SIGHUP.

sudo systemctl enable --now pingora-edge
sudo systemctl reload pingora-edge

Try it locally

A self-signed cert, a small upstream, no ACME. macOS lets a normal user bind :80 and :443; on Linux run the edge with sudo.

  1. Make a cert and a static root (git ignores these paths):

    mkdir -p examples/certs examples/site examples/state
    
    openssl req -x509 -newkey rsa:2048 -nodes -days 365 \
      -keyout examples/certs/edge.key -out examples/certs/edge.crt \
      -subj "/CN=app.example.test" \
      -addext "subjectAltName=DNS:app.example.test,DNS:static.example.test,DNS:old.example.test"
    
    echo '<h1>static root</h1>' > examples/site/index.html
    
  2. Start an upstream in another terminal:

    mkdir -p /tmp/upstream && echo '<h1>hello from the upstream</h1>' > /tmp/upstream/index.html
    
    python3 -m http.server 8081 --bind 127.0.0.1 --directory /tmp/upstream
    
  3. Check and start the edge with examples/local.toml. The check warns about relative paths, that’s fine here.

    ./target/release/pingora-edge --check examples/local.toml
    
    CONTROL_SOCK=examples/state/control.sock ./target/release/pingora-edge examples/local.toml
    

    It’s ready when it logs Pingora on 127.0.0.1:4443 (it fetches the Cloudflare and crawler IP lists first, so give it a few seconds).

  4. Send some requests:

    curl -sk --resolve app.example.test:443:127.0.0.1 https://app.example.test/ -D -
    
    curl -sk --resolve static.example.test:443:127.0.0.1 https://static.example.test/
    
    curl -sk --resolve old.example.test:443:127.0.0.1 "https://old.example.test/a?b=1" -o /dev/null -w '%{http_code} %{redirect_url}\n'
    
    curl -s http://127.0.0.1:9090/health
    
  5. Stop the upstream and ask for the app like a browser to see the 503 page:

    curl -sk --resolve app.example.test:443:127.0.0.1 -H 'Accept: text/html' https://app.example.test/ -D -
    

    After 10 failures in a row the breaker opens and the edge stops dialling the upstream. curl -s http://127.0.0.1:9090/metrics | grep edge_ shows the counters.

  6. Change X-Edge-Route in examples/local.toml and reload without a restart:

    CONTROL_SOCK=examples/state/control.sock ./target/release/pingora-edge --reload
    

Loopback is trusted, so the abuse gates don’t apply to these tests.

Configuration

One TOML file. proxy.example.toml has every key with a comment, start from there. Always check a file before using it:

pingora-edge --check proxy.toml

[acme], [security] and at least one [[route]] must be there. [security] can be empty. Required keys: acme.email, acme.provider, acme.storage, and name and hosts on each route. Everything else has a default.

Top level

KeyDefault
metricstrueserve /metrics, /health and /api/*
metrics_listen127.0.0.1:9090restart to change
on_demand_hosts""host list file for on-demand TLS

[acme]

Needs a restart to change.

KeyDefault
emailrequired
providerrequiredletsencrypt or zerossl
eab_kid, eab_hmac""for ZeroSSL, never printed
storagerequiredcerts, account and caches. Must be writable

[[route]]

modeDoesUses
proxy (default)forwards to an upstreamupstream, upstream_h2, insecure_skip_verify, timeout_secs, add_headers, on_demand_fallback
staticserves a directorystatic_root, not_found_status, redirects
redirectredirects every hostredirect_to, redirect_status
KeyDefault
namerequiredkeep it unique, it’s the route’s identity across reloads
hostsrequiredno wildcards. [] on the on-demand fallback route
upstreamhost:port, http://host:port or https://host:port, no path
upstream_h2autoHTTP/2 to a TLS upstream. Auto = on for Cloudflare upstreams
insecure_skip_verifyfalseskip the upstream cert check
timeout_secsglobalupstream read timeout for this route
add_headersextra headers to the upstream
rate_limitglobal{ rps = 100, burst = 200 }
cloudflare_onlyfalseonly accept Cloudflare peers
static_cert, static_keyown cert for this route. Without it the route is in the ACME bundle
ignore_sslfalseuse the fallback cert, no ACME. For CDN-fronted origins
static_rootmust exist at startup
not_found_status404404 or 410
redirectsexact paths that 301 on a static route
redirect_totarget host, path and query are kept
redirect_status301301, 302, 307 or 308
on_demand_fallbackfalseserves the on-demand host list. One route max

www. hosts redirect to the apex by themselves. Static files support .br/.gz siblings, ranges and conditional requests, with a 2 s memory cache.

[security]

Access and request checks:

KeyDefault
trusted_ips[]never tracked for abuse. Loopback is always trusted
trust_cloudflareautodon’t strike Cloudflare peers. Auto = on with trust_upstream_real_ip or any cloudflare_only
cloudflare_onlyfalsefor every route
maintenance_modefalse
blocked_ips[]IPs and CIDRs. --check rejects very wide ranges
block_user_agents[]substrings, case-insensitive
block_empty_user_agentfalse
block_header_patterns[]
block_scannerstrueknown scanner paths and tools
reject_invalid_content_lengthtrue
reject_header_injectiontrue
max_request_body5242880bytes

Limits:

KeyDefault
default_rate_limit, default_burst50, 100per visitor per route, req/s
max_inflight_per_ip150
global_rps_limit3000whole edge, 0 = off. Over it = instant 503
fingerprint_rps, fingerprint_burst200, 400per User-Agent, 0 = off
global_connection_limit8000inside Pingora
max_live_tls40000held by the pre-filter. The default is capped to fit RAM
penalty_box_ttl_secs300
penalty_box_capacity100000
keepalive_max_requests100per HTTP/1 connection
keepalive_idle_secsfrom RAM60 under 2 GiB, 120 under 8 GiB, else 0 (no limit)
global_timeout_secs60upstream read timeout. 0 is an error if a proxy route uses it

Pre-filter on :443:

KeyDefault
conn_rate_per_ip100per 10 s, 0 = off
abuse_strikes3strikes before a block
abuse_block_secs300
tls_fp_rate0per ClientHello fingerprint per 10 s, 0 = off
tls_fp_enforcefalsefalse = only count (shadow mode)
max_live_direct0cap for non-Cloudflare connections, 0 = none
max_live_direct_degraded0that cap while the on-demand backend is down
drop_direct_when_backend_downfalse

HTTP/2:

KeyDefault
http2_enabledtruerestart. Off is the quick fix for a rapid reset flood
h2_max_concurrent_streams64restart
h2_cancel_threshold200cancels per IP per 10 s before a block, 0 = off
h2_max_streams_per_conn1000then 429 on that connection, 0 = off

Circuit breaker:

KeyDefault
upstream_max_fails10failures in a row, 0 = off
upstream_fail_timeout_secs5then one probe

Real client IP (for chained edges):

KeyDefault
real_ip_headerX-Real-IP
real_ip_sig_headerX-Real-IP-Sig<unix-ts>.<hex HMAC-SHA256>
real_ip_secret""shared key, never logged. The old key still works for 600 s after a change
real_ip_verifyfalseonly trust a valid signature
trust_upstream_real_ipfalseinner edges only, never on the internet-facing one

[blocklist]

KeyDefault
enabledtrue
source""URL or file, JSON or plain text
token""Authorization: Bearer for URLs
insecurefalseskip cert checks for URLs
pull_secs300
dyn_source""short-lived entries, {"ips":[{"ip":"...","ttl":60}]}
dyn_secs30
cache"""" = <acme.storage>/blocklist-cache.json, off = none
origin_block_header""upstream sets it to ban the visitor (max 3600 s). Stripped before the response goes out

[error_page]

KeyDefault
enabledfalseself-refreshing 503 page for browsers
retry_secs8backs off x1.5 up to 60

Headers

Removed from requests before they go upstream: X-Real-IP, CF-Connecting-IP, True-Client-IP, X-Forwarded-For, X-Forwarded-Host, X-Forwarded-Proto, X-Original-URL, X-Rewrite-URL and your real-IP headers. Then the edge sets the real-IP header itself.

Added to responses unless the upstream sets them: X-XSS-Protection, X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security (max-age=63072000; includeSubDomains; preload), Referrer-Policy, Permissions-Policy, Cross-Origin-Opener-Policy, Cross-Origin-Resource-Policy and Content-Security-Policy (upgrade-insecure-requests).

Live or restart

[[route]] and most of [security] reload live. These need a restart: [acme], [blocklist] (except origin_block_header), [error_page], metrics_listen, on_demand_hosts, http2_enabled, h2_max_concurrent_streams and a few sizing keys.

Not sure? pingora-edge --check --against LIVE NEW tells you. More in Operations.

Certificates

RouteGets
no static_certthe shared ACME bundle (one cert, all these hosts)
static_cert + static_keythat cert, picked by SNI
ignore_ssl = truethe self-signed fallback, no ACME
host in the on-demand listits own cert on the first handshake

Any other SNI gets the fallback and never triggers an order, so scanners can’t make the edge order certs for names they made up.

ACME

HTTP-01 only. Port 80 must be reachable and the hostnames must point at the server. Everything else on :80 gets a 301 to HTTPS.

[acme]
email    = "admin@example.com"
provider = "letsencrypt"
storage  = "/var/lib/pingora-edge/acme"
  • zerossl needs eab_kid and eab_hmac, and falls back to Let’s Encrypt if it fails
  • add a route with a new host and the bundle gets reissued in the background
  • no DNS-01, so no wildcard certs

Static certs

[[route]]
name        = "shop"
hosts       = ["shop.example.com"]
upstream    = "http://127.0.0.1:8082"
static_cert = "/etc/pingora-edge/certs/shop.example.com.crt"
static_key  = "/etc/pingora-edge/certs/shop.example.com.key"

They reload when the files change. --check catches a pair that won’t load (E302) or a key that doesn’t match (E303).

Behind a CDN

If the CDN terminates the real cert, set ignore_ssl = true on the route. Add cloudflare_only = true if only the CDN should reach it.

On-demand TLS

For when customers point their own domains at you.

  1. Put one hostname per line in a file, and set on_demand_hosts to it.
  2. Add one route with on_demand_fallback = true. It serves every host on the list, with the original Host header.
on_demand_hosts = "/etc/pingora-edge/on-demand-hosts.txt"

[[route]]
name               = "tenants"
hosts              = []
upstream           = "http://127.0.0.1:8090"
on_demand_fallback = true
  • the first handshake waits up to 800 ms. If the cert isn’t ready, it gets the fallback and the next visit gets the real one
  • one order per name, even under a burst
  • a failed name waits an hour before the next try
  • certs renew 30 days before expiry
  • the list is checked every 5 s and on SIGHUP, so no restart needed

To look at it: GET /api/ssl on metrics_listen, or GET /certs/summary, GET /certs/list and POST /certs/warmup on the control socket. Warmup orders a cert for a listed name before anyone visits.

Abuse defence

Drop bad traffic as early and as cheaply as possible. From the outside in:

1. Pre-filter on :443

A small Tokio listener reads the TLS ClientHello before Pingora gets the connection, so dropped clients never cost a handshake.

  • non-TLS bytes (HTTP on 443) get reset, so do ClientHellos over 8 KiB and early disconnects
  • 3 seconds to send a full ClientHello
  • conn_rate_per_ip: new connections per IP per 10 s
  • strikes: misbehaving IPs (like disconnecting mid-handshake) get refused for abuse_block_secs after abuse_strikes
  • tls_fp_rate: limit per ClientHello fingerprint, for floods that rotate IPs but not the client. Starts in shadow mode, check /api/tls-fingerprints before you set tls_fp_enforce = true
  • max_live_tls, with separate budgets for Cloudflare and direct traffic. While the on-demand backend is down, direct traffic can get a smaller cap or be refused
  • a watchdog cleans up leaked connections

trusted_ips and Cloudflare peers (when trusted) never get strikes here. Every held connection uses one local port to Pingora, so keep max_live_tls well under the kernel’s port range.

2. HTTP/2

  • h2_max_concurrent_streams per connection
  • h2_max_streams_per_conn, then cheap 429s
  • h2_cancel_threshold counts cancels per IP and hands floods to the pre-filter to block
  • http2_enabled = false falls back to HTTP/1.1, where rapid reset can’t happen (restart)

3. Request checks

  • scanner paths and tools, header injection, bad Content-Length, big bodies
  • blocked_ips, block_user_agents, block_header_patterns, block_empty_user_agent
  • blocklist from a file or URL, plus optional short-lived entries
  • an upstream can ban the visitor it’s answering with origin_block_header
  • cloudflare_only, per route or for everything
  • verified crawler IPs (from the lists Google, Bing, Apple, DuckDuckGo and OpenAI publish) are never blocked by the IP gates

4. Rate limits

  • token bucket per route: default_rate_limit / default_burst, or rate_limit on the route
  • max_inflight_per_ip
  • global_rps_limit, past it requests get 503 right away
  • fingerprint_rps per User-Agent, for botnets that reuse one UA on many IPs

5. Penalty box

IPs that trip the HTTP gates go in for penalty_box_ttl_secs. Repeat offenders move from HTTP refusals to TCP-level blocks.

6. Circuit breaker

After upstream_max_fails failures in a row the route stops dialling the upstream, then sends one probe after upstream_fail_timeout_secs. With [error_page] on, browsers get a 503 page that refreshes itself.

7. Chained edges

The front edge sets real_ip_header and can sign it (HMAC-SHA256) with real_ip_secret. The inner edge trusts it only from trusted peers (trust_upstream_real_ip), and with real_ip_verify only when the signature is valid.

Tips

  • start with the defaults and watch /metrics, refusals are counted per gate
  • long blocks beat attackers that rotate IPs, but home IPs get shared and reused, so a long block can hit a real visitor
  • use shadow mode first where there is one

Operations

Checking a config

Same checks the edge runs at boot and on reload. Writes nothing.

pingora-edge --check [--json] [--strict] [--offline] [--workdir DIR] [--against FILE] <FILE|->
Flag
--jsonJSON output
--strictwarnings fail too
--offlineskip checks on this machine (cert files, folders). Handy on a laptop
--workdir DIRresolve relative paths from DIR
--against FILEdiff against the live config: what changes, restart or not. Needs a file
-read from stdin
CodeMeans
F1xx, F2xxcan’t read, parse or type the file
E2xx, E3xxbroken: bad upstream, redirect loop, bad cert, ACME folder not writable
W4xxallowed but suspicious: a 0 that isn’t “off”, unknown keys, odd hosts
I5xxinfo, like insecure_skip_verify
N6xxwhat a change will do: restart needed, route removed, bundle reissued

Secrets (eab_hmac, real_ip_secret, token) are never printed.

Exit codes: 0 ok, 10 restart required, 11 warnings with --strict, 12 sha mismatch, 64 usage, 65 invalid or rejected, 66 unreadable, 69 no control socket, 70 internal, 75 timeout or not ready, 77 forbidden.

Reloading the config

pingora-edge --reload [--json] [--sock PATH] [--timeout SECS] [--expect-sha HEX64]
pingora-edge --status [--json] [--sock PATH] [--expect-sha HEX64]

Three ways in, same pipeline:

  • SIGHUP (systemctl reload pingora-edge), which also rereads the on-demand list and static certs
  • the edge sees the file change
  • pingora-edge --reload, or POST /config/reload on the control socket

What you get:

  • the file is checked first, then applied whole or not at all. A request never sees half old, half new
  • restart-only keys come back as restart_required instead of half applying
  • under systemd (or PROXY_SUPERVISED=1), a SIGHUP with restart-only changes makes the edge stop itself so systemd starts it again, at most once a minute
  • --expect-sha (64 lowercase hex) applies nothing unless the file on disk has that hash, exit 12
  • every clean config is saved as .proxy.toml.last-good next to it (or PROXY_LAST_GOOD, an absolute path or off). It’s only used at boot when the real file is broken

Control socket

HTTP over a unix socket, nothing on the network. Default /run/pingora-edge/control.sock, CONTROL_SOCK changes it. Anyone local can read, POST needs root or the edge’s own user.

Route
GET /health{"status":"ok"}
GET /config/statusgeneration, hashes, pending restart keys, last reload, last-good
POST /config/reloadreload now, ?expect_sha= optional. 200, 409, 412, 422, 503 or 504
POST /config/verifysend TOML, get the check report against the live config
GET /certs/summary{total, issued, cooling}
GET /certs/liston-demand certs, limit, offset, q
POST /certs/warmup{"domain":"..."} orders a cert for a listed name
curl --unix-socket /run/pingora-edge/control.sock http://localhost/config/status

POST bodies max 64 KiB.

Metrics and health

On metrics_listen (default 127.0.0.1:9090):

Path
/metricsPrometheus: requests, refusals per gate, latency, pre-filter and h2 counters, reloads
/health200 ok, or 503 degraded
/api/sslon-demand cert state, paginated
/api/blocklistsource, last pull, counts
/api/bandwidthbytes per route per day and month
/api/tls-fingerprintstop ClientHello fingerprints

/health is about the edge itself (live TLS connections, watchdog, accept errors, config state). It only says 503 after the watchdog tried to recover and couldn’t, which is when a restart makes sense.

Counters worth watching: edge_conn_rate_drops_total, edge_strikes_total, edge_tls_fp_shadow_total, edge_tls_fp_blocked_total, edge_h2_cancels_total, edge_h2_blocked_ips_total, edge_breaker_short_circuits_total, edge_tls_live_direct, edge_tls_live_cloudflare.

Logs

stdout, so journald picks them up. RUST_LOG=debug for more, default info. Noisy Pingora lines (like clients closing early) are off and counted in metrics instead.

Memory sizing

At start it reads the machine’s memory (cgroup and systemd limits too) and sizes caches and connection caps to fit. That’s where the defaults of max_live_tls and keepalive_idle_secs come from. Set them yourself to override.

Architecture

                          +------------------------------+
 client --TCP--> :443 --> | pre-filter (Tokio)           | --loopback--> Pingora 127.0.0.1:4443
                          | conn-rate gate, abuse box,   |               TLS (BoringSSL), SNI certs,
                          | ClientHello checks, budgets  |               WAF, limits, routing
                          +------------------------------+                    |
                                                                              v
 client --HTTP--> :80 --> ACME HTTP-01 challenges, else 301 to https    upstreams / static roots

 127.0.0.1:9090   /metrics, /health, /api/*
 unix socket      config status, verify, reload; certificate status and warmup
  1. The pre-filter reads the ClientHello and decides if the connection is worth it.
  2. Good ones get spliced to Pingora on 127.0.0.1:4443. The real client IP goes along through a table keyed by the loopback source port, so no PROXY protocol.
  3. Pingora terminates TLS and picks the cert by SNI.
  4. Request checks, limits, routing, then upstream or a file from disk.
  5. :80 answers ACME challenges and redirects the rest to HTTPS.

Why the pre-filter: Pingora sets up TLS state as soon as it accepts. A flood of half-open, non-TLS or slow connections can use that up before any HTTP check runs. Reading a ClientHello first is a lot cheaper. The cost is one loopback hop and one local port per connection.

Around it: one reload task owns the config, a unix socket for control calls, the metrics listener, and a background job that renews on-demand certs.

Source

File
main.rsboot, runtimes, Pingora server
tls_router.rsthe :443 pre-filter
proxy.rsPingora ProxyHttp: filters, routing, upstreams
h2_guard.rsrapid reset guard
limiter.rs, breaker.rsrate limits, penalty box, breaker
acme.rs, on_demand.rsACME bundle, on-demand certs
static_handler.rsstatic files
config.rsconfig and defaults
check.rs, check_rules.rs--check
reload.rshot reload
shield.rs, blocklist.rsCloudflare and crawler ranges, blocklist
metrics.rs, control.rs, cli.rsmetrics, control socket, CLI
tuning.rsmemory sizing

Tests

cargo test

Unit tests for the parts (parsers, limiters, breaker, budgets, config checks, static files). No end-to-end suite, so also try changes with the local setup.