Yobb

駆け出しWebエンジニアのブログ

RubyでSSL証明書エラーが発生する場合の対処法

エラー

ターミナルから以下のコマンドを実行すると、

$ rbenv exec gem install bundler

SSL証明書のエラーが出る。(改行は編集で追加したものです。)

/Users/hoge/.rbenv/versions/2.0.0-p195/lib/ruby/2.0.0/net/http.rb:918:
  in `connect': SSL_connect
  returned=1 errno=0 state=SSLv3
  read server certificate B:
  certificate verify failed (Twitter::Error::ClientError)

環境

  • OS:Mac OS X EI Capitan 10.11.6
  • Software
    • rbenv 1.1.0
    • ruby 2.3.0
    • gem 2.5.1
    • curl 7.43.0

対処法

SSL証明書のセットアップが必要

1. 証明書のパスを確認する。

$ ruby -ropenssl -e "p OpenSSL::X509::DEFAULT_CERT_FILE"
/usr/local/bin/openssl/cert.pem

2. 証明書をダウンロードする。

ここでちょっと落とし穴。

参照したサイトには、

$ sudo curl "http://curl.haxx.se/ca/cacert.pem" -o /usr/local/etc/openssl/cert.pem

と書かれていたので実行したが、SSL証明書エラーが消えない。

ダウンロードした証明書の内容を確認してみると、

$ cat /usr/local/etc/openssl/cert.pem
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="https://curl.haxx.se/ca/cacert.pem">here</a>.</p>
<hr>
<address>Apache Server at curl.haxx.se Port 80</address>
</body></html>

どうやら、ダウンロード元のURLが変わっているようでした。

旧:http://curl.haxx.se/ca/cacert.pem
新:https://curl.haxx.se/ca/cacert.pem
※2017/03/08時点

コマンド内のURLを変更して再度実行。

$ sudo curl "https://curl.haxx.se/ca/cacert.pem" -o /usr/local/etc/openssl/cert.pem

SSL証明書の確認

今度はちゃんとダウンロードされていました。

$ cat /usr/local/etc/openssl/cert.pem
##
## Bundle of CA Root Certificates
##
## Certificate data from Mozilla as of: Wed Jan 18 04:12:05 2017 GMT
##
## This is a bundle of X.509 certificates of public Certificate Authorities
## (CA). These were automatically extracted from Mozilla's root certificates
## file (certdata.txt).  This file can be found in the mozilla source tree:
## https://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt
##
## It contains the certificates in PEM format and therefore
## can be directly used with curl / libcurl / php_curl, or with
## an Apache+mod_ssl webserver for SSL client authentication.
## Just configure this file as the SSLCACertificateFile.
##
## Conversion done with mk-ca-bundle.pl version 1.27.
## SHA256: dffa79e6aa993f558e82884abf7bb54bf440ab66ee91d82a27a627f6f2a4ace4
##


GlobalSign Root CA
==================
-----BEGIN CERTIFICATE-----

(以下省略)

参考

qiita.com