use super::{DigestAlgorithm, HttpDigestAuth};
use crate::error::{GarrisonError, GarrisonResult};
use base64::{engine::general_purpose::STANDARD, Engine};
use std::time::{SystemTime, UNIX_EPOCH};
use subtle::ConstantTimeEq;
use uuid::Uuid;
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> {
Ok(Self {
realm: realm.to_string(),
algorithm: algorithm.parse()?,
nonce_ttl: DEFAULT_NONCE_TTL_SECONDS,
dao: 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 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 = 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 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,
};
let now = current_unix_seconds();
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 => 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 % DAO_ERROR_LOG_INTERVAL == 0 {
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;
}
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 = body.unwrap_or(&[]);
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());
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;
for (key, value) in parse_digest_params(params) {
match key.as_str() {
"username" | "realm" | "uri" => {},
"nonce" => nonce = Some(value),
"response" => response = Some(value),
"qop" => qop = Some(value),
"nc" => nc = Some(value),
"cnonce" => cnonce = Some(value),
_ => {},
}
}
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())
})?,
})
}
}
#[derive(Debug, Clone)]
struct DigestResponse {
nonce: String,
response: String,
qop: Option<String>,
nc: String,
cnonce: 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() {
while matches!(chars.peek(), Some(c) if c.is_whitespace() || *c == ',') {
chars.next();
}
if chars.peek().is_none() {
break;
}
let mut key = String::new();
while let Some(c) = chars.peek() {
if c.is_whitespace() || *c == '=' {
break;
}
key.push(chars.next().unwrap());
}
while matches!(chars.peek(), Some(c) if c.is_whitespace()) {
chars.next();
}
if chars.peek() != Some(&'=') {
break;
}
chars.next();
while matches!(chars.peek(), Some(c) if c.is_whitespace()) {
chars.next();
}
let mut value = String::new();
if chars.peek() == Some(&'"') {
chars.next();
while let Some(c) = chars.next() {
if c == '"' {
break;
}
if c == '\\' {
if let Some(escaped) = chars.next() {
value.push(escaped);
}
} else {
value.push(c);
}
}
} else {
while let Some(c) = chars.peek() {
if c.is_whitespace() || *c == ',' {
break;
}
value.push(chars.next().unwrap());
}
}
if !key.is_empty() {
result.push((key, value));
}
}
result
}
pub(super) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.ct_eq(b).into()
}
pub(super) fn current_unix_seconds() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}