use super::algorithm::hex_encode;
use super::{DigestAlgorithm, HttpDigestAuth};
use crate::error::{GarrisonError, GarrisonResult};
use crate::secure::ct_eq::constant_time_eq;
use base64::{engine::general_purpose::STANDARD, Engine};
use hkdf::Hkdf;
use hmac::{Hmac, KeyInit, Mac};
use sha2::Sha256;
use std::time::{SystemTime, UNIX_EPOCH};
use uuid::Uuid;
const NONCE_HMAC_HKDF_INFO: &[u8] = b"garrison-httpdigest-nonce-v1";
const DEFAULT_NONCE_TTL_SECONDS: u64 = 300;
const MAX_AUTHORIZATION_HEADER_LEN: usize = 8 * 1024;
const DAO_ERROR_LOG_INTERVAL: u64 = 100;
static DAO_ERROR_LOG_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
impl HttpDigestAuth {
pub fn new(realm: &str, algorithm: &str) -> GarrisonResult<Self> {
let algorithm: DigestAlgorithm = algorithm.parse()?;
if algorithm == DigestAlgorithm::Md5 {
tracing::warn!(
realm = %realm,
algorithm = "MD5",
"HttpDigestAuth constructed with MD5; MD5 is collision-broken and must not be used in new deployments (use SHA256)"
);
}
Ok(Self {
realm: realm.to_string(),
algorithm,
nonce_ttl: DEFAULT_NONCE_TTL_SECONDS,
dao: None,
server_key: None,
})
}
pub fn with_dao(mut self, dao: std::sync::Arc<dyn crate::dao::GarrisonDao>) -> Self {
self.dao = Some(dao);
self
}
pub fn with_nonce_ttl(mut self, ttl_seconds: u64) -> Self {
self.nonce_ttl = ttl_seconds;
self
}
pub fn with_server_key(mut self, secret: &[u8]) -> Self {
let hkdf = Hkdf::<Sha256>::new(Some(self.realm.as_bytes()), secret);
let mut key = [0u8; 32];
hkdf.expand(NONCE_HMAC_HKDF_INFO, &mut key)
.expect("HKDF-SHA256 derive 32 bytes must not fail");
self.server_key = Some(key);
self
}
pub fn nonce_ttl(&self) -> u64 {
self.nonce_ttl
}
pub fn algorithm(&self) -> DigestAlgorithm {
self.algorithm
}
pub fn challenge(&self) -> String {
let nonce = self.generate_nonce();
format!(
r#"Digest realm="{}", nonce="{}", qop="auth,auth-int", algorithm={}"#,
self.realm,
nonce,
self.algorithm.as_str()
)
}
fn generate_nonce(&self) -> String {
let timestamp = current_unix_seconds();
let random = Uuid::new_v4().simple().to_string();
let raw = match &self.server_key {
Some(key) => {
let mac = sign_nonce_payload(key, timestamp, &random);
format!("{}:{}:{}", timestamp, random, mac)
},
None => format!("{}:{}", timestamp, random),
};
STANDARD.encode(raw.as_bytes())
}
pub(super) fn is_nonce_valid(&self, nonce: &str) -> bool {
let decoded = match STANDARD.decode(nonce) {
Ok(d) => d,
Err(_) => return false,
};
let raw = match String::from_utf8(decoded) {
Ok(s) => s,
Err(_) => return false,
};
let now = current_unix_seconds();
match &self.server_key {
Some(key) => {
let parts: Vec<&str> = raw.splitn(3, ':').collect();
if parts.len() != 3 {
return false;
}
let timestamp: u64 = match parts[0].parse() {
Ok(t) => t,
Err(_) => return false,
};
if !verify_nonce_signature(key, timestamp, parts[1], parts[2]) {
return false;
}
if timestamp > now + 5 {
return false;
}
if timestamp + self.nonce_ttl < now {
return false;
}
true
},
None => {
let parts: Vec<&str> = raw.splitn(2, ':').collect();
if parts.len() != 2 {
return false;
}
let timestamp: u64 = match parts[0].parse() {
Ok(t) => t,
Err(_) => return false,
};
if timestamp > now + 5 {
return false;
}
if timestamp + self.nonce_ttl < now {
return false;
}
true
},
}
}
fn validate_nc(&self, nonce: &str, nc_hex: &str) -> bool {
let dao = match &self.dao {
Some(d) => d,
None => {
static WARNED_NO_DAO: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
if !WARNED_NO_DAO.swap(true, std::sync::atomic::Ordering::Relaxed) {
tracing::warn!(
realm = %self.realm,
"validate_nc: no DAO injected, skipping nc monotonicity check (fail-open, replay possible within the 300s window); in production inject a DAO via with_dao to enable RFC 7616 §3.4.6 replay protection"
);
}
return true;
},
};
let nc = match u64::from_str_radix(nc_hex, 16) {
Ok(v) => v,
Err(_) => return false,
};
match tokio::runtime::Handle::try_current() {
Ok(handle) => {
if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::CurrentThread {
tracing::warn!(
realm = %self.realm,
"validate_nc rejected: current_thread runtime does not support block_in_place (fail-closed per vuln-0012)"
);
return false; }
let realm = self.realm.clone();
tokio::task::block_in_place(|| {
handle.block_on(async move {
Self::validate_nc_async(dao, &realm, nonce, nc, self.nonce_ttl).await
})
})
},
Err(_) => {
tracing::warn!(
realm = %self.realm,
"validate_nc rejected: no tokio runtime available (fail-closed per vuln-0012)"
);
false },
}
}
async fn validate_nc_async(
dao: &std::sync::Arc<dyn crate::dao::GarrisonDao>,
realm: &str,
nonce: &str,
nc: u64,
ttl_seconds: u64,
) -> bool {
let key = format!("digest:nc:{}", nonce);
match dao
.compare_and_update_if_greater(&key, nc, ttl_seconds)
.await
{
Ok(updated) => updated,
Err(e) => {
let count =
DAO_ERROR_LOG_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if count.is_multiple_of(DAO_ERROR_LOG_INTERVAL) {
tracing::warn!(
realm = realm,
count = count + 1,
error = %e,
"validate_nc: DAO compare_and_update_if_greater failed, fail-closed (sampled 1/{})",
DAO_ERROR_LOG_INTERVAL
);
} else {
tracing::debug!(
realm = realm,
count = count + 1,
"validate_nc: DAO compare_and_update_if_greater failed, fail-closed (sampled, suppressed warn)"
);
}
false
},
}
}
pub fn compute_ha1(&self, username: &str, password: &str) -> String {
let data = format!("{}:{}:{}", username, self.realm, password);
self.algorithm.hash(data.as_bytes())
}
pub fn validate(&self, authorization_header: &str, method: &str, uri: &str, ha1: &str) -> bool {
self.validate_inner(authorization_header, method, uri, None, ha1)
}
pub fn validate_with_body(
&self,
authorization_header: &str,
method: &str,
uri: &str,
body: &[u8],
ha1: &str,
) -> bool {
self.validate_inner(authorization_header, method, uri, Some(body), ha1)
}
fn validate_inner(
&self,
authorization_header: &str,
method: &str,
uri: &str,
body: Option<&[u8]>,
ha1: &str,
) -> bool {
if authorization_header.len() > MAX_AUTHORIZATION_HEADER_LEN {
return false;
}
match self.parse_authorization(authorization_header) {
Ok(resp) => {
if !self.is_nonce_valid(&resp.nonce) {
return false;
}
if !self.validate_nc(&resp.nonce, &resp.nc) {
return false;
}
if !constant_time_eq(resp.uri.as_bytes(), uri.as_bytes()) {
return false;
}
let qop = resp.qop.as_deref();
let ha2 = match qop {
Some("auth") => {
let ha2_input = format!("{}:{}", method, uri);
self.algorithm.hash(ha2_input.as_bytes())
},
Some("auth-int") => {
let body_bytes = match body {
Some(b) => b,
None => return false,
};
let body_hash = self.algorithm.hash(body_bytes);
let ha2_input = format!("{}:{}:{}", method, uri, body_hash);
self.algorithm.hash(ha2_input.as_bytes())
},
_ => return false,
};
let response_input = format!(
"{}:{}:{}:{}:{}:{}",
ha1,
resp.nonce,
resp.nc,
resp.cnonce,
qop.unwrap(),
ha2
);
let expected = self.algorithm.hash(response_input.as_bytes());
resp.response.len() == expected.len()
&& constant_time_eq(expected.as_bytes(), resp.response.as_bytes())
},
Err(_) => false,
}
}
fn parse_authorization(&self, header: &str) -> GarrisonResult<DigestResponse> {
let header = header.trim();
let (scheme, params) = header
.split_once(char::is_whitespace)
.ok_or_else(|| GarrisonError::Internal("secure-http-digest-no-params::".to_string()))?;
if !scheme.eq_ignore_ascii_case("digest") {
return Err(GarrisonError::Internal(format!(
"secure-httpdigest-unsupported-scheme::{}",
scheme
)));
}
let mut nonce = None;
let mut response = None;
let mut qop = None;
let mut nc = None;
let mut cnonce = None;
let mut uri = None;
for (key, value) in parse_digest_params(params) {
match key.as_str() {
"username" | "realm" => {},
"uri" => uri = Some(value),
"nonce" => nonce = Some(value),
"response" => response = Some(value),
"qop" => qop = Some(value),
"nc" => nc = Some(value),
"cnonce" => cnonce = Some(value),
_ => {
tracing::debug!(key = %key, "httpdigest-unknown-param-ignored");
},
}
}
Ok(DigestResponse {
nonce: nonce.ok_or_else(|| {
GarrisonError::Internal("secure-http-digest-missing-nonce::".to_string())
})?,
response: response.ok_or_else(|| {
GarrisonError::Internal("secure-http-digest-missing-response::".to_string())
})?,
qop,
nc: nc.ok_or_else(|| {
GarrisonError::Internal("secure-http-digest-missing-nc::".to_string())
})?,
cnonce: cnonce.ok_or_else(|| {
GarrisonError::Internal("secure-http-digest-missing-cnonce::".to_string())
})?,
uri: uri.ok_or_else(|| {
GarrisonError::Internal("secure-http-digest-missing-uri::".to_string())
})?,
})
}
}
#[derive(Debug, Clone)]
struct DigestResponse {
nonce: String,
response: String,
qop: Option<String>,
nc: String,
cnonce: String,
uri: String,
}
fn parse_digest_params(s: &str) -> Vec<(String, String)> {
let mut result = Vec::new();
let mut chars = s.chars().peekable();
while chars.peek().is_some() {
skip_whitespace_and_commas(&mut chars);
if chars.peek().is_none() {
break;
}
let key = parse_param_key(&mut chars);
skip_whitespace_chars(&mut chars);
if chars.peek() != Some(&'=') {
break;
}
chars.next();
skip_whitespace_chars(&mut chars);
let value = parse_param_value(&mut chars);
if !key.is_empty() {
result.push((key, value));
}
}
result
}
fn skip_whitespace_and_commas(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) {
while matches!(chars.peek(), Some(c) if c.is_whitespace() || *c == ',') {
chars.next();
}
}
fn skip_whitespace_chars(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) {
while matches!(chars.peek(), Some(c) if c.is_whitespace()) {
chars.next();
}
}
fn parse_param_key(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> String {
let mut key = String::new();
while let Some(c) = chars.peek() {
if c.is_whitespace() || *c == '=' {
break;
}
key.push(chars.next().unwrap());
}
key
}
fn parse_param_value(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> String {
if chars.peek() == Some(&'"') {
parse_quoted_value(chars)
} else {
parse_unquoted_value(chars)
}
}
fn parse_quoted_value(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> String {
chars.next(); let mut value = String::new();
while let Some(c) = chars.next() {
if c == '"' {
break;
}
if c == '\\' {
if let Some(escaped) = chars.next() {
value.push(escaped);
}
} else {
value.push(c);
}
}
value
}
fn parse_unquoted_value(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> String {
let mut value = String::new();
while let Some(c) = chars.peek() {
if c.is_whitespace() || *c == ',' {
break;
}
value.push(chars.next().unwrap());
}
value
}
pub(super) fn current_unix_seconds() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
fn sign_nonce_payload(server_key: &[u8; 32], timestamp: u64, uuid: &str) -> String {
type HmacSha256 = Hmac<Sha256>;
let mut mac = HmacSha256::new_from_slice(server_key).expect("HMAC accepts 32-byte keys");
mac.update(timestamp.to_string().as_bytes());
mac.update(b":");
mac.update(uuid.as_bytes());
let result = mac.finalize().into_bytes();
hex_encode(&result)
}
fn verify_nonce_signature(
server_key: &[u8; 32],
timestamp: u64,
uuid: &str,
mac_hex: &str,
) -> bool {
let expected = sign_nonce_payload(server_key, timestamp, uuid);
mac_hex.len() == expected.len() && constant_time_eq(expected.as_bytes(), mac_hex.as_bytes())
}