Skip to main content

rsigma_parser/
error.rs

1use std::fmt;
2
3use serde::Serialize;
4use thiserror::Error;
5
6/// Source location within a Sigma document.
7///
8/// Attached to parse errors when position information is available
9/// (e.g. from pest parse failures). Line and column are 1-indexed.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
11pub struct SourceLocation {
12    pub line: u32,
13    pub col: u32,
14}
15
16impl fmt::Display for SourceLocation {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        write!(f, "{}:{}", self.line, self.col)
19    }
20}
21
22/// Errors that can occur during Sigma rule parsing.
23#[derive(Debug, Error)]
24#[non_exhaustive]
25pub enum SigmaParserError {
26    #[error("YAML parsing error: {0}")]
27    Yaml(#[from] yaml_serde::Error),
28
29    #[error("{}", format_with_location(.0, .1))]
30    Condition(String, Option<SourceLocation>),
31
32    #[error("Unknown modifier '{0}'")]
33    UnknownModifier(String),
34
35    #[error("Modifier '{0}' is applied more than once")]
36    DuplicateModifier(String),
37
38    /// Reserved when a user writes `field|not: value` or
39    /// `field|contains|not: value` as if `not` were a value modifier.
40    /// Sigma does not support a `|not` modifier; negation is expressed at
41    /// the condition level (`not selection` or `selection and not filter`).
42    #[error(
43        "`not` is not a value modifier in Sigma; express negation in the \
44         condition (e.g. `not selection`) or move the inverted check into a \
45         separate detection used as a filter (e.g. `selection and not other`)"
46    )]
47    NotIsNotAModifier,
48
49    #[error("Invalid field specification: {0}")]
50    InvalidFieldSpec(String),
51
52    #[error("Invalid modifier combination: {0}")]
53    InvalidModifiers(String),
54
55    #[error("Invalid rule: {0}")]
56    InvalidRule(String),
57
58    #[error("Missing required field '{0}'")]
59    MissingField(String),
60
61    #[error("Invalid detection: {0}")]
62    InvalidDetection(String),
63
64    #[error("Invalid correlation rule: {0}")]
65    InvalidCorrelation(String),
66
67    #[error("Invalid timespan '{0}'")]
68    InvalidTimespan(String),
69
70    #[error("Invalid value: {0}")]
71    InvalidValue(String),
72
73    #[error("Invalid collection action '{0}'")]
74    InvalidAction(String),
75
76    #[error("IO error: {0}")]
77    Io(#[from] std::io::Error),
78
79    #[error("YAML merge exceeds maximum depth ({0})")]
80    MergeTooDeep(usize),
81
82    #[error("Condition string too long ({0} bytes, max {1})")]
83    ConditionTooLong(usize, usize),
84}
85
86/// The variant of a [`SigmaParserError`], without its payload.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
88#[serde(rename_all = "snake_case")]
89#[non_exhaustive]
90pub enum SigmaParserErrorKind {
91    Yaml,
92    Condition,
93    UnknownModifier,
94    DuplicateModifier,
95    NotIsNotAModifier,
96    InvalidFieldSpec,
97    InvalidModifiers,
98    InvalidRule,
99    MissingField,
100    InvalidDetection,
101    InvalidCorrelation,
102    InvalidTimespan,
103    InvalidValue,
104    InvalidAction,
105    Io,
106    MergeTooDeep,
107    ConditionTooLong,
108}
109
110impl SigmaParserError {
111    /// Returns the source location if this error variant carries one.
112    pub fn location(&self) -> Option<SourceLocation> {
113        match self {
114            SigmaParserError::Condition(_, loc) => *loc,
115            _ => None,
116        }
117    }
118
119    /// The variant of this error, without its payload.
120    pub fn kind(&self) -> SigmaParserErrorKind {
121        use SigmaParserErrorKind as K;
122        match self {
123            SigmaParserError::Yaml(_) => K::Yaml,
124            SigmaParserError::Condition(..) => K::Condition,
125            SigmaParserError::UnknownModifier(_) => K::UnknownModifier,
126            SigmaParserError::DuplicateModifier(_) => K::DuplicateModifier,
127            SigmaParserError::NotIsNotAModifier => K::NotIsNotAModifier,
128            SigmaParserError::InvalidFieldSpec(_) => K::InvalidFieldSpec,
129            SigmaParserError::InvalidModifiers(_) => K::InvalidModifiers,
130            SigmaParserError::InvalidRule(_) => K::InvalidRule,
131            SigmaParserError::MissingField(_) => K::MissingField,
132            SigmaParserError::InvalidDetection(_) => K::InvalidDetection,
133            SigmaParserError::InvalidCorrelation(_) => K::InvalidCorrelation,
134            SigmaParserError::InvalidTimespan(_) => K::InvalidTimespan,
135            SigmaParserError::InvalidValue(_) => K::InvalidValue,
136            SigmaParserError::InvalidAction(_) => K::InvalidAction,
137            SigmaParserError::Io(_) => K::Io,
138            SigmaParserError::MergeTooDeep(_) => K::MergeTooDeep,
139            SigmaParserError::ConditionTooLong(..) => K::ConditionTooLong,
140        }
141    }
142}
143
144fn format_with_location(msg: &str, loc: &Option<SourceLocation>) -> String {
145    match loc {
146        Some(loc) => format!("Condition parse error at {loc}: {msg}"),
147        None => format!("Condition parse error: {msg}"),
148    }
149}
150
151pub type Result<T> = std::result::Result<T, SigmaParserError>;