use crate::host::with_host;
use crate::stdlib::common::{arg, int_arg, str_arg, throws};
use crate::stdlib::fileres::{read as stream_read, strerror};
use crate::stdlib::hash::{digest_with, find, hmac, md5_bytes, read_options, sha1_bytes, Init};
use fusevm::Value;
type HmacAlgo = (fn(&[u8]) -> Vec<u8>, usize);
fn hmac_algo(algo: &str) -> Option<HmacAlgo> {
find(algo).and_then(|a| a.block.map(|b| (a.digest, b)))
}
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
Some(match name {
"md5_file" => file_digest_fn("md5_file", md5_bytes, args),
"sha1_file" => file_digest_fn("sha1_file", sha1_bytes, args),
"hash_file" => hash_file(args),
"hash_hmac_file" => hash_hmac_file(args),
"hash_equals" => Ok(Value::bool(hash_equals(args))),
"hash_pbkdf2" => hash_pbkdf2(args),
"random_bytes" => random_bytes(args),
"hash_init" => hash_init(args),
"hash_update" => hash_update(args),
"hash_update_stream" => hash_update_stream(args),
"hash_update_file" => hash_update_file(args),
"hash_final" => hash_final(args),
"hash_copy" => hash_copy(args),
_ => return None,
})
}
fn bool_arg(args: &[Value], i: usize) -> bool {
with_host(|h| h.is_truthy(&arg(args, i)))
}
fn wrap(bytes: Vec<u8>, raw: bool) -> Value {
if raw {
Value::str(crate::bytes::from_bytes(&bytes))
} else {
Value::str(hex::encode(bytes))
}
}
fn read_file(fname: &str, path: &str) -> Result<Option<Vec<u8>>, String> {
if path.is_empty() {
return Err(throws("ValueError", "Path must not be empty"));
}
match std::fs::read(path) {
Ok(bytes) => Ok(Some(bytes)),
Err(e) if std::path::Path::new(path).is_dir() => {
with_host(|h| {
h.notice(format!(
"{fname}(): Read of 8192 bytes failed with errno=21 {}",
strerror(&e)
))
});
Ok(None)
}
Err(e) => {
with_host(|h| {
h.warn(format!(
"{fname}({path}): Failed to open stream: {}",
strerror(&e)
))
});
Ok(None)
}
}
}
fn file_digest_fn(fname: &str, f: fn(&[u8]) -> Vec<u8>, args: &[Value]) -> Result<Value, String> {
let path = str_arg(args, 0);
let raw = bool_arg(args, 1);
Ok(match read_file(fname, &path)? {
Some(bytes) => wrap(f(&bytes), raw),
None => Value::bool(false),
})
}
fn hash_file(args: &[Value]) -> Result<Value, String> {
let algo = str_arg(args, 0).to_ascii_lowercase();
let path = str_arg(args, 1);
let raw = bool_arg(args, 2);
let Some(a) = find(&algo) else {
return Err(throws(
"ValueError",
"hash_file(): Argument #1 ($algo) must be a valid hashing algorithm",
));
};
let bytes = match read_file("hash_file", &path)? {
Some(b) => b,
None => return Ok(Value::bool(false)),
};
let init = read_options("hash_file", a.name, &arg(args, 3))?;
Ok(wrap(digest_with(a, &bytes, &init), raw))
}
fn hash_hmac_file(args: &[Value]) -> Result<Value, String> {
let algo = str_arg(args, 0).to_ascii_lowercase();
let path = str_arg(args, 1);
let key = crate::bytes::to_bytes(&str_arg(args, 2)).into_owned();
let raw = bool_arg(args, 3);
let (f, block_size) = match hmac_algo(&algo) {
Some(pair) => pair,
None => {
return Err(throws(
"ValueError",
"hash_hmac_file(): Argument #1 ($algo) must be a valid cryptographic \
hashing algorithm",
));
}
};
let bytes = match read_file("hash_hmac_file", &path)? {
Some(b) => b,
None => return Ok(Value::bool(false)),
};
Ok(wrap(hmac(block_size, f, &key, &bytes), raw))
}
fn hash_equals(args: &[Value]) -> bool {
let known = crate::bytes::to_bytes(&str_arg(args, 0)).into_owned();
let user = crate::bytes::to_bytes(&str_arg(args, 1)).into_owned();
if known.len() != user.len() {
return false;
}
let mut diff: u8 = 0;
for (a, b) in known.iter().zip(user.iter()) {
diff |= a ^ b;
}
diff == 0
}
fn hash_pbkdf2(args: &[Value]) -> Result<Value, String> {
let algo = str_arg(args, 0).to_ascii_lowercase();
let password = crate::bytes::to_bytes(&str_arg(args, 1)).into_owned();
let salt = crate::bytes::to_bytes(&str_arg(args, 2)).into_owned();
let iterations = int_arg(args, 3);
let length = int_arg(args, 4);
let raw = bool_arg(args, 5);
let (f, block_size) = match hmac_algo(&algo) {
Some(pair) => pair,
None => {
return Err(throws(
"ValueError",
"hash_pbkdf2(): Argument #1 ($algo) must be a valid cryptographic \
hashing algorithm",
));
}
};
if iterations <= 0 {
return Err(throws(
"ValueError",
"hash_pbkdf2(): Argument #4 ($iterations) must be greater than 0",
));
}
if length < 0 {
return Err(throws(
"ValueError",
"hash_pbkdf2(): Argument #5 ($length) must be greater than or equal to 0",
));
}
if length > (1 << 24) {
return Err("hash_pbkdf2(): Argument #5 ($length) is too large".to_string());
}
let hlen = f(&[]).len();
let length = length as usize;
let (dk_len, full) = if length == 0 {
(hlen, true)
} else if raw {
(length, false)
} else {
(length.div_ceil(2), false)
};
let dk = pbkdf2(f, block_size, &password, &salt, iterations as usize, dk_len);
if raw {
Ok(wrap(dk, true))
} else {
let hexed = hex::encode(dk);
if full {
Ok(Value::str(hexed))
} else {
Ok(Value::str(hexed[..length].to_string()))
}
}
}
fn random_bytes(args: &[Value]) -> Result<Value, String> {
let len = int_arg(args, 0);
if len < 1 {
return Err(throws(
"ValueError",
"random_bytes(): Argument #1 ($length) must be greater than 0",
));
}
if len > (1 << 24) {
return Err("random_bytes(): Argument #1 ($length) is too large".to_string());
}
let mut out = vec![0u8; len as usize];
crate::stdlib::csprng::random_bytes_throw(&mut out)?;
Ok(wrap(out, true))
}
fn pbkdf2(
f: fn(&[u8]) -> Vec<u8>,
block_size: usize,
password: &[u8],
salt: &[u8],
iterations: usize,
dk_len: usize,
) -> Vec<u8> {
let hlen = f(&[]).len();
let n_blocks = dk_len.div_ceil(hlen);
let mut out = Vec::with_capacity(n_blocks * hlen);
for i in 1..=n_blocks as u32 {
let mut msg = salt.to_vec();
msg.extend_from_slice(&i.to_be_bytes());
let mut u = hmac(block_size, f, password, &msg);
let mut t = u.clone();
for _ in 1..iterations {
u = hmac(block_size, f, password, &u);
for (tb, ub) in t.iter_mut().zip(u.iter()) {
*tb ^= *ub;
}
}
out.extend_from_slice(&t);
}
out.truncate(dk_len);
out
}
pub(crate) const HASH_HMAC: i64 = 1;
const CONTEXT_CLASS: &str = "HashContext";
fn hash_init(args: &[Value]) -> Result<Value, String> {
let algo_name = str_arg(args, 0).to_ascii_lowercase();
let hmac = int_arg(args, 1) & HASH_HMAC != 0;
let Some(algo) = find(&algo_name) else {
return Err(throws(
"ValueError",
"hash_init(): Argument #1 ($algo) must be a valid hashing algorithm",
));
};
let key = if hmac {
if algo.block.is_none() {
return Err(throws(
"ValueError",
"hash_init(): Argument #1 ($algo) must be a cryptographic hashing \
algorithm if HMAC is requested",
));
}
let key = str_arg(args, 2);
if key.is_empty() {
return Err(throws(
"ValueError",
"hash_init(): Argument #3 ($key) must not be empty when HMAC is requested",
));
}
Value::str(key)
} else {
Value::Undef
};
let (seed, secret) = match read_options("hash_init", algo.name, &arg(args, 3))? {
Init::Default => (Value::Undef, Value::Undef),
Init::Seed(n) => (Value::int(n), Value::Undef),
Init::Secret(s) => (Value::Undef, Value::str(crate::bytes::from_bytes(&s))),
};
let props = vec![
("algo".to_string(), Value::str(algo.name.to_string())),
("key".to_string(), key),
("seed".to_string(), seed),
("secret".to_string(), secret),
("data".to_string(), Value::str(String::new())),
("finalized".to_string(), Value::bool(false)),
];
Ok(with_host(|h| h.new_object_bare(CONTEXT_CLASS, props)))
}
fn context_arg(fname: &str, args: &[Value]) -> Result<Value, String> {
let ctx = arg(args, 0);
let (is_context, finalized) = with_host(|h| {
let is_context = h
.object_class(&ctx)
.is_some_and(|c| c.eq_ignore_ascii_case(CONTEXT_CLASS));
let finalized = is_context && h.is_truthy(&h.prop_get(&ctx, "finalized"));
(is_context, finalized)
});
if !is_context {
let given = with_host(|h| h.type_name_for_error(&ctx));
return Err(throws(
"TypeError",
format!("{fname}(): Argument #1 ($context) must be of type HashContext, {given} given"),
));
}
if finalized {
return Err(throws(
"TypeError",
format!("{fname}(): Argument #1 ($context) must be a valid, non-finalized HashContext"),
));
}
Ok(ctx)
}
fn context_feed(ctx: &Value, bytes: &[u8]) {
with_host(|h| {
let mut data = h.to_str(&h.prop_get(ctx, "data"));
data.extend(bytes.iter().map(|&b| char::from(b)));
h.prop_set(ctx, "data", Value::str(data));
});
}
fn hash_update(args: &[Value]) -> Result<Value, String> {
let ctx = context_arg("hash_update", args)?;
context_feed(&ctx, &crate::bytes::to_bytes(&str_arg(args, 1)));
Ok(Value::bool(true))
}
fn hash_update_stream(args: &[Value]) -> Result<Value, String> {
let ctx = context_arg("hash_update_stream", args)?;
let stream = arg(args, 1);
if !with_host(|h| h.is_resource(&stream)) {
let given = with_host(|h| h.type_name_for_error(&stream));
return Err(throws(
"TypeError",
format!("hash_update_stream(): Argument #2 ($stream) must be of type resource, {given} given"),
));
}
let length = match arg(args, 2) {
Value::Undef => -1,
_ => int_arg(args, 2),
};
let want = usize::try_from(length).unwrap_or(usize::MAX);
let bytes =
stream_read("hash_update_stream", &stream, |s| Some(s.read(want))).unwrap_or_default();
context_feed(&ctx, &bytes);
Ok(Value::int(bytes.len() as i64))
}
fn hash_update_file(args: &[Value]) -> Result<Value, String> {
let ctx = context_arg("hash_update_file", args)?;
let path = str_arg(args, 1);
Ok(match read_file("hash_update_file", &path)? {
Some(bytes) => {
context_feed(&ctx, &bytes);
Value::bool(true)
}
None => Value::bool(false),
})
}
fn hash_final(args: &[Value]) -> Result<Value, String> {
let ctx = context_arg("hash_final", args)?;
let raw = bool_arg(args, 1);
let (algo_name, key, init, data) = with_host(|h| {
let key = match h.prop_get(&ctx, "key") {
Value::Undef => None,
k => Some(crate::bytes::to_bytes(&h.to_str(&k)).into_owned()),
};
let data: Vec<u8> = h
.to_str(&h.prop_get(&ctx, "data"))
.chars()
.map(|c| c as u32 as u8)
.collect();
h.prop_set(&ctx, "data", Value::str(String::new()));
h.prop_set(&ctx, "finalized", Value::bool(true));
let init = match (h.prop_get(&ctx, "seed"), h.prop_get(&ctx, "secret")) {
(Value::Int(n), _) => Init::Seed(n),
(_, Value::Str(s)) => Init::Secret(crate::bytes::to_bytes(&s).into_owned()),
_ => Init::Default,
};
(h.to_str(&h.prop_get(&ctx, "algo")), key, init, data)
});
let algo = find(&algo_name).expect("hash_init only stores a registered algorithm");
let digest = match (key, algo.block) {
(Some(key), Some(block)) => hmac(block, algo.digest, &key, &data),
_ => digest_with(algo, &data, &init),
};
Ok(wrap(digest, raw))
}
fn hash_copy(args: &[Value]) -> Result<Value, String> {
let ctx = context_arg("hash_copy", args)?;
Ok(with_host(|h| {
let props = ["algo", "key", "seed", "secret", "data", "finalized"]
.iter()
.map(|name| (name.to_string(), h.prop_get(&ctx, name)))
.collect();
h.new_object_bare(CONTEXT_CLASS, props)
}))
}