/
ssl_verifier.rb
89 lines (71 loc) · 2.56 KB
/
ssl_verifier.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# This code is based on the implementation in Faraday:
#
# https://github.com/lostisland/faraday/blob/v1.0.1/lib/faraday/adapter/em_http_ssl_patch.rb
#
# Faraday is published under the MIT license as detailed here:
#
# https://github.com/lostisland/faraday/blob/v1.0.1/LICENSE.md
#
# Copyright (c) 2009-2019 Rick Olson, Zack Hobson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
require 'openssl'
module Faye
class WebSocket
SSLError = Class.new(OpenSSL::SSL::SSLError)
class SslVerifier
def initialize(hostname, ssl_opts)
@hostname = hostname
@ssl_opts = ssl_opts
@cert_store = OpenSSL::X509::Store.new
if ca = @ssl_opts[:cert_authority_file]
[ca].flatten.each { |ca_path| @cert_store.add_file(ca_path) }
else
@cert_store.set_default_paths
end
end
def ssl_verify_peer(cert_text)
return true unless should_verify?
certificate = parse_cert(cert_text)
return false unless certificate
unless @cert_store.verify(certificate)
raise SSLError, "Unable to verify the server certificate for '#{ @hostname }'"
end
store_cert(certificate)
@last_cert = certificate
true
end
def ssl_handshake_completed
return unless should_verify?
unless last_certificate_verified?
raise SSLError, "Host '#{ @hostname }' does not match the server certificate"
end
end
private
def should_verify?
@ssl_opts[:verify_peer] != false
end
def parse_cert(cert_text)
OpenSSL::X509::Certificate.new(cert_text)
rescue OpenSSL::X509::CertificateError
nil
end
def store_cert(certificate)
@cert_store.add_cert(certificate)
rescue OpenSSL::X509::StoreError => error
raise error unless error.message == 'cert already in hash table'
end
def last_certificate_verified?
@last_cert and OpenSSL::SSL.verify_certificate_identity(@last_cert, @hostname)
end
end
end
end