use super::*;
#[inline]
pub fn sha256(data: &[u8]) -> [u8; 32] {
sha256_finalize_from_state(SHA256_INIT, data, 0)
}
#[inline]
pub(crate) fn sha256_finalize_from_state(
mut state: [u32; 8],
data: &[u8],
prefix_bytes: u64,
) -> [u8; 32] {
let bit_len: u64 = prefix_bytes.wrapping_add(data.len() as u64).wrapping_mul(8);
let (blocks, rem_slice): (&[[u8; 64]], &[u8]) = data.as_chunks::<64>();
for block in blocks {
sha256_compress(&mut state, block);
}
let rem: usize = rem_slice.len();
let mut block: [u8; 64] = [0u8; 64];
block[..rem].copy_from_slice(rem_slice);
block[rem] = 0x80;
if rem < 56 {
block[56..64].copy_from_slice(&bit_len.to_be_bytes());
sha256_compress(&mut state, &block);
} else {
sha256_compress(&mut state, &block);
let mut last_block: [u8; 64] = [0u8; 64];
last_block[56..64].copy_from_slice(&bit_len.to_be_bytes());
sha256_compress(&mut state, &last_block);
}
let mut out: [u8; 32] = [0u8; 32];
for (i, word) in state.iter().enumerate() {
out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
}
out
}
#[inline]
pub(crate) fn sha256_finalize_32(
mut state: [u32; 8],
digest: &[u8; 32],
prefix_bytes: u64,
) -> [u8; 32] {
let bit_len: u64 = prefix_bytes.wrapping_add(32).wrapping_mul(8);
let mut block: [u8; 64] = [0u8; 64];
block[..32].copy_from_slice(digest);
block[32] = 0x80;
block[56..64].copy_from_slice(&bit_len.to_be_bytes());
sha256_compress(&mut state, &block);
let mut out: [u8; 32] = [0u8; 32];
for (i, word) in state.iter().enumerate() {
out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
}
out
}
#[inline(always)]
fn sha256_round_at(s: &mut [u32; 8], base: usize, kw: u32) {
let a: u32 = s[base & 7];
let b: u32 = s[(base + 1) & 7];
let c: u32 = s[(base + 2) & 7];
let d: u32 = s[(base + 3) & 7];
let e: u32 = s[(base + 4) & 7];
let f: u32 = s[(base + 5) & 7];
let g: u32 = s[(base + 6) & 7];
let h: u32 = s[(base + 7) & 7];
let s1: u32 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch: u32 = (e & f) ^ ((!e) & g);
let temp1: u32 = h.wrapping_add(s1).wrapping_add(ch).wrapping_add(kw);
let s0: u32 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj: u32 = (a & b) ^ (a & c) ^ (b & c);
s[(base + 3) & 7] = d.wrapping_add(temp1);
s[(base + 7) & 7] = temp1.wrapping_add(s0.wrapping_add(maj));
}
pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
let mut w: [u32; 64] = [0u32; 64];
let (words, _): (&[[u8; 4]], &[u8]) = block.as_chunks::<4>();
for (slot, word) in w[..16].iter_mut().zip(words.iter()) {
*slot = u32::from_be_bytes(*word);
}
for i in 16..64usize {
let w15: u32 = w[i - 15];
let w2: u32 = w[i - 2];
let s0: u32 = w15.rotate_right(7) ^ w15.rotate_right(18) ^ (w15 >> 3);
let s1: u32 = w2.rotate_right(17) ^ w2.rotate_right(19) ^ (w2 >> 10);
w[i] = w[i - 16]
.wrapping_add(s0)
.wrapping_add(w[i - 7])
.wrapping_add(s1);
}
let mut s: [u32; 8] = *state;
let (k_chunks, _): (&[[u32; 8]], &[u32]) = SHA256_K.as_chunks::<8>();
let (w_chunks, _): (&[[u32; 8]], &[u32]) = w.as_chunks::<8>();
for (k, w8) in k_chunks.iter().zip(w_chunks.iter()) {
sha256_round_at(&mut s, 0, k[0].wrapping_add(w8[0]));
sha256_round_at(&mut s, 7, k[1].wrapping_add(w8[1]));
sha256_round_at(&mut s, 6, k[2].wrapping_add(w8[2]));
sha256_round_at(&mut s, 5, k[3].wrapping_add(w8[3]));
sha256_round_at(&mut s, 4, k[4].wrapping_add(w8[4]));
sha256_round_at(&mut s, 3, k[5].wrapping_add(w8[5]));
sha256_round_at(&mut s, 2, k[6].wrapping_add(w8[6]));
sha256_round_at(&mut s, 1, k[7].wrapping_add(w8[7]));
}
for (dst, &delta) in state.iter_mut().zip(s.iter()) {
*dst = dst.wrapping_add(delta);
}
}
#[inline]
pub(crate) fn precompute_hmac_sha256_key(key: &[u8]) -> HmacSha256Key {
let mut pad: [u8; 64] = [0x36u8; 64];
if key.len() > 64 {
let hashed: [u8; 32] = sha256(key);
for (slot, &byte) in pad[..32].iter_mut().zip(hashed.iter()) {
*slot ^= byte;
}
} else {
for (slot, &byte) in pad[..key.len()].iter_mut().zip(key.iter()) {
*slot ^= byte;
}
}
let mut ipad_state: [u32; 8] = SHA256_INIT;
sha256_compress(&mut ipad_state, &pad);
for slot in &mut pad {
*slot ^= 0x6a;
}
let mut opad_state: [u32; 8] = SHA256_INIT;
sha256_compress(&mut opad_state, &pad);
HmacSha256Key {
ipad_state,
opad_state,
}
}
#[inline]
pub(crate) fn hmac_sha256_with_key(pre: &HmacSha256Key, data: &[u8]) -> [u8; 32] {
let inner_hash: [u8; 32] = sha256_finalize_from_state(pre.ipad_state, data, 64);
sha256_finalize_32(pre.opad_state, &inner_hash, 64)
}
#[inline]
pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
let pre: HmacSha256Key = precompute_hmac_sha256_key(key);
hmac_sha256_with_key(&pre, data)
}
#[inline]
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff: u8 = 0;
for (&x, &y) in a.iter().zip(b.iter()) {
diff |= x ^ y;
}
diff == 0
}
#[inline]
pub(crate) fn encode_hex_32_stack(bytes: &[u8; 32]) -> [u8; 64] {
let mut out: [u8; 64] = [0u8; 64];
for (idx, &byte) in bytes.iter().enumerate() {
out[idx * 2] = HEX_DIGITS[(byte >> 4) as usize];
out[idx * 2 + 1] = HEX_DIGITS[(byte & 0x0F) as usize];
}
out
}
pub fn issue_csrf_token(secret: &[u8], nonce: &str) -> String {
let mac: [u8; 32] = hmac_sha256(secret, nonce.as_bytes());
let sig_bytes: [u8; 64] = encode_hex_32_stack(&mac);
let mut out: String = String::with_capacity(nonce.len() + 1 + sig_bytes.len());
out.push_str(nonce);
out.push('.');
if let Ok(sig) = from_utf8(&sig_bytes) {
out.push_str(sig);
}
out
}
#[inline]
pub(crate) fn verify_csrf_token_with_key(pre: &HmacSha256Key, token: &str) -> bool {
let Some((nonce, provided_sig)) = token.split_once('.') else {
return false;
};
if nonce.is_empty() || provided_sig.len() != 64 {
return false;
}
let expected_mac: [u8; 32] = hmac_sha256_with_key(pre, nonce.as_bytes());
let expected_sig: [u8; 64] = encode_hex_32_stack(&expected_mac);
constant_time_eq(provided_sig.as_bytes(), &expected_sig)
}
#[inline]
pub fn verify_csrf_token(secret: &[u8], token: &str) -> bool {
let Some((nonce, provided_sig)) = token.split_once('.') else {
return false;
};
if nonce.is_empty() || provided_sig.len() != 64 {
return false;
}
let expected_mac: [u8; 32] = hmac_sha256(secret, nonce.as_bytes());
let expected_sig: [u8; 64] = encode_hex_32_stack(&expected_mac);
constant_time_eq(provided_sig.as_bytes(), &expected_sig)
}
#[inline]
pub(crate) fn is_encoded_dot_at(bytes: &[u8], idx: usize) -> bool {
idx + 2 < bytes.len()
&& bytes[idx] == b'%'
&& bytes[idx + 1] == b'2'
&& (bytes[idx + 2] == b'e' || bytes[idx + 2] == b'E')
}
#[inline]
pub fn has_path_traversal(path: &str) -> bool {
let bytes: &[u8] = path.as_bytes();
let len: usize = bytes.len();
let mut i: usize = 0;
while i < len {
let b: u8 = bytes[i];
if b == b'\\' || b == 0 {
return true;
}
if b == b'.' {
if (i + 1 < len && bytes[i + 1] == b'.') || is_encoded_dot_at(bytes, i + 1) {
return true;
}
} else if b == b'%' && i + 2 < len {
let b1: u8 = bytes[i + 1];
let b2: u8 = bytes[i + 2];
if b1 == b'0' && b2 == b'0' {
return true;
}
if b1 == b'5' && (b2 == b'c' || b2 == b'C') {
return true;
}
if b1 == b'2'
&& (b2 == b'e' || b2 == b'E')
&& ((i + 3 < len && bytes[i + 3] == b'.') || is_encoded_dot_at(bytes, i + 3))
{
return true;
}
}
i += 1;
}
false
}
#[inline]
pub(crate) fn is_valid_cookie_name(name: &str) -> bool {
!name.is_empty()
&& name
.bytes()
.all(|b: u8| b.is_ascii_alphanumeric() || COOKIE_TOKEN_PUNCTUATION.contains(&b))
}
#[inline]
pub(crate) fn find_cookie_value<'a>(raw_cookie: &'a str, target_name: &str) -> Option<&'a str> {
if raw_cookie.trim().is_empty() {
return None;
}
for part in raw_cookie.split(COOKIE_PAIR_DELIMITER) {
let trimmed: &'a str = part.trim();
if trimmed.is_empty() {
continue;
}
if let Some((name, value)) = trimmed.split_once(COOKIE_KV_DELIMITER) {
let name: &'a str = name.trim();
if name != target_name {
continue;
}
let value: &'a str = value.trim();
if is_valid_cookie_name(name) && !value.bytes().any(|b: u8| b <= 0x1F || b == 0x7F) {
return Some(value);
}
}
}
None
}
#[inline]
pub(crate) fn get_request_header_back_ref<'a>(
request: &'a Request,
lower_name: &str,
) -> Option<&'a str> {
if let Some(values) = request.get_headers().get(lower_name) {
return values.back().map(String::as_str);
}
if lower_name.len() <= STACK_HEADER_NAME_LEN
&& lower_name.bytes().any(|b: u8| b.is_ascii_uppercase())
{
let mut stack_buf: [u8; STACK_HEADER_NAME_LEN] = [0u8; STACK_HEADER_NAME_LEN];
for (dst, &src) in stack_buf.iter_mut().zip(lower_name.as_bytes().iter()) {
*dst = src.to_ascii_lowercase();
}
if let Ok(lower) = from_utf8(&stack_buf[..lower_name.len()]) {
return request
.get_headers()
.get(lower)
.and_then(|values: &RequestHeadersValue| values.back())
.map(String::as_str);
}
}
None
}
#[inline]
pub(crate) fn is_csrf_safe_method(method: &Method) -> bool {
method.is_get() || method.is_head() || method.is_options() || method.is_trace()
}