diff --git a/caddytest/integration/phpfastcgi_test.go b/caddytest/integration/phpfastcgi_test.go new file mode 100644 index 000000000..5ce3a22e1 --- /dev/null +++ b/caddytest/integration/phpfastcgi_test.go @@ -0,0 +1,151 @@ +// Copyright 2015 Matthew Holt and The Caddy Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package integration + +import ( + "fmt" + "io" + "net" + "net/http" + "net/http/fcgi" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/caddyserver/caddy/v2/caddytest" +) + +// startFakePHPFPM starts a FastCGI responder that reports the SCRIPT_FILENAME it +// was asked to execute, so a test can assert which script Caddy selected. +func startFakePHPFPM(t *testing.T) string { + t.Helper() + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listening: %v", err) + } + t.Cleanup(func() { ln.Close() }) + + go func() { + _ = fcgi.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + env := fcgi.ProcessEnv(r) + fmt.Fprintf(w, "SCRIPT_FILENAME=%s", env["SCRIPT_FILENAME"]) + })) + }() + + return ln.Addr().String() +} + +// A php_fastcgi route protected by a path matcher must not execute a script the +// matcher never evaluated. Path matchers judge the cleaned request path, so +// /admin.php/../../other.php is matched as /other.php and must not cause +// /admin.php to be executed. +// +// `index off` is used so that php_fastcgi generates no rewrite route at all +// (fastcgi/caddyfile.go skips the redirect and try_files routes entirely). That +// rewrite is otherwise the only step that normalizes r.URL.Path before the +// transport reads it, so without this the test would be satisfied by the rewrite +// rather than by the transport, and would not cover the transport's own +// normalization. +func TestPHPFastCGIProtectedRouteIgnoresDotSegments(t *testing.T) { + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "admin.php"), []byte("/admin.php. +func TestBuildEnvDotSegmentsCannotSelectAnotherScript(t *testing.T) { + t.Parallel() + + newRequest := func(target string) *http.Request { + r := httptest.NewRequest(http.MethodGet, target, nil) + ctx := context.WithValue(r.Context(), caddy.ReplacerCtxKey, caddy.NewReplacer()) + ctx = context.WithValue(ctx, caddyhttp.VarsCtxKey, map[string]any{}) + ctx = context.WithValue(ctx, caddyhttp.OriginalRequestCtxKey, *r) + return r.WithContext(ctx) + } + + for _, tc := range []struct { + name string + target string + expectedScriptName string + expectedPathInfo string + }{ + { + name: "literal dot segments", + target: "/admin.php/../../other.php", + expectedScriptName: "/other.php", + expectedPathInfo: "", + }, + { + name: "single dot segment", + target: "/admin.php/../other.php", + expectedScriptName: "/other.php", + expectedPathInfo: "", + }, + { + name: "percent-encoded separators", + target: "/admin.php/..%2f..%2fother.php", + expectedScriptName: "/other.php", + expectedPathInfo: "", + }, + { + name: "percent-encoded dots", + target: "/admin.php/%2e%2e/other.php", + expectedScriptName: "/other.php", + expectedPathInfo: "", + }, + { + name: "dot segments before legitimate path info", + target: "/admin.php/../other.php/extra/path", + expectedScriptName: "/other.php", + expectedPathInfo: "/extra/path", + }, + { + name: "no dot segments is unaffected", + target: "/other.php/extra/path", + expectedScriptName: "/other.php", + expectedPathInfo: "/extra/path", + }, + { + // path.Clean("") is ".", which must not become the script name; + // an absolute-form request-target can leave URL.Path empty. + name: "empty path stays empty", + target: "http://example.com", + expectedScriptName: "", + expectedPathInfo: "", + }, + } { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + tr := Transport{Root: root, SplitPath: []string{".php"}} + env, err := tr.buildEnv(newRequest(tc.target)) + require.NoError(t, err) + + assert.Equal(t, tc.expectedScriptName, env["SCRIPT_NAME"], + "SCRIPT_NAME must come from the cleaned path") + assert.Equal(t, tc.expectedPathInfo, env["PATH_INFO"], + "PATH_INFO must come from the cleaned path") + if tc.expectedScriptName != "" { + assert.Equal(t, filepath.Join(root, filepath.FromSlash(tc.expectedScriptName)), env["SCRIPT_FILENAME"], + "SCRIPT_FILENAME must name the script the matchers evaluated") + } + assert.NotContains(t, env["SCRIPT_FILENAME"], "admin.php", + "a pre-clean path component must never become the executed script") + }) + } +} diff --git a/modules/caddyhttp/reverseproxy/fastcgi/fastcgi_windows_test.go b/modules/caddyhttp/reverseproxy/fastcgi/fastcgi_windows_test.go new file mode 100644 index 000000000..44299c3f9 --- /dev/null +++ b/modules/caddyhttp/reverseproxy/fastcgi/fastcgi_windows_test.go @@ -0,0 +1,74 @@ +// Copyright 2015 Matthew Holt and The Caddy Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build windows + +package fastcgi + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/modules/caddyhttp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// On Windows the path matchers additionally fold backslashes into separators and +// trim per-component trailing dots and spaces (see caddyhttp.NormalizedPath), +// so the transport must do the same or the dot-segment bypass simply reappears +// spelled with backslashes. +func TestBuildEnvWindowsSeparatorsCannotSelectAnotherScript(t *testing.T) { + t.Parallel() + + newRequest := func(target string) *http.Request { + r := httptest.NewRequest(http.MethodGet, target, nil) + ctx := context.WithValue(r.Context(), caddy.ReplacerCtxKey, caddy.NewReplacer()) + ctx = context.WithValue(ctx, caddyhttp.VarsCtxKey, map[string]any{}) + ctx = context.WithValue(ctx, caddyhttp.OriginalRequestCtxKey, *r) + return r.WithContext(ctx) + } + + for _, tc := range []struct { + name string + target string + expectedScriptName string + expectedPathInfo string + }{ + {"backslash dot segments", `/admin.php\..\other.php`, "/other.php", ""}, + {"backslash, two levels", `/admin.php\..\..\other.php`, "/other.php", ""}, + {"mixed separators", `/admin.php\../other.php`, "/other.php", ""}, + // Per-component trailing dot/space folding is Windows-only and is not + // something CleanPath does, so this case fails unless the transport + // applies the same normalization the matchers do. + {"trailing dot in a path-info component", "/other.php/a./b", "/other.php", "/a/b"}, + {"trailing space in a path-info component", "/other.php/a%20/b", "/other.php", "/a/b"}, + } { + t.Run(tc.name, func(t *testing.T) { + tr := Transport{Root: `C:\srv`, SplitPath: []string{".php"}} + env, err := tr.buildEnv(newRequest(tc.target)) + require.NoError(t, err) + + assert.Equal(t, tc.expectedScriptName, env["SCRIPT_NAME"], + "SCRIPT_NAME must come from the normalized, cleaned path") + assert.Equal(t, tc.expectedPathInfo, env["PATH_INFO"], + "PATH_INFO must come from the normalized, cleaned path") + assert.NotContains(t, env["SCRIPT_FILENAME"], "admin.php", + "a pre-normalization path component must never become the executed script") + }) + } +}