diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/args.rs | 146 | ||||
-rw-r--r-- | src/auth.rs | 140 | ||||
-rw-r--r-- | src/main.rs | 2 |
3 files changed, 256 insertions, 32 deletions
diff --git a/src/args.rs b/src/args.rs index 825a4ac..f13d14f 100644 --- a/src/args.rs +++ b/src/args.rs @@ -37,9 +37,9 @@ struct CLIArgs { )] interfaces: Vec<IpAddr>, - /// Set authentication (username:password) + /// Set authentication (username:password, username:sha256:hash, or username:sha512:hash) #[structopt(short = "a", long = "auth", parse(try_from_str = "parse_auth"))] - auth: Option<(String, String)>, + auth: Option<auth::RequiredAuth>, /// Generate a random 6-hexdigit route #[structopt(long = "random-route")] @@ -76,36 +76,47 @@ fn parse_interface(src: &str) -> Result<IpAddr, std::net::AddrParseError> { } /// Checks wether the auth string is valid, i.e. it follows the syntax username:password -fn parse_auth(src: &str) -> Result<(String, String), String> { - let mut split = src.splitn(2, ':'); +fn parse_auth(src: &str) -> Result<auth::RequiredAuth, String> { + let mut split = src.splitn(3, ':'); + let errmsg = "Invalid credentials string, expected format is username:password".to_owned(); let username = match split.next() { Some(username) => username, - None => { - return Err( - "Invalid credentials string, expected format is username:password".to_owned(), - ) - } + None => return Err(errmsg), }; - let password = match split.next() { + let second_part = match split.next() { // This allows empty passwords, as the spec does not forbid it Some(password) => password, - None => { - return Err( - "Invalid credentials string, expected format is username:password".to_owned(), - ) - } + None => return Err(errmsg), }; - // To make it Windows-compatible, the password needs to be shorter than 255 characters. - // After 255 characters, Windows will truncate the value. - // As for the username, the spec does not mention a limit in length - if password.len() > 255 { - return Err("Password length cannot exceed 255 characters".to_owned()); - } + let password = if let Some(hash_hex) = split.next() { + let hash_bin = match hex::decode(hash_hex) { + Ok(hash_bin) => hash_bin, + _ => return Err("Hash string is not a valid hex code".to_owned()), + }; + + match second_part { + "sha256" => auth::RequiredAuthPassword::Sha256(hash_bin.to_owned()), + "sha512" => auth::RequiredAuthPassword::Sha512(hash_bin.to_owned()), + _ => return Err("Invalid hash method, only accept either sha256 or sha512".to_owned()), + } + } else { + // To make it Windows-compatible, the password needs to be shorter than 255 characters. + // After 255 characters, Windows will truncate the value. + // As for the username, the spec does not mention a limit in length + if second_part.len() > 255 { + return Err("Password length cannot exceed 255 characters".to_owned()); + } + + auth::RequiredAuthPassword::Plain(second_part.to_owned()) + }; - Ok((username.to_owned(), password.to_owned())) + Ok(auth::RequiredAuth { + username: username.to_owned(), + password, + }) } /// Parses the command line arguments @@ -121,11 +132,6 @@ pub fn parse_args() -> crate::MiniserveConfig { ] }; - let auth = match args.auth { - Some((username, password)) => Some(auth::BasicAuthParams { username, password }), - None => None, - }; - let random_route = if args.random_route { Some(nanoid::custom(6, &ROUTE_ALPHABET)) } else { @@ -141,7 +147,7 @@ pub fn parse_args() -> crate::MiniserveConfig { path: args.path.unwrap_or_else(|| PathBuf::from(".")), port: args.port, interfaces, - auth, + auth: args.auth, path_explicitly_chosen, no_symlinks: args.no_symlinks, random_route, @@ -150,3 +156,87 @@ pub fn parse_args() -> crate::MiniserveConfig { file_upload: args.file_upload, } } + +#[cfg(test)] +mod tests { + use super::*; + + fn create_required_auth(username: &str, password: &str, encrypt: &str) -> auth::RequiredAuth { + use auth::*; + use RequiredAuthPassword::*; + + RequiredAuth { + username: username.to_owned(), + password: match encrypt { + "plain" => Plain(password.to_owned()), + "sha256" => Sha256(hex::decode(password.to_owned()).unwrap()), + "sha512" => Sha512(hex::decode(password.to_owned()).unwrap()), + _ => panic!("Unknown encryption type"), + }, + } + } + + #[test] + fn parse_auth_plain() -> Result<(), String> { + assert_eq!( + parse_auth("username:password")?, + create_required_auth("username", "password", "plain") + ); + + Ok(()) + } + + #[test] + fn parse_auth_sha256() -> Result<(), String> { + assert_eq!( + parse_auth("username:sha256:abcd")?, + create_required_auth("username", "abcd", "sha256") + ); + + Ok(()) + } + + #[test] + fn parse_auth_sha512() -> Result<(), String> { + assert_eq!( + parse_auth("username:sha512:abcd")?, + create_required_auth("username", "abcd", "sha512") + ); + + Ok(()) + } + + #[test] + fn parse_auth_invalid_syntax() { + assert_eq!( + parse_auth("foo").unwrap_err(), + "Invalid credentials string, expected format is username:password".to_owned() + ); + } + + #[test] + fn parse_auth_invalid_hash_method() { + assert_eq!( + parse_auth("username:blahblah:abcd").unwrap_err(), + "Invalid hash method, only accept either sha256 or sha512".to_owned() + ); + } + + #[test] + fn parse_auth_invalid_hash_string() { + assert_eq!( + parse_auth("username:sha256:invalid").unwrap_err(), + "Hash string is not a valid hex code".to_owned() + ); + } + + #[test] + fn parse_auth_excessive_length() { + let auth_string = format!("username:{}", "x".repeat(256)); + + assert_eq!( + parse_auth(&*auth_string).unwrap_err(), + "Password length cannot exceed 255 characters".to_owned() + ); + } +} diff --git a/src/auth.rs b/src/auth.rs index 10e7a4a..a4b3555 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -1,6 +1,7 @@ use actix_web::http::header; use actix_web::middleware::{Middleware, Response}; use actix_web::{HttpRequest, HttpResponse, Result}; +use sha2::{Digest, Sha256, Sha512}; pub struct Auth; @@ -16,6 +17,20 @@ pub struct BasicAuthParams { pub password: String, } +#[derive(Clone, Debug, PartialEq)] +pub enum RequiredAuthPassword { + Plain(String), + Sha256(Vec<u8>), + Sha512(Vec<u8>), +} + +#[derive(Clone, Debug, PartialEq)] +/// Authentication structure to match BasicAuthParams against +pub struct RequiredAuth { + pub username: String, + pub password: RequiredAuthPassword, +} + /// Decode a HTTP basic auth string into a tuple of username and password. pub fn parse_basic_auth( authorization_header: &header::HeaderValue, @@ -34,6 +49,34 @@ pub fn parse_basic_auth( }) } +pub fn match_auth(basic_auth: BasicAuthParams, required_auth: &RequiredAuth) -> bool { + if basic_auth.username != required_auth.username { + return false; + } + + match &required_auth.password { + RequiredAuthPassword::Plain(ref required_password) => { + basic_auth.password == *required_password + } + RequiredAuthPassword::Sha256(password_hash) => { + compare_hash::<Sha256>(basic_auth.password, password_hash) + } + RequiredAuthPassword::Sha512(password_hash) => { + compare_hash::<Sha512>(basic_auth.password, password_hash) + } + } +} + +pub fn compare_hash<T: Digest>(password: String, hash: &Vec<u8>) -> bool { + get_hash::<T>(password) == *hash +} + +pub fn get_hash<T: Digest>(text: String) -> Vec<u8> { + let mut hasher = T::new(); + hasher.input(text); + hasher.result().to_vec() +} + impl Middleware<crate::MiniserveConfig> for Auth { fn response( &self, @@ -51,9 +94,7 @@ impl Middleware<crate::MiniserveConfig> for Auth { )))); } }; - if auth_req.username != required_auth.username - || auth_req.password != required_auth.password - { + if !match_auth(auth_req, required_auth) { let new_resp = HttpResponse::Unauthorized().finish(); return Ok(Response::Done(new_resp)); } @@ -70,3 +111,96 @@ impl Middleware<crate::MiniserveConfig> for Auth { Ok(Response::Done(resp)) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn assert_hex_eq(expectation: &str, received: Vec<u8>) { + let bin = hex::decode(expectation).expect("Provided string is not a valid hex code"); + assert_eq!(bin, received); + } + + #[test] + fn get_hash_hex_sha256() { + let expectation = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + let received = get_hash::<Sha256>("abc".to_owned()); + assert_hex_eq(expectation, received); + } + + #[test] + fn get_hash_hex_sha512() { + let expectation = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"; + let received = get_hash::<Sha512>("abc".to_owned()); + assert_hex_eq(expectation, received); + } + + fn create_auth_params(username: &str, password: &str) -> BasicAuthParams { + BasicAuthParams { + username: username.to_owned(), + password: password.to_owned(), + } + } + + fn create_required_auth(username: &str, password: &str, encrypt: &str) -> RequiredAuth { + use RequiredAuthPassword::*; + + RequiredAuth { + username: username.to_owned(), + password: match encrypt { + "plain" => Plain(password.to_owned()), + "sha256" => Sha256(get_hash::<sha2::Sha256>(password.to_owned())), + "sha512" => Sha512(get_hash::<sha2::Sha512>(password.to_owned())), + _ => panic!("Unknown encryption type"), + }, + } + } + + #[test] + fn match_auth_plain_password_should_pass() { + assert!(match_auth( + create_auth_params("obi", "hello there"), + &create_required_auth("obi", "hello there", "plain"), + )); + } + + #[test] + fn match_auth_plain_password_should_fail() { + assert!(!match_auth( + create_auth_params("obi", "hello there"), + &create_required_auth("obi", "hi!", "plain"), + )); + } + + #[test] + fn match_auth_sha256_password_should_pass() { + assert!(match_auth( + create_auth_params("obi", "hello there"), + &create_required_auth("obi", "hello there", "sha256"), + )); + } + + #[test] + fn match_auth_sha256_password_should_fail() { + assert!(!match_auth( + create_auth_params("obi", "hello there"), + &create_required_auth("obi", "hi!", "sha256"), + )); + } + + #[test] + fn match_auth_sha512_password_should_pass() { + assert!(match_auth( + create_auth_params("obi", "hello there"), + &create_required_auth("obi", "hello there", "sha512"), + )); + } + + #[test] + fn match_auth_sha512_password_should_fail() { + assert!(!match_auth( + create_auth_params("obi", "hello there"), + &create_required_auth("obi", "hi!", "sha512"), + )); + } +} diff --git a/src/main.rs b/src/main.rs index 9eb93b1..e63b505 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,7 +35,7 @@ pub struct MiniserveConfig { pub interfaces: Vec<IpAddr>, /// Enable HTTP basic authentication - pub auth: Option<auth::BasicAuthParams>, + pub auth: Option<auth::RequiredAuth>, /// If false, miniserve will serve the current working directory pub path_explicitly_chosen: bool, |