use crate::{
base::{check_timestamp_ordering, Stix},
common::validation::{is_vocab_value, validate_refs_are_type, validate_vocab_list},
domain_objects::vocab::{
ArchitectureExecutionEnvs, ImplementationLanguage, MalwareCapability, MalwareType,
},
error::{add_error, return_multiple_errors, StixError as Error},
types::{Identifier, KillChainPhase, Timestamp},
};
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use stixflayer_derive::StixProperties;
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, StixProperties)]
pub struct Malware {
pub name: Option<String>,
pub description: Option<String>,
pub malware_types: Option<Vec<String>>,
#[serde(default)]
pub is_family: bool,
pub aliases: Option<Vec<String>>,
pub kill_chain_phases: Option<Vec<KillChainPhase>>,
pub first_seen: Option<Timestamp>,
pub last_seen: Option<Timestamp>,
pub operating_system_refs: Option<Vec<Identifier>>,
pub architecture_execution_envs: Option<Vec<String>>,
pub implementation_languages: Option<Vec<String>>,
pub capabilities: Option<Vec<String>>,
pub sample_refs: Option<Vec<Identifier>>,
}
impl Stix for Malware {
fn stix_check(&self) -> Result<(), Error> {
let mut errors = Vec::new();
if let Some(aliases) = &self.aliases {
add_error(&mut errors, aliases.stix_check());
}
if let Some(kill_chain_phases) = &self.kill_chain_phases {
add_error(&mut errors, kill_chain_phases.stix_check());
}
if let (Some(start), Some(stop)) = (&self.first_seen, &self.last_seen) {
add_error(
&mut errors,
check_timestamp_ordering(start, stop, "first_seen", "last_seen", "Malware"),
);
}
if let Some(malware_types) = &self.malware_types {
add_error(&mut errors, malware_types.stix_check());
for malware_type in malware_types {
if malware_type.chars().any(|c| c.is_uppercase())
|| malware_type.contains('_')
|| malware_type.contains(' ')
{
errors.push(Error::ValidationError(format!(
"Open vocabulary value '{}' should be all lowercase and use hyphens instead of spaces or underscores as word separators.",
malware_type,
)));
continue;
}
if !is_vocab_value::<MalwareType, _>(malware_type) {
errors.push(Error::ValidationError(format!(
"malware_types '{}' should come from the list",
malware_type
)));
}
}
}
if let Some(operating_system_refs) = &self.operating_system_refs {
add_error(&mut errors, operating_system_refs.stix_check());
add_error(
&mut errors,
validate_refs_are_type(
operating_system_refs,
&["software"],
"operating_system_refs",
),
);
}
if let Some(architecture_execution_envs) = &self.architecture_execution_envs {
add_error(&mut errors, architecture_execution_envs.stix_check());
add_error(
&mut errors,
validate_vocab_list::<ArchitectureExecutionEnvs, _>(
architecture_execution_envs,
"processor-architecture-ov",
),
);
}
if let Some(implementation_languages) = &self.implementation_languages {
add_error(&mut errors, implementation_languages.stix_check());
add_error(
&mut errors,
validate_vocab_list::<ImplementationLanguage, _>(
implementation_languages,
"implementation-language-ov",
),
);
}
if let Some(capabilities) = &self.capabilities {
add_error(&mut errors, capabilities.stix_check());
add_error(
&mut errors,
validate_vocab_list::<MalwareCapability, _>(
capabilities,
"malware-capabilities-ov",
),
);
}
if let Some(sample_refs) = &self.sample_refs {
add_error(&mut errors, sample_refs.stix_check());
add_error(
&mut errors,
validate_refs_are_type(sample_refs, &["artifact", "file"], "sample_refs"),
);
}
return_multiple_errors(errors)
}
}
#[cfg(test)]
mod tests {
use crate::{
domain_objects::sdo::{DomainObject, DomainObjectBuilder},
types::{ExternalReference, Identifier},
};
use serde_json::Value;
use std::str::FromStr;
fn expected_malware() -> DomainObject {
DomainObjectBuilder::new("malware")
.unwrap()
.name("malware".to_string())
.unwrap()
.description("A ransomware trojan".to_string())
.unwrap()
.malware_types(vec!["adware".to_string(), "exploit-kit".to_string()])
.unwrap()
.set_family(true)
.unwrap()
.aliases(vec!["CryptoDefense".to_string(), "WannaCry".to_string()])
.unwrap()
.first_seen("2023-10-01T00:00:00.00Z".to_string())
.unwrap()
.last_seen("2023-10-01T00:00:00.00Z".to_string())
.unwrap()
.operating_system_refs(vec![Identifier::from_str(
"software--8e2e2d2b-17d4-5cbf-938f-98ee46b3cd3f",
)
.unwrap()])
.unwrap()
.architecture_execution_envs(vec!["arm".to_string(), "powerpc".to_string()])
.unwrap()
.implementation_languages(vec!["applescript".to_string(), "bash".to_string()])
.unwrap()
.capabilities(vec![
"anti-debugging".to_string(),
"anti-sandbox".to_string(),
])
.unwrap()
.external_references(vec![ExternalReference::new(
"capec",
None,
None,
Some("CAPEC-163".to_string()),
)
.unwrap()])
.build()
.unwrap()
.test_id()
.created("2016-05-12T08:17:27.000Z")
.modified("2016-05-12T08:17:27.000Z")
}
#[test]
fn serialize_malware() {
let malware = expected_malware();
let result = serde_json::to_value(&malware).unwrap();
let json = r#"{
"type": "malware",
"name": "malware",
"description": "A ransomware trojan",
"malware_types": ["adware","exploit-kit"],
"is_family": true,
"aliases": ["CryptoDefense", "WannaCry"],
"first_seen": "2023-10-01T00:00:00Z",
"last_seen": "2023-10-01T00:00:00Z",
"operating_system_refs":["software--8e2e2d2b-17d4-5cbf-938f-98ee46b3cd3f"],
"architecture_execution_envs" : ["arm", "powerpc"],
"implementation_languages": ["applescript","bash"],
"capabilities" : ["anti-debugging","anti-sandbox"],
"spec_version": "2.1",
"id": "malware--cc7fa653-c35f-43db-afdd-dce4c3a241d5",
"created": "2016-05-12T08:17:27Z",
"modified": "2016-05-12T08:17:27Z",
"external_references": [
{
"source_name": "capec",
"external_id": "CAPEC-163"
}
]
}"#;
let expected_value: Value = serde_json::from_str(json).unwrap();
assert_eq!(&result, &expected_value)
}
#[test]
fn deserialize_malware() {
let json = r#"{
"type": "malware",
"name": "malware",
"description": "A ransomware trojan",
"malware_types": ["adware","exploit-kit"],
"is_family": true,
"aliases": ["CryptoDefense", "WannaCry"],
"first_seen": "2023-10-01T00:00:00Z",
"last_seen": "2023-10-01T00:00:00Z",
"operating_system_refs":["software--8e2e2d2b-17d4-5cbf-938f-98ee46b3cd3f"],
"architecture_execution_envs" : ["arm", "powerpc"],
"implementation_languages": ["applescript","bash"],
"capabilities" : ["anti-debugging","anti-sandbox"],
"spec_version": "2.1",
"id": "malware--cc7fa653-c35f-43db-afdd-dce4c3a241d5",
"created": "2016-05-12T08:17:27Z",
"modified": "2016-05-12T08:17:27Z",
"external_references": [
{
"source_name": "capec",
"external_id": "CAPEC-163"
}
]
}"#;
let result = DomainObject::from_json(json, false).unwrap();
assert_eq!(&result, &expected_malware());
}
#[test]
fn try_ok_malware_operating_system_refs() {
let malware = DomainObjectBuilder::new("malware")
.unwrap()
.name("malware".to_string())
.unwrap()
.description("A ransomware trojan".to_string())
.unwrap()
.malware_types(vec!["adware".to_string(), "exploit-kit".to_string()])
.unwrap()
.operating_system_refs(vec![Identifier::new("software").unwrap()])
.unwrap()
.build();
assert!(malware.is_ok());
}
#[test]
fn try_err_malware_operating_system_refs() {
let malware = DomainObjectBuilder::new("malware")
.unwrap()
.name("malware".to_string())
.unwrap()
.description("A ransomware trojan".to_string())
.unwrap()
.malware_types(vec!["adware".to_string(), "exploit-kit".to_string()])
.unwrap()
.operating_system_refs(vec![Identifier::new("attack-pattern").unwrap()])
.unwrap()
.build();
assert!(malware.is_err());
let malware = DomainObjectBuilder::new("malware")
.unwrap()
.name("malware".to_string())
.unwrap()
.description("A ransomware trojan".to_string())
.unwrap()
.malware_types(vec!["adware".to_string(), "exploit-kit".to_string()])
.unwrap()
.operating_system_refs(vec![Identifier::new("sighting").unwrap()])
.unwrap()
.build();
assert!(malware.is_err());
let malware = DomainObjectBuilder::new("malware")
.unwrap()
.name("malware".to_string())
.unwrap()
.description("A ransomware trojan".to_string())
.unwrap()
.malware_types(vec!["adware".to_string(), "exploit-kit".to_string()])
.unwrap()
.operating_system_refs(vec![Identifier::new("language-content").unwrap()])
.unwrap()
.build();
assert!(malware.is_err());
}
}