diff --git a/CHANGELOG.md b/CHANGELOG.md index b687782b..ed8905b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,16 +6,27 @@ All notable changes to this project will be documented in this file. ### Breaking changes +* **`ElemType` gains `RESET` and is `#[non_exhaustive]`**: RFC 7606 error handling (see Added) marks announcements of an UPDATE whose errors call for a session reset or AFI/SAFI disable with the new variant, rendered `R` in text and PSV output. Matches on `ElemType` now need a wildcard arm. Without RFC 7606 error handling enabled, no `RESET` elems are produced. +* **`BgpElem` gains an `error_handling` field**: the RFC 7606 approach applied to the elem's UPDATE, `None` unless RFC 7606 error handling is enabled and the UPDATE had findings. Struct literals need `error_handling: None` (or `..Default::default()`); JSON output omits the field when it is `None`, and PSV output is unchanged. `Elementor` also gains a private field, so build it with `Elementor::new()` or `Elementor::with_peer_table` instead of a struct literal. +* **More specific RFC 7606 findings**: a malformed ORIGIN, AS_PATH or NEXT_HOP is reported as `InvalidOriginAttribute`, `MalformedAsPath` or `InvalidNextHopAttribute` instead of `MalformedAttributeList`, and a malformed LOCAL_PREF as `OptionalAttributeError`. A malformed MP_REACH_NLRI or MP_UNREACH_NLRI is reported as `MalformedNlri { nlri_type: "mp_reach" | "mp_unreach", .. }` with the attribute bytes, instead of `OptionalAttributeError`. `MalformedAttributeList` now means an attribute-list framing error. * **`ParserBmpError` carries the failing value and is `#[non_exhaustive]`**: `From` and the unknown-message-type conversion collapsed every failure into `InvalidOpenBmpHeader` and dropped the cause; they now return the new `IoError { kind, message }` and `UnknownMessageType(u8)` variants. Downstream matches on the enum now need a wildcard arm: `#[non_exhaustive]` means the two new variants cannot be covered by adding arms alone. ### Added +* **RFC 7606 error handling (treat-as-withdraw)** ([RFC 7606](https://datatracker.ietf.org/doc/html/rfc7606)): the parser now says what a router does with each malformed UPDATE, not just that it is malformed. + * `models::malformed_attribute_approach` maps every path attribute to the approach its RFC prescribes when it is malformed — attribute discard, treat-as-withdraw, AFI/SAFI disable, or session reset — covering RFC 7606 §7 and the later attribute RFCs (AS4_PATH, PMSI_TUNNEL, Tunnel Encapsulation, AIGP, BGP-LS, Large Communities, BGPsec_PATH, OTC, D-PATH, SFP, BFD Discriminator, Prefix-SID, BIER). The table is also documented in `src/parser/bgp/attributes/README.md`. + * `BgpValidationWarning::error_handling_approach` classifies one finding; `Attributes::error_handling_approach`, `BgpUpdateMessage::error_handling_approach` and `BgpUpdateMessage::is_treat_as_withdraw` combine an UPDATE's findings with the "strongest action wins" rule (§3(h)) and the missing-NLRI escalation (§5.2). + * MRT data does not record the session type and route collectors peer over eBGP, so the classification assumes eBGP: a malformed LOCAL_PREF, ORIGINATOR_ID or CLUSTER_LIST is attribute discard rather than treat-as-withdraw. + * Opt-in elem conversion: `BgpkitParser::enable_rfc7606_error_handling()` / `with_error_handling(ErrorHandlingMode)`, `Elementor::with_error_handling`, and the CLI flag `--rfc7606`. Announcements of a treat-as-withdraw UPDATE become `WITHDRAW` elems, those of a session-reset or AFI/SAFI-disable UPDATE become `RESET` elems, and attributes subject to attribute discard (plus repeats of an attribute after its first occurrence) are left out. Elem and filtered record iteration apply it; RIB entries are unchanged. The route iterator stays a selective parser: it checks every attribute header like the elem iterator, but parses only the values of ORIGIN, AS_PATH, AS4_PATH, MP_REACH_NLRI and MP_UNREACH_NLRI, so it may keep routes the elem iterator withdraws, never the reverse. +* **New RFC 7606 findings**: an attribute running past the attribute list, or trailing bytes too short for an attribute header (§4), previously skipped silently, now record `MalformedAttributeList`. Length checks now cover the "non-zero multiple of N" rules (COMMUNITIES, CLUSTER_LIST, extended, IPv6-specific and large communities), AGGREGATOR (6 or 8), AS4_AGGREGATOR (8), and the MP_REACH_NLRI/MP_UNREACH_NLRI minimums. An unrecognized attribute without the optional bit records `UnrecognizedWellKnownAttribute`, AS path segments without ASNs record `MalformedAsPath`, and AS 0 in AS_PATH, AS4_PATH, AGGREGATOR or AS4_AGGREGATOR is reported per [RFC 7607](https://datatracker.ietf.org/doc/html/rfc7607). The typed values are kept, so default elem output does not change. * **BGP Domain Path (D-PATH) attribute support** ([RFC 10039](https://datatracker.ietf.org/doc/html/rfc10039)): path attribute type 36 now parses into `AttributeValue::DomainPath(DomainPathAttribute)` — segments of `DomainPathDomain { global_admin, local_admin, isf_safi_type }` — and re-encodes byte-identically instead of falling into the `Unknown` raw catch-all. Malformed values, and a D-PATH on a family other than IPVPN or EVPN, become RFC 7606 validation findings with the bytes retained raw, and the encoder refuses values it cannot represent. Text rendering and byte-level dissection label the attribute `BGP_DOMAIN_PATH`. * **`--color auto|always|never` for `--format text`**: colors session keys, section headers, prefixes, and next-hop values with ANSI accents that follow the terminal theme. `auto` (the default) colors only when stdout is a terminal; `NO_COLOR` disables coloring and `CLICOLOR_FORCE` forces it. Library callers opt in with `render::text::Style::ansi()` plus the new `format_record_with_style` / `format_record_with_hex_and_style`; `format_record` and the unstyled output are unchanged, since styling is a post-pass over the rendered block. * **`parse_ris_live_message_iter`**: parses one RIS Live JSON message into an iterator over its elems instead of a `Vec`. Every elem carries its own copy of the message's AS path and communities, so collecting a message that announces many prefixes needs memory proportional to prefixes × path length; the iterator makes those copies one elem at a time. `parse_ris_live_message` is unchanged and now builds on it. ### Changed +* **Repeated attributes report only `DuplicateAttribute`**: RFC 7606 §3(g) discards every repeat of an attribute, so flag, length and value errors in a repeat are no longer reported, and no longer withdraw the routes or discard the valid first copy. +* **`examples/treat_as_withdrawal.rs` uses the library classification**: the example's own Junos-style classifier is replaced by `error_handling_approach()` and `enable_rfc7606_error_handling()`. * **Internal cleanups, no behavior change**: the MP next-hop encoder (`encode_mp_next_hop`) is shared by the `NEXT_HOP` and MP_REACH encoders instead of being duplicated, `AsPathSegment` hashing skips the sort when a set is already ordered, `Elementor::record_to_elems` logs peer-table conversion errors as its documentation promises, the invariant `unreachable!()` arms state their invariant, and both the crate-wide `uninlined_format_args` allow and a module-wide `#![allow(unused)]` are removed. * **`--format text` session labels are now `PEER`/`LOCAL`**: the endpoint lines read `PEER: AS` and `LOCAL: AS`, matching the peer/local names MRT ([RFC 6396](https://www.rfc-editor.org/rfc/rfc6396.html)) uses for the same fields instead of the ambiguous `FROM`/`TO`. The rendered values are unchanged. * **Record parse errors are logged once per parser**: the default, raw, update and route iterators log the first `ParseError` of a parser at `error` level and later ones at `debug` level. A corrupted stream re-synchronises header by header, which previously emitted one `error` line per 12 bytes of damaged input. Other error classes are logged as before. diff --git a/README.md b/README.md index bbaf63f3..bee90c92 100644 --- a/README.md +++ b/README.md @@ -246,6 +246,51 @@ match process_mrt_file("http://example.com/updates.bz2") { } ``` +**RFC 7606 Error Handling (Treat-as-Withdraw)** + +Malformed path attributes never stop parsing: each finding is recorded as a +`BgpValidationWarning` on the UPDATE, and the attribute bytes are kept. RFC 7606 and the RFCs +defining later attributes say what a router does with each finding: discard the attribute, treat +the UPDATE's routes as withdrawn, disable the AFI/SAFI, or reset the session. +`BgpUpdateMessage::error_handling_approach` returns that approach for an UPDATE, combining its +findings with the "strongest action wins" rule. The attribute-to-approach table is +`models::malformed_attribute_approach`. + +MRT data does not say whether a session was iBGP or eBGP. Route collectors peer over eBGP, so the +classification assumes eBGP: a malformed LOCAL_PREF, ORIGINATOR_ID or CLUSTER_LIST is attribute +discard, not treat-as-withdraw. + +Element output is unchanged unless you opt in with `enable_rfc7606_error_handling()`. Then: + +- announcements of an UPDATE that RFC 7606 treats as withdrawn become `ElemType::WITHDRAW`; +- announcements of an UPDATE whose errors call for a session reset or AFI/SAFI disable become + `ElemType::RESET`; +- attributes subject to attribute discard, and repeats of an attribute after its first + occurrence, are left out of the announcement; +- every element of such an UPDATE carries the approach in `BgpElem::error_handling`. + +RIB dump entries are converted as before. The CLI flag is `--rfc7606`. + +The route iterator (`into_route_iter`) stays a cheap, selective parser under this mode: it checks +every attribute header like the element iterators do, but parses only the values of ORIGIN, +AS_PATH, AS4_PATH, MP_REACH_NLRI and MP_UNREACH_NLRI. It can miss a value error in another +attribute, so it may keep routes the element iterators withdraw, never the reverse. + +```rust +use bgpkit_parser::BgpkitParser; +use bgpkit_parser::models::{ElemType, ErrorHandlingApproach}; + +let parser = BgpkitParser::new("https://data.ris.ripe.net/rrc00/latest-update.gz") + .unwrap() + .enable_rfc7606_error_handling(); +for elem in parser { + if elem.error_handling == Some(ErrorHandlingApproach::TreatAsWithdraw) { + assert_eq!(elem.elem_type, ElemType::WITHDRAW); + println!("treated as withdrawn: {}", elem.prefix); + } +} +``` + **Recovering After Damaged MRT Framing** Recovery is opt-in and never reconstructs a damaged record. It reports the skipped decompressed @@ -758,7 +803,7 @@ See the [BgpElem] documentation for the complete structure definition. **Key fields**: - `timestamp`: Unix timestamp of the BGP message -- `elem_type`: Announcement or withdrawal +- `elem_type`: Announcement, withdrawal, or (with RFC 7606 error handling) reset - `peer_ip` / `peer_asn`: The BGP peer information - `prefix`: The IP prefix being announced or withdrawn - `as_path`: The AS path attribute (if present) @@ -795,6 +840,7 @@ BGPKIT Parser implements comprehensive BGP, MRT, BMP, and related protocol stand - [RFC 4271](https://datatracker.ietf.org/doc/html/rfc4271): A Border Gateway Protocol 4 (BGP-4) - Core protocol - [RFC 2858](https://datatracker.ietf.org/doc/html/rfc2858): Multiprotocol Extensions for BGP-4 (IPv6 support) - [RFC 6793](https://datatracker.ietf.org/doc/html/rfc6793): Four-Octet AS Number Space +- [RFC 7607](https://datatracker.ietf.org/doc/html/rfc7607): Codification of AS 0 Processing - [RFC 7911](https://datatracker.ietf.org/doc/html/rfc7911): Advertisement of Multiple Paths (ADD-PATH) **Additional BGP RFCs**: diff --git a/examples/README.md b/examples/README.md index ab90f44d..ae787d8b 100644 --- a/examples/README.md +++ b/examples/README.md @@ -69,7 +69,7 @@ Construct and serialize BGP/MRT data, including the fallible encoders and the RF - [dissect_mrt.rs](dissect_mrt.rs) — Wireshark-style byte-level dissection: render the `DissectionNode` field tree with byte-offset gutters for MRT/BGP records, including a truncated-input demo showing dissectors never fail. - [diagnostic_iterator.rs](diagnostic_iterator.rs) — Classify clean records, RFC 7606 validation findings, and fatal parse failures while exporting each finding's raw MRT bytes. -- [treat_as_withdrawal.rs](treat_as_withdrawal.rs) — Scan MRT files for RFC 7606 validation issues (malformed NLRI, bad attributes) and classify them by error-handling category: attribute discard vs. treat-as-withdrawal. +- [treat_as_withdrawal.rs](treat_as_withdrawal.rs) — Report the RFC 7606 approach (attribute discard, treat-as-withdraw, AFI/SAFI disable, session reset) of each malformed UPDATE in an MRT file, then count the announcements `enable_rfc7606_error_handling()` withdraws. - [fallible_parsing.rs](fallible_parsing.rs) — Demonstrate fallible record/element iterators that let you handle parse errors explicitly while continuing to process. - [mrt_debug.rs](mrt_debug.rs) — Print parsed and raw MRT records for debugging, including raw-byte export and re-parsing. - [extract_problematic_records.rs](extract_problematic_records.rs) — Find and export MRT records that fail to parse for further analysis with other tools. diff --git a/examples/treat_as_withdrawal.rs b/examples/treat_as_withdrawal.rs index 5a97db26..2e8c9f39 100644 --- a/examples/treat_as_withdrawal.rs +++ b/examples/treat_as_withdrawal.rs @@ -1,308 +1,109 @@ -//! # RFC 7606 Treat-as-Withdrawal and Junos-style Error Classification +//! # RFC 7606 error handling: treat-as-withdraw and friends //! -//! This example demonstrates how to detect malformed BGP UPDATE messages and -//! apply RFC 7606 error-handling semantics using bgpkit-parser's validation -//! warning system. It classifies messages into the three severity tiers used -//! by Junos OS `bgp-error-tolerance`, applying the "most severe wins" rule. +//! RFC 7606 replaces "reset the session on any UPDATE error" with per-attribute +//! approaches, from weakest to strongest: //! -//! ## Three-tier error handling (Junos model) +//! 1. **Attribute discard**: drop the malformed attribute, keep the routes. +//! 2. **Treat-as-withdraw**: withdraw every route the UPDATE announces. +//! 3. **AFI/SAFI disable**: stop accepting the family the error concerns. +//! 4. **Session reset**: send a NOTIFICATION and reset the session. //! -//! 1. **Notification** (session reset): the most severe. Triggered by -//! malformed MP_REACH/MP_UNREACH, unparseable NLRI, or attribute -//! length/value mismatch. The BGP session is reset. +//! When an UPDATE has several errors, the strongest approach wins (§3(h)). //! -//! 2. **Treat-as-withdrawal**: all routes in the UPDATE are withdrawn. -//! Triggered by malformed well-known mandatory attributes (ORIGIN, -//! AS_PATH, NEXT_HOP), plus LOCAL_PREF, MED, communities, and others. +//! bgpkit-parser records every finding as a `BgpValidationWarning`, classifies it with +//! `BgpValidationWarning::error_handling_approach`, and combines them per UPDATE with +//! `BgpUpdateMessage::error_handling_approach`. MRT data does not record whether a session +//! was iBGP or eBGP; route collectors peer over eBGP, so the classification assumes eBGP. //! -//! 3. **Attribute discard**: the bad attribute is dropped, route retained. -//! Triggered by malformed optional transitive attributes (AS4_PATH, -//! AGGREGATOR, AS4_AGGREGATOR, ATOMIC_AGGREGATE) and duplicate attributes. +//! This example scans an updates file twice: //! -//! When multiple attributes are malformed in one UPDATE, the **most severe** -//! approach triggered by any single attribute is applied to the entire message. -//! -//! ## Important caveats -//! -//! - bgpkit-parser parses MRT data (offline captures), not live sessions. It -//! provides the detection signals; this example applies the classification -//! policy that a router like Junos would apply. -//! - bgpkit-parser always recovers what it can: framing errors are fatal, but -//! bad NLRI and bad attributes produce warnings + partial data. A real -//! router additionally *acts* on the classification (hide route, reset -//! session, etc.). +//! - over records, printing each UPDATE that has an approach and the finding behind it; +//! - over elements with `enable_rfc7606_error_handling()`, counting the announcements a +//! compliant speaker would not have installed. //! //! Run with: //! ```sh //! cargo run --example treat_as_withdrawal --features="local" //! ``` -use bgpkit_parser::error::BgpValidationWarning; -use bgpkit_parser::models::{AttrType, Bgp4MpEnum, BgpMessage, MrtMessage}; +use bgpkit_parser::models::{ + Bgp4MpEnum, BgpMessage, ElemType, ErrorHandlingApproach, MrtMessage, MrtRecord, +}; use bgpkit_parser::BgpkitParser; - -/// Severity tiers in decreasing order of severity (Junos model). -/// When multiple attributes are malformed, the most severe tier wins. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -enum ErrorTier { - /// Session reset (fatal). MP_REACH/MP_UNREACH malformed, unparseable NLRI. - Notification, - /// Withdraw all routes in the UPDATE. Bad mandatory + some optional attrs. - TreatAsWithdrawal, - /// Drop the bad attribute, keep the route. Bad optional transitive attrs. - AttributeDiscard, -} - -/// Classify a single validation warning into a severity tier and human-readable -/// attribute name, following the Junos per-attribute mapping. -fn classify_warning(w: &BgpValidationWarning) -> Option<(ErrorTier, &'static str)> { - match w { - // --- Notification level --- - // Malformed NLRI: Junos treats unparseable NLRI as notification-level. - BgpValidationWarning::MalformedNlri { .. } => Some((ErrorTier::Notification, "NLRI")), - // Malformed attribute list (well-known mandatory parse failure): - // Junos treats these as notification-level (can't parse the UPDATE). - BgpValidationWarning::MalformedAttributeList { .. } => { - Some((ErrorTier::Notification, "attribute list")) - } - // Missing well-known mandatory: if ORIGIN, AS_PATH, or NEXT_HOP is - // missing, Junos uses treat-as-withdrawal. - BgpValidationWarning::MissingWellKnownAttribute { attr_type } => { - Some((ErrorTier::TreatAsWithdrawal, attr_label(*attr_type))) - } - // --- Treat-as-withdrawal level --- - BgpValidationWarning::InvalidOriginAttribute { .. } => { - Some((ErrorTier::TreatAsWithdrawal, "ORIGIN")) - } - BgpValidationWarning::MalformedAsPath { .. } => { - Some((ErrorTier::TreatAsWithdrawal, "AS_PATH")) - } - BgpValidationWarning::InvalidNextHopAttribute { .. } => { - Some((ErrorTier::TreatAsWithdrawal, "NEXT_HOP")) - } - // Partial attribute errors for well-known mandatory attrs → TAW - BgpValidationWarning::PartialAttributeError { attr_type, .. } => { - let tier = if is_taw_attribute(*attr_type) { - ErrorTier::TreatAsWithdrawal - } else { - ErrorTier::AttributeDiscard - }; - Some((tier, attr_label(*attr_type))) - } - BgpValidationWarning::OptionalAttributeError { attr_type, .. } => { - let tier = if is_taw_attribute(*attr_type) { - ErrorTier::TreatAsWithdrawal - } else { - ErrorTier::AttributeDiscard - }; - Some((tier, attr_label(*attr_type))) - } - // --- Attribute discard level --- - // These attributes get "attribute discard" treatment in Junos - BgpValidationWarning::AttributeFlagsError { attr_type, .. } => { - let tier = if is_taw_attribute(*attr_type) { - ErrorTier::TreatAsWithdrawal - } else { - ErrorTier::AttributeDiscard - }; - Some((tier, attr_label(*attr_type))) - } - BgpValidationWarning::AttributeLengthError { attr_type, .. } => { - let tier = if is_taw_attribute(*attr_type) { - ErrorTier::TreatAsWithdrawal - } else { - ErrorTier::AttributeDiscard - }; - Some((tier, attr_label(*attr_type))) - } - BgpValidationWarning::DuplicateAttribute { attr_type } => { - // Junos: duplicate attributes → discard all but the first - Some((ErrorTier::AttributeDiscard, attr_label(*attr_type))) - } - // Structural issues - BgpValidationWarning::InvalidNetworkField { .. } => { - Some((ErrorTier::TreatAsWithdrawal, "network field")) - } - BgpValidationWarning::UnrecognizedWellKnownAttribute { .. } => { - Some((ErrorTier::Notification, "unrecognized well-known")) - } // Partial attribute for optional transitive → attribute discard +use std::collections::BTreeMap; + +fn update_of(record: &MrtRecord) -> Option<&bgpkit_parser::models::BgpUpdateMessage> { + match &record.message { + MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(msg)) => match &msg.bgp_message { + BgpMessage::Update(update) => Some(update), + _ => None, + }, _ => None, } } -/// Attributes that trigger treat-as-withdrawal in Junos when malformed. -/// Everything else with a validation warning defaults to attribute discard. -fn is_taw_attribute(attr_type: AttrType) -> bool { - matches!( - attr_type, - AttrType::ORIGIN - | AttrType::AS_PATH - | AttrType::NEXT_HOP - | AttrType::MULTI_EXIT_DISCRIMINATOR - | AttrType::LOCAL_PREFERENCE - | AttrType::COMMUNITIES - | AttrType::EXTENDED_COMMUNITIES - | AttrType::ORIGINATOR_ID - | AttrType::CLUSTER_LIST - | AttrType::AIGP - | AttrType::PMSI_TUNNEL - | AttrType::ATTR_SET - ) -} - -/// Human-readable attribute name for display. -fn attr_label(attr_type: AttrType) -> &'static str { - match attr_type { - AttrType::ORIGIN => "ORIGIN", - AttrType::AS_PATH => "AS_PATH", - AttrType::NEXT_HOP => "NEXT_HOP", - AttrType::MULTI_EXIT_DISCRIMINATOR => "MULTI_EXIT_DISC", - AttrType::LOCAL_PREFERENCE => "LOCAL_PREF", - AttrType::ATOMIC_AGGREGATE => "ATOMIC_AGGREGATE", - AttrType::AGGREGATOR => "AGGREGATOR", - AttrType::COMMUNITIES => "COMMUNITIES", - AttrType::ORIGINATOR_ID => "ORIGINATOR_ID", - AttrType::CLUSTER_LIST => "CLUSTER_LIST", - AttrType::MP_REACHABLE_NLRI => "MP_REACH_NLRI", - AttrType::MP_UNREACHABLE_NLRI => "MP_UNREACH_NLRI", - AttrType::EXTENDED_COMMUNITIES => "EXT_COMMUNITIES", - AttrType::AS4_PATH => "AS4_PATH", - AttrType::AS4_AGGREGATOR => "AS4_AGGREGATOR", - AttrType::AIGP => "AIGP", - AttrType::PMSI_TUNNEL => "PMSI_TUNNEL", - AttrType::ATTR_SET => "ATTR_SET", - AttrType::ONLY_TO_CUSTOMER => "OTC", - _ => "UNKNOWN", - } -} - -fn tier_label(tier: ErrorTier) -> &'static str { - match tier { - ErrorTier::Notification => "NOTIFICATION (session reset)", - ErrorTier::TreatAsWithdrawal => "TREAT-AS-WITHDRAWAL", - ErrorTier::AttributeDiscard => "ATTRIBUTE DISCARD", - } -} - fn main() { - // Point this at a collector and time window where malformed messages - // are suspected. For the Qrator OTC incident, look for UPDATEs from - // the affected ASes during the incident window. + // Point this at a collector and time window where malformed messages are suspected. let url = "https://data.ris.ripe.net/rrc00/2026.07/updates.20260727.0000.gz"; - println!("Scanning {} for BGP error-handling issues...\n", url); + println!("Scanning {url} for UPDATE errors...\n"); let parser = match BgpkitParser::new(url) { Ok(p) => p.disable_warnings(), Err(e) => { - eprintln!("Failed to create parser: {}", e); + eprintln!("Failed to create parser: {e}"); return; } }; - let mut total_records = 0u64; - let mut records_with_issues = 0u64; - let mut by_tier = [0u64; 3]; // [notification, taw, attr_discard] - - for result in parser.into_fallible_record_iter() { - match result { - Ok(record) => { - total_records += 1; - - let warnings = extract_validation_warnings(&record); - if warnings.is_empty() { - continue; - } - records_with_issues += 1; - - // Classify each warning and find the most severe tier - // (Junos "most severe wins" rule) - let findings: Vec<(ErrorTier, &str, &BgpValidationWarning)> = warnings - .iter() - .filter_map(|w| classify_warning(w).map(|(t, name)| (t, name, w))) - .collect(); - - if findings.is_empty() { - continue; - } - - // Most severe tier for this record (min ordinal = most severe) - let overall_tier = findings.iter().map(|(t, _, _)| *t).min().unwrap(); - by_tier[overall_tier as usize] += 1; - - println!( - "--- {} (record #{}) ---", - tier_label(overall_tier), - total_records - ); - - for (tier, name, warning) in &findings { - let marker = if *tier == overall_tier { "→" } else { " " }; - let action = match tier { - ErrorTier::Notification => "session reset", - ErrorTier::TreatAsWithdrawal => "routes withdrawn", - ErrorTier::AttributeDiscard => "attribute discarded", - }; - println!(" {marker} [{name}] {warning}"); - println!(" action: {action}"); - - // Show raw NLRI bytes if available - if let BgpValidationWarning::MalformedNlri { raw_bytes, .. } = warning { - let display_len = raw_bytes.len().min(32); - println!( - " raw NLRI ({} bytes): {:02x?}", - display_len, - &raw_bytes[..display_len] - ); - } - } - println!(); - } - Err(e) => { - total_records += 1; - by_tier[ErrorTier::Notification as usize] += 1; - if let Some(bytes) = &e.bytes { - eprintln!( - "Record #{}: FATAL ({} raw bytes preserved): {}", - total_records, - bytes.len(), - e - ); - } else { - eprintln!("Record #{}: FATAL: {}", total_records, e); - } - } + let mut by_approach: BTreeMap = BTreeMap::new(); + for record in parser.into_record_iter() { + let Some(update) = update_of(&record) else { + continue; + }; + let Some(approach) = update.error_handling_approach() else { + continue; + }; + *by_approach.entry(approach).or_default() += 1; + + println!("--- {approach:?} at {} ---", record.common_header.timestamp); + for warning in update.attributes.validation_warnings() { + let marker = match warning.error_handling_approach() { + Some(a) if a == approach => "→", + _ => " ", + }; + println!(" {marker} {warning}"); } + println!(); } - println!("=== Summary ==="); - println!("Total records scanned: {}", total_records); - println!("Records with issues: {}", records_with_issues); - println!( - " Notification (session reset): {}", - by_tier[ErrorTier::Notification as usize] - ); - println!( - " Treat-as-withdrawal: {}", - by_tier[ErrorTier::TreatAsWithdrawal as usize] - ); - println!( - " Attribute discard: {}", - by_tier[ErrorTier::AttributeDiscard as usize] - ); -} + println!("=== UPDATEs per approach ==="); + for (approach, count) in &by_approach { + println!(" {approach:?}: {count}"); + } -/// Extract validation warnings from an MrtRecord. -fn extract_validation_warnings( - record: &bgpkit_parser::models::MrtRecord, -) -> &[BgpValidationWarning] { - let bgp_message = match &record.message { - MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(msg)) => &msg.bgp_message, - _ => return &[], + // The same file as elements, with RFC 7606 applied. + let parser = match BgpkitParser::new(url) { + Ok(p) => p.disable_warnings().enable_rfc7606_error_handling(), + Err(e) => { + eprintln!("Failed to create parser: {e}"); + return; + } }; - - match bgp_message { - BgpMessage::Update(u) => u.attributes.validation_warnings(), - _ => &[], + let mut withdrawn = 0u64; + let mut reset = 0u64; + let mut discarded = 0u64; + for elem in parser { + match (elem.elem_type, elem.error_handling) { + (ElemType::WITHDRAW, Some(ErrorHandlingApproach::TreatAsWithdraw)) => withdrawn += 1, + (ElemType::RESET, _) => reset += 1, + (ElemType::ANNOUNCE, Some(ErrorHandlingApproach::AttributeDiscard)) => discarded += 1, + _ => {} + } } + + println!("\n=== Elements with RFC 7606 applied ==="); + println!(" announcements treated as withdrawn: {withdrawn}"); + println!(" announcements in session-reset UPDATEs: {reset}"); + println!(" announcements with attributes dropped: {discarded}"); } diff --git a/examples/update_messages_iter.rs b/examples/update_messages_iter.rs index a60bbf3d..13ded663 100644 --- a/examples/update_messages_iter.rs +++ b/examples/update_messages_iter.rs @@ -121,6 +121,8 @@ fn main() { match elem.elem_type { ElemType::ANNOUNCE => elem_iter_announced += 1, ElemType::WITHDRAW => elem_iter_withdrawn += 1, + // RESET elems only appear with RFC 7606 error handling enabled + _ => {} } } diff --git a/src/bin/README.md b/src/bin/README.md index 7c124c66..759386ef 100644 --- a/src/bin/README.md +++ b/src/bin/README.md @@ -26,6 +26,7 @@ Options: -e, --elems-count Count BGP elems -r, --records-count Count MRT records --recover Recover after damaged MRT framing and report skipped byte ranges on stderr + --rfc7606 Apply RFC 7606 error handling to elems (treat-as-withdraw, attribute discard, reset) -o, --origin-asn Filter by origin AS Number -f, --filter Generic filter expression (key=value or key!=value) -p, --prefix Filter by network prefix @@ -35,7 +36,7 @@ Options: -6, --ipv6-only Filter by IPv6 only -j, --peer-ip Filter by peer IP address -J, --peer-asn Filter by peer ASN - -m, --elem-type Filter by elem type: announce (a) or withdraw (w) + -m, --elem-type Filter by elem type: announce (a), withdraw (w), or reset (r, with --rfc7606) -t, --start-ts Filter by start unix timestamp inclusive -T, --end-ts Filter by end unix timestamp inclusive -a, --as-path Filter by AS path regex string diff --git a/src/bin/main.rs b/src/bin/main.rs index 885674a9..cf0440ae 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -4,6 +4,7 @@ use std::io::{IsTerminal, Write}; use std::net::IpAddr; use std::path::PathBuf; +use bgpkit_parser::models::ErrorHandlingMode; use bgpkit_parser::render::text::Style; use bgpkit_parser::{BgpElem, BgpkitParser, Elementor, RecoveryConfig, RecoveryEvent, RecoveryGap}; use clap::{Parser, ValueEnum}; @@ -107,6 +108,14 @@ struct Opts { #[clap(long)] recover: bool, + /// Apply RFC 7606 error handling to elems, assuming eBGP sessions: announcements of + /// an UPDATE that must be treated as withdrawn are output as withdrawals (W), + /// session-reset-class errors as resets (R), and malformed attributes subject to + /// attribute discard are dropped. JSON elems carry the applied approach in + /// `error_handling`. + #[clap(long)] + rfc7606: bool, + #[clap(flatten)] filters: Filters, } @@ -153,7 +162,7 @@ struct Filters { #[clap(short = 'J', long)] peer_asn: Option, - /// Filter by elem type: announce (a) or withdraw (w) + /// Filter by elem type: announce (a), withdraw (w), or reset (r, with --rfc7606) #[clap(short = 'm', long)] elem_type: Option, @@ -225,6 +234,9 @@ fn main() { .add_filter("peer_asn", v.to_string().as_str()) .unwrap(); } + if opts.rfc7606 { + parser = parser.enable_rfc7606_error_handling(); + } if let Some(v) = opts.filters.elem_type { parser = parser.add_filter("type", v.as_str()).unwrap(); } @@ -319,6 +331,11 @@ fn main() { // parsed records. Count-only runs emit no hex, so they keep the // normal elem/record counting pipelines and their semantics // (per-elem filtering for -e). + let error_handling = if opts.rfc7606 { + ErrorHandlingMode::Rfc7606 + } else { + ErrorHandlingMode::Preserve + }; let result = if opts.hex && !counting { run_hex_records(parser.into_filtered_raw_record_iter(), output_format, style) } else { @@ -348,6 +365,7 @@ fn main() { opts.elems_count, opts.records_count, true, + error_handling, ), (false, false) => run_records( parser @@ -358,6 +376,7 @@ fn main() { opts.elems_count, opts.records_count, false, + error_handling, ), } }; @@ -450,6 +469,7 @@ where terminal_error.map_or(Ok(()), Err) } +#[allow(clippy::too_many_arguments)] fn run_records( events: I, output_format: OutputFormat, @@ -457,12 +477,13 @@ fn run_records( elems_count_requested: bool, records_count_requested: bool, report_recovery: bool, + error_handling: ErrorHandlingMode, ) -> Result<(), String> where I: IntoIterator, String>>, { let mut stdout = std::io::stdout(); - let mut elementor = Elementor::new(); + let mut elementor = Elementor::new().with_error_handling(error_handling); let mut records_count = 0usize; let mut elems_count = 0usize; let mut stats = RecoveryStats::new(report_recovery); diff --git a/src/error.rs b/src/error.rs index dde1b25a..2a6cecfc 100644 --- a/src/error.rs +++ b/src/error.rs @@ -267,8 +267,10 @@ pub enum BgpValidationWarning { PartialAttributeError { attr_type: AttrType, reason: String }, /// Malformed NLRI field (RFC 7606 §5.3). The UPDATE message was parseable /// up to the NLRI section, but the NLRI itself contained syntactic errors. - /// Per RFC 7606, the recommended action is "treat-as-withdrawal": all - /// routes carried in the NLRI section should be withdrawn. + /// Treat-as-withdraw needs the NLRI, so RFC 7606 §3(i) and §5.3 call for a + /// session reset, or AFI/SAFI disable for a multiprotocol attribute whose + /// family is known; see + /// [`error_handling_approach`](BgpValidationWarning::error_handling_approach). /// /// `nlri_type` distinguishes between the standard (IPv4 unicast) NLRI /// field and the multiprotocol NLRI carried inside MP_REACH/MP_UNREACH diff --git a/src/lib.rs b/src/lib.rs index 78408ae7..a5b3836a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -236,6 +236,51 @@ match process_mrt_file("http://example.com/updates.bz2") { } ``` +**RFC 7606 Error Handling (Treat-as-Withdraw)** + +Malformed path attributes never stop parsing: each finding is recorded as a +`BgpValidationWarning` on the UPDATE, and the attribute bytes are kept. RFC 7606 and the RFCs +defining later attributes say what a router does with each finding: discard the attribute, treat +the UPDATE's routes as withdrawn, disable the AFI/SAFI, or reset the session. +`BgpUpdateMessage::error_handling_approach` returns that approach for an UPDATE, combining its +findings with the "strongest action wins" rule. The attribute-to-approach table is +`models::malformed_attribute_approach`. + +MRT data does not say whether a session was iBGP or eBGP. Route collectors peer over eBGP, so the +classification assumes eBGP: a malformed LOCAL_PREF, ORIGINATOR_ID or CLUSTER_LIST is attribute +discard, not treat-as-withdraw. + +Element output is unchanged unless you opt in with `enable_rfc7606_error_handling()`. Then: + +- announcements of an UPDATE that RFC 7606 treats as withdrawn become `ElemType::WITHDRAW`; +- announcements of an UPDATE whose errors call for a session reset or AFI/SAFI disable become + `ElemType::RESET`; +- attributes subject to attribute discard, and repeats of an attribute after its first + occurrence, are left out of the announcement; +- every element of such an UPDATE carries the approach in `BgpElem::error_handling`. + +RIB dump entries are converted as before. The CLI flag is `--rfc7606`. + +The route iterator (`into_route_iter`) stays a cheap, selective parser under this mode: it checks +every attribute header like the element iterators do, but parses only the values of ORIGIN, +AS_PATH, AS4_PATH, MP_REACH_NLRI and MP_UNREACH_NLRI. It can miss a value error in another +attribute, so it may keep routes the element iterators withdraw, never the reverse. + +```no_run +use bgpkit_parser::BgpkitParser; +use bgpkit_parser::models::{ElemType, ErrorHandlingApproach}; + +let parser = BgpkitParser::new("https://data.ris.ripe.net/rrc00/latest-update.gz") + .unwrap() + .enable_rfc7606_error_handling(); +for elem in parser { + if elem.error_handling == Some(ErrorHandlingApproach::TreatAsWithdraw) { + assert_eq!(elem.elem_type, ElemType::WITHDRAW); + println!("treated as withdrawn: {}", elem.prefix); + } +} +``` + **Recovering After Damaged MRT Framing** Recovery is opt-in and never reconstructs a damaged record. It reports the skipped decompressed @@ -755,7 +800,7 @@ See the [BgpElem] documentation for the complete structure definition. **Key fields**: - `timestamp`: Unix timestamp of the BGP message -- `elem_type`: Announcement or withdrawal +- `elem_type`: Announcement, withdrawal, or (with RFC 7606 error handling) reset - `peer_ip` / `peer_asn`: The BGP peer information - `prefix`: The IP prefix being announced or withdrawn - `as_path`: The AS path attribute (if present) @@ -792,6 +837,7 @@ BGPKIT Parser implements comprehensive BGP, MRT, BMP, and related protocol stand - [RFC 4271](https://datatracker.ietf.org/doc/html/rfc4271): A Border Gateway Protocol 4 (BGP-4) - Core protocol - [RFC 2858](https://datatracker.ietf.org/doc/html/rfc2858): Multiprotocol Extensions for BGP-4 (IPv6 support) - [RFC 6793](https://datatracker.ietf.org/doc/html/rfc6793): Four-Octet AS Number Space +- [RFC 7607](https://datatracker.ietf.org/doc/html/rfc7607): Codification of AS 0 Processing - [RFC 7911](https://datatracker.ietf.org/doc/html/rfc7911): Advertisement of Multiple Paths (ADD-PATH) **Additional BGP RFCs**: diff --git a/src/models/bgp/attributes/mod.rs b/src/models/bgp/attributes/mod.rs index 0292daac..edff53e4 100644 --- a/src/models/bgp/attributes/mod.rs +++ b/src/models/bgp/attributes/mod.rs @@ -144,8 +144,25 @@ pub struct Attributes { pub(crate) inner: Vec, /// RFC 7606 validation warnings collected during parsing pub(crate) validation_warnings: Vec, - /// Bitmask of seen attributes to allow O(1) checks. Fits in 4 u64s. - pub(crate) attr_mask: [u64; 4], + /// Attribute type codes present, to allow O(1) checks. + pub(crate) attr_mask: AttrCodeSet, +} + +/// Set of attribute type codes, as a 256-bit mask. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub(crate) struct AttrCodeSet([u64; 4]); + +impl AttrCodeSet { + /// Adds `code`, returning whether it was absent. + pub(crate) fn insert(&mut self, code: u8) -> bool { + let absent = !self.contains(code); + self.0[(code / 64) as usize] |= 1u64 << (code % 64); + absent + } + + pub(crate) fn contains(&self, code: u8) -> bool { + self.0[(code / 64) as usize] & (1u64 << (code % 64)) != 0 + } } impl std::fmt::Debug for Attributes { @@ -159,8 +176,7 @@ impl std::fmt::Debug for Attributes { impl Attributes { pub fn has_attr(&self, ty: AttrType) -> bool { - let attr = u8::from(ty); - (self.attr_mask[(attr / 64) as usize] & (1u64 << (attr % 64))) != 0 + self.attr_mask.contains(u8::from(ty)) } pub fn get_attr(&self, ty: AttrType) -> Option { @@ -171,8 +187,7 @@ impl Attributes { } pub fn add_attr(&mut self, attr: Attribute) { - let ty = attr.value.attr_code(); - self.attr_mask[(ty / 64) as usize] |= 1u64 << (ty % 64); + self.attr_mask.insert(attr.value.attr_code()); self.inner.push(attr); } @@ -433,11 +448,10 @@ impl Iterator for MetaCommunitiesIter<'_> { } } -fn compute_mask(inner: &[Attribute]) -> [u64; 4] { - let mut attr_mask = [0; 4]; +fn compute_mask(inner: &[Attribute]) -> AttrCodeSet { + let mut attr_mask = AttrCodeSet::default(); for attr in inner { - let ty = attr.value.attr_code(); - attr_mask[(ty / 64) as usize] |= 1u64 << (ty % 64); + attr_mask.insert(attr.value.attr_code()); } attr_mask } diff --git a/src/models/bgp/elem.rs b/src/models/bgp/elem.rs index 17c635e4..bcd25514 100644 --- a/src/models/bgp/elem.rs +++ b/src/models/bgp/elem.rs @@ -10,11 +10,15 @@ use std::sync::Arc; /// # ElemType /// -/// `ElemType` is an enumeration that represents the type of an element. -/// It has two possible values: +/// `ElemType` is an enumeration that represents the type of an element: /// /// - `ANNOUNCE`: Indicates an announcement/reachable prefix. /// - `WITHDRAW`: Indicates a withdrawn/unreachable prefix. +/// - `RESET`: A prefix announced in an UPDATE whose errors require a session reset or AFI/SAFI +/// disable under RFC 7606. Only produced when RFC 7606 error handling is enabled; see +/// [`ErrorHandlingMode`]. +/// +/// The enumeration is `#[non_exhaustive]`: match it with a wildcard arm. /// /// The enumeration derives the traits `Debug`, `Clone`, `Copy`, `PartialEq`, `Eq`, and `Hash`. /// @@ -41,9 +45,14 @@ use std::sync::Arc; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", serde(rename = "lowercase"))] +#[non_exhaustive] pub enum ElemType { ANNOUNCE, WITHDRAW, + /// A prefix announced in an UPDATE that RFC 7606 says resets the session (or disables the + /// AFI/SAFI). Such a route is not installed, and the peer's other routes would be lost + /// with the session, which a per-UPDATE element cannot express. + RESET, } impl ElemType { @@ -65,7 +74,7 @@ impl ElemType { pub fn is_announce(&self) -> bool { match self { ElemType::ANNOUNCE => true, - ElemType::WITHDRAW => false, + ElemType::WITHDRAW | ElemType::RESET => false, } } } @@ -93,6 +102,8 @@ impl ElemType { /// - `only_to_customer`: The AS number to which the prefix is only announced. /// - `unknown`: Unknown attributes formatted as (TYPE, RAW_BYTES). /// - `deprecated`: Deprecated attributes formatted as (TYPE, RAW_BYTES). +/// - `error_handling`: The RFC 7606 approach applied to the UPDATE this element came from, when +/// RFC 7606 error handling is enabled and the UPDATE had errors. /// /// Note: Constructing BGP elements consumes more memory due to duplicate information /// shared between multiple elements of one MRT record. @@ -155,6 +166,17 @@ pub struct BgpElem { pub unknown: Option>, /// deprecated attributes formatted as (TYPE, RAW_BYTES) pub deprecated: Option>, + /// The RFC 7606 approach applied to the UPDATE this element came from. + /// + /// Set only when RFC 7606 error handling is enabled (see [`ErrorHandlingMode`]) and the + /// UPDATE had validation findings; `None` otherwise. It tells a withdrawal synthesized by + /// treat-as-withdraw apart from one the peer sent, and marks announcements whose malformed + /// attributes were discarded. It is not part of the PSV output. + #[cfg_attr( + feature = "serde", + serde(default, skip_serializing_if = "Option::is_none") + )] + pub error_handling: Option, } /// Lightweight per-prefix route element. @@ -240,6 +262,7 @@ impl Default for BgpElem { only_to_customer: None, unknown: None, deprecated: None, + error_handling: None, } } } @@ -302,6 +325,7 @@ impl Display for BgpElem { let t = match self.elem_type { ElemType::ANNOUNCE => "A", ElemType::WITHDRAW => "W", + ElemType::RESET => "R", }; write!( f, @@ -329,6 +353,7 @@ impl Display for BgpRouteElem { let t = match self.elem_type { ElemType::ANNOUNCE => "A", ElemType::WITHDRAW => "W", + ElemType::RESET => "R", }; write!( f, @@ -414,6 +439,7 @@ impl BgpElem { let t = match self.elem_type { ElemType::ANNOUNCE => "A", ElemType::WITHDRAW => "W", + ElemType::RESET => "R", }; format!( "{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", diff --git a/src/models/bgp/error_handling.rs b/src/models/bgp/error_handling.rs new file mode 100644 index 00000000..a84daeba --- /dev/null +++ b/src/models/bgp/error_handling.rs @@ -0,0 +1,664 @@ +//! RFC 7606 error-handling approaches and the mapping from malformed path attributes to them. +//! +//! [RFC 7606](https://datatracker.ietf.org/doc/html/rfc7606) replaces the "reset the session on +//! any UPDATE error" rule of RFC 4271 with per-attribute approaches. Later RFCs that define new +//! attributes each name the approach for their own attribute. This module collects those rules +//! in one place: +//! +//! - [`ErrorHandlingApproach`] is the action a compliant speaker takes. +//! - [`malformed_attribute_approach`] is the RFC → attribute table. +//! - [`BgpValidationWarning::error_handling_approach`] classifies one parser finding. +//! - [`Attributes::error_handling_approach`] and +//! [`BgpUpdateMessage::error_handling_approach`] combine the findings of an UPDATE using the +//! "strongest action wins" rule of RFC 7606 §3(h). +//! +//! # Session type +//! +//! RFC 7606 treats a malformed LOCAL_PREF, ORIGINATOR_ID or CLUSTER_LIST differently depending on +//! whether it came from an internal or an external peer. MRT data does not record the session +//! type, and route collectors such as RIPE RIS and RouteViews peer over eBGP, so this module +//! assumes **eBGP** and uses "attribute discard" for those three attributes. + +use crate::error::BgpValidationWarning; +use crate::models::{Afi, AttrCodeSet, AttrType, Attributes, BgpUpdateMessage, ElemType, Safi}; + +/// The action RFC 7606 §2 prescribes for an UPDATE message error. +/// +/// Variants are declared from weakest to strongest, so the derived [`Ord`] implements the +/// RFC 7606 §3(h) rule: when an UPDATE has several errors, the strongest approach applies, and +/// `max()` over the individual approaches gives it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] +#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))] +pub enum ErrorHandlingApproach { + /// Drop the malformed attribute and keep processing the UPDATE. Only allowed for attributes + /// that do not affect route selection or installation. + AttributeDiscard, + /// Treat every route the UPDATE announces as withdrawn. + TreatAsWithdraw, + /// Stop accepting routes of the AFI/SAFI the error concerns. A speaker may instead reset + /// the session. + AfiSafiDisable, + /// Send a NOTIFICATION and reset the session. + SessionReset, +} + +impl ErrorHandlingApproach { + /// Whether the routes the UPDATE announces must not be installed: true for treat-as-withdraw + /// and every stronger approach. + pub fn withdraws_routes(&self) -> bool { + *self >= ErrorHandlingApproach::TreatAsWithdraw + } + + /// The element type of a prefix the UPDATE announces: `ANNOUNCE` for attribute discard, + /// `WITHDRAW` for treat-as-withdraw, `RESET` for AFI/SAFI disable and session reset. + pub(crate) fn announced_elem_type(self) -> ElemType { + match self { + ErrorHandlingApproach::AttributeDiscard => ElemType::ANNOUNCE, + ErrorHandlingApproach::TreatAsWithdraw => ElemType::WITHDRAW, + ErrorHandlingApproach::AfiSafiDisable | ErrorHandlingApproach::SessionReset => { + ElemType::RESET + } + } + } +} + +/// Whether elem conversion applies RFC 7606 error handling. +/// +/// This is `#[non_exhaustive]` so that a later variant can, for example, carry the session type +/// instead of assuming eBGP. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +#[non_exhaustive] +pub enum ErrorHandlingMode { + /// Emit every announcement and withdrawal as encoded, whatever the validation findings. + #[default] + Preserve, + /// Apply the RFC 7606 approach of each UPDATE to its elems; see + /// [`Elementor::with_error_handling`](crate::Elementor::with_error_handling). + Rfc7606, +} + +/// The approach for a malformed path attribute of type `attr_type`, assuming an eBGP session. +/// +/// This is the RFC → attribute table. Codes without an assigned rule, including unknown codes, +/// use treat-as-withdraw, which RFC 7606 §8 names as the preferred approach and the safe default +/// for an attribute that may affect route selection. +pub fn malformed_attribute_approach(attr_type: AttrType) -> ErrorHandlingApproach { + use ErrorHandlingApproach::*; + match attr_type { + // RFC 7606 §7.1: length other than 1 or an undefined value. + AttrType::ORIGIN => TreatAsWithdraw, + // RFC 7606 §7.2: unrecognized segment type, segment overrun or underrun, or a segment + // of zero ASNs. RFC 7607 §2 adds AS 0. + AttrType::AS_PATH => TreatAsWithdraw, + // RFC 7606 §7.3: length other than 4. + AttrType::NEXT_HOP => TreatAsWithdraw, + // RFC 7606 §7.4: length other than 4. + AttrType::MULTI_EXIT_DISCRIMINATOR => TreatAsWithdraw, + // RFC 7606 §7.5: attribute discard from an external peer (treat-as-withdraw from an + // internal peer with a length other than 4). + AttrType::LOCAL_PREFERENCE => AttributeDiscard, + // RFC 7606 §7.6: length other than 0. + AttrType::ATOMIC_AGGREGATE => AttributeDiscard, + // RFC 7606 §7.7: length other than 6 or 8. RFC 7607 §2 adds AS 0. + AttrType::AGGREGATOR => AttributeDiscard, + // RFC 7606 §7.8: length not a non-zero multiple of 4. + AttrType::COMMUNITIES => TreatAsWithdraw, + // RFC 7606 §7.9: attribute discard from an external peer (treat-as-withdraw from an + // internal peer with a length other than 4). + AttrType::ORIGINATOR_ID => AttributeDiscard, + // RFC 7606 §7.10: attribute discard from an external peer (treat-as-withdraw from an + // internal peer with a length that is not a non-zero multiple of 4). + AttrType::CLUSTER_LIST => AttributeDiscard, + // RFC 7606 §7.11 and §5.3: session reset or AFI/SAFI disable. + AttrType::MP_REACHABLE_NLRI => SessionReset, + // RFC 7606 §7.12 and §5.3: session reset or AFI/SAFI disable. + AttrType::MP_UNREACHABLE_NLRI => SessionReset, + // RFC 7606 §7.14: length not a non-zero multiple of 8. + AttrType::EXTENDED_COMMUNITIES => TreatAsWithdraw, + // RFC 6793 §6: a malformed AS4_PATH or AS4_AGGREGATOR is discarded. RFC 7607 §2 adds AS 0. + AttrType::AS4_PATH | AttrType::AS4_AGGREGATOR => AttributeDiscard, + // RFC 6514 §5: treat as withdrawn (SHOULD). + AttrType::PMSI_TUNNEL => TreatAsWithdraw, + // RFC 9012 §13: no valid TLV, or the transitive bit clear. + AttrType::TUNNEL_ENCAPSULATION => TreatAsWithdraw, + // RFC 7606 §7.13: any malformation. + AttrType::TRAFFIC_ENGINEERING => TreatAsWithdraw, + // RFC 7606 §7.15: length not a non-zero multiple of 20. + AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES => TreatAsWithdraw, + // RFC 7311 §3: handled like an unrecognized non-transitive attribute, i.e. ignored. + AttrType::AIGP => AttributeDiscard, + // RFC 9552 §8.2.2: attribute discard. + AttrType::BGP_LS_ATTRIBUTE => AttributeDiscard, + // RFC 8092 §6: length not a non-zero multiple of 12. + AttrType::LARGE_COMMUNITIES => TreatAsWithdraw, + // RFC 8205 §5.2: any syntactic or protocol error. + AttrType::BGPSEC_PATH => TreatAsWithdraw, + // RFC 9234 §6: length other than 4. + AttrType::ONLY_TO_CUSTOMER => TreatAsWithdraw, + // RFC 10039 §4: malformed, or carried with a family other than IPVPN or EVPN. + AttrType::BGP_DOMAIN_PATH => TreatAsWithdraw, + // RFC 9015 §3.2.1: wrong flags, TLV overrun, or a missing Hop TLV or sub-TLV. + AttrType::SFP_ATTRIBUTE => TreatAsWithdraw, + // RFC 9026 §3.1: attribute discard. + AttrType::BFD_DISCRIMINATOR => AttributeDiscard, + // RFC 8669 §6: attribute discard. + AttrType::BGP_PREFIX_SID => AttributeDiscard, + // RFC 9793 §4: attribute discard. + AttrType::BIER => AttributeDiscard, + // RFC 7606 §7.16 (revising RFC 6368 §5): treat-as-withdraw. + AttrType::ATTR_SET => TreatAsWithdraw, + // No rule assigned: RFC 7606 §8 default. + AttrType::RESERVED + | AttrType::PE_DISTINGUISHER_LABELS + | AttrType::DEVELOPMENT + | AttrType::Unknown(_) => TreatAsWithdraw, + } +} + +/// The AFI/SAFI header an MP_REACH_NLRI or MP_UNREACH_NLRI value starts with, when it is long +/// enough to carry one. The header identifies the family even when the rest did not decode. +pub(crate) fn mp_nlri_family(bytes: &[u8]) -> Option<(u16, u8)> { + match bytes { + [afi_hi, afi_lo, safi, ..] => Some((u16::from_be_bytes([*afi_hi, *afi_lo]), *safi)), + _ => None, + } +} + +/// Whether the parser fully decodes MP_REACH_NLRI and MP_UNREACH_NLRI of this family, so that a +/// decode failure means the attribute is malformed rather than unsupported. Other families, +/// such as VPN and FlowSpec, use encodings this parser does not implement. +fn decodes_mp_family(afi: u16, safi: u8) -> bool { + let (Ok(afi), Ok(safi)) = (Afi::try_from(afi), Safi::try_from(safi)) else { + return false; + }; + match afi { + Afi::Ipv4 | Afi::Ipv6 => matches!( + safi, + Safi::Unicast | Safi::Multicast | Safi::UnicastMulticast | Safi::MplsLabel + ), + Afi::LinkState => matches!(safi, Safi::LinkState | Safi::LinkStateVpn), + } +} + +impl BgpValidationWarning { + /// The path attribute this finding concerns, if it concerns a single one. + pub fn attr_type(&self) -> Option { + match self { + BgpValidationWarning::AttributeFlagsError { attr_type, .. } + | BgpValidationWarning::AttributeLengthError { attr_type, .. } + | BgpValidationWarning::MissingWellKnownAttribute { attr_type } + | BgpValidationWarning::OptionalAttributeError { attr_type, .. } + | BgpValidationWarning::DuplicateAttribute { attr_type } + | BgpValidationWarning::PartialAttributeError { attr_type, .. } => Some(*attr_type), + BgpValidationWarning::UnrecognizedWellKnownAttribute { attr_type_code } => { + Some(AttrType::from(*attr_type_code)) + } + BgpValidationWarning::InvalidOriginAttribute { .. } => Some(AttrType::ORIGIN), + BgpValidationWarning::InvalidNextHopAttribute { .. } => Some(AttrType::NEXT_HOP), + BgpValidationWarning::MalformedAsPath { .. } => Some(AttrType::AS_PATH), + BgpValidationWarning::MalformedNlri { nlri_type, .. } => match *nlri_type { + "mp_reach" => Some(AttrType::MP_REACHABLE_NLRI), + "mp_unreach" => Some(AttrType::MP_UNREACHABLE_NLRI), + _ => None, + }, + BgpValidationWarning::InvalidNetworkField { .. } + | BgpValidationWarning::MalformedAttributeList { .. } + | BgpValidationWarning::UnknownRouteRefreshSubtype { .. } + | BgpValidationWarning::InvalidRouteRefreshLength { .. } => None, + } + } + + /// The RFC 7606 approach for this finding on its own, assuming an eBGP session. + /// + /// Returns `None` for findings that are not UPDATE errors (ROUTE-REFRESH findings), and for + /// an MP_REACH_NLRI or MP_UNREACH_NLRI of a family this parser does not decode, whose decode + /// failure says nothing about the attribute. + pub fn error_handling_approach(&self) -> Option { + use ErrorHandlingApproach::*; + // No wildcard arm: a new finding must be classified here. + let approach = match self { + // RFC 7606 §3(c): treat-as-withdraw unless the attribute's own specification says + // otherwise; RFC 7311 §3 covers the AIGP transitive bit. + BgpValidationWarning::AttributeFlagsError { attr_type, .. } => match attr_type { + AttrType::AIGP => AttributeDiscard, + _ => TreatAsWithdraw, + }, + BgpValidationWarning::AttributeLengthError { attr_type, .. } + | BgpValidationWarning::OptionalAttributeError { attr_type, .. } + | BgpValidationWarning::PartialAttributeError { attr_type, .. } => { + malformed_attribute_approach(*attr_type) + } + // RFC 7606 §3(d). + BgpValidationWarning::MissingWellKnownAttribute { .. } => TreatAsWithdraw, + // RFC 4271 §6.3, unchanged by RFC 7606. + BgpValidationWarning::UnrecognizedWellKnownAttribute { .. } => SessionReset, + BgpValidationWarning::InvalidOriginAttribute { .. } + | BgpValidationWarning::InvalidNextHopAttribute { .. } + | BgpValidationWarning::MalformedAsPath { .. } => TreatAsWithdraw, + // RFC 7606 §3(g): a repeated MP_REACH_NLRI or MP_UNREACH_NLRI resets the session; + // any other repeated attribute keeps its first occurrence. + BgpValidationWarning::DuplicateAttribute { attr_type } => match attr_type { + AttrType::MP_REACHABLE_NLRI | AttrType::MP_UNREACHABLE_NLRI => SessionReset, + _ => AttributeDiscard, + }, + // RFC 7606 §3(i) and §5.3: NLRI that cannot be parsed leave nothing to withdraw. + BgpValidationWarning::InvalidNetworkField { .. } => SessionReset, + // RFC 7606 §4: attribute-list framing errors. + BgpValidationWarning::MalformedAttributeList { .. } => TreatAsWithdraw, + BgpValidationWarning::MalformedNlri { + nlri_type, + raw_bytes, + .. + } => match *nlri_type { + "mp_reach" | "mp_unreach" => match mp_nlri_family(raw_bytes) { + // RFC 7606 §5.3 and §7.11: the AFI/SAFI header is readable, so the + // speaker may disable just that family. + Some((afi, safi)) if decodes_mp_family(afi, safi) => AfiSafiDisable, + Some(_) => return None, + None => SessionReset, + }, + _ => SessionReset, + }, + BgpValidationWarning::UnknownRouteRefreshSubtype { .. } + | BgpValidationWarning::InvalidRouteRefreshLength { .. } => return None, + }; + Some(approach) + } +} + +/// The strongest approach across `warnings`, per RFC 7606 §3(h). +fn strongest_approach<'a>( + warnings: impl IntoIterator, +) -> Option { + warnings + .into_iter() + .filter_map(BgpValidationWarning::error_handling_approach) + .max() +} + +/// The RFC 7606 approach for a whole UPDATE with these findings: the strongest one (§3(h)), +/// escalated to session reset when the UPDATE carries path attributes other than MP_UNREACH_NLRI +/// but no reachable NLRI, which leaves nothing to treat as withdrawn (§5.2). +/// +/// Both [`BgpUpdateMessage::error_handling_approach`] and the route iterator judge UPDATEs with +/// this, so the two agree on the same findings. +pub(crate) fn update_approach<'a>( + warnings: impl IntoIterator, + has_reachable_nlri: bool, + has_attrs_other_than_mp_unreach: bool, +) -> Option { + let approach = strongest_approach(warnings)?; + if !has_reachable_nlri && has_attrs_other_than_mp_unreach && approach.withdraws_routes() { + Some(ErrorHandlingApproach::SessionReset) + } else { + Some(approach) + } +} + +/// The attributes RFC 7606 attribute discard removes, given an UPDATE's findings: every +/// occurrence of an attribute with a finding, and the second and later occurrences of a +/// repeated attribute (RFC 7606 §3(g)). Findings only ever concern the first occurrence; see +/// `AttributeValidationState::is_repeat`. +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct DiscardPlan { + pub(crate) drop_all: AttrCodeSet, + pub(crate) keep_first: AttrCodeSet, +} + +impl DiscardPlan { + pub(crate) fn from_warnings<'a>( + warnings: impl IntoIterator, + ) -> Self { + let mut plan = DiscardPlan::default(); + for warning in warnings { + let Some(attr_type) = warning.attr_type() else { + continue; + }; + match warning { + BgpValidationWarning::DuplicateAttribute { .. } => { + plan.keep_first.insert(u8::from(attr_type)); + } + _ => { + plan.drop_all.insert(u8::from(attr_type)); + } + } + } + plan + } + + /// Whether the attribute with `code`, seen before iff `seen` is true, survives. + pub(crate) fn keeps(&self, code: u8, seen: bool) -> bool { + !self.drop_all.contains(code) && !(seen && self.keep_first.contains(code)) + } + + /// Applies the plan to `attributes`, in wire order. + pub(crate) fn apply(&self, attributes: &mut Attributes) { + let mut seen = AttrCodeSet::default(); + attributes.inner.retain(|attribute| { + let code = attribute.value.attr_code(); + let first = seen.insert(code); + self.keeps(code, !first) + }); + } +} + +impl Attributes { + /// The strongest RFC 7606 approach across this attribute set's validation findings, or + /// `None` when there are no UPDATE-relevant findings. See the + /// [module documentation](crate::models::error_handling) for the eBGP assumption. + /// + /// This does not apply the RFC 7606 §5.2 rule for UPDATEs without reachable NLRI; use + /// [`BgpUpdateMessage::error_handling_approach`] for a whole UPDATE. + pub fn error_handling_approach(&self) -> Option { + strongest_approach(&self.validation_warnings) + } + + /// Whether any attribute other than MP_UNREACH_NLRI is present. + pub(crate) fn has_attrs_other_than_mp_unreach(&self) -> bool { + self.inner + .iter() + .any(|attribute| attribute.value.attr_type() != AttrType::MP_UNREACHABLE_NLRI) + } +} + +impl BgpUpdateMessage { + /// The RFC 7606 approach a compliant eBGP speaker applies to this UPDATE, or `None` when + /// the UPDATE has no UPDATE-relevant validation findings. + /// + /// This is the strongest approach across the findings (RFC 7606 §3(h)), escalated to + /// session reset when the UPDATE carries attributes but no reachable NLRI (§5.2). + pub fn error_handling_approach(&self) -> Option { + let has_reachable_nlri = !self.announced_prefixes.is_empty() + || self.attributes.has_attr(AttrType::MP_REACHABLE_NLRI); + update_approach( + &self.attributes.validation_warnings, + has_reachable_nlri, + self.attributes.has_attrs_other_than_mp_unreach(), + ) + } + + /// Whether RFC 7606 forbids installing the routes this UPDATE announces: true when its + /// approach is treat-as-withdraw or stronger. + pub fn is_treat_as_withdraw(&self) -> bool { + self.error_handling_approach() + .is_some_and(|approach| approach.withdraws_routes()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::models::{AttributeValue, NetworkPrefix, Origin}; + use std::str::FromStr; + use ErrorHandlingApproach::*; + + #[test] + fn approaches_order_from_weakest_to_strongest() { + assert!(AttributeDiscard < TreatAsWithdraw); + assert!(TreatAsWithdraw < AfiSafiDisable); + assert!(AfiSafiDisable < SessionReset); + assert!(!AttributeDiscard.withdraws_routes()); + assert!(TreatAsWithdraw.withdraws_routes()); + assert!(SessionReset.withdraws_routes()); + } + + #[test] + fn table_matches_the_rfcs() { + let expected = [ + (AttrType::ORIGIN, TreatAsWithdraw), + (AttrType::AS_PATH, TreatAsWithdraw), + (AttrType::NEXT_HOP, TreatAsWithdraw), + (AttrType::MULTI_EXIT_DISCRIMINATOR, TreatAsWithdraw), + (AttrType::LOCAL_PREFERENCE, AttributeDiscard), + (AttrType::ATOMIC_AGGREGATE, AttributeDiscard), + (AttrType::AGGREGATOR, AttributeDiscard), + (AttrType::COMMUNITIES, TreatAsWithdraw), + (AttrType::ORIGINATOR_ID, AttributeDiscard), + (AttrType::CLUSTER_LIST, AttributeDiscard), + (AttrType::MP_REACHABLE_NLRI, SessionReset), + (AttrType::MP_UNREACHABLE_NLRI, SessionReset), + (AttrType::EXTENDED_COMMUNITIES, TreatAsWithdraw), + (AttrType::AS4_PATH, AttributeDiscard), + (AttrType::AS4_AGGREGATOR, AttributeDiscard), + (AttrType::PMSI_TUNNEL, TreatAsWithdraw), + (AttrType::TUNNEL_ENCAPSULATION, TreatAsWithdraw), + (AttrType::TRAFFIC_ENGINEERING, TreatAsWithdraw), + ( + AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES, + TreatAsWithdraw, + ), + (AttrType::AIGP, AttributeDiscard), + (AttrType::PE_DISTINGUISHER_LABELS, TreatAsWithdraw), + (AttrType::BGP_LS_ATTRIBUTE, AttributeDiscard), + (AttrType::LARGE_COMMUNITIES, TreatAsWithdraw), + (AttrType::BGPSEC_PATH, TreatAsWithdraw), + (AttrType::ONLY_TO_CUSTOMER, TreatAsWithdraw), + (AttrType::BGP_DOMAIN_PATH, TreatAsWithdraw), + (AttrType::SFP_ATTRIBUTE, TreatAsWithdraw), + (AttrType::BFD_DISCRIMINATOR, AttributeDiscard), + (AttrType::BGP_PREFIX_SID, AttributeDiscard), + (AttrType::BIER, AttributeDiscard), + (AttrType::ATTR_SET, TreatAsWithdraw), + (AttrType::Unknown(200), TreatAsWithdraw), + ]; + for (attr_type, approach) in expected { + assert_eq!( + malformed_attribute_approach(attr_type), + approach, + "{attr_type:?}" + ); + } + } + + fn mp_nlri_warning(nlri_type: &'static str, raw_bytes: Vec) -> BgpValidationWarning { + BgpValidationWarning::MalformedNlri { + nlri_type, + reason: "test".to_string(), + raw_bytes, + } + } + + #[test] + fn warnings_classify_per_rfc_7606() { + let cases = [ + ( + BgpValidationWarning::AttributeFlagsError { + attr_type: AttrType::COMMUNITIES, + expected_flags: 0xc0, + actual_flags: 0x40, + }, + Some(TreatAsWithdraw), + ), + ( + BgpValidationWarning::AttributeFlagsError { + attr_type: AttrType::AIGP, + expected_flags: 0x80, + actual_flags: 0xc0, + }, + Some(AttributeDiscard), + ), + ( + BgpValidationWarning::AttributeLengthError { + attr_type: AttrType::ATOMIC_AGGREGATE, + expected_length: Some(0), + actual_length: 1, + }, + Some(AttributeDiscard), + ), + ( + BgpValidationWarning::OptionalAttributeError { + attr_type: AttrType::ONLY_TO_CUSTOMER, + reason: String::new(), + }, + Some(TreatAsWithdraw), + ), + ( + BgpValidationWarning::MissingWellKnownAttribute { + attr_type: AttrType::ORIGIN, + }, + Some(TreatAsWithdraw), + ), + ( + BgpValidationWarning::UnrecognizedWellKnownAttribute { + attr_type_code: 200, + }, + Some(SessionReset), + ), + ( + BgpValidationWarning::InvalidOriginAttribute { value: 3 }, + Some(TreatAsWithdraw), + ), + ( + BgpValidationWarning::DuplicateAttribute { + attr_type: AttrType::COMMUNITIES, + }, + Some(AttributeDiscard), + ), + ( + BgpValidationWarning::DuplicateAttribute { + attr_type: AttrType::MP_REACHABLE_NLRI, + }, + Some(SessionReset), + ), + ( + BgpValidationWarning::MalformedAttributeList { + reason: String::new(), + }, + Some(TreatAsWithdraw), + ), + (mp_nlri_warning("announced", vec![0xff]), Some(SessionReset)), + (mp_nlri_warning("withdrawn", vec![0xff]), Some(SessionReset)), + // IPv6 unicast: decoded by the parser, so the family can be disabled + ( + mp_nlri_warning("mp_reach", vec![0x00, 0x02, 0x01, 0x10]), + Some(AfiSafiDisable), + ), + // header too short to name a family + ( + mp_nlri_warning("mp_unreach", vec![0x00, 0x02]), + Some(SessionReset), + ), + // IPv4 MPLS VPN: not decoded by the parser, so no verdict + ( + mp_nlri_warning("mp_reach", vec![0x00, 0x01, 0x80, 0x0c]), + None, + ), + ( + BgpValidationWarning::UnknownRouteRefreshSubtype { subtype: 9 }, + None, + ), + ]; + for (warning, approach) in cases { + assert_eq!(warning.error_handling_approach(), approach, "{warning:?}"); + } + } + + fn update_with( + attributes: Vec, + warnings: Vec, + announced: &[&str], + ) -> BgpUpdateMessage { + let mut attrs = Attributes::default(); + for value in attributes { + attrs.add_attr(value.into()); + } + for warning in warnings { + attrs.add_validation_warning(warning); + } + BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes: attrs, + announced_prefixes: announced + .iter() + .map(|p| NetworkPrefix::from_str(p).unwrap()) + .collect(), + } + } + + #[test] + fn strongest_finding_wins() { + let update = update_with( + vec![AttributeValue::Origin(Origin::IGP)], + vec![ + BgpValidationWarning::AttributeLengthError { + attr_type: AttrType::ATOMIC_AGGREGATE, + expected_length: Some(0), + actual_length: 1, + }, + BgpValidationWarning::OptionalAttributeError { + attr_type: AttrType::COMMUNITIES, + reason: String::new(), + }, + ], + &["10.0.0.0/24"], + ); + assert_eq!(update.error_handling_approach(), Some(TreatAsWithdraw)); + assert!(update.is_treat_as_withdraw()); + } + + #[test] + fn clean_update_has_no_approach() { + let update = update_with( + vec![AttributeValue::Origin(Origin::IGP)], + vec![], + &["10.0.0.0/24"], + ); + assert_eq!(update.error_handling_approach(), None); + assert!(!update.is_treat_as_withdraw()); + } + + #[test] + fn attribute_discard_does_not_withdraw() { + let update = update_with( + vec![AttributeValue::Origin(Origin::IGP)], + vec![BgpValidationWarning::DuplicateAttribute { + attr_type: AttrType::COMMUNITIES, + }], + &["10.0.0.0/24"], + ); + assert_eq!(update.error_handling_approach(), Some(AttributeDiscard)); + assert!(!update.is_treat_as_withdraw()); + } + + #[test] + fn missing_nlri_escalates_to_session_reset() { + // RFC 7606 §5.2: attributes but no reachable NLRI, and a treat-as-withdraw error + let update = update_with( + vec![AttributeValue::Origin(Origin::IGP)], + vec![BgpValidationWarning::InvalidOriginAttribute { value: 3 }], + &[], + ); + assert_eq!(update.error_handling_approach(), Some(SessionReset)); + + // attribute discard is not escalated + let update = update_with( + vec![AttributeValue::Origin(Origin::IGP)], + vec![BgpValidationWarning::DuplicateAttribute { + attr_type: AttrType::COMMUNITIES, + }], + &[], + ); + assert_eq!(update.error_handling_approach(), Some(AttributeDiscard)); + } + + #[test] + fn discard_plan_keeps_first_duplicate_and_drops_malformed() { + let plan = DiscardPlan::from_warnings(&[ + BgpValidationWarning::DuplicateAttribute { + attr_type: AttrType::COMMUNITIES, + }, + BgpValidationWarning::AttributeLengthError { + attr_type: AttrType::ATOMIC_AGGREGATE, + expected_length: Some(0), + actual_length: 1, + }, + ]); + assert!(plan.keeps(8, false)); + assert!(!plan.keeps(8, true)); + assert!(!plan.keeps(6, false)); + assert!(plan.keeps(1, false)); + assert!(plan.keeps(1, true)); + } +} diff --git a/src/models/bgp/mod.rs b/src/models/bgp/mod.rs index 868462d2..dc08a64a 100644 --- a/src/models/bgp/mod.rs +++ b/src/models/bgp/mod.rs @@ -5,6 +5,7 @@ pub mod capabilities; pub mod community; pub mod elem; pub mod error; +pub mod error_handling; pub mod flowspec; pub mod linkstate; pub mod role; @@ -14,6 +15,7 @@ pub use attributes::*; pub use community::*; pub use elem::*; pub use error::*; +pub use error_handling::*; pub use flowspec::*; pub use linkstate::*; pub use role::*; diff --git a/src/parser/bgp/attributes/README.md b/src/parser/bgp/attributes/README.md index 808ec9d5..ace4a15b 100644 --- a/src/parser/bgp/attributes/README.md +++ b/src/parser/bgp/attributes/README.md @@ -37,6 +37,71 @@ | PE_DISTINGUISHER_LABELS | [RFC6514][rfc6514] | 27 | Raw-retained | Structured parser not implemented | | BGPSEC_PATH | [RFC8205][rfc8205] | 33 | Raw-retained | Structured parser not implemented | +## Error Handling (RFC 7606) + +When an attribute is malformed, RFC 7606 and the RFC defining the attribute name the approach a +router takes: **discard** the attribute, **treat-as-withdraw** (TAW) every route in the UPDATE, or +**reset** the session (or disable the AFI/SAFI). `malformed_attribute_approach` in +`src/models/bgp/error_handling.rs` encodes this table; `BgpUpdateMessage::error_handling_approach` +combines an UPDATE's findings, and `BgpkitParser::enable_rfc7606_error_handling` applies the result +to elements. The route iterator checks every attribute header but parses only the values of ORIGIN, +AS_PATH, AS4_PATH, MP_REACH_NLRI and MP_UNREACH_NLRI, so it can miss value errors in other +attributes. + +MRT data does not record the session type, so the table assumes **eBGP**, which is how route +collectors peer. Three attributes would be treat-as-withdraw from an iBGP peer instead. + +| Path Attribute | Code | Malformed when | Approach (eBGP) | Reference | +|----------------------------|-------|-----------------------------------------------------|----------------------|---------------------------------------------| +| ORIGIN | 1 | length ≠ 1, or undefined value | TAW | [RFC7606 §7.1][rfc7606] | +| AS_PATH | 2 | bad segment type or length, empty segment, AS 0 | TAW | [RFC7606 §7.2][rfc7606], [RFC7607][rfc7607] | +| NEXT_HOP | 3 | length ≠ 4 | TAW | [RFC7606 §7.3][rfc7606] | +| MULTI_EXIT_DISC | 4 | length ≠ 4 | TAW | [RFC7606 §7.4][rfc7606] | +| LOCAL_PREF | 5 | length ≠ 4 | Discard (iBGP: TAW) | [RFC7606 §7.5][rfc7606] | +| ATOMIC_AGGREGATE | 6 | length ≠ 0 | Discard | [RFC7606 §7.6][rfc7606] | +| AGGREGATOR | 7 | length ≠ 6 or 8, AS 0 | Discard | [RFC7606 §7.7][rfc7606], [RFC7607][rfc7607] | +| COMMUNITIES | 8 | length not a non-zero multiple of 4 | TAW | [RFC7606 §7.8][rfc7606] | +| ORIGINATOR_ID | 9 | length ≠ 4 | Discard (iBGP: TAW) | [RFC7606 §7.9][rfc7606] | +| CLUSTER_LIST | 10 | length not a non-zero multiple of 4 | Discard (iBGP: TAW) | [RFC7606 §7.10][rfc7606] | +| MP_REACH_NLRI | 14 | length < 5, bad next-hop length, bad NLRI | AFI/SAFI disable | [RFC7606 §7.11, §5.3][rfc7606] | +| MP_UNREACH_NLRI | 15 | length < 3, bad NLRI | AFI/SAFI disable | [RFC7606 §7.12, §5.3][rfc7606] | +| EXTENDED_COMMUNITIES | 16 | length not a non-zero multiple of 8 | TAW | [RFC7606 §7.14][rfc7606] | +| AS4_PATH | 17 | malformed, AS 0 | Discard | [RFC6793 §6][rfc6793], [RFC7607][rfc7607] | +| AS4_AGGREGATOR | 18 | length ≠ 8, AS 0 | Discard | [RFC6793 §6][rfc6793], [RFC7607][rfc7607] | +| PMSI_TUNNEL | 22 | undefined tunnel type, bad identifier | TAW (SHOULD) | [RFC6514 §5][rfc6514] | +| Tunnel Encapsulation | 23 | no valid TLV, transitive bit clear | TAW | [RFC9012 §13][rfc9012] | +| Traffic Engineering | 24 | any malformation | TAW | [RFC7606 §7.13][rfc7606] | +| IPv6 Ext. Community | 25 | length not a non-zero multiple of 20 | TAW | [RFC7606 §7.15][rfc7606] | +| AIGP | 26 | malformed, transitive bit set | Discard | [RFC7311 §3][rfc7311] | +| BGP-LS Attribute | 29 | malformed | Discard | [RFC9552][rfc9552] | +| LARGE_COMMUNITY | 32 | length not a non-zero multiple of 12 | TAW | [RFC8092 §6][rfc8092] | +| BGPsec_PATH | 33 | syntactic or protocol error | TAW | [RFC8205 §5.2][rfc8205] | +| Only to Customer | 35 | length ≠ 4 | TAW | [RFC9234 §6][rfc9234] | +| D-PATH | 36 | malformed, or not on IPVPN/EVPN routes | TAW | [RFC10039 §4][rfc10039] | +| SFP Attribute | 37 | wrong flags, TLV overrun, missing Hop TLV | TAW | [RFC9015 §3.2.1][rfc9015] | +| BFD Discriminator | 38 | length < 11, bad optional TLV | Discard | [RFC9026][rfc9026] | +| BGP Prefix-SID | 40 | TLV length errors | Discard | [RFC8669 §6][rfc8669] | +| BIER | 41 | TLV lengths do not add up | Discard | [RFC9793 §4][rfc9793] | +| ATTR_SET | 128 | malformed | TAW | [RFC7606 §7.16][rfc7606] | +| any other code | – | – | TAW | [RFC7606 §8][rfc7606] | + +Rules that are not tied to one attribute: + +| Condition | Approach | Reference | +|------------------------------------------------------------------|-----------------------------|------------------------------| +| Optional or transitive flag conflicts with the attribute type | TAW (AIGP: discard) | [RFC7606 §3(c)][rfc7606] | +| Missing well-known mandatory attribute | TAW | [RFC7606 §3(d)][rfc7606] | +| Attribute runs past the attribute list, or 1–2 trailing bytes | TAW | [RFC7606 §4][rfc7606] | +| Repeated MP_REACH_NLRI or MP_UNREACH_NLRI | Session reset | [RFC7606 §3(g)][rfc7606] | +| Any other repeated attribute | Discard all but the first | [RFC7606 §3(g)][rfc7606] | +| Unrecognized attribute with the optional bit clear | Session reset | [RFC4271 §6.3][rfc4271] | +| Malformed NLRI or withdrawn routes field | Session reset | [RFC7606 §3(i), §5.3][rfc7606] | +| Attributes but no reachable NLRI, with any error beyond discard | Session reset | [RFC7606 §5.2][rfc7606] | +| Several errors in one UPDATE | The strongest approach | [RFC7606 §3(h)][rfc7606] | + +An MP_REACH_NLRI or MP_UNREACH_NLRI of a family this parser does not decode, such as VPN or +FlowSpec, gets no verdict when it fails to decode: the failure says nothing about the attribute. + **Legend:** - **Raw-retained**: Attribute value bytes are preserved as `AttributeValue::Raw(AttrRaw)` and can be re-encoded, but no structured parser exists yet. - **Model only**: Data structures exist but structured parser/encoder is incomplete. @@ -51,6 +116,9 @@ [rfc5701]: https://datatracker.ietf.org/doc/html/rfc5701 [rfc6368]: https://datatracker.ietf.org/doc/html/rfc6368 [rfc6514]: https://datatracker.ietf.org/doc/html/rfc6514 +[rfc6793]: https://datatracker.ietf.org/doc/html/rfc6793 +[rfc7606]: https://datatracker.ietf.org/doc/html/rfc7606 +[rfc7607]: https://datatracker.ietf.org/doc/html/rfc7607 [rfc7311]: https://datatracker.ietf.org/doc/html/rfc7311 [rfc8092]: https://datatracker.ietf.org/doc/html/rfc8092 [rfc8205]: https://datatracker.ietf.org/doc/html/rfc8205 @@ -60,6 +128,7 @@ [rfc9015]: https://datatracker.ietf.org/doc/html/rfc9015 [rfc9026]: https://datatracker.ietf.org/doc/html/rfc9026 [rfc9234]: https://datatracker.ietf.org/doc/html/rfc9234 +[rfc9552]: https://datatracker.ietf.org/doc/html/rfc9552 [rfc9793]: https://datatracker.ietf.org/doc/html/rfc9793 [rfc10039]: https://datatracker.ietf.org/doc/html/rfc10039 [iana-bgp]: https://www.iana.org/assignments/bgp-parameters/bgp-parameters.xhtml diff --git a/src/parser/bgp/attributes/mod.rs b/src/parser/bgp/attributes/mod.rs index 20cee34e..ebeea74e 100644 --- a/src/parser/bgp/attributes/mod.rs +++ b/src/parser/bgp/attributes/mod.rs @@ -22,14 +22,15 @@ mod attr_40_bgp_prefix_sid; mod attr_41_bier; use bytes::{Buf, BufMut, Bytes, BytesMut}; -use log::{debug, warn}; +use log::debug; use std::net::IpAddr; use crate::models::*; use crate::encoder::sink::{with_u16_len, with_u8_len}; use crate::error::{BgpValidationWarning, EncodingError, ParserError}; -use crate::parser::bgp::attributes::attr_01_origin::{encode_origin, parse_origin}; +use crate::parser::bgp::attributes::attr_01_origin::encode_origin; +pub(crate) use crate::parser::bgp::attributes::attr_01_origin::parse_origin; use crate::parser::bgp::attributes::attr_02_17_as_path::encode_as_path; pub(crate) use crate::parser::bgp::attributes::attr_02_17_as_path::parse_as_path; use crate::parser::bgp::attributes::attr_03_next_hop::{encode_next_hop, parse_next_hop}; @@ -157,37 +158,31 @@ fn is_raw_retained_attr(attr_type: AttrType) -> bool { ) } -/// Check if an attribute type is well-known mandatory -fn is_well_known_mandatory(attr_type: AttrType) -> bool { - matches!( - attr_type, - AttrType::ORIGIN | AttrType::AS_PATH | AttrType::NEXT_HOP | AttrType::LOCAL_PREFERENCE - ) -} - pub(crate) struct AttributeValidationState { warnings: Vec, - attr_mask: [u64; 4], + attr_mask: AttrCodeSet, + /// Whether the attribute last passed to [`observe_header`](Self::observe_header) repeats an + /// earlier one. + repeat: bool, } impl AttributeValidationState { pub(crate) fn new() -> Self { Self { warnings: Vec::new(), - attr_mask: [0; 4], + attr_mask: AttrCodeSet::default(), + repeat: false, } } - fn has_raw_attr(&self, attr: u8) -> bool { - (self.attr_mask[(attr / 64) as usize] & (1u64 << (attr % 64))) != 0 - } - pub(crate) fn has_attr(&self, attr_type: AttrType) -> bool { - self.has_raw_attr(u8::from(attr_type)) + self.attr_mask.contains(u8::from(attr_type)) } - fn set_attr(&mut self, attr: u8) { - self.attr_mask[(attr / 64) as usize] |= 1u64 << (attr % 64); + /// Whether the current attribute repeats an earlier one. RFC 7606 §3(g) discards every + /// repeat, so the `observe_*` methods record no finding about it. + pub(crate) fn is_repeat(&self) -> bool { + self.repeat } pub(crate) fn observe_header( @@ -197,11 +192,24 @@ impl AttributeValidationState { flags: AttrFlags, length: usize, ) -> bool { - if self.has_raw_attr(raw_attr_type) { + self.repeat = !self.attr_mask.insert(raw_attr_type); + if self.repeat { self.warnings .push(BgpValidationWarning::DuplicateAttribute { attr_type }); + return flags.contains(AttrFlags::PARTIAL); + } + + // RFC 4271 §6.3: an attribute this parser does not recognize must be optional. A + // deprecated code point is recognized, so it is not reported here. + if matches!(attr_type, AttrType::Unknown(_)) + && get_deprecated_attr_type(raw_attr_type).is_none() + && !flags.contains(AttrFlags::OPTIONAL) + { + self.warnings + .push(BgpValidationWarning::UnrecognizedWellKnownAttribute { + attr_type_code: raw_attr_type, + }); } - self.set_attr(raw_attr_type); validate_attribute_flags(attr_type, flags, &mut self.warnings); validate_attribute_length(attr_type, length, &mut self.warnings); @@ -209,39 +217,142 @@ impl AttributeValidationState { flags.contains(AttrFlags::PARTIAL) } + /// RFC 7606 §4: an attribute whose length runs past the end of the attribute list. + pub(crate) fn observe_attribute_overrun( + &mut self, + attr_type: AttrType, + attr_length: usize, + remaining: usize, + ) { + debug!( + "{attr_type:?} attribute encodes a length ({attr_length}) that is longer than the remaining attribute data ({remaining}); skipping the rest of the attribute list" + ); + self.warnings + .push(BgpValidationWarning::MalformedAttributeList { + reason: format!( + "{attr_type:?} attribute length {attr_length} exceeds the {remaining} bytes left in the attribute list (RFC 7606 §4)" + ), + }); + } + + /// RFC 7606 §4: one or two bytes left at the end of the attribute list, too few for an + /// attribute header. + pub(crate) fn observe_trailing_bytes(&mut self, remaining: usize) { + if remaining == 0 { + return; + } + debug!("{remaining} trailing bytes after the last path attribute"); + self.warnings + .push(BgpValidationWarning::MalformedAttributeList { + reason: format!( + "{remaining} trailing bytes after the last path attribute, too few for an attribute header (RFC 7606 §4)" + ), + }); + } + + /// Record why an attribute value failed to parse. `raw_bytes` is the attribute value. pub(crate) fn observe_parse_error( &mut self, attr_type: AttrType, partial: bool, error: &ParserError, + raw_bytes: &[u8], ) { - if partial { - self.warnings - .push(BgpValidationWarning::PartialAttributeError { - attr_type, - reason: error.to_string(), + if self.repeat { + return; + } + let reason = error.to_string(); + match attr_type { + // RFC 7606 §5.3: the error handling of MP_REACH_NLRI and MP_UNREACH_NLRI follows + // from the family their AFI/SAFI header names. + AttrType::MP_REACHABLE_NLRI | AttrType::MP_UNREACHABLE_NLRI => { + debug!("{attr_type:?} attribute parsing failed: {reason}"); + self.warnings.push(BgpValidationWarning::MalformedNlri { + nlri_type: if attr_type == AttrType::MP_REACHABLE_NLRI { + "mp_reach" + } else { + "mp_unreach" + }, + reason, + raw_bytes: raw_bytes.to_vec(), }); - debug!("PARTIAL attribute error: {}", error); - } else if is_well_known_mandatory(attr_type) { + } + _ if partial => { + debug!("PARTIAL attribute error: {reason}"); + self.warnings + .push(BgpValidationWarning::PartialAttributeError { attr_type, reason }); + } + AttrType::ORIGIN => { + debug!("ORIGIN attribute parsing failed: {reason}"); + // A wrong length is already reported by the length check. + if let [value] = raw_bytes { + self.warnings + .push(BgpValidationWarning::InvalidOriginAttribute { value: *value }); + } + } + AttrType::AS_PATH => { + debug!("AS_PATH attribute parsing failed: {reason}"); + self.warnings + .push(BgpValidationWarning::MalformedAsPath { reason }); + } + AttrType::NEXT_HOP => { + debug!("NEXT_HOP attribute parsing failed: {reason}"); + self.warnings + .push(BgpValidationWarning::InvalidNextHopAttribute { reason }); + } + _ => { + debug!("{attr_type:?} attribute parsing failed: {reason}"); + self.warnings + .push(BgpValidationWarning::OptionalAttributeError { attr_type, reason }); + } + } + } + + /// Checks on values that parsed but are still malformed: RFC 7607 AS 0, and RFC 7606 §7.2 + /// AS_PATH segments without ASNs. The typed value is kept, so output that does not apply + /// RFC 7606 error handling is unchanged. + pub(crate) fn observe_value(&mut self, value: &AttributeValue) { + if self.repeat { + return; + } + match value { + AttributeValue::AsPath(path) => self.observe_as_path(path), + AttributeValue::As4Path(path) => self.observe_as4_path(path), + AttributeValue::Aggregator { asn, .. } | AttributeValue::As4Aggregator { asn, .. } + if asn.to_u32() == 0 => + { + self.warnings + .push(BgpValidationWarning::OptionalAttributeError { + attr_type: value.attr_type(), + reason: "aggregator AS 0 (RFC 7607 §2)".to_string(), + }); + } + _ => {} + } + } + + /// RFC 7606 §7.2 and RFC 7607 §2 checks on a parsed AS_PATH. + pub(crate) fn observe_as_path(&mut self, path: &AsPath) { + if self.repeat { + return; + } + if let Some(reason) = as_path_problem(path) { self.warnings - .push(BgpValidationWarning::MalformedAttributeList { - reason: format!( - "Well-known mandatory attribute {} parsing failed: {}", - u8::from(attr_type), - error - ), - }); - debug!( - "Well-known mandatory attribute parsing failed, treating as withdraw: {}", - error - ); - } else { + .push(BgpValidationWarning::MalformedAsPath { reason }); + } + } + + /// RFC 7607 §2 and empty-segment checks on a parsed AS4_PATH, which RFC 6793 §6 discards. + pub(crate) fn observe_as4_path(&mut self, path: &AsPath) { + if self.repeat { + return; + } + if let Some(reason) = as_path_problem(path) { self.warnings .push(BgpValidationWarning::OptionalAttributeError { - attr_type, - reason: error.to_string(), + attr_type: AttrType::AS4_PATH, + reason, }); - debug!("Optional attribute error, discarding: {}", error); } } @@ -277,48 +388,94 @@ impl AttributeValidationState { } } - pub(crate) fn finish(self) -> (Vec, [u64; 4]) { + pub(crate) fn finish(self) -> (Vec, AttrCodeSet) { (self.warnings, self.attr_mask) } } +/// An AS path that parsed but is malformed: a segment without ASNs (RFC 7606 §7.2), or AS 0 +/// (RFC 7607 §2). +fn as_path_problem(path: &AsPath) -> Option { + if path.segments.iter().any(AsPathSegment::is_empty) { + return Some("AS path segment without AS numbers (RFC 7606 §7.2)".to_string()); + } + if path + .segments + .iter() + .any(|segment| segment.iter().any(|asn| asn.to_u32() == 0)) + { + return Some("AS path contains AS 0 (RFC 7607 §2)".to_string()); + } + None +} + +/// Length constraint on an attribute value, from RFC 7606 §7 and the RFCs defining later +/// attributes. +enum LengthRule { + Exactly(usize), + OneOf(&'static [usize]), + NonZeroMultipleOf(usize), + AtLeast(usize), + Any, +} + +impl LengthRule { + fn for_attr(attr_type: AttrType) -> Self { + match attr_type { + // RFC 7606 §7.1, §7.3, §7.4, §7.5, §7.6, §7.9 + AttrType::ORIGIN => LengthRule::Exactly(1), + AttrType::NEXT_HOP => LengthRule::Exactly(4), // IPv4 next hop + AttrType::MULTI_EXIT_DISCRIMINATOR => LengthRule::Exactly(4), + AttrType::LOCAL_PREFERENCE => LengthRule::Exactly(4), + AttrType::ATOMIC_AGGREGATE => LengthRule::Exactly(0), + AttrType::ORIGINATOR_ID => LengthRule::Exactly(4), + // RFC 9234 §6 + AttrType::ONLY_TO_CUSTOMER => LengthRule::Exactly(4), + // RFC 6793 §6 + AttrType::AS4_AGGREGATOR => LengthRule::Exactly(8), + // RFC 7606 §7.7: 6 with 2-octet ASNs, 8 with 4-octet ASNs + AttrType::AGGREGATOR => LengthRule::OneOf(&[6, 8]), + // RFC 7606 §7.8, §7.10, §7.14, §7.15; RFC 8092 §6 + AttrType::COMMUNITIES | AttrType::CLUSTER_LIST => LengthRule::NonZeroMultipleOf(4), + AttrType::EXTENDED_COMMUNITIES => LengthRule::NonZeroMultipleOf(8), + AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES => { + LengthRule::NonZeroMultipleOf(20) + } + AttrType::LARGE_COMMUNITIES => LengthRule::NonZeroMultipleOf(12), + // RFC 7606 §5.3 + AttrType::MP_REACHABLE_NLRI => LengthRule::AtLeast(5), + AttrType::MP_UNREACHABLE_NLRI => LengthRule::AtLeast(3), + _ => LengthRule::Any, + } + } + + fn allows(&self, length: usize) -> bool { + match self { + LengthRule::Exactly(expected) => length == *expected, + LengthRule::OneOf(allowed) => allowed.contains(&length), + LengthRule::NonZeroMultipleOf(unit) => length != 0 && length.is_multiple_of(*unit), + LengthRule::AtLeast(min) => length >= *min, + LengthRule::Any => true, + } + } +} + /// Validate attribute length constraints fn validate_attribute_length( attr_type: AttrType, length: usize, warnings: &mut Vec, ) { - let expected_length = match attr_type { - AttrType::ORIGIN => Some(1), - AttrType::NEXT_HOP => Some(4), // IPv4 next hop - AttrType::MULTI_EXIT_DISCRIMINATOR => Some(4), - AttrType::LOCAL_PREFERENCE => Some(4), - AttrType::ATOMIC_AGGREGATE => Some(0), - AttrType::ORIGINATOR_ID => Some(4), - AttrType::ONLY_TO_CUSTOMER => Some(4), - // Variable length attributes - no fixed constraint - AttrType::AS_PATH - | AttrType::AS4_PATH - | AttrType::AGGREGATOR - | AttrType::AS4_AGGREGATOR - | AttrType::COMMUNITIES - | AttrType::EXTENDED_COMMUNITIES - | AttrType::IPV6_ADDRESS_SPECIFIC_EXTENDED_COMMUNITIES - | AttrType::LARGE_COMMUNITIES - | AttrType::CLUSTER_LIST - | AttrType::MP_REACHABLE_NLRI - | AttrType::MP_UNREACHABLE_NLRI => None, - _ => None, // Unknown attributes - }; - - if let Some(expected) = expected_length { - if length != expected { - warnings.push(BgpValidationWarning::AttributeLengthError { - attr_type, - expected_length: Some(expected), - actual_length: length, - }); - } + let rule = LengthRule::for_attr(attr_type); + if !rule.allows(length) { + warnings.push(BgpValidationWarning::AttributeLengthError { + attr_type, + expected_length: match rule { + LengthRule::Exactly(expected) => Some(expected), + _ => None, + }, + actual_length: length, + }); } } @@ -328,15 +485,6 @@ fn is_domain_path_family(afi: u16, safi: u8) -> bool { matches!((afi, safi), (1 | 2, 128) | (25, 70)) } -/// The AFI/SAFI header an MP_REACH_NLRI attribute value starts with, when it is long enough to -/// carry one. The header identifies the family even when the rest did not decode. -fn mp_reach_family(bytes: &[u8]) -> Option<(u16, u8)> { - match bytes.len() >= 3 { - true => Some((u16::from_be_bytes([bytes[0], bytes[1]]), bytes[2])), - false => None, - } -} - /// The route families a D-PATH-carrying message carries, as far as the caller can tell. #[derive(Debug, Clone, Copy, Default)] struct DomainPathFamilies { @@ -367,7 +515,7 @@ impl DomainPathFamilies { AttributeValue::Raw(raw) | AttributeValue::Unknown(raw) if raw.code == u8::from(AttrType::MP_REACHABLE_NLRI) => { - mp_reach_family(&raw.bytes) + mp_nlri_family(&raw.bytes) } _ => None, }) @@ -453,6 +601,7 @@ pub fn parse_attributes( // A handle on the whole attribute section, so an attribute that fails to parse can be kept // raw by re-slicing it, without cloning every attribute's bytes up front. let section = data.clone(); + let mut overrun = false; while data.remaining() >= 3 { // each attribute is at least 3 bytes: flag(1) + type(1) + length(1) @@ -477,12 +626,10 @@ pub fn parse_attributes( let bytes_left = data.remaining(); - if data.remaining() < attr_length { - warn!( - "{:?} attribute encodes a length ({}) that is longer than the remaining attribute data ({}). Skipping remaining attribute data for BGP message", - attr_type, attr_length, bytes_left - ); + if bytes_left < attr_length { + validation.observe_attribute_overrun(attr_type, attr_length, bytes_left); // break and return already parsed attributes + overrun = true; break; } @@ -583,10 +730,16 @@ pub fn parse_attributes( match attr { Ok(value) => { assert_eq!(attr_type, value.attr_type()); + validation.observe_value(&value); attributes.push(Attribute { value, flag }); } Err(e) => { - validation.observe_parse_error(attr_type, partial, &e); + validation.observe_parse_error( + attr_type, + partial, + &e, + §ion.slice(value_start..value_start + attr_length), + ); attributes.push(Attribute { value: AttributeValue::Raw(AttrRaw { code: raw_code, @@ -599,6 +752,10 @@ pub fn parse_attributes( }; } + if !overrun { + validation.observe_trailing_bytes(data.remaining()); + } + let (mut validation_warnings, attr_mask) = validation.finish(); if attributes .iter() @@ -1315,4 +1472,155 @@ mod tests { other => panic!("expected As4Aggregator variant, got {other:?}"), } } + + fn warnings_for(wire: &[u8]) -> Vec { + parse_attributes( + Bytes::from(wire.to_vec()), + &AsnLength::Bits32, + false, + None, + None, + None, + ) + .expect("attribute list must parse") + .validation_warnings + } + + fn has_length_error(warnings: &[BgpValidationWarning], expected: AttrType) -> bool { + warnings.iter().any(|w| { + matches!(w, BgpValidationWarning::AttributeLengthError { attr_type, .. } if *attr_type == expected) + }) + } + + #[test] + fn test_rfc7606_length_rules() { + // COMMUNITIES of 6 bytes: not a multiple of 4 + let warnings = warnings_for(&[0xc0, 0x08, 0x06, 0, 0, 0, 1, 0, 2]); + assert!(has_length_error(&warnings, AttrType::COMMUNITIES)); + // AGGREGATOR of 7 bytes: neither 6 nor 8 + let warnings = warnings_for(&[0xc0, 0x07, 0x07, 0, 0, 0, 1, 10, 0, 0]); + assert!(has_length_error(&warnings, AttrType::AGGREGATOR)); + // ATOMIC_AGGREGATE with a value byte + let warnings = warnings_for(&[0x40, 0x06, 0x01, 0x00]); + assert!(has_length_error(&warnings, AttrType::ATOMIC_AGGREGATE)); + // MP_UNREACH_NLRI shorter than its AFI/SAFI header + let warnings = warnings_for(&[0x80, 0x0f, 0x02, 0x00, 0x02]); + assert!(has_length_error(&warnings, AttrType::MP_UNREACHABLE_NLRI)); + // LARGE_COMMUNITIES of zero length + let warnings = warnings_for(&[0xc0, 0x20, 0x00]); + assert!(has_length_error(&warnings, AttrType::LARGE_COMMUNITIES)); + // well-formed values raise nothing + let warnings = warnings_for(&[ + 0xc0, 0x08, 0x04, 0, 0, 0, 1, // COMMUNITIES + 0xc0, 0x07, 0x08, 0, 0, 0, 1, 10, 0, 0, 1, // AGGREGATOR, 4-octet AS + 0x40, 0x06, 0x00, // ATOMIC_AGGREGATE + ]); + assert!(warnings.is_empty(), "{warnings:?}"); + } + + #[test] + fn test_rfc7606_attribute_overrun_is_recorded() { + // ORIGIN, then an attribute header claiming 100 bytes with 1 left + let warnings = warnings_for(&[0x40, 0x01, 0x01, 0x00, 0xc0, 0x08, 0x64, 0x00]); + assert!(warnings + .iter() + .any(|w| matches!(w, BgpValidationWarning::MalformedAttributeList { .. }))); + } + + #[test] + fn test_rfc7606_trailing_bytes_are_recorded() { + let warnings = warnings_for(&[0x40, 0x01, 0x01, 0x00, 0x40, 0x02]); + assert!(warnings + .iter() + .any(|w| matches!(w, BgpValidationWarning::MalformedAttributeList { .. }))); + } + + #[test] + fn test_unrecognized_well_known_attribute() { + // unknown type 200 without the OPTIONAL bit + let warnings = warnings_for(&[0x40, 0xc8, 0x00]); + assert!( + warnings.contains(&BgpValidationWarning::UnrecognizedWellKnownAttribute { + attr_type_code: 200 + }) + ); + // the same code marked optional is fine + assert!(warnings_for(&[0xc0, 0xc8, 0x00]).is_empty()); + // a deprecated code point is recognized + assert!(warnings_for(&[0x40, 0x0b, 0x00]).is_empty()); + } + + #[test] + fn test_specific_variants_for_mandatory_attributes() { + let warnings = warnings_for(&[0x40, 0x01, 0x01, 0x03]); + assert!(warnings.contains(&BgpValidationWarning::InvalidOriginAttribute { value: 3 })); + + // segment type 9 does not exist + let warnings = warnings_for(&[0x40, 0x02, 0x06, 0x09, 0x01, 0, 0, 0, 1]); + assert!(warnings + .iter() + .any(|w| matches!(w, BgpValidationWarning::MalformedAsPath { .. }))); + + let warnings = warnings_for(&[0x40, 0x03, 0x03, 192, 0, 2]); + assert!(warnings + .iter() + .any(|w| matches!(w, BgpValidationWarning::InvalidNextHopAttribute { .. }))); + assert!(has_length_error(&warnings, AttrType::NEXT_HOP)); + } + + #[test] + fn test_malformed_mp_reach_reports_malformed_nlri() { + // IPv6 unicast MP_REACH whose next-hop length (3) is not a valid length + let wire = [ + 0x80, 0x0e, 0x08, 0x00, 0x02, 0x01, 0x03, 0xaa, 0xbb, 0xcc, 0x00, + ]; + let warnings = warnings_for(&wire); + let found = warnings.iter().find_map(|w| match w { + BgpValidationWarning::MalformedNlri { + nlri_type, + raw_bytes, + .. + } => Some((*nlri_type, raw_bytes.clone())), + _ => None, + }); + assert_eq!(found, Some(("mp_reach", wire[3..].to_vec()))); + } + + #[test] + fn test_as_zero_and_empty_segments_keep_the_typed_value() { + // AS_SEQUENCE [0] + let attributes = parse_attributes( + Bytes::from_static(&[0x40, 0x02, 0x06, 0x02, 0x01, 0, 0, 0, 0]), + &AsnLength::Bits32, + false, + None, + None, + None, + ) + .unwrap(); + assert!(matches!( + attributes.inner[0].value, + AttributeValue::AsPath(_) + )); + assert!(attributes + .validation_warnings + .iter() + .any(|w| matches!(w, BgpValidationWarning::MalformedAsPath { reason } if reason.contains("AS 0")))); + + // an AS_SEQUENCE without ASNs + let warnings = warnings_for(&[0x40, 0x02, 0x02, 0x02, 0x00]); + assert!(warnings + .iter() + .any(|w| matches!(w, BgpValidationWarning::MalformedAsPath { reason } if reason.contains("without")))); + + // AGGREGATOR with AS 0 + let warnings = warnings_for(&[0xc0, 0x07, 0x08, 0, 0, 0, 0, 10, 0, 0, 1]); + assert!(warnings.iter().any(|w| matches!( + w, + BgpValidationWarning::OptionalAttributeError { + attr_type: AttrType::AGGREGATOR, + .. + } + ))); + } } diff --git a/src/parser/filter.rs b/src/parser/filter.rs index 2fed6252..fee520d7 100644 --- a/src/parser/filter.rs +++ b/src/parser/filter.rs @@ -13,7 +13,7 @@ The available filters are: - `peer_ips` -- peers' IP addresses (OR logic) - `peer_asn` -- peer's AS number - `peer_asns` -- multiple peer AS numbers (OR logic) -- `type` -- message type (`withdraw` or `announce`) +- `type` -- message type (`withdraw`, `announce`, or `reset`) - `ts_start` -- start and end unix timestamp - `as_path` -- regular expression for AS path string - `ip_version` -- IP version (`ipv4` or `ipv6`) @@ -141,7 +141,8 @@ use std::str::FromStr; /// - `peer_ips` (`PeerIps(Vec)`) -- peers' IP addresses (OR logic) /// - `peer_asn` (`PeerAsn(u32)`) -- peer's AS number /// - `peer_asns` (`PeerAsns(Vec)`) -- multiple peer AS numbers (OR logic) -/// - `type` (`Type(ElemType)`) -- message type (`withdraw` or `announce`) +/// - `type` (`Type(ElemType)`) -- message type (`withdraw`, `announce`, or `reset`; `reset` +/// elems only appear with RFC 7606 error handling enabled) /// - `ts_start` (`TsStart(f64)`) and `ts_end` (`TsEnd(f64)`) -- start and end unix timestamp /// - `as_path` (`ComparableRegex`) -- regular expression for AS path string /// - `community` (`ComparableRegex`) -- regular expression for community string @@ -544,6 +545,7 @@ impl Filter { "type" => match filter_value { "w" | "withdraw" | "withdrawal" => Ok(Filter::Type(ElemType::WITHDRAW)), "a" | "announce" | "announcement" => Ok(Filter::Type(ElemType::ANNOUNCE)), + "r" | "reset" => Ok(Filter::Type(ElemType::RESET)), _ => Err(FilterError(format!( "cannot parse elem type from {filter_value}" ))), @@ -997,6 +999,7 @@ mod tests { unknown: None, elem_type: ElemType::ANNOUNCE, deprecated: None, + error_handling: None, } } @@ -1338,6 +1341,9 @@ mod tests { let filter = Filter::new("type", "w").unwrap(); assert_eq!(filter, Filter::Type(ElemType::WITHDRAW)); + let filter = Filter::new("type", "reset").unwrap(); + assert_eq!(filter, Filter::Type(ElemType::RESET)); + let filter = Filter::new("ts_start", "1637437798").unwrap(); assert_eq!(filter, Filter::TsStart(1637437798_f64)); @@ -1594,6 +1600,7 @@ mod tests { unknown: None, elem_type: ElemType::ANNOUNCE, deprecated: None, + error_handling: None, }; // Test negated origin_asn filter (using value-based negation: origin_asn=!12345) @@ -2044,6 +2051,7 @@ mod tests { unknown: None, elem_type: ElemType::ANNOUNCE, deprecated: None, + error_handling: None, }; // Test OriginAsns with OR logic - element has origin ASN 12345 @@ -2096,6 +2104,7 @@ mod tests { unknown: None, elem_type: ElemType::ANNOUNCE, deprecated: None, + error_handling: None, } } diff --git a/src/parser/iters/default.rs b/src/parser/iters/default.rs index 5159976e..e249141e 100644 --- a/src/parser/iters/default.rs +++ b/src/parser/iters/default.rs @@ -20,10 +20,11 @@ pub struct RecordIterator { impl RecordIterator { pub(crate) fn new(parser: BgpkitParser) -> Self { + let elementor = parser.options.elementor(); RecordIterator { parser, count: 0, - elementor: Elementor::new(), + elementor, } } } @@ -71,11 +72,12 @@ pub struct ElemIterator { impl ElemIterator { pub(crate) fn new(parser: BgpkitParser) -> Self { + let elementor = parser.options.elementor(); ElemIterator { record_iter: RecordIterator::new(parser), count: 0, pending: PendingElems::Empty, - elementor: Elementor::new(), + elementor, } } } diff --git a/src/parser/iters/diagnostic.rs b/src/parser/iters/diagnostic.rs index 981f594a..fa7e23cc 100644 --- a/src/parser/iters/diagnostic.rs +++ b/src/parser/iters/diagnostic.rs @@ -808,7 +808,12 @@ mod tests { invalid_origin[3] = 3; assert_wire_validation( bgp4mp_update_wire(&[], &invalid_origin, &announced), - |warning| matches!(warning, BgpValidationWarning::MalformedAttributeList { .. }), + |warning| { + matches!( + warning, + BgpValidationWarning::InvalidOriginAttribute { value: 3 } + ) + }, ); let malformed_as_path = vec![ @@ -818,7 +823,7 @@ mod tests { ]; assert_wire_validation( bgp4mp_update_wire(&[], &malformed_as_path, &announced), - |warning| matches!(warning, BgpValidationWarning::MalformedAttributeList { .. }), + |warning| matches!(warning, BgpValidationWarning::MalformedAsPath { .. }), ); let invalid_next_hop = vec![ @@ -959,8 +964,8 @@ mod tests { #[test] fn with_dissection_anchors_duplicate_to_second_occurrence() { - // Two ORIGIN attributes: the duplicate warning and its companion - // flags warning both belong to the SECOND occurrence. + // Two ORIGIN attributes: the duplicate warning belongs to the SECOND + // occurrence. let mut attrs = Vec::new(); attrs.extend_from_slice(&[0x40, 0x01, 0x01, 0x00]); // first, clean attrs.extend_from_slice(&[0x80, 0x01, 0x01, 0x00]); // duplicate, bad flags @@ -983,13 +988,12 @@ mod tests { // NTH-occurrence anchoring: the duplicate points at #2 assert_eq!(duplicate.span, origins[1].span()); - // The flags error accompanying the duplicate header must - // also anchor to the second occurrence, not the first. - let flags = warnings - .iter() - .find(|w| matches!(w.warning, BgpValidationWarning::AttributeFlagsError { .. })) - .expect("flags warning"); - assert_eq!(flags.span, origins[1].span()); + // RFC 7606 §3(g) discards the repeat, so its bad flags are + // not reported against the valid first ORIGIN. + assert!(!warnings.iter().any(|w| matches!( + w.warning, + BgpValidationWarning::AttributeFlagsError { .. } + ))); } event => panic!("expected dissected record event, got {event:?}"), } diff --git a/src/parser/iters/fallible.rs b/src/parser/iters/fallible.rs index 6d347a56..31badefa 100644 --- a/src/parser/iters/fallible.rs +++ b/src/parser/iters/fallible.rs @@ -24,9 +24,10 @@ pub struct FallibleRecordIterator { impl FallibleRecordIterator { pub(crate) fn new(parser: BgpkitParser) -> Self { + let elementor = parser.options.elementor(); FallibleRecordIterator { parser, - elementor: Elementor::new(), + elementor, finished: false, } } @@ -88,10 +89,11 @@ pub struct FallibleElemIterator { impl FallibleElemIterator { pub(crate) fn new(parser: BgpkitParser) -> Self { + let elementor = parser.options.elementor(); FallibleElemIterator { record_iter: FallibleRecordIterator::new(parser), cache_elems: vec![], - elementor: Elementor::new(), + elementor, } } } diff --git a/src/parser/iters/mod.rs b/src/parser/iters/mod.rs index 61f5ffcf..b467f855 100644 --- a/src/parser/iters/mod.rs +++ b/src/parser/iters/mod.rs @@ -336,6 +336,12 @@ impl BgpkitParser { /// AS path. Use [`into_elem_iter`](Self::into_elem_iter) when you need /// the full [`BgpElem`] attribute set. Filters that only depend on route /// fields are supported; `community` filters do not match route elements. + /// + /// With [RFC 7606 error handling](Self::enable_rfc7606_error_handling), the route iterator + /// checks every attribute header like the element iterators do, but parses only the values + /// of ORIGIN, AS_PATH, AS4_PATH, MP_REACH_NLRI and MP_UNREACH_NLRI. A value error in any + /// other attribute, such as a truncated D-PATH, goes unnoticed: the route iterator may keep + /// routes the element iterators withdraw, never the reverse. pub fn into_route_iter(self) -> RouteIterator { RouteIterator::new(self) } @@ -494,6 +500,7 @@ impl BgpkitParser { where R: Read, { + let mode = self.options.error_handling; let mut raw_iter = RawRecordIterator::new(self).peekable(); let elementor = match raw_iter.peek().cloned().and_then(|r| r.parse().ok()) { Some(MrtRecord { @@ -501,9 +508,9 @@ impl BgpkitParser { .. }) => { raw_iter.next(); - Elementor::with_peer_table(pit) + Elementor::with_peer_table(pit).with_error_handling(mode) } - _ => Elementor::new(), + _ => Elementor::new().with_error_handling(mode), }; (elementor, raw_iter) } @@ -520,6 +527,7 @@ impl BgpkitParser { where R: Read, { + let mode = self.options.error_handling; let mut record_iter = RecordIterator::new(self).peekable(); let elementor = match record_iter.peek().cloned() { Some(MrtRecord { @@ -527,9 +535,9 @@ impl BgpkitParser { .. }) => { record_iter.next(); - Elementor::with_peer_table(pit) + Elementor::with_peer_table(pit).with_error_handling(mode) } - _ => Elementor::new(), + _ => Elementor::new().with_error_handling(mode), }; (elementor, record_iter) } diff --git a/src/parser/iters/raw.rs b/src/parser/iters/raw.rs index 06c7ceeb..53c6f2b0 100644 --- a/src/parser/iters/raw.rs +++ b/src/parser/iters/raw.rs @@ -81,10 +81,11 @@ pub struct FilteredRawRecordIterator { impl FilteredRawRecordIterator { pub(crate) fn new(parser: BgpkitParser) -> Self { + let elementor = parser.options.elementor(); let filters = parser.filters.clone(); FilteredRawRecordIterator { inner: RawRecordIterator::new(parser), - elementor: Elementor::new(), + elementor, filters, } } diff --git a/src/parser/iters/recovery.rs b/src/parser/iters/recovery.rs index c839217f..b2059494 100644 --- a/src/parser/iters/recovery.rs +++ b/src/parser/iters/recovery.rs @@ -169,6 +169,7 @@ pub struct RecoveringRecordIterator { impl RecoveringRecordIterator { pub(crate) fn new(parser: BgpkitParser, config: RecoveryConfig) -> Self { + let elementor = parser.options.elementor(); let unsupported_input = parser.text_dump_iter.is_some().then(|| { "text-dump parsers have no MRT record representation; iterate elements instead" .to_string() @@ -177,7 +178,7 @@ impl RecoveringRecordIterator { reader: CarryoverReader::new(parser.reader), config, filters: parser.filters, - elementor: Elementor::new(), + elementor, options: parser.options, core_dump: parser.core_dump, unsupported_input, @@ -344,12 +345,13 @@ pub struct RecoveringElemIterator { impl RecoveringElemIterator { pub(crate) fn new(mut parser: BgpkitParser, config: RecoveryConfig) -> Self { + let elementor = parser.options.elementor(); // Elements are filtered here; strip the parser filters so the inner record // iterator does not also convert every record for record-level matching. let filters = std::mem::take(&mut parser.filters); Self { inner: RecoveringRecordIterator::new(parser, config), - elementor: Elementor::new(), + elementor, filters, cache_elems: Vec::new(), } diff --git a/src/parser/iters/route.rs b/src/parser/iters/route.rs index 2c58265d..9d30d3a5 100644 --- a/src/parser/iters/route.rs +++ b/src/parser/iters/route.rs @@ -1,6 +1,8 @@ use crate::error::{ParserError, ParserErrorWithBytes}; use crate::models::*; -use crate::parser::bgp::attributes::{parse_as_path, parse_nlri, AttributeValidationState}; +use crate::parser::bgp::attributes::{ + parse_as_path, parse_nlri, parse_origin, AttributeValidationState, +}; use crate::parser::bgp::messages::read_and_validate_bgp_marker; use crate::parser::iters::{handle_record_parse_error, write_mrt_core_dump}; use crate::parser::mrt::messages::bgp4mp::{bgp4mp_message_payload_len, is_short_zebra_open}; @@ -24,6 +26,8 @@ struct RouteAttributes { as_path: Option>, announced: Vec, withdrawn: Vec, + /// RFC 7606 approach, when the attributes were judged. + approach: Option, } struct RouteAttributeContext<'a> { @@ -32,6 +36,8 @@ struct RouteAttributeContext<'a> { prefixes: Option<&'a [NetworkPrefix]>, is_announcement: Option, has_standard_nlri: bool, + /// Judge the attributes for RFC 7606 error handling; see [`parse_route_attributes`]. + judge: bool, } fn merge_as_path(as_path: Option, as4_path: Option) -> Option> { @@ -43,17 +49,29 @@ fn merge_as_path(as_path: Option, as4_path: Option) -> Option, ) -> Result { + let judge = ctx.judge; let mut validation = AttributeValidationState::new(); let mut as_path = None; let mut as4_path = None; let mut announced = Vec::new(); let mut withdrawn = Vec::new(); + let mut overrun = false; + let mut has_attrs_other_than_mp_unreach = false; while data.remaining() >= 3 { let flags = AttrFlags::from_bits_retain(data.read_u8()?); @@ -64,24 +82,51 @@ fn parse_route_attributes( data.read_u8()? as usize }; let attr_type = AttrType::from(raw_attr_type); - let partial = validation.observe_header(raw_attr_type, attr_type, flags, attr_length); + has_attrs_other_than_mp_unreach |= attr_type != AttrType::MP_UNREACHABLE_NLRI; + let partial = + judge && validation.observe_header(raw_attr_type, attr_type, flags, attr_length); if data.remaining() < attr_length { - warn!( - "{:?} attribute encodes a length ({}) that is longer than the remaining attribute data ({}). Skipping remaining attribute data for BGP message", - attr_type, - attr_length, - data.remaining() - ); + if judge { + validation.observe_attribute_overrun(attr_type, attr_length, data.remaining()); + } else { + warn!( + "{:?} attribute encodes a length ({}) that is longer than the remaining attribute data ({}). Skipping remaining attribute data for BGP message", + attr_type, + attr_length, + data.remaining() + ); + } + overrun = true; break; } let attr_data = data.split_to(attr_length); + // RFC 7606 §3(g): a repeated attribute is discarded, as the element iterators do + if judge && validation.is_repeat() { + continue; + } + // findings on these attributes carry their bytes; cloning `Bytes` is a refcount bump + let raw_bytes = (judge + && matches!( + attr_type, + AttrType::ORIGIN | AttrType::MP_REACHABLE_NLRI | AttrType::MP_UNREACHABLE_NLRI + )) + .then(|| attr_data.clone()); let result = match attr_type { + // ORIGIN's value is cheap to check; the header length rules cover the other + // fixed-size attributes + AttrType::ORIGIN if judge => parse_origin(attr_data).map(|_| ()), AttrType::AS_PATH => parse_as_path(attr_data, asn_len).map(|path| { + if judge { + validation.observe_as_path(&path); + } as_path = Some(path); }), AttrType::AS4_PATH => parse_as_path(attr_data, &AsnLength::Bits32).map(|path| { + if judge { + validation.observe_as4_path(&path); + } as4_path = Some(path); }), AttrType::MP_REACHABLE_NLRI => parse_nlri( @@ -113,20 +158,44 @@ fn parse_route_attributes( _ => Ok(()), }; - if let Err(err) = result { - validation.observe_parse_error(attr_type, partial, &err); + if let (true, Err(err)) = (judge, result) { + validation.observe_parse_error( + attr_type, + partial, + &err, + raw_bytes.as_deref().unwrap_or_default(), + ); + } + } + + let mut approach = None; + if judge { + if !overrun { + validation.observe_trailing_bytes(data.remaining()); + } + let has_mp_reach = validation.has_attr(AttrType::MP_REACHABLE_NLRI); + let is_announcement = ctx + .is_announcement + .unwrap_or(ctx.has_standard_nlri || has_mp_reach); + validation.check_mandatory_attributes(is_announcement, ctx.has_standard_nlri); + let (warnings, _) = validation.finish(); + approach = update_approach( + &warnings, + ctx.has_standard_nlri || has_mp_reach, + has_attrs_other_than_mp_unreach, + ); + // attribute discard, as the element iterators apply it; repeats were skipped above. + // Only AS4_PATH matters here: any other finding on the attributes above withdraws. + if !DiscardPlan::from_warnings(&warnings).keeps(u8::from(AttrType::AS4_PATH), false) { + as4_path = None; } } - let is_announcement = ctx - .is_announcement - .unwrap_or(ctx.has_standard_nlri || validation.has_attr(AttrType::MP_REACHABLE_NLRI)); - validation.check_mandatory_attributes(is_announcement, ctx.has_standard_nlri); - let _warnings = validation.finish(); Ok(RouteAttributes { as_path: merge_as_path(as_path, as4_path), announced, withdrawn, + approach, }) } @@ -147,6 +216,9 @@ struct RouteUpdateIter { withdrawn: std::iter::Chain, std::vec::IntoIter>, in_withdrawn_phase: bool, + /// `ANNOUNCE`, or `WITHDRAW` / `RESET` when RFC 7606 error handling withdrew the + /// announcements, in which case `as_path` is empty. + announced_as: ElemType, } impl RouteUpdateIter { @@ -155,7 +227,7 @@ impl RouteUpdateIter { if let Some(prefix) = self.announced.next() { return Some(BgpRouteElem { timestamp: self.timestamp, - elem_type: ElemType::ANNOUNCE, + elem_type: self.announced_as, peer_ip: self.peer_ip, peer_asn: self.peer_asn, prefix, @@ -277,6 +349,7 @@ impl RouteTableDumpIter { prefixes: None, is_announcement: Some(true), has_standard_nlri: self.afi == Afi::Ipv4, + judge: false, }, )?; @@ -340,6 +413,7 @@ impl RouteRibAfiIter { prefixes: Some(&prefixes), is_announcement: Some(true), has_standard_nlri: self.afi == Afi::Ipv4, + judge: false, }, )?; let Some(peer) = self.peer_table.get_peer_by_id(peer_index) else { @@ -361,6 +435,22 @@ impl RouteRibAfiIter { } } +/// Under RFC 7606 error handling, NLRI that do not parse are a session reset (RFC 7606 §3(i), +/// §5.3) instead of a fatal error, as in the UPDATE parser. +fn nlri_or_reset( + result: Result, ParserError>, + judge: bool, + reset: &mut bool, +) -> Result, ParserError> { + match result { + Err(_) if judge => { + *reset = true; + Ok(Vec::new()) + } + result => result, + } +} + fn parse_bgp_update_routes( mut input: Bytes, add_path: bool, @@ -368,15 +458,27 @@ fn parse_bgp_update_routes( timestamp: f64, peer_ip: IpAddr, peer_asn: Asn, + mode: ErrorHandlingMode, ) -> Result { + let judge = mode == ErrorHandlingMode::Rfc7606; + let mut malformed_nlri = false; let withdrawn_len = input.read_u16()? as usize; input.has_n_remaining(withdrawn_len)?; - let withdrawn_prefixes = parse_nlri_list(input.split_to(withdrawn_len), add_path, &Afi::Ipv4)?; + let withdrawn_prefixes = nlri_or_reset( + parse_nlri_list(input.split_to(withdrawn_len), add_path, &Afi::Ipv4), + judge, + &mut malformed_nlri, + )?; let attribute_length = input.read_u16()? as usize; input.has_n_remaining(attribute_length)?; let attribute_bytes = input.split_to(attribute_length); - let announced_prefixes = parse_nlri_list(input, add_path, &Afi::Ipv4)?; + let announced_bytes_present = !input.is_empty(); + let announced_prefixes = nlri_or_reset( + parse_nlri_list(input, add_path, &Afi::Ipv4), + judge, + &mut malformed_nlri, + )?; let attributes = parse_route_attributes( attribute_bytes, asn_len, @@ -386,21 +488,54 @@ fn parse_bgp_update_routes( safi: None, prefixes: None, is_announcement: None, - has_standard_nlri: !announced_prefixes.is_empty(), + // judged like the UPDATE parser: NLRI bytes that fail to parse still announce + has_standard_nlri: if judge { + announced_bytes_present + } else { + !announced_prefixes.is_empty() + }, + judge, }, )?; + let approach = match malformed_nlri { + true => Some(ErrorHandlingApproach::SessionReset), + false => attributes.approach, + }; + let announced_as = approach.map_or( + ElemType::ANNOUNCE, + ErrorHandlingApproach::announced_elem_type, + ); + Ok(RouteUpdateIter { timestamp, peer_ip, peer_asn, - as_path: attributes.as_path, + as_path: match announced_as { + ElemType::ANNOUNCE => attributes.as_path, + _ => None, + }, announced: announced_prefixes.into_iter().chain(attributes.announced), withdrawn: withdrawn_prefixes.into_iter().chain(attributes.withdrawn), in_withdrawn_phase: false, + announced_as, }) } +fn parse_update_routes( + msg_data: Bytes, + add_path: bool, + asn_len: &AsnLength, + timestamp: f64, + peer_ip: IpAddr, + peer_asn: Asn, + mode: ErrorHandlingMode, +) -> Result { + Ok(RouteRecordIter::Update(parse_bgp_update_routes( + msg_data, add_path, asn_len, timestamp, peer_ip, peer_asn, mode, + )?)) +} + fn parse_bgp_message_routes( mut data: Bytes, add_path: bool, @@ -408,6 +543,7 @@ fn parse_bgp_message_routes( timestamp: f64, peer_ip: IpAddr, peer_asn: Asn, + mode: ErrorHandlingMode, ) -> Result { let total_size = data.len(); data.has_n_remaining(19)?; @@ -444,9 +580,9 @@ fn parse_bgp_message_routes( let msg_data = data.split_to(bgp_msg_length); match msg_type { - BgpMessageType::UPDATE => Ok(RouteRecordIter::Update(parse_bgp_update_routes( - msg_data, add_path, asn_len, timestamp, peer_ip, peer_asn, - )?)), + BgpMessageType::UPDATE => parse_update_routes( + msg_data, add_path, asn_len, timestamp, peer_ip, peer_asn, mode, + ), BgpMessageType::OPEN | BgpMessageType::NOTIFICATION | BgpMessageType::KEEPALIVE @@ -472,6 +608,7 @@ fn parse_bgp4mp_routes( sub_type: u16, mut data: Bytes, timestamp: f64, + mode: ErrorHandlingMode, ) -> Result { let msg_type = Bgp4MpType::try_from(sub_type)?; let Some((asn_len, add_path)) = bgp4mp_asn_len_and_add_path(msg_type) else { @@ -490,6 +627,7 @@ fn parse_bgp4mp_routes( timestamp, IpAddr::V4(Ipv4Addr::UNSPECIFIED), peer_asn, + mode, ); } let _interface_index = data.read_u16()?; @@ -506,7 +644,7 @@ fn parse_bgp4mp_routes( ))); } - parse_bgp_message_routes(data, add_path, &asn_len, timestamp, peer_ip, peer_asn) + parse_bgp_message_routes(data, add_path, &asn_len, timestamp, peer_ip, peer_asn, mode) } fn table_dump_v2_afi_safi(rib_type: TableDumpV2Type) -> Result<(Afi, Safi), ParserError> { @@ -564,6 +702,7 @@ fn parse_legacy_bgp_routes( sub_type: u16, mut data: Bytes, timestamp: f64, + mode: ErrorHandlingMode, ) -> Result { match sub_type { BGP_UPDATE => { @@ -571,14 +710,15 @@ fn parse_legacy_bgp_routes( let peer_ip = IpAddr::V4(data.read_ipv4_address()?); let _local_asn = data.read_u16()?; let _local_ip = data.read_ipv4_address()?; - Ok(RouteRecordIter::Update(parse_bgp_update_routes( + parse_update_routes( data, false, &AsnLength::Bits16, timestamp, peer_ip, peer_asn, - )?)) + mode, + ) } BGP_STATE_CHANGE | BGP_OPEN | BGP_NOTIFY | BGP_KEEPALIVE => { parse_legacy_bgp(sub_type, data)?; @@ -633,6 +773,7 @@ fn parse_table_dump_v2_routes( fn parse_raw_record_route_iter( raw_record: crate::RawMrtRecord, peer_table: &mut Option, + mode: ErrorHandlingMode, ) -> Result { let timestamp = record_timestamp(&raw_record.common_header); match raw_record.common_header.entry_type { @@ -649,11 +790,13 @@ fn parse_raw_record_route_iter( raw_record.common_header.entry_subtype, raw_record.message_bytes, timestamp, + mode, ), EntryType::BGP => parse_legacy_bgp_routes( raw_record.common_header.entry_subtype, raw_record.message_bytes, timestamp, + mode, ), v => Err(ParserError::Unsupported(format!( "unsupported MRT type: {v:?}" @@ -731,7 +874,11 @@ impl Iterator for RouteIterator { let used_zebra_compat = raw_record_uses_zebra_compat(&raw_record); let raw_bytes = raw_record.raw_bytes().to_vec(); - match parse_raw_record_route_iter(raw_record, &mut self.peer_table) { + match parse_raw_record_route_iter( + raw_record, + &mut self.peer_table, + self.parser.options.error_handling, + ) { Ok(routes) => { if used_zebra_compat { self.parser.warn_zebra_compat_once(); @@ -809,7 +956,11 @@ impl Iterator for FallibleRouteIterator { let used_zebra_compat = raw_record_uses_zebra_compat(&raw_record); let raw_bytes = raw_record.raw_bytes().to_vec(); - match parse_raw_record_route_iter(raw_record, &mut self.peer_table) { + match parse_raw_record_route_iter( + raw_record, + &mut self.peer_table, + self.parser.options.error_handling, + ) { Ok(routes) => { if used_zebra_compat { self.parser.warn_zebra_compat_once(); @@ -1178,11 +1329,15 @@ mod tests { data.put_u16(Afi::LinkState as u16); data.put_slice(&BgpMessage::KeepAlive.encode(AsnLength::Bits16).unwrap()); - let error = - match parse_bgp4mp_routes(Bgp4MpType::Message as u16, data.freeze(), 1_700_000_000.0) { - Err(error) => error, - Ok(_) => panic!("unexpectedly parsed BGP4MP routes"), - }; + let error = match parse_bgp4mp_routes( + Bgp4MpType::Message as u16, + data.freeze(), + 1_700_000_000.0, + ErrorHandlingMode::Preserve, + ) { + Err(error) => error, + Ok(_) => panic!("unexpectedly parsed BGP4MP routes"), + }; assert!(matches!( error, ParserError::ParseError(message) @@ -1367,6 +1522,7 @@ mod tests { prefixes: None, is_announcement: Some(true), has_standard_nlri: true, + judge: false, }, ) .unwrap(); @@ -1391,6 +1547,7 @@ mod tests { prefixes: None, is_announcement: Some(true), has_standard_nlri: true, + judge: false, }, ) .unwrap(); @@ -1416,6 +1573,7 @@ mod tests { prefixes: None, is_announcement: Some(false), has_standard_nlri: false, + judge: false, }, ) .unwrap(); @@ -1438,6 +1596,7 @@ mod tests { prefixes: None, is_announcement: Some(false), has_standard_nlri: false, + judge: false, }, ) .unwrap(); @@ -1465,6 +1624,7 @@ mod tests { prefixes: None, is_announcement: Some(false), has_standard_nlri: false, + judge: false, }, ) .unwrap(); @@ -1483,6 +1643,7 @@ mod tests { prefixes: None, is_announcement: Some(false), has_standard_nlri: false, + judge: false, }, ) .unwrap(); @@ -1501,6 +1662,7 @@ mod tests { prefixes: None, is_announcement: Some(false), has_standard_nlri: false, + judge: false, }, ) .unwrap(); @@ -1657,7 +1819,8 @@ mod tests { &AsnLength::Bits16, 1_700_000_000.0, "192.0.2.1".parse().unwrap(), - Asn::new_16bit(64496) + Asn::new_16bit(64496), + ErrorHandlingMode::Preserve, ) .is_err()); assert!(parse_bgp_message_routes( @@ -1666,7 +1829,8 @@ mod tests { &AsnLength::Bits16, 1_700_000_000.0, "192.0.2.1".parse().unwrap(), - Asn::new_16bit(64496) + Asn::new_16bit(64496), + ErrorHandlingMode::Preserve, ) .is_err()); @@ -1678,6 +1842,7 @@ mod tests { 1_700_000_000.0, "192.0.2.1".parse().unwrap(), Asn::new_16bit(64496), + ErrorHandlingMode::Preserve, ) .unwrap(), ) @@ -1692,6 +1857,7 @@ mod tests { 1_700_000_000.0, "192.0.2.1".parse().unwrap(), Asn::new_16bit(64496), + ErrorHandlingMode::Preserve, ) .unwrap(), ) @@ -1706,6 +1872,7 @@ mod tests { 1_700_000_000.0, "192.0.2.1".parse().unwrap(), Asn::new_16bit(64496), + ErrorHandlingMode::Preserve, ) .unwrap(), ) diff --git a/src/parser/iters/update.rs b/src/parser/iters/update.rs index cd6a82d9..f9e2ed78 100644 --- a/src/parser/iters/update.rs +++ b/src/parser/iters/update.rs @@ -154,9 +154,10 @@ pub struct UpdateIterator { impl UpdateIterator { pub(crate) fn new(parser: BgpkitParser) -> Self { + let elementor = parser.options.elementor(); UpdateIterator { parser, - elementor: Elementor::new(), + elementor, pending_table_dump: Vec::new(), } } @@ -276,9 +277,10 @@ pub struct FallibleUpdateIterator { impl FallibleUpdateIterator { pub(crate) fn new(parser: BgpkitParser) -> Self { + let elementor = parser.options.elementor(); FallibleUpdateIterator { parser, - elementor: Elementor::new(), + elementor, pending_table_dump: Vec::new(), finished: false, } @@ -779,6 +781,7 @@ mod tests { match elem.elem_type { ElemType::ANNOUNCE => elem_iter_announced += 1, ElemType::WITHDRAW => elem_iter_withdrawn += 1, + other => panic!("unexpected elem type {other:?} without RFC 7606 handling"), } } diff --git a/src/parser/mod.rs b/src/parser/mod.rs index be9e8872..258f8791 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -1,7 +1,7 @@ /*! parser module maintains the main logic for processing BGP and MRT messages. */ -use crate::models::{BgpElem, MrtRecord}; +use crate::models::{BgpElem, ErrorHandlingMode, MrtRecord}; use log::{debug, error, warn}; use std::io::{BufReader, Cursor, Read}; pub use text_dump::{detect_text_dump, infer_timestamp_from_path, TextDumpElemIterator}; @@ -56,6 +56,7 @@ pub(crate) struct ParserOptions { show_warnings: bool, warned_zebra_compat: bool, logged_parse_error: bool, + pub(crate) error_handling: ErrorHandlingMode, } impl Default for ParserOptions { fn default() -> Self { @@ -63,11 +64,17 @@ impl Default for ParserOptions { show_warnings: true, warned_zebra_compat: false, logged_parse_error: false, + error_handling: ErrorHandlingMode::Preserve, } } } impl ParserOptions { + /// An [`Elementor`] that converts UPDATE messages the way these options ask. + pub(crate) fn elementor(&self) -> Elementor { + Elementor::new().with_error_handling(self.error_handling) + } + pub(crate) fn warn_zebra_compat_once(&mut self) { if self.show_warnings && !self.warned_zebra_compat { warn!( @@ -363,6 +370,51 @@ impl BgpkitParser { } } + /// Sets how UPDATE messages with validation findings become elements in the element and + /// route iterators, and in record filtering. See + /// [`Elementor::with_error_handling`] for what each mode does. The route iterator skips the + /// value checks of attributes it does not parse; see + /// [`into_route_iter`](Self::into_route_iter). + /// + /// Records themselves are unchanged: + /// [`BgpUpdateMessage::error_handling_approach`](crate::models::BgpUpdateMessage::error_handling_approach) reports + /// the approach of an UPDATE in any mode. + pub fn with_error_handling(self, mode: ErrorHandlingMode) -> Self { + let mut options = self.options; + options.error_handling = mode; + BgpkitParser { + reader: self.reader, + core_dump: self.core_dump, + filters: self.filters, + options, + text_dump_iter: self.text_dump_iter, + } + } + + /// Apply RFC 7606 error handling to elements, assuming eBGP sessions: announcements of an + /// UPDATE that RFC 7606 treats as withdrawn become + /// [`ElemType::WITHDRAW`](crate::models::ElemType::WITHDRAW) elements, session-reset-class + /// errors produce [`ElemType::RESET`](crate::models::ElemType::RESET) elements, and attributes subject + /// to attribute discard are left out. Shorthand for + /// [`with_error_handling(ErrorHandlingMode::Rfc7606)`](Self::with_error_handling). + /// + /// ```no_run + /// use bgpkit_parser::BgpkitParser; + /// use bgpkit_parser::models::ElemType; + /// + /// let parser = BgpkitParser::new("https://data.ris.ripe.net/rrc00/latest-update.gz") + /// .unwrap() + /// .enable_rfc7606_error_handling(); + /// for elem in parser { + /// if let Some(approach) = elem.error_handling { + /// println!("{:?} {} ({approach:?})", elem.elem_type, elem.prefix); + /// } + /// } + /// ``` + pub fn enable_rfc7606_error_handling(self) -> Self { + self.with_error_handling(ErrorHandlingMode::Rfc7606) + } + /// Add a filter to the parser by specifying filter type and value as strings. /// /// This method parses the filter type and value strings to create a [`Filter`] and adds it diff --git a/src/parser/mrt/mrt_elem.rs b/src/parser/mrt/mrt_elem.rs index 93959cec..61d0c077 100644 --- a/src/parser/mrt/mrt_elem.rs +++ b/src/parser/mrt/mrt_elem.rs @@ -13,6 +13,7 @@ use std::net::{IpAddr, Ipv4Addr}; #[derive(Default, Debug, Clone)] pub struct Elementor { pub peer_table: Option, + error_handling: ErrorHandlingMode, } /// Error returned by [`Elementor::record_to_elems_iter`]. @@ -222,6 +223,7 @@ fn rib_entry_to_elem(prefix: NetworkPrefix, peer: &Peer, entry: RibEntry) -> Bgp only_to_customer: attrs.only_to_customer, unknown: attrs.unknown, deprecated: attrs.deprecated, + error_handling: None, } } @@ -375,6 +377,11 @@ pub struct BgpUpdateElemIter { withdrawn: std::iter::Chain, std::vec::IntoIter>, in_withdrawn_phase: bool, + /// Element type of the announced prefixes: `ANNOUNCE`, or `WITHDRAW` / `RESET` when RFC 7606 + /// error handling withdrew them, in which case the shared attributes above are all empty. + announced_as: ElemType, + /// RFC 7606 approach stamped on every element, when one was applied. + error_handling: Option, } impl Iterator for BgpUpdateElemIter { @@ -405,7 +412,7 @@ impl Iterator for BgpUpdateElemIter { }; return Some(BgpElem { timestamp: self.timestamp, - elem_type: ElemType::ANNOUNCE, + elem_type: self.announced_as, peer_ip: self.peer_ip, peer_asn: self.peer_asn, peer_bgp_id: self.peer_bgp_id, @@ -423,6 +430,7 @@ impl Iterator for BgpUpdateElemIter { only_to_customer: self.only_to_customer, unknown, deprecated, + error_handling: self.error_handling, }); } self.in_withdrawn_phase = true; @@ -448,6 +456,7 @@ impl Iterator for BgpUpdateElemIter { only_to_customer: None, unknown: None, deprecated: None, + error_handling: self.error_handling, }) } @@ -510,9 +519,46 @@ impl Elementor { pub fn with_peer_table(peer_table: PeerIndexTable) -> Elementor { Elementor { peer_table: Some(peer_table), + ..Default::default() } } + /// Sets how UPDATE messages with validation findings become elements. + /// + /// With [`ErrorHandlingMode::Rfc7606`], each UPDATE is converted according to its + /// [`BgpUpdateMessage::error_handling_approach`], assuming an eBGP session: + /// + /// - attribute discard: the announcements are kept and the malformed attributes, plus + /// repeats of an attribute after its first occurrence, are left out; + /// - treat-as-withdraw: every announced prefix becomes a [`ElemType::WITHDRAW`] element; + /// - AFI/SAFI disable or session reset: every announced prefix becomes a + /// [`ElemType::RESET`] element. + /// + /// Elements of an UPDATE that had an approach applied carry it in + /// [`BgpElem::error_handling`]. RIB entries are converted as before. + /// + /// ``` + /// use bgpkit_parser::Elementor; + /// use bgpkit_parser::models::ErrorHandlingMode; + /// + /// let elementor = Elementor::new().with_error_handling(ErrorHandlingMode::Rfc7606); + /// assert_eq!(elementor.error_handling(), ErrorHandlingMode::Rfc7606); + /// ``` + pub fn with_error_handling(mut self, mode: ErrorHandlingMode) -> Elementor { + self.error_handling = mode; + self + } + + /// Shorthand for [`with_error_handling(ErrorHandlingMode::Rfc7606)`](Self::with_error_handling). + pub fn enable_rfc7606_error_handling(self) -> Elementor { + self.with_error_handling(ErrorHandlingMode::Rfc7606) + } + + /// How this elementor converts UPDATE messages with validation findings. + pub fn error_handling(&self) -> ErrorHandlingMode { + self.error_handling + } + /// Convert a [`MrtRecord`] into an iterator of [`BgpElem`]s without /// requiring `&mut self`. /// @@ -587,11 +633,12 @@ impl Elementor { MrtMessage::Bgp4Mp(msg) => match msg { Bgp4MpEnum::StateChange(_) => Ok(PendingElems::Empty), Bgp4MpEnum::Message(v) => { - match Elementor::bgp_to_elems_iter( + match Elementor::bgp_to_elems_iter_with( v.bgp_message, timestamp, &v.peer_ip, &v.peer_asn, + self.error_handling, ) { Some(iter) => Ok(PendingElems::Bgp4Mp(iter)), None => Ok(PendingElems::Empty), @@ -600,11 +647,12 @@ impl Elementor { }, MrtMessage::LegacyBgp(msg) => match msg { LegacyBgp::StateChange(_) => Ok(PendingElems::Empty), - LegacyBgp::Message(message) => match Elementor::bgp_to_elems_iter( + LegacyBgp::Message(message) => match Elementor::bgp_to_elems_iter_with( message.bgp_message, timestamp, &message.peer_ip, &message.peer_asn, + self.error_handling, ) { Some(iter) => Ok(PendingElems::Bgp4Mp(iter)), None => Ok(PendingElems::Empty), @@ -655,10 +703,28 @@ impl Elementor { timestamp: f64, peer_ip: &IpAddr, peer_asn: &Asn, + ) -> Option { + Elementor::bgp_to_elems_iter_with( + msg, + timestamp, + peer_ip, + peer_asn, + ErrorHandlingMode::Preserve, + ) + } + + /// Like [`bgp_to_elems_iter`](Self::bgp_to_elems_iter), converting UPDATE messages according + /// to `mode`; see [`with_error_handling`](Self::with_error_handling). + pub fn bgp_to_elems_iter_with( + msg: BgpMessage, + timestamp: f64, + peer_ip: &IpAddr, + peer_asn: &Asn, + mode: ErrorHandlingMode, ) -> Option { match msg { - BgpMessage::Update(msg) => Some(Elementor::bgp_update_to_elems_iter( - msg, timestamp, peer_ip, peer_asn, + BgpMessage::Update(msg) => Some(Elementor::bgp_update_to_elems_iter_with( + msg, timestamp, peer_ip, peer_asn, mode, )), BgpMessage::Open(_) | BgpMessage::Notification(_) @@ -677,6 +743,18 @@ impl Elementor { Elementor::bgp_update_to_elems_iter(msg, timestamp, peer_ip, peer_asn).collect() } + /// Like [`bgp_update_to_elems`](Self::bgp_update_to_elems), converting the UPDATE according + /// to `mode`; see [`with_error_handling`](Self::with_error_handling). + pub fn bgp_update_to_elems_with( + msg: BgpUpdateMessage, + timestamp: f64, + peer_ip: &IpAddr, + peer_asn: &Asn, + mode: ErrorHandlingMode, + ) -> Vec { + Elementor::bgp_update_to_elems_iter_with(msg, timestamp, peer_ip, peer_asn, mode).collect() + } + /// Convert a [BgpUpdateMessage] into a [`BgpUpdateElemIter`] that lazily /// yields [BgpElem]s without allocating a `Vec`. pub fn bgp_update_to_elems_iter( @@ -685,6 +763,37 @@ impl Elementor { peer_ip: &IpAddr, peer_asn: &Asn, ) -> BgpUpdateElemIter { + Elementor::bgp_update_to_elems_iter_with( + msg, + timestamp, + peer_ip, + peer_asn, + ErrorHandlingMode::Preserve, + ) + } + + /// Like [`bgp_update_to_elems_iter`](Self::bgp_update_to_elems_iter), converting the UPDATE + /// according to `mode`; see [`with_error_handling`](Self::with_error_handling). + pub fn bgp_update_to_elems_iter_with( + mut msg: BgpUpdateMessage, + timestamp: f64, + peer_ip: &IpAddr, + peer_asn: &Asn, + mode: ErrorHandlingMode, + ) -> BgpUpdateElemIter { + let approach = match mode { + ErrorHandlingMode::Rfc7606 => msg.error_handling_approach(), + ErrorHandlingMode::Preserve => None, + }; + match approach { + Some(approach) if approach.withdraws_routes() => { + return withdrawn_update_elems_iter(msg, timestamp, peer_ip, peer_asn, approach); + } + Some(_) => DiscardPlan::from_warnings(&msg.attributes.validation_warnings) + .apply(&mut msg.attributes), + None => {} + } + let mut attrs = get_relevant_attributes(msg.attributes); let path = attrs.path(); @@ -719,6 +828,8 @@ impl Elementor { .into_iter() .chain(attrs.withdrawn_prefixes), in_withdrawn_phase: false, + announced_as: ElemType::ANNOUNCE, + error_handling: approach, } } @@ -748,6 +859,58 @@ impl Elementor { } } +/// RFC 7606 treat-as-withdraw and stronger: no announced route is installed, so every announced +/// prefix becomes a `WITHDRAW` element, or a `RESET` element when the approach is AFI/SAFI disable +/// or session reset. The path attributes describe routes that are not installed, so no element +/// carries them. As in the route iterator, only the first MP_REACH_NLRI and MP_UNREACH_NLRI +/// count (RFC 7606 §3(g)). +fn withdrawn_update_elems_iter( + msg: BgpUpdateMessage, + timestamp: f64, + peer_ip: &IpAddr, + peer_asn: &Asn, + approach: ErrorHandlingApproach, +) -> BgpUpdateElemIter { + let mut nlri_announced = Vec::new(); + let mut nlri_withdrawn = Vec::new(); + let mut seen = AttrCodeSet::default(); + for attribute in msg.attributes.inner { + if !seen.insert(attribute.value.attr_code()) { + continue; + } + match attribute.value { + AttributeValue::MpReachNlri(nlri) => nlri_announced.extend(nlri.prefixes), + AttributeValue::MpUnreachNlri(nlri) => nlri_withdrawn.extend(nlri.prefixes), + _ => {} + } + } + + BgpUpdateElemIter { + timestamp, + peer_ip: *peer_ip, + peer_asn: *peer_asn, + peer_bgp_id: None, + only_to_customer: None, + path: None, + origin_asns: None, + origin: None, + next_hop: None, + local_pref: None, + med: None, + communities: None, + atomic: false, + aggr_asn: None, + aggr_ip: None, + unknown: None, + deprecated: None, + announced: msg.announced_prefixes.into_iter().chain(nlri_announced), + withdrawn: msg.withdrawn_prefixes.into_iter().chain(nlri_withdrawn), + in_withdrawn_phase: false, + announced_as: approach.announced_elem_type(), + error_handling: Some(approach), + } +} + fn table_dump_to_elem(msg: TableDumpMessage) -> BgpElem { let attrs = get_relevant_attributes(msg.attributes); @@ -776,6 +939,7 @@ fn table_dump_to_elem(msg: TableDumpMessage) -> BgpElem { only_to_customer: attrs.only_to_customer, unknown: attrs.unknown, deprecated: attrs.deprecated, + error_handling: None, } } @@ -797,7 +961,8 @@ impl From<&BgpElem> for Attributes { let mut attributes = Attributes::default(); let prefix = value.prefix; - if value.elem_type == ElemType::WITHDRAW { + // RESET elems are routes RFC 7606 forbids installing, so they encode as withdrawals too + if !value.elem_type.is_announce() { values.push(AttributeValue::MpUnreachNlri(Nlri::new_unreachable(prefix))); attributes.extend(values); return attributes; @@ -977,6 +1142,7 @@ mod tests { code: AttrType::RESERVED.into(), bytes: Bytes::new(), }]), + error_handling: None, }; let _attributes = Attributes::from(&elem); @@ -984,6 +1150,18 @@ mod tests { let _attributes = Attributes::from(&elem); } + #[test] + fn test_reset_elem_converts_to_withdrawal() { + let elem = BgpElem { + elem_type: ElemType::RESET, + prefix: NetworkPrefix::from_str("10.0.0.0/24").unwrap(), + ..Default::default() + }; + let attributes = Attributes::from(&elem); + assert!(attributes.has_attr(AttrType::MP_UNREACHABLE_NLRI)); + assert!(!attributes.has_attr(AttrType::MP_REACHABLE_NLRI)); + } + #[test] fn test_get_relevant_attributes() { let attributes = vec![ diff --git a/src/parser/rislive/mod.rs b/src/parser/rislive/mod.rs index dcc15d1b..f799528c 100644 --- a/src/parser/rislive/mod.rs +++ b/src/parser/rislive/mod.rs @@ -344,6 +344,7 @@ impl Iterator for RisLiveElemIter { only_to_customer: None, unknown: None, deprecated: None, + error_handling: None, }); } @@ -371,6 +372,7 @@ impl Iterator for RisLiveElemIter { only_to_customer: None, unknown: None, deprecated: None, + error_handling: None, }) } diff --git a/src/parser/text_dump.rs b/src/parser/text_dump.rs index 60feb4b1..8a9c47c1 100644 --- a/src/parser/text_dump.rs +++ b/src/parser/text_dump.rs @@ -380,6 +380,7 @@ fn entry_to_elem( only_to_customer: None, unknown: None, deprecated: None, + error_handling: None, peer_bgp_id: None, }) } diff --git a/src/wasm/js/generated/ErrorHandlingApproach.ts b/src/wasm/js/generated/ErrorHandlingApproach.ts new file mode 100644 index 00000000..6e6d5f36 --- /dev/null +++ b/src/wasm/js/generated/ErrorHandlingApproach.ts @@ -0,0 +1,10 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * The action RFC 7606 §2 prescribes for an UPDATE message error. + * + * Variants are declared from weakest to strongest, so the derived [`Ord`] implements the + * RFC 7606 §3(h) rule: when an UPDATE has several errors, the strongest approach applies, and + * `max()` over the individual approaches gives it. + */ +export type ErrorHandlingApproach = "attribute_discard" | "treat_as_withdraw" | "afi_safi_disable" | "session_reset"; diff --git a/src/wasm/js/index.d.ts b/src/wasm/js/index.d.ts index b61ae82d..5abfd4ff 100644 --- a/src/wasm/js/index.d.ts +++ b/src/wasm/js/index.d.ts @@ -215,7 +215,8 @@ export interface BmpPeerHeader { export interface BgpElem { timestamp: number; - type: "ANNOUNCE" | "WITHDRAW"; + /** `RESET` only appears when RFC 7606 error handling is enabled, which the WASM bindings do not do. */ + type: "ANNOUNCE" | "WITHDRAW" | "RESET"; peer_ip: string; peer_asn: number; peer_bgp_id: string | null; @@ -235,6 +236,11 @@ export interface BgpElem { unknown: { code: number; bytes: number[] }[] | null; /** Deprecated attributes serialized as `{ code, bytes }` entries. */ deprecated: { code: number; bytes: number[] }[] | null; + /** + * RFC 7606 approach applied to the element's UPDATE. Present only when RFC 7606 error + * handling is enabled and the UPDATE had validation findings. + */ + error_handling?: "attribute_discard" | "treat_as_withdraw" | "afi_safi_disable" | "session_reset"; } // ── AS path types ──────────────────────────────────────────────────── diff --git a/src/wasm/test/type-check/check.ts b/src/wasm/test/type-check/check.ts index a7a8810c..1b707965 100644 --- a/src/wasm/test/type-check/check.ts +++ b/src/wasm/test/type-check/check.ts @@ -56,9 +56,17 @@ type Widen = T extends string * serde) and the declared type. Plain assignability would silently allow * extra fixture fields — this catches a Rust model gaining or losing a field * without the .d.ts being updated (and vice versa). + * + * Keys declared optional may be absent from the fixture: serde skips + * `Option::None` fields, so a fixture cannot assert their presence. + * Required keys must all appear. */ +type RequiredKeys = { + [K in keyof T]-?: Record extends Pick ? never : K; +}[keyof T]; + type ExactKeys = [keyof Actual] extends [keyof Declared] - ? [keyof Declared] extends [keyof Actual] + ? [RequiredKeys] extends [keyof Actual] ? true : false : false; diff --git a/tests/test_rfc7606_error_handling.rs b/tests/test_rfc7606_error_handling.rs index 3301a60a..e725f488 100644 --- a/tests/test_rfc7606_error_handling.rs +++ b/tests/test_rfc7606_error_handling.rs @@ -312,6 +312,13 @@ fn test_treat_as_withdrawal_emulation() { needs_taw, "malformed NLRI should be detectable via warnings" ); + // RFC 7606 §5.3: unparseable NLRI leave nothing to withdraw, so the + // approach is a session reset, which also withdraws the routes + assert!(bad_update.is_treat_as_withdraw()); + assert_eq!( + bad_update.error_handling_approach(), + Some(ErrorHandlingApproach::SessionReset) + ); // Caller actions: // 1. Do not install any routes (announced_prefixes is empty) @@ -484,3 +491,466 @@ fn test_malformed_nlri_still_triggers_mandatory_attr_check() { "expected MissingWellKnownAttribute(NEXT_HOP)" ); } + +// ======================================================================== +// RFC 7606 error handling applied to elements +// +// These tests wrap an UPDATE body in a BGP4MP_MESSAGE_AS4 MRT record and +// parse it with `BgpkitParser`, once as encoded and once with +// `enable_rfc7606_error_handling()`. +// ======================================================================== + +/// Wrap an UPDATE body in a BGP message and a BGP4MP_MESSAGE_AS4 MRT record +/// from peer AS 65000 at 192.0.2.1. +fn bgp4mp_update_record(update_body: &[u8]) -> Vec { + let mut bgp = vec![0xff; 16]; + bgp.extend_from_slice(&((19 + update_body.len()) as u16).to_be_bytes()); + bgp.push(2); // UPDATE + bgp.extend_from_slice(update_body); + + let mut body = Vec::new(); + body.extend_from_slice(&65000u32.to_be_bytes()); // peer AS + body.extend_from_slice(&65001u32.to_be_bytes()); // local AS + body.extend_from_slice(&0u16.to_be_bytes()); // interface index + body.extend_from_slice(&1u16.to_be_bytes()); // AFI IPv4 + body.extend_from_slice(&[192, 0, 2, 1]); // peer IP + body.extend_from_slice(&[192, 0, 2, 2]); // local IP + body.extend_from_slice(&bgp); + + let mut record = Vec::new(); + record.extend_from_slice(&1_700_000_000u32.to_be_bytes()); + record.extend_from_slice(&16u16.to_be_bytes()); // BGP4MP + record.extend_from_slice(&4u16.to_be_bytes()); // BGP4MP_MESSAGE_AS4 + record.extend_from_slice(&(body.len() as u32).to_be_bytes()); + record.extend_from_slice(&body); + record +} + +fn elems_of(update_body: &[u8], rfc7606: bool) -> Vec { + let parser = + bgpkit_parser::BgpkitParser::from_reader(Cursor::new(bgp4mp_update_record(update_body))); + let parser = if rfc7606 { + parser.enable_rfc7606_error_handling() + } else { + parser + }; + parser.into_elem_iter().collect() +} + +/// ORIGIN, empty AS_PATH and NEXT_HOP, with ORIGIN set to `origin`. +fn attrs_with_origin(origin: u8) -> Vec { + let mut attrs = build_valid_attrs(); + attrs[3] = origin; + attrs +} + +/// 10.0.0.0/24 and 10.0.1.0/24 +fn two_prefixes() -> Vec { + vec![0x18, 10, 0, 0, 0x18, 10, 0, 1] +} + +/// IPv6 unicast MP_REACH_NLRI announcing 2001:db8::/32 via 2001:db8::1. +fn ipv6_mp_reach() -> Vec { + let mut value = vec![0x00, 0x02, 0x01, 16]; + value.extend_from_slice(&[0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); + value.push(0); // reserved + value.extend_from_slice(&[32, 0x20, 0x01, 0x0d, 0xb8]); + let mut attr = vec![0x80, 0x0e, value.len() as u8]; + attr.extend_from_slice(&value); + attr +} + +#[test] +fn test_treat_as_withdraw_mode_withdraws_announced_prefixes() { + let body = build_update_body(&[], &attrs_with_origin(3), &two_prefixes()); + + // as encoded: the announcements are kept and carry no verdict + let elems = elems_of(&body, false); + assert_eq!(elems.len(), 2); + assert!(elems + .iter() + .all(|e| e.elem_type == ElemType::ANNOUNCE && e.error_handling.is_none())); + + // RFC 7606 §7.1: an undefined ORIGIN value is treat-as-withdraw + let elems = elems_of(&body, true); + assert_eq!(elems.len(), 2); + for elem in &elems { + assert_eq!(elem.elem_type, ElemType::WITHDRAW); + assert_eq!( + elem.error_handling, + Some(ErrorHandlingApproach::TreatAsWithdraw) + ); + assert_eq!(elem.as_path, None); + assert_eq!(elem.next_hop, None); + assert_eq!(elem.unknown, None); + } +} + +#[test] +fn test_treat_as_withdraw_mode_covers_mp_reach_prefixes() { + let mut attrs = vec![0x40, 0x01, 0x01, 0x00, 0x40, 0x02, 0x00]; + attrs.extend_from_slice(&ipv6_mp_reach()); + // COMMUNITIES of 6 bytes: not a multiple of 4 (RFC 7606 §7.8) + attrs.extend_from_slice(&[0xc0, 0x08, 0x06, 0, 1, 0, 1, 0, 2]); + let body = build_update_body(&[], &attrs, &[]); + + let elems = elems_of(&body, true); + assert_eq!(elems.len(), 1); + assert_eq!(elems[0].prefix.to_string(), "2001:db8::/32"); + assert_eq!(elems[0].elem_type, ElemType::WITHDRAW); + assert_eq!( + elems[0].error_handling, + Some(ErrorHandlingApproach::TreatAsWithdraw) + ); +} + +#[test] +fn test_attribute_discard_mode_keeps_routes_and_drops_attributes() { + let mut attrs = build_valid_attrs(); + attrs.extend_from_slice(&[0x40, 0x06, 0x01, 0x00]); // ATOMIC_AGGREGATE with a value byte + attrs.extend_from_slice(&[0xc0, 0x07, 0x07, 0, 0, 0xfd, 0xe8, 10, 0, 0]); // AGGREGATOR, 7 bytes + attrs.extend_from_slice(&[0xc0, 0x08, 0x04, 0, 1, 0, 1]); // COMMUNITIES 1:1 + attrs.extend_from_slice(&[0xc0, 0x08, 0x04, 0, 2, 0, 2]); // repeated COMMUNITIES 2:2 + let body = build_update_body(&[], &attrs, &valid_nlri_prefix()); + + // as encoded: the malformed values show up and both COMMUNITIES are kept + let elems = elems_of(&body, false); + assert_eq!(elems.len(), 1); + assert!(elems[0].atomic); + assert!(elems[0].unknown.is_some(), "AGGREGATOR kept raw"); + + let elems = elems_of(&body, true); + assert_eq!(elems.len(), 1); + let elem = &elems[0]; + assert_eq!(elem.elem_type, ElemType::ANNOUNCE); + assert_eq!( + elem.error_handling, + Some(ErrorHandlingApproach::AttributeDiscard) + ); + assert!(!elem.atomic, "malformed ATOMIC_AGGREGATE discarded"); + assert_eq!(elem.aggr_asn, None, "malformed AGGREGATOR discarded"); + assert_eq!( + elem.unknown, None, + "discarded attribute must not leak as unknown" + ); + assert_eq!( + elem.communities, + Some(vec![MetaCommunity::Plain(Community::Custom( + Asn::new_32bit(1), + 1 + ))]), + "the first COMMUNITIES is kept (RFC 7606 §3(g))" + ); + assert_eq!(elem.next_hop.unwrap().to_string(), "1.2.3.4"); +} + +#[test] +fn test_malformed_repeat_does_not_affect_the_first_occurrence() { + // RFC 7606 §3(g): a repeat is discarded whatever it holds, so a malformed + // repeat neither withdraws the routes nor takes the valid first copy with it + let mut attrs = build_valid_attrs(); + attrs.extend_from_slice(&[0xc0, 0x08, 0x04, 0, 1, 0, 1]); // COMMUNITIES 1:1 + attrs.extend_from_slice(&[0xc0, 0x08, 0x06, 0, 2, 0, 2, 0, 2]); // COMMUNITIES, 6 bytes + attrs.extend_from_slice(&[0xc0, 0x07, 0x08, 0, 0, 0xfd, 0xe8, 10, 0, 0, 1]); // AGGREGATOR + attrs.extend_from_slice(&[0xc0, 0x07, 0x07, 0, 0, 0xfd, 0xe9, 10, 0, 0]); // AGGREGATOR, 7 bytes + let body = build_update_body(&[], &attrs, &valid_nlri_prefix()); + + let update = + parse_bgp_update_message(Bytes::from(body.clone()), false, &AsnLength::Bits32).unwrap(); + assert!(update + .attributes + .validation_warnings() + .iter() + .all(|w| matches!(w, BgpValidationWarning::DuplicateAttribute { .. }))); + + let elems = elems_of(&body, true); + assert_eq!(elems.len(), 1); + let elem = &elems[0]; + assert_eq!(elem.elem_type, ElemType::ANNOUNCE); + assert_eq!( + elem.error_handling, + Some(ErrorHandlingApproach::AttributeDiscard) + ); + assert_eq!( + elem.communities, + Some(vec![MetaCommunity::Plain(Community::Custom( + Asn::new_32bit(1), + 1 + ))]) + ); + assert_eq!(elem.aggr_asn, Some(Asn::new_32bit(65000))); + assert_routes_match_elems(&body, true); +} + +#[test] +fn test_local_pref_is_attribute_discard_under_ebgp_assumption() { + let mut attrs = build_valid_attrs(); + attrs.extend_from_slice(&[0x40, 0x05, 0x02, 0, 100]); // LOCAL_PREF, 2 bytes + let body = build_update_body(&[], &attrs, &valid_nlri_prefix()); + + let elems = elems_of(&body, true); + assert_eq!(elems.len(), 1); + assert_eq!(elems[0].elem_type, ElemType::ANNOUNCE); + assert_eq!( + elems[0].error_handling, + Some(ErrorHandlingApproach::AttributeDiscard) + ); +} + +#[test] +fn test_malformed_mp_reach_produces_reset_elems() { + let mut attrs = build_valid_attrs(); + // IPv6 unicast MP_REACH_NLRI whose next-hop length (3) is invalid + attrs.extend_from_slice(&[ + 0x80, 0x0e, 0x08, 0x00, 0x02, 0x01, 0x03, 0xaa, 0xbb, 0xcc, 0x00, + ]); + let body = build_update_body(&[], &attrs, &valid_nlri_prefix()); + + let elems = elems_of(&body, true); + assert_eq!(elems.len(), 1); + assert_eq!(elems[0].prefix.to_string(), "10.0.0.0/24"); + assert_eq!(elems[0].elem_type, ElemType::RESET); + assert_eq!( + elems[0].error_handling, + Some(ErrorHandlingApproach::AfiSafiDisable) + ); + assert!(elems[0].to_string().starts_with("R|")); +} + +#[test] +fn test_repeated_mp_reach_is_session_reset() { + let mut attrs = vec![0x40, 0x01, 0x01, 0x00, 0x40, 0x02, 0x00]; + attrs.extend_from_slice(&ipv6_mp_reach()); + attrs.extend_from_slice(&ipv6_mp_reach()); + let body = build_update_body(&[], &attrs, &[]); + + let elems = elems_of(&body, true); + assert!(!elems.is_empty()); + assert!(elems.iter().all(|e| e.elem_type == ElemType::RESET + && e.error_handling == Some(ErrorHandlingApproach::SessionReset))); +} + +#[test] +fn test_repeated_mp_reach_counts_only_the_first() { + // the repeat announces 2001:db8:1::/48; both iterators report only the + // first MP_REACH_NLRI's 2001:db8::/32 + let mut repeat = ipv6_mp_reach(); + let len = repeat.len(); + repeat[len - 5..].copy_from_slice(&[48, 0x20, 0x01, 0x0d, 0xb8]); + repeat.extend_from_slice(&[0x00, 0x01]); + repeat[2] += 2; + let mut attrs = vec![0x40, 0x01, 0x01, 0x00, 0x40, 0x02, 0x00]; + attrs.extend_from_slice(&ipv6_mp_reach()); + attrs.extend_from_slice(&repeat); + let body = build_update_body(&[], &attrs, &[]); + + let elems = elems_of(&body, true); + assert_eq!(elems.len(), 1); + assert_eq!(elems[0].prefix.to_string(), "2001:db8::/32"); + assert_eq!(elems[0].elem_type, ElemType::RESET); + assert_routes_match_elems(&body, true); +} + +#[test] +fn test_malformed_classic_nlri_is_session_reset() { + let body = build_update_body(&[], &build_valid_attrs(), &malformed_nlri()); + let update = parse_bgp_update_message(Bytes::from(body), false, &AsnLength::Bits32).unwrap(); + assert_eq!( + update.error_handling_approach(), + Some(ErrorHandlingApproach::SessionReset) + ); +} + +#[test] +fn test_update_without_nlri_escalates_to_session_reset() { + // RFC 7606 §5.2: attributes and a withdrawn route, no reachable NLRI, and a + // treat-as-withdraw error + let body = build_update_body(&valid_nlri_prefix(), &attrs_with_origin(3), &[]); + let update = + parse_bgp_update_message(Bytes::from(body.clone()), false, &AsnLength::Bits32).unwrap(); + assert_eq!( + update.error_handling_approach(), + Some(ErrorHandlingApproach::SessionReset) + ); + + let elems = elems_of(&body, true); + assert_eq!(elems.len(), 1); + assert_eq!(elems[0].elem_type, ElemType::WITHDRAW); + assert_eq!( + elems[0].error_handling, + Some(ErrorHandlingApproach::SessionReset) + ); +} + +#[test] +fn test_clean_update_is_unchanged_by_the_mode() { + let body = build_update_body(&[], &build_valid_attrs(), &two_prefixes()); + assert_eq!(elems_of(&body, false), elems_of(&body, true)); +} + +#[test] +fn test_type_filter_sees_synthesized_withdrawals() { + let body = build_update_body(&[], &attrs_with_origin(3), &two_prefixes()); + let parser = bgpkit_parser::BgpkitParser::from_reader(Cursor::new(bgp4mp_update_record(&body))) + .enable_rfc7606_error_handling() + .add_filter("type", "w") + .unwrap(); + assert_eq!(parser.into_elem_iter().count(), 2); +} + +#[test] +fn test_malformed_update_reencodes_byte_identically() { + let mut attrs = attrs_with_origin(3); + attrs.extend_from_slice(&[0xc0, 0x08, 0x06, 0, 1, 0, 1, 0, 2]); + let body = build_update_body(&[], &attrs, &two_prefixes()); + let update = + parse_bgp_update_message(Bytes::from(body.clone()), false, &AsnLength::Bits32).unwrap(); + assert!(update.is_treat_as_withdraw()); + assert_eq!(update.encode(AsnLength::Bits32).unwrap(), Bytes::from(body)); +} + +/// The route iterator yields the projection of the element iterator, for +/// UPDATEs without value errors in attributes the route iterator does not parse. +fn assert_routes_match_elems(update_body: &[u8], rfc7606: bool) { + let record = bgp4mp_update_record(update_body); + let parser = |bytes: Vec| { + let parser = bgpkit_parser::BgpkitParser::from_reader(Cursor::new(bytes)); + if rfc7606 { + parser.enable_rfc7606_error_handling() + } else { + parser + } + }; + let routes: Vec = parser(record.clone()).into_route_iter().collect(); + let projected: Vec = parser(record) + .into_elem_iter() + .map(|elem| BgpRouteElem { + timestamp: elem.timestamp, + elem_type: elem.elem_type, + peer_ip: elem.peer_ip, + peer_asn: elem.peer_asn, + prefix: elem.prefix, + as_path: elem.as_path.map(std::sync::Arc::new), + }) + .collect(); + assert_eq!(routes, projected); +} + +#[test] +fn test_route_iterator_matches_elems_under_rfc7606() { + let mut discard = build_valid_attrs(); + discard.extend_from_slice(&[0x40, 0x06, 0x01, 0x00]); + let mut reset = build_valid_attrs(); + reset.extend_from_slice(&[ + 0x80, 0x0e, 0x08, 0x00, 0x02, 0x01, 0x03, 0xaa, 0xbb, 0xcc, 0x00, + ]); + let mut as4 = vec![0x40, 0x01, 0x01, 0x00]; + as4.extend_from_slice(&[0x40, 0x02, 0x06, 0x02, 0x01, 0x00, 0x00, 0x5b, 0xa0]); // AS_TRANS + as4.extend_from_slice(&[0x40, 0x03, 0x04, 1, 2, 3, 4]); + as4.extend_from_slice(&[0xc0, 0x11, 0x06, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00]); // AS4_PATH [0] + + // header-level findings on attributes the route iterator does not parse + let mut short_communities = build_valid_attrs(); + short_communities.extend_from_slice(&[0xc0, 0x08, 0x06, 0, 1, 0, 1, 0, 2]); + let mut well_known_communities = build_valid_attrs(); + well_known_communities.extend_from_slice(&[0x40, 0x08, 0x04, 0, 1, 0, 1]); + + let bodies = [ + build_update_body(&[], &build_valid_attrs(), &two_prefixes()), + build_update_body(&[], &short_communities, &two_prefixes()), + build_update_body(&[], &well_known_communities, &two_prefixes()), + build_update_body(&[], &attrs_with_origin(3), &two_prefixes()), + build_update_body(&[], &discard, &two_prefixes()), + build_update_body(&[], &reset, &valid_nlri_prefix()), + build_update_body(&valid_nlri_prefix(), &attrs_with_origin(3), &[]), + build_update_body(&[], &as4, &valid_nlri_prefix()), + ]; + for body in &bodies { + assert_routes_match_elems(body, true); + } + // a malformed AS4_PATH is discarded, so the route keeps the AS_PATH alone + assert_eq!( + routes_of(&bodies[7])[0] + .as_path + .as_deref() + .map(|p| p.to_string()), + Some("23456".to_string()) + ); +} + +#[test] +fn test_repeated_as4_path_keeps_the_first_in_both_iterators() { + let mut attrs = vec![0x40, 0x01, 0x01, 0x00]; + attrs.extend_from_slice(&[0x40, 0x02, 0x06, 0x02, 0x01, 0x00, 0x00, 0x5b, 0xa0]); // AS_TRANS + attrs.extend_from_slice(&[0x40, 0x03, 0x04, 1, 2, 3, 4]); + attrs.extend_from_slice(&[0xc0, 0x11, 0x06, 0x02, 0x01, 0x00, 0x00, 0x34, 0x17]); // [13335] + attrs.extend_from_slice(&[0xc0, 0x11, 0x06, 0x02, 0x01, 0x00, 0x00, 0xfb, 0xf4]); // [64500] + let body = build_update_body(&[], &attrs, &valid_nlri_prefix()); + + assert_routes_match_elems(&body, true); + assert_eq!( + routes_of(&body)[0] + .as_path + .as_deref() + .map(|p| p.to_string()), + Some("13335".to_string()) + ); +} + +fn routes_of(update_body: &[u8]) -> Vec { + bgpkit_parser::BgpkitParser::from_reader(Cursor::new(bgp4mp_update_record(update_body))) + .enable_rfc7606_error_handling() + .into_route_iter() + .collect() +} + +#[test] +fn test_route_iterator_misses_value_errors_in_attributes_it_does_not_parse() { + // a D-PATH whose value is too short (RFC 10039 §4): its header is fine, so + // only the element iterator, which parses the value, withdraws the routes + let mut attrs = build_valid_attrs(); + attrs.extend_from_slice(&[0xc0, 0x24, 0x02, 0x00, 0x00]); + let body = build_update_body(&[], &attrs, &two_prefixes()); + + assert!(elems_of(&body, true) + .iter() + .all(|e| e.elem_type == ElemType::WITHDRAW)); + let routes = routes_of(&body); + assert_eq!(routes.len(), 2); + assert!(routes + .iter() + .all(|r| r.elem_type == ElemType::ANNOUNCE && r.as_path.is_some())); +} + +#[test] +fn test_route_iterator_judges_headers_of_attributes_it_does_not_parse() { + // COMMUNITIES without the optional bit is a known attribute with wrong + // flags: treat-as-withdraw in both iterators, not a session reset + let mut attrs = build_valid_attrs(); + attrs.extend_from_slice(&[0x40, 0x08, 0x04, 0, 1, 0, 1]); + let body = build_update_body(&[], &attrs, &valid_nlri_prefix()); + let routes = routes_of(&body); + assert_eq!(routes.len(), 1); + assert_eq!(routes[0].elem_type, ElemType::WITHDRAW); + + // an unknown code without the optional bit is a session reset in both + let mut attrs = build_valid_attrs(); + attrs.extend_from_slice(&[0x40, 0xc8, 0x00]); + let body = build_update_body(&[], &attrs, &valid_nlri_prefix()); + assert_eq!(routes_of(&body)[0].elem_type, ElemType::RESET); + assert_eq!(elems_of(&body, true)[0].elem_type, ElemType::RESET); +} + +#[test] +fn test_route_iterator_malformed_nlri_is_not_fatal_under_rfc7606() { + // valid withdrawn route, unparseable announced NLRI + let body = build_update_body( + &valid_nlri_prefix(), + &build_valid_attrs(), + &malformed_nlri(), + ); + let routes = routes_of(&body); + assert_eq!(routes.len(), 1); + assert_eq!(routes[0].elem_type, ElemType::WITHDRAW); + assert_eq!(routes[0].prefix.to_string(), "10.0.0.0/24"); +} diff --git a/tests/test_wasm_type_fixtures.rs b/tests/test_wasm_type_fixtures.rs index 0e02c2a0..909aa316 100644 --- a/tests/test_wasm_type_fixtures.rs +++ b/tests/test_wasm_type_fixtures.rs @@ -167,6 +167,7 @@ fn write_bgp_elem_fixtures() { bytes: Bytes::from_static(&[0xff]), }]), deprecated: None, + error_handling: None, }; write_fixture("bgp_elem_announce", &announce); @@ -190,6 +191,7 @@ fn write_bgp_elem_fixtures() { only_to_customer: None, unknown: None, deprecated: None, + error_handling: None, }; write_fixture("bgp_elem_withdraw", &withdraw); }