From 9d8c7f6cae8bd864cb5e9311f6c03036e1784cfa Mon Sep 17 00:00:00 2001 From: Kazuki Yamaguchi Date: Sun, 21 Jun 2026 23:12:55 +0900 Subject: [PATCH 1/3] Add HTTPS tests with iPAddress SAN Add a new test case to confirm the current behavior. Commit fa68e64beee8 fixed the handling of certificate identity check when connecting to an IP address, but the happy path is currently not covered by the test suite. --- test/net/fixtures/Makefile | 11 +++++--- test/net/fixtures/server.crt | 39 +++++++++++++++-------------- test/net/fixtures/server_ip_san.crt | 22 ++++++++++++++++ test/net/http/test_https.rb | 32 ++++++++++++++++++----- 4 files changed, 75 insertions(+), 29 deletions(-) create mode 100644 test/net/fixtures/server_ip_san.crt diff --git a/test/net/fixtures/Makefile b/test/net/fixtures/Makefile index 88c232e3..2b37c0bb 100644 --- a/test/net/fixtures/Makefile +++ b/test/net/fixtures/Makefile @@ -7,9 +7,12 @@ regen_certs: cacert.pem: server.key openssl req -new -x509 -days 3650 -key server.key -out cacert.pem -subj "/C=JP/ST=Shimane/L=Matz-e city/O=Ruby Core Team/CN=Ruby Test CA/emailAddress=security@ruby-lang.org" -server.csr: - openssl req -new -key server.key -out server.csr -subj "/C=JP/ST=Shimane/O=Ruby Core Team/OU=Ruby Test/CN=localhost" +server.crt: cacert.pem + openssl req -new -key server.key -out server.csr -subj "/C=JP/ST=Shimane/O=Ruby Core Team/OU=Ruby Test/CN=Server 1" -addext "subjectAltName = DNS:localhost" + openssl x509 -days 3650 -CA cacert.pem -CAkey server.key -set_serial 00 -in server.csr -req -copy_extensions copy -out server.crt + rm server.csr -server.crt: server.csr cacert.pem - openssl x509 -days 3650 -CA cacert.pem -CAkey server.key -set_serial 00 -in server.csr -req -out server.crt +server_ip_san.crt: cacert.pem + openssl req -new -key server.key -out server.csr -subj "/C=JP/ST=Shimane/O=Ruby Core Team/OU=Ruby Test/CN=Server 2" -addext "subjectAltName = IP:127.0.0.1,IP:::1" + openssl x509 -days 3650 -CA cacert.pem -CAkey server.key -set_serial 01 -in server.csr -req -copy_extensions copy -out server_ip_san.crt rm server.csr diff --git a/test/net/fixtures/server.crt b/test/net/fixtures/server.crt index 5d292379..23d5efd5 100644 --- a/test/net/fixtures/server.crt +++ b/test/net/fixtures/server.crt @@ -1,21 +1,22 @@ -----BEGIN CERTIFICATE----- -MIIDYTCCAkkCAQAwDQYJKoZIhvcNAQELBQAwgYwxCzAJBgNVBAYTAkpQMRAwDgYD -VQQIDAdTaGltYW5lMRQwEgYDVQQHDAtNYXR6LWUgY2l0eTEXMBUGA1UECgwOUnVi -eSBDb3JlIFRlYW0xFTATBgNVBAMMDFJ1YnkgVGVzdCBDQTElMCMGCSqGSIb3DQEJ -ARYWc2VjdXJpdHlAcnVieS1sYW5nLm9yZzAeFw0yNDAxMDExMTQ3MjNaFw0zMzEy -MjkxMTQ3MjNaMGAxCzAJBgNVBAYTAkpQMRAwDgYDVQQIDAdTaGltYW5lMRcwFQYD -VQQKDA5SdWJ5IENvcmUgVGVhbTESMBAGA1UECwwJUnVieSBUZXN0MRIwEAYDVQQD -DAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCw+egZ -Q6eumJKq3hfKfED4dE/tL4FI5sjqont9ABVI+1GSqyi1bFBgsRjM0THllIdMbKmJ -tWwnKW8J+5OgNN8y6Xxv8JmM/Y5vQt2lis0fqXmG8UTz0VTWdlAXXmhUs6lSADvA -aIe4RVrCsZ97L3ZQTryY7JRVcbB4khUN3Gp0yg+801SXzoFTTa+UGIRLE66jH51a -a5VXu99hnv1OiH8tQrjdi8mH6uG/icq4XuIeNWMF32wHqIOOPvQcWV3M5D2vxJEj -702Ku6k9OQXkAo17qRSEonWW4HtLbtmS8He1JNPc/n3dVUm+fM6NoDXPoLP7j55G -9zKyqGtGAWXAj1MTAgMBAAEwDQYJKoZIhvcNAQELBQADggEBACtGNdj5TEtnJBYp -M+LhBeU3oNteldfycEm993gJp6ghWZFg23oX8fVmyEeJr/3Ca9bAgDqg0t9a0npN -oWKEY6wVKqcHgu3gSvThF5c9KhGbeDDmlTSVVNQmXWX0K2d4lS2cwZHH8mCm2mrY -PDqlEkSc7k4qSiqigdS8i80Yk+lDXWsm8CjsiC93qaRM7DnS0WPQR0c16S95oM6G -VklFKUSDAuFjw9aVWA/nahOucjn0w5fVW6lyIlkBslC1ChlaDgJmvhz+Ol3iMsE0 -kAmFNu2KKPVrpMWaBID49QwQTDyhetNLaVVFM88iUdA9JDoVMEuP1mm39JqyzHTu -uBrdP4Q= +MIIDnjCCAoagAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UEBhMCSlAx +EDAOBgNVBAgMB1NoaW1hbmUxFDASBgNVBAcMC01hdHotZSBjaXR5MRcwFQYDVQQK +DA5SdWJ5IENvcmUgVGVhbTEVMBMGA1UEAwwMUnVieSBUZXN0IENBMSUwIwYJKoZI +hvcNAQkBFhZzZWN1cml0eUBydWJ5LWxhbmcub3JnMB4XDTI2MDYyMTEzMTQ0M1oX +DTM2MDYxODEzMTQ0M1owXzELMAkGA1UEBhMCSlAxEDAOBgNVBAgMB1NoaW1hbmUx +FzAVBgNVBAoMDlJ1YnkgQ29yZSBUZWFtMRIwEAYDVQQLDAlSdWJ5IFRlc3QxETAP +BgNVBAMMCFNlcnZlciAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA +sPnoGUOnrpiSqt4XynxA+HRP7S+BSObI6qJ7fQAVSPtRkqsotWxQYLEYzNEx5ZSH +TGypibVsJylvCfuToDTfMul8b/CZjP2Ob0LdpYrNH6l5hvFE89FU1nZQF15oVLOp +UgA7wGiHuEVawrGfey92UE68mOyUVXGweJIVDdxqdMoPvNNUl86BU02vlBiESxOu +ox+dWmuVV7vfYZ79Toh/LUK43YvJh+rhv4nKuF7iHjVjBd9sB6iDjj70HFldzOQ9 +r8SRI+9NirupPTkF5AKNe6kUhKJ1luB7S27ZkvB3tSTT3P593VVJvnzOjaA1z6Cz ++4+eRvcysqhrRgFlwI9TEwIDAQABozcwNTAUBgNVHREEDTALgglsb2NhbGhvc3Qw +HQYDVR0OBBYEFIkZWV4O8Wn1y71H4TT84pjMaTCRMA0GCSqGSIb3DQEBCwUAA4IB +AQCUav+Av881U4D5HXYaU4JH3AYLP3pmaCAnaASbkCV5WjjIo8A4jLC5FrgibaQc +4vw4JdHaO8JK05qb61rtzQLPyk8fIrV8LAcisBMBRnawgo98EB6OVXjpgKSRm4YU +7SlYpnO+D9jMc1ECl8K1ILQyuT4+zgEFREZLNGjKuaJXDExD8JPhT7DumJ5XMGoI +2r2YWCfnsef1RbGtze30nAJqcf6XrHyn95VU70AV45yXuE/FOZDb8dX90n1K3Frm +ebqT0Q8smwLB+R9+BhWjhlW3oj8hLtsLBPz5U7Fp4rg2nMoOSvrrqgkRyhoxzJie +R+WNFodMHu0PxkmSGD37G76S -----END CERTIFICATE----- diff --git a/test/net/fixtures/server_ip_san.crt b/test/net/fixtures/server_ip_san.crt new file mode 100644 index 00000000..505a08cd --- /dev/null +++ b/test/net/fixtures/server_ip_san.crt @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDqzCCApOgAwIBAgIBATANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UEBhMCSlAx +EDAOBgNVBAgMB1NoaW1hbmUxFDASBgNVBAcMC01hdHotZSBjaXR5MRcwFQYDVQQK +DA5SdWJ5IENvcmUgVGVhbTEVMBMGA1UEAwwMUnVieSBUZXN0IENBMSUwIwYJKoZI +hvcNAQkBFhZzZWN1cml0eUBydWJ5LWxhbmcub3JnMB4XDTI2MDYyMTEzMTQ0M1oX +DTM2MDYxODEzMTQ0M1owXzELMAkGA1UEBhMCSlAxEDAOBgNVBAgMB1NoaW1hbmUx +FzAVBgNVBAoMDlJ1YnkgQ29yZSBUZWFtMRIwEAYDVQQLDAlSdWJ5IFRlc3QxETAP +BgNVBAMMCFNlcnZlciAyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA +sPnoGUOnrpiSqt4XynxA+HRP7S+BSObI6qJ7fQAVSPtRkqsotWxQYLEYzNEx5ZSH +TGypibVsJylvCfuToDTfMul8b/CZjP2Ob0LdpYrNH6l5hvFE89FU1nZQF15oVLOp +UgA7wGiHuEVawrGfey92UE68mOyUVXGweJIVDdxqdMoPvNNUl86BU02vlBiESxOu +ox+dWmuVV7vfYZ79Toh/LUK43YvJh+rhv4nKuF7iHjVjBd9sB6iDjj70HFldzOQ9 +r8SRI+9NirupPTkF5AKNe6kUhKJ1luB7S27ZkvB3tSTT3P593VVJvnzOjaA1z6Cz ++4+eRvcysqhrRgFlwI9TEwIDAQABo0QwQjAhBgNVHREEGjAYhwR/AAABhxAAAAAA +AAAAAAAAAAAAAAABMB0GA1UdDgQWBBSJGVleDvFp9cu9R+E0/OKYzGkwkTANBgkq +hkiG9w0BAQsFAAOCAQEAi8zbc22L5+8UGjXftk2Dfg814rsholLK4h8eXHptRh1k +cqRJ0DrXn1SbiavBAkRUBeh07CtSOaxq/LP9ZiJHAcZ99+ZDVG0BRmg4esh9LEiV +FuM7piCfdsDRBfzk25Ko8lQEq1l3aIUSzMpaQV8OvZC51JM8EBGxj3r6n5iZf0b9 +3yKVZme1l2mnMSvCeJ9VY1FCnIEwF1WTzBgOQLQOu4zRlR1O0xtn4+KIL79F7XSE +HB0Sni8krQA7tDprMQsKLoLmvPpFrkTHyR3D7/BTvsE3N0k6cPV9WJTg4wOyT4JC +7Gm1sdFNKo2MhdE/YXKqb5+rv2ILfezwtdcVlB23wQ== +-----END CERTIFICATE----- diff --git a/test/net/http/test_https.rb b/test/net/http/test_https.rb index 7f71704b..90701644 100644 --- a/test/net/http/test_https.rb +++ b/test/net/http/test_https.rb @@ -286,18 +286,19 @@ def test_ractor end if defined?(Ractor) && Ractor.method_defined?(:value) end -class TestNetHTTPSIdentityVerifyFailure < Test::Unit::TestCase +class TestNetHTTPSIPAddressCertificate < Test::Unit::TestCase include TestNetHTTPUtils def self.read_fixture(key) File.read(File.expand_path("../fixtures/#{key}", __dir__)) end + # Certificate subjectAltName contains IP addresses 127.0.0.1 but no DNS names HOST = 'localhost' HOST_IP = '127.0.0.1' CA_CERT = OpenSSL::X509::Certificate.new(read_fixture("cacert.pem")) SERVER_KEY = OpenSSL::PKey.read(read_fixture("server.key")) - SERVER_CERT = OpenSSL::X509::Certificate.new(read_fixture("server.crt")) + SERVER_CERT = OpenSSL::X509::Certificate.new(read_fixture("server_ip_san.crt")) TEST_STORE = OpenSSL::X509::Store.new.tap {|s| s.add_cert(CA_CERT) } CONFIG = { @@ -309,17 +310,36 @@ def self.read_fixture(key) 'ssl_private_key' => SERVER_KEY, } - def test_identity_verify_failure - # the certificate's subject has CN=localhost + def test_identity_verify_success http = Net::HTTP.new(HOST_IP, config("port")) http.use_ssl = true http.cert_store = TEST_STORE + http.request_get("/") {|res| + assert_equal($test_net_http_data, res.body) + } + end + + def test_identity_verify_failure + http = Net::HTTP.new("172.0.0.2", config("port")) + http.ipaddr = HOST_IP + http.use_ssl = true + http.cert_store = TEST_STORE @log_tester = lambda {|_| } ex = assert_raise(OpenSSL::SSL::SSLError){ http.request_get("/") {|res| } - sleep 0.5 } - re_msg = /certificate verify failed|hostname \"#{HOST_IP}\" does not match/ + re_msg = /certificate verify failed|hostname .* does not match/ assert_match(re_msg, ex.message) end + + def test_identity_verify_disabled + http = Net::HTTP.new("172.0.0.2", config("port")) + http.ipaddr = HOST_IP + http.use_ssl = true + http.cert_store = TEST_STORE + http.verify_hostname = false + http.request_get("/") {|res| + assert_equal($test_net_http_data, res.body) + } + end end From edc18336e8174b7125b9e00a658137f92f5c74bc Mon Sep 17 00:00:00 2001 From: Kazuki Yamaguchi Date: Fri, 27 Nov 2026 19:35:50 +0900 Subject: [PATCH 2/3] Revert "implement talking SSL to the proxy too" This reverts commit ae2d83f88b122feb1cc9ec3b2a7d1f4a008d7f32. The commit is very incomplete and not actually usable. --- lib/net/http.rb | 28 ++++----------------- test/net/http/test_https_proxy.rb | 41 ------------------------------- 2 files changed, 5 insertions(+), 64 deletions(-) diff --git a/lib/net/http.rb b/lib/net/http.rb index 09b898db..82c7d805 100644 --- a/lib/net/http.rb +++ b/lib/net/http.rb @@ -1100,7 +1100,7 @@ class << HTTP # For proxy-defining arguments +p_addr+ through +p_no_proxy+, # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server]. # - def HTTP.new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, p_no_proxy = nil, p_use_ssl = nil) + def HTTP.new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, p_no_proxy = nil) http = super address, port if proxy_class? then # from Net::HTTP::Proxy() @@ -1109,7 +1109,6 @@ def HTTP.new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_p http.proxy_port = @proxy_port http.proxy_user = @proxy_user http.proxy_pass = @proxy_pass - http.proxy_use_ssl = @proxy_use_ssl elsif p_addr == :ENV then http.proxy_from_env = true else @@ -1121,7 +1120,6 @@ def HTTP.new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_p http.proxy_port = p_port || default_port http.proxy_user = p_user http.proxy_pass = p_pass - http.proxy_use_ssl = p_use_ssl end http @@ -1190,7 +1188,6 @@ def initialize(address, port = nil) # :nodoc: @proxy_port = nil @proxy_user = nil @proxy_pass = nil - @proxy_use_ssl = nil @use_ssl = false @ssl_context = nil @@ -1326,10 +1323,6 @@ def response_body_encoding=(value) # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server]. attr_writer :proxy_pass - # Sets whether the proxy uses SSL; - # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server]. - attr_writer :proxy_use_ssl - # Returns the IP address for the connection. # # If the session has not been started, @@ -1717,13 +1710,7 @@ def connect debug "opened" if use_ssl? if proxy? - if @proxy_use_ssl - proxy_sock = OpenSSL::SSL::SSLSocket.new(s) - ssl_socket_connect(proxy_sock, @open_timeout) - else - proxy_sock = s - end - proxy_sock = BufferedIO.new(proxy_sock, read_timeout: @read_timeout, + plain_sock = BufferedIO.new(s, read_timeout: @read_timeout, write_timeout: @write_timeout, continue_timeout: @continue_timeout, debug_output: @debug_output) @@ -1740,8 +1727,8 @@ def connect buf << "Proxy-Authorization: Basic #{credential}\r\n" end buf << "\r\n" - proxy_sock.write(buf) - HTTPResponse.read_new(proxy_sock).value + plain_sock.write(buf) + HTTPResponse.read_new(plain_sock).value # assuming nothing left in buffers after successful CONNECT response end @@ -1856,14 +1843,13 @@ def do_finish @proxy_port = nil @proxy_user = nil @proxy_pass = nil - @proxy_use_ssl = nil # Creates an \HTTP proxy class which behaves like \Net::HTTP, but # performs all access via the specified proxy. # # This class is obsolete. You may pass these same parameters directly to # \Net::HTTP.new. See Net::HTTP.new for details of the arguments. - def HTTP.Proxy(p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, p_use_ssl = nil) #:nodoc: + def HTTP.Proxy(p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil) #:nodoc: return self unless p_addr Class.new(self) { @@ -1881,7 +1867,6 @@ def HTTP.Proxy(p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, p_use_ss @proxy_user = p_user @proxy_pass = p_pass - @proxy_use_ssl = p_use_ssl } end @@ -1908,9 +1893,6 @@ def proxy_class? # Returns the password for accessing the proxy, or +nil+ if none; # see Net::HTTP@Proxy+Server. attr_reader :proxy_pass - - # Use SSL when talking to the proxy. If Net::HTTP does not use a proxy, nil. - attr_reader :proxy_use_ssl end # Returns +true+ if a proxy server is defined, +false+ otherwise; diff --git a/test/net/http/test_https_proxy.rb b/test/net/http/test_https_proxy.rb index d90c3ff6..a6a37429 100644 --- a/test/net/http/test_https_proxy.rb +++ b/test/net/http/test_https_proxy.rb @@ -58,45 +58,4 @@ def test_https_proxy_rejects_crlf_in_address assert_join_threads([client_thread, server_thread]) } end - - def read_fixture(key) - File.read(File.expand_path("../fixtures/#{key}", __dir__)) - end - - def test_https_proxy_ssl_connection - TCPServer.open("127.0.0.1", 0) {|tcpserver| - ctx = OpenSSL::SSL::SSLContext.new - ctx.key = OpenSSL::PKey.read(read_fixture("server.key")) - ctx.cert = OpenSSL::X509::Certificate.new(read_fixture("server.crt")) - serv = OpenSSL::SSL::SSLServer.new(tcpserver, ctx) - - _, port, _, _ = serv.addr - client_thread = Thread.new { - proxy = Net::HTTP.Proxy("127.0.0.1", port, 'user', 'password', true) - http = proxy.new("foo.example.org", 8000) - http.use_ssl = true - http.verify_mode = OpenSSL::SSL::VERIFY_NONE - begin - http.start - rescue EOFError - end - } - server_thread = Thread.new { - sock = serv.accept - begin - proxy_request = sock.gets("\r\n\r\n") - assert_equal( - "CONNECT foo.example.org:8000 HTTP/1.1\r\n" + - "Host: foo.example.org:8000\r\n" + - "Proxy-Authorization: Basic dXNlcjpwYXNzd29yZA==\r\n" + - "\r\n", - proxy_request, - "[ruby-core:96672]") - ensure - sock.close - end - } - assert_join_threads([client_thread, server_thread]) - } - end end From 1623842bab0d024578a66a1e4fddf6b81426b52b Mon Sep 17 00:00:00 2001 From: Kazuki Yamaguchi Date: Fri, 27 Nov 2026 19:35:42 +0900 Subject: [PATCH 3/3] Add support for HTTPS proxy (again) Add Net::HTTP#proxy_use_ssl= to connect to the proxy server over TLS. Also enable TLS automatically when the proxy setting taken from the environment variables has the https scheme. Making HTTPS requests through an HTTPS proxy requires ruby/openssl 4.1, which supports nesting OpenSSL::SSL::SSLSocket objects. --- lib/net/http.rb | 102 ++++++++++++++++++++++-------- test/net/http/test_http.rb | 20 ++++++ test/net/http/test_https_proxy.rb | 93 ++++++++++++++++++++++++++- 3 files changed, 188 insertions(+), 27 deletions(-) diff --git a/lib/net/http.rb b/lib/net/http.rb index 82c7d805..b32dad65 100644 --- a/lib/net/http.rb +++ b/lib/net/http.rb @@ -622,6 +622,10 @@ class HTTPHeaderSyntaxError < StandardError; end # Returns the proxy user name. # - {:proxy_user=}[rdoc-ref:Net::HTTP#proxy_user=]: # Sets the proxy user. + # - {#proxy_use_ssl?}[rdoc-ref:Net::HTTP#proxy_use_ssl?]: + # Returns whether TLS is used for connection to the proxy server. + # - {:proxy_use_ssl=}[rdoc-ref:Net::HTTP#proxy_use_ssl=]: + # Sets whether TLS is used for connection to the proxy server. # # === Security # @@ -1100,7 +1104,7 @@ class << HTTP # For proxy-defining arguments +p_addr+ through +p_no_proxy+, # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server]. # - def HTTP.new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, p_no_proxy = nil) + def HTTP.new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, p_no_proxy = nil, p_use_ssl = false) http = super address, port if proxy_class? then # from Net::HTTP::Proxy() @@ -1120,6 +1124,7 @@ def HTTP.new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_p http.proxy_port = p_port || default_port http.proxy_user = p_user http.proxy_pass = p_pass + http.proxy_use_ssl = p_use_ssl end http @@ -1188,6 +1193,7 @@ def initialize(address, port = nil) # :nodoc: @proxy_port = nil @proxy_user = nil @proxy_pass = nil + @proxy_use_ssl = false @use_ssl = false @ssl_context = nil @@ -1323,6 +1329,10 @@ def response_body_encoding=(value) # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server]. attr_writer :proxy_pass + # Sets whether TLS is used for the connection to the proxy server; + # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server]. + attr_writer :proxy_use_ssl + # Returns the IP address for the connection. # # If the session has not been started, @@ -1559,6 +1569,15 @@ def use_ssl=(flag) private_constant :IPV4_ADDRESS, :IPV6_ADDRESS + def ssl_use_sni_for?(address) + case address + when IPV4_ADDRESS, IPV6_ADDRESS + return false + end + true + end + private :ssl_use_sni_for? + # Sets or returns the path to a CA certification file in PEM format. attr_accessor :ca_file @@ -1682,32 +1701,33 @@ def do_start private :do_start def connect - if use_ssl? + if use_ssl? || proxy_use_ssl? # reference early to load OpenSSL before connecting, # as OpenSSL may take time to load. - @ssl_context = OpenSSL::SSL::SSLContext.new + OpenSSL end - if proxy? then - conn_addr = proxy_address - conn_port = proxy_port + if proxy? + debug "opening connection to proxy server #{proxy_address}:#{proxy_port}..." + s = timeouted_connect(proxy_address, proxy_port) + if proxy_use_ssl? + debug "starting SSL for #{proxy_address}:#{proxy_port}..." + s = OpenSSL::SSL::SSLSocket.new(s, proxy_ssl_context) + s.sync_close = true + s.hostname = proxy_address if ssl_use_sni_for?(proxy_address) + ssl_socket_connect(s, @open_timeout) + if proxy_ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE && + !ssl_use_sni_for?(proxy_address) + s.post_connection_check(proxy_address) + end + debug "SSL established to proxy server, " \ + "protocol: #{s.ssl_version}, cipher: #{s.cipher[0]}" + end else - conn_addr = conn_address - conn_port = port + debug "opening connection to #{conn_address}:#{port}..." + s = timeouted_connect(conn_address, port) end - debug "opening connection to #{conn_addr}:#{conn_port}..." - begin - s = timeouted_connect(conn_addr, conn_port) - rescue => e - if (defined?(IO::TimeoutError) && e.is_a?(IO::TimeoutError)) || e.is_a?(Errno::ETIMEDOUT) # for compatibility with previous versions - e = Net::OpenTimeout.new(e) - end - raise e, "Failed to open TCP connection to " + - "#{conn_addr}:#{conn_port} (#{e.message})" - end - s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) - debug "opened" if use_ssl? if proxy? plain_sock = BufferedIO.new(s, read_timeout: @read_timeout, @@ -1742,6 +1762,7 @@ def connect end end end + @ssl_context = OpenSSL::SSL::SSLContext.new @ssl_context.set_params(ssl_parameters) unless @ssl_context.session_cache_mode.nil? # a dummy method on JRuby @ssl_context.session_cache_mode = @@ -1757,18 +1778,17 @@ def connect verify_hostname = @ssl_context.verify_hostname # Server Name Indication (SNI) RFC 3546/6066 - case @address - when IPV4_ADDRESS, IPV6_ADDRESS + if ssl_use_sni_for?(@address) + ssl_host_address = @address + else # don't set SNI, as IP addresses in SNI is not valid # per RFC 6066, section 3. # Avoid openssl warning @ssl_context.verify_hostname = false - else - ssl_host_address = @address end - debug "starting SSL for #{conn_addr}:#{conn_port}..." + debug "starting SSL for #{conn_address}:#{port}..." s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context) s.sync_close = true s.hostname = ssl_host_address if s.respond_to?(:hostname=) && ssl_host_address @@ -1783,6 +1803,7 @@ def connect end debug "SSL established, protocol: #{s.ssl_version}, cipher: #{s.cipher[0]}" end + @socket = BufferedIO.new(s, read_timeout: @read_timeout, write_timeout: @write_timeout, continue_timeout: @continue_timeout, @@ -1809,13 +1830,22 @@ def connect private_constant :TCP_SOCKET_NEW_HAS_OPEN_TIMEOUT def timeouted_connect(conn_addr, conn_port) - if TCP_SOCKET_NEW_HAS_OPEN_TIMEOUT + s = if TCP_SOCKET_NEW_HAS_OPEN_TIMEOUT TCPSocket.open(conn_addr, conn_port, @local_host, @local_port, open_timeout: @open_timeout) else Timeout.timeout(@open_timeout, Net::OpenTimeout) { TCPSocket.open(conn_addr, conn_port, @local_host, @local_port) } end + s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) + s + rescue => e + s&.close + if (defined?(IO::TimeoutError) && e.is_a?(IO::TimeoutError)) || e.is_a?(Errno::ETIMEDOUT) # for compatibility with previous versions + e = Net::OpenTimeout.new(e) + end + raise e, "Failed to open TCP connection to " + + "#{conn_addr}:#{conn_port} (#{e.message})" end private :timeouted_connect @@ -1959,6 +1989,26 @@ def proxy_pass end end + # Returns whether TLS is used for the connection to the proxy server; + # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server]. + def proxy_use_ssl? + if @proxy_from_env + proxy_uri&.scheme == "https" + else + @proxy_use_ssl + end + end + + # Returns the OpenSSL::SSL::SSLContext object used for SSL/TLS sessions + # with the proxy server. + def proxy_ssl_context # :nodoc: + @proxy_ssl_context ||= ( + ctx = OpenSSL::SSL::SSLContext.new + ctx.set_params + ctx + ) + end + alias proxyaddr proxy_address #:nodoc: obsolete alias proxyport proxy_port #:nodoc: obsolete diff --git a/test/net/http/test_http.rb b/test/net/http/test_http.rb index 5cccb06e..ddaa4103 100644 --- a/test/net/http/test_http.rb +++ b/test/net/http/test_http.rb @@ -118,9 +118,18 @@ def test_proxy_address TestNetHTTPUtils.clean_http_proxy_env do http = Net::HTTP.new 'hostname.example', nil, 'proxy.example' assert_equal 'proxy.example', http.proxy_address + assert_equal 80, http.proxy_port http = Net::HTTP.new 'hostname.example', nil assert_equal nil, http.proxy_address + + http = Net::HTTP.new 'hostname.example', nil, + 'proxy.example', 8000, 'user', 'pass', 'invalid', true + assert_equal 'proxy.example', http.proxy_address + assert_equal 8000, http.proxy_port + assert_equal 'user', http.proxy_user + assert_equal 'pass', http.proxy_pass + assert_equal true, http.proxy_use_ssl? end end @@ -195,6 +204,17 @@ def test_proxy_eh_ENV_with_urlencoded_user end end + def test_proxy_eh_ENV_https_proxy + TestNetHTTPUtils.clean_http_proxy_env do + ENV['http_proxy'] = 'https://proxy.example:8000' + + http = Net::HTTP.new 'hostname.example' + + assert_equal true, http.proxy? + assert_equal true, http.proxy_use_ssl? + end + end + def test_proxy_eh_ENV_none_set TestNetHTTPUtils.clean_http_proxy_env do assert_equal false, Net::HTTP.new('hostname.example').proxy? diff --git a/test/net/http/test_https_proxy.rb b/test/net/http/test_https_proxy.rb index a6a37429..d04cfd8b 100644 --- a/test/net/http/test_https_proxy.rb +++ b/test/net/http/test_https_proxy.rb @@ -4,10 +4,11 @@ rescue LoadError end require 'test/unit' +require_relative 'utils' return unless defined?(OpenSSL::SSL) -class HTTPSProxyTest < Test::Unit::TestCase +class TestNetHTTPSOverProxy < Test::Unit::TestCase def test_https_proxy_authentication TCPServer.open("127.0.0.1", 0) {|serv| _, port, _, _ = serv.addr @@ -59,3 +60,93 @@ def test_https_proxy_rejects_crlf_in_address } end end + +class TestNetHTTPSOverHTTPSProxy < Test::Unit::TestCase + def self.read_fixture(key) + File.read(File.expand_path("../fixtures/#{key}", __dir__)) + end + + PROXY_CERT = OpenSSL::X509::Certificate.new(read_fixture("server.crt")) + SERVER_KEY = OpenSSL::PKey.read(read_fixture("server.key")) + SERVER_CERT = OpenSSL::X509::Certificate.new(read_fixture("server_ip_san.crt")) + CA_CERT = OpenSSL::X509::Certificate.new(read_fixture("cacert.pem")) + TEST_STORE = OpenSSL::X509::Store.new.add_cert(CA_CERT) + + def teardown + @server&.shutdown + end + + def test_http_over_https_proxy + proxy_port = spawn_https_proxy do |method, path, headers, socket| + str = "#{method} #{path}" + socket << "HTTP/1.1 200 OK\r\n" + socket << "Content-Length: #{str.bytesize}\r\n\r\n" + socket << str + end + + http = Net::HTTP.new("example.test", 80, "localhost", proxy_port) + http.proxy_use_ssl = true + http.proxy_ssl_context.cert_store = TEST_STORE + assert_equal("GET http://example.test/path", http.get("/path").body) + end + + def test_https_over_https_proxy + omit "nested SSLSocket is not supported" unless OpenSSL::VERSION >= "4.1" + + origin_context = OpenSSL::SSL::SSLContext.new + origin_context.add_certificate(SERVER_CERT, SERVER_KEY) + + connect = nil + proxy_port = spawn_https_proxy do |method, path, headers, socket| + connect = "#{method} #{path}" + socket << "HTTP/1.1 200 Connection Established\r\n\r\n" + origin = OpenSSL::SSL::SSLSocket.new(socket, origin_context) + origin.accept + + str = origin.gets("\r\n\r\n") + origin << "HTTP/1.1 200 OK\r\n" + origin << "Content-Length: #{str.bytesize}\r\n\r\n" + origin << str + origin.close + end + + http = Net::HTTP.new("127.0.0.1", 443, "localhost", proxy_port) + http.proxy_use_ssl = true + http.proxy_ssl_context.cert_store = TEST_STORE + http.use_ssl = true + http.cert_store = TEST_STORE + + body = http.get("/path").body + assert_equal("CONNECT 127.0.0.1:443", connect) + assert_match(%r{^GET /path HTTP/1.1\r\n}, body) + assert_match(%r{^Host: 127.0.0.1\r\n}, body) + end + + def test_proxy_certificate_validation + proxy_port = spawn_https_proxy {} + http = Net::HTTP.new("example.test", 80, "127.0.0.1", proxy_port) + http.proxy_use_ssl = true + e = assert_raise(OpenSSL::SSL::SSLError) { http.start {} } + assert_match(/certificate verify failed/, e.message) + + http = Net::HTTP.new("example.test", 80, "127.0.0.1", proxy_port) + http.proxy_use_ssl = true + http.proxy_ssl_context.cert_store = TEST_STORE + e = assert_raise(OpenSSL::SSL::SSLError) { http.start {} } + assert_match(/certificate verify failed|hostname .* does not match/, e.message) + end + + private + + def spawn_https_proxy(&handler) + config = { + 'host' => '127.0.0.1', + 'ssl_enable' => true, + 'ssl_certificate' => PROXY_CERT, + 'ssl_private_key' => SERVER_KEY, + } + @server = TestNetHTTPUtils::HTTPServer.new(config, &handler) + @server.start + @server.port + end +end