-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
message_verifier.rb
190 lines (166 loc) · 5.16 KB
/
message_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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# frozen_string_literal: true
require 'net/http'
require 'openssl'
require 'base64'
module Aws
module SNS
# A utility class that can be used to verify the authenticity of messages
# sent by Amazon SNS.
#
# verifier = Aws::SNS::MessageVerifier.new
#
# # returns true/false
# verifier.authentic?(message_body)
#
# # raises a Aws::SNS::MessageVerifier::VerificationError on failure
# verifier.authenticate!(message_body)
#
# You can re-use a single {MessageVerifier} instance to authenticate
# multiple SNS messages.
class MessageVerifier
class VerificationError < StandardError; end
# @api private
SIGNABLE_KEYS = [
'Message',
'MessageId',
'Subject',
'SubscribeURL',
'Timestamp',
'Token',
'TopicArn',
'Type'
].freeze
# @api private
AWS_HOSTNAMES = [
/^sns\.[a-zA-Z0-9\-]{3,}\.amazonaws\.com(\.cn)?$/
].freeze
# @param [Hash] http_options Supported options to be passed to Net::HTTP.
# @option http_options [String] :http_proxy A proxy to send
# requests through. Formatted like 'http://proxy.com:123'.
def initialize(http_options = {})
@cached_pems = {}
@http_proxy = http_options[:http_proxy]
end
# @param [String<JSON>] message_body
# @return [Boolean] Returns `true` if the given message has been
# successfully verified. Returns `false` otherwise.
def authentic?(message_body)
authenticate!(message_body)
rescue VerificationError
false
end
# @param [String<JSON>] message_body
# @return [Boolean] Returns `true` when the given message has been
# successfully verified.
# @raise [VerificationError] Raised when the given message has failed
# verification.
def authenticate!(message_body)
msg = Json.load(message_body)
msg = convert_lambda_msg(msg) if is_from_lambda(msg)
if public_key(msg).verify(sha1, signature(msg), canonical_string(msg))
true
else
msg = 'the authenticity of the message cannot be verified'
raise VerificationError, msg
end
end
private
def is_from_lambda(message)
message.key? 'SigningCertUrl'
end
def convert_lambda_msg(message)
cert_url = message.delete('SigningCertUrl')
unsubscribe_url = message.delete('UnsubscribeUrl')
message['SigningCertURL'] = cert_url
message['UnsubscribeURL'] = unsubscribe_url
message
end
def sha1
OpenSSL::Digest::SHA1.new
end
def signature(message)
Base64.decode64(message['Signature'])
end
def canonical_string(message)
parts = []
SIGNABLE_KEYS.each do |key|
value = message[key]
unless value.nil? or value.empty?
parts << "#{key}\n#{value}\n"
end
end
parts.join
end
def public_key(message)
x509_url = URI.parse(message['SigningCertURL'])
x509 = OpenSSL::X509::Certificate.new(pem(x509_url))
OpenSSL::PKey::RSA.new(x509.public_key)
end
def pem(uri)
if @cached_pems[uri.to_s]
@cached_pems[uri.to_s]
else
@cached_pems[uri.to_s] = download_pem(uri)
end
end
def download_pem(uri)
verify_uri!(uri)
https_get(uri)
end
def verify_uri!(uri)
verify_https!(uri)
verify_hosted_by_aws!(uri)
verify_pem!(uri)
end
def verify_https!(uri)
unless uri.scheme == 'https'
msg = "the SigningCertURL must be https, got: #{uri}"
raise VerificationError, msg
end
end
def verify_hosted_by_aws!(uri)
unless AWS_HOSTNAMES.any? { |pattern| pattern.match(uri.host) }
msg = "signing cert is not hosted by AWS: #{uri}"
raise VerificationError, msg
end
end
def verify_pem!(uri)
unless File.extname(uri.path) == '.pem'
msg = "the SigningCertURL must link to a .pem file"
raise VerificationError, msg
end
end
def https_get(uri, failed_attempts = 0)
args = []
args << uri.host
args << uri.port
args += http_proxy_parts
http = Net::HTTP.new(*args.compact)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.start
resp = http.request(Net::HTTP::Get.new(uri.request_uri))
http.finish
if resp.code == '200'
resp.body
else
raise VerificationError, resp.body
end
rescue => error
failed_attempts += 1
retry if failed_attempts < 3
raise VerificationError, error.message
end
def http_proxy_parts
# empty string if not configured, URI parts return nil
http_proxy = URI.parse(@http_proxy.to_s)
[
http_proxy.host,
http_proxy.port,
(http_proxy.user && CGI.unescape(http_proxy.user)),
(http_proxy.password && CGI.unescape(http_proxy.password))
]
end
end
end
end