stixflayer 0.1.1

Fast, spec-correct STIX 2.1 parsing, validation, and serialization in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Contains the implementation logic for Stix Domain Objects (SDOs).

#![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};

/// A STIX Domain Object (SDO) of some type.
///
/// Each of SDO type corresponds to a unique concept commonly represented in CTI.
/// These types can be categorized as tactics, techniques, and procedures (TTPs) or as adversary information.
///
/// For more information see <https://docs.oasis-open.org/cti/stix/v2.1/os/stix-v2.1-os.html#_nrhq5e9nylke>
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DomainObject {
    /// Identifies the type of SDO.
    #[serde(flatten)]
    pub object_type: DomainObjectType,
    /// Common object properties
    #[serde(flatten)]
    pub common_properties: CommonProperties,
}

impl DomainObject {
    /// Deserializes an SDO from a JSON String.
    /// Checks that all fields conform to the STIX 2.1 standard.
    /// If the `allow_custom` flag is false, checks that there are no fields in the JSON String
    /// that are not in the SDO type definition.
    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)
    }

    /// Returns whether this SDO has been marked as revoked.
    pub fn is_revoked(&self) -> bool {
        matches!(self.common_properties.revoked, Some(true))
    }

    /// Creates a Sighting SRO builder with this SDO as the `sighting_of_ref`.
    pub fn add_sighting(self) -> Result<RelationshipObjectBuilder, Error> {
        let sighting_of_ref = self.get_id().to_owned();

        RelationshipObjectBuilder::new_sighting(sighting_of_ref)
    }
}

// Returns a reference to the identifier of the `DomainObject`.
// This implementation accesses the `id` field from the `common_properties`
// of the `DomainObject`, providing a way to retrieve the unique identifier
// associated with this object.
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);

/// Required-property checks shared by builder assembly and semantic validation.
///
/// These used to live in the builder, which meant `from_json` accepted empty
/// required strings that constructors rejected. Running them from `check`
/// gives both paths identical behavior.
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) => {
            // Report only the required properties that are actually absent or
            // empty; `valid_from`'s epoch default stands in for "absent".
            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) => {
            // The spec requires `name` only for a malware family.
            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();

        // Check that we have the correct common properties for an SDO
        add_error(&mut errors, check_sdo_properties(&self.common_properties));

        // Check common properties
        add_error(&mut errors, self.common_properties.check(ctx));

        // Required fields that must also be non-empty.
        add_error(&mut errors, check_required_fields(&self.object_type));

        // Check that the id prefix matches the 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
            )));
        }

        // Check specific SDO type constraints
        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)
    }
}

/// Checks that the required properties for an SDO are present and that the prohibited fields for an SDO are not present
pub fn check_sdo_properties(properties: &CommonProperties) -> Result<(), Error> {
    let mut errors = Vec::new();

    // Check that the `spec_version` field exists for SDOs
    if properties.spec_version.is_none() {
        errors.push(Error::ValidationError(
            "SDOs must have a `spec_version` property.".to_string(),
        ));
    }
    // Check that the `created` field exists for SDOs
    if properties.created.is_none() {
        errors.push(Error::ValidationError(
            "SDOs must have a `created` property.".to_string(),
        ));
    }
    // Check that the `modified` field exists for SDOs
    if properties.modified.is_none() {
        errors.push(Error::ValidationError(
            "SDOs must have a `modified` property.".to_string(),
        ));
    }
    // Check that the `defanged` property is `None` for SDOs
    if properties.defanged.is_some() {
        errors.push(Error::ValidationError(
            "SDOs cannot have a `defanged` property.".to_string(),
        ));
    }

    return_multiple_errors(errors)
}

/// The various SDO types represented in STIX.
#[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 {
    /// An attack-pattern SDO, describing a way that adversaries attempt to compromise targets.
    AttackPattern(AttackPattern),
    /// A campaign SDO, a grouping of adversarial behaviors over a period of time.
    Campaign(Campaign),
    /// A course-of-action SDO, an action taken to prevent or respond to an attack.
    CourseOfAction(CourseOfAction),
    /// A grouping SDO, asserting that referenced STIX Objects share a common context.
    Grouping(Grouping),
    /// An identity SDO, representing an individual, organization, or group (or a class thereof).
    Identity(Identity),
    /// An incident SDO, which is a stub in STIX 2.1.
    Incident(Incident),
    /// An indicator SDO, containing a pattern used to detect suspicious or malicious activity.
    Indicator(Indicator),
    /// An infrastructure SDO, describing systems and resources supporting some purpose.
    Infrastructure(Infrastructure),
    /// An intrusion-set SDO, a grouped set of adversarial behaviors with common properties.
    IntrusionSet(IntrusionSet),
    /// A location SDO, representing a geographic location.
    Location(Location),
    /// A malware SDO, representing a malware instance or family.
    Malware(Malware),
    /// A malware-analysis SDO, capturing the metadata and results of a malware analysis.
    MalwareAnalysis(MalwareAnalysis),
    /// A note SDO, conveying informative text for further context or analysis.
    Note(Note),
    /// An observed-data SDO, conveying information about observed cyber-security related entities.
    ObservedData(ObservedData),
    /// An opinion SDO, assessing the correctness of the information in another STIX Object.
    Opinion(Opinion),
    /// A report SDO, a collection of threat intelligence focused on one or more topics.
    Report(Report),
    /// A threat-actor SDO, representing an individual, group, or organization with malicious intent.
    ThreatActor(ThreatActor),
    /// A tool SDO, representing legitimate software that can be used to perform attacks.
    Tool(Tool),
    /// A vulnerability SDO, representing a weakness in software or hardware logic.
    Vulnerability(Vulnerability),
}

impl Stix for DomainObjectType {
    /// Calls `stix_check()` on the internal SDO type struct
    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"));
    }
}