Debian Codegraph @

modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package fastcgi
16
17 import (
18 "crypto/tls"
19 "errors"
20 "fmt"
21 "net"
22 "net/http"
23 "path/filepath"
24 "strconv"
25 "strings"
26 "time"
27 "unicode/utf8"
28
29 "go.uber.org/zap"
30 "go.uber.org/zap/zapcore"
31
32 "github.com/caddyserver/caddy/v2"
33 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
34 "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy"
35 "github.com/caddyserver/caddy/v2/modules/caddytls"
36 )
37
38 var (
39 ErrInvalidSplitPath = errors.New("split path contains non-ASCII characters")
40
41 noopLogger = zap.NewNop()
42 )
43
44 func init() {
45 caddy.RegisterModule(Transport{})
46 }
47
48 // Transport facilitates FastCGI communication.
49 type Transport struct {
50 // Use this directory as the fastcgi root directory. Defaults to the root
51 // directory of the parent virtual host.
52 Root string `json:"root,omitempty"`
53
54 // The path in the URL will be split into two, with the first piece ending
55 // with the value of SplitPath. The first piece will be assumed as the
56 // actual resource (CGI script) name, and the second piece will be set to
57 // PATH_INFO for the CGI script to use.
58 //
59 // Split paths can only contain ASCII characters.
60 // Comparison is case-insensitive.
61 //
62 // Future enhancements should be careful to avoid CVE-2019-11043,
63 // which can be mitigated with use of a try_files-like behavior
64 // that 404s if the fastcgi path info is not found.
65 SplitPath []string `json:"split_path,omitempty"`
66
67 // Path declared as root directory will be resolved to its absolute value
68 // after the evaluation of any symbolic links.
69 // Due to the nature of PHP opcache, root directory path is cached: when
70 // using a symlinked directory as root this could generate errors when
71 // symlink is changed without php-fpm being restarted; enabling this
72 // directive will set $_SERVER['DOCUMENT_ROOT'] to the real directory path.
73 ResolveRootSymlink bool `json:"resolve_root_symlink,omitempty"`
74
75 // Extra environment variables.
76 EnvVars map[string]string `json:"env,omitempty"`
77
78 // The duration used to set a deadline when connecting to an upstream. Default: `3s`.
79 DialTimeout caddy.Duration `json:"dial_timeout,omitempty"`
80
81 // The duration used to set a deadline when reading from the FastCGI server.
82 ReadTimeout caddy.Duration `json:"read_timeout,omitempty"`
83
84 // The duration used to set a deadline when sending to the FastCGI server.
85 WriteTimeout caddy.Duration `json:"write_timeout,omitempty"`
86
87 // Capture and log any messages sent by the upstream on stderr. Logs at WARN
88 // level by default. If the response has a 4xx or 5xx status ERROR level will
89 // be used instead.
90 CaptureStderr bool `json:"capture_stderr,omitempty"`
91
92 serverSoftware string
93 logger *zap.Logger
94 }
95
96 // CaddyModule returns the Caddy module information.
97 func (Transport) CaddyModule() caddy.ModuleInfo {
98 return caddy.ModuleInfo{
99 ID: "http.reverse_proxy.transport.fastcgi",
100 New: func() caddy.Module { return new(Transport) },
101 }
102 }
103
104 // Provision sets up t.
105 func (t *Transport) Provision(ctx caddy.Context) error {
106 t.logger = ctx.Logger()
107
108 if t.Root == "" {
109 t.Root = "{http.vars.root}"
110 }
111
112 version, _ := caddy.Version()
113 t.serverSoftware = "Caddy/" + version
114
115 // Set a relatively short default dial timeout.
116 // This is helpful to make load-balancer retries more speedy.
117 if t.DialTimeout == 0 {
118 t.DialTimeout = caddy.Duration(3 * time.Second)
119 }
120
121 var b strings.Builder
122
123 for i, split := range t.SplitPath {
124 b.Grow(len(split))
125
126 for j := 0; j < len(split); j++ {
127 c := split[j]
128 if c >= utf8.RuneSelf {
129 return ErrInvalidSplitPath
130 }
131
132 if 'A' <= c && c <= 'Z' {
133 b.WriteByte(c + 'a' - 'A')
134 } else {
135 b.WriteByte(c)
136 }
137 }
138
139 t.SplitPath[i] = b.String()
140 b.Reset()
141 }
142
143 return nil
144 }
145
146 // DefaultBufferSizes enables request buffering for fastcgi if not configured.
147 // This is because most fastcgi servers are php-fpm that require the content length to be set to read the body, golang
148 // std has fastcgi implementation that doesn't need this value to process the body, but we can safely assume that's
149 // not used.
150 // http3 requests have a negative content length for GET and HEAD requests, if that header is not sent.
151 // see: https://github.com/caddyserver/caddy/issues/6678#issuecomment-2472224182
152 // Though it appears even if CONTENT_LENGTH is invalid, php-fpm can handle just fine if the body is empty (no Stdin records sent).
153 // php-fpm will hang if there is any data in the body though, https://github.com/caddyserver/caddy/issues/5420#issuecomment-2415943516
154
155 // TODO: better default buffering for fastcgi requests without content length, in theory a value of 1 should be enough, make it bigger anyway
156 func (t Transport) DefaultBufferSizes() (int64, int64) {
157 return 4096, 0
158 }
159
160 // RoundTrip implements http.RoundTripper.
161 func (t Transport) RoundTrip(r *http.Request) (*http.Response, error) {
162 server := r.Context().Value(caddyhttp.ServerCtxKey).(*caddyhttp.Server)
163
164 // Disallow null bytes in the request path, because
165 // PHP upstreams may do bad things, like execute a
166 // non-PHP file as PHP code. See #4574
167 if strings.Contains(r.URL.Path, "\x00") {
168 return nil, caddyhttp.Error(http.StatusBadRequest, fmt.Errorf("invalid request path"))
169 }
170
171 env, err := t.buildEnv(r)
172 if err != nil {
173 return nil, fmt.Errorf("building environment: %v", err)
174 }
175
176 ctx := r.Context()
177
178 // extract dial information from request (should have been embedded by the reverse proxy)
179 network, address := "tcp", r.URL.Host
180 if dialInfo, ok := reverseproxy.GetDialInfo(ctx); ok {
181 network = dialInfo.Network
182 address = dialInfo.Address
183 }
184
185 logCreds := server.Logs != nil && server.Logs.ShouldLogCredentials
186 loggableReq := caddyhttp.LoggableHTTPRequest{
187 Request: r,
188 ShouldLogCredentials: logCreds,
189 }
190 loggableEnv := loggableEnv{vars: env, logCredentials: logCreds}
191
192 logger := t.logger.With(
193 zap.Object("request", loggableReq),
194 zap.Object("env", loggableEnv),
195 )
196 if c := t.logger.Check(zapcore.DebugLevel, "roundtrip"); c != nil {
197 c.Write(
198 zap.String("dial", address),
199 zap.Object("env", loggableEnv),
200 zap.Object("request", loggableReq),
201 )
202 }
203
204 // connect to the backend
205 dialer := net.Dialer{Timeout: time.Duration(t.DialTimeout)}
206 conn, err := dialer.DialContext(ctx, network, address)
207 if err != nil {
208 return nil, fmt.Errorf("dialing backend: %v", err)
209 }
210 defer func() {
211 // conn will be closed with the response body unless there's an error
212 if err != nil {
213 conn.Close()
214 }
215 }()
216
217 // create the client that will facilitate the protocol
218 client := client{
219 rwc: conn,
220 reqID: 1,
221 logger: logger,
222 stderr: t.CaptureStderr,
223 }
224
225 // read/write timeouts
226 if err = client.SetReadTimeout(time.Duration(t.ReadTimeout)); err != nil {
227 return nil, fmt.Errorf("setting read timeout: %v", err)
228 }
229 if err = client.SetWriteTimeout(time.Duration(t.WriteTimeout)); err != nil {
230 return nil, fmt.Errorf("setting write timeout: %v", err)
231 }
232
233 contentLength := r.ContentLength
234 if contentLength == 0 {
235 contentLength, _ = strconv.ParseInt(r.Header.Get("Content-Length"), 10, 64)
236 }
237
238 var resp *http.Response
239 switch r.Method {
240 case http.MethodHead:
241 resp, err = client.Head(env)
242 case http.MethodGet:
243 resp, err = client.Get(env, r.Body, contentLength)
244 case http.MethodOptions:
245 resp, err = client.Options(env)
246 default:
247 resp, err = client.Post(env, r.Method, r.Header.Get("Content-Type"), r.Body, contentLength)
248 }
249 if err != nil {
250 return nil, err
251 }
252
253 return resp, nil
254 }
255
256 // buildEnv returns a set of CGI environment variables for the request.
257 func (t Transport) buildEnv(r *http.Request) (envVars, error) {
258 repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
259
260 var env envVars
261
262 // Separate remote IP and port; more lenient than net.SplitHostPort
263 var ip, port string
264 if idx := strings.LastIndex(r.RemoteAddr, ":"); idx > -1 {
265 ip = r.RemoteAddr[:idx]
266 port = r.RemoteAddr[idx+1:]
267 } else {
268 ip = r.RemoteAddr
269 }
270
271 // Remove [] from IPv6 addresses
272 ip = strings.Replace(ip, "[", "", 1)
273 ip = strings.Replace(ip, "]", "", 1)
274
275 // make sure file root is absolute
276 root, err := caddy.FastAbs(repl.ReplaceAll(t.Root, "."))
277 if err != nil {
278 return nil, err
279 }
280
281 if t.ResolveRootSymlink {
282 root, err = filepath.EvalSymlinks(root)
283 if err != nil {
284 return nil, err
285 }
286 }
287
288 fpath := r.URL.Path
289 scriptName := fpath
290
291 docURI := fpath
292 // split "actual path" from "path info" if configured
293 var pathInfo string
294 if splitPos := t.splitPos(fpath); splitPos > -1 {
295 docURI = fpath[:splitPos]
296 pathInfo = fpath[splitPos:]
297
298 // Strip PATH_INFO from SCRIPT_NAME
299 scriptName = strings.TrimSuffix(scriptName, pathInfo)
300 }
301
302 // Try to grab the path remainder from a file matcher
303 // if we didn't get a split result here.
304 // See https://github.com/caddyserver/caddy/issues/3718
305 if pathInfo == "" {
306 pathInfo, _ = repl.GetString("http.matchers.file.remainder")
307 }
308
309 // SCRIPT_FILENAME is the absolute path of SCRIPT_NAME
310 scriptFilename := caddyhttp.SanitizedPathJoin(root, scriptName)
311
312 // Ensure the SCRIPT_NAME has a leading slash for compliance with RFC3875
313 // Info: https://tools.ietf.org/html/rfc3875#section-4.1.13
314 if scriptName != "" && !strings.HasPrefix(scriptName, "/") {
315 scriptName = "/" + scriptName
316 }
317
318 // Get the request URL from context. The context stores the original URL in case
319 // it was changed by a middleware such as rewrite. By default, we pass the
320 // original URI in as the value of REQUEST_URI (the user can overwrite this
321 // if desired). Most PHP apps seem to want the original URI. Besides, this is
322 // how nginx defaults: http://stackoverflow.com/a/12485156/1048862
323 origReq := r.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request)
324
325 requestScheme := "http"
326 if r.TLS != nil {
327 requestScheme = "https"
328 }
329
330 reqHost, reqPort, err := net.SplitHostPort(r.Host)
331 if err != nil {
332 // whatever, just assume there was no port
333 reqHost = r.Host
334 }
335
336 authUser, _ := repl.GetString("http.auth.user.id")
337
338 // Some variables are unused but cleared explicitly to prevent
339 // the parent environment from interfering.
340 env = envVars{
341 // Variables defined in CGI 1.1 spec
342 "AUTH_TYPE": "", // Not used
343 "CONTENT_LENGTH": r.Header.Get("Content-Length"),
344 "CONTENT_TYPE": r.Header.Get("Content-Type"),
345 "GATEWAY_INTERFACE": "CGI/1.1",
346 "PATH_INFO": pathInfo,
347 "QUERY_STRING": r.URL.RawQuery,
348 "REMOTE_ADDR": ip,
349 "REMOTE_HOST": ip, // For speed, remote host lookups disabled
350 "REMOTE_PORT": port,
351 "REMOTE_IDENT": "", // Not used
352 "REMOTE_USER": authUser,
353 "REQUEST_METHOD": r.Method,
354 "REQUEST_SCHEME": requestScheme,
355 "SERVER_NAME": reqHost,
356 "SERVER_PROTOCOL": r.Proto,
357 "SERVER_SOFTWARE": t.serverSoftware,
358
359 // Other variables
360 "DOCUMENT_ROOT": root,
361 "DOCUMENT_URI": docURI,
362 "HTTP_HOST": r.Host, // added here, since not always part of headers
363 "REQUEST_URI": origReq.URL.RequestURI(),
364 "SCRIPT_FILENAME": scriptFilename,
365 "SCRIPT_NAME": scriptName,
366 }
367
368 // compliance with the CGI specification requires that
369 // PATH_TRANSLATED should only exist if PATH_INFO is defined.
370 // Info: https://www.ietf.org/rfc/rfc3875 Page 14
371 if env["PATH_INFO"] != "" {
372 env["PATH_TRANSLATED"] = caddyhttp.SanitizedPathJoin(root, pathInfo) // Info: http://www.oreilly.com/openbook/cgi/ch02_04.html
373 }
374
375 // compliance with the CGI specification requires that
376 // the SERVER_PORT variable MUST be set to the TCP/IP port number on which this request is received from the client
377 // even if the port is the default port for the scheme and could otherwise be omitted from a URI.
378 // https://tools.ietf.org/html/rfc3875#section-4.1.15
379 if reqPort != "" {
380 env["SERVER_PORT"] = reqPort
381 } else if requestScheme == "http" {
382 env["SERVER_PORT"] = "80"
383 } else if requestScheme == "https" {
384 env["SERVER_PORT"] = "443"
385 }
386
387 // Some web apps rely on knowing HTTPS or not
388 if r.TLS != nil {
389 env["HTTPS"] = "on"
390 // and pass the protocol details in a manner compatible with apache's mod_ssl
391 // (which is why these have a SSL_ prefix and not TLS_).
392 v, ok := tlsProtocolStrings[r.TLS.Version]
393 if ok {
394 env["SSL_PROTOCOL"] = v
395 }
396 // and pass the cipher suite in a manner compatible with apache's mod_ssl
397 for _, cs := range caddytls.SupportedCipherSuites() {
398 if cs.ID == r.TLS.CipherSuite {
399 env["SSL_CIPHER"] = cs.Name
400 break
401 }
402 }
403 }
404
405 // Add env variables from config (with support for placeholders in values)
406 for key, value := range t.EnvVars {
407 env[key] = repl.ReplaceAll(value, "")
408 }
409
410 // Add all HTTP headers to env variables
411 for field, val := range r.Header {
412 header := strings.ToUpper(field)
413 header = headerNameReplacer.Replace(header)
414 env["HTTP_"+header] = strings.Join(val, ", ")
415 }
416 return env, nil
417 }
418
419 // splitPos returns the index where path should
420 // be split based on t.SplitPath.
421 //
422 // example: if splitPath is [".php"]
423 // "/path/to/script.php/some/path": ("/path/to/script.php", "/some/path")
424 //
425 // Matching is strictly ASCII case-insensitive. Bytes >= utf8.RuneSelf in path
426 // never match any split entry: split strings are validated ASCII-only and
427 // lower-cased in Provision(), so any Unicode equivalence (e.g. fullwidth or
428 // mathematical letters folding to ASCII) would let an attacker upload a file
429 // whose name contains such code points and have it served as PHP. See
430 // FrankenPHP advisories GHSA-3g8v-8r37-cgjm and GHSA-v4h7-cj44-8fc8.
431 //
432 // Adapted from FrankenPHP's code (copyright 2026 Kévin Dunglas, MIT license)
433 func (t Transport) splitPos(path string) int {
434 // TODO: from v1...
435 // if httpserver.CaseSensitivePath {
436 // return strings.Index(path, r.SplitPath)
437 // }
438 if len(t.SplitPath) == 0 {
439 return 0
440 }
441
442 pathLen := len(path)
443
444 for _, split := range t.SplitPath {
445 splitLen := len(split)
446 if splitLen == 0 || splitLen > pathLen {
447 continue
448 }
449
450 for i := 0; i <= pathLen-splitLen; i++ {
451 match := true
452 for j := range splitLen {
453 c := path[i+j]
454 if c >= utf8.RuneSelf {
455 match = false
456
457 break
458 }
459
460 if 'A' <= c && c <= 'Z' {
461 c += 'a' - 'A'
462 }
463
464 if c != split[j] {
465 match = false
466
467 break
468 }
469 }
470
471 if match {
472 return i + splitLen
473 }
474 }
475 }
476
477 return -1
478 }
479
480 type envVars map[string]string
481
482 // loggableEnv is a simple type to allow for speeding up zap log encoding.
483 type loggableEnv struct {
484 vars envVars
485 logCredentials bool
486 }
487
488 func (env loggableEnv) MarshalLogObject(enc zapcore.ObjectEncoder) error {
489 for k, v := range env.vars {
490 if !env.logCredentials {
491 switch strings.ToLower(k) {
492 case "http_cookie", "http_set_cookie", "http_authorization", "http_proxy_authorization":
493 v = ""
494 }
495 }
496 enc.AddString(k, v)
497 }
498 return nil
499 }
500
501 // Map of supported protocols to Apache ssl_mod format
502 // Note that these are slightly different from SupportedProtocols in caddytls/config.go
503 var tlsProtocolStrings = map[uint16]string{
504 tls.VersionTLS10: "TLSv1",
505 tls.VersionTLS11: "TLSv1.1",
506 tls.VersionTLS12: "TLSv1.2",
507 tls.VersionTLS13: "TLSv1.3",
508 }
509
510 var headerNameReplacer = strings.NewReplacer("-", "_")
511
512 // Interface guards
513 var (
514 _ zapcore.ObjectMarshaler = (*loggableEnv)(nil)
515
516 _ caddy.Provisioner = (*Transport)(nil)
517 _ http.RoundTripper = (*Transport)(nil)
518 _ reverseproxy.BufferedTransport = (*Transport)(nil)
519 )