From 334c4ba9c74b44ff58bdbdf597042bbc35abee77 Mon Sep 17 00:00:00 2001 From: yjjnls Date: Wed, 11 Nov 2026 09:00:48 +0800 Subject: [PATCH] fix(envd): cap the /init request body at 1 MiB MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PostInit read the request body with an unbounded io.ReadAll before any auth check (auth needs the parsed access token). Any guest process that can reach the envd HTTP port could therefore send an arbitrarily large body and allocate heap until envd — the sandbox control plane, which manages file I/O, process execution, cgroup freezing, NFS mounts, and live-upgrade handover — is OOM-killed, orphaning all user processes, breaking graceful teardown, and corrupting in-progress pause/resume. Wrap the body with http.MaxBytesReader before the read and answer 413 on a MaxBytesError (the reader also makes the server close the connection after the response instead of draining the oversized remainder). 1 MiB is far above any legitimate /init payload (env vars plus a CA bundle), and keeping the whole body in one modest allocation also preserves the intent of the memguard wipe of the access token. Fixes #3563 --- packages/envd/internal/api/init.go | 20 ++++++++++ packages/envd/internal/api/init_test.go | 49 +++++++++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/packages/envd/internal/api/init.go b/packages/envd/internal/api/init.go index 8d01b9e38be..a5206193808 100644 --- a/packages/envd/internal/api/init.go +++ b/packages/envd/internal/api/init.go @@ -195,6 +195,13 @@ const thawHeader = "X-Envd-Thaw" // clock. const clockCorrectionHeader = "X-Envd-Init-Clock-Correction" +// maxInitBodyBytes caps the /init request body. The largest legitimate payload carries env +// vars and a CA bundle, both far below this. The body is read before auth (auth needs the +// parsed token), and the server sets no ReadTimeout, so an unbounded io.ReadAll would let +// any guest process that can reach the port allocate heap until envd — the sandbox's +// control plane — is OOM-killed. +const maxInitBodyBytes = 1 << 20 // 1 MiB + func (a *API) PostInit(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() @@ -237,11 +244,24 @@ func (a *API) PostInit(w http.ResponseWriter, r *http.Request) { freezeGen := a.workloadFreezer.FreezeGeneration(ctx) if r.Body != nil { + // Cap the body before reading it: the read runs before auth, so this is + // the only thing standing between an unauthenticated oversized request + // and an OOM. MaxBytesError also makes the server close the connection + // after the response instead of draining the oversized remainder. + r.Body = http.MaxBytesReader(w, r.Body, maxInitBodyBytes) + // Read raw body so we can wipe it after parsing body, err := io.ReadAll(r.Body) // Ensure body is wiped after we're done defer memguard.WipeBytes(body) if err != nil { + var maxBytesErr *http.MaxBytesError + if errors.As(err, &maxBytesErr) { + logger.Warn().Msg("Request body exceeds the /init size limit") + w.WriteHeader(http.StatusRequestEntityTooLarge) + + return + } logger.Error().Msgf("Failed to read request body: %v", err) w.WriteHeader(http.StatusBadRequest) diff --git a/packages/envd/internal/api/init_test.go b/packages/envd/internal/api/init_test.go index 0951e832a19..dd3f5f0206d 100644 --- a/packages/envd/internal/api/init_test.go +++ b/packages/envd/internal/api/init_test.go @@ -1225,3 +1225,52 @@ func TestPostInit_UnauthorizedDoesNotUnfreeze(t *testing.T) { assert.Equal(t, http.StatusUnauthorized, rec.Code) assert.Empty(t, mgr.unfreezeAttempts, "unauthorized /init must not attempt unfreeze") } + +// An oversized /init body must be rejected before it can be parsed or applied: +// the body is read before auth, so the size cap is the only thing standing +// between an unauthenticated oversized request and an envd OOM. +func TestPostInit_RejectsOversizedBody(t *testing.T) { + t.Parallel() + + mgr := &fakeCgroupManager{} + api := newAPIWithCgroupManager(mgr) + api.isNotFC = true + + // One byte past the cap. Well-formed JSON is irrelevant: the read itself + // must fail first. + body := bytes.Repeat([]byte{'a'}, maxInitBodyBytes+1) + + req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/init", bytes.NewReader(body)) + require.NoError(t, err) + rec := httptest.NewRecorder() + api.PostInit(rec, req) + + assert.Equal(t, http.StatusRequestEntityTooLarge, rec.Code) + assert.Empty(t, mgr.unfreezeAttempts, "rejected /init must not attempt unfreeze") +} + +// A body at the cap is still accepted. +func TestPostInit_AcceptsBodyAtSizeCap(t *testing.T) { + t.Parallel() + + mgr := &fakeCgroupManager{} + api := newAPIWithCgroupManager(mgr) + api.isNotFC = true + + // Padding inside the cap, via an env var value. + value := strings.Repeat("x", maxInitBodyBytes-64) + body, err := json.Marshal(PostInitJSONBody{ + EnvVars: &EnvVars{"PADDING": value}, + }) + require.NoError(t, err) + require.Less(t, len(body), maxInitBodyBytes) + + req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "/init", bytes.NewReader(body)) + require.NoError(t, err) + rec := httptest.NewRecorder() + api.PostInit(rec, req) + + require.Equal(t, http.StatusNoContent, rec.Code) + _, ok := api.defaults.EnvVars.Load("PADDING") + assert.True(t, ok, "body at the cap should still be applied") +}