Ruby
Mechanize

MechanizeでTLSv1を使用して暗号化通信するサーバー上のページにアクセスできない問題の対処法

More than 5 years have passed since last update.

問題の概要

MechanizeでTLSv1を使用して暗号化通信するサーバー上のページにアクセスしようとすると、接続が切断されます。

再現コード

ng.rb
require 'rubygems'
require 'mechanize'

agent = Mechanize.new
agent.verify_mode = OpenSSL::SSL::VERIFY_NONE # 証明書の検証をしない(通常はこの行は不要)
agent.get('https://www.hikari.ntt-east.net/AGT_Main.htm') # => Connection reset by peer

出力

$ ruby1.9.3 ng.rb
/var/lib/gems/1.9.1/gems/net-http-persistent-2.8/lib/net/http/persistent/ssl_reuse.rb:70:in `connect': Connection reset by peer - SSL_connect (Errno::ECONNRESET)
        from /var/lib/gems/1.9.1/gems/net-http-persistent-2.8/lib/net/http/persistent/ssl_reuse.rb:70:in `block in connect'
        from /usr/lib/ruby/1.9.1/timeout.rb:54:in `timeout'
        from /usr/lib/ruby/1.9.1/timeout.rb:99:in `timeout'
        from /var/lib/gems/1.9.1/gems/net-http-persistent-2.8/lib/net/http/persistent/ssl_reuse.rb:70:in `connect'
        from /usr/lib/ruby/1.9.1/net/http.rb:755:in `do_start'
        from /usr/lib/ruby/1.9.1/net/http.rb:750:in `start'
        from /var/lib/gems/1.9.1/gems/net-http-persistent-2.8/lib/net/http/persistent.rb:628:in `start'
        from /var/lib/gems/1.9.1/gems/net-http-persistent-2.8/lib/net/http/persistent.rb:570:in `connection_for'
        from /var/lib/gems/1.9.1/gems/net-http-persistent-2.8/lib/net/http/persistent.rb:926:in `request'
        from /var/lib/gems/1.9.1/gems/mechanize-2.5.1/lib/mechanize/http/agent.rb:258:in `fetch'
        from /var/lib/gems/1.9.1/gems/mechanize-2.5.1/lib/mechanize.rb:407:in `get'
        from ng.rb:6:in `<main>'

解決方法

Mechanize#ssl_version= で 'TLSv1' を指定する

解決コード

ok.rb
require 'rubygems'
require 'mechanize'

agent = Mechanize.new
agent.verify_mode = OpenSSL::SSL::VERIFY_NONE # 証明書の検証をしない(通常はこの行は不要)
agent.ssl_version = 'TLSv1'
agent.get('https://www.hikari.ntt-east.net/AGT_Main.htm') # => Success