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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
use failure::{bail, Error, Fail, ResultExt};
use log::error;
use std::{collections::HashMap, path::Path};
use time::Duration;
use url::{Host, Url};
use x509_parser::objects::Nid;
mod normalize;
const CERT_CHAIN_URL_SCHEME: &str = "https";
const CERT_CHAIN_URL_HOSTNAME: &str = "s3.amazonaws.com";
const CERT_CHAIN_URL_STARTPATH: &str = "/echo.api/";
const CERT_CHAIN_URL_PORT: u16 = 443;
const CERT_CHAIN_DOMAIN: &str = "echo-api.amazon.com";
const DEFAULT_TIMESTAMP_TOLERANCE_IN_MILLIS: i64 = 150_000;
const MAX_TIMESTAMP_TOLERANCE_IN_MILLIS: i64 = 3_600_000;
#[derive(Debug, Fail)]
pub enum VerificationError {
#[fail(display = "Failed to validate URL")]
ValidateUrl,
#[fail(display = "Failed to retreive cert")]
RetrieveCert,
#[fail(display = "Failed to decode PEM")]
PemParse,
#[fail(display = "Failed to parse certificate to x509")]
CertParse,
#[fail(display = "Failed to parse x509 extension")]
CertExtParse,
#[fail(display = "No valid data in SAN extension")]
SanExtension,
#[fail(display = "Cert missing from cache")]
MissingCertCache,
#[fail(display = "Signing Certificate expired")]
ExpiredCert,
#[fail(display = "'echo-api.amazon.com' not in SAN extension")]
DomainNotInSan,
#[fail(display = "Expecting 'https', got '{}'", scheme)]
UrlScheme { scheme: String },
#[fail(display = "Expecting 's3.amazonaws.com', got '{}'", hostname)]
UrlHostname { hostname: String },
#[fail(display = "Expecting '/echo.api/', got '{}'", path)]
UrlPath { path: String },
#[fail(display = "Expecting '443', got '{}'", port)]
UrlPort { port: u16 },
#[fail(display = "Could not parse timestamp into DateTime: '{}'", timestamp)]
TimestampParse { timestamp: String },
#[fail(
display = "Provided tolerance of '{}' exceeds max of 3_600_000",
millis
)]
TimestampMax { millis: i64 },
#[fail(display = "Timestamp verification failed")]
Timestamp,
}
#[derive(Clone)]
pub struct RequestVerifier {
cert_cache: HashMap<String, Vec<u8>>,
}
impl Default for RequestVerifier {
fn default() -> Self {
RequestVerifier {
cert_cache: HashMap::new(),
}
}
}
impl RequestVerifier {
pub fn new() -> Self {
RequestVerifier::default()
}
pub fn verify(
&mut self,
signature_cert_chain_url: &str,
signature: &str,
body: &[u8],
timestamp: &str,
timestamp_tolerance_millis: Option<u64>,
) -> Result<(), Error> {
if let Err(e) = self.retrieve_and_validate_cert(signature_cert_chain_url, signature, body) {
log_error(e)?;
};
if let Err(e) = self.validate_timestamp(timestamp, timestamp_tolerance_millis) {
log_error(e)?;
};
Ok(())
}
fn retrieve_and_validate_cert(
&mut self,
signature_cert_chain_url: &str,
signature: &str,
body: &[u8],
) -> Result<(), Error> {
self.validate_cert_url(&signature_cert_chain_url)?;
let mut not_exists = false;
if !self
.cert_cache
.contains_key(&signature_cert_chain_url.to_string())
{
not_exists = true;
self.retrieve_cert(&signature_cert_chain_url)
.context(VerificationError::RetrieveCert)?;
}
let pem_bytes = self
.cert_cache
.get(&signature_cert_chain_url.to_string())
.ok_or(VerificationError::MissingCertCache)?;
let (_, pem) =
x509_parser::pem::pem_to_der(pem_bytes).map_err(|_| VerificationError::PemParse)?;
let certificate = pem.parse_x509().map_err(|_| VerificationError::CertParse)?;
let not_before = certificate.tbs_certificate.validity.not_before;
let not_after = certificate.tbs_certificate.validity.not_after;
let now_utc = time::now_utc();
if now_utc < not_before || now_utc > not_after {
bail!(VerificationError::ExpiredCert)
}
if not_exists {
let mut sans: Vec<&str> = Vec::new();
for ext in &certificate.tbs_certificate.extensions {
if ext.oid == x509_parser::objects::nid2obj(&Nid::SubjectAltName).unwrap() {
let (_, ber) = der_parser::parse_der(&ext.value)
.map_err(|_| VerificationError::CertExtParse)?;
for b in ber.into_iter() {
if let der_parser::ber::BerObjectContent::Unknown(_, i) = b.content {
sans.push(
std::str::from_utf8(i).context(VerificationError::SanExtension)?,
)
} else {
bail!(VerificationError::SanExtension)
}
}
}
}
if !sans.contains(&CERT_CHAIN_DOMAIN) {
bail!(VerificationError::DomainNotInSan)
}
}
let pkey = certificate
.tbs_certificate
.subject_pki
.subject_public_key
.data;
self.validate_request_body(signature, body, pkey)?;
Ok(())
}
fn retrieve_cert(&mut self, signature_cert_chain_url: &str) -> Result<(), Error> {
let mut resp = reqwest::get(signature_cert_chain_url)?;
let mut buf: Vec<u8> = vec![];
resp.copy_to(&mut buf)?;
let _ = self
.cert_cache
.insert(signature_cert_chain_url.to_string(), buf);
Ok(())
}
fn validate_cert_url(&self, signature_cert_chain_url: &str) -> Result<(), Error> {
let parsed_url = Url::parse(signature_cert_chain_url)?;
let scheme = parsed_url.scheme();
if scheme != CERT_CHAIN_URL_SCHEME {
bail!(VerificationError::UrlScheme {
scheme: scheme.to_string()
})
}
if let Some(hostname) = parsed_url.host() {
match hostname {
Host::Domain(hostname) => {
if hostname.to_lowercase() != CERT_CHAIN_URL_HOSTNAME {
bail!(VerificationError::UrlHostname {
hostname: hostname.to_string()
});
}
}
Host::Ipv4(ip) => bail!(VerificationError::UrlHostname {
hostname: format!("{}", ip)
}),
Host::Ipv6(ip) => bail!(VerificationError::UrlHostname {
hostname: format!("{}", ip)
}),
}
} else {
bail!(VerificationError::UrlHostname {
hostname: "".to_string()
})
}
let path = Path::new(parsed_url.path());
let normalized_path = normalize::normalize_path(&path);
if !normalized_path.starts_with(CERT_CHAIN_URL_STARTPATH) {
bail!(VerificationError::UrlPath {
path: format!("{}", normalized_path.display())
})
}
if let Some(port) = parsed_url.port() {
if port != CERT_CHAIN_URL_PORT {
bail!(VerificationError::UrlPort { port })
}
}
Ok(())
}
fn validate_request_body(
&self,
signature: &str,
body: &[u8],
pkey_bytes: &[u8],
) -> Result<(), Error> {
let decoded_signature = base64::decode(&signature)?;
let pkey = ring::signature::UnparsedPublicKey::new(
&ring::signature::RSA_PKCS1_2048_8192_SHA1_FOR_LEGACY_USE_ONLY,
pkey_bytes,
);
pkey.verify(body, &decoded_signature)?;
Ok(())
}
fn validate_timestamp(
&self,
timestamp: &str,
timestamp_tolerance_millis: Option<u64>,
) -> Result<(), Error> {
let tolerance_millis = {
if let Some(t) = timestamp_tolerance_millis {
Duration::milliseconds(t as i64)
} else {
Duration::milliseconds(DEFAULT_TIMESTAMP_TOLERANCE_IN_MILLIS)
}
};
if tolerance_millis > Duration::milliseconds(MAX_TIMESTAMP_TOLERANCE_IN_MILLIS) {
bail!(VerificationError::TimestampMax {
millis: tolerance_millis.num_milliseconds()
});
}
let timestamp =
time::strptime(timestamp, "%FT%TZ").context(VerificationError::TimestampParse {
timestamp: timestamp.to_owned(),
})?;
let utc_now = time::now_utc();
let duration_between = utc_now - timestamp;
if duration_between > tolerance_millis {
bail!(VerificationError::Timestamp);
};
Ok(())
}
}
fn log_error(e: Error) -> Result<(), Error> {
error!("{}", e);
for cause in e.iter_causes() {
error!("Caused by: {}", cause);
}
Err(e)
}