use crate::error::{Error, Result};
use base64::{engine::general_purpose::STANDARD as B64, Engine};
#[derive(Debug, Clone)]
pub enum Secret {
Password(String),
NtHash([u8; 16]),
}
impl Secret {
pub fn from_input(s: &str) -> Self {
let candidate = if let Some((lm, nt)) = s.split_once(':') {
if lm.len() == 32
&& nt.len() == 32
&& lm.chars().all(|c| c.is_ascii_hexdigit())
&& nt.chars().all(|c| c.is_ascii_hexdigit())
{
Some(nt)
} else {
None
}
} else if s.len() == 32 && s.chars().all(|c| c.is_ascii_hexdigit()) {
Some(s)
} else {
None
};
if let Some(hex) = candidate {
let mut h = [0u8; 16];
for i in 0..16 {
h[i] = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).unwrap_or(0);
}
Secret::NtHash(h)
} else {
Secret::Password(s.to_string())
}
}
}
pub fn split_user(raw: &str) -> (String, String) {
if let Some((d, u)) = raw.split_once('\\') {
(d.to_string(), u.to_string())
} else if let Some((u, d)) = raw.split_once('@') {
(d.to_string(), u.to_string())
} else {
(String::new(), raw.to_string())
}
}
pub fn negotiate_header(type1: &[u8]) -> String {
format!("Negotiate {}", B64.encode(type1))
}
pub fn parse_challenge_header(www_authenticate: &str) -> Result<Vec<u8>> {
for part in www_authenticate.split(',') {
let part = part.trim();
if let Some(rest) = part.strip_prefix("Negotiate ") {
return B64.decode(rest.trim()).map_err(Error::from);
}
if let Some(rest) = part.strip_prefix("NTLM ") {
return B64.decode(rest.trim()).map_err(Error::from);
}
}
Err(Error::Auth(format!(
"no Negotiate CHALLENGE in {www_authenticate:?}"
)))
}
pub fn authenticate(
ntlm: &ntlmssp::Ntlm,
challenge: &[u8],
user_domain: (&str, &str),
secret: &Secret,
workstation: &str,
) -> Result<(String, [u8; 16])> {
let (type3, session_key) = match secret {
Secret::Password(p) => {
ntlm.authenticate(challenge, user_domain.0, user_domain.1, p, workstation)?
}
Secret::NtHash(h) => {
ntlm.authenticate_hash(challenge, user_domain.0, user_domain.1, h, workstation)?
}
};
let hdr = format!("Negotiate {}", B64.encode(&type3));
Ok((hdr, session_key))
}
pub fn encrypt(_session_key: &[u8; 16], _plaintext: &[u8]) -> Result<Vec<u8>> {
Err(Error::Unsupported(
"WSMan HTTP sign+seal not yet implemented — use HTTPS (port 5986)",
))
}