📘

Ruby SSL error and the certificate chain

2024/05/26に公開

Last week, suddenly, one of my very old crawler programs got an SSL error.

ERROR -- : SSL_connect returned=1 errno=0 state=error: certificate verify failed

This script was built to run in Windows, so in the past, I downloaded the certificate from http://curl.haxx.se/ca/cacert.pem to make it work. My first thought was that the certificate had been outdated, so I tried downloading the latest one. The error changed a little bit.

ERROR -- : SSL_connect returned=1 errno=0 state=error: certificate verify failed (unable to get local issuer certificate)

Then, I found this Stackoverflow answer, which suggests that the certificate issuer of the site I'm accessing is not included in the pem file, and I need to export it manually from the browser and add to the pem file.

The problem is there are 3 levels of certification, so I don't know which one I should export.

Then, I tried running openssl directly and got the certificate chain

openssl s_client -CAfile /home/lamphanqg/Projects/nlbc_crawler/cacert.pem -connect www.id.nlbc.go.jp:443
CONNECTED(00000003)
depth=0 C = JP, ST = Fukushima, L = "Nishigo-mura, Nishishirakawa-gun", O = National Livestock Breeding Center, CN = www.id.nlbc.go.jp
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 C = JP, ST = Fukushima, L = "Nishigo-mura, Nishishirakawa-gun", O = National Livestock Breeding Center, CN = www.id.nlbc.go.jp
verify error:num=21:unable to verify the first certificate
verify return:1
---
Certificate chain
 0 s:C = JP, ST = Fukushima, L = "Nishigo-mura, Nishishirakawa-gun", O = National Livestock Breeding Center, CN = www.id.nlbc.go.jp
   i:C = JP, O = "Cybertrust Japan Co., Ltd.", CN = Cybertrust Japan SureServer CA G4
 1 s:C = JP, O = "Cybertrust Japan Co., Ltd.", CN = Cybertrust Japan SureServer EV CA G3
   i:C = JP, O = "SECOM Trust Systems CO.,LTD.", OU = Security Communication RootCA2
---
...
---
SSL handshake has read 3551 bytes and written 426 bytes
Verification error: unable to verify the first certificate
---
...

The error said unable to verify the first certificate, so it must be this one

0 s:C = JP, ST = Fukushima, L = "Nishigo-mura, Nishishirakawa-gun", O = National Livestock Breeding Center, CN = www.id.nlbc.go.jp
   i:C = JP, O = "Cybertrust Japan Co., Ltd.", CN = Cybertrust Japan SureServer CA G4

Actually I don't have much knowledge about certificates, so I don't know what the text mean. However, I saw CN = www.id.nlbc.go.jp and CN = Cybertrust Japan SureServer CA G4 parts match with 2 lines in the certificate viewer, so I tried exporting those 2, and the latter worked.

So, next time this error happens, I know that I should get the details from openssl command, and export the certificate that matches with the CN of the i line of the certificate that failed to verify.

Discussion