Skip to main content

asterust_junos/
firewall.rs

1//! `firewall { ... }`: stateless filters and policers.
2
3use crate::{
4    active_children, arg_of, child_block, list_values, named_children, split_keyword, statements, top_level, unquote,
5};
6use asterust::config::{Config, ConfigLine};
7
8/// One `from` match condition, e.g. `destination-port bgp` or `source-address { 10.0.0.0/8; }`.
9#[derive(Clone, Debug, PartialEq, Eq)]
10#[non_exhaustive]
11pub struct MatchCondition {
12    pub name: String,
13    /// Values as written, including any trailing modifier such as `except`; empty for a flag like `first-fragment`.
14    pub values: Vec<String>,
15}
16
17/// The terminating action of a filter term. A term without one accepts matching packets.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum FilterAction {
21    Accept,
22    Discard,
23    Reject,
24    NextTerm,
25}
26
27/// The actions of a term's `then` statement. Actions not listed here are ignored.
28#[derive(Clone, Debug, Default, PartialEq, Eq)]
29#[non_exhaustive]
30pub struct FilterActions {
31    pub action: Option<FilterAction>,
32    /// Counter name from `count`.
33    pub count: Option<String>,
34    pub policer: Option<String>,
35    pub forwarding_class: Option<String>,
36    pub loss_priority: Option<String>,
37    pub log: bool,
38    pub syslog: bool,
39}
40
41/// A `term` of a filter.
42#[derive(Clone, Debug, PartialEq, Eq)]
43#[non_exhaustive]
44pub struct FilterTerm {
45    pub name: String,
46    pub from: Vec<MatchCondition>,
47    pub then: FilterActions,
48}
49
50impl FilterTerm {
51    /// The `from` condition called `name`, e.g. `"destination-port"`.
52    pub fn condition(&self, name: &str) -> Option<&MatchCondition> {
53        self.from.iter().find(|c| c.name == name)
54    }
55}
56
57/// A `filter <name>` under `family <family>`.
58#[derive(Clone, Debug, PartialEq, Eq)]
59#[non_exhaustive]
60pub struct FirewallFilter {
61    /// Address family, e.g. `"inet"`, `"inet6"`, `"bridge"`.
62    pub family: String,
63    pub name: String,
64    pub terms: Vec<FilterTerm>,
65}
66
67/// A `policer <name>`.
68#[derive(Clone, Debug, PartialEq, Eq)]
69#[non_exhaustive]
70pub struct Policer {
71    pub name: String,
72    pub bandwidth_limit: Option<String>,
73    pub bandwidth_percent: Option<String>,
74    pub burst_size_limit: Option<String>,
75    /// `then discard`.
76    pub discard: bool,
77    pub forwarding_class: Option<String>,
78    pub loss_priority: Option<String>,
79}
80
81/// The top-level `firewall` configuration. `simple-filter`, `service-filter` and `prefix-action` are not extracted.
82#[derive(Clone, Debug, PartialEq, Eq)]
83#[non_exhaustive]
84pub struct Firewall {
85    pub filters: Vec<FirewallFilter>,
86    pub policers: Vec<Policer>,
87}
88
89/// The top-level `firewall` block, or `None` if there is none.
90pub fn firewall(config: &Config) -> Option<Firewall> {
91    let root = top_level(config, "firewall")?;
92    let filters = named_children(root, "family")
93        .flat_map(|(family, family_line)| {
94            named_children(family_line, "filter").map(move |(name, filter)| parse_filter(family, name, filter))
95        })
96        .collect();
97    Some(Firewall {
98        filters,
99        policers: named_children(root, "policer")
100            .map(|(name, line)| parse_policer(name, line))
101            .collect(),
102    })
103}
104
105fn parse_filter(family: &str, name: &str, line: &ConfigLine) -> FirewallFilter {
106    FirewallFilter {
107        family: family.to_string(),
108        name: name.to_string(),
109        terms: named_children(line, "term")
110            .map(|(term_name, term)| FilterTerm {
111                name: term_name.to_string(),
112                from: parse_conditions(term),
113                then: parse_actions(term),
114            })
115            .collect(),
116    }
117}
118
119/// Conditions written either as `from x;` or inside a `from { ... }` block.
120fn parse_conditions(term: &ConfigLine) -> Vec<MatchCondition> {
121    let mut found = Vec::new();
122    for child in active_children(term) {
123        if child.text == "from" {
124            found.extend(active_children(child).map(parse_condition));
125        } else if let Some(statement) = child.arg("from") {
126            found.push(condition_from(statement, &[]));
127        }
128    }
129    found
130}
131
132fn parse_condition(line: &ConfigLine) -> MatchCondition {
133    condition_from(&line.text, &line.children)
134}
135
136fn condition_from(statement: &str, children: &[ConfigLine]) -> MatchCondition {
137    let (name, arg) = split_keyword(statement);
138    // A bare value keeps its modifier (`10.0.0.0/8 except`); only a bracketed list is split.
139    let mut values = if arg.is_empty() {
140        Vec::new()
141    } else if arg.starts_with('[') {
142        list_values(arg)
143    } else {
144        vec![unquote(arg).to_string()]
145    };
146    values.extend(
147        children
148            .iter()
149            .filter(|c| !c.text.starts_with("inactive:"))
150            .map(|c| c.text.clone()),
151    );
152    MatchCondition {
153        name: name.to_string(),
154        values,
155    }
156}
157
158fn parse_actions(term: &ConfigLine) -> FilterActions {
159    let mut actions = FilterActions::default();
160    for statement in statements(term, "then") {
161        let (action, arg) = split_keyword(statement);
162        let value = || Some(unquote(arg).to_string());
163        match (action, arg) {
164            ("accept", _) => actions.action = Some(FilterAction::Accept),
165            ("discard", _) => actions.action = Some(FilterAction::Discard),
166            ("reject", _) => actions.action = Some(FilterAction::Reject),
167            ("next", "term") => actions.action = Some(FilterAction::NextTerm),
168            ("count", _) => actions.count = value(),
169            ("policer", _) => actions.policer = value(),
170            ("forwarding-class", _) => actions.forwarding_class = value(),
171            ("loss-priority", _) => actions.loss_priority = value(),
172            ("log", "") => actions.log = true,
173            ("syslog", "") => actions.syslog = true,
174            _ => {}
175        }
176    }
177    actions
178}
179
180fn parse_policer(name: &str, line: &ConfigLine) -> Policer {
181    let limit = |keyword: &str| {
182        child_block(line, "if-exceeding")
183            .and_then(|block| arg_of(block, keyword))
184            .map(str::to_string)
185    };
186    let mut policer = Policer {
187        name: name.to_string(),
188        bandwidth_limit: limit("bandwidth-limit"),
189        bandwidth_percent: limit("bandwidth-percent"),
190        burst_size_limit: limit("burst-size-limit"),
191        discard: false,
192        forwarding_class: None,
193        loss_priority: None,
194    };
195    for statement in statements(line, "then") {
196        let (action, arg) = split_keyword(statement);
197        match action {
198            "discard" => policer.discard = true,
199            "forwarding-class" => policer.forwarding_class = Some(unquote(arg).to_string()),
200            "loss-priority" => policer.loss_priority = Some(unquote(arg).to_string()),
201            _ => {}
202        }
203    }
204    policer
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use asterust::config::juniper;
211
212    fn parse(text: &str) -> Firewall {
213        firewall(&juniper::parse_braces(text)).expect("fixture has a firewall block")
214    }
215
216    // Adapted from Juniper's BGP User Guide "TCP Access Restriction for BGP" (Device E and the prefix-list example);
217    // see the README "Sources".
218    const DOC_BGP179_PEERS: &str = r#"
219firewall {
220    family inet {
221        filter filter_bgp179 {
222            term 1 {
223                from {
224                    source-address {
225                        10.10.10.2/32;
226                        10.10.10.6/32;
227                    }
228                    destination-port bgp;
229                }
230                then accept;
231            }
232            term 2 {
233                then {
234                    reject;
235                }
236            }
237        }
238    }
239}
240"#;
241
242    const DOC_BGP179_PREFIX_LIST: &str = r#"
243firewall {
244    family inet {
245        filter filter_bgp179 {
246            term 1 {
247                from {
248                    source-address {
249                        0.0.0.0/0;
250                    }
251                    source-prefix-list {
252                        plist_bgp179 except;
253                    }
254                    destination-port bgp;
255                }
256                then {
257                    reject;
258                }
259            }
260            term 2 {
261                then {
262                    accept;
263                }
264            }
265        }
266    }
267}
268"#;
269
270    #[test]
271    fn doc_filter_with_address_block_and_leaf_then() {
272        let firewall = parse(DOC_BGP179_PEERS);
273        assert_eq!(firewall.filters.len(), 1);
274        let filter = &firewall.filters[0];
275        assert_eq!(filter.family, "inet");
276        assert_eq!(filter.name, "filter_bgp179");
277        assert_eq!(filter.terms.len(), 2);
278
279        let term = &filter.terms[0];
280        assert_eq!(term.name, "1");
281        assert_eq!(
282            term.condition("source-address").unwrap().values,
283            ["10.10.10.2/32", "10.10.10.6/32"]
284        );
285        assert_eq!(term.condition("destination-port").unwrap().values, ["bgp"]);
286        assert_eq!(term.then.action, Some(FilterAction::Accept));
287    }
288
289    #[test]
290    fn doc_term_without_from_and_block_then() {
291        let filter = &parse(DOC_BGP179_PEERS).filters[0];
292        assert!(filter.terms[1].from.is_empty());
293        assert_eq!(filter.terms[1].then.action, Some(FilterAction::Reject));
294    }
295
296    #[test]
297    fn doc_prefix_list_with_except_modifier() {
298        let filter = &parse(DOC_BGP179_PREFIX_LIST).filters[0];
299        let term = &filter.terms[0];
300        assert_eq!(term.condition("source-address").unwrap().values, ["0.0.0.0/0"]);
301        assert_eq!(
302            term.condition("source-prefix-list").unwrap().values,
303            ["plist_bgp179 except"]
304        );
305        assert_eq!(term.then.action, Some(FilterAction::Reject));
306        assert_eq!(filter.terms[1].then.action, Some(FilterAction::Accept));
307    }
308
309    // Not from documentation: covers statements the Juniper examples do not use. See the README "Sources".
310    const CONFIG: &str = r#"
311firewall {
312    family inet {
313        filter PROTECT-RE {
314            term ICMP {
315                from {
316                    protocol icmp;
317                    icmp-type [ echo-request echo-reply ];
318                    first-fragment;
319                }
320                then {
321                    policer ICMP-LIMIT;
322                    count icmp-packets;
323                    log;
324                    accept;
325                }
326            }
327            term SSH {
328                from destination-port ssh;
329                then {
330                    forwarding-class network-control;
331                    loss-priority low;
332                    next term;
333                }
334            }
335            inactive: term OLD {
336                then discard;
337            }
338            term DEFAULT {
339                then {
340                    syslog;
341                    discard;
342                }
343            }
344        }
345    }
346    family inet6 {
347        filter V6 {
348            term ALL {
349                then accept;
350            }
351        }
352    }
353    policer ICMP-LIMIT {
354        if-exceeding {
355            bandwidth-limit 1m;
356            burst-size-limit 15k;
357        }
358        then discard;
359    }
360    policer PERCENT {
361        if-exceeding {
362            bandwidth-percent 10;
363            burst-size-limit 10k;
364        }
365        then {
366            forwarding-class best-effort;
367            loss-priority high;
368        }
369    }
370}
371"#;
372
373    #[test]
374    fn lists_flags_and_nonterminating_actions() {
375        let firewall = parse(CONFIG);
376        let names: Vec<_> = firewall
377            .filters
378            .iter()
379            .map(|f| (f.family.as_str(), f.name.as_str()))
380            .collect();
381        assert_eq!(names, [("inet", "PROTECT-RE"), ("inet6", "V6")]);
382
383        let icmp = &firewall.filters[0].terms[0];
384        assert_eq!(icmp.condition("protocol").unwrap().values, ["icmp"]);
385        assert_eq!(
386            icmp.condition("icmp-type").unwrap().values,
387            ["echo-request", "echo-reply"]
388        );
389        assert!(icmp.condition("first-fragment").unwrap().values.is_empty());
390        assert_eq!(icmp.then.policer.as_deref(), Some("ICMP-LIMIT"));
391        assert_eq!(icmp.then.count.as_deref(), Some("icmp-packets"));
392        assert!(icmp.then.log);
393        assert!(!icmp.then.syslog);
394    }
395
396    #[test]
397    fn leaf_from_next_term_and_skipped_inactive_term() {
398        let terms = &parse(CONFIG).filters[0].terms;
399        let names: Vec<_> = terms.iter().map(|t| t.name.as_str()).collect();
400        assert_eq!(names, ["ICMP", "SSH", "DEFAULT"]);
401
402        let ssh = &terms[1];
403        assert_eq!(ssh.condition("destination-port").unwrap().values, ["ssh"]);
404        assert_eq!(ssh.then.action, Some(FilterAction::NextTerm));
405        assert_eq!(ssh.then.forwarding_class.as_deref(), Some("network-control"));
406        assert_eq!(ssh.then.loss_priority.as_deref(), Some("low"));
407
408        assert_eq!(terms[2].then.action, Some(FilterAction::Discard));
409        assert!(terms[2].then.syslog);
410    }
411
412    #[test]
413    fn extracts_policers() {
414        let policers = parse(CONFIG).policers;
415        assert_eq!(policers.len(), 2);
416
417        assert_eq!(policers[0].name, "ICMP-LIMIT");
418        assert_eq!(policers[0].bandwidth_limit.as_deref(), Some("1m"));
419        assert_eq!(policers[0].burst_size_limit.as_deref(), Some("15k"));
420        assert_eq!(policers[0].bandwidth_percent, None);
421        assert!(policers[0].discard);
422
423        assert_eq!(policers[1].bandwidth_percent.as_deref(), Some("10"));
424        assert!(!policers[1].discard);
425        assert_eq!(policers[1].forwarding_class.as_deref(), Some("best-effort"));
426        assert_eq!(policers[1].loss_priority.as_deref(), Some("high"));
427    }
428
429    #[test]
430    fn no_firewall_is_none() {
431        assert!(firewall(&juniper::parse_braces("system {\n host-name r1;\n}\n")).is_none());
432    }
433}