1
0
Fork 0

Implement CSRF protection fairing

This commit is contained in:
Alex Kotov 2020-10-16 11:41:26 +05:00
parent b49ed15975
commit 7893df38f4
Signed by: kotovalexarian
GPG key ID: 553C0EBBEB5D5F08
3 changed files with 21 additions and 3 deletions

8
Cargo.lock generated
View file

@ -97,6 +97,12 @@ version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3441f0f7b02788e948e47f457ca01f1d7e6d92c693bc132c22b087d3141c03ff" checksum = "3441f0f7b02788e948e47f457ca01f1d7e6d92c693bc132c22b087d3141c03ff"
[[package]]
name = "base64"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd"
[[package]] [[package]]
name = "bcrypt" name = "bcrypt"
version = "0.8.2" version = "0.8.2"
@ -299,10 +305,12 @@ checksum = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed"
name = "fedihub-registry" name = "fedihub-registry"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"base64 0.13.0",
"bcrypt", "bcrypt",
"diesel", "diesel",
"dotenv", "dotenv",
"r2d2", "r2d2",
"rand",
"regex", "regex",
"rocket", "rocket",
"rocket_contrib", "rocket_contrib",

View file

@ -13,9 +13,11 @@ categories = []
publish = true publish = true
[dependencies] [dependencies]
base64 = "0.13.0"
bcrypt = "0.8.2" bcrypt = "0.8.2"
dotenv = "0.15.0" dotenv = "0.15.0"
r2d2 = "0.8.9" r2d2 = "0.8.9"
rand = "0.7.3"
regex = "1.4.1" regex = "1.4.1"
serde = "1.0" serde = "1.0"
serde_derive = "1.0" serde_derive = "1.0"

View file

@ -1,7 +1,10 @@
use rand::RngCore;
use rocket::{Data, Request}; use rocket::{Data, Request};
use rocket::fairing::{Fairing as RocketFairing, Info, Kind}; use rocket::fairing::{Fairing as RocketFairing, Info, Kind};
use rocket::http::Cookie;
const COOKIE_NAME: &str = "csrf_token"; const COOKIE_NAME: &str = "csrf_token";
const RAW_TOKEN_LENGTH: usize = 32;
pub struct Fairing; pub struct Fairing;
@ -20,8 +23,13 @@ impl RocketFairing for Fairing {
} }
fn on_request(&self, request: &mut Request, _: &Data) { fn on_request(&self, request: &mut Request, _: &Data) {
let _token: Option<String> = request.cookies() if request.cookies().get_private(COOKIE_NAME).is_some() { return };
.get_private(COOKIE_NAME)
.and_then(|cookie| Some(cookie.value().to_string())); let mut raw = [0u8; RAW_TOKEN_LENGTH];
rand::thread_rng().fill_bytes(&mut raw);
let encoded = base64::encode(raw);
request.cookies().add_private(Cookie::new(COOKIE_NAME, encoded));
} }
} }