diff --git a/CHANGELOG.md b/CHANGELOG.md index 63d9118d..707e0165 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ All notable changes to this project will be documented in this file. ## Unreleased +### Breaking changes + +* **`Afi` and `Safi` gain the EVPN family and `ExtendedCommunity` gains `MacMobility`**: `Afi::L2vpn` (25) and `Safi::Evpn` (70) now parse instead of failing, and the MAC Mobility extended community (type `0x06`, sub-type `0x00`) parses into `ExtendedCommunity::MacMobility { sticky, sequence }` instead of a raw 8-byte blob. `ExtendedCommunity::Raw` now reports the registered type of an undecoded community (`Evpn` for the other EVPN sub-types) rather than `Unknown`. Downstream exhaustive matches on these enums need a new arm. + +### Added + +* **EVPN NLRI support** ([RFC 7432](https://datatracker.ietf.org/doc/html/rfc7432), [RFC 9136](https://datatracker.ietf.org/doc/html/rfc9136)): `MP_REACH_NLRI` and `MP_UNREACH_NLRI` for AFI 25 / SAFI 70 decode into `Nlri::evpn_nlris`, one `EvpnNlri` per route with its route distinguisher and a route-type-specific body: type 2 (MAC/IP advertisement: ESI, Ethernet tag, MAC, optional IP, label), type 3 (inclusive multicast), and type 5 (IP prefix). Route types 1 and 4 keep their octets in `EvpnRoutePayload::Raw`, and an EVPN end-of-RIB marker decodes to an empty list. Until now an EVPN BMP feed produced only `AttributeValue::Raw` and no fields at all. The encoder writes the same routes back, so `MrtRecord::try_from(&BmpMessage)` keeps converting EVPN route monitoring messages, and text output renders an `ANNOUNCED (EVPN)` / `WITHDRAWN (EVPN)` section instead of dropping them. +* **MAC Mobility extended community encoder**: `ExtendedCommunity::MacMobility` re-encodes to the 8 wire octets, so a decoded EVPN route survives a decode/encode round trip of its communities. + ## v0.23.0 - 2026-10-17 ### Breaking changes diff --git a/src/lib.rs b/src/lib.rs index 78408ae7..3fafdb4e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -857,6 +857,13 @@ Additional known attribute type codes are raw-retained (`AttributeValue::Raw`) a ## Advanced Features +**EVPN** (AFI 25 / SAFI 70): +- [RFC 7432](https://datatracker.ietf.org/doc/html/rfc7432): BGP MPLS-Based Ethernet VPN - route types 2 + and 3, and the MAC Mobility extended community +- [RFC 9136](https://datatracker.ietf.org/doc/html/rfc9136): IP Prefix Advertisement in EVPN - route type 5 + +Route types 1 and 4 are accepted and preserved as raw octets; they are not decoded yet. + **FlowSpec**: - [RFC 8955](https://datatracker.ietf.org/doc/html/rfc8955): Dissemination of Flow Specification Rules - [RFC 8956](https://datatracker.ietf.org/doc/html/rfc8956): Dissemination of Flow Specification Rules for IPv6 diff --git a/src/models/bgp/attributes/nlri.rs b/src/models/bgp/attributes/nlri.rs index cb353d9c..56b9398e 100644 --- a/src/models/bgp/attributes/nlri.rs +++ b/src/models/bgp/attributes/nlri.rs @@ -29,6 +29,9 @@ pub struct Nlri { /// Flow-Spec NLRI data - RFC 8955/8956 #[cfg_attr(feature = "ts-rs", ts(type = "Record[] | null"))] pub flowspec_nlris: Option>, + /// EVPN NLRI data - RFC 7432 (AFI 25, SAFI 70) + #[cfg_attr(feature = "ts-rs", ts(type = "Record[] | null"))] + pub evpn_nlris: Option>, } impl Nlri { @@ -52,11 +55,26 @@ impl Nlri { matches!(self.safi, Safi::FlowSpec | Safi::FlowSpecL3Vpn) } + /// Returns true if this NLRI refers to EVPN (AFI 25, SAFI 70). + pub const fn is_evpn(&self) -> bool { + matches!(self.afi, Afi::L2vpn) && matches!(self.safi, Safi::Evpn) + } + /// Returns true if this NLRI refers to MPLS-labeled prefixes (SAFI 4). pub const fn is_mpls_labeled(&self) -> bool { matches!(self.safi, Safi::MplsLabel) } + /// Returns true when this NLRI carries no reachability information in any + /// family, which is the shape of an MP_UNREACH end-of-RIB marker. + pub fn is_empty(&self) -> bool { + self.prefixes.is_empty() + && self.labeled_prefixes.as_ref().is_none_or(|p| p.is_empty()) + && self.link_state_nlris.as_ref().is_none_or(|n| n.is_empty()) + && self.flowspec_nlris.as_ref().is_none_or(|n| n.is_empty()) + && self.evpn_nlris.as_ref().is_none_or(|n| n.is_empty()) + } + /// Returns true if this NLRI refers to reachable prefixes pub const fn is_reachable(&self) -> bool { self.next_hop.is_some() @@ -88,6 +106,7 @@ impl Nlri { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, } } @@ -105,6 +124,7 @@ impl Nlri { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, } } @@ -122,6 +142,7 @@ impl Nlri { labeled_prefixes: None, link_state_nlris: Some(nlri_list), flowspec_nlris: None, + evpn_nlris: None, } } @@ -137,6 +158,7 @@ impl Nlri { labeled_prefixes: None, link_state_nlris: Some(nlri_list), flowspec_nlris: None, + evpn_nlris: None, } } @@ -156,6 +178,7 @@ impl Nlri { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: Some(flowspec_nlris), + evpn_nlris: None, } } @@ -173,6 +196,7 @@ impl Nlri { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: Some(flowspec_nlris), + evpn_nlris: None, } } @@ -191,6 +215,39 @@ impl Nlri { labeled_prefixes: Some(labeled_prefixes), link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, + } + } + + /// Create a new EVPN reachable NLRI (AFI 25 / SAFI 70) - RFC 7432 + pub fn new_evpn_reachable( + next_hop: Option, + nlri_list: Vec, + ) -> Nlri { + let next_hop = next_hop.map(NextHopAddress::from); + Nlri { + afi: Afi::L2vpn, + safi: Safi::Evpn, + next_hop, + prefixes: Vec::new(), + labeled_prefixes: None, + link_state_nlris: None, + flowspec_nlris: None, + evpn_nlris: Some(nlri_list), + } + } + + /// Create a new EVPN unreachable NLRI (AFI 25 / SAFI 70) - RFC 7432 + pub fn new_evpn_unreachable(nlri_list: Vec) -> Nlri { + Nlri { + afi: Afi::L2vpn, + safi: Safi::Evpn, + next_hop: None, + prefixes: Vec::new(), + labeled_prefixes: None, + link_state_nlris: None, + flowspec_nlris: None, + evpn_nlris: Some(nlri_list), } } @@ -205,6 +262,7 @@ impl Nlri { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, } } } diff --git a/src/models/bgp/community.rs b/src/models/bgp/community.rs index ffd59374..b73c4bfb 100644 --- a/src/models/bgp/community.rs +++ b/src/models/bgp/community.rs @@ -56,6 +56,8 @@ pub enum ExtendedCommunityType { TransitiveIpv4Addr = 0x01, TransitiveFourOctetAs = 0x02, TransitiveOpaque = 0x03, + /// EVPN extended community - RFC 7432 §7 + Evpn = 0x06, // non-transitive types NonTransitiveTwoOctetAs = 0x40, @@ -67,6 +69,29 @@ pub enum ExtendedCommunityType { Unknown(u8), } +impl ExtendedCommunityType { + /// Map a wire type octet to a variant. + /// + /// [`From`] cannot be used in a constant context, and + /// [`ExtendedCommunity::community_type`] is `const`, so the mapping is + /// spelled out here. Keep it in step with the enum. + pub const fn from_byte(byte: u8) -> Self { + use ExtendedCommunityType::*; + match byte { + 0x00 => TransitiveTwoOctetAs, + 0x01 => TransitiveIpv4Addr, + 0x02 => TransitiveFourOctetAs, + 0x03 => TransitiveOpaque, + 0x06 => Evpn, + 0x40 => NonTransitiveTwoOctetAs, + 0x41 => NonTransitiveIpv4Addr, + 0x42 => NonTransitiveFourOctetAs, + 0x43 => NonTransitiveOpaque, + other => Unknown(other), + } + } +} + /// Extended Communities. /// /// ## Overview @@ -116,6 +141,8 @@ pub enum ExtendedCommunity { FlowSpecTrafficMarking(FlowSpecTrafficMarking), /// BGP Link Bandwidth - RFC 10005 LinkBandwidth(LinkBandwidth), + /// MAC Mobility - RFC 7432 §7.7 + MacMobility(MacMobility), Raw([u8; 8]), } @@ -142,7 +169,8 @@ impl ExtendedCommunity { NonTransitiveTwoOctetAs } } - ExtendedCommunity::Raw(buffer) => Unknown(buffer[0]), + ExtendedCommunity::MacMobility(_) => Evpn, + ExtendedCommunity::Raw(buffer) => ExtendedCommunityType::from_byte(buffer[0]), } } } @@ -159,6 +187,33 @@ pub struct Ipv6AddrExtCommunity { pub local_admin: [u8; 2], } +/// MAC Mobility Extended Community - RFC 7432 §7.7 +/// +/// Carried with a MAC/IP Advertisement (route type 2). The sequence number is +/// how a fabric orders competing advertisements for the same MAC: the highest +/// value wins, and a PE that sees a locally learned MAC it previously knew as +/// remote re-advertises it with the sequence number incremented. +/// +/// ```text +/// 0 1 2 3 +/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +/// | Type = 0x06 | Sub-Type = 0x00| Flags | Reserved | +/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +/// | Sequence Number | +/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +/// ``` +#[derive(Debug, PartialEq, Clone, Copy, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS), ts(export))] +pub struct MacMobility { + /// Sticky/static flag (bit 0 of the flags octet): the MAC is considered + /// immobile and does not take part in sequence-number comparison. + pub sticky: bool, + /// Sequence number, 32 bits big-endian. + pub sequence: u32, +} + /// Two-Octet AS Specific Extended Community /// /// @@ -439,6 +494,16 @@ impl Display for ExtendedCommunity { ec_type, 0x04, link_bandwidth.global_admin, link_bandwidth.bandwidth ) } + ExtendedCommunity::MacMobility(mobility) => { + write!( + f, + "{}:{}:{}:{}", + ec_type, + 0x00, + u8::from(mobility.sticky), + mobility.sequence + ) + } ExtendedCommunity::Raw(ec) => { write!(f, "{}", ToHexString(ec)) } diff --git a/src/models/bgp/evpn.rs b/src/models/bgp/evpn.rs new file mode 100644 index 00000000..4c7550bf --- /dev/null +++ b/src/models/bgp/evpn.rs @@ -0,0 +1,157 @@ +//! Ethernet VPN (EVPN) NLRI and route fields - RFC 7432. +//! +//! EVPN is carried in the L2VPN address family ([`Afi::L2vpn`]) with the EVPN +//! subsequent address family ([`Safi::Evpn`]). Every NLRI starts with a route +//! type and a length in octets, followed by a route-distinguisher and a +//! type-specific body. +//! +//! References: +//! - RFC 7432: BGP MPLS-Based Ethernet VPN - route types 1 to 4, MAC Mobility +//! extended community (§7.2, §7.3, §7.7) +//! - RFC 8365: Network Virtualization Overlay Solution Using EVPN - VXLAN +//! encapsulation, where the label field carries the VXLAN Network Identifier +//! - RFC 9136: IP Prefix Advertisement in EVPN - route type 5 (§3.1) +//! +//! [`Afi::L2vpn`]: crate::models::Afi::L2vpn +//! [`Safi::Evpn`]: crate::models::Safi::Evpn + +use crate::models::RouteDistinguisher; +use num_enum::{FromPrimitive, IntoPrimitive}; +use std::net::IpAddr; + +/// EVPN route type - the first octet of every EVPN NLRI. +/// +/// Types 1 to 5 are defined by RFC 7432 and RFC 9136; anything else is kept as +/// [`EvpnRouteType::Unknown`] so that new route types do not fail parsing. +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, FromPrimitive, IntoPrimitive)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[repr(u8)] +pub enum EvpnRouteType { + /// Ethernet Auto-Discovery route - RFC 7432 §7.1 + EthernetAutoDiscovery = 1, + /// MAC/IP Advertisement route - RFC 7432 §7.2 + MacIpAdvertisement = 2, + /// Inclusive Multicast Ethernet Tag route - RFC 7432 §7.3 + InclusiveMulticastEthernetTag = 3, + /// Ethernet Segment route - RFC 7432 §7.4 + EthernetSegment = 4, + /// IP Prefix route - RFC 9136 §3.1 + IpPrefix = 5, + #[num_enum(catch_all)] + Unknown(u8), +} + +/// One EVPN NLRI entry (AFI 25 / SAFI 70). +#[derive(Debug, PartialEq, Eq, Clone)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct EvpnNlri { + /// ADD-PATH path identifier (RFC 7911); present when the session + /// negotiated ADD-PATH, `None` otherwise. + pub path_id: Option, + pub route_type: EvpnRouteType, + /// Route Distinguisher (8 octets), shared by every EVPN route type. + pub route_distinguisher: RouteDistinguisher, + pub payload: EvpnRoutePayload, +} + +/// Route-type-specific part of an EVPN NLRI. +#[derive(Debug, PartialEq, Eq, Clone)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum EvpnRoutePayload { + /// Route type 2 - RFC 7432 §7.2 + MacIpAdvertisement(MacIpAdvertisement), + /// Route type 3 - RFC 7432 §7.3 + InclusiveMulticast(InclusiveMulticastRoute), + /// Route type 5 - RFC 9136 §3.1 + IpPrefix(IpPrefixRoute), + /// Route types this parser does not decode yet (1 and 4 at the time of + /// writing). The octets after the route distinguisher are preserved, so + /// nothing is lost and the value survives a debug or JSON round trip. + Raw(Vec), +} + +/// MAC/IP Advertisement route body - RFC 7432 §7.2. +#[derive(Debug, PartialEq, Eq, Clone)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct MacIpAdvertisement { + /// Ethernet Segment Identifier (10 octets); all zero for a single-homed + /// host - RFC 7432 §5. + pub esi: [u8; 10], + /// Ethernet Tag ID (4 octets). + pub ethernet_tag_id: u32, + /// MAC address (6 octets); the route type fixes the length at 48 bits. + pub mac: [u8; 6], + /// IP address when the advertisement carries one; `None` when the IP + /// address length is zero, which is a MAC-only advertisement. + pub ip: Option, + /// Label1 as it appears on the wire: a 24-bit field. For VXLAN this *is* + /// the VNI, with no MPLS label semantics - RFC 8365 §5; an MPLS-signalled + /// fabric puts a label plus its TC/S/TTL bits here instead, see + /// [`MacIpAdvertisement::mpls_label`]. + pub raw_label: u32, + /// Optional Label2, same encoding as [`Self::raw_label`], present when the + /// route is used for IP-VRF forwarding - RFC 7432 §7.2. + pub raw_label2: Option, +} + +impl MacIpAdvertisement { + /// Interpret Label1 as an MPLS label: the high 20 bits are the label value + /// and the low 4 bits carry TC, S and TTL - RFC 7432 §7.2. + /// + /// A VXLAN fabric does not use MPLS label semantics; there the whole + /// 24-bit field is the VNI and this value is meaningless. + pub fn mpls_label(&self) -> crate::models::MplsLabel { + crate::models::MplsLabel::decode([ + (self.raw_label >> 16) as u8, + (self.raw_label >> 8) as u8, + self.raw_label as u8, + ]) + .0 + } +} + +/// Inclusive Multicast Ethernet Tag route body - RFC 7432 §7.3. +#[derive(Debug, PartialEq, Eq, Clone)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct InclusiveMulticastRoute { + /// Ethernet Tag ID (4 octets). + pub ethernet_tag_id: u32, + /// Originating router's IP address (4 or 16 octets). + pub originating_router_ip: IpAddr, +} + +/// IP Prefix route body - RFC 9136 §3.1. +/// +/// The wire format carries the Ethernet Segment Identifier like the other EVPN +/// route types, and the IP prefix and gateway address are always full width +/// (4 or 16 octets). The NLRI length, not the prefix length, tells IPv4 (34 +/// octets) from IPv6 (58). +#[derive(Debug, PartialEq, Eq, Clone)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct IpPrefixRoute { + /// Ethernet Segment Identifier (10 octets). + pub esi: [u8; 10], + /// Ethernet Tag ID (4 octets). + pub ethernet_tag_id: u32, + /// The advertised IP prefix; the prefix length is on the wire and the + /// address family follows from it. + pub ip_prefix: ipnet::IpNet, + /// Gateway IP address (4 or 16 octets, matching the prefix family). + pub gateway_ip: IpAddr, + /// The 24-bit label field: a VNI in a VXLAN fabric (RFC 8365 §5), or an + /// MPLS label with TC/S/TTL in the low bits, see + /// [`IpPrefixRoute::mpls_label`]. + pub raw_label: u32, +} + +impl IpPrefixRoute { + /// Interpret the label field as an MPLS label - RFC 7432 §7.2. + pub fn mpls_label(&self) -> crate::models::MplsLabel { + crate::models::MplsLabel::decode([ + (self.raw_label >> 16) as u8, + (self.raw_label >> 8) as u8, + self.raw_label as u8, + ]) + .0 + } +} diff --git a/src/models/bgp/mod.rs b/src/models/bgp/mod.rs index 868462d2..1b8858d5 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 evpn; 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 evpn::*; pub use flowspec::*; pub use linkstate::*; pub use role::*; diff --git a/src/models/network/afi.rs b/src/models/network/afi.rs index 244238c7..afb85a0d 100644 --- a/src/models/network/afi.rs +++ b/src/models/network/afi.rs @@ -11,6 +11,8 @@ use std::net::IpAddr; pub enum Afi { Ipv4 = 1, Ipv6 = 2, + /// Layer 2 VPN address family, used to carry EVPN - RFC 7432 + L2vpn = 25, /// BGP Link-State - RFC 7752 LinkState = 16388, } @@ -47,6 +49,8 @@ pub enum Safi { /// MPLS-labeled address - RFC 3107/8277 /// SAFI 4 for labeled unicast prefixes (not VPN) MplsLabel = 4, + /// BGP EVPN - RFC 7432 + Evpn = 70, /// BGP Link-State - RFC 7752 LinkState = 71, /// BGP Link-State VPN - RFC 7752 @@ -85,11 +89,14 @@ mod tests { fn test_afi_safi_repr() { assert_eq!(Afi::Ipv4 as u16, 1); assert_eq!(Afi::Ipv6 as u16, 2); + assert_eq!(Afi::L2vpn as u16, 25); assert_eq!(Afi::LinkState as u16, 16388); assert_eq!(Safi::Unicast as u8, 1); assert_eq!(Safi::Multicast as u8, 2); assert_eq!(Safi::UnicastMulticast as u8, 3); + // RFC 7432 EVPN SAFI value + assert_eq!(Safi::Evpn as u8, 70); // RFC 7752 Link-State SAFI values assert_eq!(Safi::LinkState as u8, 71); assert_eq!(Safi::LinkStateVpn as u8, 72); diff --git a/src/parser/bgp/attributes/attr_14_15_nlri.rs b/src/parser/bgp/attributes/attr_14_15_nlri.rs index ad3b0810..a4488873 100644 --- a/src/parser/bgp/attributes/attr_14_15_nlri.rs +++ b/src/parser/bgp/attributes/attr_14_15_nlri.rs @@ -5,7 +5,8 @@ use crate::parser::bgp::attributes::attr_03_next_hop::{encode_mp_next_hop, parse use crate::parser::bgp::attributes::attr_29_linkstate::parse_link_state_nlri; use crate::parser::{parse_nlri_list, ReadUtils}; use crate::ParserError; -use bytes::{BufMut, Bytes, BytesMut}; +use bytes::{Buf, BufMut, Bytes, BytesMut}; +use std::net::IpAddr; use log::warn; @@ -66,8 +67,22 @@ pub fn parse_nlri( } // Handle different NLRI types based on AFI/SAFI - let (prefixes, labeled_prefixes, link_state_nlris) = - if afi == Afi::LinkState && (safi == Safi::LinkState || safi == Safi::LinkStateVpn) { + let (prefixes, labeled_prefixes, link_state_nlris, evpn_nlris) = + if afi == Afi::L2vpn && safi == Safi::Evpn { + // EVPN NLRI - RFC 7432. Reachable NLRI carry the reserved octet + // after the next hop, exactly like the IP families. + if reachable && input.read_u8()? != 0 { + warn!("NLRI reserved byte not 0 (parsing EVPN NLRI)"); + } + let nlris = parse_evpn_nlri(&mut input, additional_paths)?; + (Vec::new(), None, None, Some(nlris)) + } else if afi == Afi::L2vpn || safi == Safi::Evpn { + // L2VPN with another SAFI, or EVPN with another AFI: not a family we + // can interpret, and not one to hand to the IP-prefix parser either. + return Err(ParserError::Unsupported(format!( + "unsupported address family combination {afi:?}/{safi:?}" + ))); + } else if afi == Afi::LinkState && (safi == Safi::LinkState || safi == Safi::LinkStateVpn) { // Parse Link-State NLRI if reachable { // skip reserved byte for reachable NRLI @@ -77,7 +92,7 @@ pub fn parse_nlri( } let ls_nlri = parse_link_state_nlri(input, afi, safi, next_hop, reachable)?; let link_state_list = ls_nlri.link_state_nlris; - (Vec::new(), None, link_state_list) + (Vec::new(), None, link_state_list, None) } else if safi == Safi::MplsLabel { // Parse MPLS-labeled NLRI (RFC 3107/8277) // Use MultiLabel mode as default since it handles both single and multiple labels @@ -95,11 +110,11 @@ pub fn parse_nlri( warn!("NLRI reserved byte not 0 (parsing MPLS-labeled NLRI)"); } let labeled = parse_labeled_nlri(&mut input, afi, &config)?; - (Vec::new(), Some(labeled), None) + (Vec::new(), Some(labeled), None, None) } else { // Parse labeled withdrawal (withdrawals use plain prefixes per RFC 8277 §2.4) let prefixes = parse_labeled_withdrawal_nlri(&mut input, afi, &config)?; - (prefixes, None, None) + (prefixes, None, None, None) } } else { // Parse traditional IP prefixes @@ -128,7 +143,7 @@ pub fn parse_nlri( parse_nlri_list(input, additional_paths, &afi)? } }; - (prefixes, None, None) + (prefixes, None, None, None) }; let nlri = Nlri { @@ -139,6 +154,7 @@ pub fn parse_nlri( labeled_prefixes, link_state_nlris, flowspec_nlris: None, + evpn_nlris, }; match reachable { @@ -147,6 +163,334 @@ pub fn parse_nlri( } } +/// Parse a sequence of EVPN NLRI entries - RFC 7432 §7. +/// +/// Every entry is a route type octet, a length octet, an 8-octet route +/// distinguisher and a route-type-specific body. With ADD-PATH (RFC 7911) a +/// 4-octet path identifier precedes each entry; the length excludes it. +fn parse_evpn_nlri( + input: &mut Bytes, + additional_paths: bool, +) -> Result, ParserError> { + let mut nlris = Vec::new(); + + while input.remaining() > 0 { + let path_id = if additional_paths { + Some(input.read_u32()?) + } else { + None + }; + + let route_type = EvpnRouteType::from(input.read_u8()?); + let body_len = input.read_u8()? as usize; + input.has_n_remaining(body_len)?; + let mut body = input.split_to(body_len); + + // The route distinguisher is common to every EVPN route type. + if body.remaining() < 8 { + return Err(ParserError::ParseError( + "EVPN NLRI shorter than a route distinguisher".to_string(), + )); + } + let mut rd = [0u8; 8]; + body.copy_to_slice(&mut rd); + let route_distinguisher = RouteDistinguisher(rd); + + let payload = match route_type { + EvpnRouteType::MacIpAdvertisement => { + EvpnRoutePayload::MacIpAdvertisement(parse_mac_ip_advertisement(&mut body)?) + } + EvpnRouteType::InclusiveMulticastEthernetTag => { + EvpnRoutePayload::InclusiveMulticast(parse_inclusive_multicast(&mut body)?) + } + EvpnRouteType::IpPrefix => { + EvpnRoutePayload::IpPrefix(parse_ip_prefix_route(&mut body)?) + } + // Route types 1 and 4 are accepted but not decoded yet; keep the + // octets so nothing is lost and the type stays visible. + _ => EvpnRoutePayload::Raw(body.to_vec()), + }; + + nlris.push(EvpnNlri { + path_id, + route_type, + route_distinguisher, + payload, + }); + } + + Ok(nlris) +} + +/// MAC/IP Advertisement route body - RFC 7432 §7.2. +fn parse_mac_ip_advertisement(body: &mut Bytes) -> Result { + // Fixed part, with the route distinguisher already consumed: + // ESI (10) | Ethernet tag (4) | MAC length (1) | MAC (6) | IP length (1) | + // Label1 (3). + if body.remaining() < 10 + 4 + 1 + 6 + 1 + 3 { + return Err(ParserError::ParseError( + "EVPN type 2 NLRI too short for the fixed fields".to_string(), + )); + } + + let mut esi = [0u8; 10]; + body.copy_to_slice(&mut esi); + let ethernet_tag_id = body.read_u32()?; + + let mac_len = body.read_u8()?; + if mac_len != 48 { + return Err(ParserError::ParseError(format!( + "EVPN type 2 MAC address length {mac_len} is not 48" + ))); + } + let mut mac = [0u8; 6]; + body.copy_to_slice(&mut mac); + + let ip_len = body.read_u8()?; + let ip = match ip_len { + 0 => None, + 32 => Some(IpAddr::V4(body.read_ipv4_address()?)), + 128 => Some(IpAddr::V6(body.read_ipv6_address()?)), + other => { + return Err(ParserError::ParseError(format!( + "EVPN type 2 IP address length {other} is not 0, 32 or 128" + ))) + } + }; + + let raw_label = read_three_octet_label(body)?; + + // Label2 is optional: it appears when the route is used for IP-VRF + // forwarding - RFC 7432 §7.2. + let raw_label2 = if body.remaining() == 3 { + Some(read_three_octet_label(body)?) + } else { + None + }; + + if body.remaining() != 0 { + return Err(ParserError::ParseError(format!( + "EVPN type 2 NLRI has {} trailing octets", + body.remaining() + ))); + } + + Ok(MacIpAdvertisement { + esi, + ethernet_tag_id, + mac, + ip, + raw_label, + raw_label2, + }) +} + +/// Inclusive Multicast Ethernet Tag route body - RFC 7432 §7.3. +fn parse_inclusive_multicast(body: &mut Bytes) -> Result { + if body.remaining() < 4 + 1 { + return Err(ParserError::ParseError( + "EVPN type 3 NLRI too short".to_string(), + )); + } + + let ethernet_tag_id = body.read_u32()?; + let ip_len = body.read_u8()?; + let originating_router_ip = match ip_len { + 32 => IpAddr::V4(body.read_ipv4_address()?), + 128 => IpAddr::V6(body.read_ipv6_address()?), + other => { + return Err(ParserError::ParseError(format!( + "EVPN type 3 originating router IP length {other} is not 32 or 128" + ))) + } + }; + + if body.remaining() != 0 { + return Err(ParserError::ParseError(format!( + "EVPN type 3 NLRI has {} trailing octets", + body.remaining() + ))); + } + + Ok(InclusiveMulticastRoute { + ethernet_tag_id, + originating_router_ip, + }) +} + +/// IP Prefix route body - RFC 9136 §3.1. +/// +/// Layout, with the route distinguisher already consumed: +/// `ESI (10) | Ethernet tag (4) | IP prefix length (1) | IP prefix (4 or 16) | +/// GW IP address (4 or 16) | MPLS label (3)`. The NLRI length identifies the +/// address family: 34 octets for IPv4 and 58 for IPv6, which leaves 26 or 50 +/// here. The prefix and gateway fields are full width, so a /32 IPv6 prefix is +/// still a 16-octet field. +fn parse_ip_prefix_route(body: &mut Bytes) -> Result { + let is_ipv6 = match body.len() { + 26 => false, + 50 => true, + other => { + return Err(ParserError::ParseError(format!( + "EVPN type 5 payload is {other} octets after the route distinguisher, not 26 (IPv4) or 50 (IPv6)" + ))) + } + }; + + let mut esi = [0u8; 10]; + body.copy_to_slice(&mut esi); + let ethernet_tag_id = body.read_u32()?; + + let prefix_len = body.read_u8()?; + let max_len = if is_ipv6 { 128 } else { 32 }; + if prefix_len > max_len { + return Err(ParserError::ParseError(format!( + "EVPN type 5 prefix length {prefix_len} is invalid for an {is_ipv6} prefix" + ))); + } + + let ip_prefix = if is_ipv6 { + let addr = body.read_ipv6_address()?; + ipnet::IpNet::new(addr.into(), prefix_len) + } else { + let addr = body.read_ipv4_address()?; + ipnet::IpNet::new(addr.into(), prefix_len) + } + .map_err(|e| ParserError::ParseError(format!("EVPN type 5 invalid prefix: {e}")))?; + + let gateway_ip = if is_ipv6 { + IpAddr::V6(body.read_ipv6_address()?) + } else { + IpAddr::V4(body.read_ipv4_address()?) + }; + let raw_label = read_three_octet_label(body)?; + + if body.remaining() != 0 { + return Err(ParserError::ParseError(format!( + "EVPN type 5 NLRI has {} trailing octets", + body.remaining() + ))); + } + + Ok(IpPrefixRoute { + esi, + ethernet_tag_id, + ip_prefix, + gateway_ip, + raw_label, + }) +} + +/// Encode the route-type-specific body of an EVPN NLRI - RFC 7432 §7. +/// +/// The payload variant has to agree with the route type: the wire format has one +/// type octet and one body, so a mismatch would be published as a route of the +/// wrong kind. +fn encode_evpn_payload(route: &EvpnNlri) -> Result, EncodingError> { + let payload = &route.payload; + let expected = match payload { + EvpnRoutePayload::MacIpAdvertisement(_) => EvpnRouteType::MacIpAdvertisement, + EvpnRoutePayload::InclusiveMulticast(_) => EvpnRouteType::InclusiveMulticastEthernetTag, + EvpnRoutePayload::IpPrefix(_) => EvpnRouteType::IpPrefix, + EvpnRoutePayload::Raw(_) => route.route_type, + }; + if expected != route.route_type { + return Err(EncodingError::unencodable( + "EVPN NLRI route type", + format!( + "route type {:?} does not match its {:?} payload", + route.route_type, expected + ), + )); + } + + let mut out = Vec::new(); + match payload { + EvpnRoutePayload::MacIpAdvertisement(body) => { + out.extend_from_slice(&body.esi); + out.extend_from_slice(&body.ethernet_tag_id.to_be_bytes()); + out.push(48); // MAC address length + out.extend_from_slice(&body.mac); + match body.ip { + None => out.push(0), + Some(IpAddr::V4(ip)) => { + out.push(32); + out.extend_from_slice(&ip.octets()); + } + Some(IpAddr::V6(ip)) => { + out.push(128); + out.extend_from_slice(&ip.octets()); + } + } + push_three_octet(&mut out, body.raw_label, "EVPN Label1")?; + if let Some(label2) = body.raw_label2 { + push_three_octet(&mut out, label2, "EVPN Label2")?; + } + } + EvpnRoutePayload::InclusiveMulticast(body) => { + out.extend_from_slice(&body.ethernet_tag_id.to_be_bytes()); + match body.originating_router_ip { + IpAddr::V4(ip) => { + out.push(32); + out.extend_from_slice(&ip.octets()); + } + IpAddr::V6(ip) => { + out.push(128); + out.extend_from_slice(&ip.octets()); + } + } + } + EvpnRoutePayload::IpPrefix(body) => { + out.extend_from_slice(&body.esi); + out.extend_from_slice(&body.ethernet_tag_id.to_be_bytes()); + out.push(body.ip_prefix.prefix_len()); + match (&body.ip_prefix, body.gateway_ip) { + (ipnet::IpNet::V4(net), IpAddr::V4(gateway)) => { + out.extend_from_slice(&net.addr().octets()); + out.extend_from_slice(&gateway.octets()); + } + (ipnet::IpNet::V6(net), IpAddr::V6(gateway)) => { + out.extend_from_slice(&net.addr().octets()); + out.extend_from_slice(&gateway.octets()); + } + _ => { + return Err(EncodingError::unencodable( + "EVPN IP prefix route", + "the prefix and the gateway address must be of the same family", + )) + } + } + push_three_octet(&mut out, body.raw_label, "EVPN MPLS label")?; + } + // Undecoded route types are written back exactly as they were read. + EvpnRoutePayload::Raw(bytes) => out.extend_from_slice(bytes), + } + Ok(out) +} + +/// Append a value as the 3-octet label field EVPN uses. +fn push_three_octet( + out: &mut Vec, + value: u32, + field: &'static str, +) -> Result<(), EncodingError> { + if value > 0x00FF_FFFF { + return Err(EncodingError::unencodable( + field, + format!("{value} does not fit 3 octets"), + )); + } + out.extend_from_slice(&[(value >> 16) as u8, (value >> 8) as u8, value as u8]); + Ok(()) +} + +/// Read the 3-octet label field shared by EVPN route types 2 and 5. +fn read_three_octet_label(body: &mut Bytes) -> Result { + body.has_n_remaining(3)?; + let octets = body.split_to(3); + Ok(u32::from_be_bytes([0, octets[0], octets[1], octets[2]])) +} + /// Encode NLRI attribute to wire format. /// /// # Arguments @@ -160,6 +504,27 @@ pub fn encode_nlri( add_path: bool, bytes: &mut BytesMut, ) -> Result<(), EncodingError> { + // An EVPN MP_REACH always carries the VTEP as next hop, and an MP_UNREACH + // never carries one. Either mismatch would produce a header a receiver + // decodes into something else, so reject it before writing a byte. + if nlri.afi == Afi::L2vpn { + match (reachable, nlri.next_hop) { + (true, None) => { + return Err(EncodingError::unencodable( + "EVPN NLRI next hop", + "an EVPN announcement needs the originating VTEP as next hop", + )) + } + (false, Some(_)) => { + return Err(EncodingError::unencodable( + "EVPN NLRI next hop", + "an EVPN withdrawal carries no next hop", + )) + } + _ => {} + } + } + // encode address family bytes.put_u16(nlri.afi as u16); bytes.put_u8(nlri.safi as u8); @@ -174,8 +539,52 @@ pub fn encode_nlri( put_u8_len_slice(bytes, "MP NLRI next hop length", &next_hop_bytes)?; } - // Handle MPLS-labeled NLRI encoding (SAFI 4 per RFC 3107/8277) - if nlri.safi == Safi::MplsLabel { + // EVPN NLRI - RFC 7432 §7: a sequence of route type, length, route + // distinguisher and route-type-specific body. + if nlri.afi == Afi::L2vpn && nlri.safi == Safi::Evpn { + // RFC 4760 §3: the reserved octet precedes reachable NLRI. + if reachable { + bytes.put_u8(0); + } + for route in nlri.evpn_nlris.iter().flatten() { + match (add_path, route.path_id) { + (true, Some(path_id)) => bytes.put_u32(path_id), + (true, None) => { + return Err(EncodingError::unencodable( + "EVPN NLRI path id", + "ADD-PATH is requested but the route carries no path identifier", + )) + } + (false, Some(_)) => { + return Err(EncodingError::unencodable( + "EVPN NLRI path id", + "the route carries a path identifier but ADD-PATH is not enabled", + )) + } + (false, None) => {} + } + let body = encode_evpn_payload(route)?; + // The length covers the route distinguisher and the body, and + // excludes the ADD-PATH identifier. + let entry_len = 8 + body.len(); + if entry_len > u8::MAX as usize { + return Err(EncodingError::unencodable( + "EVPN NLRI length", + format!("{entry_len} octets do not fit the 1-octet length field"), + )); + } + bytes.put_u8(u8::from(route.route_type)); + bytes.put_u8(entry_len as u8); + bytes.put_slice(&route.route_distinguisher.0); + bytes.extend_from_slice(&body); + } + } else if nlri.afi == Afi::L2vpn { + // L2VPN is only defined with the EVPN subsequent address family here. + return Err(EncodingError::unencodable( + "MP NLRI", + "L2VPN NLRI require the EVPN subsequent address family", + )); + } else if nlri.safi == Safi::MplsLabel { // RFC 8277: Write reserved byte for reachable NLRI if reachable { bytes.put_u8(0); @@ -377,6 +786,7 @@ mod tests { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, }; let mut buf = BytesMut::new(); encode_nlri(&nlri, true, false, &mut buf).unwrap(); @@ -410,6 +820,7 @@ mod tests { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, }; let mut buf = BytesMut::new(); encode_nlri(&nlri, true, true, &mut buf).unwrap(); @@ -471,6 +882,7 @@ mod tests { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, }; let mut buf = BytesMut::new(); encode_nlri(&nlri, false, false, &mut buf).unwrap(); @@ -506,6 +918,7 @@ mod tests { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, }; let mut buf = BytesMut::new(); encode_nlri(&nlri_with_next_hop, false, false, &mut buf).unwrap(); @@ -526,3 +939,500 @@ mod tests { ); } } + +#[cfg(test)] +mod evpn_tests { + use super::*; + use std::str::FromStr; + + /// Wrap EVPN NLRI octets in an MP_REACH_NLRI payload with next hop 10.0.0.1. + fn reach(nlri: Vec) -> Bytes { + let mut bytes = vec![ + 0x00, 0x19, // AFI 25 (L2VPN) + 0x46, // SAFI 70 (EVPN) + 0x04, 0x0a, 0x00, 0x00, 0x01, // next hop 10.0.0.1 + 0x00, // reserved + ]; + bytes.extend(nlri); + Bytes::from(bytes) + } + + /// Wrap EVPN NLRI octets in an MP_UNREACH_NLRI payload. + fn unreach(nlri: Vec) -> Bytes { + let mut bytes = vec![0x00, 0x19, 0x46]; + bytes.extend(nlri); + Bytes::from(bytes) + } + + fn mac_ip_nlri(ip_length: u8, ip_bytes: &[u8]) -> Vec { + let body_len = 8 + 10 + 4 + 1 + 6 + 1 + ip_bytes.len() + 3; + let mut nlri = vec![0x02, body_len as u8]; + nlri.extend_from_slice(&[0x00, 0x01, 10, 10, 0, 11, 0, 2]); // RD 10.10.0.11:2 + nlri.extend_from_slice(&[0u8; 10]); // ESI + nlri.extend_from_slice(&[0, 0, 0, 100]); // ethernet tag + nlri.extend_from_slice(&[0x30]); // MAC length 48 + nlri.extend_from_slice(&[0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]); + nlri.push(ip_length); + nlri.extend_from_slice(ip_bytes); + nlri.extend_from_slice(&[0x00, 0x00, 0x64]); // label 100 + nlri + } + + #[test] + fn parses_mac_ip_route_with_ipv4() { + let res = parse_nlri( + reach(mac_ip_nlri(32, &[192, 0, 2, 10])), + &None, + &None, + &None, + true, + false, + ); + let Ok(AttributeValue::MpReachNlri(nlri)) = res else { + panic!("expected MP_REACH_NLRI, got {res:?}"); + }; + assert_eq!(nlri.afi, Afi::L2vpn); + assert_eq!(nlri.safi, Safi::Evpn); + assert!(nlri.is_evpn()); + assert_eq!( + nlri.next_hop, + Some(NextHopAddress::Ipv4("10.0.0.1".parse().unwrap())) + ); + + let routes = nlri.evpn_nlris.expect("EVPN NLRI"); + assert_eq!(routes.len(), 1); + assert_eq!(routes[0].route_type, EvpnRouteType::MacIpAdvertisement); + assert_eq!(routes[0].route_distinguisher.0, [0, 1, 10, 10, 0, 11, 0, 2]); + let EvpnRoutePayload::MacIpAdvertisement(body) = &routes[0].payload else { + panic!("expected a MAC/IP advertisement"); + }; + assert_eq!(body.esi, [0u8; 10]); + assert_eq!(body.ethernet_tag_id, 100); + assert_eq!(body.mac, [0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]); + assert_eq!(body.ip, Some("192.0.2.10".parse().unwrap())); + assert_eq!(body.raw_label, 100); + } + + #[test] + fn parses_mac_ip_route_with_ipv6() { + let ip: std::net::Ipv6Addr = "2001:db8::1".parse().unwrap(); + let res = parse_nlri( + reach(mac_ip_nlri(128, &ip.octets())), + &None, + &None, + &None, + true, + false, + ); + let Ok(AttributeValue::MpReachNlri(nlri)) = res else { + panic!("expected MP_REACH_NLRI, got {res:?}"); + }; + let routes = nlri.evpn_nlris.expect("EVPN NLRI"); + let EvpnRoutePayload::MacIpAdvertisement(body) = &routes[0].payload else { + panic!("expected a MAC/IP advertisement"); + }; + assert_eq!(body.ip, Some(std::net::IpAddr::V6(ip))); + } + + #[test] + fn parses_implicit_route() { + let mut nlri = vec![0x03, 0x11]; + nlri.extend_from_slice(&[0x00, 0x01, 10, 10, 0, 11, 0, 2]); // RD + nlri.extend_from_slice(&[0, 0, 0, 100]); // ethernet tag + nlri.push(32); // originating router IP length + nlri.extend_from_slice(&[10, 10, 0, 11]); + + let res = parse_nlri(reach(nlri), &None, &None, &None, true, false); + let Ok(AttributeValue::MpReachNlri(parsed)) = res else { + panic!("expected MP_REACH_NLRI, got {res:?}"); + }; + let routes = parsed.evpn_nlris.expect("EVPN NLRI"); + assert_eq!( + routes[0].route_type, + EvpnRouteType::InclusiveMulticastEthernetTag + ); + let EvpnRoutePayload::InclusiveMulticast(body) = &routes[0].payload else { + panic!("expected an IMET route"); + }; + assert_eq!(body.ethernet_tag_id, 100); + assert_eq!( + body.originating_router_ip, + "10.10.0.11".parse::().unwrap() + ); + } + + #[test] + fn parses_ip_prefix_route() { + // RFC 9136 §3.1: RD | ESI | Ethernet tag | prefix length | prefix (4) | + // gateway (4) | label, 34 octets in total for IPv4. + let mut nlri = vec![0x05, 0x22]; + nlri.extend_from_slice(&[0x00, 0x01, 10, 10, 0, 12, 0, 2]); // RD + nlri.extend_from_slice(&[0u8; 10]); // ESI + nlri.extend_from_slice(&[0, 0, 0, 0]); // ethernet tag + nlri.push(24); // prefix length + nlri.extend_from_slice(&[198, 51, 100, 0]); // 198.51.100.0/24, full width + nlri.extend_from_slice(&[0, 0, 0, 0]); // gateway IP + nlri.extend_from_slice(&[0, 0, 0x64]); // label 100 + + let res = parse_nlri(reach(nlri), &None, &None, &None, true, false); + let Ok(AttributeValue::MpReachNlri(parsed)) = res else { + panic!("expected MP_REACH_NLRI, got {res:?}"); + }; + let routes = parsed.evpn_nlris.expect("EVPN NLRI"); + assert_eq!(routes[0].route_type, EvpnRouteType::IpPrefix); + let EvpnRoutePayload::IpPrefix(body) = &routes[0].payload else { + panic!("expected an IP prefix route"); + }; + assert_eq!(body.esi, [0u8; 10]); + assert_eq!( + body.ip_prefix, + ipnet::IpNet::from_str("198.51.100.0/24").unwrap() + ); + assert_eq!(body.gateway_ip, "0.0.0.0".parse::().unwrap()); + assert_eq!(body.raw_label, 100); + } + + #[test] + fn parses_ipv6_ip_prefix_route_shorter_than_slash_32() { + // A /20 IPv6 prefix still carries 16-octet prefix and gateway fields; + // the family comes from the NLRI length, not from the prefix length. + let mut nlri = vec![0x05, 0x3a]; + nlri.extend_from_slice(&[0x00, 0x01, 10, 10, 0, 12, 0, 2]); // RD + nlri.extend_from_slice(&[0u8; 10]); // ESI + nlri.extend_from_slice(&[0, 0, 0, 0]); // ethernet tag + nlri.push(20); // prefix length + nlri.extend_from_slice(&[0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + nlri.extend_from_slice(&[0u8; 16]); // gateway IP + nlri.extend_from_slice(&[0, 0, 0x64]); // label 100 + + let res = parse_nlri(reach(nlri), &None, &None, &None, true, false); + let Ok(AttributeValue::MpReachNlri(parsed)) = res else { + panic!("expected MP_REACH_NLRI, got {res:?}"); + }; + let routes = parsed.evpn_nlris.expect("EVPN NLRI"); + let EvpnRoutePayload::IpPrefix(body) = &routes[0].payload else { + panic!("expected an IP prefix route"); + }; + assert_eq!( + body.ip_prefix, + ipnet::IpNet::from_str("2001:db8::/20").unwrap() + ); + assert_eq!(body.gateway_ip, "::".parse::().unwrap()); + } + + #[test] + fn rejects_ip_prefix_route_with_the_wrong_length() { + // 26 octets after the route distinguisher is neither 34 nor 58 in total. + let mut nlri = vec![0x05, 0x1a]; + nlri.extend_from_slice(&[0x00, 0x01, 10, 10, 0, 12, 0, 2]); // RD + nlri.extend_from_slice(&[0u8; 18]); + + let res = parse_nlri(reach(nlri), &None, &None, &None, true, false); + assert!( + res.is_err(), + "a type 5 route of the wrong length must not parse" + ); + } + + #[test] + fn parses_optional_second_label() { + // MAC/IP advertisement used for IP-VRF forwarding carries Label2 too. + let mut body = mac_ip_nlri(32, &[192, 0, 2, 10]); + let label2 = [0x00, 0x00, 0x2a]; + body[1] += 3; // body length + body.extend_from_slice(&label2); + + let res = parse_nlri(reach(body), &None, &None, &None, true, false); + let Ok(AttributeValue::MpReachNlri(parsed)) = res else { + panic!("expected MP_REACH_NLRI, got {res:?}"); + }; + let routes = parsed.evpn_nlris.expect("EVPN NLRI"); + let EvpnRoutePayload::MacIpAdvertisement(route) = &routes[0].payload else { + panic!("expected a MAC/IP advertisement"); + }; + assert_eq!(route.raw_label, 100); + assert_eq!(route.raw_label2, Some(42)); + } + + #[test] + fn rejects_a_mac_address_that_does_not_fit() { + // The fixed-field check passes, but the body ends where the MAC should + // start: this must be an error, never a panic. + let mut nlri = vec![0x02, 0x17]; + nlri.extend_from_slice(&[0x00, 0x01, 10, 10, 0, 12, 0, 2]); // RD + nlri.extend_from_slice(&[0u8; 10]); // ESI + nlri.extend_from_slice(&[0, 0, 0, 0]); // ethernet tag + nlri.push(48); // MAC length 48, no MAC bytes follow + + let res = parse_nlri(reach(nlri), &None, &None, &None, true, false); + assert!(res.is_err(), "a truncated MAC must be a parse error"); + } + + #[test] + fn keeps_the_add_path_identifier() { + let mut nlri = vec![0x00, 0x00, 0x00, 0x07]; // path id 7 + nlri.extend_from_slice(&mac_ip_nlri(0, &[])); + + let res = parse_nlri(reach(nlri), &None, &None, &None, true, true); + let Ok(AttributeValue::MpReachNlri(parsed)) = res else { + panic!("expected MP_REACH_NLRI, got {res:?}"); + }; + let routes = parsed.evpn_nlris.expect("EVPN NLRI"); + assert_eq!(routes[0].path_id, Some(7)); + } + + #[test] + fn rejects_families_that_mix_l2vpn_or_evpn_with_something_else() { + // AFI 1 with SAFI 70 would otherwise be read as IPv4 prefixes. + let bytes = Bytes::from(vec![0x00, 0x01, 0x46, 0x00]); + let res = parse_nlri(bytes, &None, &None, &None, false, false); + assert!(res.is_err(), "ipv4/evpn must not be parsed as prefixes"); + + // AFI 25 with SAFI 1 is not a family this parser knows either. + let bytes = Bytes::from(vec![0x00, 0x19, 0x01, 0x00]); + let res = parse_nlri(bytes, &None, &None, &None, false, false); + assert!(res.is_err(), "l2vpn/unicast must not be parsed as prefixes"); + } + + #[test] + fn keeps_undecoded_route_types_as_raw_bytes() { + // Route type 6 does not exist today; the bytes after the RD survive. + let mut nlri = vec![0x06, 0x0a]; + nlri.extend_from_slice(&[0x00, 0x01, 10, 10, 0, 12, 0, 2]); + nlri.extend_from_slice(&[0xde, 0xad]); + + let res = parse_nlri(reach(nlri), &None, &None, &None, true, false); + let Ok(AttributeValue::MpReachNlri(parsed)) = res else { + panic!("expected MP_REACH_NLRI, got {res:?}"); + }; + let routes = parsed.evpn_nlris.expect("EVPN NLRI"); + assert_eq!(routes[0].route_type, EvpnRouteType::Unknown(6)); + assert_eq!(routes[0].payload, EvpnRoutePayload::Raw(vec![0xde, 0xad])); + } + + #[test] + fn parses_withdrawals_and_end_of_rib() { + let res = parse_nlri( + unreach(mac_ip_nlri(0, &[])), + &None, + &None, + &None, + false, + false, + ); + let Ok(AttributeValue::MpUnreachNlri(parsed)) = res else { + panic!("expected MP_UNREACH_NLRI, got {res:?}"); + }; + assert_eq!(parsed.next_hop, None); + let routes = parsed.evpn_nlris.expect("EVPN NLRI"); + assert_eq!(routes.len(), 1); + + // End-of-RIB for EVPN: the address family with no NLRI at all. + let res = parse_nlri(unreach(vec![]), &None, &None, &None, false, false); + let Ok(AttributeValue::MpUnreachNlri(parsed)) = res else { + panic!("expected MP_UNREACH_NLRI, got {res:?}"); + }; + assert_eq!(parsed.evpn_nlris, Some(vec![])); + } + + #[test] + fn evpn_nlri_round_trips_through_the_encoder() { + let wire = reach(mac_ip_nlri(32, &[192, 0, 2, 10])); + let Ok(AttributeValue::MpReachNlri(parsed)) = + parse_nlri(wire.clone(), &None, &None, &None, true, false) + else { + panic!("expected MP_REACH_NLRI"); + }; + + let mut buf = BytesMut::new(); + encode_nlri(&parsed, true, false, &mut buf).expect("EVPN encoding"); + let encoded = buf.freeze(); + + assert_eq!(encoded, wire, "encoding reproduces the wire bytes"); + let again = parse_nlri(encoded, &None, &None, &None, true, false).unwrap(); + assert_eq!(again, AttributeValue::MpReachNlri(parsed)); + } + + #[test] + fn evpn_type_5_round_trips_through_the_encoder() { + let mut nlri = vec![0x05, 0x22]; + nlri.extend_from_slice(&[0x00, 0x01, 10, 10, 0, 12, 0, 2]); // RD + nlri.extend_from_slice(&[0u8; 10]); // ESI + nlri.extend_from_slice(&[0, 0, 0, 0]); // ethernet tag + nlri.push(24); // prefix length + nlri.extend_from_slice(&[198, 51, 100, 0]); + nlri.extend_from_slice(&[0, 0, 0, 0]); + nlri.extend_from_slice(&[0, 0, 0x64]); // label 100 + let wire = reach(nlri); + + let Ok(AttributeValue::MpReachNlri(parsed)) = + parse_nlri(wire.clone(), &None, &None, &None, true, false) + else { + panic!("expected MP_REACH_NLRI"); + }; + let mut buf = BytesMut::new(); + encode_nlri(&parsed, true, false, &mut buf).unwrap(); + assert_eq!(buf.freeze(), wire); + } + + #[test] + fn evpn_add_path_round_trips_preserving_the_path_id() { + let mut nlri = vec![0x00, 0x00, 0x00, 0x07]; // path id + nlri.extend_from_slice(&mac_ip_nlri(0, &[])); + let wire = reach(nlri); + + let Ok(AttributeValue::MpReachNlri(parsed)) = + parse_nlri(wire.clone(), &None, &None, &None, true, true) + else { + panic!("expected MP_REACH_NLRI"); + }; + assert_eq!( + parsed.evpn_nlris.as_ref().and_then(|r| r[0].path_id), + Some(7) + ); + + let mut buf = BytesMut::new(); + encode_nlri(&parsed, true, true, &mut buf).unwrap(); + assert_eq!(buf.freeze(), wire); + + // Without ADD-PATH the identifier would be read as a route type. + let mut buf = BytesMut::new(); + let err = encode_nlri(&parsed, true, false, &mut buf) + .expect_err("ADD-PATH state and path identifiers must agree"); + assert!(format!("{err:?}").contains("path identifier")); + } + + #[test] + fn rejects_trailing_octets_in_an_implicit_route() { + let mut nlri = vec![0x03, 0x13]; + nlri.extend_from_slice(&[0x00, 0x01, 10, 10, 0, 11, 0, 2]); // RD + nlri.extend_from_slice(&[0, 0, 0, 100]); // ethernet tag + nlri.push(32); + nlri.extend_from_slice(&[10, 10, 0, 11]); + nlri.extend_from_slice(&[0xde, 0xad]); // trailing junk + + let res = parse_nlri(reach(nlri), &None, &None, &None, true, false); + assert!(res.is_err(), "trailing octets must not be dropped silently"); + } + + #[test] + fn refuses_evpn_next_hop_states_that_do_not_exist_on_the_wire() { + let route = EvpnNlri { + path_id: None, + route_type: EvpnRouteType::MacIpAdvertisement, + route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 11, 0, 2]), + payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement { + esi: [0; 10], + ethernet_tag_id: 0, + mac: [0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff], + ip: None, + raw_label: 100, + raw_label2: None, + }), + }; + + // An announcement without a VTEP would omit the next-hop length. + let announcement = Nlri::new_evpn_reachable(None, vec![route.clone()]); + let mut buf = BytesMut::new(); + let err = encode_nlri(&announcement, true, false, &mut buf) + .expect_err("a reachable EVPN NLRI needs a next hop"); + assert!(format!("{err:?}").contains("next hop"), "{err:?}"); + assert!(buf.is_empty(), "nothing is written before the refusal"); + + // A withdrawal with a next hop would write a field MP_UNREACH lacks. + let withdrawal = Nlri::new_evpn_reachable(Some("10.10.0.11".parse().unwrap()), vec![route]); + let mut buf = BytesMut::new(); + let err = encode_nlri(&withdrawal, false, false, &mut buf) + .expect_err("an EVPN withdrawal carries no next hop"); + assert!(format!("{err:?}").contains("no next hop"), "{err:?}"); + } + + #[test] + fn refuses_a_route_type_that_disagrees_with_its_payload() { + let route = EvpnNlri { + path_id: None, + // Type 5 with a type 2 body: the header would advertise a family the + // body does not describe. + route_type: EvpnRouteType::IpPrefix, + route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 11, 0, 2]), + payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement { + esi: [0; 10], + ethernet_tag_id: 0, + mac: [0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff], + ip: None, + raw_label: 100, + raw_label2: None, + }), + }; + let nlri = Nlri::new_evpn_reachable(Some("10.10.0.11".parse().unwrap()), vec![route]); + let mut buf = BytesMut::new(); + let err = encode_nlri(&nlri, true, false, &mut buf) + .expect_err("the route type and payload must agree"); + assert!(format!("{err:?}").contains("route type"), "{err:?}"); + } + + #[test] + fn the_attribute_encoder_keeps_add_path_state_for_evpn() { + // The public path infers ADD-PATH from the routes, for announcements + // and withdrawals alike. + let route = EvpnNlri { + path_id: Some(7), + route_type: EvpnRouteType::MacIpAdvertisement, + route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 12, 0, 2]), + payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement { + esi: [0; 10], + ethernet_tag_id: 0, + mac: [0xaa, 0xc1, 0xab, 0x73, 0x01, 0x4d], + ip: None, + raw_label: 100, + raw_label2: None, + }), + }; + + let announced = AttributeValue::MpReachNlri(Nlri::new_evpn_reachable( + Some("10.10.0.12".parse().unwrap()), + vec![route.clone()], + )); + let mut buf = BytesMut::new(); + Attribute { + value: announced, + flag: AttrFlags::OPTIONAL, + } + .encode_to(AsnLength::Bits32, &mut buf) + .expect("an ADD-PATH EVPN announcement encodes"); + // attribute header, then AFI/SAFI, next hop, reserved octet, path id + assert!( + buf.windows(4) + .any(|window| window == [0x00, 0x00, 0x00, 0x07]), + "the path identifier is on the wire" + ); + + let withdrawn = AttributeValue::MpUnreachNlri(Nlri::new_evpn_unreachable(vec![route])); + let mut buf = BytesMut::new(); + Attribute { + value: withdrawn, + flag: AttrFlags::OPTIONAL, + } + .encode_to(AsnLength::Bits32, &mut buf) + .expect("an ADD-PATH EVPN withdrawal encodes"); + assert!( + buf.windows(4) + .any(|window| window == [0x00, 0x00, 0x00, 0x07]), + "the path identifier survives a withdrawal" + ); + } + + #[test] + fn truncated_evpn_nlri_is_an_error() { + // Type 2 with a body that ends before the MAC address. + let res = parse_nlri( + reach(vec![0x02, 0x08, 0, 1, 10, 10, 0, 11, 0, 2]), + &None, + &None, + &None, + true, + false, + ); + assert!(res.is_err(), "a truncated route must not parse"); + } +} diff --git a/src/parser/bgp/attributes/attr_16_25_extended_communities.rs b/src/parser/bgp/attributes/attr_16_25_extended_communities.rs index 891fec2a..fd776508 100644 --- a/src/parser/bgp/attributes/attr_16_25_extended_communities.rs +++ b/src/parser/bgp/attributes/attr_16_25_extended_communities.rs @@ -177,6 +177,32 @@ pub fn parse_extended_community(mut input: Bytes) -> Result { + let sub_type = input.read_u8()?; + match sub_type { + // MAC Mobility - RFC 7432 §7.7 + 0x00 => { + let flags = input.read_u8()?; + // Reserved octet, sent as zero and ignored on receipt. + input.read_u8()?; + let sequence = input.read_u32()?; + ExtendedCommunity::MacMobility(MacMobility { + sticky: flags & 0x01 != 0, + sequence, + }) + } + // Other EVPN sub-types (ESI Label, ES-Import Route Target, + // Router's MAC, Layer 2 Attributes, E-Tree, Default Gateway, + // ARP/ND) and anything newer keep their octets verbatim. + _ => { + let mut buffer: [u8; 8] = [0; 8]; + buffer[0] = ec_type_u8; + buffer[1] = sub_type; + input.read_exact(&mut buffer[2..])?; + ExtendedCommunity::Raw(buffer) + } + } + } ExtendedCommunityType::Unknown(_) => { let mut buffer: [u8; 8] = [0; 8]; buffer[0] = ec_type_u8; @@ -296,6 +322,13 @@ pub fn encode_extended_communities(communities: &Vec) -> Byte bytes.put_u16(link_bandwidth.global_admin); bytes.put_f32(link_bandwidth.bandwidth); } + ExtendedCommunity::MacMobility(mobility) => { + bytes.put_u8(ec_type); + bytes.put_u8(0x00); // MAC Mobility subtype + bytes.put_u8(u8::from(mobility.sticky)); + bytes.put_u8(0); // reserved + bytes.put_u32(mobility.sequence); + } ExtendedCommunity::Raw(raw) => { bytes.put_slice(raw); } @@ -328,6 +361,61 @@ mod tests { // TransitiveFourOctetAsSpecific = 0x02, // TransitiveOpaque = 0x03, + #[test] + fn test_parse_mac_mobility() { + // MAC Mobility, sequence 7, sticky flag clear - RFC 7432 §7.7 + let data: Vec = vec![0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07]; + if let AttributeValue::ExtendedCommunities(communities) = + parse_extended_community(Bytes::from(data)).unwrap() + { + assert_eq!(communities.len(), 1); + assert_eq!( + communities[0], + ExtendedCommunity::MacMobility(MacMobility { + sticky: false, + sequence: 7 + }) + ); + } else { + panic!("expected extended communities"); + } + + // Sticky bit set in the flags octet. + let data: Vec = vec![0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00]; + if let AttributeValue::ExtendedCommunities(communities) = + parse_extended_community(Bytes::from(data)).unwrap() + { + assert_eq!( + communities[0], + ExtendedCommunity::MacMobility(MacMobility { + sticky: true, + sequence: 256 + }) + ); + } + + // Other EVPN sub-types stay raw, with type and sub-type preserved: + // 0x0c is the Encapsulation extended community, VXLAN tunnel type 8. + let data: Vec = vec![0x06, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08]; + let expected: [u8; 8] = data.clone().try_into().unwrap(); + if let AttributeValue::ExtendedCommunities(communities) = + parse_extended_community(Bytes::from(data)).unwrap() + { + assert_eq!(communities[0], ExtendedCommunity::Raw(expected)); + } + + // The MAC Mobility community round-trips through the encoder. + let community = ExtendedCommunity::MacMobility(MacMobility { + sticky: true, + sequence: 42, + }); + let encoded = encode_extended_communities(&vec![community]); + assert_eq!( + &encoded[..], + &[0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 42] + ); + } + #[test] fn test_parse_extended_communities_two_octet_as() { // test Transitive Two Octet AS Specific diff --git a/src/parser/bgp/attributes/attr_36_domain_path.rs b/src/parser/bgp/attributes/attr_36_domain_path.rs index d5c3b61e..e11359ec 100644 --- a/src/parser/bgp/attributes/attr_36_domain_path.rs +++ b/src/parser/bgp/attributes/attr_36_domain_path.rs @@ -392,8 +392,7 @@ mod tests { #[test] fn test_domain_path_with_evpn_mp_reach_is_not_flagged() { - // EVPN is AFI 25 with SAFI 70: the NLRI do not decode yet, but the header still - // identifies a family D-PATH is allowed on + // EVPN is AFI 25 with SAFI 70, a family D-PATH is allowed on. let mut wire = DPATH.to_vec(); wire.extend(mp_reach(&[ 0x00, 0x19, // AFI: L2VPN (25) @@ -417,8 +416,8 @@ mod tests { #[test] fn test_domain_path_with_mismatched_evpn_safi_is_flagged() { - // SAFI 70 is EVPN only together with AFI 25, so this combination stays unsupported - // even though the MP_REACH attribute itself does not decode + // SAFI 70 is EVPN only together with AFI 25, so this combination is not + // a supported family. let mut wire = DPATH.to_vec(); wire.extend(mp_reach(&[ 0x00, 0x02, // AFI: IPv6 diff --git a/src/parser/bgp/attributes/mod.rs b/src/parser/bgp/attributes/mod.rs index 20cee34e..6c740219 100644 --- a/src/parser/bgp/attributes/mod.rs +++ b/src/parser/bgp/attributes/mod.rs @@ -618,6 +618,20 @@ pub fn parse_attributes( }) } +/// Whether any route in this NLRI carries an ADD-PATH identifier (RFC 7911). +/// +/// The wire format has no flag for it: the encoder has to infer the state from +/// the routes themselves, exactly as a decoder is told the state out of band. +fn has_path_id(nlri: &Nlri) -> bool { + nlri.labeled_prefixes + .as_ref() + .is_some_and(|prefixes| prefixes.iter().any(|p| p.path_id.is_some())) + || nlri + .evpn_nlris + .as_ref() + .is_some_and(|routes| routes.iter().any(|r| r.path_id.is_some())) +} + impl Attribute { /// Append the wire representation of this attribute to `buf`. /// @@ -668,16 +682,13 @@ impl Attribute { } AttributeValue::Clusters(v) => b.put_slice(&encode_clusters(v)), AttributeValue::MpReachNlri(v) => { - // Infer ADD-PATH from presence of path_id in any labeled prefix - let add_path = v - .labeled_prefixes - .as_ref() - .is_some_and(|prefixes| prefixes.iter().any(|p| p.path_id.is_some())); - encode_nlri(v, true, add_path, b)?; + encode_nlri(v, true, has_path_id(v), b)?; } AttributeValue::MpUnreachNlri(v) => { - // Withdrawals don't use ADD-PATH encoding per RFC 8277 - encode_nlri(v, false, false, b)?; + // Labeled withdrawals carry plain prefixes (RFC 8277 §2.4), + // but an EVPN withdrawal still carries its ADD-PATH + // identifier, so the state follows the NLRI either way. + encode_nlri(v, false, has_path_id(v), b)?; } AttributeValue::LinkState(v) => encode_link_state_attribute(v, b)?, AttributeValue::TunnelEncapsulation(v) => { diff --git a/src/parser/bgp/messages.rs b/src/parser/bgp/messages.rs index a205d89c..62351226 100644 --- a/src/parser/bgp/messages.rs +++ b/src/parser/bgp/messages.rs @@ -702,7 +702,9 @@ impl BgpUpdateMessage { // has only one attribute, check if it is withdrawal attribute if let AttributeValue::MpUnreachNlri(nlri) = &self.attributes.inner.first().unwrap().value { - if nlri.prefixes.is_empty() { + // Every family's collection has to be empty: an EVPN withdrawal + // carries its routes in `evpn_nlris`, not in `prefixes`. + if nlri.is_empty() { // the only attribute is MP_UNREACH_NLRI with no prefixes: // case 2 end-of-rib return true; @@ -783,6 +785,7 @@ mod tests { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, })]); let msg = BgpUpdateMessage { withdrawn_prefixes: vec![], @@ -791,6 +794,42 @@ mod tests { }; assert!(msg.is_end_of_rib()); + // EVPN withdrawal: the routes live in `evpn_nlris`, so an empty + // `prefixes` alone must not read as an end-of-rib marker. + let withdrawn = EvpnNlri { + path_id: None, + route_type: EvpnRouteType::MacIpAdvertisement, + route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 11, 0, 2]), + payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement { + esi: [0; 10], + ethernet_tag_id: 0, + mac: [0xaa, 0xc1, 0xab, 0x73, 0x01, 0x4d], + ip: None, + raw_label: 100, + raw_label2: None, + }), + }; + let attrs = Attributes::from_iter(vec![AttributeValue::MpUnreachNlri( + Nlri::new_evpn_unreachable(vec![withdrawn.clone()]), + )]); + let msg = BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes: attrs, + announced_prefixes: vec![], + }; + assert!(!msg.is_end_of_rib(), "an EVPN withdrawal is not an EOR"); + + // The same family with no routes is the actual EVPN end-of-rib marker. + let attrs = Attributes::from_iter(vec![AttributeValue::MpUnreachNlri( + Nlri::new_evpn_unreachable(vec![]), + )]); + let msg = BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes: attrs, + announced_prefixes: vec![], + }; + assert!(msg.is_end_of_rib()); + // message with announced prefixes let prefix = NetworkPrefix::from_str("192.168.1.0/24").unwrap(); let attrs = Attributes::default(); @@ -820,6 +859,7 @@ mod tests { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, })]); let msg = BgpUpdateMessage { withdrawn_prefixes: vec![], @@ -837,6 +877,7 @@ mod tests { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, })]); let msg = BgpUpdateMessage { withdrawn_prefixes: vec![], @@ -854,6 +895,7 @@ mod tests { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, })]); let msg = BgpUpdateMessage { withdrawn_prefixes: vec![], @@ -872,6 +914,7 @@ mod tests { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, }), AttributeValue::AtomicAggregate, ]); @@ -967,7 +1010,7 @@ mod tests { 0xFF, 0xFF, 0xFF, 0xFF, // marker 0x00, 0x1A, // length = 26 0x05, // type = ROUTE-REFRESH - 0x00, 0x19, // AFI = 25 (L2VPN, not in the Afi enum) + 0x00, 0x63, // AFI = 99, not in the Afi enum 0x01, // subtype = BoRR 0x41, // SAFI = 65 (VPLS, not in the Safi enum) 0xDE, 0xAD, 0xBE, // trailing ORF bytes, kept raw @@ -978,7 +1021,7 @@ mod tests { BgpMessage::RouteRefresh(refresh) => refresh, _ => panic!("expected RouteRefresh, got {msg:?}"), }; - assert_eq!(refresh.afi, 25); + assert_eq!(refresh.afi, 99); assert_eq!(refresh.subtype, 1); assert_eq!(refresh.safi, 65); assert_eq!(refresh.data, vec![0xDE, 0xAD, 0xBE]); diff --git a/src/parser/bmp/messages/headers.rs b/src/parser/bmp/messages/headers.rs index f8f65409..e7939c38 100644 --- a/src/parser/bmp/messages/headers.rs +++ b/src/parser/bmp/messages/headers.rs @@ -323,9 +323,10 @@ pub fn parse_per_peer_header(data: &mut Bytes) -> Result IpAddr::V6(data.read_ipv6_address()?), - Afi::LinkState => { - // Link-State doesn't use traditional IP addresses for peer identification - // Use IPv4 zero address as placeholder + // Peer addresses are IPv4 or IPv6 (see `PeerFlags::address_family`); + // anything else, Link-State and EVPN included, has no peer IP of + // its own here, so consume the field and use the zero placeholder. + Afi::LinkState | Afi::L2vpn => { data.has_n_remaining(12)?; data.advance(12); IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)) diff --git a/src/parser/bmp/messages/peer_up_notification.rs b/src/parser/bmp/messages/peer_up_notification.rs index 5e4ffaa9..b5eef542 100644 --- a/src/parser/bmp/messages/peer_up_notification.rs +++ b/src/parser/bmp/messages/peer_up_notification.rs @@ -65,9 +65,9 @@ pub fn parse_peer_up_notification( ip.into() } Afi::Ipv6 => data.read_ipv6_address()?.into(), - Afi::LinkState => { - // Link-State doesn't use traditional IP addresses for local address - // Use IPv4 zero address as placeholder + // Only IPv4 and IPv6 sessions have an address of their own here; for + // Link-State and EVPN consume the field and use the zero placeholder. + Afi::LinkState | Afi::L2vpn => { data.has_n_remaining(12)?; data.advance(12); std::net::Ipv4Addr::new(0, 0, 0, 0).into() diff --git a/src/parser/iters/route.rs b/src/parser/iters/route.rs index 418c3291..31875c46 100644 --- a/src/parser/iters/route.rs +++ b/src/parser/iters/route.rs @@ -259,7 +259,9 @@ impl RouteTableDumpIter { Afi::Ipv4 => self.data.read_ipv4_prefix().map(IpNet::V4), Afi::Ipv6 => self.data.read_ipv6_prefix().map(IpNet::V6), // `parse_table_dump_routes` only builds this iterator for subtypes 1 and 2 - Afi::LinkState => unreachable!("table dumps carry IPv4 or IPv6 prefixes only"), + Afi::LinkState | Afi::L2vpn => { + unreachable!("table dumps carry IPv4 or IPv6 prefixes only") + } }?; let _status = self.data.read_u8()?; let originated_time = self.data.read_u32()? as f64; diff --git a/src/parser/mrt/messages/bgp4mp.rs b/src/parser/mrt/messages/bgp4mp.rs index 1cd87928..ae74f839 100644 --- a/src/parser/mrt/messages/bgp4mp.rs +++ b/src/parser/mrt/messages/bgp4mp.rs @@ -117,6 +117,9 @@ pub(crate) fn validate_bgp4mp_afi(afi: &Afi) -> Result<(), ParserError> { Afi::LinkState => Err(ParserError::ParseError( "Link-State AFI is invalid in a BGP4MP envelope".to_string(), )), + Afi::L2vpn => Err(ParserError::ParseError( + "L2VPN AFI is invalid in a BGP4MP envelope".to_string(), + )), } } @@ -214,8 +217,91 @@ pub fn parse_bgp4mp_message( }) } +/// Whether any route in this update carries an ADD-PATH identifier (RFC 7911). +pub(crate) fn carries_path_ids(message: &BgpMessage) -> bool { + let BgpMessage::Update(update) = message else { + return false; + }; + + update + .announced_prefixes + .iter() + .chain(update.withdrawn_prefixes.iter()) + .any(|prefix| prefix.path_id.is_some()) + || update.attributes.iter().any(|attribute| { + let (AttributeValue::MpReachNlri(nlri) | AttributeValue::MpUnreachNlri(nlri)) = + attribute + else { + return false; + }; + nlri.prefixes.iter().any(|prefix| prefix.path_id.is_some()) + || nlri + .labeled_prefixes + .as_ref() + .is_some_and(|prefixes| prefixes.iter().any(|p| p.path_id.is_some())) + || nlri + .evpn_nlris + .as_ref() + .is_some_and(|routes| routes.iter().any(|r| r.path_id.is_some())) + }) +} + +/// Whether the update carries any route at all, in any family. +fn carries_routes(update: &BgpUpdateMessage) -> bool { + !update.announced_prefixes.is_empty() + || !update.withdrawn_prefixes.is_empty() + || update.attributes.iter().any(|attribute| { + let (AttributeValue::MpReachNlri(nlri) | AttributeValue::MpUnreachNlri(nlri)) = + attribute + else { + return false; + }; + !nlri.prefixes.is_empty() + || nlri + .labeled_prefixes + .as_ref() + .is_some_and(|p| !p.is_empty()) + || nlri.evpn_nlris.as_ref().is_some_and(|r| !r.is_empty()) + }) +} + +/// ADD-PATH is a property of the record subtype (RFC 8050), not of the message, +/// so the payload and the subtype have to agree: encoding route identifiers +/// under `MessageAs4` publishes bytes a reader decodes as NLRI. +fn check_add_path_consistency( + msg_type: Bgp4MpType, + message: &BgpMessage, +) -> Result<(), EncodingError> { + let BgpMessage::Update(update) = message else { + return Ok(()); + }; + if !carries_routes(update) { + return Ok(()); + } + + let add_path_subtype = matches!( + msg_type, + Bgp4MpType::MessageAddpath + | Bgp4MpType::MessageAs4Addpath + | Bgp4MpType::MessageLocalAddpath + | Bgp4MpType::MessageLocalAs4Addpath + ); + + if add_path_subtype != carries_path_ids(message) { + return Err(EncodingError::unencodable( + "BGP4MP message", + format!( + "subtype {msg_type:?} does not match the ADD-PATH identifiers present in the update" + ), + )); + } + + Ok(()) +} + impl Bgp4MpMessage { pub fn encode(&self, asn_len: AsnLength) -> Result { + check_add_path_consistency(self.msg_type, &self.bgp_message)?; let mut bytes = BytesMut::new(); bytes.extend(encode_asn(&self.peer_asn, &asn_len)); bytes.extend(encode_asn(&self.local_asn, &asn_len)); @@ -322,6 +408,99 @@ impl Bgp4MpStateChange { #[cfg(test)] mod tests { use super::*; + use std::net::Ipv4Addr; + + fn add_path_update() -> BgpUpdateMessage { + let route = EvpnNlri { + path_id: Some(7), + route_type: EvpnRouteType::MacIpAdvertisement, + route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 11, 0, 2]), + payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement { + esi: [0; 10], + ethernet_tag_id: 0, + mac: [0xaa, 0xc1, 0xab, 0x73, 0x01, 0x4d], + ip: None, + raw_label: 100, + raw_label2: None, + }), + }; + BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes: Attributes::from_iter(vec![AttributeValue::MpReachNlri( + Nlri::new_evpn_reachable( + Some(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 11))), + vec![route], + ), + )]), + announced_prefixes: vec![], + } + } + + fn message(msg_type: Bgp4MpType, update: BgpUpdateMessage) -> Bgp4MpMessage { + Bgp4MpMessage { + msg_type, + peer_asn: Asn::new_32bit(65000), + local_asn: Asn::new_32bit(65000), + interface_index: 0, + peer_ip: IpAddr::V4(Ipv4Addr::new(10, 10, 0, 11)), + local_ip: IpAddr::V4(Ipv4Addr::new(10, 10, 0, 254)), + bgp_message: BgpMessage::Update(update), + } + } + + #[test] + fn test_add_path_payload_requires_an_add_path_subtype() { + let update = add_path_update(); + assert!(carries_path_ids(&BgpMessage::Update(update.clone()))); + + // MessageAs4 says nothing about ADD-PATH, so the identifiers would be + // read back as NLRI. + let err = message(Bgp4MpType::MessageAs4, update.clone()) + .encode(AsnLength::Bits32) + .expect_err("a plain subtype cannot carry ADD-PATH identifiers"); + assert!(format!("{err:?}").contains("ADD-PATH"), "{err:?}"); + + message(Bgp4MpType::MessageAs4Addpath, update) + .encode(AsnLength::Bits32) + .expect("the ADD-PATH subtype accepts them"); + } + + #[test] + fn test_plain_payload_requires_a_plain_subtype() { + let route = EvpnNlri { + path_id: None, + route_type: EvpnRouteType::MacIpAdvertisement, + route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 11, 0, 2]), + payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement { + esi: [0; 10], + ethernet_tag_id: 0, + mac: [0xaa, 0xc1, 0xab, 0x73, 0x01, 0x4d], + ip: None, + raw_label: 100, + raw_label2: None, + }), + }; + let update = BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes: Attributes::from_iter(vec![AttributeValue::MpReachNlri( + Nlri::new_evpn_reachable( + Some(IpAddr::V4(Ipv4Addr::new(10, 10, 0, 11))), + vec![route], + ), + )]), + announced_prefixes: vec![], + }; + + let err = message(Bgp4MpType::MessageAs4Addpath, update.clone()) + .encode(AsnLength::Bits32) + .expect_err("an ADD-PATH subtype needs identifiers"); + assert!(format!("{err:?}").contains("ADD-PATH"), "{err:?}"); + + message(Bgp4MpType::MessageAs4, update) + .encode(AsnLength::Bits32) + .expect("a plain subtype accepts a plain payload"); + } + use std::net::IpAddr; use std::str::FromStr; diff --git a/src/parser/mrt/messages/table_dump.rs b/src/parser/mrt/messages/table_dump.rs index 528e20bc..5fcd6a49 100644 --- a/src/parser/mrt/messages/table_dump.rs +++ b/src/parser/mrt/messages/table_dump.rs @@ -118,9 +118,9 @@ fn parse_table_dump_entry( let prefix = match afi { Afi::Ipv4 => data.read_ipv4_prefix().map(ipnet::IpNet::V4), Afi::Ipv6 => data.read_ipv6_prefix().map(ipnet::IpNet::V6), - Afi::LinkState => { - // Link-State doesn't use traditional prefixes, but we need a placeholder - // Use 0.0.0.0/0 as a placeholder for now + Afi::LinkState | Afi::L2vpn => { + // Neither Link-State nor EVPN uses traditional prefixes, but we need + // a placeholder; use 0.0.0.0/0. Ok(ipnet::IpNet::V4( ipnet::Ipv4Net::new(std::net::Ipv4Addr::new(0, 0, 0, 0), 0).unwrap(), )) diff --git a/src/parser/mrt/mrt_record.rs b/src/parser/mrt/mrt_record.rs index c5834e57..9ea51ee7 100644 --- a/src/parser/mrt/mrt_record.rs +++ b/src/parser/mrt/mrt_record.rs @@ -438,8 +438,16 @@ impl TryFrom<&BmpMessage> for MrtRecord { false => Asn::new_16bit(0), }; + // A BMP feed cannot say whether the session negotiated ADD-PATH, but the + // parsed update can: pick the subtype that matches its identifiers. + let msg_type = if crate::parser::mrt::messages::bgp4mp::carries_path_ids(bgp_message) { + Bgp4MpType::MessageAs4Addpath + } else { + Bgp4MpType::MessageAs4 + }; + let bgp4mp_message = Bgp4MpMessage { - msg_type: Bgp4MpType::MessageAs4, // TODO: check Message or MessageAs4 + msg_type, peer_asn: bmp_header.peer_asn, local_asn, interface_index: 0, @@ -452,7 +460,7 @@ impl TryFrom<&BmpMessage> for MrtRecord { let (seconds, microseconds) = convert_timestamp(bmp_header.timestamp); - let subtype = Bgp4MpType::MessageAs4 as u16; + let subtype = msg_type as u16; let encoded_message = mrt_message .encode(subtype) .map_err(|e| format!("cannot encode MRT message: {e}"))?; @@ -460,7 +468,7 @@ impl TryFrom<&BmpMessage> for MrtRecord { timestamp: seconds, microsecond_timestamp: Some(microseconds), entry_type: EntryType::BGP4MP_ET, - entry_subtype: Bgp4MpType::MessageAs4 as u16, + entry_subtype: msg_type as u16, length: encoded_message.len() as u32, }; @@ -647,6 +655,69 @@ mod tests { assert_eq!(mrt_record.common_header.entry_type, EntryType::BGP4MP_ET); } + #[test] + fn test_try_from_bmp_message_selects_the_add_path_subtype() { + // A BMP session cannot say whether ADD-PATH was negotiated, but the + // parsed update can: the conversion has to pick the subtype that + // matches its route identifiers or the record decodes into garbage. + let route = EvpnNlri { + path_id: Some(7), + route_type: EvpnRouteType::MacIpAdvertisement, + route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 11, 0, 2]), + payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement { + esi: [0; 10], + ethernet_tag_id: 0, + mac: [0xaa, 0xc1, 0xab, 0x73, 0x01, 0x4d], + ip: None, + raw_label: 100, + raw_label2: None, + }), + }; + let update = BgpUpdateMessage { + withdrawn_prefixes: vec![], + attributes: Attributes::from_iter(vec![AttributeValue::MpReachNlri( + Nlri::new_evpn_reachable( + Some(IpAddr::from_str("10.10.0.11").unwrap()), + vec![route], + ), + )]), + announced_prefixes: vec![], + }; + let bmp_message = BmpMessage { + common_header: BmpCommonHeader { + version: 3, + msg_len: 0, + msg_type: BmpMsgType::RouteMonitoring, + }, + per_peer_header: Some(BmpPerPeerHeader { + peer_asn: Asn::new_32bit(65000), + peer_ip: IpAddr::from_str("10.10.0.11").unwrap(), + peer_bgp_id: Ipv4Addr::from_str("10.10.0.11").unwrap(), + timestamp: 0.0, + peer_type: BmpPeerType::Global, + peer_flags: PerPeerFlags::PeerFlags(PeerFlags::empty()), + peer_distinguisher: 0, + }), + message_body: BmpMessageBody::RouteMonitoring(RouteMonitoring { + bgp_message: BgpMessage::Update(update), + }), + }; + + let record = MrtRecord::try_from(&bmp_message).unwrap(); + assert_eq!( + record.common_header.entry_subtype, + Bgp4MpType::MessageAs4Addpath as u16 + ); + // And the result survives a round trip through its own encoding. + let encoded = record.encode().expect("the converted record encodes"); + let mut cursor = std::io::Cursor::new(encoded); + let reparsed = crate::parse_mrt_record(&mut cursor).expect("the record parses back"); + assert_eq!( + reparsed.common_header.entry_subtype, + Bgp4MpType::MessageAs4Addpath as u16 + ); + } + #[test] fn test_parse_mrt_body() { let mut data = BytesMut::new(); diff --git a/src/parser/utils.rs b/src/parser/utils.rs index af44bd71..11cbfc52 100644 --- a/src/parser/utils.rs +++ b/src/parser/utils.rs @@ -72,9 +72,9 @@ pub trait ReadUtils: Buf { Ok(ip) => Ok(IpAddr::V6(ip)), _ => Err(io::Error::other("Cannot parse IPv6 address")), }, - Afi::LinkState => { - // Link-State doesn't use traditional IP addresses - // Use IPv4 zero address as placeholder + Afi::LinkState | Afi::L2vpn => { + // Neither Link-State nor EVPN uses a traditional IP next hop in + // this path; use the IPv4 zero address as a placeholder. Ok(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))) } } @@ -221,7 +221,9 @@ fn try_parse_prefix( let max_bit_len: u8 = match afi { Afi::Ipv4 => 32, Afi::Ipv6 => 128, - Afi::LinkState => 0, + // EVPN NLRI are decoded by their own parser; a bit-length prefix does + // not apply to either family here. + Afi::LinkState | Afi::L2vpn => 0, }; if bit_len > max_bit_len { @@ -267,7 +269,8 @@ fn try_parse_prefix( pos += byte_len; IpAddr::V6(Ipv6Addr::from(buff)) } - Afi::LinkState => { + // Neither Link-State nor EVPN carries a traditional prefix here. + Afi::LinkState | Afi::L2vpn => { pos += byte_len; IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)) } diff --git a/src/render/text.rs b/src/render/text.rs index 0fe5769e..6cd7d94f 100644 --- a/src/render/text.rs +++ b/src/render/text.rs @@ -350,6 +350,43 @@ fn capability_summary(cap: &Capability) -> String { } } +/// One EVPN route as a single line: route type, route distinguisher, and the +/// fields an operator looks at first (MAC, prefix, originator, label). +fn render_evpn_route(route: &EvpnNlri) -> String { + let route_distinguisher = route.route_distinguisher; + let path_id = route + .path_id + .map_or_else(String::new, |id| format!(" path-id {id}")); + match &route.payload { + EvpnRoutePayload::MacIpAdvertisement(body) => { + let mac = body + .mac + .iter() + .map(|octet| format!("{octet:02x}")) + .collect::>() + .join(":"); + let ip = body.ip.map_or_else(|| "-".to_string(), |ip| ip.to_string()); + format!( + "[2] RD {route_distinguisher} MAC {mac} IP {ip} label {}{path_id}", + body.raw_label + ) + } + EvpnRoutePayload::InclusiveMulticast(body) => format!( + "[3] RD {route_distinguisher} originator {}{path_id}", + body.originating_router_ip + ), + EvpnRoutePayload::IpPrefix(body) => format!( + "[5] RD {route_distinguisher} {} via {} label {}{path_id}", + body.ip_prefix, body.gateway_ip, body.raw_label + ), + EvpnRoutePayload::Raw(octets) => format!( + "[{}] RD {route_distinguisher} {} octets (not decoded){path_id}", + u8::from(route.route_type), + octets.len() + ), + } +} + fn render_update(out: &mut String, update: &BgpUpdateMessage) { // Withdrawn prefixes: the standard field plus any carried in // MP_UNREACH_NLRI, so the transcript never silently drops routes. @@ -358,18 +395,22 @@ fn render_update(out: &mut String, update: &BgpUpdateMessage) { let mut withdrawn: Vec<&NetworkPrefix> = update.withdrawn_prefixes.iter().collect(); let mut announced: Vec<&NetworkPrefix> = update.announced_prefixes.iter().collect(); let mut labeled_announced: Vec<&LabeledNetworkPrefix> = Vec::new(); + let mut evpn_withdrawn: Vec<&EvpnNlri> = Vec::new(); + let mut evpn_announced: Vec<&EvpnNlri> = Vec::new(); let mut link_state_count = 0usize; let mut flowspec_count = 0usize; for attr in update.attributes.iter() { match attr { AttributeValue::MpUnreachNlri(nlri) => { withdrawn.extend(nlri.prefixes.iter()); + evpn_withdrawn.extend(nlri.evpn_nlris.iter().flatten()); link_state_count += nlri.link_state_nlris.as_ref().map_or(0, Vec::len); flowspec_count += nlri.flowspec_nlris.as_ref().map_or(0, Vec::len); } AttributeValue::MpReachNlri(nlri) => { announced.extend(nlri.prefixes.iter()); labeled_announced.extend(nlri.labeled_prefixes.iter().flatten()); + evpn_announced.extend(nlri.evpn_nlris.iter().flatten()); link_state_count += nlri.link_state_nlris.as_ref().map_or(0, Vec::len); flowspec_count += nlri.flowspec_nlris.as_ref().map_or(0, Vec::len); } @@ -409,6 +450,18 @@ fn render_update(out: &mut String, update: &BgpUpdateMessage) { )); } } + if !evpn_withdrawn.is_empty() { + out.push_str(&format!("{INDENT}WITHDRAWN (EVPN):\n")); + for route in evpn_withdrawn { + out.push_str(&format!("{INDENT}{INDENT}{}\n", render_evpn_route(route))); + } + } + if !evpn_announced.is_empty() { + out.push_str(&format!("{INDENT}ANNOUNCED (EVPN):\n")); + for route in evpn_announced { + out.push_str(&format!("{INDENT}{INDENT}{}\n", render_evpn_route(route))); + } + } if link_state_count > 0 { out.push_str(&format!( "{INDENT}LINK_STATE_NLRI: {link_state_count} entries (BGP-LS)\n" @@ -634,6 +687,53 @@ mod tests { } } + #[test] + fn renders_evpn_routes() { + let announced = EvpnNlri { + path_id: None, + route_type: EvpnRouteType::MacIpAdvertisement, + route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 11, 0, 2]), + payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement { + esi: [0; 10], + ethernet_tag_id: 0, + mac: [0xaa, 0xc1, 0xab, 0x73, 0x01, 0x4d], + ip: Some(IpAddr::from_str("10.100.0.101").unwrap()), + raw_label: 100, + raw_label2: None, + }), + }; + let withdrawn = EvpnNlri { + path_id: None, + route_type: EvpnRouteType::IpPrefix, + route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 12, 0, 2]), + payload: EvpnRoutePayload::IpPrefix(IpPrefixRoute { + esi: [0; 10], + ethernet_tag_id: 0, + ip_prefix: ipnet::IpNet::from_str("198.51.100.0/24").unwrap(), + gateway_ip: IpAddr::from_str("0.0.0.0").unwrap(), + raw_label: 100, + }), + }; + let attributes = Attributes::from_iter(vec![ + AttributeValue::MpReachNlri(Nlri::new_evpn_reachable( + Some(IpAddr::from_str("10.10.0.11").unwrap()), + vec![announced], + )), + AttributeValue::MpUnreachNlri(Nlri::new_evpn_unreachable(vec![withdrawn])), + ]); + + let text = format_record(&update_record(attributes)); + + assert!( + text.contains("ANNOUNCED (EVPN):\n [2] RD 00:01:0a:0a:00:0b:00:02 MAC aa:c1:ab:73:01:4d IP 10.100.0.101 label 100"), + "missing EVPN announcement line in:\n{text}" + ); + assert!( + text.contains("WITHDRAWN (EVPN):\n [5] RD 00:01:0a:0a:00:0c:00:02 198.51.100.0/24 via 0.0.0.0 label 100"), + "missing EVPN withdrawal line in:\n{text}" + ); + } + fn full_attributes() -> Attributes { let mut attributes = Attributes::default(); attributes.add_attr(AttributeValue::Origin(Origin::IGP).into()); @@ -723,6 +823,7 @@ UPDATE: labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, }) .into(), ); @@ -775,6 +876,7 @@ UPDATE: labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, }) .into(), ); @@ -1010,6 +1112,7 @@ UPDATE: labeled_prefixes: Some(vec![labeled]), link_state_nlris: Some(vec![]), flowspec_nlris: Some(vec![]), + evpn_nlris: None, }) .into(), ); diff --git a/src/wasm/js/generated/Afi.ts b/src/wasm/js/generated/Afi.ts index 725090fd..473806f7 100644 --- a/src/wasm/js/generated/Afi.ts +++ b/src/wasm/js/generated/Afi.ts @@ -5,4 +5,4 @@ * * */ -export type Afi = "Ipv4" | "Ipv6" | "LinkState"; +export type Afi = "Ipv4" | "Ipv6" | "L2vpn" | "LinkState"; diff --git a/src/wasm/js/generated/ExtendedCommunity.ts b/src/wasm/js/generated/ExtendedCommunity.ts index 8806f49a..7bbf12cc 100644 --- a/src/wasm/js/generated/ExtendedCommunity.ts +++ b/src/wasm/js/generated/ExtendedCommunity.ts @@ -5,6 +5,7 @@ import type { FlowSpecTrafficRate } from "./FlowSpecTrafficRate"; import type { FourOctetAsExtCommunity } from "./FourOctetAsExtCommunity"; import type { Ipv4AddrExtCommunity } from "./Ipv4AddrExtCommunity"; import type { LinkBandwidth } from "./LinkBandwidth"; +import type { MacMobility } from "./MacMobility"; import type { OpaqueExtCommunity } from "./OpaqueExtCommunity"; import type { TwoOctetAsExtCommunity } from "./TwoOctetAsExtCommunity"; @@ -37,4 +38,4 @@ import type { TwoOctetAsExtCommunity } from "./TwoOctetAsExtCommunity"; * otherwise. * ``` */ -export type ExtendedCommunity = { "TransitiveTwoOctetAs": TwoOctetAsExtCommunity } | { "TransitiveIpv4Addr": Ipv4AddrExtCommunity } | { "TransitiveFourOctetAs": FourOctetAsExtCommunity } | { "TransitiveOpaque": OpaqueExtCommunity } | { "NonTransitiveTwoOctetAs": TwoOctetAsExtCommunity } | { "NonTransitiveIpv4Addr": Ipv4AddrExtCommunity } | { "NonTransitiveFourOctetAs": FourOctetAsExtCommunity } | { "NonTransitiveOpaque": OpaqueExtCommunity } | { "FlowSpecTrafficRate": FlowSpecTrafficRate } | { "FlowSpecTrafficAction": FlowSpecTrafficAction } | { "FlowSpecRedirect": TwoOctetAsExtCommunity } | { "FlowSpecTrafficMarking": FlowSpecTrafficMarking } | { "LinkBandwidth": LinkBandwidth } | { "Raw": [number, number, number, number, number, number, number, number] }; +export type ExtendedCommunity = { "TransitiveTwoOctetAs": TwoOctetAsExtCommunity } | { "TransitiveIpv4Addr": Ipv4AddrExtCommunity } | { "TransitiveFourOctetAs": FourOctetAsExtCommunity } | { "TransitiveOpaque": OpaqueExtCommunity } | { "NonTransitiveTwoOctetAs": TwoOctetAsExtCommunity } | { "NonTransitiveIpv4Addr": Ipv4AddrExtCommunity } | { "NonTransitiveFourOctetAs": FourOctetAsExtCommunity } | { "NonTransitiveOpaque": OpaqueExtCommunity } | { "FlowSpecTrafficRate": FlowSpecTrafficRate } | { "FlowSpecTrafficAction": FlowSpecTrafficAction } | { "FlowSpecRedirect": TwoOctetAsExtCommunity } | { "FlowSpecTrafficMarking": FlowSpecTrafficMarking } | { "LinkBandwidth": LinkBandwidth } | { "MacMobility": MacMobility } | { "Raw": [number, number, number, number, number, number, number, number] }; diff --git a/src/wasm/js/generated/ExtendedCommunityType.ts b/src/wasm/js/generated/ExtendedCommunityType.ts index d3705f72..23cf3fc1 100644 --- a/src/wasm/js/generated/ExtendedCommunityType.ts +++ b/src/wasm/js/generated/ExtendedCommunityType.ts @@ -3,4 +3,4 @@ /** * Type definitions of extended communities */ -export type ExtendedCommunityType = "TransitiveTwoOctetAs" | "TransitiveIpv4Addr" | "TransitiveFourOctetAs" | "TransitiveOpaque" | "NonTransitiveTwoOctetAs" | "NonTransitiveIpv4Addr" | "NonTransitiveFourOctetAs" | "NonTransitiveOpaque" | { "Unknown": number }; +export type ExtendedCommunityType = "TransitiveTwoOctetAs" | "TransitiveIpv4Addr" | "TransitiveFourOctetAs" | "TransitiveOpaque" | "Evpn" | "NonTransitiveTwoOctetAs" | "NonTransitiveIpv4Addr" | "NonTransitiveFourOctetAs" | "NonTransitiveOpaque" | { "Unknown": number }; diff --git a/src/wasm/js/generated/MacMobility.ts b/src/wasm/js/generated/MacMobility.ts new file mode 100644 index 00000000..9ef90e93 --- /dev/null +++ b/src/wasm/js/generated/MacMobility.ts @@ -0,0 +1,30 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * MAC Mobility Extended Community - RFC 7432 §7.7 + * + * Carried with a MAC/IP Advertisement (route type 2). The sequence number is + * how a fabric orders competing advertisements for the same MAC: the highest + * value wins, and a PE that sees a locally learned MAC it previously knew as + * remote re-advertises it with the sequence number incremented. + * + * ```text + * 0 1 2 3 + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Type = 0x06 | Sub-Type = 0x00| Flags | Reserved | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Sequence Number | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * ``` + */ +export type MacMobility = { +/** + * Sticky/static flag (bit 0 of the flags octet): the MAC is considered + * immobile and does not take part in sequence-number comparison. + */ +sticky: boolean, +/** + * Sequence number, 32 bits big-endian. + */ +sequence: number, }; diff --git a/src/wasm/js/generated/Nlri.ts b/src/wasm/js/generated/Nlri.ts index 931fb286..3cdcc5fb 100644 --- a/src/wasm/js/generated/Nlri.ts +++ b/src/wasm/js/generated/Nlri.ts @@ -25,4 +25,8 @@ link_state_nlris: Record[] | null, /** * Flow-Spec NLRI data - RFC 8955/8956 */ -flowspec_nlris: Record[] | null, }; +flowspec_nlris: Record[] | null, +/** + * EVPN NLRI data - RFC 7432 (AFI 25, SAFI 70) + */ +evpn_nlris: Record[] | null, }; diff --git a/src/wasm/js/generated/Safi.ts b/src/wasm/js/generated/Safi.ts index fade4c6c..7b6e656f 100644 --- a/src/wasm/js/generated/Safi.ts +++ b/src/wasm/js/generated/Safi.ts @@ -13,4 +13,4 @@ * - RFC 7752: BGP Link-State - defines SAFI 71, 72 * - RFC 8950: Advertising IPv4 Network Layer Reachability Information (NLRI) with an IPv6 Next Hop */ -export type Safi = "Unicast" | "Multicast" | "UnicastMulticast" | "MplsLabel" | "LinkState" | "LinkStateVpn" | "MplsVpn" | "MulticastVpn" | "FlowSpec" | "FlowSpecL3Vpn"; +export type Safi = "Unicast" | "Multicast" | "UnicastMulticast" | "MplsLabel" | "Evpn" | "LinkState" | "LinkStateVpn" | "MplsVpn" | "MulticastVpn" | "FlowSpec" | "FlowSpecL3Vpn"; diff --git a/src/wasm/test/fixtures/attribute_values.json b/src/wasm/test/fixtures/attribute_values.json index 371216d1..8654782e 100644 --- a/src/wasm/test/fixtures/attribute_values.json +++ b/src/wasm/test/fixtures/attribute_values.json @@ -176,6 +176,7 @@ "value": { "MpReachNlri": { "afi": "Ipv6", + "evpn_nlris": null, "flowspec_nlris": null, "labeled_prefixes": null, "link_state_nlris": null, @@ -201,6 +202,7 @@ "value": { "MpUnreachNlri": { "afi": "Ipv6", + "evpn_nlris": null, "flowspec_nlris": null, "labeled_prefixes": null, "link_state_nlris": null, @@ -389,6 +391,7 @@ { "MpReachNlri": { "afi": "Ipv6", + "evpn_nlris": null, "flowspec_nlris": null, "labeled_prefixes": null, "link_state_nlris": null, @@ -411,6 +414,7 @@ { "MpUnreachNlri": { "afi": "Ipv6", + "evpn_nlris": null, "flowspec_nlris": null, "labeled_prefixes": null, "link_state_nlris": null, diff --git a/src/wasm/test/fixtures/ris_live_raw_full.json b/src/wasm/test/fixtures/ris_live_raw_full.json index 6ede9e1a..ed1d8f34 100644 --- a/src/wasm/test/fixtures/ris_live_raw_full.json +++ b/src/wasm/test/fixtures/ris_live_raw_full.json @@ -234,7 +234,8 @@ ], "labeled_prefixes": null, "link_state_nlris": null, - "flowspec_nlris": null + "flowspec_nlris": null, + "evpn_nlris": null } }, "flag": "OPTIONAL" diff --git a/tests/evpn.rs b/tests/evpn.rs new file mode 100644 index 00000000..855c4e63 --- /dev/null +++ b/tests/evpn.rs @@ -0,0 +1,312 @@ +//! EVPN decoding against a capture from a real FRR fabric. +//! +//! `fixtures/evpn/mac-move.bmp` is 19 BMP messages exported by an FRR 10.7.1 +//! route reflector in the `evpn-mac-mobility` lab (BGPKIT Labs, `topologies/`): +//! an init message, three peer-up messages and 15 route-monitoring messages, +//! captured with `bmp monitor l2vpn evpn post-policy`. +//! +//! Two FRR leaves advertised a MAC for the same VNI 100. One host then started +//! sending frames with the other host's MAC address, so both leaves kept +//! re-advertising it with an incremented MAC Mobility sequence number: 1, 2, 3 +//! and 4, each round preceded by a withdrawal of the previous claim. + +use bgpkit_parser::models::*; +use bgpkit_parser::parser::bmp::messages::BmpMessageBody; +use bgpkit_parser::{parse_bmp_msg, parse_mrt_record}; +use bytes::Bytes; + +const CAPTURE: &[u8] = include_bytes!("fixtures/evpn/mac-move.bmp"); + +/// MAC that moved between the two leaves (the address of the host behind leaf1). +const MOVED_MAC: [u8; 6] = [0xaa, 0xc1, 0xab, 0x73, 0x01, 0x4d]; + +struct Parsed { + init: usize, + peer_up: usize, + announces: Vec<(BgpUpdateMessage, std::net::IpAddr)>, + withdrawals: Vec, +} + +fn parse_capture() -> Parsed { + let mut data = Bytes::from_static(CAPTURE); + let mut parsed = Parsed { + init: 0, + peer_up: 0, + announces: Vec::new(), + withdrawals: Vec::new(), + }; + + while !data.is_empty() { + let message = parse_bmp_msg(&mut data).expect("every message in the capture parses"); + match message.message_body { + BmpMessageBody::InitiationMessage(_) => parsed.init += 1, + BmpMessageBody::PeerUpNotification(_) => parsed.peer_up += 1, + BmpMessageBody::RouteMonitoring(monitoring) => { + let BgpMessage::Update(update) = monitoring.bgp_message else { + continue; + }; + let peer = message + .per_peer_header + .expect("route monitoring carries a per-peer header") + .peer_ip; + if update + .attributes + .iter() + .any(|attribute| matches!(attribute, AttributeValue::MpReachNlri(_))) + { + parsed.announces.push((update, peer)); + } else { + parsed.withdrawals.push(update); + } + } + _ => {} + } + } + + parsed +} + +fn evpn_nlri(update: &BgpUpdateMessage, reachable: bool) -> &Vec { + update + .attributes + .iter() + .find_map(|attribute| match (attribute, reachable) { + (AttributeValue::MpReachNlri(nlri), true) => Some(nlri), + (AttributeValue::MpUnreachNlri(nlri), false) => Some(nlri), + _ => None, + }) + .and_then(|nlri| nlri.evpn_nlris.as_ref()) + .expect("EVPN NLRI") +} + +fn mac_ip_route(nlri: &EvpnNlri) -> &MacIpAdvertisement { + match &nlri.payload { + EvpnRoutePayload::MacIpAdvertisement(route) => route, + other => panic!("expected a MAC/IP advertisement, got {other:?}"), + } +} + +fn sequence_numbers(update: &BgpUpdateMessage) -> Vec { + update + .attributes + .iter() + .find_map(|attribute| match attribute { + AttributeValue::ExtendedCommunities(communities) => Some( + communities + .iter() + .filter_map(|community| match community { + ExtendedCommunity::MacMobility(mobility) => { + assert!(!mobility.sticky, "the capture carries no sticky MAC"); + Some(mobility.sequence) + } + _ => None, + }) + .collect::>(), + ), + _ => None, + }) + .unwrap_or_default() +} + +#[test] +fn capture_decodes_into_typed_evpn_records() { + let parsed = parse_capture(); + + assert_eq!(parsed.init, 1, "one BMP init message"); + assert_eq!(parsed.peer_up, 3, "three peer-up messages"); + assert_eq!(parsed.announces.len(), 8, "eight announcements"); + assert_eq!(parsed.withdrawals.len(), 7, "seven withdrawals"); +} + +#[test] +fn the_fabric_starts_with_one_mac_ip_and_one_implicit_route_per_leaf() { + let parsed = parse_capture(); + let initial = &parsed.announces[..4]; + + let macs: Vec<[u8; 6]> = initial + .iter() + .filter_map(|(update, _)| { + evpn_nlri(update, true) + .iter() + .find_map(|route| match &route.payload { + EvpnRoutePayload::MacIpAdvertisement(body) => Some(body.mac), + _ => None, + }) + }) + .collect(); + assert_eq!(macs.len(), 2, "each leaf advertises its own host"); + assert!(macs.contains(&MOVED_MAC)); + assert!( + initial + .iter() + .all(|(update, _)| sequence_numbers(update).is_empty()), + "the first advertisement of a MAC carries no MAC Mobility community" + ); + + let imet: Vec = initial + .iter() + .filter_map(|(update, _)| { + evpn_nlri(update, true) + .iter() + .find_map(|route| match &route.payload { + EvpnRoutePayload::InclusiveMulticast(body) => Some(body.originating_router_ip), + _ => None, + }) + }) + .collect(); + assert_eq!( + imet, + vec![ + "10.10.0.11".parse::().unwrap(), + "10.10.0.12".parse().unwrap() + ], + "one IMET route each" + ); +} + +#[test] +fn the_relearn_war_counts_up_in_the_mac_mobility_community() { + let parsed = parse_capture(); + let war: Vec<_> = parsed + .announces + .iter() + .filter(|(update, _)| !sequence_numbers(update).is_empty()) + .collect(); + + assert_eq!(war.len(), 4, "four rounds of the war"); + let sequences: Vec = war + .iter() + .flat_map(|(update, _)| sequence_numbers(update)) + .collect(); + assert_eq!(sequences, vec![1, 2, 3, 4], "one increment per round"); + + // The originator alternates: the challenger claims, the holder re-asserts. + let peers: Vec = war.iter().map(|(_, peer)| *peer).collect(); + assert_eq!( + peers, + vec![ + "10.10.0.12".parse::().unwrap(), + "10.10.0.11".parse().unwrap(), + "10.10.0.12".parse().unwrap(), + "10.10.0.11".parse().unwrap(), + ] + ); +} + +#[test] +fn every_route_names_its_own_leaf_as_rd_and_next_hop() { + let parsed = parse_capture(); + + for (update, peer) in &parsed.announces { + for route in evpn_nlri(update, true) { + let EvpnRoutePayload::MacIpAdvertisement(body) = &route.payload else { + continue; + }; + + assert_eq!(body.esi, [0u8; 10], "single-homed host, ESI 0"); + assert_eq!(body.raw_label2, None, "MAC-only route, no IP-VRF label"); + assert_eq!(route.path_id, None, "the lab session does not run ADD-PATH"); + assert_eq!(body.ethernet_tag_id, 0); + assert_eq!(body.ip, None, "MAC-only advertisement, IP length 0"); + assert_eq!(body.raw_label, 100, "VNI 100"); + + // The route distinguisher is derived from the advertising VTEP: + // type 1 (IP-based), the leaf's underlay address, local part 2. + let rd = route.route_distinguisher.0; + assert_eq!(rd[0..2], [0x00, 0x01], "RD type 1"); + let rd_ip = std::net::Ipv4Addr::new(rd[2], rd[3], rd[4], rd[5]); + assert_eq!(std::net::IpAddr::V4(rd_ip), *peer); + assert_eq!(rd[6..8], [0x00, 0x02]); + + // The next hop is the VTEP of the advertising leaf. + let next_hop = update + .attributes + .iter() + .find_map(|attribute| match attribute { + AttributeValue::MpReachNlri(nlri) => Some(nlri.next_hop), + _ => None, + }) + .flatten() + .expect("reachable NLRI has a next hop"); + assert_eq!(next_hop.global_addr(), *peer); + } + } +} + +#[test] +fn withdrawals_and_end_of_rib_are_typed() { + let parsed = parse_capture(); + + // Two end-of-rib markers arrive right after the peer-up messages: an + // MP_UNREACH carrying the EVPN family and no NLRI. + let empty = parsed + .withdrawals + .iter() + .filter(|update| evpn_nlri(update, false).is_empty()) + .count(); + assert_eq!(empty, 2, "one end-of-rib marker per peer"); + + // The other five withdraw a MAC/IP route, the moved MAC among them. + let mut withdrawn_macs = Vec::new(); + for update in &parsed.withdrawals { + for route in evpn_nlri(update, false) { + assert_eq!(route.route_type, EvpnRouteType::MacIpAdvertisement); + withdrawn_macs.push(mac_ip_route(route).mac); + } + } + assert_eq!(withdrawn_macs.len(), 5); + assert!( + withdrawn_macs.contains(&MOVED_MAC), + "the war ends with a withdrawal of the moved MAC" + ); +} + +#[test] +fn a_route_monitoring_message_converts_to_an_mrt_record() { + // `MrtRecord::try_from(&BmpMessage)` re-encodes the parsed update, so a + // decoded EVPN route has to survive the encoder for BMP-to-MRT conversion + // to keep working. + let mut data = Bytes::from_static(CAPTURE); + let mut original: Vec> = Vec::new(); + let mut converted: Vec> = Vec::new(); + + while !data.is_empty() { + let message = parse_bmp_msg(&mut data).expect("parses"); + let BmpMessageBody::RouteMonitoring(monitoring) = &message.message_body else { + continue; + }; + let BgpMessage::Update(update) = &monitoring.bgp_message else { + continue; + }; + if !update + .attributes + .iter() + .any(|attribute| matches!(attribute, AttributeValue::MpReachNlri(_))) + { + continue; + } + + original.push(evpn_nlri(update, true).clone()); + + // The conversion clones the parsed message, so encode the record and + // parse those bytes: only that proves the re-encoded NLRI is valid. + let record = MrtRecord::try_from(&message) + .expect("an EVPN route monitoring message converts to an MRT record"); + let encoded = record.encode().expect("the converted record encodes"); + let mut encoded_data = std::io::Cursor::new(encoded); + let reparsed = parse_mrt_record(&mut encoded_data).expect("the encoded record parses"); + let MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(bgp4mp)) = &reparsed.message else { + panic!("expected a BGP4MP message record"); + }; + let BgpMessage::Update(converted_update) = &bgp4mp.bgp_message else { + panic!("expected an update"); + }; + converted.push(evpn_nlri(converted_update, true).clone()); + } + + assert_eq!(original.len(), 8, "every announcement converts"); + assert_eq!( + original, converted, + "the re-encoded routes decode to the same values" + ); +} diff --git a/tests/fixtures/evpn/mac-move.bmp b/tests/fixtures/evpn/mac-move.bmp new file mode 100644 index 00000000..b08a42d3 Binary files /dev/null and b/tests/fixtures/evpn/mac-move.bmp differ diff --git a/tests/test_encoding_errors.rs b/tests/test_encoding_errors.rs index 72629a72..eb42e757 100644 --- a/tests/test_encoding_errors.rs +++ b/tests/test_encoding_errors.rs @@ -85,6 +85,7 @@ fn test_mp_reach_empty_label_stack_propagates() { }]), link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, }; let attr = Attribute::from(AttributeValue::MpReachNlri(nlri)); let err = attr.encode(AsnLength::Bits32).unwrap_err(); diff --git a/tests/test_wasm_type_fixtures.rs b/tests/test_wasm_type_fixtures.rs index 0e02c2a0..bb374f2b 100644 --- a/tests/test_wasm_type_fixtures.rs +++ b/tests/test_wasm_type_fixtures.rs @@ -95,6 +95,7 @@ fn sample_attributes() -> Vec { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, }), AttributeValue::MpUnreachNlri(Nlri { afi: Afi::Ipv6, @@ -107,6 +108,7 @@ fn sample_attributes() -> Vec { labeled_prefixes: None, link_state_nlris: None, flowspec_nlris: None, + evpn_nlris: None, }), AttributeValue::Development(vec![1, 2, 3]), AttributeValue::Raw(AttrRaw {