Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions lib/ruby_proxy_headers/connection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ def initialize(proxy, options = {})
# @param target_port [Integer] Target port (default: 443)
# @return [OpenSSL::SSL::SSLSocket] TLS-wrapped socket to target
def connect(target_host, target_port = 443)
validate_connect_target!(target_host, target_port)

# Connect to proxy
@socket = TCPSocket.new(@proxy[:host], @proxy[:port])
@socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
Expand Down Expand Up @@ -132,6 +134,17 @@ def upgrade_to_tls(target_host)
@socket = ssl_socket
end

def validate_connect_target!(host, port)
if RubyProxyHeaders::INVALID_HEADER_VALUE_RE.match?(host.to_s)
raise ArgumentError,
"CONNECT target host contains invalid characters (CR, LF, or NUL): #{host.inspect}"
end
if RubyProxyHeaders::INVALID_HEADER_VALUE_RE.match?(port.to_s)
raise ArgumentError,
"CONNECT target port contains invalid characters (CR, LF, or NUL): #{port.inspect}"
end
end

def raise_connect_error
case @proxy_response_status
when 407
Expand Down
26 changes: 26 additions & 0 deletions spec/connection_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,30 @@
expect(decoded).to eq('user:pass')
end
end

describe '#connect target validation' do
let(:connection) do
described_class.new({ host: 'proxy.example.com', port: 8080 })
end

it 'rejects target_host containing CR' do
expect { connection.connect("evil.com\r\nInjected: header") }
.to raise_error(ArgumentError, /target host.*invalid/i)
end

it 'rejects target_host containing LF' do
expect { connection.connect("evil.com\nInjected: header") }
.to raise_error(ArgumentError, /target host.*invalid/i)
end

it 'rejects target_host containing NUL' do
expect { connection.connect("evil.com\0hidden") }
.to raise_error(ArgumentError, /target host.*invalid/i)
end

it 'rejects target_port containing CR' do
expect { connection.connect('example.com', "443\r\nInjected: header") }
.to raise_error(ArgumentError, /target port.*invalid/i)
end
end
end