stixflayer 0.1.0

Fast STIX 2.1 parsing, validation, and serialization in Rust
Documentation
//! Malware Analysis SDO
//!
//! Malware Analysis captures the metadata and results of a particular static or dynamic analysis performed on a malware instance or family.
//!
//! For more information, see <https://docs.oasis-open.org/cti/stix/v2.1/os/stix-v2.1-os.html#_6hdrixb3ua4j>

use crate::{
    base::Stix,
    common::validation::{validate_refs_are_type, validate_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 {
    /// The name of the analysis engine or product that was used.
    pub product: String,
    /// The version of the analysis product that was used to perform the analysis.
    pub version: Option<String>,
    /// A description of the virtual machine environment used to host the guest operating system.
    pub host_vm_ref: Option<Identifier>,
    /// The operating system used for the dynamic analysis of the malware instance or family.
    pub operating_system_ref: Option<Identifier>,
    /// Any non-standard software installed on the operating system.
    pub installed_software_refs: Option<Vec<Identifier>>,
    /// The named configuration of additional product configuration parameters for this analysis run.
    pub configuration_version: Option<String>,
    /// The specific analysis modules that were used and configured in the product during this analysis run.
    pub modules: Option<Vec<String>>,
    /// The version of the analysis engine or product that was used to perform the analysis.
    pub analysis_engine_version: Option<String>,
    /// The version of the analysis engine or product that was used to perform the analysis.
    pub analysis_definition_version: Option<String>,
    /// The date and time that the malware was first submitted for scanning or analysis.
    pub submitted: Option<Timestamp>,
    /// The date and time that the malware analysis was initiated.
    pub analysis_started: Option<Timestamp>,
    /// The date and time that the malware analysis ended.
    pub analysis_ended: Option<Timestamp>,
    /// The classification result as determined by the scanner or tool analysis process.
    pub result_name: Option<String>,
    /// The classification result as determined by the scanner or tool analysis process.
    pub result: Option<String>,
    /// This property contains the references to the STIX Cyber-observable Objects that were captured during the analysis process.
    pub analysis_sco_refs: Option<Vec<Identifier>>,
    /// This property contains the reference to the SCO file, network traffic or artifact object that this malware analysis was performed against.
    pub sample_ref: Option<Identifier>,
}

impl Stix for MalwareAnalysis {
    fn stix_check(&self) -> 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.stix_check());
            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.stix_check());
        }

        if let Some(operating_system_ref) = &self.operating_system_ref {
            add_error(&mut errors, operating_system_ref.stix_check());
            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.stix_check());
            add_error(
                &mut errors,
                validate_refs_are_type(
                    installed_software_refs,
                    &["software"],
                    "installed_software_refs",
                ),
            );
        }

        if let Some(result) = &self.result {
            add_error(
                &mut errors,
                validate_vocab_value::<MalwareResult, _>(result, "malware-result-ov"),
            );
        }

        if let Some(analysis_sco_refs) = &self.analysis_sco_refs {
            add_error(&mut errors, analysis_sco_refs.stix_check());
            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.stix_check());
            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());
    }
}