image4 0.8.2

A no_std-friendly library for parsing and generation of Image4 images written in pure Rust.
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use super::{CertChain, ManifestRef, UnsignedManifestRef};
use crate::{
    manifest::AnyManifestRef,
    property::{Dict, Value},
    Tag,
};
use alloc::{collections::BTreeMap, vec::Vec};
use der::{
    asn1::OctetString,
    referenced::{OwnedToRef, RefToOwned},
    DecodeValue, EncodeValue, FixedTag, Header, Length, Reader, Writer,
};
#[cfg(feature = "signature")]
use {
    super::SigningError,
    signature::{SignatureEncoding, Signer},
};

/// A signed Image4 manifest that owns its contents.
///
/// # Validation
///
/// The manifest's body, signature and certificate chain **ARE NOT** required to be valid. Types
/// representing the body and the certificate chain were designed for lazy decoding and thus **DO
/// NOT VERIFY** their contents.
///
/// Currently the only way to check that a [`Manifest`] contains valid data is as follows:
///
/// ```
/// # use der::Decode;
/// # use image4::Manifest;
/// # fn main() -> der::Result<()> {
/// # let bytes = include_bytes!("../../tests/data/apticket.der");
/// let manifest = Manifest::from_der(bytes)?;
///
/// let _body = manifest.decode_body()?;
/// let _certs = manifest.cert_chain().decode_body()?;
/// # Ok(())
/// # }
/// ```
///
/// This **DOES NOT** check that the signature is valid and only ensures that the manifest is
/// properly encoded.
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub struct Manifest {
    pub(super) tbs: UnsignedManifest,
    pub(super) signature: OctetString,
    pub(super) cert_chain: CertChain,
}

impl Manifest {
    /// Builds an Image4 property list for a manifest body from a [`BTreeMap`] describing its
    /// properties and signs the encoded body with the provided key and certificate chain.
    ///
    /// # Certificate chain validity
    ///
    /// The certificate chain isn't validated anyhow and may be completely unrelated to the signing
    /// key or even contain invalid X.509 certificates. Validating the certificate chain is the
    /// caller's responsibility.
    #[cfg(feature = "signature")]
    pub fn encode_and_sign<K: Signer<S>, S: SignatureEncoding>(
        body: &BTreeMap<Tag, Value>,
        key: &K,
        cert_chain: impl Into<CertChain>,
    ) -> Result<Self, SigningError> {
        let body = Dict::encode_from(body)?;
        Self::sign_encoded(body, key, cert_chain)
    }

    /// Signs an encoded body with the provided key and certificate chain and produces a signed
    /// manifest.
    ///
    /// # Certificate chain validity
    ///
    /// The certificate chain isn't validated anyhow and may be completely unrelated to the signing
    /// key or even contain invalid X.509 certificates. Validating the certificate chain is the
    /// caller's responsibility.
    #[cfg(feature = "signature")]
    pub fn sign_encoded<K: Signer<S>, S: SignatureEncoding>(
        body: impl Into<Dict>,
        key: &K,
        cert_chain: impl Into<CertChain>,
    ) -> Result<Self, SigningError> {
        let body = body.into();
        let signature = key.try_sign(body.as_bytes())?;

        Ok(Manifest {
            tbs: UnsignedManifest { version: 0, body },
            signature: OctetString::new(signature.to_vec())?,
            cert_chain: cert_chain.into(),
        })
    }

    /// Decodes the part of a manifest after the magic string.
    ///
    /// May be used when it is required to first identify what kind of buffer you're looking at by
    /// checking the magic string.
    pub fn decode_after_magic<'a, R: Reader<'a>>(decoder: &mut R) -> der::Result<Self> {
        Ok(ManifestRef::decode_after_magic(decoder)?.into())
    }

    /// Returns the manifest's version.
    pub fn version(&self) -> u32 {
        self.tbs.version
    }

    /// Returns a reference to the manifest's body.
    pub fn body(&self) -> &Dict {
        &self.tbs.body
    }

    /// Decodes the manifest's body into a [`BTreeMap`] describing its properties.
    pub fn decode_body(&self) -> der::Result<BTreeMap<Tag, Value>> {
        self.tbs.decode_body()
    }

    /// Encodes new manifest body from a [`BTreeMap`] which describes the properties.
    pub fn encode_body(&mut self, body: &BTreeMap<Tag, Value>) -> der::Result<()> {
        self.tbs.encode_body(body)
    }

    /// Returns a reference to the signature data.
    pub fn signature(&self) -> &[u8] {
        self.signature.as_bytes()
    }

    /// Sets a new signature.
    pub fn set_signature(&mut self, signature: Vec<u8>) -> der::Result<()> {
        self.signature = OctetString::new(signature)?;
        Ok(())
    }

    /// Returns an immutable reference to the encoded certificate chain.
    pub fn cert_chain(&self) -> &CertChain {
        &self.cert_chain
    }

    /// Returns a mutable reference to the encoded certificate chain.
    pub fn cert_chain_mut(&mut self) -> &mut CertChain {
        &mut self.cert_chain
    }

    /// Sets a new certificate chain.
    pub fn set_cert_chain(&mut self, cert_chain: CertChain) {
        self.cert_chain = cert_chain;
    }

    /// Resigns a signed manifest with the specified key and certificate chain.
    ///
    /// # Certificate chain validity
    ///
    /// The certificate chain isn't validated anyhow and may be completely unrelated to the signing
    /// key or even contain invalid X.509 certificates. Validating the certificate chain is the
    /// caller's responsibility.
    #[cfg(feature = "signature")]
    pub fn resign<K: Signer<S>, S: SignatureEncoding>(
        &mut self,
        key: &K,
        cert_chain: impl Into<CertChain>,
    ) -> Result<(), SigningError> {
        let signature = key.try_sign(self.tbs.body.as_bytes())?;

        self.signature = OctetString::new(signature.to_vec())?;
        self.cert_chain = cert_chain.into();

        Ok(())
    }
}

impl FixedTag for Manifest {
    const TAG: der::Tag = der::Tag::Sequence;
}

impl<'a> DecodeValue<'a> for Manifest {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
        ManifestRef::decode_value(reader, header).map(Manifest::from)
    }
}

impl EncodeValue for Manifest {
    fn value_len(&self) -> der::Result<Length> {
        ManifestRef::from(self).value_len()
    }

    fn encode_value(&self, encoder: &mut impl Writer) -> der::Result<()> {
        ManifestRef::from(self).encode_value(encoder)
    }
}

impl From<ManifestRef<'_>> for Manifest {
    fn from(value: ManifestRef<'_>) -> Self {
        (&value).into()
    }
}

impl From<&'_ ManifestRef<'_>> for Manifest {
    fn from(value: &'_ ManifestRef<'_>) -> Self {
        Self {
            tbs: value.tbs.ref_to_owned(),
            signature: value.signature.ref_to_owned(),
            cert_chain: value.cert_chain.ref_to_owned(),
        }
    }
}

impl OwnedToRef for Manifest {
    type Borrowed<'a> = ManifestRef<'a>;

    fn owned_to_ref(&self) -> Self::Borrowed<'_> {
        self.into()
    }
}

impl AsRef<UnsignedManifest> for Manifest {
    fn as_ref(&self) -> &UnsignedManifest {
        &self.tbs
    }
}

/// An unsigned Image4 manifest that owns its contents.
///
/// # Validation
///
/// The manifest's body **IS NOT** required to be valid.
///
/// Currently the only way to check that an [`UnsignedManifest`] contains valid data is to decode
/// its body using the [`UnsignedManifest::decode_body`] method.
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub struct UnsignedManifest {
    pub(super) version: u32,
    pub(super) body: Dict,
}

impl UnsignedManifest {
    /// Creates a new unsigned manifest from its body contents.
    pub fn new(body: Dict) -> Self {
        Self { version: 0, body }
    }

    /// Creates a bew unsigned manifest by encoding an Image4 property list.
    pub fn encode_from(dict: &BTreeMap<Tag, Value>) -> der::Result<Self> {
        Ok(Self {
            version: 0,
            body: Dict::encode_from(dict)?,
        })
    }

    /// Decodes the part of an unsigned manifest after the magic string.
    ///
    /// May be used when it is required to first identify what kind of buffer you're looking at by
    /// checking the magic string.
    pub fn decode_after_magic<'a, R: Reader<'a>>(decoder: &mut R) -> der::Result<Self> {
        Ok(UnsignedManifestRef::decode_after_magic(decoder)?.into())
    }

    /// Returns the manifest's version.
    pub fn version(&self) -> u32 {
        self.version
    }

    /// Returns a reference to the manifest's body.
    pub fn body(&self) -> &Dict {
        &self.body
    }

    /// Decodes the manifest's body into a [`BTreeMap`] describing its properties.
    pub fn decode_body(&self) -> der::Result<BTreeMap<Tag, Value>> {
        self.body.decode_owned()
    }

    /// Encodes new manifest body from a [`BTreeMap`] which describes the properties.
    pub fn encode_body(&mut self, body: &BTreeMap<Tag, Value>) -> der::Result<()> {
        self.body = Dict::encode_from(body)?;
        Ok(())
    }

    /// Signs an unsigned manifest with the specified key and certificate chain.
    ///
    /// # Certificate chain validity
    ///
    /// The certificate chain isn't validated anyhow and may be completely unrelated to the signing
    /// key or even contain invalid X.509 certificates. Validating the certificate chain is the
    /// caller's responsibility.
    #[cfg(feature = "signature")]
    pub fn sign<K: Signer<S>, S: SignatureEncoding>(
        self,
        key: &K,
        cert_chain: impl Into<CertChain>,
    ) -> Result<Manifest, SigningError> {
        let signature = key.try_sign(self.body.as_bytes())?;

        Ok(Manifest {
            tbs: self,
            signature: OctetString::new(signature.to_vec())?,
            cert_chain: cert_chain.into(),
        })
    }
}

impl FixedTag for UnsignedManifest {
    const TAG: der::Tag = der::Tag::Sequence;
}

impl<'a> DecodeValue<'a> for UnsignedManifest {
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> der::Result<Self> {
        UnsignedManifestRef::decode_value(reader, header).map(From::from)
    }
}

impl EncodeValue for UnsignedManifest {
    fn value_len(&self) -> der::Result<Length> {
        UnsignedManifestRef::from(self).value_len()
    }

    fn encode_value(&self, encoder: &mut impl Writer) -> der::Result<()> {
        UnsignedManifestRef::from(self).encode_value(encoder)
    }
}

impl From<Manifest> for UnsignedManifest {
    fn from(value: Manifest) -> Self {
        value.tbs
    }
}

impl From<ManifestRef<'_>> for UnsignedManifest {
    fn from(value: ManifestRef<'_>) -> Self {
        (&value.tbs).into()
    }
}

impl From<&'_ ManifestRef<'_>> for UnsignedManifest {
    fn from(value: &'_ ManifestRef<'_>) -> Self {
        (&value.tbs).into()
    }
}

impl From<UnsignedManifestRef<'_>> for UnsignedManifest {
    fn from(value: UnsignedManifestRef<'_>) -> Self {
        (&value).into()
    }
}

impl From<&'_ UnsignedManifestRef<'_>> for UnsignedManifest {
    fn from(value: &'_ UnsignedManifestRef<'_>) -> Self {
        Self {
            version: value.version,
            body: value.body.ref_to_owned(),
        }
    }
}

impl OwnedToRef for UnsignedManifest {
    type Borrowed<'a> = UnsignedManifestRef<'a>;

    fn owned_to_ref(&self) -> Self::Borrowed<'_> {
        self.into()
    }
}

/// Either a signed or an unsigned Image4 manifest that owns its contents.
#[derive(Clone, Debug)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub enum AnyManifest {
    /// A signed manifest.
    Signed(Manifest),
    /// An unsigned manifest.
    Unsigned(UnsignedManifest),
}

impl AnyManifest {
    /// Decodes the part of a manifest after the magic string.
    ///
    /// May be used when it is required to first identify what kind of buffer you're looking at by
    /// checking the magic string.
    ///
    /// See docs for [`AnyManifestRef::decode_after_magic`] for more info.
    pub fn decode_after_magic<'a, R: Reader<'a>>(decoder: &mut R) -> der::Result<Self> {
        Ok(UnsignedManifestRef::decode_after_magic(decoder)?.into())
    }

    /// Returns the manifest's version.
    pub fn version(&self) -> u32 {
        match self {
            AnyManifest::Signed(m) => m.version(),
            AnyManifest::Unsigned(m) => m.version(),
        }
    }

    /// Decodes the manifest's body into a [`BTreeMap`] describing its properties.
    pub fn decode_body(&self) -> der::Result<BTreeMap<Tag, Value>> {
        match self {
            AnyManifest::Signed(m) => m.decode_body(),
            AnyManifest::Unsigned(m) => m.decode_body(),
        }
    }

    /// Encodes new manifest body from a [`BTreeMap`] which describes the properties.
    pub fn encode_body(&mut self, body: &BTreeMap<Tag, Value>) -> der::Result<()> {
        match self {
            AnyManifest::Signed(m) => m.encode_body(body),
            AnyManifest::Unsigned(m) => m.encode_body(body),
        }
    }
}

impl From<Manifest> for AnyManifest {
    fn from(value: Manifest) -> Self {
        Self::Signed(value)
    }
}

impl From<UnsignedManifest> for AnyManifest {
    fn from(value: UnsignedManifest) -> Self {
        Self::Unsigned(value)
    }
}

impl From<UnsignedManifestRef<'_>> for AnyManifest {
    fn from(value: UnsignedManifestRef<'_>) -> Self {
        (&value).into()
    }
}

impl From<&'_ UnsignedManifestRef<'_>> for AnyManifest {
    fn from(value: &'_ UnsignedManifestRef<'_>) -> Self {
        Self::Unsigned(value.into())
    }
}

impl From<ManifestRef<'_>> for AnyManifest {
    fn from(value: ManifestRef<'_>) -> Self {
        (&value).into()
    }
}

impl From<&'_ ManifestRef<'_>> for AnyManifest {
    fn from(value: &'_ ManifestRef<'_>) -> Self {
        Self::Signed(value.into())
    }
}

impl From<AnyManifestRef<'_>> for AnyManifest {
    fn from(value: AnyManifestRef<'_>) -> Self {
        (&value).into()
    }
}

impl From<&'_ AnyManifestRef<'_>> for AnyManifest {
    fn from(value: &'_ AnyManifestRef<'_>) -> Self {
        match value {
            AnyManifestRef::Signed(m) => Self::Signed(m.into()),
            AnyManifestRef::Unsigned(m) => Self::Unsigned(m.into()),
        }
    }
}

impl OwnedToRef for AnyManifest {
    type Borrowed<'a> = AnyManifestRef<'a>;

    fn owned_to_ref(&self) -> Self::Borrowed<'_> {
        self.into()
    }
}

impl AsRef<UnsignedManifest> for AnyManifest {
    fn as_ref(&self) -> &UnsignedManifest {
        match self {
            AnyManifest::Signed(m) => &m.tbs,
            AnyManifest::Unsigned(m) => m,
        }
    }
}