Repository navigation
Expand file tree
/
Copy pathcgi.go
More file actions
567 lines (472 loc) · 18.1 KB
/
Copy pathcgi.go
File metadata and controls
567 lines (472 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
package frankenphp
// #cgo nocallback frankenphp_register_server_vars
// #cgo nocallback frankenphp_register_variable_safe
// #cgo nocallback frankenphp_register_known_variable
// #cgo nocallback frankenphp_init_persistent_string
// #cgo nocallback frankenphp_add_to_prepared_env
// #cgo noescape frankenphp_register_server_vars
// #cgo noescape frankenphp_register_variable_safe
// #cgo noescape frankenphp_register_known_variable
// #cgo noescape frankenphp_init_persistent_string
// #cgo noescape frankenphp_add_to_prepared_env
// #include "frankenphp.h"
// #include <php_variables.h>
import "C"
import (
"crypto/tls"
"net"
"net/http"
"net/url"
"path"
"path/filepath"
"runtime"
"strings"
"unicode/utf8"
"unsafe"
"github.com/dunglas/frankenphp/internal/phpheaders"
)
// computeKnownVariables returns a set of CGI environment variables for the request.
//
// TODO: handle this case https://github.com/caddyserver/caddy/issues/3718
// Inspired by https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
func addKnownVariablesToServer(fc *frankenPHPContext, trackVarsArray *C.zval) {
request := fc.request
ip, port := splitRemoteAddr(request.RemoteAddr)
var rs, https, sslProtocol *C.zend_string
var sslCipher string
if request.TLS == nil {
rs = C.frankenphp_strings.httpLowercase
https = C.frankenphp_strings.empty
sslProtocol = C.frankenphp_strings.empty
sslCipher = ""
} else {
rs = C.frankenphp_strings.httpsLowercase
https = C.frankenphp_strings.on
// and pass the protocol details in a manner compatible with Apache's mod_ssl
// (which is why these have an SSL_ prefix and not TLS_).
sslProtocol = tlsProtocol(request.TLS.Version)
if request.TLS.CipherSuite != 0 {
sslCipher = tls.CipherSuiteName(request.TLS.CipherSuite)
}
}
reqHost, reqPort, _ := net.SplitHostPort(request.Host)
if reqHost == "" {
// whatever, just assume there was no port
reqHost = request.Host
}
if reqPort == "" {
// compliance with the CGI specification requires that
// the SERVER_PORT variable MUST be set to the TCP/IP port number on which this request is received from the client
// even if the port is the default port for the scheme and could otherwise be omitted from a URI.
// https://tools.ietf.org/html/rfc3875#section-4.1.15
switch rs {
case C.frankenphp_strings.httpsLowercase:
reqPort = "443"
case C.frankenphp_strings.httpLowercase:
reqPort = "80"
}
}
serverPort := reqPort
// IP of the interface that accepted the connection, absent for Unix sockets
var serverAddr string
switch addr := request.Context().Value(http.LocalAddrContextKey).(type) {
case *net.TCPAddr:
serverAddr = addr.IP.String()
case *net.UDPAddr:
serverAddr = addr.IP.String()
}
contentLength := request.Header.Get("Content-Length")
phpSelf := fc.scriptName + fc.pathInfo
// PATH_TRANSLATED is only defined if PATH_INFO is, see http://www.oreilly.com/openbook/cgi/ch02_04.html
var pathTranslated string
if fc.pathInfo != "" {
pathTranslated = sanitizedPathJoin(fc.documentRoot, fc.pathInfo)
}
C.frankenphp_register_server_vars(trackVarsArray, C.frankenphp_server_vars{
// approximate total length to avoid array re-hashing:
// 29 CGI vars + headers + environment
total_num_vars: C.size_t(29 + len(request.Header) + len(fc.env) + lengthOfEnv),
// CGI vars with variable values
remote_addr: toUnsafeChar(ip),
remote_addr_len: C.size_t(len(ip)),
remote_host: toUnsafeChar(ip),
remote_host_len: C.size_t(len(ip)),
remote_port: toUnsafeChar(port),
remote_port_len: C.size_t(len(port)),
document_root: toUnsafeChar(fc.documentRoot),
document_root_len: C.size_t(len(fc.documentRoot)),
path_info: toUnsafeChar(fc.pathInfo),
path_info_len: C.size_t(len(fc.pathInfo)),
path_translated: toUnsafeChar(pathTranslated),
path_translated_len: C.size_t(len(pathTranslated)),
php_self: toUnsafeChar(phpSelf),
php_self_len: C.size_t(len(phpSelf)),
document_uri: toUnsafeChar(fc.docURI),
document_uri_len: C.size_t(len(fc.docURI)),
script_filename: toUnsafeChar(fc.scriptFilename),
script_filename_len: C.size_t(len(fc.scriptFilename)),
script_name: toUnsafeChar(fc.scriptName),
script_name_len: C.size_t(len(fc.scriptName)),
server_name: toUnsafeChar(reqHost),
server_name_len: C.size_t(len(reqHost)),
server_port: toUnsafeChar(serverPort),
server_port_len: C.size_t(len(serverPort)),
server_addr: toUnsafeChar(serverAddr),
server_addr_len: C.size_t(len(serverAddr)),
content_length: toUnsafeChar(contentLength),
content_length_len: C.size_t(len(contentLength)),
server_protocol: toUnsafeChar(request.Proto),
server_protocol_len: C.size_t(len(request.Proto)),
http_host: toUnsafeChar(request.Host),
http_host_len: C.size_t(len(request.Host)),
request_uri: toUnsafeChar(fc.requestURI),
request_uri_len: C.size_t(len(fc.requestURI)),
ssl_cipher: toUnsafeChar(sslCipher),
ssl_cipher_len: C.size_t(len(sslCipher)),
// CGI vars with known values
request_scheme: rs, // "http" or "https"
ssl_protocol: sslProtocol, // values from tlsProtocol
https: https, // "on" or empty
})
}
func addHeadersToServer(request *http.Request, trackVarsArray *C.zval) {
for field, val := range request.Header {
// HTTP_HOST comes from request.Host: over HTTP/2, net/http keeps a "host" field distinct from :authority
if field == "Host" {
continue
}
if k := commonHeaders[field]; k != nil {
v := strings.Join(val, ", ")
C.frankenphp_register_known_variable(k, toUnsafeChar(v), C.size_t(len(v)), trackVarsArray)
continue
}
// if the header name could not be cached, it needs to be registered safely
// this is more inefficient but allows additional sanitizing by PHP
k := phpheaders.GetUnCommonHeader(field)
v := strings.Join(val, ", ")
C.frankenphp_register_variable_safe(toUnsafeChar(k), toUnsafeChar(v), C.size_t(len(v)), trackVarsArray)
}
}
// registerPreparedEnv exposes fc.env and fc.server.env to getenv() before any PHP code runs.
func registerPreparedEnv(fc *frankenPHPContext, preparedEnvLen int) {
for k, v := range fc.server.env {
C.frankenphp_add_to_prepared_env(toUnsafeChar(k), C.size_t(len(k)-1), toUnsafeChar(v), C.size_t(len(v)), C.size_t(preparedEnvLen))
}
for k, v := range fc.env {
C.frankenphp_add_to_prepared_env(toUnsafeChar(k), C.size_t(len(k)-1), toUnsafeChar(v), C.size_t(len(v)), C.size_t(preparedEnvLen))
}
}
//export go_register_server_variables
func go_register_server_variables(threadIndex C.uintptr_t, trackVarsArray *C.zval) C.bool {
thread := phpThreads[threadIndex]
fc := thread.handler.frankenPHPContext()
if fc.request == nil {
// go_update_request_info() never ran
return false
}
addKnownVariablesToServer(fc, trackVarsArray)
addHeadersToServer(fc.request, trackVarsArray)
return C.bool(len(fc.env) != 0 || len(fc.server.env) != 0)
}
// splitCgiPath splits the request path into SCRIPT_NAME, SCRIPT_FILENAME, PATH_INFO, DOCUMENT_URI
func splitCgiPath(fc *frankenPHPContext) error {
path := cleanRequestPath(fc.request.URL.Path, runtime.GOOS == "windows")
splitPath := fc.splitPath
if splitPath == nil {
splitPath = []string{".php"}
}
pos := splitPos(path, splitPath)
if pos > -1 {
fc.docURI = path[:pos]
fc.pathInfo = path[pos:]
}
// If a worker is already assigned explicitly, derive SCRIPT_NAME from its filename
if fc.worker != nil {
fc.scriptFilename = fc.worker.fileName
if rest, ok := strings.CutPrefix(fc.worker.fileName, fc.documentRoot); ok && rest != "" && rest[0] == filepath.Separator {
fc.scriptName = filepath.ToSlash(rest)
} else {
fc.docURI = ""
fc.pathInfo = ""
}
return nil
}
// a path no split matches names no script: running it would execute a file the split extensions exclude
if pos == -1 {
return ErrInvalidScriptPath
}
// an 8.3 alias or an alternate data stream can name a non-PHP file with a PHP-looking path
if runtime.GOOS == "windows" && (strings.ContainsRune(path[:pos], ':') || hasWindowsShortName(path[:pos])) {
return ErrInvalidScriptPath
}
// Strip PATH_INFO from SCRIPT_NAME
// Ensure the SCRIPT_NAME has a leading slash for compliance with RFC3875
// Info: https://tools.ietf.org/html/rfc3875#section-4.1.13
fc.scriptName = ensureLeadingSlash(strings.TrimSuffix(path, fc.pathInfo))
// TODO: is it possible to delay this and avoid saving everything in the context?
// SCRIPT_FILENAME is the absolute path of SCRIPT_NAME
fc.scriptFilename = sanitizedPathJoin(fc.documentRoot, fc.scriptName)
// see if a php_server worker or global worker matches the request path
// aka: root + request path == worker.filename
if fc.worker = fc.server.workersByPath[fc.scriptFilename]; fc.worker == nil {
fc.worker = globalWorkersByPath[fc.scriptFilename]
}
return nil
}
const windowsShortNamePunctuation = "$%'-_@~`!(){}^#&"
// possibleWindowsShortNamePart mirrors Caddy's file server: non-ASCII is accepted since Windows may allow it in 8.3 names.
func possibleWindowsShortNamePart(s string) bool {
for _, c := range s {
if c >= utf8.RuneSelf ||
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
strings.ContainsRune(windowsShortNamePunctuation, c) {
continue
}
return false
}
return true
}
// hasWindowsShortName reports whether a component of p has the syntax of an NTFS 8.3 short name, like Caddy's file server.
func hasWindowsShortName(p string) bool {
for _, component := range strings.FieldsFunc(p, func(r rune) bool {
return r == '/' || r == '\\'
}) {
component = strings.TrimRight(component, ". ")
base, extension, hasExtension := strings.Cut(component, ".")
if utf8.RuneCountInString(base) > 8 || !possibleWindowsShortNamePart(base) ||
(hasExtension && (utf8.RuneCountInString(extension) > 3 || !possibleWindowsShortNamePart(extension))) {
continue
}
tilde := strings.LastIndexByte(base, '~')
if tilde <= 0 || tilde == len(base)-1 {
continue
}
digits := true
for _, c := range base[tilde+1:] {
if c < '0' || c > '9' {
digits = false
break
}
}
if digits {
return true
}
}
return false
}
// cleanRequestPath resolves dot segments as Caddy's matchers do, so the script run is the one they matched.
func cleanRequestPath(reqPath string, windows bool) string {
if windows {
reqPath = strings.ReplaceAll(reqPath, `\`, "/")
}
if !strings.Contains(reqPath, "/.") {
return reqPath
}
if windows {
// mirror Caddy's normalizeWindowsPath, which trims "..." to an empty segment before cleaning
segments := strings.Split(reqPath, "/")
for i, segment := range segments {
if segment != "." && segment != ".." {
segments[i] = strings.TrimRight(segment, ". ")
}
}
reqPath = strings.Join(segments, "/")
}
cleaned := path.Clean("/" + reqPath)
if cleaned != "/" && strings.HasSuffix(reqPath, "/") {
cleaned += "/"
}
return cleaned
}
// escapedPathSelectsAnotherScript reports whether cleaning the escaped path, as Caddy's path matchers do for patterns containing "%", leads to another script than cleaning the decoded one.
func escapedPathSelectsAnotherScript(u *url.URL, splitPath []string, windows bool) bool {
// on Windows, those matchers read a backslash, escaped even without RawPath, as an escaped separator
backslash := windows && strings.Contains(u.Path, `\`)
if u.RawPath == "" && !backslash {
return false
}
escaped, err := url.PathUnescape(cleanRequestPath(u.EscapedPath(), windows))
if err != nil {
return true
}
if backslash {
escaped = strings.ReplaceAll(escaped, `\`, "/")
}
if splitPath == nil {
splitPath = []string{".php"}
}
return scriptPart(cleanRequestPath(u.Path, windows), splitPath) != scriptPart(escaped, splitPath)
}
func scriptPart(path string, splitPath []string) string {
if pos := splitPos(path, splitPath); pos > -1 {
return path[:pos]
}
return path
}
// splitPos returns the index where path should be split based on splitPath.
// example: if splitPath is [".php"]
// "/path/to/script.php/some/path": ("/path/to/script.php", "/some/path")
//
// Matching is strictly ASCII case-insensitive. Bytes >= utf8.RuneSelf in path
// never match any split entry: split strings are validated ASCII-only and
// lower-cased in WithRequestSplitPath, so any Unicode equivalence (e.g.
// fullwidth or mathematical letters folding to ASCII) would let an attacker
// upload a file whose name contains such code points and have it served as
// PHP. See GHSA-3g8v-8r37-cgjm and GHSA-v4h7-cj44-8fc8.
func splitPos(path string, splitPath []string) int {
if len(splitPath) == 0 {
return 0
}
pathLen := len(path)
for _, split := range splitPath {
splitLen := len(split)
if splitLen == 0 || splitLen > pathLen {
continue
}
for i := 0; i <= pathLen-splitLen; i++ {
match := true
for j := range splitLen {
c := path[i+j]
if c >= utf8.RuneSelf {
match = false
break
}
if 'A' <= c && c <= 'Z' {
c += 'a' - 'A'
}
if c != split[j] {
match = false
break
}
}
if match {
pos := i + splitLen
// the split must end the path or a whole path segment, like
// the "*.php/*" route matcher: a split inside a filename
// ("/a.php.txt/b.php") would run a script the router never matched
if pos != pathLen && path[pos] != '/' {
continue
}
return pos
}
}
}
return -1
}
// go_update_request_info updates the sapi_request_info struct
// See: https://github.com/php/php-src/blob/345e04b619c3bc11ea17ee02cdecad6ae8ce5891/main/SAPI.h#L72
//
//export go_update_request_info
func go_update_request_info(threadIndex C.uintptr_t, info *C.sapi_request_info) *C.char {
thread := phpThreads[threadIndex]
fc := thread.handler.frankenPHPContext()
request := fc.request
// PHP stats this as the executed script (getlastmod(), session cache limiters...), unlike the PATH_TRANSLATED CGI variable
info.path_translated = thread.pinCString(fc.scriptFilename)
if request == nil {
return nil
}
preparedEnvLen := len(fc.env) + len(fc.server.env)
if preparedEnvLen != 0 {
registerPreparedEnv(fc, preparedEnvLen)
}
if m, ok := cStringHTTPMethods[request.Method]; ok {
info.request_method = m
} else {
info.request_method = thread.pinCString(request.Method)
}
info.query_string = thread.pinCString(request.URL.RawQuery)
info.content_length = C.zend_long(request.ContentLength)
if contentType := request.Header.Get("Content-Type"); contentType != "" {
info.content_type = thread.pinCString(contentType)
}
info.request_uri = thread.pinCString(fc.requestURI)
info.proto_num = C.int(request.ProtoMajor*1000 + request.ProtoMinor)
authorizationHeader := request.Header.Get("Authorization")
if authorizationHeader == "" {
return nil
}
return thread.pinCString(authorizationHeader)
}
// SanitizedPathJoin performs filepath.Join(root, reqPath) that
// is safe against directory traversal attacks. It uses logic
// similar to that in the Go standard library, specifically
// in the implementation of http.Dir. The root is assumed to
// be a trusted path, but reqPath is not; and the output will
// never be outside of root. The resulting path can be used
// with the local file system.
//
// Adapted from https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go
// Copyright 2015 Matthew Holt and The Caddy Authors
func sanitizedPathJoin(root, reqPath string) string {
if root == "" {
root = "."
}
// Clean with "path", not "filepath": on Windows filepath.Clean keeps the
// ".." behind a leading "//" (UNC prefix), letting reqPath escape root.
relPath := path.Clean(ensureLeadingSlash(reqPath))[1:]
// A cleaned rooted path is always local on POSIX: only Windows needs the check
if runtime.GOOS == "windows" && relPath != "" && !filepath.IsLocal(relPath) {
// path is unsafe (see https://github.com/golang/go/issues/56336#issuecomment-1416214885)
return root
}
joined := filepath.Join(root, filepath.FromSlash(relPath))
// filepath.Join also cleans the path, and cleaning strips
// the trailing slash, so we need to re-add it afterward.
// if the length is 1, then it's a path to the root,
// and that should return ".", so we don't append the separator.
if strings.HasSuffix(reqPath, "/") && len(reqPath) > 1 {
joined += separator
}
return joined
}
// splitRemoteAddr splits "host:port" leniently: a missing port is accepted.
// A malformed value such as "[" must not panic, as that would unwind out of
// the go_register_server_variables cgo callback and crash the whole process.
func splitRemoteAddr(remoteAddr string) (ip, port string) {
if host, p, err := net.SplitHostPort(remoteAddr); err == nil {
return host, p
}
// CutLast yields (remoteAddr, "") when there is no colon, i.e. no port.
ip, port, _ = strings.CutLast(remoteAddr, ":")
if len(ip) >= 2 && ip[0] == '[' && ip[len(ip)-1] == ']' {
ip = ip[1 : len(ip)-1]
}
return ip, port
}
const separator = string(filepath.Separator)
func ensureLeadingSlash(path string) string {
if path == "" || path[0] == '/' {
return path
}
return "/" + path
}
// toUnsafeChar returns a *C.char pointing at the backing bytes the Go string.
// If C does not store the string, it may be passed directly in a Cgo call (most efficient).
// If C stores the string, it must be pinned explicitly instead (inefficient).
// C may never modify the string.
func toUnsafeChar(s string) *C.char {
return (*C.char)(unsafe.Pointer(unsafe.StringData(s)))
}
// initialize a global zend_string that must never be freed and is ignored by GC
func newPersistentZendString(str string) *C.zend_string {
return C.frankenphp_init_persistent_string(toUnsafeChar(str), C.size_t(len(str)))
}
// Protocol versions, in Apache mod_ssl format: https://httpd.apache.org/docs/current/mod/mod_ssl.html
// Note that these are slightly different from SupportedProtocols in caddytls/config.go
func tlsProtocol(proto uint16) *C.zend_string {
switch proto {
case tls.VersionTLS10:
return C.frankenphp_strings.tls1
case tls.VersionTLS11:
return C.frankenphp_strings.tls11
case tls.VersionTLS12:
return C.frankenphp_strings.tls12
case tls.VersionTLS13:
return C.frankenphp_strings.tls13
default:
return C.frankenphp_strings.empty
}
}