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
//! Parse a stalkerware-indicators yaml into a list of [`Rule`](struct.Rule.html)s.
//!
//! ## Example
//!
//! ```
//! use anyhow::Context;
//! use std::fs;
//!
//! fn main() -> anyhow::Result<()> {
//!     let buf = fs::read("test_data/ioc-2022-04-30.yaml")
//!         .context("Failed to read ioc yaml file")?;
//!
//!     let rules = stalkerware_indicators::parse_from_buf(&buf);
//!     for rule in rules {
//!         println!("Rule: {:?}", rule);
//!     }
//!
//!     Ok(())
//! }
//! ```

pub mod errors;
mod structs;

use crate::errors::*;
pub use crate::structs::*;
use std::fmt;
use std::fs;
use std::path::Path;

/// Load a yaml ioc.yaml from a byte slice
pub fn parse_from_buf(buf: &[u8]) -> Result<Vec<Rule>> {
    let data =
        serde_yaml::from_slice(buf).context("Failed to parse stalkerware-indicators rules")?;
    Ok(data)
}

/// Load a yaml ioc.yaml from the file system
pub fn parse_from_file<T: AsRef<Path> + fmt::Debug>(path: T) -> Result<Vec<Rule>> {
    let buf = fs::read(&path).with_context(|| anyhow!("Failed to read file: {:?}", path))?;
    parse_from_buf(&buf)
}

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

    #[test]
    fn test_load_2022_04_30() {
        let rules = parse_from_file("test_data/ioc-2022-04-30.yaml").unwrap();
        assert_eq!(rules.len(), 81);
    }

    #[test]
    fn parse_minimal() {
        let buf = r#"
- name: Minimal
        "#;

        let rules = parse_from_buf(buf.as_bytes()).unwrap();
        assert_eq!(
            rules,
            vec![Rule {
                name: "Minimal".to_string(),
                names: Vec::new(),
                packages: Vec::new(),
                certificates: Vec::new(),
                websites: Vec::new(),
                c2: C2Rule {
                    ips: Vec::new(),
                    domains: Vec::new(),
                },
            },]
        );
    }

    #[test]
    fn parse_empty_c2() {
        let buf = r#"
- name: Minimal
  c2: {}
        "#;

        let rules = parse_from_buf(buf.as_bytes()).unwrap();
        assert_eq!(
            rules,
            vec![Rule {
                name: "Minimal".to_string(),
                names: Vec::new(),
                packages: Vec::new(),
                certificates: Vec::new(),
                websites: Vec::new(),
                c2: C2Rule {
                    ips: Vec::new(),
                    domains: Vec::new(),
                },
            },]
        );
    }
}