Skip to main content

asterust_junos/firewall/
mod.rs

1//! `firewall { ... }`: stateless filters and policers.
2
3mod family;
4mod policer;
5
6pub use family::{FilterAction, FilterActions, FilterTerm, FirewallFilter, MatchCondition};
7pub use policer::Policer;
8
9use crate::{named_children, top_level};
10use asterust::config::Config;
11use family::filters;
12use policer::parse_policer;
13
14/// The top-level `firewall` configuration. `simple-filter`, `service-filter` and `prefix-action` are not extracted.
15#[derive(Clone, Debug, PartialEq, Eq)]
16#[non_exhaustive]
17pub struct Firewall {
18    pub filters: Vec<FirewallFilter>,
19    pub policers: Vec<Policer>,
20}
21
22/// The top-level `firewall` block, or `None` if there is none.
23pub fn firewall(config: &Config) -> Option<Firewall> {
24    let root = top_level(config, "firewall")?;
25    Some(Firewall {
26        filters: filters(root),
27        policers: named_children(root, "policer")
28            .map(|(name, line)| parse_policer(name, line))
29            .collect(),
30    })
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36    use asterust::config::juniper;
37
38    fn parse(text: &str) -> Firewall {
39        firewall(&juniper::parse_braces(text)).expect("fixture has a firewall block")
40    }
41
42    // Adapted from Juniper's BGP User Guide "TCP Access Restriction for BGP" (Device E and the prefix-list example);
43    // see the README "Sources".
44    const DOC_BGP179_PEERS: &str = r#"
45firewall {
46    family inet {
47        filter filter_bgp179 {
48            term 1 {
49                from {
50                    source-address {
51                        10.10.10.2/32;
52                        10.10.10.6/32;
53                    }
54                    destination-port bgp;
55                }
56                then accept;
57            }
58            term 2 {
59                then {
60                    reject;
61                }
62            }
63        }
64    }
65}
66"#;
67
68    const DOC_BGP179_PREFIX_LIST: &str = r#"
69firewall {
70    family inet {
71        filter filter_bgp179 {
72            term 1 {
73                from {
74                    source-address {
75                        0.0.0.0/0;
76                    }
77                    source-prefix-list {
78                        plist_bgp179 except;
79                    }
80                    destination-port bgp;
81                }
82                then {
83                    reject;
84                }
85            }
86            term 2 {
87                then {
88                    accept;
89                }
90            }
91        }
92    }
93}
94"#;
95
96    #[test]
97    fn doc_filter_with_address_block_and_leaf_then() {
98        let firewall = parse(DOC_BGP179_PEERS);
99        assert_eq!(firewall.filters.len(), 1);
100        let filter = &firewall.filters[0];
101        assert_eq!(filter.family, "inet");
102        assert_eq!(filter.name, "filter_bgp179");
103        assert_eq!(filter.terms.len(), 2);
104
105        let term = &filter.terms[0];
106        assert_eq!(term.name, "1");
107        assert_eq!(
108            term.condition("source-address").unwrap().values,
109            ["10.10.10.2/32", "10.10.10.6/32"]
110        );
111        assert_eq!(term.condition("destination-port").unwrap().values, ["bgp"]);
112        assert_eq!(term.then.action, Some(FilterAction::Accept));
113    }
114
115    #[test]
116    fn doc_term_without_from_and_block_then() {
117        let filter = &parse(DOC_BGP179_PEERS).filters[0];
118        assert!(filter.terms[1].from.is_empty());
119        assert_eq!(filter.terms[1].then.action, Some(FilterAction::Reject));
120    }
121
122    #[test]
123    fn doc_prefix_list_with_except_modifier() {
124        let filter = &parse(DOC_BGP179_PREFIX_LIST).filters[0];
125        let term = &filter.terms[0];
126        assert_eq!(term.condition("source-address").unwrap().values, ["0.0.0.0/0"]);
127        assert_eq!(
128            term.condition("source-prefix-list").unwrap().values,
129            ["plist_bgp179 except"]
130        );
131        assert_eq!(term.then.action, Some(FilterAction::Reject));
132        assert_eq!(filter.terms[1].then.action, Some(FilterAction::Accept));
133    }
134
135    // Not from documentation: covers statements the Juniper examples do not use. See the README "Sources".
136    const CONFIG: &str = r#"
137firewall {
138    family inet {
139        filter PROTECT-RE {
140            term ICMP {
141                from {
142                    protocol icmp;
143                    icmp-type [ echo-request echo-reply ];
144                    first-fragment;
145                }
146                then {
147                    policer ICMP-LIMIT;
148                    count icmp-packets;
149                    log;
150                    accept;
151                }
152            }
153            term SSH {
154                from destination-port ssh;
155                then {
156                    forwarding-class network-control;
157                    loss-priority low;
158                    next term;
159                }
160            }
161            inactive: term OLD {
162                then discard;
163            }
164            term DEFAULT {
165                then {
166                    syslog;
167                    discard;
168                }
169            }
170        }
171    }
172    family inet6 {
173        filter V6 {
174            term ALL {
175                then accept;
176            }
177        }
178    }
179    policer ICMP-LIMIT {
180        if-exceeding {
181            bandwidth-limit 1m;
182            burst-size-limit 15k;
183        }
184        then discard;
185    }
186    policer PERCENT {
187        if-exceeding {
188            bandwidth-percent 10;
189            burst-size-limit 10k;
190        }
191        then {
192            forwarding-class best-effort;
193            loss-priority high;
194        }
195    }
196}
197"#;
198
199    #[test]
200    fn lists_flags_and_nonterminating_actions() {
201        let firewall = parse(CONFIG);
202        let names: Vec<_> = firewall
203            .filters
204            .iter()
205            .map(|f| (f.family.as_str(), f.name.as_str()))
206            .collect();
207        assert_eq!(names, [("inet", "PROTECT-RE"), ("inet6", "V6")]);
208
209        let icmp = &firewall.filters[0].terms[0];
210        assert_eq!(icmp.condition("protocol").unwrap().values, ["icmp"]);
211        assert_eq!(
212            icmp.condition("icmp-type").unwrap().values,
213            ["echo-request", "echo-reply"]
214        );
215        assert!(icmp.condition("first-fragment").unwrap().values.is_empty());
216        assert_eq!(icmp.then.policer.as_deref(), Some("ICMP-LIMIT"));
217        assert_eq!(icmp.then.count.as_deref(), Some("icmp-packets"));
218        assert!(icmp.then.log);
219        assert!(!icmp.then.syslog);
220    }
221
222    #[test]
223    fn leaf_from_next_term_and_skipped_inactive_term() {
224        let terms = &parse(CONFIG).filters[0].terms;
225        let names: Vec<_> = terms.iter().map(|t| t.name.as_str()).collect();
226        assert_eq!(names, ["ICMP", "SSH", "DEFAULT"]);
227
228        let ssh = &terms[1];
229        assert_eq!(ssh.condition("destination-port").unwrap().values, ["ssh"]);
230        assert_eq!(ssh.then.action, Some(FilterAction::NextTerm));
231        assert_eq!(ssh.then.forwarding_class.as_deref(), Some("network-control"));
232        assert_eq!(ssh.then.loss_priority.as_deref(), Some("low"));
233
234        assert_eq!(terms[2].then.action, Some(FilterAction::Discard));
235        assert!(terms[2].then.syslog);
236    }
237
238    #[test]
239    fn extracts_policers() {
240        let policers = parse(CONFIG).policers;
241        assert_eq!(policers.len(), 2);
242
243        assert_eq!(policers[0].name, "ICMP-LIMIT");
244        assert_eq!(policers[0].bandwidth_limit.as_deref(), Some("1m"));
245        assert_eq!(policers[0].burst_size_limit.as_deref(), Some("15k"));
246        assert_eq!(policers[0].bandwidth_percent, None);
247        assert!(policers[0].discard);
248
249        assert_eq!(policers[1].bandwidth_percent.as_deref(), Some("10"));
250        assert!(!policers[1].discard);
251        assert_eq!(policers[1].forwarding_class.as_deref(), Some("best-effort"));
252        assert_eq!(policers[1].loss_priority.as_deref(), Some("high"));
253    }
254
255    #[test]
256    fn no_firewall_is_none() {
257        assert!(firewall(&juniper::parse_braces("system {\n host-name r1;\n}\n")).is_none());
258    }
259}