wintrust 0.3.0

Portable Rust catalog trust with Windows API name aliases
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Bounded inspection of Microsoft PKCS#7 catalog CTLs. Parsing establishes no trust.
use alloc::{
    format,
    string::{String, ToString},
    vec::Vec,
};
use core::fmt;
use der::{
    Decode,
    asn1::{AnyRef, ObjectIdentifier},
};
use serde::Serialize;

const SIGNED_DATA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.7.2");
const CTL: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.311.10.1");
const INDIRECT: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.311.2.1.4");

#[derive(Clone, Copy, Debug)]
pub struct CatalogLimits {
    pub max_bytes: usize,
    pub max_nodes: usize,
    pub max_depth: usize,
    pub max_members: usize,
}
impl Default for CatalogLimits {
    fn default() -> Self {
        Self {
            max_bytes: 32 * 1024 * 1024,
            max_nodes: 500_000,
            max_depth: 64,
            max_members: 100_000,
        }
    }
}
#[derive(Debug)]
pub enum CatalogError {
    Malformed(String),
    Unsupported(String),
    Limit(&'static str),
}
impl fmt::Display for CatalogError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Malformed(s) => write!(f, "malformed catalog: {s}"),
            Self::Unsupported(s) => write!(f, "unsupported catalog: {s}"),
            Self::Limit(s) => write!(f, "catalog limit exceeded: {s}"),
        }
    }
}
impl core::error::Error for CatalogError {}
impl From<der::Error> for CatalogError {
    fn from(e: der::Error) -> Self {
        Self::Malformed(e.to_string())
    }
}
#[derive(Debug, Serialize)]
pub struct Catalog {
    #[serde(with = "crate::oid_serde")]
    pub content_type: ObjectIdentifier,
    #[serde(with = "crate::oid_serde::vec")]
    pub digest_algorithms: Vec<ObjectIdentifier>,
    pub certificate_count: usize,
    pub signers: Vec<Signer>,
    pub ctl: CertificateTrustList,
    pub trust_established: bool,
}
#[derive(Debug, Serialize)]
pub struct Signer {
    #[serde(with = "crate::oid_serde")]
    pub digest_algorithm: ObjectIdentifier,
    #[serde(with = "crate::oid_serde")]
    pub signature_algorithm: ObjectIdentifier,
    pub signature_bytes: usize,
    pub signed_attributes: Vec<Attribute>,
    pub unsigned_attributes: Vec<Attribute>,
}
#[derive(Debug, Serialize)]
pub struct Attribute {
    #[serde(with = "crate::oid_serde")]
    pub oid: ObjectIdentifier,
    pub values_der_hex: Vec<String>,
}
#[derive(Debug, Serialize)]
pub struct CertificateTrustList {
    pub version: u64,
    #[serde(with = "crate::oid_serde::vec")]
    pub subject_usage: Vec<ObjectIdentifier>,
    pub list_identifier_hex: Option<String>,
    pub sequence_number_hex: Option<String>,
    pub this_update: String,
    pub next_update: Option<String>,
    #[serde(with = "crate::oid_serde")]
    pub subject_algorithm: ObjectIdentifier,
    pub members: Vec<CatalogMember>,
    pub extensions_der_hex: Option<String>,
    /// Exact CTL DER encoding; legacy PKCS#7 signs its value octets, not a CMS OCTET STRING.
    pub encoded_hex: String,
}
#[derive(Debug, Serialize)]
pub struct CatalogMember {
    pub identifier_hex: String,
    pub attributes: Vec<Attribute>,
    pub indirect_data: Option<IndirectData>,
}
#[derive(Debug, Serialize)]
pub struct IndirectData {
    #[serde(with = "crate::oid_serde")]
    pub data_type: ObjectIdentifier,
    #[serde(with = "crate::oid_serde")]
    pub digest_algorithm: ObjectIdentifier,
    pub digest_hex: String,
}

pub(crate) use crate::der::{Node, children, field, node, oid, preflight, tagged};
pub(crate) fn bad(message: &str) -> CatalogError {
    CatalogError::Malformed(message.into())
}
pub(crate) fn algorithm(n: Node<'_>) -> Result<ObjectIdentifier, CatalogError> {
    let fields = children(tagged(n, 0x30)?)?;
    if fields.is_empty() || fields.len() > 2 {
        return Err(bad("invalid AlgorithmIdentifier"));
    }
    oid(fields[0])
}
pub(crate) fn integer(n: Node<'_>) -> Result<u64, CatalogError> {
    tagged(n, 2)?;
    Ok(AnyRef::from_der(n.full)?.decode_as::<u64>()?)
}
pub(crate) fn time(n: Node<'_>) -> Result<String, CatalogError> {
    match n.tag {
        0x17 => {
            AnyRef::from_der(n.full)?.decode_as::<der::asn1::UtcTime>()?;
        }
        0x18 => {
            AnyRef::from_der(n.full)?.decode_as::<der::asn1::GeneralizedTime>()?;
        }
        _ => return Err(bad("invalid CTL time")),
    };
    String::from_utf8(n.value.to_vec()).map_err(|_| bad("invalid time encoding"))
}
pub(crate) fn attributes(n: Node<'_>) -> Result<Vec<Attribute>, CatalogError> {
    children(n)?
        .into_iter()
        .map(|n| {
            let f = children(tagged(n, 0x30)?)?;
            if f.len() != 2 {
                return Err(bad("invalid attribute"));
            }
            let values = children(tagged(f[1], 0x31)?)?;
            if values.is_empty() {
                return Err(bad("empty attribute values"));
            }
            Ok(Attribute {
                oid: oid(f[0])?,
                values_der_hex: values.iter().map(|v| hex::encode(v.full)).collect(),
            })
        })
        .collect()
}
fn signer(n: Node<'_>) -> Result<Signer, CatalogError> {
    let f = children(tagged(n, 0x30)?)?;
    integer(field(&f, 0, 2)?)?;
    let sid = *f.get(1).ok_or_else(|| bad("missing signer identifier"))?;
    if !matches!(sid.tag, 0x30 | 0x80) {
        return Err(bad("invalid signer identifier"));
    }
    let digest_algorithm = algorithm(field(&f, 2, 0x30)?)?;
    let mut pos = 3;
    let signed_attributes = if f.get(pos).is_some_and(|n| n.tag == 0xa0) {
        let a = attributes(f[pos])?;
        pos += 1;
        a
    } else {
        Vec::new()
    };
    let signature_algorithm = algorithm(field(&f, pos, 0x30)?)?;
    pos += 1;
    let signature_bytes = field(&f, pos, 4)?.value.len();
    pos += 1;
    let unsigned_attributes = if f.get(pos).is_some_and(|n| n.tag == 0xa1) {
        let a = attributes(f[pos])?;
        pos += 1;
        a
    } else {
        Vec::new()
    };
    if pos != f.len() {
        return Err(bad("unexpected signer fields"));
    }
    Ok(Signer {
        digest_algorithm,
        signature_algorithm,
        signature_bytes,
        signed_attributes,
        unsigned_attributes,
    })
}
fn indirect(n: Node<'_>) -> Result<IndirectData, CatalogError> {
    let f = children(tagged(n, 0x30)?)?;
    if f.len() != 2 {
        return Err(bad("invalid indirect data"));
    }
    let data = children(tagged(f[0], 0x30)?)?;
    let data_type = oid(*data.first().ok_or_else(|| bad("missing data type"))?)?;
    if data.len() > 2 {
        return Err(bad("invalid indirect data type"));
    }
    let digest = children(tagged(f[1], 0x30)?)?;
    if digest.len() != 2 {
        return Err(bad("invalid DigestInfo"));
    }
    let digest_algorithm = algorithm(digest[0])?;
    let bytes = tagged(digest[1], 4)?.value;
    let expected = match digest_algorithm.to_string().as_str() {
        "1.3.14.3.2.26" => Some(20),
        "2.16.840.1.101.3.4.2.1" => Some(32),
        "2.16.840.1.101.3.4.2.2" => Some(48),
        "2.16.840.1.101.3.4.2.3" => Some(64),
        _ => None,
    };
    if expected.is_some_and(|len| len != bytes.len()) {
        return Err(bad("digest length does not match algorithm"));
    }
    Ok(IndirectData {
        data_type,
        digest_algorithm,
        digest_hex: hex::encode(bytes),
    })
}
fn ctl(n: Node<'_>, limits: CatalogLimits) -> Result<CertificateTrustList, CatalogError> {
    let metadata = crate::ctl::parse_node(n, limits)?;
    let mut members = Vec::new();
    let mut identifiers = alloc::collections::BTreeMap::new();
    {
        for entry in &metadata.entries {
            let (member, _) = node(entry.encoded)?;
            let m = children(tagged(member, 0x30)?)?;
            if m.len() != 2 {
                return Err(bad("invalid CTL member"));
            }
            let identifier_hex = hex::encode(entry.subject_identifier);
            let attrs = entry
                .attributes
                .iter()
                .map(|attr| Attribute {
                    oid: attr.oid,
                    values_der_hex: attr.values.iter().map(hex::encode).collect(),
                })
                .collect();
            let mut indirect_data = None;
            let mut indirect_der = None;
            for attr in &entry.attributes {
                if attr.oid == INDIRECT {
                    if indirect_data.is_some() {
                        return Err(bad("duplicate indirect data"));
                    }
                    if attr.values.len() != 1 {
                        return Err(bad("multiple indirect data values"));
                    }
                    let (value, _) = node(attr.values[0])?;
                    indirect_data = Some(indirect(value)?);
                    indirect_der = Some(value.full);
                }
            }
            // A catalog can bind identical content to several authenticated Hint
            // names. Retain every signed row. Identical opaque rows remain
            // inspectable, but never supply SIP membership. Differing rows must
            // carry exactly the same supported SIP/digest DER; whole-row equality
            // would incorrectly reject differing member-info metadata.
            if let Some(previous) =
                identifiers.insert(identifier_hex.clone(), (member.full, indirect_der))
            {
                let supported = indirect_data.as_ref().is_some_and(|data| {
                    matches!(
                        data.data_type.to_string().as_str(),
                        "1.3.6.1.4.1.311.2.1.15"
                            | "1.3.6.1.4.1.311.2.1.18"
                            | "1.3.6.1.4.1.311.2.1.25"
                    ) && matches!(
                        data.digest_algorithm.to_string().as_str(),
                        "1.3.14.3.2.26"
                            | "2.16.840.1.101.3.4.2.1"
                            | "2.16.840.1.101.3.4.2.2"
                            | "2.16.840.1.101.3.4.2.3"
                    )
                });
                if previous.0 != member.full
                    && (!supported || indirect_der.is_none() || previous.1 != indirect_der)
                {
                    return Err(bad("conflicting duplicate CTL member identifier"));
                }
            }
            members.push(CatalogMember {
                identifier_hex,
                attributes: attrs,
                indirect_data,
            });
        }
    }
    Ok(CertificateTrustList {
        version: metadata.version,
        subject_usage: metadata.subject_usage,
        list_identifier_hex: metadata.list_identifier.map(hex::encode),
        sequence_number_hex: metadata.sequence_number.map(hex::encode),
        this_update: metadata.this_update,
        next_update: metadata.next_update,
        subject_algorithm: metadata.subject_algorithm,
        members,
        extensions_der_hex: metadata.extensions.map(hex::encode),
        encoded_hex: hex::encode(n.full),
    })
}
/// Inspect a strict DER catalog, retaining unknown attribute OIDs without assigning trust.
pub fn parse(bytes: &[u8], limits: CatalogLimits) -> Result<Catalog, CatalogError> {
    if bytes.len() > limits.max_bytes {
        return Err(CatalogError::Limit("bytes"));
    }
    // Preflight every constructed value before allocating output, including nested timestamp data.
    let (root, len) = node(bytes)?;
    if len != bytes.len() {
        return Err(bad("trailing bytes"));
    }
    let mut count = 0;
    preflight(root, limits, &mut count)?;
    let outer = children(tagged(root, 0x30)?)?;
    if outer.len() != 2 || oid(outer[0])? != SIGNED_DATA {
        return Err(CatalogError::Unsupported(
            "expected PKCS#7 SignedData".into(),
        ));
    }
    let wrapper = children(tagged(outer[1], 0xa0)?)?;
    if wrapper.len() != 1 {
        return Err(bad("invalid SignedData wrapper"));
    }
    let sd = children(tagged(wrapper[0], 0x30)?)?;
    integer(field(&sd, 0, 2)?)?;
    let digest_algorithms = children(field(&sd, 1, 0x31)?)?
        .into_iter()
        .map(algorithm)
        .collect::<Result<Vec<_>, _>>()?;
    let content = children(field(&sd, 2, 0x30)?)?;
    if content.len() != 2 {
        return Err(bad("detached or invalid catalog content"));
    }
    let content_type = oid(content[0])?;
    if content_type != CTL {
        return Err(CatalogError::Unsupported(format!(
            "content type {content_type}"
        )));
    }
    let encap = children(tagged(content[1], 0xa0)?)?;
    if encap.len() != 1 {
        return Err(bad("invalid CTL wrapper"));
    }
    let ctl_node = if encap[0].tag == 4 {
        let (n, len) = node(encap[0].value)?;
        if len != encap[0].value.len() {
            return Err(bad("trailing CTL bytes"));
        }
        preflight(n, limits, &mut count)?;
        n
    } else {
        encap[0]
    };
    let ctl = ctl(ctl_node, limits)?;
    let mut pos = 3;
    let certificate_count = if sd.get(pos).is_some_and(|n| n.tag == 0xa0) {
        let count = children(sd[pos])?.len();
        pos += 1;
        count
    } else {
        0
    };
    if sd.get(pos).is_some_and(|n| n.tag == 0xa1) {
        pos += 1;
    }
    let signers = children(field(&sd, pos, 0x31)?)?
        .into_iter()
        .map(signer)
        .collect::<Result<Vec<_>, _>>()?;
    pos += 1;
    if pos != sd.len() {
        return Err(bad("unexpected SignedData fields"));
    }
    Ok(Catalog {
        content_type,
        digest_algorithms,
        certificate_count,
        signers,
        ctl,
        trust_established: false,
    })
}

/// Match flat XML MUM/manifest bytes against parsed indirect-data digests.
/// This checks membership only; neither the catalog signature nor its signer is verified.
/// PE and other SIP-specific formats are deliberately excluded.
pub fn match_flat_xml_member(catalog: &Catalog, bytes: &[u8]) -> Result<Vec<usize>, CatalogError> {
    use sha2::Digest;
    let text = core::str::from_utf8(bytes)
        .map_err(|_| CatalogError::Unsupported("flat member must be UTF-8 XML".into()))?;
    let xml = roxmltree::Document::parse(text)
        .map_err(|_| CatalogError::Unsupported("flat member must be XML".into()))?;
    if xml.root_element().tag_name().name() != "assembly" {
        return Err(CatalogError::Unsupported(
            "flat member must be an assembly MUM/manifest".into(),
        ));
    }
    let sha1 = hex::encode(sha1::Sha1::digest(bytes));
    let sha256 = hex::encode(sha2::Sha256::digest(bytes));
    let mut matched = Vec::new();
    for (index, member) in catalog.ctl.members.iter().enumerate() {
        if let Some(indirect) = &member.indirect_data {
            if indirect.data_type != ObjectIdentifier::new_unwrap("1.3.6.1.4.1.311.2.1.25") {
                continue;
            }
            let digest = match indirect.digest_algorithm.to_string().as_str() {
                "1.3.14.3.2.26" => &sha1,
                "2.16.840.1.101.3.4.2.1" => &sha256,
                _ => continue,
            };
            if indirect.digest_hex == *digest {
                matched.push(index);
            }
        }
    }
    Ok(matched)
}