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
#![deny(warnings)]
extern crate openssl;
extern crate iron;
extern crate url;
extern crate bodyparser;
extern crate persistent;
extern crate rustc_serialize;
use iron::prelude::*;
use iron::response::ResponseBody;
use iron::{BeforeMiddleware, AfterMiddleware};
use openssl::crypto::hash::Type;
use openssl::crypto::hmac::HMAC;
use std::io::Write;
use std::ops::Deref;
use url::format::PathFormatter;
mod error;
#[macro_use]
mod macros;
mod util;
use error::Result;
use error::Error;
#[derive(Debug, Clone)]
pub struct SecretKey(Vec<u8>);
impl SecretKey {
pub fn new(s: &[u8]) -> SecretKey {
SecretKey(::std::convert::From::from(s))
}
}
impl Deref for SecretKey {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.0[..]
}
}
impl Into<SecretKey> for &'static str {
fn into(self) -> SecretKey {
SecretKey::new(self.as_bytes())
}
}
impl Into<SecretKey> for String {
fn into(self) -> SecretKey {
SecretKey::new(&self[..].as_bytes())
}
}
#[derive(Debug, Clone)]
pub struct Hmac256Authentication {
secret: SecretKey,
hmac_header_key: String
}
impl Hmac256Authentication {
pub fn middleware<K: Into<SecretKey>, S: Into<String>>(secret: K, hmac_header_key: S)
-> (Hmac256Authentication, Hmac256Authentication) {
let auth = Hmac256Authentication {
secret: secret.into(),
hmac_header_key: hmac_header_key.into()
};
(auth.clone(), auth)
}
fn compute_request_hmac(&self, req: &mut iron::Request) -> Result<Vec<u8>> {
let body = match try!(req.get::<bodyparser::Raw>()) {
Some(body) => body,
None => "".to_string()
};
let method = req.method.as_ref();
let path = {
let formatter = PathFormatter { path: &req.url.path };
formatter.to_string()
};
let method_hmac = util::hmac256(&self.secret, method.as_bytes());
let path_hmac = util::hmac256(&self.secret, path.as_bytes());
let body_hmac = util::hmac256(&self.secret, body.as_bytes());
let mut merged_hmac = HMAC::new(Type::SHA256, &self.secret[..]);
try!(merged_hmac.write_all(&method_hmac[..]));
try!(merged_hmac.write_all(&path_hmac[..]));
try!(merged_hmac.write_all(&body_hmac[..]));
Ok(merged_hmac.finish())
}
fn compute_response_hmac(&self, res: &mut iron::Response) -> Result<Vec<u8>> {
let body: Vec<u8> = match res.body {
Some(ref mut body) => {
let mut buf = util::Buffer::new();
try!(body.write_body(&mut ResponseBody::new(&mut buf)));
buf.to_inner()
},
None => Vec::new()
};
let response_hmac = util::hmac256(&self.secret, &body[..]);
res.body = Some(Box::new(body));
Ok(response_hmac)
}
}
impl BeforeMiddleware for Hmac256Authentication {
fn before(&self, req: &mut iron::Request) -> IronResult<()> {
let computed = try!(self.compute_request_hmac(req));
let supplied = match req.headers.get_raw(&self.hmac_header_key[..]) {
Some(hmac) => try!(util::from_hex(&hmac[0][..])),
None => {
let err = Error::MissingHmacHeader(self.hmac_header_key.clone());
return Err(::iron::IronError::new(err, ::iron::status::Forbidden));
}
};
if computed.len() != supplied.len() {
forbidden!();
}
if util::contant_time_equals(&computed[..], &supplied[..]) {
Ok(())
} else {
forbidden!()
}
}
}
impl AfterMiddleware for Hmac256Authentication {
fn after(&self, _: &mut iron::Request, mut res: iron::Response) -> IronResult<Response> {
let hmac = try!(self.compute_response_hmac(&mut res));
let hmac_hex_encoded = util::to_hex(&hmac[..]).as_bytes().to_vec();
res.headers.set_raw(self.hmac_header_key.clone(), vec![hmac_hex_encoded]);
Ok(res)
}
}