use crate::error::CheckContext;
use crate::{
base::Stix,
common::validation::{validate_refs_are_type, warn_vocab_value},
domain_objects::vocab::MalwareResult,
error::{add_error, return_multiple_errors, StixError as Error},
types::{stix_case, Identifier, ScoTypes, SdoTypes, SroTypes, StixMetaTypes, Timestamp},
};
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use stixflayer_derive::StixProperties;
use strum::IntoEnumIterator;
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, StixProperties)]
pub struct MalwareAnalysis {
pub product: String,
pub version: Option<String>,
pub host_vm_ref: Option<Identifier>,
pub operating_system_ref: Option<Identifier>,
pub installed_software_refs: Option<Vec<Identifier>>,
pub configuration_version: Option<String>,
pub modules: Option<Vec<String>>,
pub analysis_engine_version: Option<String>,
pub analysis_definition_version: Option<String>,
pub submitted: Option<Timestamp>,
pub analysis_started: Option<Timestamp>,
pub analysis_ended: Option<Timestamp>,
pub result_name: Option<String>,
pub result: Option<String>,
pub analysis_sco_refs: Option<Vec<Identifier>>,
pub sample_ref: Option<Identifier>,
}
impl Stix for MalwareAnalysis {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
let mut errors = Vec::new();
let product = &self.product;
if *product != stix_case(product) {
errors.push(Error::ValidationError(
"Product names MUST be all lowercase with words separated by a dash '-'"
.to_string(),
));
}
if let Some(host_vm_ref) = &self.host_vm_ref {
add_error(&mut errors, host_vm_ref.check(ctx));
if host_vm_ref.get_type() != "software" {
errors.push(Error::ValidationError(format!(
"A host_vm_ref must be the identifier for a software SCO. The provided identifier has type '{}'",host_vm_ref.get_type(),
)));
}
}
if let Some(modules) = &self.modules {
add_error(&mut errors, modules.check(ctx));
}
if let Some(operating_system_ref) = &self.operating_system_ref {
add_error(&mut errors, operating_system_ref.check(ctx));
if operating_system_ref.get_type() != "software" {
errors.push(Error::ValidationError(format!(
"A operating_system_ref must be the identifier for a software SCO. The provided identifier has type '{}'",operating_system_ref.get_type(),
)));
}
}
if let Some(installed_software_refs) = &self.installed_software_refs {
add_error(&mut errors, installed_software_refs.check(ctx));
add_error(
&mut errors,
validate_refs_are_type(
installed_software_refs,
&["software"],
"installed_software_refs",
),
);
}
if let Some(result) = &self.result {
warn_vocab_value::<MalwareResult, _>(ctx, result, "malware-result-ov", "result");
}
if let Some(analysis_sco_refs) = &self.analysis_sco_refs {
add_error(&mut errors, analysis_sco_refs.check(ctx));
for analysis_sco_ref in analysis_sco_refs {
if ScoTypes::iter().all(|x| x.as_ref() != stix_case(analysis_sco_ref.get_type())) {
errors.push(Error::ValidationError(format!(
"An analysis_sco_ref should come from STIX Cyber-observable objects. Malware is type '{}'.",
analysis_sco_ref,
)));
}
if !SroTypes::iter().all(|x| x.as_ref() != stix_case(analysis_sco_ref.get_type()))
|| !SdoTypes::iter()
.all(|x| x.as_ref() != stix_case(analysis_sco_ref.get_type()))
|| !StixMetaTypes::iter()
.all(|x| x.as_ref() != stix_case(analysis_sco_ref.get_type()))
{
errors.push(Error::ValidationError(format!(
"An analysis_sco_ref should come from STIX Cyber-observable objects. Malware '{}' is not in the SCO.",
analysis_sco_ref,
)));
}
}
}
if let Some(sample_ref) = &self.sample_ref {
add_error(&mut errors, sample_ref.check(ctx));
if !ScoTypes::iter().any(|x| x.as_ref() == stix_case(sample_ref.get_type())) {
errors.push(Error::ValidationError(format!(
"A sample_ref must be an SCO. Malware Analysis host_vm_ref is type '{}'.",
sample_ref.get_type(),
)));
}
if !SroTypes::iter().all(|x| x.as_ref() != stix_case(sample_ref.get_type()))
|| !SdoTypes::iter().all(|x| x.as_ref() != stix_case(sample_ref.get_type()))
|| !StixMetaTypes::iter().all(|x| x.as_ref() != stix_case(sample_ref.get_type()))
{
errors.push(Error::ValidationError(format!(
"A sample_ref must be an SCO. Malware Analysis host_vm_ref is type '{}'.",
sample_ref,
)));
}
}
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_analysis() -> DomainObject {
DomainObjectBuilder::new("malware-analysis")
.unwrap()
.set_result("benign".to_string())
.unwrap()
.product("malware-analysis".to_string())
.unwrap()
.host_vm_ref(
Identifier::from_str("software--5b7f978f-7299-57f5-b5ff-f043f6b3cf8d").unwrap(),
)
.unwrap()
.operating_system_ref(
Identifier::from_str("software--2a40a042-e9d3-529d-b029-7a9a3c4e7b79").unwrap(),
)
.unwrap()
.installed_software_refs(vec![Identifier::from_str(
"software--8e2e2d2b-17d4-5cbf-938f-98ee46b3cd3f",
)
.unwrap()])
.unwrap()
.configuration_version("v1.3.2".to_string())
.unwrap()
.modules(vec!["Dridex".to_string(), "Ransomware".to_string()])
.unwrap()
.analysis_engine_version("v1.1.1".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_analysis() {
let malware_analysis = expected_malware_analysis();
let json = r#"{
"type": "malware-analysis",
"result": "benign",
"product": "malware-analysis",
"host_vm_ref": "software--5b7f978f-7299-57f5-b5ff-f043f6b3cf8d",
"operating_system_ref":"software--2a40a042-e9d3-529d-b029-7a9a3c4e7b79",
"installed_software_refs":["software--8e2e2d2b-17d4-5cbf-938f-98ee46b3cd3f"],
"configuration_version":"v1.3.2",
"modules":["Dridex", "Ransomware"],
"analysis_engine_version":"v1.1.1",
"spec_version": "2.1",
"id": "malware-analysis--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 = serde_json::to_value(&malware_analysis).unwrap();
let expected_value: Value = serde_json::from_str(json).unwrap();
assert_eq!(&result, &expected_value)
}
#[test]
fn deserialize_malware_analysis() {
let json = r#"{
"type": "malware-analysis",
"result": "benign",
"product": "malware-analysis",
"host_vm_ref": "software--5b7f978f-7299-57f5-b5ff-f043f6b3cf8d",
"operating_system_ref":"software--2a40a042-e9d3-529d-b029-7a9a3c4e7b79",
"installed_software_refs":["software--8e2e2d2b-17d4-5cbf-938f-98ee46b3cd3f"],
"configuration_version":"v1.3.2",
"modules":["Dridex", "Ransomware"],
"analysis_engine_version":"v1.1.1",
"spec_version": "2.1",
"id": "malware-analysis--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_analysis());
}
}