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 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 } }