use crate::common::validation::is_vocab_value;
use crate::error::{CheckContext, Entry, StixError as Error};
use identyhash::identify_hash;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, sync::OnceLock};
use strum::{AsRefStr, EnumIter};
fn ssdeep_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(r"^\d+:[A-Za-z0-9/+]{1,}:[A-Za-z0-9/+]{1,}$").expect("ssdeep regex is valid")
})
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Hashes(HashMap<String, String>);
impl Hashes {
pub fn new(key: &str, value: &str) -> Result<Self, Error> {
if check_hash_key(key) {
let mut hashes = HashMap::new();
hashes.insert(key.to_string(), value.to_string());
Ok(Self(hashes))
} else {
Err(Error::ValidationError(format!("Key {} is not a valid key under STIX policies. Keys may only contain letters, numbers, '-, or '_'.", key)))
}
}
pub fn insert(&mut self, key: &str, value: &str) -> Result<(), Error> {
if check_hash_key(key) {
match self.0.insert(key.to_string(), value.to_string()) {
Some(_duplicate_key) => Err(Error::ValidationError(format!(
"Duplicate value specified for {}",
key
))),
None => Ok(()),
}
} else {
Err(Error::ValidationError(format!("Key {} is not a valid key under STIX policies. Keys may only contain letters, numbers, '-, or '_'.", key)))
}
}
pub fn get(&self, key: &str) -> Option<&String> {
self.0.get(key)
}
pub fn iter(&self) -> impl Iterator<Item = (&String, &String)> {
self.0.iter()
}
pub fn length(&self) -> usize {
self.0.len()
}
}
fn check_hash_key(key: &str) -> bool {
let valid = key.len() >= 3
&& key.len() <= 250
&& (key
.chars()
.all(|c| c.is_ascii() && (c.is_alphanumeric() || c == '-' || c == '_')));
valid
}
impl crate::base::Stix for Hashes {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
for (key, value) in self.iter() {
let origin_hash_str = value.as_str();
let hash_type_identity = identify_hash(origin_hash_str).to_lowercase();
let origin_hash_type = key.as_str().to_lowercase();
if key.len() < 3 {
return Err(Error::ValidationError(format!(
"Hash type '{}' is shorter than 3 characters.",
key,
)));
}
if key.len() > 250 {
return Err(Error::ValidationError(format!(
"Hash type '{}' is longer than 250 characters.",
key,
)));
}
if !origin_hash_type.starts_with("x_")
&& !is_vocab_value::<LegalHashTypes, _>(&origin_hash_type)
{
return Err(Error::InvalidVocabValue {
value: key.clone(),
vocabulary: "hash-algorithm-ov".to_string(),
});
}
if origin_hash_type != *LegalHashTypes::SHA256.as_ref() {
ctx.warn(
Entry::new(
"hash_not_sha256",
"STIX 2.1 recommends that the SHA-256 hash should be used whenever possible.",
)
.property("hashes")
.value(key.clone()),
);
}
if (origin_hash_type == *LegalHashTypes::SHA256.as_ref()
|| origin_hash_type == *LegalHashTypes::SHA3256.as_ref())
&& hash_type_identity != *LegalHashTypes::SHA256.as_ref()
{
return Err(Error::InvalidHash {
hash_type: origin_hash_type,
hash_identity: hash_type_identity,
hash_string: origin_hash_str.to_string(),
});
}
if (origin_hash_type == *LegalHashTypes::SHA512.as_ref()
|| origin_hash_type == *LegalHashTypes::SHA3512.as_ref())
&& hash_type_identity != *LegalHashTypes::SHA512.as_ref()
{
return Err(Error::InvalidHash {
hash_type: origin_hash_type,
hash_identity: hash_type_identity,
hash_string: origin_hash_str.to_string(),
});
}
if origin_hash_type == *LegalHashTypes::SSDEEP.as_ref()
&& !ssdeep_re().is_match(origin_hash_str)
{
return Err(Error::InvalidHash {
hash_type: origin_hash_type,
hash_identity: hash_type_identity,
hash_string: origin_hash_str.to_string(),
});
}
if origin_hash_type == *LegalHashTypes::TLSH.as_ref() {
if origin_hash_str.len() != 70
&& !origin_hash_str.chars().all(|c| c.is_ascii_hexdigit())
{
return Err(Error::InvalidHash {
hash_type: origin_hash_type,
hash_identity: hash_type_identity,
hash_string: origin_hash_str.to_string(),
});
}
}
if (origin_hash_type == *LegalHashTypes::SHA1.as_ref()
|| origin_hash_type == *LegalHashTypes::MD5.as_ref())
&& hash_type_identity != origin_hash_type
{
return Err(Error::InvalidHash {
hash_type: origin_hash_type,
hash_identity: hash_type_identity,
hash_string: origin_hash_str.to_string(),
});
}
}
Ok(())
}
}
#[derive(Debug, PartialEq, Eq, Clone, AsRefStr, EnumIter, Serialize, Deserialize)]
pub enum LegalHashTypes {
#[strum(serialize = "md5")]
MD5,
#[strum(serialize = "sha-1")]
SHA1,
#[strum(serialize = "sha-256")]
SHA256,
#[strum(serialize = "sha-512")]
SHA512,
#[strum(serialize = "sha3-256")]
SHA3256,
#[strum(serialize = "sha3-512")]
SHA3512,
#[strum(serialize = "ssdeep")]
SSDEEP,
#[strum(serialize = "tlsh")]
TLSH,
}