Skip to content

Instantly share code, notes, and snippets.

@bethesque
Last active January 9, 2018 00:28
Show Gist options
  • Save bethesque/9a393ebd5e1f6754373fede226942f0e to your computer and use it in GitHub Desktop.
Save bethesque/9a393ebd5e1f6754373fede226942f0e to your computer and use it in GitHub Desktop.
Making a request to a server with a self signed certificate
require 'openssl'
require 'uri'
require 'net/http'
uri = URI('https://self-signed.badssl.com')
downloaded_cert_path = '/tmp/downloaded_cert.pem'
puts `openssl s_client -showcerts -servername #{uri.host} -connect #{uri.host}:#{uri.port} </dev/null 2>/dev/null|openssl x509 -text`
command = "openssl s_client -showcerts -servername #{uri.host} -connect #{uri.host}:#{uri.port} </dev/null 2>/dev/null|openssl x509 -outform PEM > #{downloaded_cert_path}"
puts command
puts `#{command}`
cert_store = OpenSSL::X509::Store.new
puts "Adding certificate #{downloaded_cert_path}"
cert_store.add_file(downloaded_cert_path)
req = Net::HTTP::Get.new(uri)
options = {
:use_ssl => uri.scheme == 'https',
verify_mode: OpenSSL::SSL::VERIFY_PEER,
cert_store: cert_store
}
response = Net::HTTP.start(uri.hostname, uri.port, options) do |http|
http.request req
end
puts response
@bethesque
Copy link
Author

Ok, for some reason, the certificate that openssl downloads is not the certificate that the browser displays. When I grab the certificate through the browser (shown below) this works:

-----BEGIN CERTIFICATE-----
MIIDeTCCAmGgAwIBAgIJAIb7Tcjl3Q8YMA0GCSqGSIb3DQEBCwUAMGIxCzAJBgNV
BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNp
c2NvMQ8wDQYDVQQKDAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTAeFw0x
NjA4MDgyMTE3MDVaFw0xODA4MDgyMTE3MDVaMGIxCzAJBgNVBAYTAlVTMRMwEQYD
VQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQ8wDQYDVQQK
DAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTCCASIwDQYJKoZIhvcNAQEB
BQADggEPADCCAQoCggEBAMIE7PiM7gTCs9hQ1XBYzJMY61yoaEmwIrX5lZ6xKyx2
PmzAS2BMTOqytMAPgLaw+XLJhgL5XEFdEyt/ccRLvOmULlA3pmccYYz2QULFRtMW
hyefdOsKnRFSJiFzbIRMeVXk0WvoBj1IFVKtsyjbqv9u/2CVSndrOfEk0TG23U3A
xPxTuW1CrbV8/q71FdIzSOciccfCFHpsKOo3St/qbLVytH5aohbcabFXRNsKEqve
ww9HdFxBIuGa+RuT5q0iBikusbpJHAwnnqP7i/dAcgCskgjZjFeEU4EFy+b+a1SY
QCeFxxC7c3DvaRhBB0VVfPlkPz0sw6l865MaTIbRyoUCAwEAAaMyMDAwCQYDVR0T
BAIwADAjBgNVHREEHDAaggwqLmJhZHNzbC5jb22CCmJhZHNzbC5jb20wDQYJKoZI
hvcNAQELBQADggEBALW4pad52T7VNw2nFMjPH98ZJNAQQgWyr3H2KlZN6IFGsonO
nCC/Do8BPx6BnP3PFwovWMat1VvnRRoC8lw/30eEazWqBRGZWPz6LHTE3DNBJdc8
xz6mh8q9RJX/PAj+YYGNElTu6qj49YT0BEhMF4U+dTQ0G8y3x4WNfiu9pGqyrp8d
AzeidMfQ/pU01PpoPTDLvRDNkmMsABNE1fXBfJxDDGwfq1xY1j23Fm6BolwZC2y7
n19h+vMYVWbGoovrf2/ibTvtcTyfDop7gl5Yy3OncZxokFj21rUZpLgx9ea4a9z3
FzEz5ufynq03RhHTE1eu+gDzMEF0GNhGGsKqeA4=
-----END CERTIFICATE-----

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment