stixflayer 0.1.1

Fast, spec-correct STIX 2.1 parsing, validation, and serialization in Rust.
Documentation
//! Malware SDO
//!
//! Malware is a type of TTP that represents malicious code.
//!
//! For more information see <https://docs.oasis-open.org/cti/stix/v2.1/os/stix-v2.1-os.html#_s5l7katgbp09>

use crate::error::CheckContext;
use crate::{
    base::{check_timestamp_ordering, Stix},
    common::validation::{validate_refs_are_type, warn_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)]
/// Represents a malware instance or family.
pub struct Malware {
    /// A name used to identify the malware instance or family.
    pub name: Option<String>,
    /// A description providing more details about the malware.
    pub description: Option<String>,
    /// A set of categorizations for the malware.
    pub malware_types: Option<Vec<String>>,
    /// Whether the object represents a malware family or instance.
    #[serde(default)]
    pub is_family: bool,
    /// Alternative names for the malware.
    pub aliases: Option<Vec<String>>,
    /// List of Kill Chain Phases for which this malware can be used.
    pub kill_chain_phases: Option<Vec<KillChainPhase>>,
    /// The time the malware was first seen.
    pub first_seen: Option<Timestamp>,
    /// The time the malware was last seen.
    pub last_seen: Option<Timestamp>,
    /// Operating systems the malware is executable on.
    pub operating_system_refs: Option<Vec<Identifier>>,
    /// Processor architectures the malware is executable on.
    pub architecture_execution_envs: Option<Vec<String>>,
    /// Programming languages used to implement the malware.
    pub implementation_languages: Option<Vec<String>>,
    /// Capabilities identified for the malware.
    pub capabilities: Option<Vec<String>>,
    /// Identifiers of the SCO file or artifact objects associated with the malware.
    pub sample_refs: Option<Vec<Identifier>>,
}

impl Stix for Malware {
    fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
        let mut errors = Vec::new();

        if let Some(aliases) = &self.aliases {
            add_error(&mut errors, aliases.check(ctx));
        }
        if let Some(kill_chain_phases) = &self.kill_chain_phases {
            add_error(&mut errors, kill_chain_phases.check(ctx));
        }
        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.check(ctx));
            warn_vocab_list::<MalwareType, _>(
                ctx,
                malware_types,
                "malware-type-ov",
                "malware_types",
            );
        }

        if let Some(operating_system_refs) = &self.operating_system_refs {
            add_error(&mut errors, operating_system_refs.check(ctx));
            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.check(ctx));
            warn_vocab_list::<ArchitectureExecutionEnvs, _>(
                ctx,
                architecture_execution_envs,
                "processor-architecture-ov",
                "architecture_execution_envs",
            );
        }

        if let Some(implementation_languages) = &self.implementation_languages {
            add_error(&mut errors, implementation_languages.check(ctx));
            warn_vocab_list::<ImplementationLanguage, _>(
                ctx,
                implementation_languages,
                "implementation-language-ov",
                "implementation_languages",
            );
        }
        if let Some(capabilities) = &self.capabilities {
            add_error(&mut errors, capabilities.check(ctx));
            warn_vocab_list::<MalwareCapability, _>(
                ctx,
                capabilities,
                "malware-capabilities-ov",
                "capabilities",
            );
        }
        if let Some(sample_refs) = &self.sample_refs {
            add_error(&mut errors, sample_refs.check(ctx));
            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());
    }
}