Skip to main content

asterust_junos/firewall/family/
filter.rs

1//! `filter`
2//! `firewall { family <family> { filter <name> { term <name> { from { ... } then { ... } } } } }`, and the same for
3//! `simple-filter` and `service-filter`.
4//!
5//! # See also
6//!
7//! - [filter (Configuring)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/filter-edit-firewall.html)
8//! - [term (Firewall Filter)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/term-edit-firewall.html)
9
10use crate::{active_children, arg_of, has_leaf, list_values, named_children, split_keyword, statements, unquote};
11use asterust::config::ConfigLine;
12
13/// One `from` match condition, e.g. `destination-port bgp` or `source-address { 10.0.0.0/8; }`.
14#[derive(Clone, Debug, PartialEq, Eq)]
15#[non_exhaustive]
16pub struct MatchCondition {
17    pub name: String,
18    /// Values as written, including any trailing modifier such as `except`; empty for a flag like
19    /// `first-fragment`.
20    pub values: Vec<String>,
21}
22
23/// The terminating action of a filter term. A term without one accepts matching packets.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum FilterAction {
27    Accept,
28    Discard,
29    Reject,
30    NextTerm,
31}
32
33/// The actions of a term's `then` statement. Actions not listed here are ignored.
34#[derive(Clone, Debug, Default, PartialEq, Eq)]
35#[non_exhaustive]
36pub struct FilterActions {
37    pub action: Option<FilterAction>,
38    /// The message type after `reject`, e.g. `"tcp-reset"`.
39    pub reject_message: Option<String>,
40    /// `skip`: in a service filter, bypass the service.
41    pub skip: bool,
42    /// `service`: in a service filter, send the packet to the service.
43    pub service: bool,
44    pub exclude_accounting: bool,
45    pub bgp_output_queue_priority: Option<String>,
46    /// `"set"` or `"clear"`.
47    pub dont_fragment: Option<String>,
48    pub dscp: Option<String>,
49    pub enhanced_hierarchical_policer: bool,
50    pub force_premium: bool,
51    /// The name after `hierarchical-policer`, if given.
52    pub hierarchical_policer: Option<String>,
53    pub ipsec_sa: Option<String>,
54    pub load_balance: Option<String>,
55    pub logical_system: Option<String>,
56    pub next_hop_group: Option<String>,
57    /// The interface of `next-interface`, written inline or as a block.
58    pub next_interface: Option<String>,
59    /// The `routing-instance` inside a `next-interface` block.
60    pub next_interface_routing_instance: Option<String>,
61    pub next_ip: Option<String>,
62    pub next_ip6: Option<String>,
63    pub packet_mode: bool,
64    pub policy_map: Option<String>,
65    /// `port-mirror` or `port-mirror-instance`.
66    pub port_mirror: bool,
67    pub port_mirror_instance: Option<String>,
68    pub prefix_action: Option<String>,
69    pub routing_instance: Option<String>,
70    pub sample: bool,
71    pub service_accounting: bool,
72    pub service_filter_hit: bool,
73    pub slice: Option<String>,
74    pub source_class: Option<String>,
75    pub destination_class: Option<String>,
76    /// Everything after `three-color-policer`, e.g. `"single-rate SRTCM1"`.
77    pub three_color_policer: Option<String>,
78    pub topology: Option<String>,
79    pub traffic_class: Option<String>,
80    /// Everything after `decapsulate`, e.g. `"gre routing-instance VRF-A"`.
81    pub decapsulate: Option<String>,
82    /// Everything after `encapsulate`, i.e. the template name.
83    pub encapsulate: Option<String>,
84    /// Counter name from `count`.
85    pub count: Option<String>,
86    pub policer: Option<String>,
87    pub forwarding_class: Option<String>,
88    pub loss_priority: Option<String>,
89    pub log: bool,
90    pub syslog: bool,
91}
92
93/// A `term` of a filter.
94#[derive(Clone, Debug, PartialEq, Eq)]
95#[non_exhaustive]
96pub struct FilterTerm {
97    pub name: String,
98    pub from: Vec<MatchCondition>,
99    pub then: FilterActions,
100}
101
102impl FilterTerm {
103    /// The `from` condition called `name`, e.g. `"destination-port"`.
104    pub fn condition(&self, name: &str) -> Option<&MatchCondition> {
105        self.from.iter().find(|c| c.name == name)
106    }
107}
108
109/// Which statement a filter is written with.
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111#[non_exhaustive]
112pub enum FilterKind {
113    /// `filter`.
114    Filter,
115    /// `simple-filter`, which only sets the forwarding class and loss priority.
116    SimpleFilter,
117    /// `service-filter`, which selects the traffic that a service processes.
118    ServiceFilter,
119}
120
121/// A `filter`, `simple-filter` or `service-filter <name>` under `family <family>`.
122#[derive(Clone, Debug, PartialEq, Eq)]
123#[non_exhaustive]
124pub struct FirewallFilter {
125    /// Address family, e.g. `"inet"`, `"inet6"`, `"bridge"`; `"inet"` for a filter written directly under
126    /// `firewall`.
127    pub family: String,
128    pub kind: FilterKind,
129    pub name: String,
130    pub accounting_profile: Option<String>,
131    pub enhanced_mode: bool,
132    pub fast_lookup_filter: bool,
133    pub filter_list_template: bool,
134    pub interface_shared: bool,
135    pub interface_specific: bool,
136    pub physical_interface_filter: bool,
137    /// `promote gre-key`.
138    pub promote_gre_key: bool,
139    pub terms: Vec<FilterTerm>,
140}
141
142pub(super) fn parse_filter(family: &str, kind: FilterKind, name: &str, line: &ConfigLine) -> FirewallFilter {
143    FirewallFilter {
144        family: family.to_string(),
145        kind,
146        name: name.to_string(),
147        accounting_profile: arg_of(line, "accounting-profile").map(str::to_string),
148        enhanced_mode: has_leaf(line, "enhanced-mode"),
149        fast_lookup_filter: has_leaf(line, "fast-lookup-filter"),
150        filter_list_template: has_leaf(line, "filter-list-template"),
151        interface_shared: has_leaf(line, "interface-shared"),
152        interface_specific: has_leaf(line, "interface-specific"),
153        physical_interface_filter: has_leaf(line, "physical-interface-filter"),
154        promote_gre_key: arg_of(line, "promote") == Some("gre-key"),
155        terms: named_children(line, "term")
156            .map(|(term_name, term)| FilterTerm {
157                name: term_name.to_string(),
158                from: parse_conditions(term),
159                then: parse_actions(term),
160            })
161            .collect(),
162    }
163}
164
165/// Conditions written either as `from x;` or inside a `from { ... }` block.
166fn parse_conditions(term: &ConfigLine) -> Vec<MatchCondition> {
167    let mut found = Vec::new();
168    for child in active_children(term) {
169        if child.text == "from" {
170            found.extend(active_children(child).map(parse_condition));
171        } else if let Some(statement) = child.arg("from") {
172            found.push(condition_from(statement, &[]));
173        }
174    }
175    found
176}
177
178fn parse_condition(line: &ConfigLine) -> MatchCondition {
179    condition_from(&line.text, &line.children)
180}
181
182fn condition_from(statement: &str, children: &[ConfigLine]) -> MatchCondition {
183    let (name, arg) = split_keyword(statement);
184    // A bare value keeps its modifier (`10.0.0.0/8 except`); only a bracketed list is split.
185    let mut values = if arg.is_empty() {
186        Vec::new()
187    } else if arg.starts_with('[') {
188        list_values(arg)
189    } else {
190        vec![unquote(arg).to_string()]
191    };
192    values.extend(
193        children
194            .iter()
195            .filter(|c| !c.text.starts_with("inactive:"))
196            .map(|c| c.text.clone()),
197    );
198    MatchCondition {
199        name: name.to_string(),
200        values,
201    }
202}
203
204fn parse_actions(term: &ConfigLine) -> FilterActions {
205    let mut actions = FilterActions::default();
206    for statement in statements(term, "then") {
207        let (action, arg) = split_keyword(statement);
208        let value = || Some(unquote(arg).to_string());
209        match (action, arg) {
210            ("accept", _) => actions.action = Some(FilterAction::Accept),
211            ("discard", _) => actions.action = Some(FilterAction::Discard),
212            ("reject", _) => {
213                actions.action = Some(FilterAction::Reject);
214                actions.reject_message = value();
215            }
216            ("next", "term") => actions.action = Some(FilterAction::NextTerm),
217            ("count", _) => actions.count = value(),
218            ("policer", _) => actions.policer = value(),
219            ("forwarding-class", _) => actions.forwarding_class = value(),
220            ("loss-priority", _) => actions.loss_priority = value(),
221            ("log", "") => actions.log = true,
222            ("syslog", "") => actions.syslog = true,
223            ("skip", "") => actions.skip = true,
224            ("service", "") => actions.service = true,
225            ("exclude-accounting", "") => actions.exclude_accounting = true,
226            ("bgp-output-queue-priority", _) => actions.bgp_output_queue_priority = value(),
227            ("dont-fragment", _) => actions.dont_fragment = value(),
228            ("dscp", _) => actions.dscp = value(),
229            ("enhanced-hierarchical-policer", "") => actions.enhanced_hierarchical_policer = true,
230            ("force-premium", "") => actions.force_premium = true,
231            ("hierarchical-policer", _) => actions.hierarchical_policer = value().filter(|v| !v.is_empty()),
232            ("ipsec-sa", _) => actions.ipsec_sa = value(),
233            ("load-balance", _) => actions.load_balance = value(),
234            ("logical-system", _) => actions.logical_system = value(),
235            ("next-hop-group", _) => actions.next_hop_group = value(),
236            ("next-interface", _) if !arg.is_empty() => actions.next_interface = value(),
237            ("next-ip", _) => actions.next_ip = value(),
238            ("next-ip6", _) => actions.next_ip6 = value(),
239            ("packet-mode", "") => actions.packet_mode = true,
240            ("policy-map", _) => actions.policy_map = value(),
241            ("port-mirror", _) => {
242                actions.port_mirror = true;
243                actions.port_mirror_instance = value().filter(|v| !v.is_empty());
244            }
245            ("port-mirror-instance", _) => {
246                actions.port_mirror = true;
247                actions.port_mirror_instance = value();
248            }
249            ("prefix-action", _) => actions.prefix_action = value(),
250            ("routing-instance", _) => actions.routing_instance = value(),
251            ("sample", "") => actions.sample = true,
252            ("service-accounting", _) | ("service-accounting-deferred", _) => actions.service_accounting = true,
253            ("service-filter-hit", "") => actions.service_filter_hit = true,
254            ("slice", _) => actions.slice = value(),
255            ("source-class", _) => actions.source_class = value(),
256            ("destination-class", _) => actions.destination_class = value(),
257            ("three-color-policer", _) if !arg.is_empty() => actions.three_color_policer = value(),
258            ("topology", _) => actions.topology = value(),
259            ("traffic-class", _) => actions.traffic_class = value(),
260            ("decapsulate", _) => actions.decapsulate = value(),
261            ("encapsulate", _) => actions.encapsulate = value(),
262            _ => {}
263        }
264    }
265    for then in active_children(term).filter(|c| c.text == "then") {
266        for action in active_children(then) {
267            match action.text.as_str() {
268                "next-interface" => {
269                    actions.next_interface = active_children(action)
270                        .find(|c| !c.text.contains(' '))
271                        .map(|c| c.text.clone());
272                    actions.next_interface_routing_instance = arg_of(action, "routing-instance").map(str::to_string);
273                }
274                "three-color-policer" => {
275                    actions.three_color_policer = active_children(action)
276                        .find(|c| c.text.starts_with("single-rate ") || c.text.starts_with("two-rate "))
277                        .map(|c| c.text.clone());
278                }
279                _ => {}
280            }
281        }
282    }
283    actions
284}