Let's Encrypt Without Port 80: DNS-01 Certificates for CapRover on a VPN-Only Host

Share

Let's Encrypt Without Port 80: DNS-01 Certificates for CapRover on a VPN-Only Host

TLS certificates have a failure mode that hides for two months. A host that issued its certificates the ordinary way keeps serving valid HTTPS long after the conditions that made issuance possible have gone away. Nothing looks wrong. The padlock is green, the apps load, and the expiry date is comfortably distant.

Then renewal runs, cannot reach the host, and gives up. If you are lucky you notice the browser warning a few days later. If you are not, you notice when a client complains.

This is the story of exactly that situation, and the fix that removes the dependency on inbound reachability completely: switching CapRover from the HTTP-01 challenge to DNS-01.

The problem with HTTP-01 on a private host

By default, CapRover issues certificates with certbot using the webroot authenticator. The command it runs is:

certbot certonly --webroot -w ${webroot} -d ${domainName}

That is the HTTP-01 challenge. To prove you control the domain, Let's Encrypt fetches a token from a path on your server:

http://<YOUR_DOMAIN>/.well-known/acme-challenge/<TOKEN>

The consequence is easy to state and easy to forget: HTTP-01 requires the certificate authority to open a connection to your host from the public internet. Every time, for every renewal.

That is fine on a public web server. It is fatal on a host you have deliberately put behind a VPN, and it fails for two independent reasons.

Reason one: the name resolves somewhere Let's Encrypt cannot reach

The application DNS records point at a private address:

$ dig +short captain.example.com
100.96.238.16

A 100.64.0.0/10 address is carrier-grade NAT space, used here by the VPN overlay. It is not routable from the public internet, so the challenge request has nowhere to go. This alone ends HTTP-01, before any firewall is involved.

Reason two: inbound traffic is dropped before it reaches the apps

The second reason is a pre-DNAT guard that drops new inbound connections on the public interface, so container ports published by the platform are not exposed to the internet:

$ sudo iptables -t mangle -L CAP-VPN-ONLY -n --line-numbers
Chain CAP-VPN-ONLY (1 references)
num  target     prot opt source               destination
1    RETURN     all  --  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
2    RETURN     udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:41641
3    RETURN     icmp --  0.0.0.0/0            0.0.0.0/0
4    DROP       all  --  0.0.0.0/0            0.0.0.0/0

Established connections and the VPN's own transport are permitted, ICMP is permitted, and everything else is dropped. Note the chain sits in the mangle table on the public interface, ahead of Docker's nat rules, so a permissive ufw allow 80 would change nothing. The challenge never gets that far.

Why the renewal config matters more than the firewall

Both reasons above are inbound problems, and it is tempting to conclude that temporarily opening port 80 fixes the renewal. On this host it would not, because the name does not resolve publicly either. You would have to move DNS back and open the port, then undo both.

There is also a detail that catches people out later. certbot records the authenticator it used inside each renewal configuration file:

$ sudo cat /captain/data/letencrypt/etc/renewal/captain.example.com.conf
[renewalparams]
account = f44c8edfd766a507b4986b6e8ed7cad3
authenticator = webroot
webroot_path = /captain-webroot/captain.example.com,
server = https://acme-v02.api.letsencrypt.org/directory

Changing the issuance method does not rewrite this line. An existing certificate keeps trying HTTP-01 on renewal even after you have configured something else, which is the reason for the forced re-issue step later in this guide.

What DNS-01 changes

The DNS-01 challenge proves domain control through the DNS zone instead of through your web server. Let's Encrypt asks the ACME client to create a TXT record:

_acme-challenge.<YOUR_DOMAIN>  TXT  "<token>"

The authority then queries DNS for that record. If it matches, you get a certificate.

The properties that matter for a private host:

  • No inbound connection is required. Your host only needs outbound access to the ACME API and to your DNS provider's API.
  • It works when the name does not resolve publicly at all, which is the exact case that breaks HTTP-01.
  • Wildcards are possible, which HTTP-01 cannot do.
  • The renewal keeps working after every unrelated hardening change you make, because nothing about it depends on reachability.

For a host behind a VPN, that is the whole argument. DNS-01 is not a workaround here. It is the only challenge type that matches how the host is deployed.

Prerequisites

Four things before you start:

  • CapRover 1.12.0 or newer, since the certbot override feature arrived in that release. This guide was worked through on 1.15.4.
  • Your DNS hosted somewhere with an API and a certbot plugin. Cloudflare is used here, which has both.
  • A DNS API token scoped to editing records in the one zone you need. Not a global key.
  • A maintenance window of a few minutes. The apps stay up, but the platform service is replaced once.

Step 1: Build a certbot image that carries the DNS plugin

The image CapRover ships does not include third-party certbot plugins, so the default one cannot talk to Cloudflare. You build a tagged copy on top of the DNS-enabled image:

FROM certbot/dns-cloudflare:v2.11.0
ENTRYPOINT ["/bin/sh", "-c"]
CMD ["sleep 9999d"]

Two things about that file are load-bearing.

The base tag should match the certbot version the platform itself runs, so the renewal behaviour and configuration format stay consistent. Check what that is before choosing:

$ sudo docker service inspect captain-certbot --format '{{.Spec.TaskTemplate.ContainerSpec.Image}}'
caprover/certbot-sleeping:v2.11.0

The entrypoint and command reproduce the "sleeping container" pattern CapRover expects, because it executes certbot inside a long-running container rather than starting one per issuance.

Build it with an empty context so Docker does not upload a directory tree:

$ mkdir -p /tmp/certbot-build && cd /tmp/certbot-build
$ cat > Dockerfile <<'EOF'
FROM certbot/dns-cloudflare:v2.11.0
ENTRYPOINT ["/bin/sh", "-c"]
CMD ["sleep 9999d"]
EOF
$ sudo docker build -t certbot-customized .

Then verify the plugin is really inside the image, rather than trusting the tag:

$ sudo docker run --rm --entrypoint certbot certbot-customized plugins
* dns-cloudflare
Description: Obtain certificates using a DNS TXT record (if you are using
Cloudflare for DNS).
Interfaces: Authenticator, Plugin

If dns-cloudflare does not appear in that list, stop here. Everything downstream depends on it.

Step 2: Store the API credentials

The plugin reads an INI file. Create the directory certbot expects and write the token into it:

# Cloudflare API token used by Certbot
dns_cloudflare_api_token = <your-scoped-token>
$ sudo mkdir -p /captain/data/letencrypt/etc/captain-files
$ sudo install -m 600 -o root -g root /path/to/token.ini \
    /captain/data/letencrypt/etc/captain-files/mycreds.ini

Two notes on that path. The directory is spelled letencrypt, not letsencrypt, which is CapRover's own naming and easy to get wrong. And the path is the host side of a volume: the container sees the same file as /etc/letsencrypt/captain-files/mycreds.ini, which is what the command in the next step references.

Permissions are not cosmetic here. certbot refuses to use a credentials file that other users can read, and the message it gives is easy to skim past:

Unsafe permissions on credentials configuration file

Keep the token scoped. A token with Zone:DNS:Edit limited to the single zone is enough, and it cannot be used to change anything else in the account. Verify that before wiring it in, so a bad paste fails now rather than halfway through an issuance:

$ curl -s -H "Authorization: Bearer $TOKEN" \
    https://api.cloudflare.com/client/v4/user/tokens/verify
{"result":{"id":"...","status":"active"},"success":true,...}

Step 3: Override CapRover's certbot command

CapRover reads an override file from the data directory, which lets you replace the certbot image and command without patching anything:

{
  "skipVerifyingDomains": "true",
  "certbotImageName": "certbot-customized",
  "certbotCertCommandRules": [
    {
      "domain": "*",
      "command": "certbot certonly --dns-cloudflare --dns-cloudflare-credentials /etc/letsencrypt/captain-files/mycreds.ini -d ${domainName}"
    }
  ]
}

Install it and check the JSON parses before restarting anything:

$ sudo install -m 600 -o root -g root config-override.json /captain/data/config-override.json
$ sudo python3 -c "import json;json.load(open('/captain/data/config-override.json'));print('valid JSON')"
valid JSON

Each key is there for a reason.

certbotImageName points at the image you built. On a single-node swarm the locally built image resolves without a registry, which is worth knowing because the platform also has a private registry feature that is not required for this.

certbotCertCommandRules replaces the issuance command. The domain field matches a specific name, *.<domain> for a subdomain, or * for everything. ${domainName} and ${subdomain} are substituted by CapRover.

skipVerifyingDomains is the one people miss. CapRover normally checks that the domain resolves publicly before attempting issuance. Your names deliberately do not, so leaving this at its default makes the platform refuse to try. Setting it to true is not a shortcut around validation; validation is still performed by Let's Encrypt through the DNS challenge. It only skips the platform's own pre-flight check, which is calibrated for publicly reachable hosts.

Step 4: Restart the platform and confirm the override loaded

The override is read at startup, so the service has to be replaced:

$ sudo docker service update --force --detach=false captain-captain
verify: Service captain-captain converged

Then confirm it actually took effect, rather than assuming. CapRover logs every key it overrides:

$ sudo docker service logs --since 5m captain-captain | grep -i overrid
Overriding skipVerifyingDomains from /captain/data/config-override.json
Overriding certbotImageName from /captain/data/config-override.json
Overriding certbotCertCommandRules from /captain/data/config-override.json

Those three lines are your proof that the change is live. If they are absent, the file is in the wrong place or malformed, and nothing you do later will use DNS-01.

You should also see the platform replace its certbot service with your image. On a single-node swarm it does this itself:

$ sudo docker service inspect captain-certbot --format '{{.Spec.TaskTemplate.ContainerSpec.Image}}'
certbot-customized

While it swaps, the log may show Retrying to get containerId for captain-certbot several times. That is the platform waiting for the new task to come up, not a failure. Confirm the service converged before moving on.

Step 5: Prove the path works before you commit to it

You now have a configuration you believe in and no certificate issued with it. Test the whole chain against Let's Encrypt's staging environment first, which has its own rate limits and cannot affect your production certificates.

The trick that makes this genuinely safe is --config-dir. Point it at a scratch directory instead of the real one, and nothing can touch your live state even if the command misbehaves:

$ sudo docker run --rm \
    -v /tmp/certbot-dryrun:/etc/letsencrypt \
    -v /captain/data/letencrypt/etc/captain-files:/captain-files:ro \
    --entrypoint certbot \
    certbot-customized \
    certonly \
      --dns-cloudflare \
      --dns-cloudflare-credentials /captain-files/mycreds.ini \
      -d dns01-test.example.com \
      --dry-run \
      --non-interactive \
      --agree-tos \
      --register-unsafely-without-email \
      --config-dir /etc/letsencrypt \
      --work-dir /tmp/work \
      --logs-dir /tmp/logs
Account registered.
Simulating a certificate request for dns01-test.example.com
Waiting 10 seconds for DNS changes to propagate
The dry run was successful.

That single run exercises the plugin, the token, the zone permissions, outbound API access, and the DNS propagation wait. The Waiting 10 seconds for DNS changes to propagate line is the plugin's default and is normally enough for Cloudflare.

If this succeeds, the remaining risk is small. If it fails, you have learned it before any certificate was replaced.

Step 6: Issue for real, once, and understand why it must be forced

Here is the part that is easy to get wrong. After switching to DNS-01, the existing certificates will still renew over HTTP-01, because each one carries its original authenticator in its renewal configuration. Configure the platform, wait until the certificates come due, and renewal fails exactly as it did before.

Each certificate has to be issued once through DNS-01 so certbot rewrites that record. Because the certificates are usually not yet due, the issuance has to be forced:

$ sudo docker exec <certbot-container> certbot certonly \
    --dns-cloudflare \
    --dns-cloudflare-credentials /etc/letsencrypt/captain-files/mycreds.ini \
    -d captain.example.com \
    --force-renewal \
    --non-interactive

Then check the file that actually matters, not the certificate:

$ sudo grep '^authenticator' /captain/data/letencrypt/etc/renewal/captain.example.com.conf
authenticator = dns-cloudflare

Stage it: do one domain, confirm the authenticator flipped, then do the rest. The command above is identical to what CapRover would run, minus the platform's own bookkeeping, so you are not creating a divergent path.

Once the certificates are reissued, reload the web tier. Validate the configuration first so a typo does not take the front end down:

$ sudo docker exec <nginx-container> nginx -t
$ sudo docker exec <nginx-container> nginx -s reload

Note that the reload is what makes the new certificates visible. Issuing alone updates the files on disk and leaves the running server serving the old certificate from memory, which is a useful property: you can verify the new certificate before anything user-facing changes.

Step 7: Verify that renewal will actually work

The real test is not that you have fresh certificates today. It is that the renewal path succeeds unattended, months from now, with the same conditions. certbot has a mode for exactly this:

$ sudo docker exec <certbot-container> certbot renew --dry-run --non-interactive
Simulating renewal of an existing certificate for captain.example.com
Waiting 10 seconds for DNS changes to propagate
Simulating renewal of an existing certificate for fresh.example.com
Waiting 10 seconds for DNS changes to propagate
...
Congratulations, all simulated renewals succeeded:
  /etc/letsencrypt/live/captain.example.com/fullchain.pem (success)
  /etc/letsencrypt/live/fresh.example.com/fullchain.pem (success)
  /etc/letsencrypt/live/guac.example.com/fullchain.pem (success)
  /etc/letsencrypt/live/min.example.com/fullchain.pem (success)

This walks every renewal configuration, reads its recorded authenticator, and performs a staging issuance for each. A pass here means the unattended renewal will pass.

Then confirm the served state matches the files on disk, which catches the case where issuance worked but the reload did not:

$ for d in captain fresh guac; do
    got=$(echo | openssl s_client -connect 10.0.0.1:443 -servername $d.example.com 2>/dev/null \
          | openssl x509 -noout -fingerprint -sha256 | sed 's/.*=//')
    ondisk=$(sudo openssl x509 -in /captain/data/letencrypt/etc/live/$d.example.com/cert.pem \
             -noout -fingerprint -sha256 | sed 's/.*=//')
    [ "$got" = "$ondisk" ] && echo "$d: served == on-disk" || echo "$d: MISMATCH"
  done

One caveat if you have an app name with a certificate but no configured vhost. Its SNI will be answered by the default certificate, so the comparison above reports a mismatch for that name even though the certificate on disk is valid. That is a routing gap to fix separately, not a symptom of this change.

Traps that cost real time

None of these are specific to DNS-01, and all of them produced a confident wrong answer at some point during this work.

A docker ps name filter matches more than you expect. docker ps -qf name=captain returns captain-certbot as a match, because the filter is a substring and that container exists. Commands intended for the platform container silently ran somewhere else. If your certificates live in a volume, they are not in the application container at all. Read them from the host path, or target the exact service:

$ sudo docker ps -qf name=captain
c1c2da7acd5a   # this is captain-certbot, not captain-captain

sudo cmd > file gives the redirection to your own shell. The command runs as root, the redirect does not, so writing a backup into a root-only directory fails with Permission denied while the command itself looks like it worked. Wrap the whole thing:

$ sudo sh -c "docker service inspect captain-certbot > /root/backup/spec.json"

A failed grep is not evidence of absence. Searching the renewal directory with a pattern that returned nothing temporarily suggested the configs held no authenticator line at all. Reading the file directly showed authenticator = webroot in plain sight. The pipeline was broken, not the data. When a search over a known-populated set returns nothing, suspect the search first.

A connection failure immediately after a service restart is usually the restart. Checks run during the window where the platform is regenerating front-end configuration return connection errors that look identical to a misconfiguration. Wait for the service to converge and re-run them before concluding anything. The first round of checks in this work reported a total failure and the second reported everything healthy, with no change in between.

Why not just use Origin certificates

If your DNS is on Cloudflare, it is tempting to skip ACME entirely and use a long-lived Cloudflare Origin certificate. On a VPN-only host this does not work, and the reason is worth being explicit about.

Origin certificates are trusted by Cloudflare's edge, not by browsers. They exist for the case where Cloudflare terminates TLS for visitors and talks to your origin over a connection only Cloudflare can see. If clients connect to your host directly, which is exactly what happens when the addresses are private, browsers have no reason to trust that chain. DNS-01 with a publicly trusted authority remains the correct answer.

What you end up with

After this change, certificate renewal has no dependency on inbound reachability at all. The host talks outward to the ACME API and to your DNS provider, proves control through a TXT record, and receives a certificate. Nothing is listening publicly, no port is opened temporarily, and no manual step is required at renewal time.

That last part is the real gain. The previous arrangement worked, in the sense that certificates could be issued, but it worked by temporarily reversing the security posture of the host. Every renewal was an opportunity to forget to close something, and the failure was silent until it was user-visible.

For reference, the authoritative sources for the pieces used here are CapRover's certbot overrides documentation, Let's Encrypt's challenge types, and the certbot DNS plugin documentation. The behaviour of the platform's renewal path, which is what makes the forced re-issue necessary, is not documented and had to be read out of the running system.

## Convertkit Newsletter