certmagic: Corrupted metadata JSON files caused by bug #297

The bug #297 frequently leads to corrupted JSON files when multiple instances mount a shared NFS directory as storage. We’ve encountered numerous cases in production where this causes certificate failures with the error message decoding certificate metadata: invalid character '}' after top-level value, rendering the affected sites completely unusable.

The number of corrupted files is increasing, and I can’t restart the service.

I see the bug fix is in the master branch. Please release a new version that includes this fix. Additionally, how can I identify and repair the already corrupted files among thousands without deleting all files? Alternatively, is there a way to ignore corrupted files during loading?

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 46 (21 by maintainers)

Most upvoted comments

The internal rate limits are pretty generous now, I think it’s 1 per second.

To be exact, 10 per 10 seconds, but effectively the same.

I spent about a dozen hours debugging this yesterday, and I believe my initial comment was incorrect: rather than the bug persisting, I believe I just hadn’t sufficiently cleaned all of the existing corrupt files. There were situations in which there were two trailing bytes at the end of a file (\n}), and my cleanup script didn’t account for that.

I am using NFS, but it does appear to support locking correctly with my current mount options–or, at least, in a way that is compatible with this patch. I’m not a huge fan of NFS and generally don’t trust it, but it should work with this lock/write pattern. I doubt it would ever make sense to officially support NFS given how fickle it is, but the locking code in certmagic is straightforward enough that I should be able to debug and patch it if there are further issues.

The one thing that still has me a little worried is a disconcerting number of requests to the on-demand ask endpoint. The docs make it sound as though that’s to be expected, but it’s accompanied by a large number of log entries related to ARI. I don’t think it’s a bug–it’s probably just a coincidence–but I happened to notice it while troubleshooting.

Catching up after the weekend…

If I’m not mistaken, Let’s Encrypt’s rate limiting is much stricter for requests that fail DV–that is, you’re likely to run into rate limiting if you’re requesting a lot of certs and not doing DNS checks on your own.

Somewhat. From Let’s Encrypt Rate Limits:

There is a Failed Validation limit of 5 failures per account, per hostname, per hour.

Note that it’s per account, per hostname, (and per hour). So, kind of, but if one person’s domain fails to verify, that won’t block others.

I’ve since confirmed this: the ask endpoint won’t receive a request. … I knew there were likely multiple issues, which is why debugging was so complicated. I do think the PR here resolves https://github.com/caddyserver/certmagic/issues/303, although it doesn’t fix the already-broken metadata. My only complaint was that the design decisions surrounding ask made it difficult to gain introspection into Caddy’s logic and determine what was actually happening. In an ideal world without any bugs, the behavior wouldn’t really matter.

Thanks so much for investigating this! And thanks for the follow-up. I’ll see if we can make things clearer.

@bracketforward Good questions.

at what point does the CA decide that too many are failing and that the provider should be taking proactive steps to reduce those failures? What are the consequences of that CA’s decision on hosting providers?

I think Let’s Encrypt’s rate limits are a good example of this. They have many rate limits, and if you reach them, you could take steps to reduce those failures. On the other hand, they exist to prevent excessive use of resources, so hitting them isn’t “bad” per-se, especially when the domain is truly misconfigured (i.e. trying again won’t help). The only time it’s not good is when it’s a “false positive” like if DNS records have been set but haven’t propagated yet (it’s not really a “false positive” either, I just don’t know a better term).

I’ve seen LE staff reach out to integrators that are having notable difficulty. But it’s always been reasonable IMO.

My browser is crashing so I’ll brb to finish this.

what if there are thousands of domains with this issue being visited daily? That’s entirely plausible for a medium-sized provider.

The internal rate limits are pretty generous now, I think it’s 1 per second.

The main thing is the CA sets their rate limits, we just want to avoid slamming CAs with thousands of requests per minute.

@Zenexer

Changing the log level for no information found to solve challenge for identifier to info or debug would be my best recommendation. Adding it to the docs would also help, since it’s probably not clear what it means to anyone who isn’t familiar with ACME.

That’s not a bad idea. Maybe DEBUG.

I don’t think it makes sense to query the ask endpoint prior to checking storage. Requests to /.well-known/acme-challenge/* go directly to storage anyway, so it has to be fast.

We have specifically had requests – from large integrators – to gate this behind the ask endpoint. It is fast, but it’s expensive. The well-known lookups are a good point, though I haven’t had complaints about that yet (other than, in a way, this thread, I suppose).

We’ve discussed this a lot in the past, including with Let’s Encrypt themselves, and with their community, and the overall consensus seems to be that because DNS is a matter of perspective, doing the lookup yourself is seldom helpful. And we’ve seen from experience (with the lego project, before we diverted from it) that doing DNS lookups oneself got in the way more often than it helped.

If I’m not mistaken, Let’s Encrypt’s rate limiting is much stricter for requests that fail DV–that is, you’re likely to run into rate limiting if you’re requesting a lot of certs and not doing DNS checks on your own.

It checks storage for a challenge token, not for a certificate. This flow has nothing to do with On-Demand TLS.

I’ve since confirmed this: the ask endpoint won’t receive a request.

I think a self-contained example would be helpful here. It should go without saying, but to anyone coming across this discussion: this example does not use best practices; it’s intended to demonstrate a particular issue with minimal code. Do not use this in production.

Caddyfile
{
	email invalid@invalid.invalid
	acme_ca https://acme-staging-v02.api.letsencrypt.org/directory
	default_sni invalid
	on_demand_tls {
		ask http://127.0.0.1:8002/ask
	}
}

http://127.0.0.1:8002 {
	log
	route /ask {
		@known query domain=known.example
		respond @known 200
		respond 400
	}
}

http:// {
	log
}

https:// {
	log
	tls {
		on_demand
	}
}
docker-compose.yml
services:
  caddy:
    image: "library/caddy:latest"
    ports:
      - "127.0.0.1:8080:80"
      - "127.0.0.1:8443:443"
      - "127.0.0.1:8443:443/udp"
    volumes:
      - "./Caddyfile:/etc/caddy/Caddyfile"

In my use case, I’m getting a lot of requests to /.well-known/acme-challenge/* from various CAs and vulnerability scanners. Neither Caddy nor anything else in my infrastructure was trying to get a certificate, so Caddy doesn’t have any challenge data.

Command:

% curl -sv --connect-to unknown.example:80:127.0.0.1:8080 http://unknown.example/.well-known/acme-challenge/foobar
* Connecting to hostname: 127.0.0.1
* Connecting to port: 8080
*   Trying 127.0.0.1:8080...
* Connected to 127.0.0.1 (127.0.0.1) port 8080
> GET /.well-known/acme-challenge/foobar HTTP/1.1
> Host: unknown.example
> User-Agent: curl/8.7.1
> Accept: */*
>
* Request completely sent off
< HTTP/1.1 308 Permanent Redirect
< Connection: close
< Location: https://unknown.example/.well-known/acme-challenge/foobar
< Server: Caddy
< Date: Sat, 28 Sep 2024 16:15:44 GMT
< Content-Length: 0
<
* Closing connection

Caddy logs:

% docker compose logs -fn0 caddy
caddy-1  | {"level":"warn","ts":1727540193.833114,"logger":"http","msg":"looking up info for HTTP challenge","host":"unknown.example","remote_addr":"172.19.0.1:56906","user_agent":"curl/8.7.1","error":"no information found to solve challenge for identifier: unknown.example"}
caddy-1  | {"level":"info","ts":1727540193.8339462,"logger":"http.log.access","msg":"handled request","request":{"remote_ip":"172.19.0.1","remote_port":"56906","client_ip":"172.19.0.1","proto":"HTTP/1.1","method":"GET","host":"unknown.example","uri":"/.well-known/acme-challenge/foobar","headers":{"User-Agent":["curl/8.7.1"],"Accept":["*/*"]}},"bytes_read":0,"user_id":"","duration":0.002686333,"size":0,"status":308,"resp_headers":{"Server":["Caddy"],"Connection":["close"],"Location":["https://unknown.example/.well-known/acme-challenge/foobar"],"Content-Type":[]}}

For comparison, curl -sv --connect-to unknown.example:443:127.0.0.1:8443 https://unknown.example/ will show a query to the ask endpoint, as will curl -sv --connect-to known.example:443:127.0.0.1:8443 https://known.example/. The former will end with a TLS alert, while the latter will try to get a cert from LE’s staging endpoint.

The most notable log message here is "error":"no information found to solve challenge for identifier: unknown.example". That’s emitted even without the log directive. While trying to debug #303, I didn’t really have any way of determining whether these were the result of concurrency issues, storage issues, or third-parties making bogus requests to /.well-known/acme-challenge/. It turned out to be mostly the latter.

As you pointed out, ask isn’t consulted in this scenario–on-demand TLS doesn’t come into play. I wasn’t certain of that at the time.

In my case, there were a combination of issues:

  1. My underlying storage was flaky. I was using NFS, which should be fine here, but I had incorrect mount options that were preventing locking from working correctly.
  2. Because storage was flaky, a small percentage of these error messages were the result of legitimate ACME attempts, but Caddy just couldn’t see the challenge token in storage yet.
  3. Even with that resolved, #303 meant that locking wasn’t working correctly.
  4. Even with the fix for #303 applied, there was a lot of corrupt metadata JSON still sitting around.
  5. Caddy was sending a lot of requests to the ask endpoint because certificates weren’t being synchronized. There seemed to be a correlation between the no information found to solve challenge error messages and the ask endpoint requests. This was probably a coincidence.

I knew there were likely multiple issues, which is why debugging was so complicated.

I do think the PR here resolves #303, although it doesn’t fix the already-broken metadata. My only complaint was that the design decisions surrounding ask made it difficult to gain introspection into Caddy’s logic and determine what was actually happening. In an ideal world without any bugs, the behavior wouldn’t really matter.

@aaomidi

There is no external database to check in this circumstance. There is no UI. There is no app. The database is DNS.

I just want to reiterate. This is not okay to do. The problem is that any bad actor can point a wildcard domain to your server and then infinitely make requests like a.badguy.com then b.badguy.com to infinity, making your server issue a cert per domain, resulting in a DDOS (rate limits getting hit, or storage exhaustion). That why you must have an allow-list, you cannot trust DNS because it’s not under your control.

@Zenexer

By “wasting PKI resources,” I’m referring to the fact that DV isn’t free, especially at scale. There’s an expectation that integrators should make a reasonable effort to ensure a domain actually points to them (and that an ACME challenge will succeed) prior to trying to get a cert.

Caddy’s internal rate limiting should prevent that from being a concern. It slows itself down if too many attempts are happening.

If I follow the instructions in the docs and stop performing DNS checks, then I become Hosting Provider A in my example, and I will get rate limited.

No, because only a TLS handshake that actually reaches your server (meaning the DNS is already configured correctly) can trigger On-Demand TLS. Any domain which doesn’t point to your server will not renew when the time comes because only a TLS handshake would trigger a renewal attempt.

I’ve never seen any evidence of the usecase you’re describing being a real issue.

This should only be negatively affecting them (and I guess the CAs, which is why they rate limit them). If they initiate an ACME challenge for a domain pointed to you, you will see junk log entries at most. Or what wasted PKI resources are you referring to?

To be clear, the only reason I’m bringing up any of this is because it’s made debugging this concurrency issue difficult. If everything worked perfectly as described all the time, it would just be a matter of ignoring the logs–the same as I was already doing.

It’s only a problem because I can’t tell which log entries and ask requests are a result of my Caddy instances trying to get certs (or encountering concurrency issues), versus which log entries are from someone else’s lazy misuse of ACME.

By “wasting PKI resources,” I’m referring to the fact that DV isn’t free, especially at scale. There’s an expectation that integrators should make a reasonable effort to ensure a domain actually points to them (and that an ACME challenge will succeed) prior to trying to get a cert.

I should have mentioned that this is what I was referring to that is a bit unconventional. Typically, users sign up with their domain name(s) they are going to use, then your service knows what the domains are. If setting DNS records is itself the act of “signing up” with your service, then it makes sense that you have to check DNS records. This is the only time I have heard of this being the case… and for a few reasons (complexity, reliability, etc) I don’t recommend this… unless, perhaps, you do like what our Caddy homepage demo does, where a user can point a specific subdomain (“caddydemo” in our case) to your IP, and then no signup is required. This still prevents abuse because it only works for one specific identifier per registered domain, hence there’s a relatively significant cost barrier to abuse it.

I think we’re getting a bit caught up with my specific use case, which isn’t too relevant here. Let’s use the example I provided in a recent comment with two hosting providers.

To clarify once more, if someone else initiates an ACME challenge for a hostname that fails repeatedly, that doesn’t rate limit you. It only rate limits their ACME account, not yours.

Correct. I’m not being rate limited and am not proposing that as a concern.

If I follow the instructions in the docs and stop performing DNS checks, then I become Hosting Provider A in my example, and I will get rate limited.

Ah, I think I see where the confusion is. What I said here is true, and doesn’t preclude what I said earlier. ‘Ask’ is consulted before checking to see if storage has a certificate to satisfy the TLS handshake (I’m talking about normal handshakes here, not TLS-ALPN-01 challenge handshakes which use only a very specific, minimal code path). If ‘ask’ returns 200, storage is checked. If storage returns no cert, then an ACME challenge is initiated to obtain one. Does that make sense?

Yes, that was my initial impression. That design strongly disincentivizes ask endpoints from performing sufficient checks. That leads to an ecosystem problem as Caddy becomes more popular.

It invites Caddy users to put themselves in the position of Hosting Provider A above.

Just catching up after feeding the baby and running some kids around… sorry!

I’ve been drafting this reply while several new replies have come in – I wish GitHub would show that someone was replying or at least show the new replies. I feel like the conversation went off-track and got confused by some things, but maybe I did instead. In any case, here’s my attempt to bring it back:

@Zenexer

Thanks for clarifying above. It seems to me you have an extraordinary situation that is not common from what I know of existing large-scale CertMagic deployments. That’s not bad, just something that is worthy of discussion/understanding.

Scenario 1: I control example.com. Large hosting provider used to control example.com, and they used to have certificates for it. They keep trying to renew those certificates.

So, in this case, the hosting provider would fail their own ACME challenge, but your server would likely get pinged with a TLS handshake or HTTP request in an attempt to solve the challenge.

The HTTP-01 challenge does not use TLS, so those would not issue a certificate. You’d see junk in your logs, but what’s new (it’s the Internet).

The TLS-ALPN-01 challenge does use TLS, but with a special ALPN value. When it sees a handshake of this sort, it only follows a special code path that serves the challenge solution certificate (if it doesn’t find one it just returns an error and aborts the handshake).

Neither case will initiate an ACME challenge that you end up failing and getting rate limited for. (If they are, that’s a bug I’d like more details, likely in a separate issue.)

Scenario 2: I control example.com. Someone runs Acunetix against example.com. For whatever reason, it starts brute forcing random paths with a prefix of /.well-known/acme-challenge/–for example, /.well-known/acme-challenge/xmlrpc.php. I want certificates for example.com, so the ask endpoint returns 200.

@aaomidi

I think to simplify this, what @Zenexer is stating is that a third party actor can initiate a request to /.well-known/acme-challenge/$token - and caddy will hit the ask endpoint even if caddy knows that the challenge is bogus, or the challenge is real but caddy can’t solve it (e.g, it was a token that caddy does not know about).

The ask endpoint is only invoked if the client tries to establish a TLS handshake using a domain name it does not have a certificate for (and isn’t itself a challenge handshake). But this endpoint is for the HTTP-01 challenge, which is HTTP-only. Are the servers accessing this plaintext endpoint over HTTPS? That would be the only way this is possible, but is extremely broken / in violation of spec.

@Zenexer’s use case allows people to point their domains to their infrastructure without any registration, etc.

From what I’m understanding, there is no registration or direct user involvement. The only involvement is going to DNS and changing name servers or A records.

@Zenexer What you should do is have your customers register their domain via your app’s settings, and you add it to your DB allow list. Then all the ask endpoint does is compare against that list. That’s how it’s meant to work.

It sounds like your ask endpoint needs to check to make sure you are expecting to be getting a certificate for those domain names.

It already does that. I am expecting to get certificates for those domains.

Scenario 1: I control example.com. Large hosting provider used to control example.com, and they used to have certificates for it. They keep trying to renew those certificates. My ask endpoint needs to return 200, because I need certificates.

Scenario 2: I control example.com. Someone runs Acunetix against example.com. For whatever reason, it starts brute forcing random paths with a prefix of /.well-known/acme-challenge/–for example, /.well-known/acme-challenge/xmlrpc.php. I want certificates for example.com, so the ask endpoint returns 200.

Not exactly; why not check your database (or whatever is relevant to your application/service) to see if you should be expecting to maintain a certificate for a hostname? That’s the purpose of the ask endpoint and it should resolve the rate limit problems, yeah?

I do. However, I’m running a free service to which non-technical users can point their domains. They might use my service for a while, decide they don’t like it, and point their domain elsewhere. I can’t trust that the users are going to maintain a list of domains that point to me, so I do have to validate the A/AAAA records before requesting a certificate. The result gets cached in Redis for a while, so subsequent calls to the ask endpoint are very fast.

To make sure I understand, you want a way for the ‘ask’ request to distinguish whether a certificate is being obtained or something else?

Yes, mostly for debugging purposes. If I see that multiple Caddy instances are all trying to get certs at the same time, that’s a sign something is amiss. It would likely help when troubleshooting future concurrency issues, but a lightweight plugin could probably serve the same purpose.

I’m still not 100% confident the remaining errors I’m seeing are benign, but I’ll have more data over the next few days.

I’m not seeing any overlap between ARI requests so far. Each one is unique.

If you’re in a hurry, you can make a build yourself with this:

xcaddy build --with github.com/caddyserver/certmagic@16e2e0b