stixflayer 0.1.0

Fast 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
use crate::base::Stix;
use crate::common::validation::validate_refs_are_type;
use crate::error::{add_error, return_multiple_errors, StixError as Error};
use crate::types::{DictionaryValue, Identifier, StixDictionary, Timestamp};
use log::warn;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_this_or_that::as_opt_u64;
use serde_with::skip_serializing_none;
use std::sync::OnceLock;
use stixflayer_derive::StixProperties;

fn protocol_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"^[a-zA-Z0-9-]{1,15}$").expect("protocol name regex is valid"))
}

fn ipfix_key_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"^[a-z][a-zA-Z0-9]+$").expect("IPFIX dictionary key regex is valid")
    })
}

/// Network Traffic
///
/// The Network Traffic object represents arbitrary network traffic that originates \
/// from a source and is addressed to a destination. The network traffic MAY or MAY NOT
/// constitute a valid unicast, multicast, or broadcast network connection. This MAY also
/// include traffic that is not established, such as a SYN flood.
///
/// To allow for use cases where a source or destination address may be sensitive and not
/// suitable for sharing, such as addresses that are internal to an organization’s network,
/// the source and destination properties (src_ref and dst_ref, respectively) are defined
/// as optional in the properties table below. However, a Network Traffic object **MUST**
/// contain the protocols property and at least one of the src_ref or dst_ref properties
/// and SHOULD contain the src_port and dst_port properties.
///
/// For more information see <https://docs.oasis-open.org/cti/stix/v2.1/os/stix-v2.1-os.html#_rgnc3w40xy>
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, StixProperties)]
pub struct NetworkTraffic {
    pub start: Option<Timestamp>,
    pub end: Option<Timestamp>,
    pub is_active: Option<bool>,
    pub src_ref: Option<Identifier>,
    pub dst_ref: Option<Identifier>,
    #[serde(default, deserialize_with = "as_opt_u64")]
    pub src_port: Option<u64>,
    #[serde(default, deserialize_with = "as_opt_u64")]
    pub dst_port: Option<u64>,
    pub protocols: Vec<String>,
    #[serde(default, deserialize_with = "as_opt_u64")]
    pub src_byte_count: Option<u64>,
    #[serde(default, deserialize_with = "as_opt_u64")]
    pub dst_byte_count: Option<u64>,
    #[serde(default, deserialize_with = "as_opt_u64")]
    pub src_packets: Option<u64>,
    #[serde(default, deserialize_with = "as_opt_u64")]
    pub dst_packets: Option<u64>,
    pub ipfix: Option<StixDictionary<DictionaryValue>>,
    pub src_payload_ref: Option<Identifier>,
    pub dst_payload_ref: Option<Identifier>,
    pub encapsulates_refs: Option<Vec<Identifier>>,
    pub encapsulated_by_ref: Option<Identifier>,
}
impl Stix for NetworkTraffic {
    fn stix_check(&self) -> Result<(), Error> {
        let mut errors = Vec::new();

        if let Some(src_port) = &self.src_port {
            add_error(&mut errors, src_port.stix_check());
        }
        if let Some(dst_port) = &self.dst_port {
            add_error(&mut errors, dst_port.stix_check());
        }
        if let Some(src_byte_count) = &self.src_byte_count {
            add_error(&mut errors, src_byte_count.stix_check());
        }
        if let Some(dst_byte_count) = &self.dst_byte_count {
            add_error(&mut errors, dst_byte_count.stix_check());
        }
        if let Some(src_packets) = &self.src_packets {
            add_error(&mut errors, src_packets.stix_check());
        }
        if let Some(dst_packets) = &self.dst_packets {
            add_error(&mut errors, dst_packets.stix_check());
        }

        if self.src_port.is_none() || self.dst_port.is_none() {
            warn!("Network traffic should contain both the src_port and dst_port properties.");
        }
        if let Some(dst_payload_ref) = &self.dst_payload_ref {
            dst_payload_ref.stix_check()?;
            if dst_payload_ref.get_type() != "artifact" {
                errors.push(Error::ValidationError(format!(
                    "dst_payload_ref {} MUST be of type artifact.",
                    dst_payload_ref.get_type()
                )));
            }
        }
        if let Some(encapsulated_by_ref) = &self.encapsulated_by_ref {
            encapsulated_by_ref.stix_check()?;
            if encapsulated_by_ref.get_type() != "network-traffic" {
                errors.push(Error::ValidationError(format!(
                    "encapsulated_by_ref {} MUST be of type network-traffic.",
                    encapsulated_by_ref.get_type()
                )));
            }
        }
        if let Some(dst_port) = self.dst_port {
            if !(0..=65535).contains(&dst_port) {
                errors.push(Error::ValidationError(
                format!("dst_port {} Specifies the source port used in the network traffic, as an integer. The port value MUST be in the range of 0 - 65535.",dst_port),
            ));
            }
        }
        if let Some(src_port) = self.src_port {
            if !(0..=65535).contains(&src_port) {
                errors.push(Error::ValidationError(
                format!("src_port {} Specifies the source port used in the network traffic, as an integer. The port value MUST be in the range of 0 - 65535.",src_port),
            ));
            }
        }
        if let Some(dst_ref) = &self.dst_ref {
            add_error(&mut errors, dst_ref.stix_check());
            if dst_ref.get_type() != "ipv4-addr"
                && dst_ref.get_type() != "ipv6-addr"
                && dst_ref.get_type() != "mac-addr"
                && dst_ref.get_type() != "domain-name"
            {
                errors.push(Error::ValidationError(
                    format!("dst_ref {} MUST be of type ipv4-addr, ipv6-addr, mac-addr, or domain-name (for cases where the IP address for a domain name is unknown).",dst_ref.get_type(),
                )));
            }
        }
        if let Some(encapsulates_refs) = &self.encapsulates_refs {
            encapsulates_refs.stix_check()?;
            add_error(
                &mut errors,
                validate_refs_are_type(
                    encapsulates_refs,
                    &["network-traffic"],
                    "encapsulates_refs",
                ),
            );
        }
        if let (Some(end), Some(is_active)) = (&self.end, &self.is_active) {
            if *is_active {
                errors.push(Error::ValidationError(
                    format!("If the is_active property is true, then the end {} property MUST NOT be included. If the end property is provided, is_active MUST be false.",end)
                ));
            }
        }

        if let (Some(start), Some(stop)) = (&self.start, &self.end) {
            if stop < start {
                errors.push(Error::ValidationError(format!("Network traffic has an end timestamp of {} and a start timestamp of {}. The former cannot be earlier than the latter.",
                    stop,
                    start
                )));
            }
        }

        if let Some(src_payload_ref) = &self.src_payload_ref {
            src_payload_ref.stix_check()?;
            if src_payload_ref.get_type() != "artifact" {
                errors.push(Error::ValidationError(format!(
                    "src_payload_ref {} MUST be of type artifact.",
                    src_payload_ref.get_type()
                )));
            }
        }
        if let Some(src_ref) = &self.src_ref {
            add_error(&mut errors, src_ref.stix_check());
            if src_ref.get_type() != "ipv4-addr"
                && src_ref.get_type() != "ipv6-addr"
                && src_ref.get_type() != "mac-addr"
                && src_ref.get_type() != "domain-name"
            {
                errors.push(Error::ValidationError(
                        format!("src_ref {} MUST be of type ipv4-addr, ipv6-addr, mac-addr, or domain-name (for cases where the IP address for a domain name is unknown).",src_ref.get_type()),
                    ));
            }
        }

        add_error(&mut errors, self.protocols.stix_check());

        let protocols_joined = &self.protocols.join(",");
        if protocols_joined.contains("ip") && !protocols_joined.starts_with("ip") {
            errors.push(Error::ValidationError(
                    format!("protocols {} Protocols MUST be listed in low to high order, from outer to inner in terms of packet encapsulation. That is, the protocols in the outer level of the packet, such as IP, MUST be listed first.",protocols_joined),
                ));
        }
        for p in &self.protocols {
            if !protocol_re().is_match(p) {
                errors.push(Error::ValidationError(format!(
                "The protocol name '{}' is not a valid IANA service name or protocol identifier.", p
            )));
            }
        }
        if let Some(ipfix) = &self.ipfix {
            add_error(&mut errors, ipfix.stix_check());
            for (key, val) in ipfix.iter() {
                if !ipfix_key_re().is_match(key) {
                    errors.push(Error::ValidationError(format!(
                        "IPFIX key '{}' is not valid. Must start with a lowercase letter and contain only alphanumeric characters.", key
                    )));
                }
                match val {
                    DictionaryValue::String(string) => add_error(&mut errors,string.stix_check()),
                    DictionaryValue::Int(int) => add_error(&mut errors,int.stix_check()),
                    _ =>  errors.push(Error::ValidationError(
                        format!("Ipfix dictionary value {} SHOULD be a case-preserved version of the IPFIX element name, e.g., octetDeltaCount. Each dictionary value MUST be either an integer or a string, as well as a valid IPFIX property.",val)
                    )),
                };
            }
        }

        return_multiple_errors(errors)
    }
}

#[cfg(test)]
mod tests {
    #![allow(unused_imports)]
    use crate::cyber_observable_objects::sco::{CyberObject, CyberObjectBuilder};
    use crate::extensions::{
        ArchiveExtension, FileExtensions, HttpRequestExtension, IcmpExtension,
        NetworkTrafficExtensions, ProcessExtensions, SocketExtenion, SpecialExtensions,
        UnixAccountExtension, UserAccountExtensions, WindowsProcessExtension,
    };
    use crate::types::{DictionaryValue, Hashes, Identifier, StixDictionary, Timestamp};
    use log::warn;
    use serde_json::Value;
    use std::{collections::HashMap, str::FromStr};
    use test_log::test;

    #[test]
    fn deserialize_network_traffic_se() {
        let json = r#"{
            "type": "network-traffic",
            "spec_version": "2.1",
            "id": "network-traffic--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "src_ref": "ipv4-addr--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "src_port": 223,
            "protocols": [
                "ip",
                "tcp"
            ],
            "extensions": {
                "socket-ext": {
                "address_family": "AF_INET",
                "is_listening": true,
                "socket_type": "SOCK_STREAM"
                }
            }
        }"#;

        let result = CyberObject::from_json(json, false).unwrap();

        let se = SpecialExtensions::NetworkTrafficExtensions(NetworkTrafficExtensions::SocketExt(
            SocketExtenion {
                address_family: Some("AF_INET".to_string()),
                is_blocking: None,
                is_listening: Some(true),
                options: None,
                socket_type: Some("SOCK_STREAM".to_string()),
                socket_descriptor: None,
                socket_handle: None,
            },
        ));

        let expected = CyberObjectBuilder::new("network-traffic")
            .unwrap()
            .src_ref(Identifier::new_test("ipv4-addr"))
            .unwrap()
            .src_port(223)
            .unwrap()
            .protocols(vec!["ip".to_string(), "tcp".to_string()])
            .unwrap()
            .add_extension("socket-ext", se.extension_to_dict().unwrap())
            .unwrap()
            .build()
            .unwrap()
            // Change id, created, and modified fields for test matching
            .test_id();

        assert_eq!(result, expected);
    }

    #[test]
    fn serialize_network_traffic_se() {
        let mut se = r#"{
            "type": "network-traffic",
            "src_ref": "ipv4-addr--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "src_port": 223,
            "is_active":false,
            "end":"2016-05-12T08:17:27Z",
            "protocols": [
                "ip",
                "tcp"
            ],
            "spec_version": "2.1",
            "id": "network-traffic--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "extensions": {
                "socket-ext": {
                "address_family": "AF_INET",
                "is_listening": true,
                "socket_type": "SOCK_STREAM"
                }
            }
        }"#
        .to_string();
        se.retain(|c| !c.is_whitespace());

        let expected: Value = serde_json::from_str(&se).unwrap();

        let se = SpecialExtensions::NetworkTrafficExtensions(NetworkTrafficExtensions::SocketExt(
            SocketExtenion {
                address_family: Some("AF_INET".to_string()),
                is_listening: Some(true),
                socket_type: Some("SOCK_STREAM".to_string()),
                is_blocking: None,
                options: None,

                socket_descriptor: None,
                socket_handle: None,
            },
        ));

        let nt = CyberObjectBuilder::new("network-traffic")
            .unwrap()
            .src_ref(Identifier::new_test("ipv4-addr"))
            .unwrap()
            .src_port(223)
            .unwrap()
            .is_active(false)
            .unwrap()
            .end(Timestamp("2016-05-12T08:17:27.000Z".parse().unwrap()))
            .unwrap()
            .protocols(vec!["ip".to_string(), "tcp".to_string()])
            .unwrap()
            .add_extension("socket-ext", se.extension_to_dict().unwrap())
            .unwrap()
            .build()
            .unwrap()
            // Change id, created, and modified fields for test matching
            .test_id();
        let result = serde_json::to_value(&nt).unwrap();

        assert_eq!(result, expected);
    }

    #[test]
    fn deserialize_network_traffic_http_err() {
        let json = r#"{
            "type": "network-traffic",
            "spec_version": "2.1",
            "id": "network-traffic--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "dst_ref": "ipv4x-addr--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "protocols": [
                "tcp",
                "http"
            ],
            "extensions": {
                "http-request-ext": {
                "request_method": "get",
                "request_value": "/download.html",
                "request_version": "http/1.1"
                }
            }             
        }"#;

        let result = CyberObject::from_json(json, false);

        assert!(result.is_err());
    }

    #[test]
    fn deserialize_network_traffic_http_dict() {
        let json = r#"{
            "type": "network-traffic",
            "spec_version": "2.1",
            "id": "network-traffic--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "dst_ref": "ipv4-addr--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "protocols": [
                "tcp",
                "http"
            ],
            "extensions": {
                    "http-request-ext": {
                    "request_method": "get",
                    "request_value": "/download.html",
                    "request_version": "http/1.1",
                    "request_header": {
                        "Accept-Encoding": "gzip,deflate",
                        "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.6) Gecko/20040113",
                        "Host": "www.example.com"
                    }
                }
            }             
        }"#;

        let result = CyberObject::from_json(json, false).unwrap();

        let mut rh = StixDictionary::new();
        rh.insert("Accept-Encoding", "gzip,deflate".to_string())
            .unwrap();
        rh.insert(
            "User-Agent",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.6) Gecko/20040113".to_string(),
        )
        .unwrap();
        rh.insert("Host", "www.example.com".to_string()).unwrap();

        let hre = SpecialExtensions::NetworkTrafficExtensions(
            NetworkTrafficExtensions::HttpRequestExt(HttpRequestExtension {
                request_method: "get".to_string(),
                request_value: "/download.html".to_string(),
                request_version: Some("http/1.1".to_string()),
                request_header: Some(rh),
                message_body_length: None,
                message_body_data_ref: None,
            }),
        );

        let expected = CyberObjectBuilder::new("network-traffic")
            .unwrap()
            .dst_ref(Identifier::new_test("ipv4-addr"))
            .unwrap()
            .protocols(vec!["tcp".to_string(), "http".to_string()])
            .unwrap()
            .add_extension("http-request-ext", hre.extension_to_dict().unwrap())
            .unwrap()
            .build()
            .unwrap()
            // Change id, created, and modified fields for test matching
            .test_id();

        assert_eq!(result, expected);
    }

    #[test]
    fn deserialize_network_traffic_icmp() {
        let json = r#"{
            "type": "network-traffic",
            "spec_version": "2.1",
            "id": "network-traffic--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "src_ref": "ipv4-addr--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "dst_ref": "ipv4-addr--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "ipfix": {
                "minimumIpTotalLength": 32,
                "maximumIpTotalLength": 2556
            },
            "protocols": [
                "icmp"
            ],
            "extensions": {
                "icmp-ext": {
                "icmp_type_hex": "08",
                "icmp_code_hex": "00"
                }
            }
        }"#;

        let mut ipfix = StixDictionary::new();
        ipfix
            .insert("minimumIpTotalLength", DictionaryValue::Int(32))
            .unwrap();
        ipfix
            .insert("maximumIpTotalLength", DictionaryValue::Int(2556))
            .unwrap();

        let result = CyberObject::from_json(json, false).unwrap();

        let icmp = SpecialExtensions::NetworkTrafficExtensions(NetworkTrafficExtensions::IcmpExt(
            IcmpExtension {
                icmp_type_hex: "08".to_string(),
                icmp_code_hex: "00".to_string(),
            },
        ));

        let expected = CyberObjectBuilder::new("network-traffic")
            .unwrap()
            .src_ref(Identifier::new_test("ipv4-addr"))
            .unwrap()
            .dst_ref(Identifier::new_test("ipv4-addr"))
            .unwrap()
            .ipfix(ipfix)
            .unwrap()
            .protocols(vec!["icmp".to_string()])
            .unwrap()
            .add_extension("icmp-ext", icmp.extension_to_dict().unwrap())
            .unwrap()
            .build()
            .unwrap()
            // Change id, created, and modified fields for test matching
            .test_id();

        assert_eq!(result, expected);
    }

    #[test]
    fn deserialize_network_traffic_icmp_invalid() {
        //using invalid icmp_type_hex
        let json = r#"{
            "type": "network-traffic",
            "spec_version": "2.1",
            "id": "network-traffic--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "src_ref": "ipv4-addr--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "dst_ref": "ipv4-addr--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "ipfix": {
                "minimumIpTotalLength": 32,
                "maximumIpTotalLength": 2556
            },
            "protocols": [
                "icmp"
            ],
            "extensions": {
                "icmp-ext": {
                "icmp_type_hex": "081",
                "icmp_code_hex": "00"
                }
            }
        }"#;

        let result = CyberObject::from_json(json, false);

        assert!(result.is_err());
    }

    #[test]
    fn deserialize_network_traffic_http_request_invalid_header() {
        let json = r#"{
            "type": "network-traffic",
            "spec_version": "2.1",
            "id": "network-traffic--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "dst_ref": "ipv4-addr--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
            "protocols": [
                "tcp",
                "http"
            ],
            "extensions": {
                "http-request-ext": {
                    "request_method": "get",
                    "request_value": "/download.html",
                    "request_version": "http/1.1",
                    "request_header": {
                        "Accept-Encoding": ["gzip,deflate"],
                        "Host": ["www.example.com"],
                        "x-foobar": ["something"]
                    }
                }
            }
        }"#;

        let result = CyberObject::from_json(json, false);
        assert!(result.is_err());
    }
}