Challenge

This commit is contained in:
Pascal Engélibert 2025-03-31 22:29:43 +02:00
commit e090b70dba
7 changed files with 416 additions and 62 deletions

51
src/challenge.rs Normal file
View file

@ -0,0 +1,51 @@
use base64::Engine;
use sha3::{Digest};
use subtle::ConstantTimeEq;
use crate::{CHALLENGE_TIMEOUT, MAC_LEN, SALT_LEN, SECRET_LEN};
pub fn check_challenge() -> bool {
false
}
pub fn compute_challenge_mac(secret: &[u8; SECRET_LEN], salt: &[u8; SALT_LEN], timestamp: [u8; 8], ip: &[u8], user_agent: &[u8]) -> [u8; MAC_LEN] {
let mut hasher = sha3::Sha3_256::default();
hasher.update(secret);
hasher.update(salt);
hasher.update(&timestamp);
hasher.update(ip);
hasher.update(b"/");
hasher.update(user_agent);
hasher.finalize().into()
}
pub fn format_challenge_cookie(salt: &[u8; SALT_LEN], timestamp: [u8; 8], mac: &[u8; MAC_LEN]) -> String {
let mut buf = Vec::new();
buf.extend_from_slice(salt);
buf.extend_from_slice(&timestamp);
buf.extend_from_slice(mac);
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(buf)
}
pub fn verify_challenge_cookie(cookie: &[u8], secret: &[u8; SECRET_LEN], user_agent: &[u8], ip: &[u8]) -> bool {
let Ok(cookie_bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(cookie) else {
dbg!("invalid base64");
return false;
};
if cookie_bytes.len() != SALT_LEN + 8 + MAC_LEN {
dbg!("invalid len");
return false;
}
let timestamp: [u8; 8] = cookie_bytes[SALT_LEN..SALT_LEN+8].try_into().unwrap();
let timestamp_time = u64::from_be_bytes(timestamp);
if timestamp_time.wrapping_add(CHALLENGE_TIMEOUT) < std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() {
dbg!("invalid time");
return false;
}
let salt: [u8; SALT_LEN] = cookie_bytes[0..SALT_LEN].try_into().unwrap();
let mac: [u8; MAC_LEN] = cookie_bytes[SALT_LEN + 8..SALT_LEN + 8 + MAC_LEN].try_into().unwrap();
let expected_mac = compute_challenge_mac(secret, &salt, timestamp, ip, user_agent);
expected_mac.ct_eq(&mac).into()
}

View file

@ -47,11 +47,9 @@ pub fn parse_cookies<'a>(line: &'a [u8]) -> Option<&'a [u8]> {
let mut iter = line.iter().enumerate().skip(7);
while let Some((i, c)) = iter.next() {
if *c == b' ' {
continue
}
if waiting_for_name {
continue;
}
if waiting_for_name {}
//iter.advance_by(5);
}
None

View file

@ -1,16 +1,23 @@
mod challenge;
mod http;
mod policy;
use http::HeaderLineIterator;
use policy::{CompiledPolicies, Policy};
use regex::bytes::Regex;
use rand::Rng;
use regex::{bytes::Regex, bytes::RegexSet};
use std::{
io::{BufReader, Write},
net::SocketAddr,
time::Duration,
io::{BufReader, Write}, net::SocketAddr, sync::atomic::ATOMIC_BOOL_INIT, time::Duration
};
use tokio::{io::{ReadBuf, AsyncWriteExt}, time::timeout};
use tokio::{
io::{AsyncWriteExt, ReadBuf}, net::TcpSocket, time::timeout
};
const SALT_LEN: usize = 16;
const SECRET_LEN: usize = 32;
const MAC_LEN: usize = 32;
const CHALLENGE_TIMEOUT: u64 = 3600;
static CHALLENGE_BODY: &str = include_str!("challenge.html");
@ -25,17 +32,31 @@ macro_rules! mk_static {
#[tokio::main]
async fn main() {
let listen_addr = "127.0.0.1:8000".parse().unwrap();
let mut rng = rand::thread_rng();
let listen_addr: SocketAddr = "127.0.0.1:8504".parse().unwrap();
let pass_addr: SocketAddr = "127.0.0.1:80".parse().unwrap();
let policy_groups = &[&[Policy {
name: String::from("Block"),
filter: policy::Filter::FirstLineMatch(String::from("GET /block")),
action: policy::Action::Drop,
priority: 0,
}]];
let secret: [u8; SECRET_LEN] = rng.r#gen();
let challenge_response = &*mk_static!(String, format!("HTTP/1.1 200\r\ncontent-type: text/html\r\ncontent-length: {}\r\n\r\n{}", CHALLENGE_BODY.len(), CHALLENGE_BODY));
let challenge_response = &*mk_static!(
String,
format!(
"HTTP/1.1 200\r\ncontent-type: text/html\r\ncontent-length: {}\r\n\r\n{}",
CHALLENGE_BODY.len(),
CHALLENGE_BODY
)
);
let policy_groups: Vec<CompiledPolicies> = policy_groups.into_iter().map(|policies| CompiledPolicies::new(*policies)).collect();
let policy_groups: Vec<CompiledPolicies> = policy_groups
.into_iter()
.map(|policies| CompiledPolicies::new(*policies))
.collect();
let socket = realm_syscall::new_tcp_socket(&listen_addr).unwrap();
@ -46,50 +67,120 @@ async fn main() {
let listener = tokio::net::TcpListener::from_std(socket.into()).unwrap();
let cookie_regex = Regex::new(r"^Cookie: *(?:[^;=]+=[^;=]* *; *)*mesozoa *= *([0-9a-zA-Z]{4})").unwrap();
let proof_regex =
Regex::new(r"^Cookie: *(?:[^;=]+=[^;=]* *; *)*mesozoa-proof *= *([0-9a-zA-Z_-]{4})").unwrap();
let challenge_regex =
Regex::new(r"^Cookie: *(?:[^;=]+=[^;=]* *; *)*mesozoa-challenge *= *([0-9a-zA-Z_-]{75})").unwrap();
let ip_regex =
Regex::new(r"^X-Forwarded-For: *([a-fA-F0-9.:]+)$").unwrap();
let user_agent_regex =
Regex::new(r"^User-Agent: *([a-zA-Z0-9.,:;/ _()-]+)$").unwrap();
loop {
let Ok((mut client_stream, client_addr)) = listener.accept().await else {
continue;
};
//client_stream.set_nodelay(true).ok();
loop {
let Ok((mut client_stream, client_addr)) = listener.accept().await else {
continue;
};
//client_stream.set_nodelay(true).ok();
let cookie_regex = cookie_regex.clone();
tokio::spawn(async move {
let mut buf = [0u8; 1024];
let mut buf_reader = ReadBuf::new(&mut buf);
if let Err(_) = timeout(
Duration::from_millis(100),
std::future::poll_fn(|cx| client_stream.poll_peek(cx, &mut buf_reader)),
)
.await
{
println!("peek timeout");
return;
}
let mut header_line_iter = HeaderLineIterator::new(&buf);
let Some(first_line) = header_line_iter.next() else {
println!("Not HTTP, or too long line");
return;
};
// TODO matching
// for test we will challenge everything!
if let Some(captures) = header_line_iter.find_map(|line| cookie_regex.captures(line)) {
if let Some(cookie) = captures.get(1) {
let mut stdout = std::io::stdout();
stdout.write_all(cookie.as_bytes()).unwrap();
stdout.flush().unwrap();
println!("");
} else {
println!("cookie header, but no cookie")
}
} else {
println!("no cookie");
}
client_stream.writable().await.unwrap();
client_stream.write_all(challenge_response.as_bytes()).await.unwrap();
});
let proof_regex = proof_regex.clone();
let challenge_regex = challenge_regex.clone();
let ip_regex = ip_regex.clone();
let user_agent_regex = user_agent_regex.clone();
tokio::spawn(async move {
let mut buf = [0u8; 1024];
let mut buf_reader = ReadBuf::new(&mut buf);
if let Err(_) = timeout(
Duration::from_millis(100),
std::future::poll_fn(|cx| client_stream.poll_peek(cx, &mut buf_reader)),
)
.await
{
println!("peek timeout");
return;
}
let mut stdout = std::io::stdout();
stdout.write_all(&buf).unwrap();
stdout.flush().unwrap();
println!("");
let mut header_line_iter = HeaderLineIterator::new(&buf);
let Some(first_line) = header_line_iter.next() else {
println!("Not HTTP, or too long line");
return;
};
// TODO matching
// for test we will challenge everything!
let mut req_challenge = None;
let mut req_proof = None;
let mut req_user_agent: &[u8] = &[];
let mut req_ip: &[u8] = &[];
for line in header_line_iter {
if let Some(Some(m)) = challenge_regex.captures(line).map(|c| c.get(1)) {
req_challenge = Some(m.as_bytes());
}
if let Some(Some(m)) = proof_regex.captures(line).map(|c| c.get(1)) {
req_proof = Some(m.as_bytes());
}
if let Some(Some(m)) = user_agent_regex.captures(line).map(|c| c.get(1)) {
req_user_agent = m.as_bytes();
}
if let Some(Some(m)) = ip_regex.captures(line).map(|c| c.get(1)) {
req_ip = m.as_bytes();
}
}
let mut allow = false;
if let Some(req_challenge) = req_challenge {
allow = challenge::verify_challenge_cookie(req_challenge, &secret, req_user_agent, req_ip);
}
if allow {
// TODO reuse connections
let pass_socket = realm_syscall::new_tcp_socket(&pass_addr).unwrap();
pass_socket.set_reuse_address(true).ok();
let pass_socket = TcpSocket::from_std_stream(pass_socket.into());
let mut pass_stream = pass_socket.connect(pass_addr).await.unwrap();
match realm_io::bidi_zero_copy(&mut client_stream, &mut pass_stream).await {
Ok(_) => {},
Err(ref e) if e.kind() == tokio::io::ErrorKind::InvalidInput => {
realm_io::bidi_copy(&mut client_stream, &mut pass_stream).await.unwrap();
}
Err(e) => panic!("err {}", e),
}
} else {
let salt: [u8; SALT_LEN] = rand::thread_rng().r#gen();
let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
let timestamp_bytes = timestamp.to_be_bytes();
let challenge_mac = challenge::compute_challenge_mac(&secret, &salt, timestamp_bytes, req_ip, req_user_agent);
let challenge_cookie = challenge::format_challenge_cookie(&salt, timestamp_bytes, &challenge_mac);
let response = format!(
"HTTP/1.1 200\r\n\
content-type: text/html\r\n\
content-length: {}\r\n\
set-cookie: mesozoa-challenge={}; max-age=3600; samesite=strict\r\n\
\r\n\
{}",
CHALLENGE_BODY.len(),
challenge_cookie,
CHALLENGE_BODY,
);
client_stream.writable().await.unwrap();
client_stream
.write_all(response.as_bytes())
.await
.unwrap();
}
});
}
}

View file

@ -103,21 +103,33 @@ impl CompiledPolicies {
}
CompiledPolicies {
first_line_regex_set: if first_line_regexes.is_empty() {None} else {Some(RegexSet::new(&first_line_regexes).unwrap())},
header_line_regex_set: if header_line_regexes.is_empty() {None} else {Some(RegexSet::new(&header_line_regexes).unwrap())},
first_line_regex_set: if first_line_regexes.is_empty() {
None
} else {
Some(RegexSet::new(&first_line_regexes).unwrap())
},
header_line_regex_set: if header_line_regexes.is_empty() {
None
} else {
Some(RegexSet::new(&header_line_regexes).unwrap())
},
policies: compiled_policies,
}
}
pub fn evaluate<'a>(&self, mut header_lines: impl Iterator<Item=&'a [u8]>) -> Result<Option<&CompiledPolicy>, PolicyEvaluationError> {
pub fn evaluate<'a>(
&self,
mut header_lines: impl Iterator<Item = &'a [u8]>,
) -> Result<Option<&CompiledPolicy>, PolicyEvaluationError> {
let mut best_policy = None;
let mut best_priority = i32::MAX;
let first_line = header_lines.next().ok_or(PolicyEvaluationError::NoFirstLine)?;
let first_line = header_lines
.next()
.ok_or(PolicyEvaluationError::NoFirstLine)?;
if let Some(first_line_regex_set) = &self.first_line_regex_set {
//let matches = first_line_regex_set.matches(first_line);
}
Ok(best_policy)