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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Contains the implementation logic for STIX Cyber-observable Objects (SCOs).

/// The Artifact cyber-observable object.
pub mod artifact;
/// The autonomous-system cyber-observable object.
pub mod autonomous_system;
pub mod builder;
/// The directory cyber-observable object.
pub mod directory;
/// The domain-name cyber-observable object.
pub mod domain_name;
/// The email-addr cyber-observable object.
pub mod email_addr;
/// The email-message cyber-observable object.
pub mod email_message;
/// The file cyber-observable object.
pub mod file;
/// The ipv4-addr cyber-observable object.
pub mod ipv4_addr;
/// The ipv6-addr cyber-observable object.
pub mod ipv6_addr;
/// The mac-addr cyber-observable object.
pub mod mac_addr;
/// The mutex cyber-observable object.
pub mod mutex;
/// The network-traffic cyber-observable object.
pub mod network_traffic;
/// The process cyber-observable object.
pub mod process;
/// The software cyber-observable object.
pub mod software;
/// The url cyber-observable object.
pub mod url;
/// The user-account cyber-observable object.
pub mod user_account;
/// The windows-registry-key cyber-observable object.
pub mod windows_registry_key;
/// The x509-certificate cyber-observable object.
pub mod x509_certificate;

pub use artifact::Artifact;
pub use autonomous_system::AutonomousSystem;
pub use directory::Directory;
pub use domain_name::DomainName;
pub use email_addr::EmailAddress;
pub use email_message::{EmailMessage, EmailMimeCompomentType};
pub use file::File;
pub use file::File as ScoFile;
pub use ipv4_addr::Ipv4Addr;
pub use ipv6_addr::Ipv6Addr;
pub use mac_addr::MacAddr;
pub use mac_addr::MacAddr as ScoMacAddr;
pub use mutex::Mutex;
pub use mutex::Mutex as ScoMutex;
pub use network_traffic::NetworkTraffic;
pub use process::Process;
pub use process::Process as ScoProcess;
pub use software::Software;
pub use url::Url;
pub use url::Url as ScoUrl;
pub use user_account::UserAccount;
pub use windows_registry_key::{WindowsRegistryKey, WindowsRegistryKeyType};
pub use x509_certificate::{X509Certificate, X509V3Extensions};

use crate::{
    base::{CommonProperties, Stix},
    error::{add_error, return_multiple_errors, CheckContext, Entry, StixError as Error},
    relationship_objects::{Related, RelationshipObjectBuilder},
    types::{Identified, Identifier},
    validation::validate_value,
};
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use std::{collections::HashMap, sync::LazyLock};
use stixflayer_derive::StixProperties;
use strum::{AsRefStr, Display as StrumDisplay, EnumString};
// Static dictionaries of ID contributing properties for each SCO type

// ID Contributing properties that will always be present for a given SCO type
pub(super) static REQUIRED_ID_PROPERTIES: LazyLock<HashMap<&'static str, Vec<&'static str>>> =
    LazyLock::new(|| {
        let mut m = HashMap::new();
        m.insert("artifact", Vec::new());
        m.insert("autonomous-system", vec!["number"]);
        m.insert("directory", vec!["path"]);
        m.insert("domain-name", vec!["value"]);
        m.insert("email-addr", vec!["value"]);
        m.insert("email-message", Vec::new());
        m.insert("file", Vec::new());
        m.insert("ipv4-addr", vec!["value"]);
        m.insert("ipv6-addr", vec!["value"]);
        m.insert("mac-addr", vec!["value"]);
        m.insert("mutex", vec!["name"]);
        m.insert("network-traffic", vec!["protocols"]);
        m.insert("process", Vec::new());
        m.insert("software", vec!["name"]);
        m.insert("url", vec!["value"]);
        m.insert("user-account", Vec::new());
        m.insert("windows-registry-key", Vec::new());
        m.insert("x509-certificate", Vec::new());
        m
    });

// ID Contributing properties that are not guaranteed to be present for a given SCO type, but should be used if they are
pub(super) static OPTIONAL_ID_PROPERTIES: LazyLock<HashMap<&'static str, Vec<&'static str>>> =
    LazyLock::new(|| {
        let mut m = HashMap::new();
        m.insert("artifact", vec!["hashes", "payload_bin"]);
        m.insert("autonomous-system", Vec::new());
        m.insert("directory", Vec::new());
        m.insert("domain-name", Vec::new());
        m.insert("email-addr", Vec::new());
        m.insert("email-message", vec!["from_ref", "subject", "body"]);
        m.insert(
            "file",
            vec!["hashes", "name", "extensions", "parent_directory_ref"],
        );
        m.insert("ipv4-addr", Vec::new());
        m.insert("ipv6-addr", Vec::new());
        m.insert("mac-addr", Vec::new());
        m.insert(
            "network-traffic",
            vec![
                "start",
                "end",
                "src_ref",
                "dst_ref",
                "src_port",
                "dst_port",
                "extensions",
            ],
        );
        m.insert("process", Vec::new());
        m.insert("url", Vec::new());
        m.insert(
            "user-account",
            vec!["account_type", "user_id", "account_login"],
        );
        m.insert("windows-registry-key", vec!["key", "values"]);
        m.insert("x509-certificate", vec!["hashes", "serial_number"]);
        m
    });

// Static dictionary of network-traffic extension protocols
static PROTOCOLS_MAP: LazyLock<HashMap<String, String>> = LazyLock::new(|| {
    let mut protocols_map = HashMap::new();
    protocols_map.insert("http-request-ext".to_string(), "http".to_string());
    protocols_map.insert("tcp-ext".to_string(), "tcp".to_string());
    protocols_map.insert("icmp-ext".to_string(), "icmp".to_string());
    protocols_map.insert("socket-ext".to_string(), "tcp".to_string());
    protocols_map
});

/// A STIX Cyber-observable Object (SCO) of some type.
///
/// STIX defines a set of STIX Cyber-observable Objects (SCOs) for characterizing host-based and network-based information.
///
/// SCOs are used by various STIX Domain Objects (SDOs) to provide supporting context. The Observed Data SDO, for example, indicates that the raw data was observed at a particular time.
///
/// For more information see <https://docs.oasis-open.org/cti/stix/v2.1/os/stix-v2.1-os.html#_rosvg2qjx4h4>
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct CyberObject {
    /// Identifies the SCO type of SCO.
    #[serde(flatten)]
    pub object_type: CyberObjectType,
    /// Common object properties
    #[serde(flatten)]
    pub common_properties: CommonProperties,
}
impl CyberObject {
    /// Deserializes an SCO 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 SCO type definition.
    pub fn from_json(json: &str, allow_custom: bool) -> Result<Self, Error> {
        let value: serde_json::Value =
            serde_json::from_str(json).map_err(|e| Error::DeserializationError(e.to_string()))?;
        validate_value(value, allow_custom, true)
    }

    /// Returns whether the object's `revoked` property is `true`.
    pub fn is_revoked(&self) -> bool {
        matches!(self.common_properties.revoked, Some(true))
    }
}

// Returns a reference to the identifier of the `CyberObject`.
// This implementation accesses the `id` field from the `common_properties`
// of the `CyberObject`, providing a way to retrieve the unique identifier
// associated with this object.
impl Identified for CyberObject {
    fn get_id(&self) -> &Identifier {
        &self.common_properties.id
    }
}

impl Related for CyberObject {
    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!(CyberObject);

/// Required-property checks shared by builder assembly and semantic validation.
///
/// These used to live in the builder, which meant `from_json` accepted empty
/// required values that constructors rejected. Running them from `check`
/// gives both paths identical behavior.
fn check_required_fields(object_type: &CyberObjectType) -> Result<(), Error> {
    // Note: Many SCOs have all optional fields, but require that at least one such field be present.
    // This is checked as part of stix_check() to guarantee that an error will occur during building or deserialization.
    match object_type {
        CyberObjectType::AutonomousSystem(ref automomous_system) => {
            if automomous_system.number == 0 {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "number".to_string(),
                });
            }
        }
        CyberObjectType::Directory(ref directory) => {
            if directory.path.is_empty() {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "path".to_string(),
                });
            }
        }
        CyberObjectType::DomainName(ref domain_name) => {
            if domain_name.value.is_empty() {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "value".to_string(),
                });
            }
        }
        CyberObjectType::EmailAddress(ref email_address) => {
            if email_address.value.is_empty() {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "value".to_string(),
                });
            }
        }
        CyberObjectType::Ipv4Addr(ref ipv4_addr) => {
            if ipv4_addr.value.is_empty() {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "value".to_string(),
                });
            }
        }
        CyberObjectType::Ipv6Addr(ref ipv6_addr) => {
            if ipv6_addr.value.is_empty() {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "value".to_string(),
                });
            }
        }
        CyberObjectType::MacAddr(ref mac_address) => {
            if mac_address.value.is_empty() {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "value".to_string(),
                });
            }
        }
        CyberObjectType::Mutex(ref mutex) => {
            if mutex.name.is_empty() {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "name".to_string(),
                });
            }
        }
        CyberObjectType::Process(ref process) => {
            // A Process object MUST contain at least one property (other than type) from this object (or one of its extensions)
            if process.is_hidden.is_none()
                && process.pid.is_none()
                && process.created_time.is_none()
                && process.cwd.is_none()
                && process.command_line.is_none()
                && process.environment_variables.is_none()
                && process.opened_connection_refs.is_none()
                && process.creator_user_ref.is_none()
                && process.image_ref.is_none()
                && process.parent_ref.is_none()
                && process.child_refs.is_none()
            {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "extensions, is_hidden, pid, created_time, cwd, command_line, environment_variables,opened_connection_refs, creator_user_ref, image_ref, parent_ref, child_refs "
                        .to_string(),
                });
            }
        }
        // stix_check() will fail is the `protocols` field is an empty Vec, but we check here to provide a more specific error in this situation
        CyberObjectType::NetworkTraffic(ref network_traffic) => {
            if network_traffic.protocols.is_empty() {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "protocols".to_string(),
                });
            }
            if network_traffic.src_ref.is_none() && network_traffic.dst_ref.is_none() {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "src_ref, dst_ref".to_string(),
                });
            }
        }
        CyberObjectType::Software(ref software) => {
            if software.name.is_empty() {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "name".to_string(),
                });
            }
        }
        CyberObjectType::Url(ref url) => {
            if &url.value.to_string() == "http://example.com" {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "value".to_string(),
                });
            }
        }
        CyberObjectType::WindowsRegistryKey(ref windows_registry_key) => {
            if windows_registry_key.key.is_none()
                && windows_registry_key.values.is_none()
                && windows_registry_key.modified_time.is_none()
                && windows_registry_key.creator_user_ref.is_none()
                && windows_registry_key.number_of_subkeys.is_none()
            {
                return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "key, values, creator_user_ref, number_of_subkeys".to_string(),
                });
            }
        }
        CyberObjectType::X509Certificate(ref x509_certificate)
            if x509_certificate.is_self_signed.is_none()
                && x509_certificate.hashes.is_none()
                && x509_certificate.version.is_none()
                && x509_certificate.serial_number.is_none()
                && x509_certificate.signature_algorithm.is_none()
                && x509_certificate.issuer.is_none()
                && x509_certificate.validity_not_before.is_none()
                && x509_certificate.validity_not_after.is_none()
                && x509_certificate.subject.is_none()
                && x509_certificate.subject_public_key_algorithm.is_none()
                && x509_certificate.subject_public_key_modulus.is_none()
                && x509_certificate.subject_public_key_exponent.is_none()
                && x509_certificate.x509_v3_extensions.is_none() =>
        {
            return Err(Error::MissingProperty {
                    object_type: object_type.to_string(),
                    property: "is_self_signed, hashes, version, serial_number, signature_algorithm, issuer, validity_not_before, validity_not_after, subject, subject_public_key_algorithm, subject_public_key_modulus, subject_public_key_exponent, x509_v3_extensions".to_string(),
                });
        }
        _ => {}
    }
    Ok(())
}

impl Stix for CyberObject {
    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 SCO
        add_error(&mut errors, check_sco_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 the identifier (enforces UUIDv5 for SCOs)
        add_error(&mut errors, self.common_properties.id.check(ctx));

        // Special check for NetworkTraffic that looks at both a NetworkTraffic property and a CommonProperty
        // If a protocol extension is present for a NetworkTraffic SCO, the corresponding protocol value for that extension **SHOULD** be listed in the protocols property.
        if let (CyberObjectType::NetworkTraffic(network_traffic), Some(extensions)) =
            (&self.object_type, &self.common_properties.extensions)
        {
            for key in extensions.keys() {
                // Check if the extension key is in the list of predefined protocol extensions
                if let Some(protocol) = PROTOCOLS_MAP.get(key) {
                    // If it is, check that the corresponding protocol is in the protocols property list, otherwise warn the user
                    if !network_traffic.protocols.contains(protocol) {
                        ctx.warn(
                            Entry::new(
                                "protocol_missing_from_protocols",
                                format!(
                                    "A {} extension is present for network-traffic {}, but the protocol {} is missing from its protocols property.",
                                    key,
                                    self.get_id(),
                                    protocol
                                ),
                            )
                            .property("protocols")
                            .value(protocol.clone()),
                        );
                    }
                }
            }
        }

        // Check SCO type specific errors
        add_error(
            &mut errors,
            self.object_type
                .check(ctx)
                .map_err(|e| Error::InvalidNestedObject {
                    context: format!(
                        "Cyber 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 SCO are present and that the prohibited fields for an SCO are not present
pub fn check_sco_properties(properties: &CommonProperties) -> Result<(), Error> {
    let mut errors = Vec::new();

    if properties.created_by_ref.is_some() {
        errors.push(Error::ValidationError(
            "SCOs cannot have a `created_by_ref` property.".to_string(),
        ));
    }
    if properties.revoked.is_some() {
        errors.push(Error::ValidationError(
            "SCOs cannot have a `revoked` property.".to_string(),
        ));
    }
    if properties.labels.is_some() {
        errors.push(Error::ValidationError(
            "SCOs cannot have a `labels` property.".to_string(),
        ));
    }
    if properties.confidence.is_some() {
        errors.push(Error::ValidationError(
            "SCOs cannot have a `confidence` property.".to_string(),
        ));
    }
    if properties.lang.is_some() {
        errors.push(Error::ValidationError(
            "SCOs cannot have a `lang` property.".to_string(),
        ));
    }
    if properties.external_references.is_some() {
        errors.push(Error::ValidationError(
            "SCOs cannot have a `external_references` property.".to_string(),
        ));
    }
    if properties.created.is_some() {
        errors.push(Error::ValidationError(
            "SCOs cannot have a `created` property.".to_string(),
        ));
    }
    if properties.modified.is_some() {
        errors.push(Error::ValidationError(
            "SCOs cannot have a `modified` property.".to_string(),
        ));
    }

    return_multiple_errors(errors)
}

impl Stix for CyberObjectType {
    fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
        match self {
            CyberObjectType::Artifact(artifact) => artifact.check(ctx),
            CyberObjectType::AutonomousSystem(automomous_system) => automomous_system.check(ctx),
            CyberObjectType::Directory(directory) => directory.check(ctx),
            CyberObjectType::DomainName(domain_name) => domain_name.check(ctx),
            CyberObjectType::EmailAddress(email_address) => email_address.check(ctx),
            CyberObjectType::EmailMessage(email_message) => email_message.check(ctx),
            CyberObjectType::File(file) => file.check(ctx),
            CyberObjectType::Ipv4Addr(ipv4_addr) => ipv4_addr.check(ctx),
            CyberObjectType::Ipv6Addr(ipv6_addr) => ipv6_addr.check(ctx),
            CyberObjectType::MacAddr(mac_address) => mac_address.check(ctx),
            CyberObjectType::Mutex(mutex) => mutex.check(ctx),
            CyberObjectType::NetworkTraffic(network_traffic) => network_traffic.check(ctx),
            CyberObjectType::Process(process) => process.check(ctx),
            CyberObjectType::Software(software) => software.check(ctx),
            CyberObjectType::Url(url) => url.check(ctx),
            CyberObjectType::UserAccount(user_account) => user_account.check(ctx),
            CyberObjectType::WindowsRegistryKey(windows_registry_key) => {
                windows_registry_key.check(ctx)
            }
            CyberObjectType::WindowsRegistryKeyType(windows_registry_key_type) => {
                windows_registry_key_type.check(ctx)
            }
            CyberObjectType::X509Certificate(x509_certificate) => x509_certificate.check(ctx),
        }
    }
}

pub use builder::CyberObjectBuilder;

/// The various SCO 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 CyberObjectType {
    /// An `artifact` object.
    Artifact(Artifact),
    /// An `autonomous-system` object.
    AutonomousSystem(AutonomousSystem),
    /// A `directory` object.
    Directory(Directory),
    /// A `domain-name` object.
    DomainName(DomainName),
    /// An `email-addr` object.
    #[serde(rename = "email-addr", alias = "email-address")]
    #[strum(serialize = "email-addr")]
    EmailAddress(EmailAddress),
    /// An `email-message` object.
    EmailMessage(EmailMessage),
    /// A `file` object.
    File(File),
    /// An `ipv4-addr` object.
    Ipv4Addr(Ipv4Addr),
    /// An `ipv6-addr` object.
    Ipv6Addr(Ipv6Addr),
    /// A `mac-addr` object.
    MacAddr(MacAddr),
    /// A `mutex` object.
    Mutex(Mutex),
    /// A `network-traffic` object.
    NetworkTraffic(NetworkTraffic),
    /// A `process` object.
    Process(Process),
    /// A `software` object.
    Software(Software),
    /// A `url` object.
    Url(Url),
    /// A `user-account` object.
    UserAccount(UserAccount),
    /// A `windows-registry-key` object.
    WindowsRegistryKey(WindowsRegistryKey),
    /// A `windows-registry-key` value entry.
    WindowsRegistryKeyType(WindowsRegistryKeyType),
    /// An `x509-certificate` object.
    X509Certificate(Box<X509Certificate>),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn protocol_extension_map_matches_spec() {
        assert_eq!(
            PROTOCOLS_MAP.get("icmp-ext").map(String::as_str),
            Some("icmp")
        );
        assert_eq!(
            PROTOCOLS_MAP.get("tcp-ext").map(String::as_str),
            Some("tcp")
        );
        assert_eq!(
            PROTOCOLS_MAP.get("http-request-ext").map(String::as_str),
            Some("http")
        );
        assert_eq!(
            PROTOCOLS_MAP.get("socket-ext").map(String::as_str),
            Some("tcp")
        );
    }
}