use crate::{
base::Stix,
custom_objects::CustomObject,
cyber_observable_objects::sco::{CyberObject, CyberObjectType},
cyber_observable_objects::sco_types::{
Artifact, AutonomousSystem, Directory, DomainName, EmailAddress, EmailMessage,
File as ScoFile, Ipv4Addr, Ipv6Addr, MacAddr as ScoMacAddr, Mutex as ScoMutex,
NetworkTraffic, Process as ScoProcess, Software, Url as ScoUrl, UserAccount,
WindowsRegistryKey, WindowsRegistryKeyType, X509Certificate,
},
domain_objects::sdo::{DomainObject, DomainObjectType},
domain_objects::sdo_types::{
AttackPattern, Campaign, CourseOfAction, Grouping, Identity, Incident, Indicator,
Infrastructure, IntrusionSet, Location, Malware, MalwareAnalysis, Note, ObservedData,
Opinion, Report, ThreatActor, Tool, Vulnerability,
},
error::StixError as Error,
meta_objects::{
extension_definition::ExtensionDefinition, language_content::LanguageContent,
marking_definition::MarkingDefinition,
},
relationship_objects::{Relationship, RelationshipObject, RelationshipObjectType, Sighting},
types::{get_object_type, ExtensionType, Identified},
validation::validate_value_from_object,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use strum::AsRefStr;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, AsRefStr)]
#[serde(untagged)]
pub enum StixObject {
#[strum(serialize = "sdo")]
Sdo(DomainObject),
#[strum(serialize = "sro")]
Sro(RelationshipObject),
#[strum(serialize = "sco")]
Sco(CyberObject),
#[strum(serialize = "language-content")]
LanguageContent(LanguageContent),
#[strum(serialize = "extension-definition")]
ExtensionDefinition(ExtensionDefinition),
#[strum(serialize = "marking-definition")]
MarkingDefinition(MarkingDefinition),
#[strum(serialize = "custom")]
Custom(CustomObject),
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Options {
#[serde(default = "default_strict")]
pub strict: bool,
#[serde(default = "default_version")]
pub version: String,
#[serde(default)]
pub allow_custom: bool,
}
impl Default for Options {
fn default() -> Self {
Self {
strict: default_strict(),
version: default_version(),
allow_custom: false,
}
}
}
fn default_strict() -> bool {
true
}
fn default_version() -> String {
"2.1".to_string()
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Envelope {
pub object: Value,
#[serde(default)]
pub options: Options,
}
impl StixObject {
pub fn get_object_type(&self) -> Result<&str, Error> {
match self {
StixObject::Custom(custom_object) => match custom_object.get_object_type()? {
ExtensionType::NewSdo => Ok("sdo"),
ExtensionType::NewSro => Ok("sro"),
ExtensionType::NewSco => Ok("sco"),
_ => unreachable!(),
},
_ => Ok(self.as_ref()),
}
}
pub fn get_type(&self) -> &str {
match self {
StixObject::Sdo(sdo) => sdo.object_type.as_ref(),
StixObject::Sro(sro) => sro.object_type.as_ref(),
StixObject::Sco(sco) => sco.object_type.as_ref(),
StixObject::LanguageContent(_) => "language-content",
StixObject::ExtensionDefinition(_) => "extension-definition",
StixObject::MarkingDefinition(_) => "marking-definition",
Self::Custom(custom) => custom.object_type.as_ref(),
}
}
pub fn get_id(&self) -> String {
match self {
StixObject::Sdo(sdo) => sdo.get_id().to_string(),
StixObject::Sro(sro) => sro.get_id().to_string(),
StixObject::Sco(sco) => sco.get_id().to_string(),
StixObject::LanguageContent(language_content) => language_content.get_id().to_string(),
StixObject::ExtensionDefinition(extension_definition) => {
extension_definition.get_id().to_string()
}
StixObject::MarkingDefinition(marking_definition) => {
marking_definition.get_id().to_string()
}
Self::Custom(custom) => custom.get_id().to_string(),
}
}
pub fn get_modified(&self) -> Option<String> {
match self {
StixObject::Sdo(sdo) => Some(sdo.common_properties.modified.as_ref()?.to_string()),
StixObject::Sro(sro) => Some(sro.common_properties.modified.as_ref()?.to_string()),
StixObject::Sco(_) => None,
StixObject::LanguageContent(language_content) => Some(
language_content
.common_properties
.modified
.as_ref()?
.to_string(),
),
StixObject::ExtensionDefinition(extension_definition) => Some(
extension_definition
.common_properties
.modified
.as_ref()?
.to_string(),
),
StixObject::MarkingDefinition(marking_definition) => Some(
marking_definition
.common_properties
.modified
.as_ref()?
.to_string(),
),
Self::Custom(custom) => custom.get_modified(),
}
}
pub fn from_json(json_str: &str, allow_custom: bool) -> Result<Self, Error> {
let value: Value = serde_json::from_str(json_str)
.map_err(|e| Error::DeserializationError(e.to_string()))?;
Self::from_value(value, allow_custom, true)
}
pub fn from_value(value: Value, allow_custom: bool, strict: bool) -> Result<Self, Error> {
let type_name = value
.get("type")
.and_then(|v| v.as_str())
.unwrap_or_default();
match get_object_type(type_name).as_ref() {
"sdo" => Ok(StixObject::Sdo(validate_value_from_object(
value,
allow_custom,
strict,
)?)),
"sro" => Ok(StixObject::Sro(validate_value_from_object(
value,
allow_custom,
strict,
)?)),
"sco" => Ok(StixObject::Sco(validate_value_from_object(
value,
allow_custom,
strict,
)?)),
"language-content" => Ok(StixObject::LanguageContent(validate_value_from_object(
value,
allow_custom,
strict,
)?)),
"extension-definition" => Ok(StixObject::ExtensionDefinition(
validate_value_from_object(value, allow_custom, strict)?,
)),
"marking-definition" => Ok(StixObject::MarkingDefinition(validate_value_from_object(
value,
allow_custom,
strict,
)?)),
_ => Ok(StixObject::Custom(validate_value_from_object(
value,
allow_custom,
strict,
)?)),
}
}
pub fn from_envelope(envelope_json: &str) -> Result<Self, Error> {
let envelope: Envelope = serde_json::from_str(envelope_json)
.map_err(|e| Error::DeserializationError(e.to_string()))?;
if envelope.options.version != "2.1" {
return Err(Error::ValidationError(format!(
"Unsupported STIX version '{}'. Only 2.1 is supported.",
envelope.options.version
)));
}
Self::from_value(
envelope.object,
envelope.options.allow_custom,
envelope.options.strict,
)
}
}
impl Stix for StixObject {
fn stix_check(&self) -> Result<(), Error> {
match self {
StixObject::Sdo(sdo) => sdo.stix_check(),
StixObject::Sro(sro) => sro.stix_check(),
StixObject::Sco(sco) => sco.stix_check(),
StixObject::LanguageContent(language_content) => language_content.stix_check(),
StixObject::ExtensionDefinition(extension_definition) => {
extension_definition.stix_check()
}
StixObject::MarkingDefinition(marking_definition) => marking_definition.stix_check(),
StixObject::Custom(custom) => custom.stix_check(),
}
}
}
pub fn parse_sdo(
json_str: &str,
strict: bool,
version: &str,
allow_custom: bool,
) -> Result<DomainObject, Error> {
if version != "2.1" {
return Err(Error::ValidationError(format!(
"Unsupported STIX version '{}'. Only 2.1 is supported.",
version
)));
}
let value: Value =
serde_json::from_str(json_str).map_err(|e| Error::DeserializationError(e.to_string()))?;
validate_value_from_object::<DomainObject>(value, allow_custom, strict)
}
pub fn parse_sco(
json_str: &str,
strict: bool,
version: &str,
allow_custom: bool,
) -> Result<CyberObject, Error> {
if version != "2.1" {
return Err(Error::ValidationError(format!(
"Unsupported STIX version '{}'. Only 2.1 is supported.",
version
)));
}
let value: Value =
serde_json::from_str(json_str).map_err(|e| Error::DeserializationError(e.to_string()))?;
validate_value_from_object::<CyberObject>(value, allow_custom, strict)
}
pub fn parse_sro(
json_str: &str,
strict: bool,
version: &str,
allow_custom: bool,
) -> Result<RelationshipObject, Error> {
if version != "2.1" {
return Err(Error::ValidationError(format!(
"Unsupported STIX version '{}'. Only 2.1 is supported.",
version
)));
}
let value: Value =
serde_json::from_str(json_str).map_err(|e| Error::DeserializationError(e.to_string()))?;
validate_value_from_object::<RelationshipObject>(value, allow_custom, strict)
}
pub trait FromJson: Sized {
fn from_json(
json_str: &str,
strict: bool,
version: &str,
allow_custom: bool,
) -> Result<Self, Error>;
}
macro_rules! impl_from_json_sdo {
($type:ty, $variant:path, $expected:literal) => {
impl FromJson for $type {
fn from_json(
json_str: &str,
strict: bool,
version: &str,
allow_custom: bool,
) -> Result<Self, Error> {
if version != "2.1" {
return Err(Error::ValidationError(format!(
"Unsupported STIX version '{}'. Only 2.1 is supported.",
version
)));
}
let value: Value = serde_json::from_str(json_str)
.map_err(|e| Error::DeserializationError(e.to_string()))?;
let sdo = validate_value_from_object::<DomainObject>(value, allow_custom, strict)?;
match sdo.object_type {
$variant(value) => Ok(value),
_ => Err(Error::ValidationError(format!(
"Expected {}, got {}",
$expected,
sdo.object_type.as_ref()
))),
}
}
}
};
}
macro_rules! impl_from_json_sco {
($type:ty, $variant:path, $expected:literal) => {
impl FromJson for $type {
fn from_json(
json_str: &str,
strict: bool,
version: &str,
allow_custom: bool,
) -> Result<Self, Error> {
if version != "2.1" {
return Err(Error::ValidationError(format!(
"Unsupported STIX version '{}'. Only 2.1 is supported.",
version
)));
}
let value: Value = serde_json::from_str(json_str)
.map_err(|e| Error::DeserializationError(e.to_string()))?;
let sco = validate_value_from_object::<CyberObject>(value, allow_custom, strict)?;
match sco.object_type {
$variant(value) => Ok(value),
_ => Err(Error::ValidationError(format!(
"Expected {}, got {}",
$expected,
sco.object_type.as_ref()
))),
}
}
}
};
}
macro_rules! impl_from_json_sro {
($type:ty, $variant:path, $expected:literal) => {
impl FromJson for $type {
fn from_json(
json_str: &str,
strict: bool,
version: &str,
allow_custom: bool,
) -> Result<Self, Error> {
if version != "2.1" {
return Err(Error::ValidationError(format!(
"Unsupported STIX version '{}'. Only 2.1 is supported.",
version
)));
}
let value: Value = serde_json::from_str(json_str)
.map_err(|e| Error::DeserializationError(e.to_string()))?;
let sro =
validate_value_from_object::<RelationshipObject>(value, allow_custom, strict)?;
match sro.object_type {
$variant(value) => Ok(value),
_ => Err(Error::ValidationError(format!(
"Expected {}, got {}",
$expected,
sro.object_type.as_ref()
))),
}
}
}
};
}
macro_rules! impl_from_json_meta {
($type:ty, $variant:path, $expected:literal) => {
impl FromJson for $type {
fn from_json(
json_str: &str,
strict: bool,
version: &str,
allow_custom: bool,
) -> Result<Self, Error> {
if version != "2.1" {
return Err(Error::ValidationError(format!(
"Unsupported STIX version '{}'. Only 2.1 is supported.",
version
)));
}
let value: Value = serde_json::from_str(json_str)
.map_err(|e| Error::DeserializationError(e.to_string()))?;
let stix_obj = StixObject::from_value(value, allow_custom, strict)?;
match stix_obj {
$variant(value) => Ok(value),
_ => Err(Error::ValidationError(format!(
"Expected {}, got {}",
$expected,
stix_obj.get_type()
))),
}
}
}
};
}
macro_rules! impl_from_json_custom {
($type:ty) => {
impl FromJson for $type {
fn from_json(
json_str: &str,
strict: bool,
version: &str,
allow_custom: bool,
) -> Result<Self, Error> {
if version != "2.1" {
return Err(Error::ValidationError(format!(
"Unsupported STIX version '{}'. Only 2.1 is supported.",
version
)));
}
let value: Value = serde_json::from_str(json_str)
.map_err(|e| Error::DeserializationError(e.to_string()))?;
let stix_obj = StixObject::from_value(value, allow_custom, strict)?;
match stix_obj {
StixObject::Custom(value) => Ok(value),
_ => Err(Error::ValidationError(format!(
"Expected custom object, got {}",
stix_obj.get_type()
))),
}
}
}
};
}
impl_from_json_sdo!(
AttackPattern,
DomainObjectType::AttackPattern,
"attack-pattern"
);
impl_from_json_sdo!(Campaign, DomainObjectType::Campaign, "campaign");
impl_from_json_sdo!(
CourseOfAction,
DomainObjectType::CourseOfAction,
"course-of-action"
);
impl_from_json_sdo!(Grouping, DomainObjectType::Grouping, "grouping");
impl_from_json_sdo!(Identity, DomainObjectType::Identity, "identity");
impl_from_json_sdo!(Incident, DomainObjectType::Incident, "incident");
impl_from_json_sdo!(Indicator, DomainObjectType::Indicator, "indicator");
impl_from_json_sdo!(
Infrastructure,
DomainObjectType::Infrastructure,
"infrastructure"
);
impl_from_json_sdo!(
IntrusionSet,
DomainObjectType::IntrusionSet,
"intrusion-set"
);
impl_from_json_sdo!(Location, DomainObjectType::Location, "location");
impl_from_json_sdo!(Malware, DomainObjectType::Malware, "malware");
impl_from_json_sdo!(
MalwareAnalysis,
DomainObjectType::MalwareAnalysis,
"malware-analysis"
);
impl_from_json_sdo!(Note, DomainObjectType::Note, "note");
impl_from_json_sdo!(
ObservedData,
DomainObjectType::ObservedData,
"observed-data"
);
impl_from_json_sdo!(Opinion, DomainObjectType::Opinion, "opinion");
impl_from_json_sdo!(Report, DomainObjectType::Report, "report");
impl_from_json_sdo!(ThreatActor, DomainObjectType::ThreatActor, "threat-actor");
impl_from_json_sdo!(Tool, DomainObjectType::Tool, "tool");
impl_from_json_sdo!(
Vulnerability,
DomainObjectType::Vulnerability,
"vulnerability"
);
impl_from_json_sco!(Artifact, CyberObjectType::Artifact, "artifact");
impl_from_json_sco!(
AutonomousSystem,
CyberObjectType::AutonomousSystem,
"autonomous-system"
);
impl_from_json_sco!(Directory, CyberObjectType::Directory, "directory");
impl_from_json_sco!(DomainName, CyberObjectType::DomainName, "domain-name");
impl_from_json_sco!(EmailAddress, CyberObjectType::EmailAddress, "email-addr");
impl_from_json_sco!(EmailMessage, CyberObjectType::EmailMessage, "email-message");
impl_from_json_sco!(ScoFile, CyberObjectType::File, "file");
impl_from_json_sco!(Ipv4Addr, CyberObjectType::Ipv4Addr, "ipv4-addr");
impl_from_json_sco!(Ipv6Addr, CyberObjectType::Ipv6Addr, "ipv6-addr");
impl_from_json_sco!(ScoMacAddr, CyberObjectType::MacAddr, "mac-addr");
impl_from_json_sco!(ScoMutex, CyberObjectType::Mutex, "mutex");
impl_from_json_sco!(
NetworkTraffic,
CyberObjectType::NetworkTraffic,
"network-traffic"
);
impl_from_json_sco!(ScoProcess, CyberObjectType::Process, "process");
impl_from_json_sco!(Software, CyberObjectType::Software, "software");
impl_from_json_sco!(ScoUrl, CyberObjectType::Url, "url");
impl_from_json_sco!(UserAccount, CyberObjectType::UserAccount, "user-account");
impl_from_json_sco!(
WindowsRegistryKey,
CyberObjectType::WindowsRegistryKey,
"windows-registry-key"
);
impl_from_json_sco!(
WindowsRegistryKeyType,
CyberObjectType::WindowsRegistryKeyType,
"windows-registry-key-type"
);
impl FromJson for X509Certificate {
fn from_json(
json_str: &str,
strict: bool,
version: &str,
allow_custom: bool,
) -> Result<Self, Error> {
let envelope = serde_json::json!({
"object": serde_json::from_str::<serde_json::Value>(json_str)
.map_err(|e| Error::DeserializationError(e.to_string()))?,
"options": {
"strict": strict,
"version": version,
"allow_custom": allow_custom
}
});
let stix_obj = StixObject::from_envelope(&envelope.to_string())?;
match stix_obj {
StixObject::Sco(sco) => match sco.object_type {
CyberObjectType::X509Certificate(value) => Ok(*value),
_ => Err(Error::ValidationError(format!(
"Expected x509-certificate, got {}",
sco.object_type.as_ref()
))),
},
_ => Err(Error::ValidationError(format!(
"Expected x509-certificate, got {}",
stix_obj.get_type()
))),
}
}
}
impl_from_json_sro!(
Relationship,
RelationshipObjectType::Relationship,
"relationship"
);
impl_from_json_sro!(Sighting, RelationshipObjectType::Sighting, "sighting");
impl_from_json_meta!(
LanguageContent,
StixObject::LanguageContent,
"language-content"
);
impl_from_json_meta!(
ExtensionDefinition,
StixObject::ExtensionDefinition,
"extension-definition"
);
impl_from_json_meta!(
MarkingDefinition,
StixObject::MarkingDefinition,
"marking-definition"
);
impl_from_json_custom!(CustomObject);
#[cfg(test)]
mod tests {
use crate::object::*;
fn minimal_attack_pattern() -> serde_json::Value {
serde_json::json!({
"type": "attack-pattern",
"id": "attack-pattern--12345678-1234-5678-1234-567812345678",
"created": "2016-05-12T08:17:27Z",
"modified": "2016-05-12T08:17:27Z",
"spec_version": "2.1",
"name": "Spear Phishing"
})
}
#[test]
fn envelope_uses_defaults_when_options_omitted() {
let envelope = serde_json::json!({
"object": minimal_attack_pattern()
});
let obj = StixObject::from_envelope(&envelope.to_string()).unwrap();
assert!(matches!(obj, StixObject::Sdo(_)));
assert_eq!(obj.get_type(), "attack-pattern");
assert_eq!(
obj.get_id(),
"attack-pattern--12345678-1234-5678-1234-567812345678"
);
}
#[test]
fn envelope_options_override_defaults() {
let mut object = minimal_attack_pattern();
object
.as_object_mut()
.unwrap()
.insert("spec_version".to_string(), serde_json::json!("3.0"));
let envelope = serde_json::json!({
"object": object,
"options": {
"strict": false,
"version": "2.1",
"allow_custom": false
}
});
let obj = StixObject::from_envelope(&envelope.to_string()).unwrap();
assert!(matches!(obj, StixObject::Sdo(_)));
}
#[test]
fn envelope_rejects_unsupported_version() {
let envelope = serde_json::json!({
"object": minimal_attack_pattern(),
"options": { "version": "2.0" }
});
let err = StixObject::from_envelope(&envelope.to_string()).unwrap_err();
assert!(
matches!(err, Error::ValidationError(_)),
"expected version ValidationError, got {err:?}"
);
}
#[test]
fn parse_sdo_matches_stix_object_dispatch() {
let json = minimal_attack_pattern().to_string();
let stix = StixObject::from_json(&json, false).unwrap();
let sdo = parse_sdo(&json, true, "2.1", false).unwrap();
assert_eq!(stix, StixObject::Sdo(sdo));
}
#[test]
fn parse_sco_matches_stix_object_dispatch() {
let json = serde_json::json!({
"type": "ipv4-addr",
"id": "ipv4-addr--12345678-1234-5678-1234-567812345678",
"spec_version": "2.1",
"value": "192.168.1.1"
})
.to_string();
let stix = StixObject::from_json(&json, false).unwrap();
let sco = parse_sco(&json, true, "2.1", false).unwrap();
assert_eq!(stix, StixObject::Sco(sco));
}
#[test]
fn parse_sro_matches_stix_object_dispatch() {
let json = serde_json::json!({
"type": "relationship",
"id": "relationship--550e8400-e29b-41d4-a716-446655440000",
"created": "2016-05-12T08:17:27Z",
"modified": "2016-05-12T08:17:27Z",
"spec_version": "2.1",
"relationship_type": "related-to",
"source_ref": "attack-pattern--550e8400-e29b-41d4-a716-446655440001",
"target_ref": "attack-pattern--550e8400-e29b-41d4-a716-446655440002"
})
.to_string();
let stix = StixObject::from_json(&json, false).unwrap();
let sro = parse_sro(&json, true, "2.1", false).unwrap();
assert_eq!(stix, StixObject::Sro(sro));
}
#[test]
fn parse_sdo_custom_properties_roundtrip() {
let mut object = minimal_attack_pattern();
let map = object.as_object_mut().unwrap();
map.insert(
"x_vendor_field".to_string(),
serde_json::json!("vendor-value"),
);
let json = object.to_string();
let sdo = parse_sdo(&json, true, "2.1", true).unwrap();
let custom = sdo
.common_properties
.custom_properties
.expect("custom properties should be captured");
assert_eq!(
custom.get("x_vendor_field"),
Some(&serde_json::json!("vendor-value"))
);
}
#[test]
fn parse_sdo_rejects_unknown_properties_when_not_allowed() {
let mut object = minimal_attack_pattern();
object.as_object_mut().unwrap().insert(
"x_vendor_field".to_string(),
serde_json::json!("vendor-value"),
);
let json = object.to_string();
let err = parse_sdo(&json, true, "2.1", false).unwrap_err();
assert!(
matches!(err, Error::UnknownProperties { .. }),
"expected UnknownProperties, got {err:?}"
);
}
#[test]
fn from_json_trait_extracts_inner_sdo() {
use crate::object::FromJson;
let json = minimal_attack_pattern().to_string();
let ap = AttackPattern::from_json(&json, true, "2.1", false).unwrap();
assert_eq!(ap.name, "Spear Phishing");
}
#[test]
fn reserialize_stix_object() {
let mut json_str = r#"{
"type": "identity",
"name": "Identity",
"description": "Responsible for managing personal digital identity",
"roles": ["User", "Administrator"],
"identity_class": "individual",
"sectors": ["Technology","Aerospace"],
"contact_information": "alex.johnson@example.com",
"spec_version": "2.1",
"id": "identity--12345678-1234-5678-1234-567812345678",
"created": "2016-05-12T08:17:27Z",
"modified": "2016-05-12T08:17:27Z",
"external_references": [
{
"source_name": "capec",
"external_id": "CAPEC-163"
}
]
}"#
.to_string();
json_str.retain(|c| !c.is_whitespace());
let object = StixObject::from_json(&json_str, false).unwrap();
let mut new_json = serde_json::to_string_pretty(&object).unwrap();
new_json.retain(|c| !c.is_whitespace());
assert_eq!(json_str, new_json)
}
}