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
#![cfg_attr(test, feature(plugin))]
#![cfg_attr(test, plugin(clippy))]
#![deny(missing_docs)]

//! Iron middleware providing cross-site request forgery (CSRF) protection.
//!
//! ## Overview
//!
//! `iron-dsc-csrf` is used as an `Iron::AroundMiddleware` that checks unsafe
//! HTTP methods (for example POST, PUT, and PATCH) for a valid CSRF token.
//!
//! ## Implementation
//!
//! `iron-dsc-csrf` uses a method called Double Submit Cookie (or DSC). On the
//! first request to a protected handler, `iron-dsc-csrf` generates a long
//! random value, called the token. The token is placed into a cookie and
//! provided to the client in the response.
//!
//! When a client makes an unsafe request, it must provide the token in a way
//! that cannot be triggered without user action and intent. The usual method of
//! providing the token is with a hidden input field in a form.
//!
//! Upon receiving the unsafe request, `iron-dsc-csrf` compares the token from
//! the cookie to the token in the submitted data. If the tokens match, the
//! request is allowed, otherwise it is denied.
//!
//! ## Usage
//!
//! ```
//! extern crate iron_dsc_csrf;
//! extern crate iron;
//!
//! use iron_dsc_csrf::Csrf;
//! use iron::AroundMiddleware;
//! use iron::prelude::*;
//! use iron::status;
//!
//! fn main() {
//!     let csrf = Csrf::new(extract_token);
//!
//!     let handler = csrf.around(Box::new(index));
//!
//!     // Make and start the server
//!     Iron::new(handler); //.http("localhost:8080").unwrap();
//! }
//!
//! fn extract_token(request: &Request) -> Option<String> {
//!     // Here you can extract the token from the form body, the query string,
//!     // or anywhere else you like.
//!
//!     request.url.query().map(|x| x.to_owned())
//! }
//!
//! fn index(request: &mut Request) -> IronResult<Response> {
//!     let token = request.extensions.get::<Csrf>().unwrap();
//!     let msg = format!("Hello, CSRF Token: {}", token);
//!     Ok(Response::with((status::Ok, msg)))
//! }
//! ```

extern crate base64;
extern crate cookie;
extern crate iron;
extern crate rand;
extern crate subtle;

use cookie::Cookie;

use iron::prelude::*;
use iron::{headers, typemap, AroundMiddleware, Handler, Headers};

use rand::{OsRng, Rng};

use subtle::slices_equal;

mod errors;

pub use errors::CsrfError;

const COOKIE_NAME: &str = "csrf";

/// An `iron::AroundMiddleware` that provides CSRF protection.
pub struct Csrf {
    extract_token: Box<Fn(&Request) -> Option<String> + Sync + Send>,
}

impl Csrf {
    /// Create a new instance of `Csrf` given a function to extract the CSRF
    /// token from a request.
    pub fn new<K: Fn(&Request) -> Option<String> + Sync + Send + 'static>(
        extract_token: K,
    ) -> Self {
        Csrf {
            extract_token: Box::new(extract_token),
        }
    }
}

impl typemap::Key for Csrf {
    type Value = String;
}

impl AroundMiddleware for Csrf {
    fn around(self, handler: Box<Handler>) -> Box<Handler> {
        Box::new(CsrfHandler {
            handler: handler,
            csrf: self,
        })
    }
}

struct CsrfHandler {
    handler: Box<Handler>,
    csrf: Csrf,
}

impl Handler for CsrfHandler {
    fn handle(&self, req: &mut Request) -> IronResult<Response> {
        let state = self.before(req)?;
        let res = self.handler.handle(req)?;
        self.after(state, res)
    }
}

impl CsrfHandler {
    fn before(&self, req: &mut Request) -> IronResult<Option<Cookie>> {
        let cookie = self.find_csrf_cookie(&req.headers);
        self.verify_csrf(req, cookie.as_ref())?;

        let (csrf_token, set_cookie) = match cookie {
            Some(c) => (c.value().to_owned(), None),
            None => Self::generate_token()?,
        };

        req.extensions.insert::<Csrf>(csrf_token);

        Ok(set_cookie)
    }

    fn find_csrf_cookie<'a>(&self, hdrs: &'a Headers) -> Option<Cookie<'a>> {
        let cookies = match hdrs.get::<headers::Cookie>() {
            Some(c) => c,
            None => return None,
        };

        cookies
            .iter()
            .filter_map(|raw_cookie| {
                let parsed_cookie = match Cookie::parse(raw_cookie.as_ref()) {
                    Ok(c) => c,
                    Err(_) => return None,
                };

                if COOKIE_NAME == parsed_cookie.name() {
                    Some(parsed_cookie)
                } else {
                    None
                }
            })
            .nth(0)
    }

    fn generate_token() -> IronResult<(String, Option<Cookie<'static>>)> {
        let mut rng = OsRng::new().map_err(CsrfError::NoRandom)?;

        let mut token_bytes = [0u8; 32];

        rng.fill_bytes(&mut token_bytes);

        let token = base64::encode(&token_bytes);

        Ok((token.clone(), Some(Cookie::new(COOKIE_NAME, token))))
    }

    fn verify_csrf(&self, req: &Request, cookie: Option<&Cookie>) -> IronResult<()> {
        if req.method.safe() {
            return Ok(());
        }

        let cookie = match cookie {
            Some(c) => c,
            None => return Err(CsrfError::CookieMissing.into()),
        };

        let token = match (self.csrf.extract_token)(req) {
            Some(x) => x,
            None => return Err(CsrfError::TokenMissing.into()),
        };

        let cookie_bytes = base64::decode(cookie.value()).or(Err(CsrfError::CookieMissing))?;

        let token_bytes = base64::decode(&token).or(Err(CsrfError::TokenInvalid))?;

        if token_bytes.len() != cookie_bytes.len() {
            return Err(CsrfError::TokenMissing.into());
        }

        if 1 == slices_equal(&cookie_bytes, &token_bytes) {
            Ok(())
        } else {
            Err(CsrfError::TokenInvalid.into())
        }
    }

    fn after<'a>(&self, set_cookie: Option<Cookie<'a>>, mut res: Response) -> IronResult<Response> {
        if let Some(set_cookie) = set_cookie {
            let header = if res.headers.has::<headers::SetCookie>() {
                res.headers.get_mut::<headers::SetCookie>()
            } else {
                res.headers.set(headers::SetCookie(vec![]));
                res.headers.get_mut::<headers::SetCookie>()
            }.unwrap();

            header.push(set_cookie.to_string());
        }

        Ok(res)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use iron::status;

    fn new_impl_none() -> CsrfHandler {
        CsrfHandler {
            handler: Box::new(|_: &mut Request| Ok(Response::with(status::NoContent))),
            csrf: Csrf {
                extract_token: Box::new(|_| None),
            },
        }
    }

    #[test]
    fn generate_token() {
        let (token, cookie) = CsrfHandler::generate_token().unwrap();
        assert_eq!(token, cookie.unwrap().value());
        assert!(token.is_ascii());
        assert_eq!(44, token.len());
    }

    #[test]
    fn after_no_cookie() {
        let csrf = new_impl_none();
        let expected = Response::with(status::NoContent);
        let input = Response::with(status::NoContent);

        let actual = csrf.after(None, input).unwrap();

        assert_eq!(expected.status, actual.status);
        assert_eq!(expected.headers, actual.headers);
        assert!(expected.extensions.is_empty());
    }

    #[test]
    fn after_set_cookie() {
        let csrf = new_impl_none();
        let mut expected = Response::with(status::NoContent);
        expected
            .headers
            .set(headers::SetCookie(vec!["hello=world".to_owned()]));

        let cookie = Cookie::new("hello", "world");

        let input = Response::with(status::NoContent);
        let actual = csrf.after(Some(cookie), input).unwrap();

        assert_eq!(expected.status, actual.status);
        assert_eq!(expected.headers, actual.headers);
        assert!(expected.extensions.is_empty());
    }

    #[test]
    fn after_append_cookie() {
        let csrf = new_impl_none();
        let mut expected = Response::with(status::NoContent);
        expected.headers.set(headers::SetCookie(vec![
            "orange=banana".to_owned(),
            "hello=world".to_owned(),
        ]));

        let cookie = Cookie::new("hello", "world");

        let mut input = Response::with(status::NoContent);
        input
            .headers
            .set(headers::SetCookie(vec!["orange=banana".to_owned()]));
        let actual = csrf.after(Some(cookie), input).unwrap();

        assert_eq!(expected.status, actual.status);
        assert_eq!(expected.headers, actual.headers);
        assert!(expected.extensions.is_empty());
    }
}