From fdab86f645d277b8694290024163df618c661341 Mon Sep 17 00:00:00 2001 From: Ties de Kock Date: Sun, 11 Oct 2026 13:40:35 +0200 Subject: [PATCH 1/3] fix: desync after MRT record of unknown type The parser de-synced after a MRT record of unknown type. The header was consumed, but the body was not. Since the length of the body is known from the header, this can be read to prevent a desync after this type of record. --- CHANGELOG.md | 3 + src/error.rs | 11 ++ src/parser/iters/default.rs | 3 + src/parser/iters/default/tests.rs | 127 ++++++++++++++++++ src/parser/iters/diagnostic.rs | 60 ++++++++- src/parser/iters/mod.rs | 38 ++++-- src/parser/iters/route.rs | 5 +- src/parser/mrt/mrt_record.rs | 216 +++++++++++++++++++++++++++--- tests/torn_mrt_records.rs | 81 ++++++++--- 9 files changed, 490 insertions(+), 54 deletions(-) create mode 100644 src/parser/iters/default/tests.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index b687782b..c1c24e8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file. ### Breaking changes +* **`ParserError::OversizedRecord { length }`**: an MRT header declaring a body over the 16 MiB limit now returns this variant instead of `Unsupported("MRT message too large: …")`. The `Display` text is unchanged. Downstream exhaustive matches on `ParserError` need a new arm. * **`ParserBmpError` carries the failing value and is `#[non_exhaustive]`**: `From` and the unknown-message-type conversion collapsed every failure into `InvalidOpenBmpHeader` and dropped the cause; they now return the new `IoError { kind, message }` and `UnknownMessageType(u8)` variants. Downstream matches on the enum now need a wildcard arm: `#[non_exhaustive]` means the two new variants cannot be covered by adding arms alone. ### Added @@ -23,6 +24,8 @@ All notable changes to this project will be documented in this file. ### Fixed +* **Iterators stay aligned after an unknown MRT entry type**: `chunk_mrt_record` rejected an entry type it did not know after reading only the 12-byte header, leaving the record body in the stream. `into_record_iter`, `into_elem_iter`, `into_raw_record_iter` and the fallible iterators then read that body as the next header and misparsed or dropped every record after it. The body is now consumed before the error is returned, so the reader sits at the next record and the error's `bytes` hold the whole skipped record. `into_diagnostic_iter` reports the unknown-type record as a `ParseError` event and continues with the records after it, where it previously terminated on any framing error. +* **Iterators stop at an oversized MRT length instead of desynchronising**: a header declaring a body over 16 MiB left the reader at no usable boundary, yet the default and fallible iterators carried on and reinterpreted the body as headers. The skip-and-continue iterators now log the `OversizedRecord` error and end, and the fallible iterators yield it once and end. `into_recovering_record_iter` still scans forward as before. * **RIS Live JSON elems carry `origin_asns`**: `parse_ris_live_message` left `origin_asns` empty, so an `origin_asn` filter never matched an elem parsed from RIS Live's JSON fields. It is now derived from the AS path, as `parse_ris_live_message_raw` and the MRT iterators already did. * **Dissection span correlation is linear in the number of warnings**: `span_record_warnings` (used by `DiagnosticIterator::with_dissection`) walked the whole dissection tree once per warning, so a BGP UPDATE carrying thousands of duplicate attributes took tens of seconds to diagnose. The tree is now indexed by field name once per record. Spans are unchanged. * **Fallible iterators stop after a fatal stream read error**: `into_fallible_record_iter`, `into_fallible_elem_iter`, `into_fallible_update_iter` and `into_fallible_route_iter` now yield a framing I/O or decompression error once and then end, instead of polling a spent decoder indefinitely. An `Interrupted`/`WouldBlock` read stays retryable only when it consumed no framing bytes, and skippable malformed records are unchanged ([#350](https://github.com/bgpkit/bgpkit-parser/pull/350)). diff --git a/src/error.rs b/src/error.rs index dde1b25a..a8a8c046 100644 --- a/src/error.rs +++ b/src/error.rs @@ -19,6 +19,14 @@ pub enum ParserError { ParseError(String), TruncatedMsg(String), Unsupported(String), + /// An MRT common header declared a body longer than the parser is willing to + /// read (16 MiB). The length field itself is untrusted, so the reader is left + /// just past the header with no known record boundary to resume from; the + /// skip-and-continue iterators stop rather than reinterpret the body as headers. + OversizedRecord { + /// The declared body length that exceeded the limit. + length: u32, + }, FilterError(String), /// NLRI length field is inconsistent with content /// (total_bits < minimum required, or underflow in prefix calculation) @@ -133,6 +141,9 @@ impl Display for ParserError { ParserError::ParseError(s) => write!(f, "Error: {s}"), ParserError::TruncatedMsg(s) => write!(f, "Error: {s}"), ParserError::Unsupported(s) => write!(f, "Error: {s}"), + ParserError::OversizedRecord { length } => { + write!(f, "Error: MRT message too large: {length} bytes") + } ParserError::EofExpected => write!(f, "Error: reach end of file"), #[cfg(feature = "oneio")] ParserError::OneIoError(e) => write!(f, "Error: {e}"), diff --git a/src/parser/iters/default.rs b/src/parser/iters/default.rs index 5159976e..e66f9301 100644 --- a/src/parser/iters/default.rs +++ b/src/parser/iters/default.rs @@ -8,6 +8,9 @@ use crate::parser::BgpkitParser; use crate::{Elementor, Filterable}; use std::io::Read; +#[cfg(test)] +mod tests; + /********* MrtRecord Iterator **********/ diff --git a/src/parser/iters/default/tests.rs b/src/parser/iters/default/tests.rs new file mode 100644 index 00000000..9632f6dd --- /dev/null +++ b/src/parser/iters/default/tests.rs @@ -0,0 +1,127 @@ +//! Alignment tests for the skip-and-continue iterators: a rejected header must +//! leave the reader at a record boundary, or stop iteration when it cannot. + +use crate::models::*; +use crate::parser::BgpkitParser; +use crate::{ParserError, RawMrtRecord}; +use bytes::{BufMut, BytesMut}; +use std::io::Cursor; + +/// A record of type 0x7777 whose 20-byte body reads as a plausible common +/// header, so reading only the 12 header bytes would desynchronise the stream. +fn unknown_type_record() -> Vec { + let mut wire = BytesMut::new(); + wire.put_u32(946_684_800); + wire.put_u16(0x7777); + wire.put_u16(0); + wire.put_u32(20); + wire.put_slice(&[0, 0, 0, 1, 0, 5, 0, 7, 0, 0, 0, 32]); + wire.put_slice(&[0xaa; 8]); + wire.to_vec() +} + +/// A legacy BGP KEEPALIVE record (type BGP, subtype 7). +fn keepalive_record(timestamp: u32) -> Vec { + let body = [0, 1, 192, 0, 2, 1, 0, 2, 192, 0, 2, 2]; + let header = CommonHeader { + timestamp, + microsecond_timestamp: None, + entry_type: EntryType::BGP, + entry_subtype: 7, + length: body.len() as u32, + }; + let mut wire = header.encode().to_vec(); + wire.extend_from_slice(&body); + wire +} + +/// A header declaring a body larger than the parser will read, followed by +/// bytes that would parse as a valid record if the iterator carried on. +fn oversized_record() -> Vec { + let mut wire = BytesMut::new(); + wire.put_u32(1); + wire.put_u16(EntryType::BGP as u16); + wire.put_u16(7); + wire.put_u32(17 * 1024 * 1024); + wire.to_vec() +} + +#[test] +fn record_iter_skips_unknown_entry_type_whole() { + let mut wire = unknown_type_record(); + wire.extend_from_slice(&keepalive_record(946_684_801)); + wire.extend_from_slice(&keepalive_record(946_684_802)); + + let records: Vec = BgpkitParser::from_reader(Cursor::new(wire)) + .into_record_iter() + .collect(); + + let timestamps: Vec = records + .iter() + .map(|record| record.common_header.timestamp) + .collect(); + assert_eq!(timestamps, vec![946_684_801, 946_684_802]); +} + +#[test] +fn raw_record_iter_skips_unknown_entry_type_whole() { + let mut wire = unknown_type_record(); + wire.extend_from_slice(&keepalive_record(946_684_801)); + + let records: Vec = BgpkitParser::from_reader(Cursor::new(wire)) + .into_raw_record_iter() + .collect(); + + assert_eq!(records.len(), 1); + assert_eq!(records[0].common_header.timestamp, 946_684_801); +} + +#[test] +fn record_iter_stops_at_oversized_length() { + let mut wire = keepalive_record(946_684_801); + wire.extend_from_slice(&oversized_record()); + wire.extend_from_slice(&keepalive_record(946_684_802)); + + let records: Vec = BgpkitParser::from_reader(Cursor::new(wire)) + .into_record_iter() + .collect(); + + let timestamps: Vec = records + .iter() + .map(|record| record.common_header.timestamp) + .collect(); + assert_eq!(timestamps, vec![946_684_801]); +} + +#[test] +fn fallible_record_iter_yields_unknown_type_error_then_next_record() { + let mut wire = unknown_type_record(); + wire.extend_from_slice(&keepalive_record(946_684_801)); + + let mut iter = BgpkitParser::from_reader(Cursor::new(wire)).into_fallible_record_iter(); + + let error = iter.next().expect("unknown-type error").unwrap_err(); + assert!(matches!(error.error, ParserError::ParseError(_))); + assert_eq!( + error.bytes.as_deref(), + Some(unknown_type_record().as_slice()) + ); + let record = iter.next().expect("following record").unwrap(); + assert_eq!(record.common_header.timestamp, 946_684_801); + assert!(iter.next().is_none()); +} + +#[test] +fn fallible_record_iter_ends_after_oversized_length() { + let mut wire = oversized_record(); + wire.extend_from_slice(&keepalive_record(946_684_801)); + + let mut iter = BgpkitParser::from_reader(Cursor::new(wire)).into_fallible_record_iter(); + + let error = iter.next().expect("oversized error").unwrap_err(); + assert!(matches!( + error.error, + ParserError::OversizedRecord { length } if length == 17 * 1024 * 1024 + )); + assert!(iter.next().is_none()); +} diff --git a/src/parser/iters/diagnostic.rs b/src/parser/iters/diagnostic.rs index 981f594a..42594330 100644 --- a/src/parser/iters/diagnostic.rs +++ b/src/parser/iters/diagnostic.rs @@ -93,8 +93,9 @@ impl Iterator for DiagnosticIterator { } Err(error) => { // A framing error may leave the reader between record boundaries. Do not - // attempt to reinterpret the remaining bytes as another MRT header. - self.terminated = true; + // attempt to reinterpret the remaining bytes as another MRT header unless + // the declared record was consumed whole (an unknown entry type). + self.terminated = !error.aligned; return Some(DiagnosticEvent::ParseError { error: error.error, common_header: error.common_header, @@ -687,6 +688,61 @@ mod tests { assert!(iter.next().is_none()); } + #[test] + fn diagnostic_iterator_continues_after_unknown_entry_type() { + // An unknown entry type is skipped whole, so the reader is still on a + // record boundary and the following record must be reported. + let mut unknown = vec![ + 0, 0, 0, 1, // timestamp + 0x77, 0x77, // unknown entry type + 0, 0, // subtype + 0, 0, 0, 20, // length + ]; + unknown.extend_from_slice(&[0, 0, 0, 1, 0, 5, 0, 7, 0, 0, 0, 32]); + unknown.extend_from_slice(&[0xaa; 8]); + let mut input = unknown.clone(); + input.extend_from_slice(&update_record(valid_attributes()).encode().unwrap()); + + let mut iter = BgpkitParser::from_reader(Cursor::new(input)).into_diagnostic_iter(); + match iter.next().unwrap() { + DiagnosticEvent::ParseError { + error, + common_header, + raw_bytes, + .. + } => { + assert!(matches!(error, ParserError::ParseError(_))); + assert_eq!(common_header, None); + assert_eq!(raw_bytes.as_deref(), Some(unknown.as_slice())); + } + event => panic!("expected parse error event, got {event:?}"), + } + assert!(matches!(iter.next(), Some(DiagnosticEvent::Record { .. }))); + assert!(iter.next().is_none()); + } + + #[test] + fn diagnostic_iterator_terminates_after_truncated_unknown_entry_type() { + // The declared body outruns the stream, so no boundary is known and the + // iterator must not poll again. + let input = vec![ + 0, 0, 0, 1, // timestamp + 0x77, 0x77, // unknown entry type + 0, 0, // subtype + 0, 0, 0, 8, // length, but only 4 body bytes follow + 1, 2, 3, 4, + ]; + + let mut iter = BgpkitParser::from_reader(Cursor::new(input.clone())).into_diagnostic_iter(); + match iter.next().unwrap() { + DiagnosticEvent::ParseError { raw_bytes, .. } => { + assert_eq!(raw_bytes.as_deref(), Some(input.as_slice())); + } + event => panic!("expected parse error event, got {event:?}"), + } + assert!(iter.next().is_none()); + } + #[test] fn diagnostic_iterator_preserves_invalid_header_bytes() { let invalid_header = vec![ diff --git a/src/parser/iters/mod.rs b/src/parser/iters/mod.rs index 61f5ffcf..7e197630 100644 --- a/src/parser/iters/mod.rs +++ b/src/parser/iters/mod.rs @@ -70,16 +70,24 @@ fn next_fallible_raw_record( None } Err(error) => { - if let ParserError::IoError(io_error) | ParserError::EofError(io_error) = &error.error { - // A resumed pull starts a fresh header, so retrying is only safe - // when the failed read consumed nothing; otherwise the partial - // framing bytes are gone and the stream stays misaligned. - let nothing_consumed = error.bytes.as_ref().is_none_or(Vec::is_empty); - *finished = !(nothing_consumed - && matches!( - io_error.kind(), - std::io::ErrorKind::Interrupted | std::io::ErrorKind::WouldBlock - )); + match &error.error { + ParserError::IoError(io_error) | ParserError::EofError(io_error) => { + // A resumed pull starts a fresh header, so retrying is only safe + // when the failed read consumed nothing; otherwise the partial + // framing bytes are gone and the stream stays misaligned. + let nothing_consumed = error.bytes.as_ref().is_none_or(Vec::is_empty); + *finished = !(nothing_consumed + && matches!( + io_error.kind(), + std::io::ErrorKind::Interrupted | std::io::ErrorKind::WouldBlock + )); + } + ParserError::OversizedRecord { .. } => { + // The declared length is untrusted, so the reader sits at no + // known record boundary and must not be polled again. + *finished = true; + } + _ => {} } Some(Err(error)) } @@ -165,6 +173,16 @@ pub(crate) fn handle_record_parse_error( // normal end of file false } + ParserError::OversizedRecord { length } => { + // The length field itself is corrupt, so there is no record boundary + // to skip to; continuing would reinterpret the body as headers. + error!( + "parser error: MRT message too large: {} bytes; stream position is unreliable, stopping", + length + ); + write_mrt_core_dump(parser.core_dump, bytes); + false + } ParserError::IoError(err) | ParserError::EofError(err) => { // when reaching IO error, stop iterating error!("{:?}", err); diff --git a/src/parser/iters/route.rs b/src/parser/iters/route.rs index 2c58265d..418c3291 100644 --- a/src/parser/iters/route.rs +++ b/src/parser/iters/route.rs @@ -1950,7 +1950,10 @@ mod tests { let mut iter = BgpkitParser::from_reader(Cursor::new(invalid_data.clone())).into_fallible_route_iter(); + // The unknown-type record is skipped whole, so the error carries the + // header and the declared body, and the stream ends cleanly after it. let error = iter.next().unwrap().unwrap_err(); - assert_eq!(error.bytes.as_deref(), Some(&invalid_data[..12])); + assert_eq!(error.bytes.as_deref(), Some(invalid_data.as_slice())); + assert!(iter.next().is_none()); } } diff --git a/src/parser/mrt/mrt_record.rs b/src/parser/mrt/mrt_record.rs index 2b264138..c75b8d09 100644 --- a/src/parser/mrt/mrt_record.rs +++ b/src/parser/mrt/mrt_record.rs @@ -16,6 +16,12 @@ use std::net::IpAddr; use std::path::Path; use std::str::FromStr; +/// Upper bound on the MRT body length the parser will read into memory. +const MAX_MRT_MESSAGE_LEN: u32 = 16 * 1024 * 1024; // 16 MiB + +/// Length of the MRT common header without the ET microsecond timestamp. +const MRT_BASE_HEADER_LEN: usize = 12; + /// Raw MRT record containing the common header and unparsed message bytes. /// This allows for lazy parsing of the MRT message body, and provides /// utilities for debugging and exporting problematic records. @@ -33,6 +39,9 @@ pub(crate) struct RawMrtRecordError { pub(crate) error: ParserError, pub(crate) common_header: Option, pub(crate) bytes: Option>, + /// The reader was left at the next record boundary, so framing can continue + /// after this error. False whenever the body was not consumed whole. + pub(crate) aligned: bool, } impl RawMrtRecord { @@ -139,37 +148,21 @@ pub(crate) fn chunk_mrt_record_with_context( captured: &mut consumed_header, }) { Ok(v) => v, - Err(e) => { - if let ParserError::EofError(e) = &e { - if e.kind() == std::io::ErrorKind::UnexpectedEof && consumed_header.is_empty() { - return Err(RawMrtRecordError { - error: ParserError::EofExpected, - common_header: None, - bytes: None, - }); - } - } - return Err(RawMrtRecordError { - error: e, - common_header: None, - bytes: Some(consumed_header), - }); - } + Err(error) => return Err(header_error(input, error, consumed_header)), }; let common_header = parsed_header.header; let header_bytes = parsed_header.raw_bytes; // Protect against unreasonable allocations from corrupt headers - const MAX_MRT_MESSAGE_LEN: u32 = 16 * 1024 * 1024; // 16 MiB upper bound if common_header.length > MAX_MRT_MESSAGE_LEN { return Err(RawMrtRecordError { - error: ParserError::Unsupported(format!( - "MRT message too large: {} bytes", - common_header.length - )), + error: ParserError::OversizedRecord { + length: common_header.length, + }, common_header: Some(common_header), bytes: Some(header_bytes.to_vec()), + aligned: false, }); } @@ -245,6 +238,73 @@ pub(crate) fn chunk_mrt_record_with_context( }) } +/// Build the framing error for a common header that could not be parsed. +/// +/// When the 12-byte base header was read whole but its contents were rejected +/// (an entry type the parser does not know, or an ET length below four), the +/// declared body is still unread in the stream. Consume it here so the reader is +/// left at the next record boundary: the skip-and-continue iterators would +/// otherwise reinterpret the body as the next header and misparse everything +/// after it. The skipped body is kept in `bytes` so core dumps and recovery see +/// the whole record. A declared length over the limit is reported as +/// [`ParserError::OversizedRecord`] instead, since it cannot be trusted. +fn header_error( + input: &mut impl Read, + error: ParserError, + mut consumed: Vec, +) -> RawMrtRecordError { + if let ParserError::EofError(io_error) = &error { + if io_error.kind() == std::io::ErrorKind::UnexpectedEof && consumed.is_empty() { + return RawMrtRecordError { + error: ParserError::EofExpected, + common_header: None, + bytes: None, + aligned: false, + }; + } + } + + if matches!(error, ParserError::ParseError(_)) && consumed.len() == MRT_BASE_HEADER_LEN { + // The on-wire length counts every byte after the 12-byte base header, + // including the microsecond timestamp of an ET record, so skipping it + // lands on the next record whatever the unknown type would have been. + let length = u32::from_be_bytes(consumed[8..12].try_into().unwrap()); + if length > MAX_MRT_MESSAGE_LEN { + return RawMrtRecordError { + error: ParserError::OversizedRecord { length }, + common_header: None, + bytes: Some(consumed), + aligned: false, + }; + } + if let Err(io_error) = input.take(length as u64).read_to_end(&mut consumed) { + return RawMrtRecordError { + error: ParserError::IoError(io_error), + common_header: None, + bytes: Some(consumed), + aligned: false, + }; + } + // A short read means the stream ended inside this record. The next + // chunk attempt then reads nothing and reports `EofExpected`, so the + // header error is the one worth reporting here. + let aligned = consumed.len() == MRT_BASE_HEADER_LEN + length as usize; + return RawMrtRecordError { + error, + common_header: None, + bytes: Some(consumed), + aligned, + }; + } + + RawMrtRecordError { + error, + common_header: None, + bytes: Some(consumed), + aligned: false, + } +} + struct CapturingReader<'a, R: ?Sized> { inner: &'a mut R, captured: &'a mut Vec, @@ -271,6 +331,7 @@ fn record_io_error( error: ParserError::IoError(error), common_header: Some(common_header), bytes: Some(bytes), + aligned: false, } } @@ -766,4 +827,117 @@ mod tests { let error = chunk_mrt_record(&mut Cursor::new(wire.clone().freeze())).unwrap_err(); assert_eq!(error.bytes.as_deref(), Some(wire.as_ref())); } + + /// A record of type 0x7777 whose 20-byte body reads as a plausible common + /// header (timestamp 1, type BGP, subtype 7, length 8), so a reader that + /// skips only the 12 header bytes would treat the body as the next record. + fn unknown_type_record() -> Vec { + let mut wire = BytesMut::new(); + wire.put_u32(946_684_800); + wire.put_u16(0x7777); + wire.put_u16(0); + wire.put_u32(20); + wire.put_slice(&[0, 0, 0, 1, 0, 5, 0, 7, 0, 0, 0, 32]); + wire.put_slice(&[0xaa; 8]); + wire.to_vec() + } + + fn keepalive_record() -> (CommonHeader, Vec) { + let body = vec![0, 1, 192, 0, 2, 1, 0, 2, 192, 0, 2, 2]; + let header = CommonHeader { + timestamp: 946_684_801, + microsecond_timestamp: None, + entry_type: EntryType::BGP, + entry_subtype: 7, + length: body.len() as u32, + }; + let mut wire = header.encode().to_vec(); + wire.extend_from_slice(&body); + (header, wire) + } + + #[test] + fn chunk_skips_body_of_unknown_entry_type() { + let unknown = unknown_type_record(); + let (next_header, next_wire) = keepalive_record(); + let mut wire = unknown.clone(); + wire.extend_from_slice(&next_wire); + let mut cursor = Cursor::new(wire); + + let error = chunk_mrt_record(&mut cursor).unwrap_err(); + assert!( + matches!(&error.error, ParserError::ParseError(msg) if msg.contains("entry type")), + "unexpected error: {}", + error.error + ); + assert_eq!(error.bytes.as_deref(), Some(unknown.as_slice())); + assert_eq!(cursor.position(), unknown.len() as u64); + + let next = chunk_mrt_record(&mut cursor).unwrap(); + assert_eq!(next.common_header, next_header); + assert!(matches!( + next.parse().unwrap().message, + MrtMessage::LegacyBgp(LegacyBgp::Message(LegacyBgpMessage { + bgp_message: BgpMessage::KeepAlive, + .. + })) + )); + assert!(matches!( + chunk_mrt_record(&mut cursor).unwrap_err().error, + ParserError::EofExpected + )); + } + + #[test] + fn chunk_reports_header_error_when_unknown_type_body_is_truncated() { + let unknown = unknown_type_record(); + let truncated = &unknown[..unknown.len() - 5]; + let mut cursor = Cursor::new(truncated.to_vec()); + + let error = chunk_mrt_record(&mut cursor).unwrap_err(); + assert!(matches!(error.error, ParserError::ParseError(_))); + assert_eq!(error.bytes.as_deref(), Some(truncated)); + assert!(matches!( + chunk_mrt_record(&mut cursor).unwrap_err().error, + ParserError::EofExpected + )); + } + + #[test] + fn chunk_reports_oversized_length_without_reading_body() { + let mut wire = BytesMut::new(); + wire.put_u32(1); + wire.put_u16(EntryType::BGP as u16); + wire.put_u16(7); + wire.put_u32(MAX_MRT_MESSAGE_LEN + 1); + wire.put_slice(&[0xaa; 32]); + let mut cursor = Cursor::new(wire.to_vec()); + + let error = chunk_mrt_record(&mut cursor).unwrap_err(); + assert!(matches!( + error.error, + ParserError::OversizedRecord { length } if length == MAX_MRT_MESSAGE_LEN + 1 + )); + assert_eq!(error.bytes.as_deref(), Some(&wire[..12])); + assert_eq!(cursor.position(), 12); + } + + #[test] + fn chunk_reports_oversized_length_for_unknown_entry_type() { + let mut wire = BytesMut::new(); + wire.put_u32(1); + wire.put_u16(0x7777); + wire.put_u16(0); + wire.put_u32(u32::MAX); + wire.put_slice(&[0xaa; 32]); + let mut cursor = Cursor::new(wire.to_vec()); + + let error = chunk_mrt_record(&mut cursor).unwrap_err(); + assert!(matches!( + error.error, + ParserError::OversizedRecord { length: u32::MAX } + )); + assert_eq!(error.bytes.as_deref(), Some(&wire[..12])); + assert_eq!(cursor.position(), 12); + } } diff --git a/tests/torn_mrt_records.rs b/tests/torn_mrt_records.rs index 29d0c0c9..5cd49e64 100644 --- a/tests/torn_mrt_records.rs +++ b/tests/torn_mrt_records.rs @@ -35,8 +35,17 @@ //! UPDATE, 307 STATE_CHANGE, 34 KEEPALIVE), 5,378 elements, zero errors — so there //! is no body-level parsing defect here. What is missing is stream //! resynchronization: on a framing error the reader has no pushback and cannot scan -//! forward for the next plausible common header, so every iterator either retries -//! at the same wrong offset or stops. +//! forward for the next plausible common header. From offset 14,756 the parser +//! frames two more "headers" out of mid-record bytes before giving up: +//! +//! ```text +//! 00 cb 25 ff 7e 31 6e c1 00 00 01 00 unknown entry type 32305, 256-byte body +//! de 57 0c 14 c8 bc 80 38 dc 36 b9 00 length 3,694,573,824 exceeds the 16 MiB limit +//! ``` +//! +//! The unknown-type record is skipped whole, which keeps the reader on whatever +//! boundary it is on, and the oversized length stops iteration because the length +//! cannot be trusted. //! //! The assertions below therefore pin **current, lossy** behaviour rather than //! desired behaviour. Every count is a deterministic function of the fixture bytes. @@ -57,10 +66,13 @@ const FIXTURE: &str = "tests/fixtures/ripe/rrc00/2000.03/updates.20000325.0345.g /// holds 2,580 recoverable records and 5,378 recoverable elements, so all but these /// four are lost. const RECORDS_BEFORE_FIRST_TORN_WRITE: usize = 4; -/// Errors produced while the parser hunts forward 12 bytes at a time after -/// desynchronizing. It never re-aligns, because the true record boundary is not a -/// multiple of 12 from where the oversized read left it. -const DESYNCHRONIZED_ERRORS: usize = 128; +/// Errors produced from the torn write onwards: the truncated 14,556-byte body, +/// the unknown-type "record" skipped whole, and the oversized length that ends +/// iteration. +const DESYNCHRONIZED_ERRORS: usize = 3; +/// Body length the unknown-type "header" at offset 14,756 declares; its 12 header +/// bytes plus this body are consumed and attached to the error. +const UNKNOWN_TYPE_BODY_LENGTH: usize = 256; /// Header the parser manufactures from the 10-byte torn write at offset 188. const TORN_HEADER_TIMESTAMP: u32 = 953_955_944; @@ -87,16 +99,13 @@ fn torn_writes_desynchronize_raw_record_framing() { } // Only 5 of the fixture's 2,580 records reach framing — 4 genuine ones plus the - // 14,556-byte torn "record" — after which the parser frames 3 more headers out of - // misaligned bytes. - assert_eq!(raw_records, 8); + // 14,556-byte torn "record". The misaligned bytes after it frame no further + // records: one header has an unknown type and is skipped, the next declares an + // oversized body and stops the iterator. + assert_eq!(raw_records, 5); assert_eq!( headers, BTreeMap::from([ - ( - (EntryType::NULL as u16, 256), - 3 // pure garbage, framed mid-record after desynchronizing - ), ( (EntryType::BGP as u16, 1), 4 // 3 genuine UPDATEs plus the torn 14,556-byte "record" @@ -110,8 +119,8 @@ fn torn_writes_desynchronize_raw_record_framing() { fn torn_writes_lose_all_but_four_records() { let source = repo_fixture(FIXTURE); - // Skipping iterators: the error arms can only retry at the same wrong offset or - // stop, so 2,576 of 2,580 records and 5,374 of 5,378 elements are lost. + // Skipping iterators: the error arms can only skip a framed record or stop, so + // 2,576 of 2,580 records and 5,374 of 5,378 elements are lost. assert_eq!( BgpkitParser::new(&source) .unwrap() @@ -207,9 +216,10 @@ fn diagnostic_iterator_reports_both_torn_writes() { .into_diagnostic_iter() .collect(); - // Four clean records, then one body error, then one framing error which - // terminates the iterator by design. - assert_eq!(events.len(), RECORDS_BEFORE_FIRST_TORN_WRITE + 2); + // Four clean records, then one body error, then the unknown-type record that + // is skipped whole, then the oversized length which terminates the iterator + // by design. + assert_eq!(events.len(), RECORDS_BEFORE_FIRST_TORN_WRITE + 3); for event in &events[..RECORDS_BEFORE_FIRST_TORN_WRITE] { let DiagnosticEvent::Record { record, .. } = event else { panic!("expected a clean record, got {event:?}"); @@ -249,8 +259,9 @@ fn diagnostic_iterator_reports_both_torn_writes() { ); // The oversized read left the stream mid-record, so the next 12 bytes are not a - // header. There is no header to report, and the framing error terminates - // iteration rather than reinterpreting the remaining bytes. + // header. There is no header to report; the declared 256-byte body is consumed + // and attached, and because the record was consumed whole the iterator carries + // on from the byte after it. let DiagnosticEvent::ParseError { error, common_header, @@ -268,5 +279,35 @@ fn diagnostic_iterator_reports_both_torn_writes() { }; assert_eq!(message, "cannot parse entry type: 32305"); assert!(common_header.is_none()); + assert_eq!( + raw_bytes.as_deref().map(<[u8]>::len), + Some(12 + UNKNOWN_TYPE_BODY_LENGTH) + ); + + // The bytes after that have another unknown entry type (51388) and declare a + // body the parser will not read. The length cannot be trusted, so there is no + // boundary to continue from and the framing error terminates iteration. + let DiagnosticEvent::ParseError { + error, + common_header, + raw_bytes, + .. + } = &events[RECORDS_BEFORE_FIRST_TORN_WRITE + 2] + else { + panic!( + "expected an oversized-length error, got {:?}", + events[RECORDS_BEFORE_FIRST_TORN_WRITE + 2] + ); + }; + assert!( + matches!( + error, + ParserError::OversizedRecord { + length: 3_694_573_824 + } + ), + "expected OversizedRecord, got {error:?}" + ); + assert!(common_header.is_none()); assert_eq!(raw_bytes.as_deref().map(<[u8]>::len), Some(12)); } From 6f2d955197b587b731087716d26a3281fe52403f Mon Sep 17 00:00:00 2001 From: Ties de Kock Date: Sun, 11 Oct 2026 15:26:40 +0200 Subject: [PATCH 2/3] refactor(mrt): frame rejected headers by their declared length Read the common header's length separately from validating its contents, so chunk_mrt_record reads the body of every record the same way and rejects an unknown entry type (or an ET length below four) only once the record is consumed. This replaces header_error, which guessed the case from the error type and bytes consumed and repeated the 16 MiB check. A truncated unknown-type body now reports the truncated-body I/O error, like any other record. Rename RawMrtRecordError::aligned to record_consumed: reading the declared body does not prove the record started on a real boundary. Assisted-by: Claude Code --- src/parser/iters/diagnostic.rs | 4 +- src/parser/mrt/mrt_header.rs | 61 ++++++++--- src/parser/mrt/mrt_record.rs | 183 +++++++++++++++------------------ 3 files changed, 136 insertions(+), 112 deletions(-) diff --git a/src/parser/iters/diagnostic.rs b/src/parser/iters/diagnostic.rs index 42594330..5bb8e8c0 100644 --- a/src/parser/iters/diagnostic.rs +++ b/src/parser/iters/diagnostic.rs @@ -94,8 +94,8 @@ impl Iterator for DiagnosticIterator { Err(error) => { // A framing error may leave the reader between record boundaries. Do not // attempt to reinterpret the remaining bytes as another MRT header unless - // the declared record was consumed whole (an unknown entry type). - self.terminated = !error.aligned; + // a rejected header's record was consumed whole. + self.terminated = !error.record_consumed; return Some(DiagnosticEvent::ParseError { error: error.error, common_header: error.common_header, diff --git a/src/parser/mrt/mrt_header.rs b/src/parser/mrt/mrt_header.rs index 70bbf898..2522e3da 100644 --- a/src/parser/mrt/mrt_header.rs +++ b/src/parser/mrt/mrt_header.rs @@ -118,6 +118,27 @@ pub fn parse_common_header(input: &mut T) -> Result(input: &mut T) -> Result { + let framed = frame_common_header(input)?; + Ok(ParsedHeader { + header: framed.header?, + raw_bytes: framed.raw_bytes, + }) +} + +/// A common header as read from the wire, with its contents validated separately +/// from its framing. +pub(crate) struct FramedHeader { + /// The parsed header, or why its contents were rejected. + pub(crate) header: Result, + /// The header bytes as read from the wire. + pub(crate) raw_bytes: Bytes, + /// Length of the record body following `raw_bytes`. + pub(crate) body_length: u32, +} + +/// Read a common header, keeping its body length even when the contents are +/// rejected. Only I/O failures are returned as `Err`. +pub(crate) fn frame_common_header(input: &mut T) -> std::io::Result { let mut base_bytes = [0u8; 12]; input.read_exact(&mut base_bytes)?; @@ -126,40 +147,56 @@ pub fn parse_common_header_with_bytes(input: &mut T) -> Result entry_type, + Err(error) => return Ok(rejected(error.into())), + }; + + let (microsecond_timestamp, raw_bytes, body_length) = match &entry_type { EntryType::BGP4MP_ET => { // For ET records, the on-wire length includes the extra 4-byte microsecond timestamp // that lives in the header. Internally we store `length` as the message length only, // so subtract 4 after validating to avoid underflow. if length < 4 { - return Err(ParserError::ParseError( + return Ok(rejected(ParserError::ParseError( "invalid MRT header length for ET record: length < 4".into(), - )); + ))); } - length -= 4; let mut combined = [0u8; 16]; combined[..12].copy_from_slice(&base_bytes); input.read_exact(&mut combined[12..])?; let microseconds = u32::from_be_bytes(combined[12..16].try_into().unwrap()); - (Some(microseconds), Bytes::copy_from_slice(&combined)) + ( + Some(microseconds), + Bytes::copy_from_slice(&combined), + length - 4, + ) } - _ => (None, Bytes::copy_from_slice(&base_bytes)), + _ => (None, Bytes::copy_from_slice(&base_bytes), length), }; - Ok(ParsedHeader { - header: CommonHeader { + Ok(FramedHeader { + header: Ok(CommonHeader { timestamp, microsecond_timestamp, entry_type, entry_subtype, - length, - }, + length: body_length, + }), raw_bytes, + body_length, }) } diff --git a/src/parser/mrt/mrt_record.rs b/src/parser/mrt/mrt_record.rs index c75b8d09..5603d29d 100644 --- a/src/parser/mrt/mrt_record.rs +++ b/src/parser/mrt/mrt_record.rs @@ -1,4 +1,4 @@ -use super::mrt_header::parse_common_header_with_bytes; +use super::mrt_header::frame_common_header; use crate::bmp::messages::{BmpMessage, BmpMessageBody}; use crate::error::{check_max, EncodingError, ParserError}; use crate::models::*; @@ -19,9 +19,6 @@ use std::str::FromStr; /// Upper bound on the MRT body length the parser will read into memory. const MAX_MRT_MESSAGE_LEN: u32 = 16 * 1024 * 1024; // 16 MiB -/// Length of the MRT common header without the ET microsecond timestamp. -const MRT_BASE_HEADER_LEN: usize = 12; - /// Raw MRT record containing the common header and unparsed message bytes. /// This allows for lazy parsing of the MRT message body, and provides /// utilities for debugging and exporting problematic records. @@ -39,9 +36,10 @@ pub(crate) struct RawMrtRecordError { pub(crate) error: ParserError, pub(crate) common_header: Option, pub(crate) bytes: Option>, - /// The reader was left at the next record boundary, so framing can continue - /// after this error. False whenever the body was not consumed whole. - pub(crate) aligned: bool, + /// The header was rejected after its declared body was read in full, so the + /// next read starts after this record (which is not proof the record itself + /// started on a true boundary). + pub(crate) record_consumed: bool, } impl RawMrtRecord { @@ -141,60 +139,88 @@ pub fn chunk_mrt_record(input: &mut impl Read) -> Result Result { - // parse common header and capture raw bytes + // read the common header and capture raw bytes let mut consumed_header = Vec::with_capacity(16); - let parsed_header = match parse_common_header_with_bytes(&mut CapturingReader { + let framed = match frame_common_header(&mut CapturingReader { inner: input, captured: &mut consumed_header, }) { - Ok(v) => v, - Err(error) => return Err(header_error(input, error, consumed_header)), + Ok(framed) => framed, + Err(error) => { + if error.kind() == std::io::ErrorKind::UnexpectedEof && consumed_header.is_empty() { + return Err(RawMrtRecordError { + error: ParserError::EofExpected, + common_header: None, + bytes: None, + record_consumed: false, + }); + } + return Err(RawMrtRecordError { + error: error.into(), + common_header: None, + bytes: Some(consumed_header), + record_consumed: false, + }); + } }; - let common_header = parsed_header.header; - let header_bytes = parsed_header.raw_bytes; + let header_bytes = framed.raw_bytes; + let parsed_header = framed.header.as_ref().ok().copied(); // Protect against unreasonable allocations from corrupt headers - if common_header.length > MAX_MRT_MESSAGE_LEN { + if framed.body_length > MAX_MRT_MESSAGE_LEN { return Err(RawMrtRecordError { error: ParserError::OversizedRecord { - length: common_header.length, + length: framed.body_length, }, - common_header: Some(common_header), + common_header: parsed_header, bytes: Some(header_bytes.to_vec()), - aligned: false, + record_consumed: false, }); } // Read the declared body while retaining partial bytes on failure. - let mut buffer = Vec::with_capacity(common_header.length as usize + 4); + let mut buffer = Vec::with_capacity(framed.body_length as usize + 4); if let Err(error) = input - .take(common_header.length as u64) + .take(framed.body_length as u64) .read_to_end(&mut buffer) { return Err(record_io_error( error, - common_header, + parsed_header, &header_bytes, &buffer, )); } - if buffer.len() != common_header.length as usize { + if buffer.len() != framed.body_length as usize { return Err(record_io_error( std::io::Error::new( std::io::ErrorKind::UnexpectedEof, format!( "truncated MRT body: expected {} bytes, read {}", - common_header.length, + framed.body_length, buffer.len() ), ), - common_header, + parsed_header, &header_bytes, &buffer, )); } + // A rejected header is reported only now, so its body is not left in the stream. + let common_header = match framed.header { + Ok(common_header) => common_header, + Err(error) => { + return Err(RawMrtRecordError { + error, + common_header: None, + bytes: Some([&header_bytes[..], &buffer].concat()), + record_consumed: true, + }) + } + }; + if common_header.entry_type == EntryType::TABLE_DUMP && super::messages::table_dump::needs_legacy_length_correction( common_header.entry_subtype, @@ -206,7 +232,7 @@ pub(crate) fn chunk_mrt_record_with_context( buffer.extend_from_slice(&correction); return Err(record_io_error( error, - common_header, + Some(common_header), &header_bytes, &buffer, )); @@ -218,7 +244,7 @@ pub(crate) fn chunk_mrt_record_with_context( std::io::ErrorKind::UnexpectedEof, "truncated historical TABLE_DUMP length correction", ), - common_header, + Some(common_header), &header_bytes, &buffer, )); @@ -238,73 +264,6 @@ pub(crate) fn chunk_mrt_record_with_context( }) } -/// Build the framing error for a common header that could not be parsed. -/// -/// When the 12-byte base header was read whole but its contents were rejected -/// (an entry type the parser does not know, or an ET length below four), the -/// declared body is still unread in the stream. Consume it here so the reader is -/// left at the next record boundary: the skip-and-continue iterators would -/// otherwise reinterpret the body as the next header and misparse everything -/// after it. The skipped body is kept in `bytes` so core dumps and recovery see -/// the whole record. A declared length over the limit is reported as -/// [`ParserError::OversizedRecord`] instead, since it cannot be trusted. -fn header_error( - input: &mut impl Read, - error: ParserError, - mut consumed: Vec, -) -> RawMrtRecordError { - if let ParserError::EofError(io_error) = &error { - if io_error.kind() == std::io::ErrorKind::UnexpectedEof && consumed.is_empty() { - return RawMrtRecordError { - error: ParserError::EofExpected, - common_header: None, - bytes: None, - aligned: false, - }; - } - } - - if matches!(error, ParserError::ParseError(_)) && consumed.len() == MRT_BASE_HEADER_LEN { - // The on-wire length counts every byte after the 12-byte base header, - // including the microsecond timestamp of an ET record, so skipping it - // lands on the next record whatever the unknown type would have been. - let length = u32::from_be_bytes(consumed[8..12].try_into().unwrap()); - if length > MAX_MRT_MESSAGE_LEN { - return RawMrtRecordError { - error: ParserError::OversizedRecord { length }, - common_header: None, - bytes: Some(consumed), - aligned: false, - }; - } - if let Err(io_error) = input.take(length as u64).read_to_end(&mut consumed) { - return RawMrtRecordError { - error: ParserError::IoError(io_error), - common_header: None, - bytes: Some(consumed), - aligned: false, - }; - } - // A short read means the stream ended inside this record. The next - // chunk attempt then reads nothing and reports `EofExpected`, so the - // header error is the one worth reporting here. - let aligned = consumed.len() == MRT_BASE_HEADER_LEN + length as usize; - return RawMrtRecordError { - error, - common_header: None, - bytes: Some(consumed), - aligned, - }; - } - - RawMrtRecordError { - error, - common_header: None, - bytes: Some(consumed), - aligned: false, - } -} - struct CapturingReader<'a, R: ?Sized> { inner: &'a mut R, captured: &'a mut Vec, @@ -320,7 +279,7 @@ impl Read for CapturingReader<'_, R> { fn record_io_error( error: std::io::Error, - common_header: CommonHeader, + common_header: Option, header: &[u8], body: &[u8], ) -> RawMrtRecordError { @@ -329,9 +288,9 @@ fn record_io_error( bytes.extend_from_slice(body); RawMrtRecordError { error: ParserError::IoError(error), - common_header: Some(common_header), + common_header, bytes: Some(bytes), - aligned: false, + record_consumed: false, } } @@ -889,13 +848,41 @@ mod tests { } #[test] - fn chunk_reports_header_error_when_unknown_type_body_is_truncated() { + fn chunk_skips_body_of_et_header_with_short_length() { + let mut wire = BytesMut::new(); + wire.put_u32(1); + wire.put_u16(EntryType::BGP4MP_ET as u16); + wire.put_u16(4); + wire.put_u32(2); + wire.put_slice(&[0xaa; 2]); + let rejected = wire.to_vec(); + let (next_header, next_wire) = keepalive_record(); + wire.put_slice(&next_wire); + let mut cursor = Cursor::new(wire.to_vec()); + + let error = chunk_mrt_record_with_context(&mut cursor).unwrap_err(); + assert!(matches!(error.error, ParserError::ParseError(_))); + assert!(error.record_consumed); + assert_eq!(error.bytes.as_deref(), Some(rejected.as_slice())); + assert_eq!( + chunk_mrt_record(&mut cursor).unwrap().common_header, + next_header + ); + } + + #[test] + fn chunk_reports_truncated_body_of_unknown_entry_type() { let unknown = unknown_type_record(); let truncated = &unknown[..unknown.len() - 5]; let mut cursor = Cursor::new(truncated.to_vec()); - let error = chunk_mrt_record(&mut cursor).unwrap_err(); - assert!(matches!(error.error, ParserError::ParseError(_))); + let error = chunk_mrt_record_with_context(&mut cursor).unwrap_err(); + assert!(matches!( + &error.error, + ParserError::IoError(io_error) if io_error.kind() == std::io::ErrorKind::UnexpectedEof + )); + assert!(error.common_header.is_none()); + assert!(!error.record_consumed); assert_eq!(error.bytes.as_deref(), Some(truncated)); assert!(matches!( chunk_mrt_record(&mut cursor).unwrap_err().error, From 8359c3d238b4d22969b1384bf869a231b52e259a Mon Sep 17 00:00:00 2001 From: Ties de Kock Date: Sun, 11 Oct 2026 15:28:39 +0200 Subject: [PATCH 3/3] docs: trim and correct comments on MRT framing errors Keep the "length is untrusted, so stop" reasoning on the OversizedRecord variant and shorten the call sites and changelog entries that repeated it. Fix the test-helper length (32, not 8), the oversized_record() doc that described bytes its callers append, and the torn-write test comments that implied skipping the unknown-type record restores alignment. Credit the framing fixes in the changelog's Contributors section. Assisted-by: Claude Code --- CHANGELOG.md | 6 +++--- src/error.rs | 7 +++---- src/parser/iters/default/tests.rs | 4 ++-- src/parser/iters/mod.rs | 6 ++---- src/parser/mrt/mrt_record.rs | 7 +++---- tests/torn_mrt_records.rs | 19 +++++++++---------- 6 files changed, 22 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c1c24e8a..ca67edc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,15 +24,15 @@ All notable changes to this project will be documented in this file. ### Fixed -* **Iterators stay aligned after an unknown MRT entry type**: `chunk_mrt_record` rejected an entry type it did not know after reading only the 12-byte header, leaving the record body in the stream. `into_record_iter`, `into_elem_iter`, `into_raw_record_iter` and the fallible iterators then read that body as the next header and misparsed or dropped every record after it. The body is now consumed before the error is returned, so the reader sits at the next record and the error's `bytes` hold the whole skipped record. `into_diagnostic_iter` reports the unknown-type record as a `ParseError` event and continues with the records after it, where it previously terminated on any framing error. -* **Iterators stop at an oversized MRT length instead of desynchronising**: a header declaring a body over 16 MiB left the reader at no usable boundary, yet the default and fallible iterators carried on and reinterpreted the body as headers. The skip-and-continue iterators now log the `OversizedRecord` error and end, and the fallible iterators yield it once and end. `into_recovering_record_iter` still scans forward as before. +* **Iterators stay aligned after an unknown MRT entry type**: `chunk_mrt_record` rejected an unknown entry type after reading only the 12-byte header, so `into_record_iter`, `into_elem_iter`, `into_raw_record_iter` and the fallible iterators read the record body as the next header and misparsed or dropped every record after it. The body is now consumed first, and the error's `bytes` hold the whole record. `into_diagnostic_iter` reports the record as a `ParseError` event and continues, where it previously stopped at any framing error. +* **Iterators stop at an oversized MRT length**: after a header declaring a body over 16 MiB, the default and fallible iterators read that body as headers. The default iterators now log the new `OversizedRecord` error and end, and the fallible iterators yield it once and end. `into_recovering_record_iter` still scans forward. * **RIS Live JSON elems carry `origin_asns`**: `parse_ris_live_message` left `origin_asns` empty, so an `origin_asn` filter never matched an elem parsed from RIS Live's JSON fields. It is now derived from the AS path, as `parse_ris_live_message_raw` and the MRT iterators already did. * **Dissection span correlation is linear in the number of warnings**: `span_record_warnings` (used by `DiagnosticIterator::with_dissection`) walked the whole dissection tree once per warning, so a BGP UPDATE carrying thousands of duplicate attributes took tens of seconds to diagnose. The tree is now indexed by field name once per record. Spans are unchanged. * **Fallible iterators stop after a fatal stream read error**: `into_fallible_record_iter`, `into_fallible_elem_iter`, `into_fallible_update_iter` and `into_fallible_route_iter` now yield a framing I/O or decompression error once and then end, instead of polling a spent decoder indefinitely. An `Interrupted`/`WouldBlock` read stays retryable only when it consumed no framing bytes, and skippable malformed records are unchanged ([#350](https://github.com/bgpkit/bgpkit-parser/pull/350)). ### Contributors -* @ties — faster elem conversion ([#348](https://github.com/bgpkit/bgpkit-parser/pull/348)), `parse_ris_live_message_iter` and RIS Live origin ASNs, once-per-parser parse error logging, linear-time dissection span correlation +* @ties — faster elem conversion ([#348](https://github.com/bgpkit/bgpkit-parser/pull/348)), `parse_ris_live_message_iter` and RIS Live origin ASNs, once-per-parser parse error logging, linear-time dissection span correlation, MRT framing after unknown entry types and oversized lengths ## v0.22.0 - 2026-09-10 diff --git a/src/error.rs b/src/error.rs index a8a8c046..76953b9e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -19,10 +19,9 @@ pub enum ParserError { ParseError(String), TruncatedMsg(String), Unsupported(String), - /// An MRT common header declared a body longer than the parser is willing to - /// read (16 MiB). The length field itself is untrusted, so the reader is left - /// just past the header with no known record boundary to resume from; the - /// skip-and-continue iterators stop rather than reinterpret the body as headers. + /// An MRT common header declared a body over the 16 MiB limit. The length is + /// untrusted, so the reader is left past the header with no record boundary to + /// resume from, and the iterators stop instead of reading the body as headers. OversizedRecord { /// The declared body length that exceeded the limit. length: u32, diff --git a/src/parser/iters/default/tests.rs b/src/parser/iters/default/tests.rs index 9632f6dd..6c7b80a6 100644 --- a/src/parser/iters/default/tests.rs +++ b/src/parser/iters/default/tests.rs @@ -35,8 +35,8 @@ fn keepalive_record(timestamp: u32) -> Vec { wire } -/// A header declaring a body larger than the parser will read, followed by -/// bytes that would parse as a valid record if the iterator carried on. +/// A bare header declaring a body over the 16 MiB limit. Tests append a valid +/// record after it to check that iteration does not resume there. fn oversized_record() -> Vec { let mut wire = BytesMut::new(); wire.put_u32(1); diff --git a/src/parser/iters/mod.rs b/src/parser/iters/mod.rs index 7e197630..a13f1606 100644 --- a/src/parser/iters/mod.rs +++ b/src/parser/iters/mod.rs @@ -83,8 +83,7 @@ fn next_fallible_raw_record( )); } ParserError::OversizedRecord { .. } => { - // The declared length is untrusted, so the reader sits at no - // known record boundary and must not be polled again. + // no record boundary to resume from *finished = true; } _ => {} @@ -174,8 +173,7 @@ pub(crate) fn handle_record_parse_error( false } ParserError::OversizedRecord { length } => { - // The length field itself is corrupt, so there is no record boundary - // to skip to; continuing would reinterpret the body as headers. + // no record boundary to resume from, stop iterating error!( "parser error: MRT message too large: {} bytes; stream position is unreliable, stopping", length diff --git a/src/parser/mrt/mrt_record.rs b/src/parser/mrt/mrt_record.rs index 5603d29d..c5834e57 100644 --- a/src/parser/mrt/mrt_record.rs +++ b/src/parser/mrt/mrt_record.rs @@ -36,9 +36,8 @@ pub(crate) struct RawMrtRecordError { pub(crate) error: ParserError, pub(crate) common_header: Option, pub(crate) bytes: Option>, - /// The header was rejected after its declared body was read in full, so the - /// next read starts after this record (which is not proof the record itself - /// started on a true boundary). + /// A rejected header's declared body was read in full, so the next read starts + /// after this record, though not necessarily on a true boundary. pub(crate) record_consumed: bool, } @@ -788,7 +787,7 @@ mod tests { } /// A record of type 0x7777 whose 20-byte body reads as a plausible common - /// header (timestamp 1, type BGP, subtype 7, length 8), so a reader that + /// header (timestamp 1, type BGP, subtype 7, length 32), so a reader that /// skips only the 12 header bytes would treat the body as the next record. fn unknown_type_record() -> Vec { let mut wire = BytesMut::new(); diff --git a/tests/torn_mrt_records.rs b/tests/torn_mrt_records.rs index 5cd49e64..e49fb600 100644 --- a/tests/torn_mrt_records.rs +++ b/tests/torn_mrt_records.rs @@ -43,9 +43,9 @@ //! de 57 0c 14 c8 bc 80 38 dc 36 b9 00 length 3,694,573,824 exceeds the 16 MiB limit //! ``` //! -//! The unknown-type record is skipped whole, which keeps the reader on whatever -//! boundary it is on, and the oversized length stops iteration because the length -//! cannot be trusted. +//! Skipping the unknown-type "record" by its declared length does not restore +//! alignment here: it moves 256 bytes further into the damage. Only the oversized +//! length stops iteration. //! //! The assertions below therefore pin **current, lossy** behaviour rather than //! desired behaviour. Every count is a deterministic function of the fixture bytes. @@ -258,10 +258,10 @@ fn diagnostic_iterator_reports_both_torn_writes() { Some(12 + TORN_HEADER_LENGTH as usize) ); - // The oversized read left the stream mid-record, so the next 12 bytes are not a - // header. There is no header to report; the declared 256-byte body is consumed - // and attached, and because the record was consumed whole the iterator carries - // on from the byte after it. + // The 14,556-byte read left the stream mid-record, so the next 12 bytes are not a + // real header. Their entry type is unknown, so no header is reported; the + // declared 256-byte body is consumed and attached, and the iterator carries on + // from the byte after it, still misaligned. let DiagnosticEvent::ParseError { error, common_header, @@ -284,9 +284,8 @@ fn diagnostic_iterator_reports_both_torn_writes() { Some(12 + UNKNOWN_TYPE_BODY_LENGTH) ); - // The bytes after that have another unknown entry type (51388) and declare a - // body the parser will not read. The length cannot be trusted, so there is no - // boundary to continue from and the framing error terminates iteration. + // The next 12 bytes have another unknown entry type (51388) and a length over + // the 16 MiB limit, which ends iteration. let DiagnosticEvent::ParseError { error, common_header,