rewrite: clean paths before regexp replacement changes depth

Canonicalize the path before capturing and substituting its components, not only afterward. Retain repeated slashes, query strings and valid alternate encodings; cover the supplied depth-changing traversal and encoded dot segments.

Addresses scan report 34013c71-0786-4179-8403-eacc143a1d89 (marked duplicate, but not fixed by the prior post-replacement safeguard).

Code written by GitHub Copilot (GPT-6.1 Sol, Claude Opus 5.5); reviewed by mholt.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Matthew Holt 2026-11-10 19:00:30 -07:00
parent 9461da6583
commit 7593fd002f
2 changed files with 42 additions and 0 deletions

View file

@ -95,6 +95,7 @@ type Rewrite struct {
URISubstring []substrReplacer `json:"uri_substring,omitempty"`
// Performs regular expression replacements on the URI path.
// Dot segments are cleaned before matching and after replacement.
PathRegexp []*regexReplacer `json:"path_regexp,omitempty"`
// Mutates the query string of the URI.
@ -607,6 +608,9 @@ func (rep regexReplacer) do(r *http.Request, repl *caddy.Replacer) {
return
}
replace := repl.ReplaceAll(rep.Replace, "")
// Match the same cleaned path that path guards and filesystem handlers use,
// before a replacement can change the depth at which dot segments resolve.
canonicalizePath(r)
oldPath := r.URL.Path
changePath(r, func(pathOrRawPath string) string {
return rep.re.ReplaceAllString(pathOrRawPath, replace)

View file

@ -0,0 +1,38 @@
package rewrite
import (
"net/http"
"regexp"
"testing"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
func TestRegexpRewriteCleansBeforeChangingDepth(t *testing.T) {
const find = `^/public/preserved/(.*)$`
rewr := Rewrite{PathRegexp: []*regexReplacer{
{Find: find, Replace: "/allowed/$1", re: regexp.MustCompile(find)},
}}
for _, tc := range []struct {
target, want string
}{
{"/public/preserved/public.txt", "/allowed/public.txt"},
{"/public/preserved/a/b/../../../secret.txt", "/public/secret.txt"},
{"/public/preserved/a/b/%2e%2e/%2e%2e/%2e%2e/secret.txt", "/public/secret.txt"},
{"/public/preserved/a/../public.txt", "/allowed/public.txt"},
{"/public/preserved/a%2Fb", "/allowed/a%2Fb"},
{"/public/preserved/a//b", "/allowed/a//b"},
{"/public/preserved/%252e%252e/secret.txt", "/allowed/%252e%252e/secret.txt"},
} {
t.Run(tc.target, func(t *testing.T) {
req := newRequest(t, http.MethodGet, tc.target+"?keep=yes")
repl := caddy.NewReplacer()
req = caddyhttp.PrepareRequest(req, repl, nil, nil)
rewr.Rewrite(req, repl)
if got := req.URL.RequestURI(); got != tc.want+"?keep=yes" {
t.Fatalf("rewritten target = %q, want %q", got, tc.want+"?keep=yes")
}
})
}
}