This commit is contained in:
D'Ali Ben Macha 2026-11-14 01:26:24 -05:00 • committed by GitHub
commit 5318a69f6a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 236 additions and 0 deletions

View file

@ -134,6 +134,7 @@ var pad [maxPad]byte
var (
errNoContentLength = errors.New("request body has no known length; increase request_buffers so the body can be buffered in full to determine it")
errBadContentLength = errors.New("request body length is not a valid CONTENT_LENGTH")
errParamNameTooLong = errors.New("fastcgi param name too long")
)
// maxSurplus and maxSurplusWait bound how far a body reads on once a responder

View file

@ -0,0 +1,82 @@
package fastcgi
import (
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// A client-controlled header whose name cannot fit in a Params record fails
// the request through Transport.RoundTrip, and the backend sees the
// BeginRequest record and then EOF: no params, partial or otherwise.
func TestRoundTripRejectsOversizedHeaderName(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
t.Cleanup(func() { ln.Close() })
type received struct {
data []byte
err error
}
got := make(chan received, 1)
go func() {
conn, err := ln.Accept()
if err != nil {
got <- received{err: err}
return
}
defer conn.Close()
_ = conn.SetReadDeadline(time.Now().Add(5 * time.Second))
data, err := io.ReadAll(conn)
got <- received{data: data, err: err}
}()
// buildEnv turns the header into HTTP_X_<name>, which is longer than
// any name a record can carry.
req := httptest.NewRequest(http.MethodGet, "http://example.com/index.php", nil)
req.Header.Set("X-"+strings.Repeat("a", maxWrite), "1")
res, err := fcgiRoundTrip(t, ln.Addr().String(), req)
if !errors.Is(err, errParamNameTooLong) {
t.Fatalf("RoundTrip() error = %v, want %v", err, errParamNameTooLong)
}
if res != nil {
t.Errorf("RoundTrip() response = %v, want nil", res)
}
r := <-got
if r.err != nil {
t.Fatalf("backend read: %v (want EOF after the records)", r.err)
}
types := recordTypes(t, r.data)
if len(types) != 1 || types[0] != BeginRequest {
t.Fatalf("backend received record types %v, want only BeginRequest (%d) then EOF", types, BeginRequest)
}
}
// recordTypes returns the type of each FastCGI record in data.
func recordTypes(t *testing.T, data []byte) []uint8 {
t.Helper()
var types []uint8
for len(data) > 0 {
if len(data) < 8 {
t.Fatalf("truncated record header: %d bytes", len(data))
}
contentLength := int(data[4])<<8 | int(data[5])
size := 8 + contentLength + int(data[6])
if len(data) < size {
t.Fatalf("truncated record: %d bytes, want %d", len(data), size)
}
types = append(types, data[1])
data = data[size:]
}
return types
}

View file

@ -17,6 +17,7 @@ package fastcgi
import (
"bytes"
"encoding/binary"
"fmt"
)
// streamWriter abstracts out the separation of a stream into discrete records.
@ -76,6 +77,15 @@ func (w *streamWriter) endStream() error {
}
func (w *streamWriter) writePairs(pairs map[string]string) error {
// A name that cannot fit in a record, even with an empty value, cannot
// be sent. Check every name before writing anything, so the backend
// never receives a partial set of params.
for k := range pairs {
if len(k) > maxWrite-8 {
return fmt.Errorf("%w: %d bytes, max %d", errParamNameTooLong, len(k), maxWrite-8)
}
}
b := make([]byte, 8)
nn := 0
// init headers

View file

@ -0,0 +1,143 @@
// 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 fastcgi
import (
"bytes"
"encoding/binary"
"io"
"net"
"reflect"
"strings"
"testing"
)
func TestWritePairsOversized(t *testing.T) {
longestName := strings.Repeat("N", maxWrite-8)
tests := []struct {
name string
pairs map[string]string
want map[string]string
}{
{
name: "longest name that fits is kept with an empty value",
pairs: map[string]string{longestName: "x"},
want: map[string]string{longestName: ""},
},
{
name: "long value is truncated",
pairs: map[string]string{"K": strings.Repeat("v", maxWrite)},
want: map[string]string{"K": strings.Repeat("v", maxWrite-9)},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
data, err := writePairsToPipe(tt.pairs)
if err != nil {
t.Fatalf("writePairs: %v", err)
}
got := decodeParams(t, data)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("got %d params, want %d", len(got), len(tt.want))
for k, v := range got {
if tt.want[k] != v {
t.Errorf("param with %d-byte name has %d-byte value, want %d bytes", len(k), len(v), len(tt.want[k]))
}
}
}
})
}
}
func TestWritePairsNameTooLong(t *testing.T) {
for _, n := range []int{maxWrite - 7, maxWrite + 1} {
pairs := map[string]string{"SCRIPT_NAME": "/index.php", strings.Repeat("N", n): "x"}
if _, err := writePairsToPipe(pairs); err == nil {
t.Errorf("%d-byte name: expected an error, got none", n)
}
}
}
// writePairsToPipe writes pairs as Params records and returns the bytes
// that were sent, along with the error returned by writePairs.
func writePairsToPipe(pairs map[string]string) ([]byte, error) {
clientConn, serverConn := net.Pipe()
defer serverConn.Close()
errCh := make(chan error, 1)
go func() {
defer clientConn.Close()
w := &streamWriter{c: &client{rwc: clientConn, reqID: 1}, buf: new(bytes.Buffer), recType: Params}
errCh <- w.writePairs(pairs)
}()
data, readErr := io.ReadAll(serverConn)
if err := <-errCh; err != nil {
return data, err
}
return data, readErr
}
// decodeParams reads the name-value pairs out of a stream of Params records.
func decodeParams(t *testing.T, data []byte) map[string]string {
t.Helper()
var stream []byte
for len(data) > 0 {
if len(data) < 8 {
t.Fatalf("short record header: %d bytes", len(data))
}
if data[1] != Params {
t.Fatalf("record type %d, want %d", data[1], Params)
}
contentLen := int(binary.BigEndian.Uint16(data[4:6]))
end := 8 + contentLen + int(data[6])
if len(data) < end {
t.Fatalf("short record: %d bytes, want %d", len(data), end)
}
stream = append(stream, data[8:8+contentLen]...)
data = data[end:]
}
pairs := make(map[string]string)
for len(stream) > 0 {
var nameLen, valueLen int
nameLen, stream = decodeSize(t, stream)
valueLen, stream = decodeSize(t, stream)
if len(stream) < nameLen+valueLen {
t.Fatalf("short pair: %d bytes, want %d", len(stream), nameLen+valueLen)
}
pairs[string(stream[:nameLen])] = string(stream[nameLen : nameLen+valueLen])
stream = stream[nameLen+valueLen:]
}
return pairs
}
func decodeSize(t *testing.T, b []byte) (int, []byte) {
t.Helper()
if len(b) == 0 {
t.Fatal("missing pair length")
}
if b[0]>>7 == 0 {
return int(b[0]), b[1:]
}
if len(b) < 4 {
t.Fatalf("short pair length: %d bytes", len(b))
}
return int(binary.BigEndian.Uint32(b) &^ (1 << 31)), b[4:]
}