Skip to main content

blob_decoder/
lib.rs

1//! `blob-decoder` — identify and decode opaque forensic blobs of unknown type.
2//!
3//! Hand it raw bytes; it reports what they are, decodes them, and returns
4//! **scored, cited candidates** — recursively unwrapping nested wrappers (a
5//! base64'd, gzip'd binary-plist is reported as the full
6//! `Base64 → Gzip → BinaryPlist` chain).
7//!
8//! The actual decoding is delegated to mature crates (`plist`, `base64`, `hex`,
9//! `uuid`, `flate2`, `snap`, `serde_json`); this crate adds only the
10//! orchestration layer: identify → dispatch → score → recursively unwrap, plus a
11//! clean forensic result type.
12//!
13//! # Epistemics
14//!
15//! A blob is often underdetermined: bytes that are valid hex are frequently also
16//! valid base64, and a run of ASCII is *technically* decodable as base64 to
17//! gibberish. `blob-decoder` never asserts a single verdict — it returns every
18//! plausible reading with an honest [`Confidence`], and a low-confidence reading
19//! lowers the rank, never hides the finding.
20//!
21//! # Example
22//!
23//! ```
24//! // gzip magic (0x1f 0x8b) → identified as a Gzip wrapper.
25//! let gz = b"\x1f\x8b\x08\x00\x00\x00\x00\x00";
26//! let cands = blob_decoder::identify(gz);
27//! assert_eq!(cands[0].kind, blob_decoder::BlobKind::Gzip);
28//! ```
29#![forbid(unsafe_code)]
30#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
31
32pub mod identify;
33
34pub use identify::{identify, identify_with_limits};
35
36/// The engine's version (`CARGO_PKG_VERSION`), for callers that surface it.
37pub const VERSION: &str = env!("CARGO_PKG_VERSION");
38
39/// A recognised (or unrecognised) blob type.
40///
41/// The `citation` and `label` are carried per-kind so a reading is traceable to
42/// the authoritative format definition it was matched against.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
44#[serde(rename_all = "snake_case")]
45pub enum BlobKind {
46    /// Apple binary property list (`bplist00` magic).
47    BinaryPlist,
48    /// Apple XML property list.
49    XmlPlist,
50    /// gzip member (`1f 8b` magic).
51    Gzip,
52    /// zlib stream (RFC 1950 header).
53    Zlib,
54    /// Snappy framed stream.
55    Snappy,
56    /// base64 text (standard or URL-safe alphabet).
57    Base64,
58    /// Hexadecimal text.
59    Hex,
60    /// A UUID / GUID (16 raw bytes or the canonical hyphenated string).
61    Uuid,
62    /// JSON (object or array root).
63    Json,
64    /// UTF-16LE text.
65    Utf16Le,
66    /// UTF-8 text (printable).
67    Utf8Text,
68    /// No known type matched — the raw head bytes are reported for the analyst.
69    Unknown,
70}
71
72impl BlobKind {
73    /// A short human label.
74    #[must_use]
75    pub fn label(self) -> &'static str {
76        match self {
77            Self::BinaryPlist => "Apple binary property list",
78            Self::XmlPlist => "Apple XML property list",
79            Self::Gzip => "gzip stream",
80            Self::Zlib => "zlib stream",
81            Self::Snappy => "Snappy framed stream",
82            Self::Base64 => "base64 text",
83            Self::Hex => "hexadecimal text",
84            Self::Uuid => "UUID / GUID",
85            Self::Json => "JSON",
86            Self::Utf16Le => "UTF-16LE text",
87            Self::Utf8Text => "UTF-8 text",
88            Self::Unknown => "unknown",
89        }
90    }
91
92    /// The authoritative spec / reference this kind is matched against.
93    #[must_use]
94    pub fn citation(self) -> &'static str {
95        match self {
96            Self::BinaryPlist | Self::XmlPlist => {
97                "Apple CoreFoundation CFBinaryPList.c; `man 5 plist`"
98            }
99            Self::Gzip => "RFC 1952 (GZIP file format)",
100            Self::Zlib => "RFC 1950 (ZLIB compressed data format)",
101            Self::Snappy => "google/snappy framing_format.txt",
102            Self::Base64 => "RFC 4648 §4-5 (Base 64 / Base64url)",
103            Self::Hex => "RFC 4648 §8 (Base 16)",
104            Self::Uuid => "RFC 9562 (UUID)",
105            Self::Json => "RFC 8259 (JSON)",
106            Self::Utf16Le => "The Unicode Standard; RFC 2781 (UTF-16LE)",
107            Self::Utf8Text => "RFC 3629 (UTF-8)",
108            Self::Unknown => "no matching format",
109        }
110    }
111
112    /// True when this kind is a *wrapper* whose payload is itself another blob
113    /// (base64/hex text, or a compression stream) — the recursion drivers.
114    #[must_use]
115    pub fn is_wrapper(self) -> bool {
116        matches!(
117            self,
118            Self::Gzip | Self::Zlib | Self::Snappy | Self::Base64 | Self::Hex
119        )
120    }
121}
122
123/// How strongly the evidence supports a reading. Ordered `Low < Medium < High`
124/// so candidates sort best-first by *descending* confidence.
125///
126/// - [`Confidence::High`] — a strong, near-unique MAGIC signature or a full
127///   successful structural parse (`bplist00`, `1f 8b`, a valid RFC 1950 header,
128///   a parseable JSON object, a canonical hyphenated UUID string).
129/// - [`Confidence::Medium`] — a magic matched but the payload failed to fully
130///   decode, or a heuristic wrapper (base64/hex) whose decoded payload was
131///   itself recognised as a concrete type.
132/// - [`Confidence::Low`] — a purely structural heuristic that a random blob
133///   could satisfy by coincidence (16 arbitrary bytes as a UUID; base64/hex text
134///   decoding only to more opaque bytes; plain printable text).
135#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
136#[serde(rename_all = "snake_case")]
137pub enum Confidence {
138    /// A coincidence-prone structural heuristic.
139    Low,
140    /// A magic matched but payload decode was partial, or a heuristic wrapper
141    /// whose payload was recognised.
142    Medium,
143    /// A strong magic signature or a full successful parse.
144    High,
145}
146
147/// One scored, cited candidate reading of a blob. A wrapper candidate nests the
148/// identification of its decoded payload in [`Candidate::inner`], so a
149/// `base64 → gzip → binary-plist` blob reports the whole chain.
150#[derive(Debug, Clone, serde::Serialize)]
151pub struct Candidate {
152    /// The identified (or unidentified) kind.
153    pub kind: BlobKind,
154    /// How strongly the evidence supports this reading.
155    pub score: Confidence,
156    /// A human summary of *what was found* (root type, byte counts, decoded
157    /// text prefix, or — for [`BlobKind::Unknown`] — the raw head bytes).
158    pub summary: String,
159    /// The authoritative spec citation for [`Candidate::kind`].
160    pub citation: &'static str,
161    /// For a wrapper kind, the identification of the decoded/decompressed
162    /// payload — the next link in the chain. `None` for a leaf reading, a failed
163    /// decode, or when the recursion depth cap was reached.
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub inner: Option<Box<DecodedChain>>,
166}
167
168/// The decoded payload of a wrapper [`Candidate`]: how many bytes it produced
169/// and the best reading of those bytes.
170#[derive(Debug, Clone, serde::Serialize)]
171pub struct DecodedChain {
172    /// Number of bytes the wrapper decoded/decompressed to (after any cap).
173    pub decoded_len: usize,
174    /// True when the decoded output was truncated at the size cap (a possible
175    /// decompression bomb) — the payload reading is of the capped prefix.
176    pub capped: bool,
177    /// The best (highest-confidence) reading of the decoded payload.
178    pub best: Box<Candidate>,
179}
180
181/// Resource bounds for [`identify_with_limits`] — the guard against
182/// decompression bombs and infinitely-nested wrappers on untrusted input.
183#[derive(Debug, Clone, Copy)]
184pub struct Limits {
185    /// Maximum recursion depth through nested wrappers.
186    pub max_depth: usize,
187    /// Maximum bytes to hold from a single decompression/decode step (a
188    /// decompression bomb is capped here, never allowed to exhaust memory).
189    pub max_output: usize,
190    /// Inputs larger than this skip the *heuristic* decoders (base64/hex/text);
191    /// magic-signature detection still runs. Bounds worst-case work.
192    pub max_input: usize,
193}
194
195impl Default for Limits {
196    fn default() -> Self {
197        Self {
198            max_depth: 8,
199            max_output: 64 * 1024 * 1024,
200            max_input: 128 * 1024 * 1024,
201        }
202    }
203}