asterust-junos 0.5.6

Typed Juniper JunOS config views (interfaces, protocols, routing instances and options, policy options, firewall filters, class of service, system, services) extracted from an asterust config tree.
Documentation
//! `filter`
//! `firewall { family <family> { filter <name> { term <name> { from { ... } then { ... } } } } }`, and the same for
//! `simple-filter` and `service-filter`.
//!
//! # See also
//!
//! - [filter (Configuring)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/filter-edit-firewall.html)
//! - [term (Firewall Filter)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/term-edit-firewall.html)

use crate::{active_children, arg_of, has_leaf, list_values, named_children, split_keyword, statements, unquote};
use asterust::config::ConfigLine;

/// One `from` match condition, e.g. `destination-port bgp` or `source-address { 10.0.0.0/8; }`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct MatchCondition {
    pub name: String,
    /// Values as written, including any trailing modifier such as `except`; empty for a flag like
    /// `first-fragment`.
    pub values: Vec<String>,
}

/// The terminating action of a filter term. A term without one accepts matching packets.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FilterAction {
    Accept,
    Discard,
    Reject,
    NextTerm,
}

/// The actions of a term's `then` statement. Actions not listed here are ignored.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct FilterActions {
    pub action: Option<FilterAction>,
    /// The message type after `reject`, e.g. `"tcp-reset"`.
    pub reject_message: Option<String>,
    /// `skip`: in a service filter, bypass the service.
    pub skip: bool,
    /// `service`: in a service filter, send the packet to the service.
    pub service: bool,
    pub exclude_accounting: bool,
    pub bgp_output_queue_priority: Option<String>,
    /// `"set"` or `"clear"`.
    pub dont_fragment: Option<String>,
    pub dscp: Option<String>,
    pub enhanced_hierarchical_policer: bool,
    pub force_premium: bool,
    /// The name after `hierarchical-policer`, if given.
    pub hierarchical_policer: Option<String>,
    pub ipsec_sa: Option<String>,
    pub load_balance: Option<String>,
    pub logical_system: Option<String>,
    pub next_hop_group: Option<String>,
    /// The interface of `next-interface`, written inline or as a block.
    pub next_interface: Option<String>,
    /// The `routing-instance` inside a `next-interface` block.
    pub next_interface_routing_instance: Option<String>,
    pub next_ip: Option<String>,
    pub next_ip6: Option<String>,
    pub packet_mode: bool,
    pub policy_map: Option<String>,
    /// `port-mirror` or `port-mirror-instance`.
    pub port_mirror: bool,
    pub port_mirror_instance: Option<String>,
    pub prefix_action: Option<String>,
    pub routing_instance: Option<String>,
    pub sample: bool,
    pub service_accounting: bool,
    pub service_filter_hit: bool,
    pub slice: Option<String>,
    pub source_class: Option<String>,
    pub destination_class: Option<String>,
    /// Everything after `three-color-policer`, e.g. `"single-rate SRTCM1"`.
    pub three_color_policer: Option<String>,
    pub topology: Option<String>,
    pub traffic_class: Option<String>,
    /// Everything after `decapsulate`, e.g. `"gre routing-instance VRF-A"`.
    pub decapsulate: Option<String>,
    /// Everything after `encapsulate`, i.e. the template name.
    pub encapsulate: Option<String>,
    /// Counter name from `count`.
    pub count: Option<String>,
    pub policer: Option<String>,
    pub forwarding_class: Option<String>,
    pub loss_priority: Option<String>,
    pub log: bool,
    pub syslog: bool,
}

/// A `term` of a filter.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct FilterTerm {
    pub name: String,
    pub from: Vec<MatchCondition>,
    pub then: FilterActions,
}

impl FilterTerm {
    /// The `from` condition called `name`, e.g. `"destination-port"`.
    pub fn condition(&self, name: &str) -> Option<&MatchCondition> {
        self.from.iter().find(|c| c.name == name)
    }
}

/// Which statement a filter is written with.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FilterKind {
    /// `filter`.
    Filter,
    /// `simple-filter`, which only sets the forwarding class and loss priority.
    SimpleFilter,
    /// `service-filter`, which selects the traffic that a service processes.
    ServiceFilter,
}

/// A `filter`, `simple-filter` or `service-filter <name>` under `family <family>`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct FirewallFilter {
    /// Address family, e.g. `"inet"`, `"inet6"`, `"bridge"`; `"inet"` for a filter written directly under
    /// `firewall`.
    pub family: String,
    pub kind: FilterKind,
    pub name: String,
    pub accounting_profile: Option<String>,
    pub enhanced_mode: bool,
    pub fast_lookup_filter: bool,
    pub filter_list_template: bool,
    pub interface_shared: bool,
    pub interface_specific: bool,
    pub physical_interface_filter: bool,
    /// `promote gre-key`.
    pub promote_gre_key: bool,
    pub terms: Vec<FilterTerm>,
}

pub(super) fn parse_filter(family: &str, kind: FilterKind, name: &str, line: &ConfigLine) -> FirewallFilter {
    FirewallFilter {
        family: family.to_string(),
        kind,
        name: name.to_string(),
        accounting_profile: arg_of(line, "accounting-profile").map(str::to_string),
        enhanced_mode: has_leaf(line, "enhanced-mode"),
        fast_lookup_filter: has_leaf(line, "fast-lookup-filter"),
        filter_list_template: has_leaf(line, "filter-list-template"),
        interface_shared: has_leaf(line, "interface-shared"),
        interface_specific: has_leaf(line, "interface-specific"),
        physical_interface_filter: has_leaf(line, "physical-interface-filter"),
        promote_gre_key: arg_of(line, "promote") == Some("gre-key"),
        terms: named_children(line, "term")
            .map(|(term_name, term)| FilterTerm {
                name: term_name.to_string(),
                from: parse_conditions(term),
                then: parse_actions(term),
            })
            .collect(),
    }
}

/// Conditions written either as `from x;` or inside a `from { ... }` block.
fn parse_conditions(term: &ConfigLine) -> Vec<MatchCondition> {
    let mut found = Vec::new();
    for child in active_children(term) {
        if child.text == "from" {
            found.extend(active_children(child).map(parse_condition));
        } else if let Some(statement) = child.arg("from") {
            found.push(condition_from(statement, &[]));
        }
    }
    found
}

fn parse_condition(line: &ConfigLine) -> MatchCondition {
    condition_from(&line.text, &line.children)
}

fn condition_from(statement: &str, children: &[ConfigLine]) -> MatchCondition {
    let (name, arg) = split_keyword(statement);
    // A bare value keeps its modifier (`10.0.0.0/8 except`); only a bracketed list is split.
    let mut values = if arg.is_empty() {
        Vec::new()
    } else if arg.starts_with('[') {
        list_values(arg)
    } else {
        vec![unquote(arg).to_string()]
    };
    values.extend(
        children
            .iter()
            .filter(|c| !c.text.starts_with("inactive:"))
            .map(|c| c.text.clone()),
    );
    MatchCondition {
        name: name.to_string(),
        values,
    }
}

fn parse_actions(term: &ConfigLine) -> FilterActions {
    let mut actions = FilterActions::default();
    for statement in statements(term, "then") {
        let (action, arg) = split_keyword(statement);
        let value = || Some(unquote(arg).to_string());
        match (action, arg) {
            ("accept", _) => actions.action = Some(FilterAction::Accept),
            ("discard", _) => actions.action = Some(FilterAction::Discard),
            ("reject", _) => {
                actions.action = Some(FilterAction::Reject);
                actions.reject_message = value();
            }
            ("next", "term") => actions.action = Some(FilterAction::NextTerm),
            ("count", _) => actions.count = value(),
            ("policer", _) => actions.policer = value(),
            ("forwarding-class", _) => actions.forwarding_class = value(),
            ("loss-priority", _) => actions.loss_priority = value(),
            ("log", "") => actions.log = true,
            ("syslog", "") => actions.syslog = true,
            ("skip", "") => actions.skip = true,
            ("service", "") => actions.service = true,
            ("exclude-accounting", "") => actions.exclude_accounting = true,
            ("bgp-output-queue-priority", _) => actions.bgp_output_queue_priority = value(),
            ("dont-fragment", _) => actions.dont_fragment = value(),
            ("dscp", _) => actions.dscp = value(),
            ("enhanced-hierarchical-policer", "") => actions.enhanced_hierarchical_policer = true,
            ("force-premium", "") => actions.force_premium = true,
            ("hierarchical-policer", _) => actions.hierarchical_policer = value().filter(|v| !v.is_empty()),
            ("ipsec-sa", _) => actions.ipsec_sa = value(),
            ("load-balance", _) => actions.load_balance = value(),
            ("logical-system", _) => actions.logical_system = value(),
            ("next-hop-group", _) => actions.next_hop_group = value(),
            ("next-interface", _) if !arg.is_empty() => actions.next_interface = value(),
            ("next-ip", _) => actions.next_ip = value(),
            ("next-ip6", _) => actions.next_ip6 = value(),
            ("packet-mode", "") => actions.packet_mode = true,
            ("policy-map", _) => actions.policy_map = value(),
            ("port-mirror", _) => {
                actions.port_mirror = true;
                actions.port_mirror_instance = value().filter(|v| !v.is_empty());
            }
            ("port-mirror-instance", _) => {
                actions.port_mirror = true;
                actions.port_mirror_instance = value();
            }
            ("prefix-action", _) => actions.prefix_action = value(),
            ("routing-instance", _) => actions.routing_instance = value(),
            ("sample", "") => actions.sample = true,
            ("service-accounting", _) | ("service-accounting-deferred", _) => actions.service_accounting = true,
            ("service-filter-hit", "") => actions.service_filter_hit = true,
            ("slice", _) => actions.slice = value(),
            ("source-class", _) => actions.source_class = value(),
            ("destination-class", _) => actions.destination_class = value(),
            ("three-color-policer", _) if !arg.is_empty() => actions.three_color_policer = value(),
            ("topology", _) => actions.topology = value(),
            ("traffic-class", _) => actions.traffic_class = value(),
            ("decapsulate", _) => actions.decapsulate = value(),
            ("encapsulate", _) => actions.encapsulate = value(),
            _ => {}
        }
    }
    for then in active_children(term).filter(|c| c.text == "then") {
        for action in active_children(then) {
            match action.text.as_str() {
                "next-interface" => {
                    actions.next_interface = active_children(action)
                        .find(|c| !c.text.contains(' '))
                        .map(|c| c.text.clone());
                    actions.next_interface_routing_instance = arg_of(action, "routing-instance").map(str::to_string);
                }
                "three-color-policer" => {
                    actions.three_color_policer = active_children(action)
                        .find(|c| c.text.starts_with("single-rate ") || c.text.starts_with("two-rate "))
                        .map(|c| c.text.clone());
                }
                _ => {}
            }
        }
    }
    actions
}