#![allow(dead_code)]
use crate::error::CheckContext;
use jiff::Timestamp as JiffTimestamp;
use crate::{
base::{CommonProperties, Stix},
error::{add_error, return_multiple_errors, StixError as Error},
relationship_objects::{Related, RelationshipObjectBuilder},
types::{Identified, Identifier},
validation::validate_value,
};
#[cfg(test)]
use crate::types::Timestamp;
pub mod attack_pattern;
pub mod builder;
pub mod campaign;
pub mod course_of_action;
pub mod grouping;
pub mod identity;
pub mod incident;
pub mod indicator;
pub mod infrastructure;
pub mod intrusion_set;
pub mod location;
pub mod malware;
pub mod malware_analysis;
pub mod note;
pub mod observed_data;
pub mod opinion;
pub mod report;
pub mod threat_actor;
pub mod tool;
pub mod vulnerability;
#[cfg(test)]
use crate::relationship_objects::RelationshipObject;
pub use attack_pattern::AttackPattern;
pub use campaign::Campaign;
pub use course_of_action::CourseOfAction;
pub use grouping::Grouping;
pub use identity::Identity;
pub use incident::Incident;
pub use indicator::Indicator;
pub use infrastructure::Infrastructure;
pub use intrusion_set::IntrusionSet;
pub use location::Location;
pub use malware::Malware;
pub use malware_analysis::MalwareAnalysis;
pub use note::Note;
pub use observed_data::ObservedData;
pub use opinion::Opinion;
pub use report::Report;
use stixflayer_derive::StixProperties;
pub use threat_actor::ThreatActor;
pub use tool::Tool;
pub use vulnerability::Vulnerability;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::skip_serializing_none;
use strum::{AsRefStr, Display as StrumDisplay, EnumString};
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DomainObject {
#[serde(flatten)]
pub object_type: DomainObjectType,
#[serde(flatten)]
pub common_properties: CommonProperties,
}
impl DomainObject {
pub fn from_json(json: &str, allow_custom: bool) -> Result<Self, Error> {
let value: Value =
serde_json::from_str(json).map_err(|e| Error::DeserializationError(e.to_string()))?;
validate_value(value, allow_custom, true)
}
pub fn is_revoked(&self) -> bool {
matches!(self.common_properties.revoked, Some(true))
}
pub fn add_sighting(self) -> Result<RelationshipObjectBuilder, Error> {
let sighting_of_ref = self.get_id().to_owned();
RelationshipObjectBuilder::new_sighting(sighting_of_ref)
}
}
impl Identified for DomainObject {
fn get_id(&self) -> &Identifier {
&self.common_properties.id
}
}
impl Related for DomainObject {
fn add_relationship<T: Related + Identified>(
self,
target: T,
relationship_type: String,
) -> Result<RelationshipObjectBuilder, Error> {
let source_id = self.get_id().to_owned();
let target_id = target.get_id().to_owned();
RelationshipObjectBuilder::new(source_id, target_id, &relationship_type)
}
}
crate::impl_custom_properties_holder!(DomainObject);
fn check_required_fields(object_type: &DomainObjectType) -> Result<(), Error> {
match object_type {
DomainObjectType::AttackPattern(ref attack_pattern) => {
if attack_pattern.name.is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "name".to_string(),
});
}
}
DomainObjectType::Campaign(ref campaign) => {
if campaign.name.is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "name".to_string(),
});
}
}
DomainObjectType::CourseOfAction(ref course_of_action) => {
if course_of_action.name.is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "name".to_string(),
});
}
}
DomainObjectType::Grouping(ref grouping) => {
if grouping.object_refs.is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "object_refs".to_string(),
});
}
}
DomainObjectType::Identity(ref identity) => {
if identity.name.is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "name".to_string(),
});
}
}
DomainObjectType::Incident(ref incident) => {
if incident.name.is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "name".to_string(),
});
}
}
DomainObjectType::Indicator(ref indicator) => {
let mut errors = Vec::new();
if indicator.pattern.is_empty() {
errors.push(Error::MissingProperty {
object_type: object_type.to_string(),
property: "pattern".to_string(),
});
}
if indicator.pattern_type.is_empty() {
errors.push(Error::MissingProperty {
object_type: object_type.to_string(),
property: "pattern_type".to_string(),
});
}
if indicator.valid_from.0 == JiffTimestamp::UNIX_EPOCH {
errors.push(Error::MissingProperty {
object_type: object_type.to_string(),
property: "valid_from".to_string(),
});
}
return_multiple_errors(errors)?;
}
DomainObjectType::Infrastructure(ref infrastructure) => {
if infrastructure.name.is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "name".to_string(),
});
}
}
DomainObjectType::IntrusionSet(ref intrusion_set) => {
if intrusion_set.name.is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "name".to_string(),
});
}
}
DomainObjectType::Location(_) => {}
DomainObjectType::Malware(ref malware) => {
if malware.is_family
&& (malware.name.is_none() || malware.name.as_ref().unwrap().is_empty())
{
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "name".to_string(),
});
}
}
DomainObjectType::MalwareAnalysis(ref malware_analysis) => {
if malware_analysis.product.is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "product".to_string(),
});
}
if malware_analysis.result.is_none() && malware_analysis.analysis_sco_refs.is_none() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "result or analysis_sco_refs".to_string(),
});
}
}
DomainObjectType::Note(ref note) => {
if note.content.is_empty() || note.object_refs.is_empty() {
return Err(Error::ValidationErrors(vec![
Error::MissingProperty {
object_type: object_type.to_string(),
property: "content".to_string(),
},
Error::MissingProperty {
object_type: object_type.to_string(),
property: "object_refs".to_string(),
},
]));
}
}
DomainObjectType::ObservedData(ref observed_data) => {
if observed_data.first_observed.0 == JiffTimestamp::UNIX_EPOCH
|| observed_data.last_observed.0 == JiffTimestamp::UNIX_EPOCH
|| observed_data.number_observed == 0
|| observed_data.object_refs.is_empty()
{
return Err(Error::ValidationErrors(vec![
Error::MissingProperty {
object_type: object_type.to_string(),
property: "first_observed".to_string(),
},
Error::MissingProperty {
object_type: object_type.to_string(),
property: "last_observed".to_string(),
},
Error::MissingProperty {
object_type: object_type.to_string(),
property: "number_observed".to_string(),
},
Error::MissingProperty {
object_type: object_type.to_string(),
property: "object_refs".to_string(),
},
]));
}
}
DomainObjectType::Opinion(ref opinion) => {
if opinion.object_refs.is_empty() || opinion.opinion.as_ref().is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "object_refs or opinion".to_string(),
});
}
}
DomainObjectType::Report(ref report) => {
if report.name.is_empty()
|| report.object_refs.is_empty()
|| report.published.0 == JiffTimestamp::UNIX_EPOCH
{
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "name, published, or object_refs".to_string(),
});
}
}
DomainObjectType::ThreatActor(ref threat_actor) => {
if threat_actor.name.is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "name".to_string(),
});
}
}
DomainObjectType::Tool(ref tool) => {
if tool.name.is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "name".to_string(),
});
}
}
DomainObjectType::Vulnerability(ref vulnerability) => {
if vulnerability.name.is_empty() {
return Err(Error::MissingProperty {
object_type: object_type.to_string(),
property: "name".to_string(),
});
}
}
}
Ok(())
}
impl Stix for DomainObject {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
ctx.set_object_id(Some(self.get_id().to_string()));
let mut errors = Vec::new();
add_error(&mut errors, check_sdo_properties(&self.common_properties));
add_error(&mut errors, self.common_properties.check(ctx));
add_error(&mut errors, check_required_fields(&self.object_type));
let expected_type = self.object_type.as_ref();
let actual_type = self.common_properties.id.get_type();
if expected_type != actual_type {
errors.push(Error::ValidationError(format!(
"The `id` prefix '{}' does not match the object type '{}'",
actual_type, expected_type
)));
}
add_error(
&mut errors,
self.object_type
.check(ctx)
.map_err(|e| Error::InvalidNestedObject {
context: format!(
"Domain Object {} is not a valid {}",
self.get_id(),
self.object_type.as_ref()
),
source: Box::new(e),
}),
);
return_multiple_errors(errors)
}
}
pub fn check_sdo_properties(properties: &CommonProperties) -> Result<(), Error> {
let mut errors = Vec::new();
if properties.spec_version.is_none() {
errors.push(Error::ValidationError(
"SDOs must have a `spec_version` property.".to_string(),
));
}
if properties.created.is_none() {
errors.push(Error::ValidationError(
"SDOs must have a `created` property.".to_string(),
));
}
if properties.modified.is_none() {
errors.push(Error::ValidationError(
"SDOs must have a `modified` property.".to_string(),
));
}
if properties.defanged.is_some() {
errors.push(Error::ValidationError(
"SDOs cannot have a `defanged` property.".to_string(),
));
}
return_multiple_errors(errors)
}
#[derive(
Clone,
Debug,
PartialEq,
Eq,
Serialize,
Deserialize,
AsRefStr,
EnumString,
StrumDisplay,
StixProperties,
)]
#[serde(tag = "type", rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
pub enum DomainObjectType {
AttackPattern(AttackPattern),
Campaign(Campaign),
CourseOfAction(CourseOfAction),
Grouping(Grouping),
Identity(Identity),
Incident(Incident),
Indicator(Indicator),
Infrastructure(Infrastructure),
IntrusionSet(IntrusionSet),
Location(Location),
Malware(Malware),
MalwareAnalysis(MalwareAnalysis),
Note(Note),
ObservedData(ObservedData),
Opinion(Opinion),
Report(Report),
ThreatActor(ThreatActor),
Tool(Tool),
Vulnerability(Vulnerability),
}
impl Stix for DomainObjectType {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
match self {
DomainObjectType::AttackPattern(attack_pattern) => attack_pattern.check(ctx),
DomainObjectType::Campaign(campaign) => campaign.check(ctx),
DomainObjectType::CourseOfAction(course_of_action) => course_of_action.check(ctx),
DomainObjectType::Grouping(grouping) => grouping.check(ctx),
DomainObjectType::Identity(identity) => identity.check(ctx),
DomainObjectType::Incident(incident) => incident.check(ctx),
DomainObjectType::Indicator(indicator) => indicator.check(ctx),
DomainObjectType::Infrastructure(infrastructure) => infrastructure.check(ctx),
DomainObjectType::IntrusionSet(intrustion_set) => intrustion_set.check(ctx),
DomainObjectType::Location(location) => location.check(ctx),
DomainObjectType::Note(note) => note.check(ctx),
DomainObjectType::ObservedData(observed_data) => observed_data.check(ctx),
DomainObjectType::Opinion(opinion) => opinion.check(ctx),
DomainObjectType::Malware(malware) => malware.check(ctx),
DomainObjectType::MalwareAnalysis(malware_anlaysis) => malware_anlaysis.check(ctx),
DomainObjectType::Report(report) => report.check(ctx),
DomainObjectType::ThreatActor(threat_actor) => threat_actor.check(ctx),
DomainObjectType::Tool(tool) => tool.check(ctx),
DomainObjectType::Vulnerability(vulnerability) => vulnerability.check(ctx),
}
}
}
pub use builder::DomainObjectBuilder;
#[cfg(test)]
impl DomainObject {
pub(crate) fn test_id(mut self) -> Self {
let object_type = self.object_type.as_ref();
self.common_properties.id = Identifier::new_test(object_type);
self
}
pub(crate) fn created(mut self, datetime: &str) -> Self {
self.common_properties.created = Some(Timestamp(datetime.parse().unwrap()));
self
}
pub(crate) fn modified(mut self, datetime: &str) -> Self {
self.common_properties.modified = Some(Timestamp(datetime.parse().unwrap()));
self
}
}
#[cfg(test)]
impl RelationshipObject {
pub(crate) fn test_id(mut self) -> Self {
let object_type = self.object_type.as_ref();
self.common_properties.id = Identifier::new_test(object_type);
self
}
pub(crate) fn created(mut self, datetime: &str) -> Self {
self.common_properties.created = Some(Timestamp(datetime.parse().unwrap()));
self
}
pub(crate) fn modified(mut self, datetime: &str) -> Self {
self.common_properties.modified = Some(Timestamp(datetime.parse().unwrap()));
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn indicator_reports_only_the_absent_required_field() {
let indicator = Indicator {
pattern: "[domain-name:value = 'example.com']".to_string(),
pattern_type: "stix".to_string(),
..Indicator::default()
};
let error = check_required_fields(&DomainObjectType::Indicator(indicator)).unwrap_err();
let entries = error.errors();
assert_eq!(entries.len(), 1, "expected one finding, got {entries:?}");
assert_eq!(entries[0].kind, "missing_property");
assert_eq!(entries[0].property.as_deref(), Some("valid_from"));
}
}