fastcgi: keep the php_fastcgi directory redirect on the same origin (#8285)

* fastcgi: keep the php_fastcgi directory redirect on the same origin
* fastcgi: build the directory redirect from the escaped original segment
This commit is contained in:
sam-kota 2026-10-28 15:15:37 +05:30 committed by GitHub
parent fead9c3f24
commit 32bba15459
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 101 additions and 7 deletions

View file

@ -8,7 +8,7 @@ route {
}
not path */
}
redir @canonicalPath {orig_path}/{orig_?query} 308
redir @canonicalPath ./{http.request.orig_uri.path.file_escaped}/{orig_?query} 308
# If the requested file does not exist, try index files
@indexFiles {
@ -50,7 +50,7 @@ route {
"handler": "static_response",
"headers": {
"Location": [
"{http.request.orig_uri.path}/{http.request.orig_uri.prefixed_query}"
"./{http.request.orig_uri.path.file_escaped}/{http.request.orig_uri.prefixed_query}"
]
},
"status_code": 308

View file

@ -42,7 +42,7 @@
"handler": "static_response",
"headers": {
"Location": [
"{http.request.orig_uri.path}/{http.request.orig_uri.prefixed_query}"
"./{http.request.orig_uri.path.file_escaped}/{http.request.orig_uri.prefixed_query}"
]
},
"status_code": 308

View file

@ -33,7 +33,7 @@ php_fastcgi @test localhost:9000
"handler": "static_response",
"headers": {
"Location": [
"{http.request.orig_uri.path}/{http.request.orig_uri.prefixed_query}"
"./{http.request.orig_uri.path.file_escaped}/{http.request.orig_uri.prefixed_query}"
]
},
"status_code": 308

View file

@ -43,7 +43,7 @@ php_fastcgi localhost:9000 {
"handler": "static_response",
"headers": {
"Location": [
"{http.request.orig_uri.path}/{http.request.orig_uri.prefixed_query}"
"./{http.request.orig_uri.path.file_escaped}/{http.request.orig_uri.prefixed_query}"
]
},
"status_code": 308

View file

@ -46,7 +46,7 @@ php_fastcgi localhost:9000 {
"handler": "static_response",
"headers": {
"Location": [
"{http.request.orig_uri.path}/{http.request.orig_uri.prefixed_query}"
"./{http.request.orig_uri.path.file_escaped}/{http.request.orig_uri.prefixed_query}"
]
},
"status_code": 308

View file

@ -22,6 +22,7 @@ import (
"net/http/fcgi"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
@ -149,3 +150,80 @@ func TestPHPFastCGIProtectedRouteIgnoresDotSegments(t *testing.T) {
})
}
}
// The php_fastcgi directory redirect must stay on the requesting origin. Its
// matcher judges the cleaned request path, so /%2Fevil.com%2F..%2Fsub is matched
// as /sub and resolves to <root>/sub/index.php, but the Location header used to
// be built from the raw original path and came out as //evil.com/../sub/, which
// browsers treat as a scheme-relative URL to another host. The relative
// reference is built from the escaped original segment, so names with reserved
// or non-ASCII characters must still round-trip to the same directory.
func TestPHPFastCGIDirectoryRedirectStaysOnOrigin(t *testing.T) {
dirs := []string{"sub", "a b", "a#b", "50%", "a;b", "café", "x/sub"}
if runtime.GOOS != "windows" {
dirs = append(dirs, "a?b", "a:b")
}
root := t.TempDir()
for _, dir := range dirs {
if err := os.MkdirAll(filepath.Join(root, filepath.FromSlash(dir)), 0o755); err != nil {
t.Fatalf("creating %s: %v", dir, err)
}
if err := os.WriteFile(filepath.Join(root, filepath.FromSlash(dir), "index.php"), []byte("<?php // index"), 0o644); err != nil {
t.Fatalf("writing %s/index.php: %v", dir, err)
}
}
tester := caddytest.NewTester(t)
tester.InitServer(fmt.Sprintf(`{
skip_install_trust
admin localhost:2999
http_port 9080
https_port 9443
grace_period 1ns
}
localhost:9080 {
root * %s
php_fastcgi 127.0.0.1:9
}
`, root), "caddyfile")
tests := []struct {
uri string
want string
}{
{uri: "/sub", want: "/sub/"},
{uri: "/sub?a=1", want: "/sub/?a=1"},
{uri: "/%2Fevil.com%2F..%2Fsub", want: "/%2Fevil.com%2F..%2Fsub/"},
{uri: "/%5Cevil.com%2F..%2Fsub", want: "/%5Cevil.com%2F..%2Fsub/"},
{uri: "/a%20b", want: "/a%20b/"},
{uri: "/a%23b", want: "/a%23b/"},
{uri: "/50%25", want: "/50%25/"},
{uri: "/a;b", want: "/a;b/"},
{uri: "/caf%C3%A9", want: "/caf%C3%A9/"},
{uri: "/x%2Fsub", want: "/x%2Fsub/"},
}
if runtime.GOOS != "windows" {
tests = append(tests,
struct{ uri, want string }{uri: "/a%3Fb", want: "/a%3Fb/"},
struct{ uri, want string }{uri: "/a:b", want: "/a:b/"},
)
}
for _, tc := range tests {
resp := tester.AssertRedirect("http://localhost:9080"+tc.uri, "http://localhost:9080"+tc.want, http.StatusPermanentRedirect)
if resp == nil {
continue
}
loc := resp.Header.Get("Location")
// a Location beginning with // or /\ is scheme-relative to browsers
if strings.HasPrefix(loc, "//") || strings.HasPrefix(loc, `/\`) {
t.Errorf("requesting %q: Location %q is not origin-relative", tc.uri, loc)
}
for i := 0; i < len(loc); i++ {
if loc[i] < 0x21 || loc[i] > 0x7e {
t.Errorf("requesting %q: Location %q contains an unescaped byte %#x", tc.uri, loc, loc[i])
break
}
}
}
}

View file

@ -76,6 +76,7 @@ func init() {
// `{http.request.orig_uri.path.*}` | Parts of the original path, split by `/` (0-based from left)
// `{http.request.orig_uri.path.dir}` | The request's original directory
// `{http.request.orig_uri.path.file}` | The request's original filename
// `{http.request.orig_uri.path.file_escaped}` | The request's original filename, percent-encoded as in the request's escaped path
// `{http.request.orig_uri.query}` | The request's original query string (without `?`)
// `{http.request.orig_uri.prefixed_query}` | The request's original query string with a `?` prefix, if non-empty
// `{http.request.port}` | The port part of the request's Host header

View file

@ -263,6 +263,13 @@ func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.Respo
or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request)
_, file := path.Split(or.URL.Path)
return file, true
case "http.request.orig_uri.path.file_escaped":
// split the escaped path rather than escaping the decoded
// file name, since an encoded slash (%2F) in the request
// is part of the last segment, not a separator
or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request)
_, file := path.Split(or.URL.EscapedPath())
return file, true
case "http.request.orig_uri.path.dir":
or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request)
dir, _ := path.Split(or.URL.Path)

View file

@ -346,9 +346,17 @@ func parsePHPFastCGI(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error
},
}),
}
// The matcher above judges the cleaned request path, so the
// Location must not echo the raw original path: a request for
// /%2Fevil.com%2F..%2Fsub matches <root>/sub/index.php but would
// redirect to //evil.com/../sub/, which browsers resolve to
// another host. A reference relative to the last path segment
// resolves against the URL the client actually requested, so it
// can only ever land on the same origin; the leading ./ keeps a
// segment containing ':' from being read as a scheme.
redirHandler := caddyhttp.StaticResponse{
StatusCode: caddyhttp.WeakString(strconv.Itoa(http.StatusPermanentRedirect)),
Headers: http.Header{"Location": []string{"{http.request.orig_uri.path}/{http.request.orig_uri.prefixed_query}"}},
Headers: http.Header{"Location": []string{"./{http.request.orig_uri.path.file_escaped}/{http.request.orig_uri.prefixed_query}"}},
}
redirRoute := caddyhttp.Route{
MatcherSetsRaw: []caddy.ModuleMap{redirMatcherSet},