xmpp-rs/sasl/src/common/scram.rs

180 lines
5.6 KiB
Rust
Raw Normal View History

use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::fmt;
2021-12-25 15:57:41 +01:00
use hmac::{digest::InvalidLength, Hmac, Mac};
2019-01-17 23:59:31 +01:00
use pbkdf2::pbkdf2;
2019-01-17 23:32:39 +01:00
use sha1::{Digest, Sha1 as Sha1_hash};
use sha2::Sha256 as Sha256_hash;
2019-01-17 22:54:32 +01:00
use crate::common::Password;
2019-01-17 22:54:32 +01:00
use crate::secret;
use base64::{engine::general_purpose::STANDARD as Base64, Engine};
/// Generate a nonce for SCRAM authentication.
pub fn generate_nonce() -> Result<String, getrandom::Error> {
2019-01-17 23:53:29 +01:00
let mut data = [0u8; 32];
getrandom::fill(&mut data)?;
2024-05-06 08:01:54 +10:00
Ok(Base64.encode(data))
}
#[derive(Debug, PartialEq)]
pub enum DeriveError {
IncompatibleHashingMethod(String, String),
IncorrectSalt,
InvalidLength,
2020-06-22 01:19:24 +02:00
IncompatibleIterationCount(u32, u32),
}
impl fmt::Display for DeriveError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self {
DeriveError::IncompatibleHashingMethod(one, two) => {
write!(fmt, "incompatible hashing method, {} is not {}", one, two)
}
DeriveError::IncorrectSalt => write!(fmt, "incorrect salt"),
DeriveError::InvalidLength => write!(fmt, "invalid length"),
DeriveError::IncompatibleIterationCount(one, two) => {
write!(fmt, "incompatible iteration count, {} is not {}", one, two)
}
}
}
}
impl core::error::Error for DeriveError {}
impl From<hmac::digest::InvalidLength> for DeriveError {
fn from(_err: hmac::digest::InvalidLength) -> DeriveError {
DeriveError::InvalidLength
}
}
/// A trait which defines the needed methods for SCRAM.
pub trait ScramProvider {
/// The kind of secret this `ScramProvider` requires.
2017-03-25 23:45:30 +01:00
type Secret: secret::Secret;
/// The name of the hash function.
fn name() -> &'static str;
/// A function which hashes the data using the hash function.
fn hash(data: &[u8]) -> Vec<u8>;
/// A function which performs an HMAC using the hash function.
2021-12-25 15:57:41 +01:00
fn hmac(data: &[u8], key: &[u8]) -> Result<Vec<u8>, InvalidLength>;
/// A function which does PBKDF2 key derivation using the hash function.
2020-06-22 01:19:24 +02:00
fn derive(data: &Password, salt: &[u8], iterations: u32) -> Result<Vec<u8>, DeriveError>;
}
/// A `ScramProvider` which provides SCRAM-SHA-1 and SCRAM-SHA-1-PLUS
pub struct Sha1;
impl ScramProvider for Sha1 {
2017-03-25 23:45:30 +01:00
type Secret = secret::Pbkdf2Sha1;
fn name() -> &'static str {
"SHA-1"
}
fn hash(data: &[u8]) -> Vec<u8> {
2019-01-17 23:32:39 +01:00
let hash = Sha1_hash::digest(data);
hash.to_vec()
}
2021-12-25 15:57:41 +01:00
fn hmac(data: &[u8], key: &[u8]) -> Result<Vec<u8>, InvalidLength> {
2019-01-17 23:40:46 +01:00
type HmacSha1 = Hmac<Sha1_hash>;
2021-12-25 15:57:41 +01:00
let mut mac = HmacSha1::new_from_slice(key)?;
2020-06-22 01:19:24 +02:00
mac.update(data);
Ok(mac.finalize().into_bytes().to_vec())
}
2020-06-22 01:19:24 +02:00
fn derive(password: &Password, salt: &[u8], iterations: u32) -> Result<Vec<u8>, DeriveError> {
match *password {
Password::Plain(ref plain) => {
let mut result = vec![0; 20];
pbkdf2::<Hmac<Sha1_hash>>(plain.as_bytes(), salt, iterations, &mut result)?;
Ok(result)
}
Password::Pbkdf2 {
ref method,
salt: ref my_salt,
iterations: my_iterations,
ref data,
} => {
if method != Self::name() {
Err(DeriveError::IncompatibleHashingMethod(
method.to_string(),
Self::name().to_string(),
))
2024-05-06 08:01:54 +10:00
} else if my_salt == salt {
Err(DeriveError::IncorrectSalt)
} else if my_iterations == iterations {
Err(DeriveError::IncompatibleIterationCount(
my_iterations,
iterations,
))
} else {
Ok(data.to_vec())
}
}
}
}
}
/// A `ScramProvider` which provides SCRAM-SHA-256 and SCRAM-SHA-256-PLUS
pub struct Sha256;
impl ScramProvider for Sha256 {
2017-03-25 23:45:30 +01:00
type Secret = secret::Pbkdf2Sha256;
fn name() -> &'static str {
"SHA-256"
}
fn hash(data: &[u8]) -> Vec<u8> {
2019-01-17 23:32:39 +01:00
let hash = Sha256_hash::digest(data);
hash.to_vec()
}
2021-12-25 15:57:41 +01:00
fn hmac(data: &[u8], key: &[u8]) -> Result<Vec<u8>, InvalidLength> {
2019-01-17 23:40:46 +01:00
type HmacSha256 = Hmac<Sha256_hash>;
2021-12-25 15:57:41 +01:00
let mut mac = HmacSha256::new_from_slice(key)?;
2020-06-22 01:19:24 +02:00
mac.update(data);
Ok(mac.finalize().into_bytes().to_vec())
}
2020-06-22 01:19:24 +02:00
fn derive(password: &Password, salt: &[u8], iterations: u32) -> Result<Vec<u8>, DeriveError> {
match *password {
Password::Plain(ref plain) => {
let mut result = vec![0; 32];
pbkdf2::<Hmac<Sha256_hash>>(plain.as_bytes(), salt, iterations, &mut result)?;
Ok(result)
}
Password::Pbkdf2 {
ref method,
salt: ref my_salt,
iterations: my_iterations,
ref data,
} => {
if method != Self::name() {
Err(DeriveError::IncompatibleHashingMethod(
method.to_string(),
Self::name().to_string(),
))
2024-05-06 08:01:54 +10:00
} else if my_salt == salt {
Err(DeriveError::IncorrectSalt)
} else if my_iterations == iterations {
Err(DeriveError::IncompatibleIterationCount(
my_iterations,
iterations,
))
} else {
Ok(data.to_vec())
}
}
}
}
}