diff --git a/lib/net/http.rb b/lib/net/http.rb index 708a7f2e..6e643e00 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,15 +1188,13 @@ def initialize(address, port = nil) # :nodoc: @proxy_port = nil @proxy_user = nil @proxy_pass = nil - @proxy_use_ssl = nil + @proxy_use_ssl = false @use_ssl = false @ssl_context = nil @ssl_session = nil + @verify_hostname = true @sspi_enabled = false - SSL_IVNAMES.each do |ivname| - instance_variable_set ivname, nil - end end # Returns a string representation of +self+: @@ -1523,26 +1519,6 @@ def use_ssl=(flag) @use_ssl = flag end - SSL_ATTRIBUTES = [ - :ca_file, - :ca_path, - :cert, - :cert_store, - :ciphers, - :extra_chain_cert, - :key, - :ssl_timeout, - :ssl_version, - :min_version, - :max_version, - :verify_callback, - :verify_depth, - :verify_mode, - :verify_hostname, - ].freeze # :nodoc: - - SSL_IVNAMES = SSL_ATTRIBUTES.map { |a| "@#{a}".to_sym }.freeze # :nodoc: - # Resolv::IPv4::Regex and Resolv::IPv6::Regex, copied from resolv 0.7.1 rather # than required, so that net/http does not load a DNS resolver just to keep an # IP address literal out of the Server Name Indication. @@ -1566,61 +1542,155 @@ def use_ssl=(flag) private_constant :IPV4_ADDRESS, :IPV6_ADDRESS + def ssl_sni_enabled?(address) + case address + when IPV4_ADDRESS, IPV6_ADDRESS + return false + end + true + end + private :ssl_sni_enabled? + + # Returns the OpenSSL::SSL::SSLContext object used for SSL/TLS sessions. + # + # The object is frozen after a session is started for the first time and + # cannot be modified afterwards. + def ssl_context + @ssl_context ||= ( + ctx = OpenSSL::SSL::SSLContext.new + ctx.set_params + + # See the note on #verify_hostname + ctx.verify_hostname = verify_hostname && ssl_sni_enabled?(@address) + + unless ctx.session_cache_mode.nil? # a dummy method on JRuby + ctx.session_cache_mode = + OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT | + OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE + end + if ctx.respond_to?(:session_new_cb) # not implemented under JRuby + ctx.session_new_cb = proc {|sock, sess| @ssl_session = sess } + end + + ctx + ) + end + + def_ssl_attr = proc do |attr| + class_eval <<~EOS, __FILE__, __LINE__ + 1 + def #{attr} + ssl_context.#{attr} + end + + def #{attr}=(value) + ssl_context.#{attr} = value + end + EOS + end + + ## + # :attr_accessor: ca_file # Sets or returns the path to a CA certification file in PEM format. - attr_accessor :ca_file + def_ssl_attr.call(:ca_file) + ## + # :attr_accessor: ca_path # Sets or returns the path of to CA directory # containing certification files in PEM format. - attr_accessor :ca_path + def_ssl_attr.call(:ca_path) + ## + # :attr_accessor: cert # Sets or returns the OpenSSL::X509::Certificate object # to be used for client certification. - attr_accessor :cert + def_ssl_attr.call(:cert) + ## + # :attr_accessor: cert_store # Sets or returns the X509::Store to be used for verifying peer certificate. - attr_accessor :cert_store + def_ssl_attr.call(:cert_store) + ## + # :attr_accessor: ciphers # Sets or returns the available SSL ciphers. # See {OpenSSL::SSL::SSLContext#ciphers=}[https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html#method-i-ciphers-3D]. - attr_accessor :ciphers + def_ssl_attr.call(:ciphers) + ## + # :attr_accessor: extra_chain_cert # Sets or returns the extra X509 certificates to be added to the certificate chain. # See {OpenSSL::SSL::SSLContext#add_certificate}[https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html#method-i-add_certificate]. - attr_accessor :extra_chain_cert + def_ssl_attr.call(:extra_chain_cert) + ## + # :attr_accessor: key # Sets or returns the OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object. - attr_accessor :key + def_ssl_attr.call(:key) + ## + # :attr_accessor: ssl_timeout # Sets or returns the SSL timeout seconds. - attr_accessor :ssl_timeout + def_ssl_attr.call(:ssl_timeout) + ## + # :attr_accessor: ssl_version # Sets or returns the SSL version. # See {OpenSSL::SSL::SSLContext#ssl_version=}[https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html#method-i-ssl_version-3D]. - attr_accessor :ssl_version + def_ssl_attr.call(:ssl_version) + ## + # :attr_accessor: min_version # Sets or returns the minimum SSL version. # See {OpenSSL::SSL::SSLContext#min_version=}[https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html#method-i-min_version-3D]. - attr_accessor :min_version + def_ssl_attr.call(:min_version) + ## + # :attr_accessor: max_version # Sets or returns the maximum SSL version. # See {OpenSSL::SSL::SSLContext#max_version=}[https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html#method-i-max_version-3D]. - attr_accessor :max_version + def_ssl_attr.call(:max_version) + ## + # :attr_accessor: verify_callback # Sets or returns the callback for the server certification verification. - attr_accessor :verify_callback + def_ssl_attr.call(:verify_callback) + ## + # :attr_accessor: verify_depth # Sets or returns the maximum depth for the certificate chain verification. - attr_accessor :verify_depth + def_ssl_attr.call(:verify_depth) + ## + # :attr_accessor: verify_mode # Sets or returns the flags for server the certification verification # at the beginning of the SSL/TLS session. # OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER are acceptable. - attr_accessor :verify_mode + def_ssl_attr.call(:verify_mode) + ## + # :attr_accessor: verify_hostname # Sets or returns whether to verify that the server certificate is valid - # for the hostname. + # for the hostname or the IP address of the server. # See {OpenSSL::SSL::SSLContext#verify_hostname=}[https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html#attribute-i-verify_hostname]. - attr_accessor :verify_hostname + #-- + # This attribute is not forwarded directly to SSLContext because the + # semantics are slightly different. + # - SSLContext#verify_hostname must be used together with SNI, which + # is unavailable when connecting to an IP address. + # - Net::HTTP#verify_hostname is expected to verify the certificate + # identity regardless of whether SNI is used. + #++ + + # :stopdoc: + def verify_hostname + @verify_hostname + end + + def verify_hostname=(value) + @verify_hostname = value + ssl_context.verify_hostname = value && ssl_sni_enabled?(@address) + end + # :startdoc: # Returns the X509 certificate chain (an array of strings) # for the session's socket peer, @@ -1692,38 +1762,32 @@ def connect if use_ssl? # reference early to load OpenSSL before connecting, # as OpenSSL may take time to load. - @ssl_context = OpenSSL::SSL::SSLContext.new + ssl_context.setup 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_sni_enabled?(proxy_address) + ssl_socket_connect(s, @open_timeout) + if proxy_ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE + 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? - 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,62 +1804,29 @@ 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 - ssl_parameters = Hash.new - iv_list = instance_variables - SSL_IVNAMES.each_with_index do |ivname, i| - if iv_list.include?(ivname) - value = instance_variable_get(ivname) - unless value.nil? - ssl_parameters[SSL_ATTRIBUTES[i]] = value - end - end - end - @ssl_context.set_params(ssl_parameters) - unless @ssl_context.session_cache_mode.nil? # a dummy method on JRuby - @ssl_context.session_cache_mode = - OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT | - OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE - end - if @ssl_context.respond_to?(:session_new_cb) # not implemented under JRuby - @ssl_context.session_new_cb = proc {|sock, sess| @ssl_session = sess } - end - - # Still do the post_connection_check below even if connecting - # to IP address - verify_hostname = @ssl_context.verify_hostname - - # Server Name Indication (SNI) RFC 3546/6066 - case @address - when IPV4_ADDRESS, IPV6_ADDRESS - # 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}..." - s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context) + 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 + # Server Name Indication (SNI) RFC 3546/6066 + s.hostname = @address if ssl_sni_enabled?(@address) if @ssl_session and Process.clock_gettime(Process::CLOCK_REALTIME) < @ssl_session.time.to_f + @ssl_session.timeout s.session = @ssl_session end ssl_socket_connect(s, @open_timeout) - if (@ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE) && verify_hostname + # See the note on #verify_hostname + if ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE && verify_hostname s.post_connection_check(@address) 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, @@ -1822,13 +1853,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 @@ -1856,14 +1896,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 +1920,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 +1946,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; @@ -1977,6 +2012,27 @@ def proxy_pass end end + # Returns +true+ if SSL is used to connect 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 + @proxy_ssl_context ||= ( + ctx = OpenSSL::SSL::SSLContext.new + ctx.set_params + ctx.verify_hostname = ssl_sni_enabled?(proxy_address) + ctx + ) + end + alias proxyaddr proxy_address #:nodoc: obsolete alias proxyport proxy_port #:nodoc: obsolete 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 -DAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQE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mUx +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 CERT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QEq1l3aIUSzMpaQV8OvZC51JM8EBGxj3r6n5iZf0b9 +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..2e917ed8 100644 --- a/test/net/http/test_https.rb +++ b/test/net/http/test_https.rb @@ -256,16 +256,37 @@ def test_min_version def test_max_version http = Net::HTTP.new(HOST, config("port")) http.use_ssl = true - http.max_version = :SSL2 + begin + http.max_version = :SSL2 + rescue OpenSSL::SSL::SSLError => e + # May fail early if SSLv2 is not supported at all by the OpenSSL release + return if /SSL_CTX_set_max_proto_version/ =~ e.message + raise + end http.cert_store = TEST_STORE @log_tester = lambda {|_| } ex = assert_raise(OpenSSL::SSL::SSLError){ http.request_get("/") {|res| } } - re_msg = /\ASSL_connect returned=1 errno=0 |SSL_CTX_set_max_proto_version|No appropriate protocol/ + re_msg = /\ASSL_connect returned=1 errno=0 |No appropriate protocol/ assert_match(re_msg, ex.message) end + def test_ssl_context + http = Net::HTTP.new(HOST, config("port")) + http.use_ssl = true + http.cert_store = TEST_STORE + assert_same(TEST_STORE, http.ssl_context.cert_store) + http.ssl_context.cert_store = OpenSSL::X509::Store.new # empty + assert_raise(OpenSSL::SSL::SSLError) { + http.request_get("/") {|res| } + } + assert_predicate(http.ssl_context, :frozen?) + assert_raise(FrozenError) { + http.cert_store = OpenSSL::X509::Store.new + } + end + def test_ractor assert_ractor(<<~RUBY, require: 'net/https') expected = #{$test_net_http_data.dump}.b @@ -286,18 +307,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 +331,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 diff --git a/test/net/http/test_https_proxy.rb b/test/net/http/test_https_proxy.rb index d90c3ff6..13b085b1 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 @@ -58,45 +59,111 @@ def test_https_proxy_rejects_crlf_in_address assert_join_threads([client_thread, server_thread]) } end +end - def read_fixture(key) +class TestNetHTTPSOverHTTPSProxy < Test::Unit::TestCase + def self.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) + 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) - _, 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]) + 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" + Socket.open(:INET, :STREAM) do |io| + ssl = OpenSSL::SSL::SSLSocket.new(io) + begin + OpenSSL::SSL::SSLSocket.new(ssl) + rescue TypeError + omit "nested SSLSocket is not supported" + end + end + + 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.ssl_context.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 + + def test_https_proxy_from_env + TestNetHTTPUtils.clean_http_proxy_env do + ENV["http_proxy"] = "https://localhost:8443" + http = Net::HTTP.new("example.test") + assert_predicate(http, :proxy_from_env?) + assert_predicate(http, :proxy_use_ssl?) + end + 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