243 lines
9.6 KiB
Rust
243 lines
9.6 KiB
Rust
//! Logins that servers ask for: Basic and Digest (RFC 7617, RFC 7616).
|
|
|
|
use md5::Md5;
|
|
use reqwest::header::{HeaderMap, WWW_AUTHENTICATE};
|
|
use serde::{Deserialize, Serialize};
|
|
use sha2::{Digest as _, Sha256};
|
|
use std::fmt;
|
|
use std::hash::{BuildHasher, Hasher, RandomState};
|
|
use url::{Position, Url};
|
|
|
|
#[derive(Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
|
pub struct Login {
|
|
pub user: String,
|
|
pub password: String,
|
|
}
|
|
|
|
impl fmt::Debug for Login {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
f.write_str("Login([hidden])")
|
|
}
|
|
}
|
|
|
|
/// Takes the login out of `scheme://user:password@host`, for the keyring. Works for proxies too.
|
|
pub fn take_login(text: &str) -> (String, Option<Login>) {
|
|
let Ok(mut url) = Url::parse(text) else { return (text.into(), None) };
|
|
let plain = |s: &str| percent_encoding::percent_decode_str(s).decode_utf8_lossy().into_owned();
|
|
let login = Login { user: plain(url.username()), password: plain(url.password().unwrap_or_default()) };
|
|
if login == Login::default() || url.set_username("").is_err() || url.set_password(None).is_err() {
|
|
return (text.into(), None);
|
|
}
|
|
(url.into(), Some(login))
|
|
}
|
|
|
|
/// What a server wants to see.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum Challenge {
|
|
Basic,
|
|
Digest(Digest),
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Digest {
|
|
realm: String,
|
|
pub(crate) nonce: String,
|
|
opaque: Option<String>,
|
|
sha: bool,
|
|
session: bool,
|
|
qop: bool,
|
|
/// Requests answered with this nonce.
|
|
count: u32,
|
|
}
|
|
|
|
impl Challenge {
|
|
/// The strongest one that Medlar knows.
|
|
pub fn of(headers: &HeaderMap) -> Option<Challenge> {
|
|
let mut found: Vec<(u8, Challenge)> = vec![];
|
|
for value in headers.get_all(WWW_AUTHENTICATE).iter().filter_map(|v| v.to_str().ok()) {
|
|
for (scheme, params) in schemes(value) {
|
|
if scheme.eq_ignore_ascii_case("basic") {
|
|
found.push((0, Challenge::Basic));
|
|
} else if scheme.eq_ignore_ascii_case("digest")
|
|
&& let Some(d) = Digest::of(¶ms)
|
|
{
|
|
found.push((1 + u8::from(d.sha), Challenge::Digest(d)));
|
|
}
|
|
}
|
|
}
|
|
found.into_iter().max_by_key(|(strength, _)| *strength).map(|(_, c)| c)
|
|
}
|
|
}
|
|
|
|
impl Digest {
|
|
fn of(params: &[(String, String)]) -> Option<Digest> {
|
|
let get = |key: &str| params.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.clone());
|
|
let algorithm = get("algorithm").unwrap_or("MD5".into()).to_ascii_uppercase();
|
|
let (hash, session) = algorithm.strip_suffix("-SESS").map_or((algorithm.as_str(), false), |h| (h, true));
|
|
let sha = match hash {
|
|
"MD5" => false,
|
|
"SHA-256" => true,
|
|
_ => return None,
|
|
};
|
|
let qop = match get("qop") {
|
|
None => false,
|
|
Some(q) if q.split(',').any(|q| q.trim().eq_ignore_ascii_case("auth")) => true,
|
|
// Only the kind that signs bodies.
|
|
Some(_) => return None,
|
|
};
|
|
Some(Digest { realm: get("realm")?, nonce: get("nonce")?, opaque: get("opaque"), sha, session, qop, count: 0 })
|
|
}
|
|
|
|
/// The `Authorization` header for the next GET of `url`.
|
|
pub fn answer(&mut self, login: &Login, url: &Url) -> String {
|
|
self.count += 1;
|
|
let random = || RandomState::new().build_hasher().finish();
|
|
self.answer_with(login, url, &format!("{:016x}{:016x}", random(), random()))
|
|
}
|
|
|
|
fn answer_with(&self, login: &Login, url: &Url, cnonce: &str) -> String {
|
|
let Digest { realm, nonce, .. } = self;
|
|
let uri = &url[Position::BeforePath..Position::AfterQuery];
|
|
let mut secret = self.hash(&format!("{}:{realm}:{}", login.user, login.password));
|
|
if self.session {
|
|
secret = self.hash(&format!("{secret}:{nonce}:{cnonce}"));
|
|
}
|
|
let what = self.hash(&format!("GET:{uri}"));
|
|
let count = format!("{:08x}", self.count);
|
|
let response = if self.qop {
|
|
self.hash(&format!("{secret}:{nonce}:{count}:{cnonce}:auth:{what}"))
|
|
} else {
|
|
self.hash(&format!("{secret}:{nonce}:{what}"))
|
|
};
|
|
let quoted = |s: &str| format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""));
|
|
let mut out = format!(
|
|
"Digest username={}, realm={}, nonce={}, uri={}, response=\"{response}\", algorithm={}{}",
|
|
quoted(&login.user),
|
|
quoted(realm),
|
|
quoted(nonce),
|
|
quoted(uri),
|
|
if self.sha { "SHA-256" } else { "MD5" },
|
|
if self.session { "-sess" } else { "" },
|
|
);
|
|
if self.qop {
|
|
out += &format!(", qop=auth, nc={count}, cnonce=\"{cnonce}\"");
|
|
} else if self.session {
|
|
out += &format!(", cnonce=\"{cnonce}\"");
|
|
}
|
|
if let Some(opaque) = &self.opaque {
|
|
out += &format!(", opaque={}", quoted(opaque));
|
|
}
|
|
out
|
|
}
|
|
|
|
fn hash(&self, text: &str) -> String {
|
|
if self.sha { hex(&Sha256::digest(text)) } else { hex(&Md5::digest(text)) }
|
|
}
|
|
}
|
|
|
|
pub(crate) fn hex(bytes: &[u8]) -> String {
|
|
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
|
}
|
|
|
|
/// `Scheme key=value, key="value", Scheme …`, the parts of a `WWW-Authenticate` header.
|
|
fn schemes(header: &str) -> Vec<(String, Vec<(String, String)>)> {
|
|
let mut out: Vec<(String, Vec<(String, String)>)> = vec![];
|
|
let mut rest = header.trim_start_matches([' ', ',']);
|
|
while !rest.is_empty() {
|
|
let end = rest.find([' ', '=', ',']).unwrap_or(rest.len());
|
|
let word = &rest[..end];
|
|
let after = rest[end..].trim_start();
|
|
if let Some(value) = after.strip_prefix('=').map(str::trim_start) {
|
|
let (value, left) = quoted(value);
|
|
if let Some((_, params)) = out.last_mut() {
|
|
params.push((word.into(), value));
|
|
}
|
|
rest = left;
|
|
} else {
|
|
out.push((word.into(), vec![]));
|
|
rest = after;
|
|
}
|
|
rest = rest.trim_start_matches([' ', ',']);
|
|
}
|
|
out
|
|
}
|
|
|
|
/// A token or quoted string at the start, and what follows it.
|
|
fn quoted(text: &str) -> (String, &str) {
|
|
let Some(inner) = text.strip_prefix('"') else {
|
|
let end = text.find([',', ' ']).unwrap_or(text.len());
|
|
// One that starts with `=` is the rest of a token68 and means nothing here.
|
|
return (text[..end].into(), &text[end..]);
|
|
};
|
|
let (mut value, mut escaped) = (String::new(), false);
|
|
for (i, c) in inner.char_indices() {
|
|
match c {
|
|
c if escaped => {
|
|
value.push(c);
|
|
escaped = false;
|
|
}
|
|
'\\' => escaped = true,
|
|
'"' => return (value, &inner[i + 1..]),
|
|
c => value.push(c),
|
|
}
|
|
}
|
|
(value, "")
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use reqwest::header::HeaderValue;
|
|
|
|
fn of(lines: &[&str]) -> Option<Challenge> {
|
|
Challenge::of(&lines.iter().map(|l| (WWW_AUTHENTICATE, HeaderValue::from_str(l).unwrap())).collect())
|
|
}
|
|
|
|
fn digest(lines: &[&str]) -> Digest {
|
|
let Some(Challenge::Digest(d)) = of(lines) else { panic!("{lines:?}") };
|
|
d
|
|
}
|
|
|
|
/// RFC 7616, 3.9.1.
|
|
#[test]
|
|
fn digest_of_the_standard() {
|
|
let common = r#"realm="[email protected]", qop="auth, auth-int", nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS""#;
|
|
let login = Login { user: "Mufasa".into(), password: "Circle of Life".into() };
|
|
let url = Url::parse("http://www.example.org/dir/index.html").unwrap();
|
|
for (algorithm, response) in [
|
|
("SHA-256", "753927fa0e85d155564e2e272a28d1802ca10daf4496794697cf8db5856cb6c1"),
|
|
("MD5", "8ca523f5e9506fed4657c9700eebdbec"),
|
|
] {
|
|
let mut d = digest(&[&format!("Digest {common}, algorithm={algorithm}")]);
|
|
d.count = 1;
|
|
let answer = d.answer_with(&login, &url, "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ");
|
|
assert!(answer.contains(&format!("response=\"{response}\"")), "{answer}");
|
|
assert!(answer.contains("nc=00000001") && answer.contains("opaque=\"FQhe") && answer.contains("uri=\"/dir/index.html\""));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn the_strongest_known_one_is_taken() {
|
|
assert_eq!(of(&["Basic realm=\"x, Digest y\""]), Some(Challenge::Basic));
|
|
assert_eq!(of(&["Bearer realm=\"x\""]), None);
|
|
assert_eq!(of(&["Negotiate", "NTLM abc=="]), None);
|
|
assert_eq!(of(&["Digest realm=\"x\""]), None);
|
|
assert_eq!(of(&["Digest realm=x, nonce=y, algorithm=SHA-512"]), None);
|
|
assert_eq!(of(&["Digest realm=x, nonce=y, qop=auth-int, Basic realm=x"]), Some(Challenge::Basic));
|
|
let d = digest(&["Basic realm=\"a\", Digest realm=\"q\\\"\", nonce=\"n\", algorithm=md5-sess"]);
|
|
assert_eq!((d.realm.as_str(), d.nonce.as_str(), d.sha, d.session, d.qop), ("q\"", "n", false, true, false));
|
|
assert!(digest(&["Digest realm=a, nonce=b", "Digest realm=a, nonce=c, algorithm=SHA-256"]).sha);
|
|
for junk in ["", ",", "=", "Digest =", "a=b", "Digest realm=\"", "\""] {
|
|
let _ = of(&[junk]);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn logins_come_out_of_links() {
|
|
let (url, login) = take_login("https://me%40x:p%[email protected]/f?q");
|
|
assert_eq!((url.as_str(), login), ("https://h.example/f?q", Some(Login { user: "me@x".into(), password: "p:ss".into() })));
|
|
assert_eq!(take_login("http://h/f"), ("http://h/f".into(), None));
|
|
assert_eq!(take_login("no link"), ("no link".into(), None));
|
|
assert_eq!(format!("{:?}", Login { user: "u".into(), password: "p".into() }), "Login([hidden])");
|
|
}
|
|
}
|