Skip to main content

libtea_core/
signature_format.rs

1//! Recognize the format of detached signature bytes, without verifying them.
2//!
3//! **Experimental:** may change in a 0.x minor release.
4//!
5//! TEA "makes no assumption about the signature technology in use"
6//! (`openapi.yaml`, `/artifact/{uuid}/{artifactVersion}/signature/download`).
7//! This module looks at the bytes a server returned and says which known
8//! container they look like. That is all: a recognized format is **not** a
9//! valid signature, and nothing here checks a signature, a key or a signer.
10//! The server's `Content-Type` is not consulted, so a mislabelled response
11//! cannot change the answer.
12//!
13//! See `docs/design/signature-verification.md`, "Stage 1".
14
15/// Inputs longer than this are not inspected ([`SignatureFormat::TooLarge`]).
16pub const MAX_SIGNATURE_INSPECT_BYTES: usize = 1024 * 1024;
17
18/// The container a detached signature appears to use.
19///
20/// **Experimental:** may change in a 0.x minor release.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22#[non_exhaustive]
23pub enum SignatureFormat {
24    /// OpenPGP ASCII armor (`-----BEGIN PGP SIGNATURE-----`).
25    OpenPgpArmored,
26    /// A binary OpenPGP signature packet (tag 2, version 3 to 6).
27    OpenPgpBinary,
28    /// DER CMS `ContentInfo` whose content type is `SignedData`
29    /// (OID 1.2.840.113549.1.7.2).
30    Cms,
31    /// A JSON object whose `mediaType` starts with
32    /// `application/vnd.dev.sigstore.bundle`.
33    SigstoreBundle,
34    /// No bytes.
35    Empty,
36    /// More than [`MAX_SIGNATURE_INSPECT_BYTES`]; not inspected.
37    TooLarge,
38    /// None of the above.
39    Unknown,
40}
41
42impl SignatureFormat {
43    /// Stable lowercase name, used in CLI JSON output.
44    #[must_use]
45    pub fn as_str(self) -> &'static str {
46        match self {
47            Self::OpenPgpArmored => "openpgp_armored",
48            Self::OpenPgpBinary => "openpgp_binary",
49            Self::Cms => "cms",
50            Self::SigstoreBundle => "sigstore_bundle",
51            Self::Empty => "empty",
52            Self::TooLarge => "too_large",
53            Self::Unknown => "unknown",
54        }
55    }
56}
57
58/// Say which signature container `bytes` look like.
59///
60/// Never panics. Only the first bytes are read for the binary formats; the
61/// Sigstore check parses the whole input as JSON, which is why the input is
62/// capped at [`MAX_SIGNATURE_INSPECT_BYTES`] first.
63///
64/// ```
65/// use libtea_core::signature_format::{detect_signature_format, SignatureFormat};
66///
67/// let armored = b"-----BEGIN PGP SIGNATURE-----\n\niQEz...\n-----END PGP SIGNATURE-----\n";
68/// assert_eq!(detect_signature_format(armored), SignatureFormat::OpenPgpArmored);
69/// assert_eq!(detect_signature_format(b""), SignatureFormat::Empty);
70/// assert_eq!(detect_signature_format(b"not a signature"), SignatureFormat::Unknown);
71/// ```
72#[must_use]
73pub fn detect_signature_format(bytes: &[u8]) -> SignatureFormat {
74    if bytes.is_empty() {
75        return SignatureFormat::Empty;
76    }
77    if bytes.len() > MAX_SIGNATURE_INSPECT_BYTES {
78        return SignatureFormat::TooLarge;
79    }
80    if is_openpgp_armored(bytes) {
81        SignatureFormat::OpenPgpArmored
82    } else if is_openpgp_binary(bytes) {
83        SignatureFormat::OpenPgpBinary
84    } else if is_cms_signed_data(bytes) {
85        SignatureFormat::Cms
86    } else if is_sigstore_bundle(bytes) {
87        SignatureFormat::SigstoreBundle
88    } else {
89        SignatureFormat::Unknown
90    }
91}
92
93const PGP_ARMOR: &[u8] = b"-----BEGIN PGP SIGNATURE-----";
94
95fn is_openpgp_armored(bytes: &[u8]) -> bool {
96    let start = bytes
97        .iter()
98        .position(|b| !b.is_ascii_whitespace())
99        .unwrap_or(bytes.len());
100    let rest = &bytes[start..];
101    rest.starts_with(PGP_ARMOR) && matches!(rest.get(PGP_ARMOR.len()), Some(b'\r' | b'\n'))
102}
103
104/// RFC 9580 section 4.2: the packet header, then a signature packet body that
105/// starts with its version octet. The declared length must fit the input.
106fn is_openpgp_binary(bytes: &[u8]) -> bool {
107    let Some(&header) = bytes.first() else {
108        return false;
109    };
110    if header & 0x80 == 0 {
111        return false;
112    }
113    let (tag, body_start, body_len) = if header & 0x40 != 0 {
114        // New format: the tag is the low six bits.
115        let Some(&first) = bytes.get(1) else {
116            return false;
117        };
118        let (start, len) = match first {
119            0..=191 => (2, usize::from(first)),
120            192..=223 => match bytes.get(2) {
121                Some(&second) => (
122                    3,
123                    ((usize::from(first) - 192) << 8) + usize::from(second) + 192,
124                ),
125                None => return false,
126            },
127            255 => match bytes.get(2..6) {
128                Some(four) => (6, be_len(four)),
129                None => return false,
130            },
131            // Partial body lengths are not allowed for signature packets.
132            _ => return false,
133        };
134        (header & 0x3f, start, len)
135    } else {
136        // Legacy format: tag in bits 5..2, length type in bits 1..0.
137        let length_octets = match header & 0x03 {
138            0 => 1,
139            1 => 2,
140            2 => 4,
141            _ => return false,
142        };
143        match bytes.get(1..1 + length_octets) {
144            Some(octets) => ((header >> 2) & 0x0f, 1 + length_octets, be_len(octets)),
145            None => return false,
146        }
147    };
148    tag == 2
149        && body_len >= 1
150        && bytes.len() - body_start >= body_len
151        && matches!(bytes.get(body_start), Some(3..=6))
152}
153
154fn be_len(octets: &[u8]) -> usize {
155    octets.iter().fold(0usize, |acc, &b| {
156        acc.saturating_mul(256).saturating_add(usize::from(b))
157    })
158}
159
160/// DER encoding of OID 1.2.840.113549.1.7.2 (`id-signedData`), tag and length included.
161const SIGNED_DATA_OID: &[u8] = &[
162    0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02,
163];
164
165/// `ContentInfo ::= SEQUENCE { contentType OBJECT IDENTIFIER, ... }`: a SEQUENCE
166/// whose definite length fits the input, starting with the `SignedData` OID.
167fn is_cms_signed_data(bytes: &[u8]) -> bool {
168    if bytes.first() != Some(&0x30) {
169        return false;
170    }
171    let Some(&first) = bytes.get(1) else {
172        return false;
173    };
174    let (content_start, len) = if first < 0x80 {
175        (2, usize::from(first))
176    } else {
177        let count = usize::from(first & 0x7f);
178        if count == 0 || count > 4 {
179            return false;
180        }
181        match bytes.get(2..2 + count) {
182            Some(octets) => (2 + count, be_len(octets)),
183            None => return false,
184        }
185    };
186    len >= SIGNED_DATA_OID.len()
187        && bytes.len() - content_start >= len
188        && bytes[content_start..].starts_with(SIGNED_DATA_OID)
189}
190
191const SIGSTORE_BUNDLE_PREFIX: &str = "application/vnd.dev.sigstore.bundle";
192
193fn is_sigstore_bundle(bytes: &[u8]) -> bool {
194    let start = bytes
195        .iter()
196        .position(|b| !b.is_ascii_whitespace())
197        .unwrap_or(bytes.len());
198    if bytes.get(start) != Some(&b'{') {
199        return false;
200    }
201    #[derive(serde::Deserialize)]
202    struct Head {
203        #[serde(rename = "mediaType")]
204        media_type: Option<String>,
205    }
206    serde_json::from_slice::<Head>(bytes)
207        .ok()
208        .and_then(|head| head.media_type)
209        .is_some_and(|media_type| media_type.starts_with(SIGSTORE_BUNDLE_PREFIX))
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    /// A v4 signature packet: legacy header (tag 2, one length octet), body
217    /// starting with the version octet. Not a valid signature.
218    fn pgp_legacy(version: u8) -> Vec<u8> {
219        let body = [version, 0x00, 0x01, 0x08, 0x00, 0x00];
220        let mut packet = vec![0x88, body.len() as u8];
221        packet.extend_from_slice(&body);
222        packet
223    }
224
225    fn cms(extra: &[u8]) -> Vec<u8> {
226        let mut content = SIGNED_DATA_OID.to_vec();
227        content.extend_from_slice(extra);
228        let mut der = vec![0x30, content.len() as u8];
229        der.extend_from_slice(&content);
230        der
231    }
232
233    #[test]
234    fn armored_openpgp_with_leading_whitespace_and_crlf() {
235        assert_eq!(
236            detect_signature_format(b"\r\n  -----BEGIN PGP SIGNATURE-----\r\n\r\nabc"),
237            SignatureFormat::OpenPgpArmored
238        );
239        // A signed message is not a detached signature.
240        assert_eq!(
241            detect_signature_format(b"-----BEGIN PGP MESSAGE-----\n"),
242            SignatureFormat::Unknown
243        );
244        // The armor line must end there.
245        assert_eq!(
246            detect_signature_format(b"-----BEGIN PGP SIGNATURE-----X\n"),
247            SignatureFormat::Unknown
248        );
249    }
250
251    #[test]
252    fn binary_openpgp_legacy_and_new_headers() {
253        assert_eq!(
254            detect_signature_format(&pgp_legacy(4)),
255            SignatureFormat::OpenPgpBinary
256        );
257        assert_eq!(
258            detect_signature_format(&pgp_legacy(6)),
259            SignatureFormat::OpenPgpBinary
260        );
261        // New format, tag 2, one-octet length.
262        assert_eq!(
263            detect_signature_format(&[0xc2, 0x03, 0x04, 0x00, 0x01]),
264            SignatureFormat::OpenPgpBinary
265        );
266        // New format, two-octet length 192 + 1 = 193.
267        let mut long = vec![0xc2, 0xc0, 0x01, 0x04];
268        long.resize(3 + 193, 0);
269        assert_eq!(
270            detect_signature_format(&long),
271            SignatureFormat::OpenPgpBinary
272        );
273        long.truncate(long.len() - 1);
274        assert_eq!(detect_signature_format(&long), SignatureFormat::Unknown);
275    }
276
277    #[test]
278    fn binary_openpgp_rejects_other_packets_and_bad_lengths() {
279        // Unknown signature version.
280        assert_eq!(
281            detect_signature_format(&pgp_legacy(7)),
282            SignatureFormat::Unknown
283        );
284        // Tag 6 (public key), legacy header 0x98.
285        assert_eq!(
286            detect_signature_format(&[0x98, 0x02, 0x04, 0x00]),
287            SignatureFormat::Unknown
288        );
289        // Declared length longer than the input.
290        assert_eq!(
291            detect_signature_format(&[0x88, 0x40, 0x04, 0x00]),
292            SignatureFormat::Unknown
293        );
294        // Indeterminate legacy length and partial new-format length.
295        assert_eq!(
296            detect_signature_format(&[0x8b, 0x04, 0x00]),
297            SignatureFormat::Unknown
298        );
299        assert_eq!(
300            detect_signature_format(&[0xc2, 0xe0, 0x04]),
301            SignatureFormat::Unknown
302        );
303        assert_eq!(detect_signature_format(&[0x88]), SignatureFormat::Unknown);
304        assert_eq!(
305            detect_signature_format(&[0xc2, 0xff, 0x00]),
306            SignatureFormat::Unknown
307        );
308    }
309
310    #[test]
311    fn cms_signed_data_short_and_long_lengths() {
312        assert_eq!(
313            detect_signature_format(&cms(&[0xa0, 0x00])),
314            SignatureFormat::Cms
315        );
316        let mut long = vec![0x30, 0x81, 0x80];
317        long.extend_from_slice(SIGNED_DATA_OID);
318        long.resize(3 + 0x80, 0);
319        assert_eq!(detect_signature_format(&long), SignatureFormat::Cms);
320        long.pop();
321        assert_eq!(detect_signature_format(&long), SignatureFormat::Unknown);
322    }
323
324    #[test]
325    fn cms_with_another_content_type_is_unknown() {
326        // id-data (1.2.840.113549.1.7.1).
327        let mut data = cms(&[]);
328        let last = data.len() - 1;
329        data[last] = 0x01;
330        assert_eq!(detect_signature_format(&data), SignatureFormat::Unknown);
331        assert_eq!(
332            detect_signature_format(&[0x30, 0x80]),
333            SignatureFormat::Unknown
334        );
335        assert_eq!(
336            detect_signature_format(&[0x30, 0x85, 1, 1, 1, 1, 1]),
337            SignatureFormat::Unknown
338        );
339    }
340
341    #[test]
342    fn sigstore_bundle_by_media_type_only() {
343        let v03 = br#"{"mediaType":"application/vnd.dev.sigstore.bundle.v0.3+json","verificationMaterial":{}}"#;
344        let v01 = br#" {"mediaType":"application/vnd.dev.sigstore.bundle+json;version=0.1"}"#;
345        assert_eq!(
346            detect_signature_format(v03),
347            SignatureFormat::SigstoreBundle
348        );
349        assert_eq!(
350            detect_signature_format(v01),
351            SignatureFormat::SigstoreBundle
352        );
353        for other in [
354            br#"{"mediaType":"application/json"}"#.as_slice(),
355            br#"{"verificationMaterial":{}}"#,
356            br#"{"mediaType":7}"#,
357            br#"["application/vnd.dev.sigstore.bundle"]"#,
358            br#"{"mediaType":"application/vnd.dev.sigstore.bundle""#,
359        ] {
360            assert_eq!(detect_signature_format(other), SignatureFormat::Unknown);
361        }
362    }
363
364    #[test]
365    fn empty_and_oversized_are_not_inspected() {
366        assert_eq!(detect_signature_format(b""), SignatureFormat::Empty);
367        let mut big = PGP_ARMOR.to_vec();
368        big.push(b'\n');
369        big.resize(MAX_SIGNATURE_INSPECT_BYTES + 1, b'A');
370        assert_eq!(detect_signature_format(&big), SignatureFormat::TooLarge);
371        big.truncate(MAX_SIGNATURE_INSPECT_BYTES);
372        assert_eq!(
373            detect_signature_format(&big),
374            SignatureFormat::OpenPgpArmored
375        );
376    }
377
378    #[test]
379    fn names_are_distinct() {
380        let all = [
381            SignatureFormat::OpenPgpArmored,
382            SignatureFormat::OpenPgpBinary,
383            SignatureFormat::Cms,
384            SignatureFormat::SigstoreBundle,
385            SignatureFormat::Empty,
386            SignatureFormat::TooLarge,
387            SignatureFormat::Unknown,
388        ];
389        let names: std::collections::BTreeSet<_> = all.iter().map(|f| f.as_str()).collect();
390        assert_eq!(names.len(), all.len());
391    }
392}