Skip to content

Commit 5809e13

Browse files
committed
fix(ingress): harden DNS provider API calls
- No provider HTTP call had a timeout, so a stalled connection could hang dnsman.py inside run_pass and stop the renewal loop. Every Cloudflare, Linode and Namecheap request now has a 30s timeout; the per-method request branches collapse into requests.request. - Linode list calls read only the first page (100 items): records past it were never seen, so a stale CAA pin stayed, TXT records were duplicated and unset reported success. _get_all pages through, and a failed page fails the lookup. - Linode set_alias_record deleted the existing records before resolving the target, so a resolution failure left the name empty. Resolve first, then clear_conflicting_alias (which already covers CNAMEs). The docs described a CNAME fallback the code never had. - Route53 returned a stale zone id from another zone when the lookup failed. - Credential files were written under the default umask and chmod'ed afterwards; the Route53 one was never tightened. write_secret_file creates them 0600 (tightening an existing file before writing), and dns01.sh writes the AWS credentials under umask 077. Signed-off-by: Kevin Wang <wy721@qq.com>
1 parent a3410a0 commit 5809e13

25 files changed

Lines changed: 468 additions & 1292 deletions

‎custom-domain/dstack-ingress/DNS_PROVIDERS.md‎

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,15 @@ This guide explains how to configure dstack-ingress to work with different DNS p
1515

1616
- `DOMAIN` - Your custom domain (e.g., `app.example.com`)
1717
- `GATEWAY_DOMAIN` - dstack gateway domain (e.g., `gateway.dstack-prod5.phala.network`)
18+
- `CERTBOT_EMAIL` - Email for Let's Encrypt registration
1819
- `TARGET_ENDPOINT` - Backend application endpoint to proxy to
20+
- `DNS_PROVIDER` - DNS provider to use (`cloudflare`, `linode`, `namecheap`)
1921

2022
### Optional Variables
2123

22-
- `DNS_PROVIDER` - DNS provider to use (`cloudflare`, `linode`, `namecheap`, `route53`). Detected from the provider's credential variable when unset; set it explicitly for `route53`
23-
- `ACME_EMAIL` - Contact address for the ACME account (`CERTBOT_EMAIL` still works). Published in the evidence, so leave it unset unless you want one
2424
- `SET_CAA` - Enable CAA record setup (default: false)
2525
- `PORT` - HTTPS port (default: 443)
26-
- `TXT_PREFIX` - Prefix for TXT records (default: "_dstack-app-address")
27-
28-
See the [README](README.md#environment-variables) for the full list.
26+
- `TXT_PREFIX` - Prefix for TXT records (default: "_tapp-address")
2927

3028
## Provider-Specific Configuration
3129

@@ -52,9 +50,9 @@ LINODE_API_TOKEN=your-api-token
5250

5351
**Important Note for Linode:**
5452
- Linode has a limitation where CAA and CNAME records cannot coexist on the same subdomain
55-
- To work around this, the system will attempt to use A records instead of CNAME records
56-
- If the gateway domain can be resolved to an IP, an A record will be created
57-
- If resolution fails, it falls back to CNAME (but CAA records won't work on that subdomain)
53+
- To work around this, the system uses A records instead of CNAME records
54+
- The gateway domain is resolved to an IP and an A record is created for it
55+
- If resolution fails, the alias step fails and the existing records are left untouched
5856
- This is a Linode-specific limitation not present in other providers
5957

6058
### Namecheap
@@ -70,7 +68,6 @@ NAMECHEAP_CLIENT_IP=your-client-ip
7068
- `NAMECHEAP_USERNAME` - Your Namecheap account username
7169
- `NAMECHEAP_API_KEY` - Your Namecheap API key (from https://ap.www.namecheap.com/settings/tools/apiaccess/)
7270
- `NAMECHEAP_CLIENT_IP` - The IP address of the node (required for Namecheap API authentication)
73-
- `NAMECHEAP_SANDBOX` - Set to `true` to use the Namecheap sandbox API (default: false)
7471

7572
**Important Notes for Namecheap:**
7673
- Namecheap API requires node IP address for authentication, and you need add it to whitelist IP first.
@@ -84,7 +81,7 @@ DNS_PROVIDER=route53
8481
AWS_ACCESS_KEY_ID=service-account-key-that-can-assume-role
8582
AWS_SECRET_ACCESS_KEY=service-account-secret-that-can-assume-role
8683
AWS_ROLE_ARN=role-that-can-mod-route53
87-
AWS_REGION=your-closest-region # default: us-east-1
84+
AWS_REGION=your-closest-region
8885
```
8986

9087
**Required Permissions:**
@@ -210,7 +207,7 @@ If you see "Could not detect DNS provider type", ensure you have either:
210207

211208
### Certificate Generation Issues
212209

213-
Different providers may have different propagation times. certbot waits 120 seconds after writing the challenge record (300 for Linode); Route53 instead waits until the change has synced. With `DELEGATION_ZONE`, the wait is `DELEGATION_PROPAGATION_SECONDS`.
210+
Different providers may have different propagation times. The default is 120 seconds, but you may need to adjust based on your provider's behavior.
214211

215212
### Permission Errors
216213

‎custom-domain/dstack-ingress/Dockerfile‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,14 +79,19 @@ RUN --mount=type=bind,source=scripts,target=/tmp/scripts,ro \
7979
/bin/bash -o pipefail -c 'set -euo pipefail; \
8080
rm -rf /scripts && mkdir -p /scripts && chmod 755 /scripts && \
8181
cd /tmp/scripts && \
82+
find . -type d -print0 | while IFS= read -r -d "" dir; do \
83+
rel="${dir#./}"; \
84+
[[ -z "$rel" ]] && continue; \
85+
install -d -m 755 "/scripts/$rel"; \
86+
done && \
8287
find . -type f -print0 | while IFS= read -r -d "" file; do \
8388
rel="${file#./}"; \
8489
perm=644; \
8590
case "$rel" in \
8691
*.sh) perm=755 ;; \
8792
*.py) case "$rel" in */*) perm=644 ;; *) perm=755 ;; esac ;; \
8893
esac; \
89-
install -D -m "$perm" "$file" "/scripts/$rel"; \
94+
install -m "$perm" "$file" "/scripts/$rel"; \
9095
done'
9196

9297
ENV PATH="/scripts:$PATH"

‎custom-domain/dstack-ingress/README.md‎

Lines changed: 26 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ TCP proxy with automatic TLS termination for dstack applications.
77
dstack-ingress is a HAProxy-based L4 (TCP) proxy that provides:
88

99
- Automatic SSL certificate provisioning and renewal via Let's Encrypt
10-
- Multi-provider DNS support (Cloudflare, Linode DNS, Namecheap, Route53)
10+
- Multi-provider DNS support (Cloudflare, Linode DNS, Namecheap)
1111
- Pure TCP proxying — all protocols (HTTP, WebSocket, gRPC, arbitrary TCP) work transparently
1212
- Wildcard domain support
1313
- SNI-based multi-domain routing
@@ -22,7 +22,7 @@ dstack-ingress is a HAProxy-based L4 (TCP) proxy that provides:
2222

2323
3. **Certificate Renewal**: A background daemon checks for renewal every 12 hours. On renewal, HAProxy is gracefully reloaded with zero downtime.
2424

25-
4. **Evidence Generation**: Generates cryptographically linked attestation evidence (ACME account, certificates, TDX quote / dstack attestation) for TEE verification.
25+
4. **Evidence Generation**: Generates cryptographically linked attestation evidence (ACME account, certificates, TDX quote) for TEE verification.
2626

2727
### Wildcard Domain Support
2828

@@ -156,9 +156,11 @@ environment:
156156

157157
| Variable | Description |
158158
|----------|-------------|
159-
| `DOMAIN` or `DOMAINS` | The domain to serve, or several in `DOMAINS`; both may be set. `DOMAINS` takes one domain per line, or a single comma-separated line (commas in a multi-line value are not separators). Supports wildcards (`*.example.com`) |
160-
| `TARGET_ENDPOINT` | Backend address, e.g. `app:80` or `http://app:80`. Not needed with `ROUTING_MAP` |
159+
| `DOMAIN` | Your domain (single-domain mode). Supports wildcards (`*.example.com`) |
160+
| `TARGET_ENDPOINT` | Backend address, e.g. `app:80` or `http://app:80` |
161161
| `GATEWAY_DOMAIN` | dstack gateway domain (e.g. `gateway.dstack-prod5.phala.network`) |
162+
| `ACME_EMAIL` | *(optional)* ACME contact address, in either mode. `CERTBOT_EMAIL` is the historical name and still works. See below — it is optional, and published |
163+
| `DNS_PROVIDER` | DNS provider (`cloudflare`, `linode`, `namecheap`) |
162164

163165
`GATEWAY_DOMAIN` is published as your domain's CNAME target, so its first label
164166
must start with a letter or digit. Android's resolver rejects a leading
@@ -171,34 +173,28 @@ otherwise arbitrary — the gateway answers every name under its domain.
171173
| Variable | Default | Description |
172174
|----------|---------|-------------|
173175
| `PORT` | `443` | HAProxy listen port |
174-
| `DOMAINS` | | Multiple domains, one per line or one comma-separated line. Without `ROUTING_MAP`, all of them go to `TARGET_ENDPOINT` |
175-
| `ROUTING_MAP` | | Multi-domain routing: `domain=host:port` per line. A wildcard entry (`*.example.com=host:port`) matches one label, and exact entries take precedence over it. Unmatched names go to the first entry |
176+
| `DOMAINS` | | Multiple domains, one per line |
177+
| `ROUTING_MAP` | | Multi-domain routing: `domain=host:port` per line |
176178
| `SET_CAA` | `false` | Enable CAA DNS record (dns-01 only; tls-alpn-01 cannot write DNS) |
177179
| `TXT_PREFIX` | `_dstack-app-address` | DNS TXT record prefix |
178-
| `ACME_EMAIL` | | ACME contact address, in either mode. `CERTBOT_EMAIL` is the historical name and still works. See [below](#the-acme-contact-address-is-optional-and-public) — it is optional, and published |
179180
| `ACME_STAGING` | `false` | Use Let's Encrypt staging, in either mode. `CERTBOT_STAGING` is the historical name and still works |
180-
| `ACME_DIRECTORY_URL` | | ACME directory of a test server such as Pebble, used instead of Let's Encrypt in either mode (CAA records always name `letsencrypt.org`, so other public CAs are not supported); takes precedence over `ACME_STAGING` |
181181
| `CHALLENGE_TYPE` | `dns-01` | `dns-01` (certbot + DNS credentials) or `tls-alpn-01` (lego, no DNS credentials) |
182-
| `DNS_PROVIDER` | detected | dns-01: `cloudflare`, `linode`, `namecheap` or `route53`. Detected from the provider's credential variable when unset; set it explicitly for `route53`, whose role setup depends on it |
183182
| `DNS_SETUP_MODE` | `wait` | How to handle operator-managed records: `wait`, `print` or `webhook` — see below. Applies to tls-alpn-01 and to dns-01 challenge delegation |
184183
| `DNS_SETUP_TIMEOUT` | `1800` | Seconds to wait for those records to appear |
185184
| `DNS_SETUP_INTERVAL` | `15` | Seconds between DNS checks |
186-
| `DNS_WEBHOOK_URL` | | `DNS_SETUP_MODE=webhook`: endpoint to notify |
185+
| `DNS_WEBHOOK_URL` | | tls-alpn-01 + `DNS_SETUP_MODE=webhook`: endpoint to notify |
187186
| `DNS_WEBHOOK_TOKEN` | | Shared secret; the payload is HMAC-SHA256 signed with it |
188-
| `DNS_WEBHOOK_TIMEOUT` | `15` | Seconds per webhook POST attempt |
189187
| `DOH_RESOLVERS` | Google + Cloudflare | Comma-separated DoH endpoints used to verify records |
190-
| `TLSALPN_ADDRESS` | `127.0.0.1` | Address lego's ACME responder binds to, and haproxy forwards `acme-tls/1` connections to |
191188
| `TLSALPN_PORT` | `9443` | Loopback port lego's ACME responder binds to |
192189
| `TLS_TERMINATE_PORT` | `9444` | Loopback port the TLS frontend moves to in tls-alpn-01 mode |
193190
| `RENEW_DAYS_BEFORE` | client default | Days of remaining lifetime that trigger renewal. Applies to both modes: passed to lego as `--renew-days`, and written to certbot's `renew_before_expiry`. Unsetting it removes that setting again, so the client's own default applies |
194-
| `DETERMINISTIC_TLS_KEY` | `false` | Derive a stable TLS key from the dstack KMS so clients can pin it; see [Deterministic TLS keys](#deterministic-tls-keys-spki-pinning) |
195191
| `RENEW_INTERVAL` | `43200` | Seconds between successful certificate passes |
196-
| `DNS_SETTLE_SECONDS` | `30` | tls-alpn-01: wait after DNS verifies, so the gateway's own TXT cache expires |
192+
| `DNS_SETTLE_SECONDS` | `30` | Wait after DNS verifies, so the gateway's own TXT cache expires |
197193
| `MAXCONN` | `4096` | HAProxy max connections |
198194
| `TIMEOUT_CONNECT` | `10s` | Backend connect timeout |
199195
| `TIMEOUT_CLIENT` | `86400s` | Client-side timeout (24h for long-lived connections) |
200196
| `TIMEOUT_SERVER` | `86400s` | Server-side timeout |
201-
| `EVIDENCE_SERVER` | `true` | Serve evidence files at `/evidences/` on the TLS port. Set `false` for backends whose server speaks first — see [Evidence & Attestation](#evidence--attestation) |
197+
| `EVIDENCE_SERVER` | `true` | Serve evidence files at `/evidences/` on the TLS port |
202198
| `EVIDENCE_PORT` | `80` | Internal port for evidence HTTP server |
203199
| `ALPN` | | TLS ALPN protocols (e.g. `h2,http/1.1`). Only set if backends support h2c |
204200
| `ACCEPT_PROXY_PROTOCOL` | `false` | Read the client's address from a PROXY protocol header (v1 or v2) on every connection to `PORT`, as the dstack gateway sends when the app's `port_policy` sets `pp` for it. A connection without one is refused. See [Client address](#client-address-proxy-protocol) |
@@ -303,82 +299,27 @@ protocol internally. The ACME responder never sees the header.
303299
If the gateway itself sits behind an L4 load balancer, the gateway operator must enable `inbound_pp_enabled` on it
304300
(and PROXY protocol on the load balancer), or the address passed on is the load balancer's.
305301

306-
## Deterministic TLS keys (SPKI pinning)
307-
308-
Set `DETERMINISTIC_TLS_KEY=true` to derive a P-256 TLS key per domain from the dstack
309-
`/GetKey` endpoint instead of generating a random one. The key depends only on the app's
310-
KMS-derived key and the domain, so every instance, restart, upgrade and certificate
311-
renewal serves the same public key, and clients can pin its SPKI. Works in both challenge
312-
modes; turning it on for an existing deployment re-issues the certificate with the
313-
derived key on the next pass.
314-
315-
The SPKI stays the same only as long as the app ID and the KMS do. It changes when the app
316-
is deployed under a new app ID, when it moves to a different KMS, or when it runs without
317-
a KMS (the local key provider ties keys to the host). There is no rotation: if the key has
318-
to be replaced, so do the pins. The derived key is not covered by the agent's signature
319-
chain; bind it to the app through the attested evidence instead.
320-
321-
In dns-01 mode certbot cannot keep a lineage for a key it did not generate, so these
322-
certificates live under `/etc/letsencrypt/deterministic/` and are renewed by the container
323-
at the same point certbot would (two thirds into the lifetime, or `RENEW_DAYS_BEFORE`),
324-
without ARI. In tls-alpn-01 mode lego renews them on its normal schedule.
325-
326302
## Evidence & Attestation
327303

328304
Evidence files are served at `https://your-domain.com/evidences/` by default (via payload inspection in HAProxy's TCP mode). They can also be accessed by the backend application through the shared `/evidences` volume.
329305

330306
To disable the built-in evidence endpoint and serve evidence files only through your backend, set `EVIDENCE_SERVER=false`.
331307

332-
The endpoint matches the first bytes of an HTTP/1.x request, so:
333-
334-
- With `ALPN` including `h2`, clients that negotiate HTTP/2 (curl's default) send their evidence requests to the
335-
backend instead. Use `curl --http1.1`, or serve `/evidences` from the backend too.
336-
- haproxy waits up to 5 seconds for a request that could start with `GET` or `HEAD`. A backend whose server speaks
337-
first (SMTP, MySQL, ...), or whose client's first message starts with `G` or `H` and is shorter than 16 bytes,
338-
sees that delay on every connection. Set `EVIDENCE_SERVER=false` for such backends.
339-
340308
### Evidence Files
341309

342310
| File | Description |
343311
|------|-------------|
344312
| `acme-account.json` | ACME account used to request certificates |
345313
| `cert-{domain}.pem` | Let's Encrypt certificate for each domain |
346314
| `sha256sum.txt` | SHA-256 checksums of all evidence files |
347-
| `quote.json` | TDX quote with `sha256sum.txt` digest in report_data (TDX only) |
348-
| `attestation.json` | dstack attestation (`/v1/Attest`) with the same report_data, on dstack 0.6+ on every platform |
315+
| `quote.json` | TDX quote with `sha256sum.txt` digest in report_data |
349316

350317
### Verification Chain
351318

352-
The attestation's 64-byte `report_data` is the SHA-256 of `sha256sum.txt` followed by 32 zero bytes, and
353-
`sha256sum.txt` lists `acme-account.json` and every `cert-<domain>.pem`. That is all it covers: no nonce, no
354-
timestamp, no TLS key, nothing about the connection. Anyone can fetch these files and relay them, so an
355-
attestation that matches the files only proves that *some* CVM published them. All of the following are needed:
356-
357-
1. **The attestation is genuine.** POST `attestation.json` (or `quote.json`) to
358-
[dstack-verifier](https://github.com/Dstack-TEE/dstack/tree/HEAD/dstack/verifier)'s `/verify`, or check a
359-
`quote.json` quote against Intel collateral with `dcap-qvl`. The verifier's `is_valid` must be `true`; take
360-
`report_data` from its `details.report_data`, not from the `report_data` field in `quote.json`, which the agent
361-
echoes back.
362-
2. **It is your app.** The verifier replays the event log into `details.app_info`; check that `app_id` and
363-
`compose_hash` there are the app you expect, and `os_image_hash` a known dstack OS image. A genuine attestation
364-
from someone else's CVM proves nothing about yours.
365-
3. **The files are the attested ones.** `sha256(sha256sum.txt)` is the first 32 bytes of `report_data`, and
366-
`sha256sum -c sha256sum.txt` passes.
367-
4. **The connection uses the attested certificate.** The leaf certificate served on your TLS connection is the
368-
first certificate in `cert-<domain>.pem` (compare fingerprints, or the SPKI hash to tolerate renewals with
369-
`DETERMINISTIC_TLS_KEY=true`). Otherwise a man in the middle can serve its own certificate and relay the real
370-
`/evidences`.
371-
5. **No one else can get a certificate.** The CAA records the container publishes for the domain (at the base
372-
name for a wildcard) pin `accounturi` to the account URI in `acme-account.json` — `.uri` for certbot,
373-
`.registration.uri` or `.registration.accountURL` for lego — and no other `issue`/`issuewild` record at that
374-
name allows another CA or account. The account key never leaves the CVM, so while these records are in place
375-
only the CVM can obtain a certificate for the domain, and step 4 holds for every client, not just the one that
376-
checked. A CAA lookup only shows the current state: whoever controls the DNS zone can remove the pin, get a
377-
certificate and put it back. Monitor Certificate Transparency logs (e.g. crt.sh) for certificates of the
378-
domain that are not in the evidence.
379-
Without the pin (`SET_CAA=false`, or tls-alpn-01 without the printed CAA record) anyone who can pass ACME
380-
validation for the domain — whoever controls its DNS or the route to it — can get a valid certificate, and
381-
the evidence cannot rule that out.
319+
1. Verify the TDX quote in `quote.json`
320+
2. Extract `report_data` — it contains the SHA-256 of `sha256sum.txt`
321+
3. Verify checksums in `sha256sum.txt` against `acme-account.json` and `cert-*.pem`
322+
4. This proves the certificates were obtained within the TEE
382323

383324
## Building
384325

@@ -555,27 +496,15 @@ Encrypt dropping expiry mail, and the container passes it for you.
555496
{
556497
"payload": "{\"app_id\":\"…\",\"challenge\":\"tls-alpn-01\",\"domain\":\"app.example.com\",\"instance_id\":\"…\",\"records\":[…],\"timestamp\":1234567890,\"version\":1}",
557498
"hmac_sha256": "…",
558-
"attestation": { "quote": "…", "event_log": "…", "attestation": "…", "report_data": "…" }
499+
"attestation": { "quote": "…", "report_data": "…" }
559500
}
560501
```
561502

562-
`attestation` holds the `GetQuote` response (TDX only) and, on dstack 0.6+, the
563-
`/v1/Attest` response's `attestation` field.
564-
565503
`payload` is a *string* so you sign and hash exactly the bytes you received.
566504
Verify `hmac_sha256` with `DNS_WEBHOOK_TOKEN`, and — since this request asks you
567-
to point a hostname at the instance it names — verify `attestation` too (dstack-verifier `/verify` takes it as is): its
568-
`report_data` is `sha256(payload)`, so it proves which enclave produced
505+
to point a hostname at the instance it names — verify `attestation` too: the
506+
quote's `report_data` is `sha256(payload)`, so it proves which enclave produced
569507
those records. Check the app ID and measurements in it before changing DNS.
570-
Take `report_data` from the verified result — `sha256(payload)` in its first
571-
32 bytes, then 32 zero bytes — not from `attestation.report_data`, which the
572-
container fills in itself.
573-
574-
Neither the HMAC nor the attestation expires, so a captured envelope stays valid forever; replaying an old one
575-
would point the hostname back at an instance that no longer serves it. The `timestamp` inside `payload` is covered
576-
by both, so use it: reject envelopes more than a few minutes old, and remember, per `domain`, the `timestamp` of
577-
the last one you applied. Reject anything older. A failed POST is retried with the identical envelope, so treat a
578-
byte-identical `payload` as a retry of the one already applied rather than a new request.
579508

580509
### Why lego and not certbot
581510

@@ -595,3 +524,10 @@ and renewal therefore never interrupt serving traffic. In this mode haproxy
595524
starts on a self-signed placeholder certificate — it has to be listening before
596525
the first certificate can be issued — and reloads onto the real one as soon as
597526
it arrives.
527+
528+
### Deterministic TLS keys (optional)
529+
530+
Set `DETERMINISTIC_TLS_KEY=true` to derive a stable P-256 TLS key per domain from the
531+
internal dstack agent `/GetKey` endpoint. The default is `false`; when unset, Certbot
532+
retains its normal key generation behavior. The derived key is used only to generate the
533+
CSR and is not represented by the agent's signature chain.

0 commit comments

Comments
 (0)