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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
use std::{borrow, fmt, ops};
use bcder::{decode, encode};
use bcder::{
BitString, Captured, Ia5String, Mode, OctetString, Oid, Tag,
};
use bcder::decode::{DecodeError, IntoSource, Source};
use bcder::encode::{PrimitiveContent, Values};
use bytes::Bytes;
use crate::{oid, uri};
use crate::crypto::{DigestAlgorithm, Signer, SigningError};
use super::cert::{Cert, ResourceCert};
use super::error::{ValidationError, VerificationError};
use super::sigobj::{SignedObject, SignedObjectBuilder};
use super::x509::{Serial, Time};
#[derive(Clone, Debug)]
pub struct Manifest {
signed: SignedObject,
content: ManifestContent,
}
impl Manifest {
pub fn decode<S: IntoSource>(
source: S,
strict: bool
) -> Result<Self, DecodeError<<S::Source as Source>::Error>> {
let signed = SignedObject::decode_if_type(
source, &oid::CT_RPKI_MANIFEST, strict
)?;
let content = signed.decode_content(
|cons| ManifestContent::take_from(cons)
).map_err(DecodeError::convert)?;
Ok(Manifest { signed, content })
}
pub fn validate(
self,
cert: &ResourceCert,
strict: bool,
) -> Result<(ResourceCert, ManifestContent), ValidationError> {
self.validate_at(cert, strict, Time::now())
}
pub fn validate_at(
self,
cert: &ResourceCert,
strict: bool,
now: Time
) -> Result<(ResourceCert, ManifestContent), ValidationError> {
let cert = self.signed.validate_at(cert, strict, now)?;
Ok((cert, self.content))
}
pub fn encode_ref(&self) -> impl encode::Values + '_ {
self.signed.encode_ref()
}
pub fn to_captured(&self) -> Captured {
self.encode_ref().to_captured(Mode::Der)
}
pub fn cert(&self) -> &Cert {
self.signed.cert()
}
pub fn content(&self) -> &ManifestContent {
&self.content
}
}
impl ops::Deref for Manifest {
type Target = ManifestContent;
fn deref(&self) -> &Self::Target {
&self.content
}
}
impl AsRef<Manifest> for Manifest {
fn as_ref(&self) -> &Self {
self
}
}
impl AsRef<ManifestContent> for Manifest {
fn as_ref(&self) -> &ManifestContent {
&self.content
}
}
impl borrow::Borrow<ManifestContent> for Manifest {
fn borrow(&self) -> &ManifestContent {
&self.content
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for Manifest {
fn serialize<S: serde::Serializer>(
&self,
serializer: S
) -> Result<S::Ok, S::Error> {
let bytes = self.to_captured().into_bytes();
let b64 = base64::encode(&bytes);
b64.serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Manifest {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D
) -> Result<Self, D::Error> {
use serde::de;
let string = String::deserialize(deserializer)?;
let decoded = base64::decode(string).map_err(de::Error::custom)?;
let bytes = Bytes::from(decoded);
Manifest::decode(bytes, true).map_err(de::Error::custom)
}
}
#[derive(Clone, Debug)]
pub struct ManifestContent {
manifest_number: Serial,
this_update: Time,
next_update: Time,
file_hash_alg: DigestAlgorithm,
file_list: Captured,
len: usize,
}
impl ManifestContent {
pub fn new<I, FH, F, H>(
manifest_number: Serial,
this_update: Time,
next_update: Time,
file_hash_alg: DigestAlgorithm,
iter: I,
) -> Self
where
I: IntoIterator<Item = FH>,
FH: AsRef<FileAndHash<F, H>>,
F: AsRef<[u8]>,
H: AsRef<[u8]>,
{
let mut len = 0;
let mut file_list = Captured::builder(Mode::Der);
for item in iter.into_iter() {
file_list.extend(item.as_ref().encode_ref());
len += 1;
}
Self {
manifest_number,
this_update,
next_update,
file_hash_alg,
file_list: file_list.freeze(),
len
}
}
pub fn into_manifest<S: Signer>(
self,
mut sigobj: SignedObjectBuilder,
signer: &S,
issuer_key: &S::KeyId,
) -> Result<Manifest, SigningError<S::Error>> {
sigobj.set_v4_resources_inherit();
sigobj.set_v6_resources_inherit();
sigobj.set_as_resources_inherit();
let signed = sigobj.finalize(
Oid(oid::CT_RPKI_MANIFEST.0.into()),
self.encode_ref().to_captured(Mode::Der).into_bytes(),
signer,
issuer_key,
)?;
Ok(Manifest { signed, content: self })
}
}
impl ManifestContent {
pub fn manifest_number(&self) -> Serial {
self.manifest_number
}
pub fn this_update(&self) -> Time {
self.this_update
}
pub fn next_update(&self) -> Time {
self.next_update
}
pub fn file_hash_alg(&self) -> DigestAlgorithm {
self.file_hash_alg
}
pub fn iter(&self) -> FileListIter {
FileListIter(self.file_list.clone())
}
pub fn iter_uris<'a>(
&'a self,
base: &'a uri::Rsync
) -> impl Iterator<Item = (uri::Rsync, ManifestHash)> + 'a {
let alg = self.file_hash_alg;
self.iter().map(move |item| {
let (file, hash) = item.into_pair();
(
base.join(file.as_ref()).unwrap(),
ManifestHash::new(hash, alg)
)
})
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.file_list.is_empty()
}
pub fn is_stale(&self) -> bool {
self.next_update < Time::now()
}
}
impl ManifestContent {
pub fn take_from<S: decode::Source>(
cons: &mut decode::Constructed<S>
) -> Result<Self, DecodeError<S::Error>> {
cons.take_sequence(|cons| {
cons.take_opt_constructed_if(Tag::CTX_0, |c| c.skip_u8_if(0))?;
let manifest_number = Serial::take_from(cons)?;
let this_update = Time::take_from(cons)?;
let next_update = Time::take_from(cons)?;
let file_hash_alg = DigestAlgorithm::take_oid_from(cons)?;
if this_update > next_update {
return Err(cons.content_err(
"thisUpdate after nextUpdate"
));
}
let mut len = 0;
let file_list = cons.take_sequence(|cons| {
cons.capture(|cons| {
while let Some(()) = FileAndHash::skip_opt_in(cons)? {
len += 1;
}
Ok(())
})
})?;
Ok(Self {
manifest_number,
this_update,
next_update,
file_hash_alg,
file_list,
len
})
})
}
pub fn encode_ref(&self) -> impl encode::Values + '_ {
encode::sequence((
self.manifest_number.encode(),
self.this_update.encode_generalized_time(),
self.next_update.encode_generalized_time(),
self.file_hash_alg.encode_oid(),
encode::sequence(
&self.file_list
)
))
}
}
#[derive(Clone, Debug)]
pub struct FileListIter(Captured);
impl Iterator for FileListIter {
type Item = FileAndHash<Bytes, Bytes>;
fn next(&mut self) -> Option<Self::Item> {
self.0.decode_partial(|cons| {
FileAndHash::take_opt_from(cons)
}).unwrap()
}
}
#[derive(Clone, Debug)]
pub struct FileAndHash<F, H> {
file: F,
hash: H
}
impl<F, H> FileAndHash<F, H> {
pub fn new(file: F, hash: H) -> Self {
FileAndHash { file, hash }
}
pub fn file(&self) -> &F {
&self.file
}
pub fn hash(&self) -> &H {
&self.hash
}
pub fn into_pair(self) -> (F, H) {
(self.file, self.hash)
}
}
impl FileAndHash<Bytes, Bytes> {
fn skip_opt_in<S: decode::Source>(
cons: &mut decode::Constructed<S>
) -> Result<Option<()>, DecodeError<S::Error>> {
cons.take_opt_sequence(|cons| {
cons.take_value_if(
Tag::IA5_STRING,
OctetString::from_content
)?;
BitString::skip_in(cons)?;
Ok(())
})
}
fn take_opt_from<S: decode::Source>(
cons: &mut decode::Constructed<S>
) -> Result<Option<Self>, DecodeError<S::Error>> {
cons.take_opt_sequence(|cons| {
Ok(FileAndHash {
file: Ia5String::take_from(cons)?.into_bytes(),
hash: BitString::take_from(cons)?.octet_bytes(),
})
})
}
}
impl<F: AsRef<[u8]>, H: AsRef<[u8]>> FileAndHash<F, H> {
pub fn encode_ref(&self) -> impl encode::Values + '_ {
encode::sequence((
OctetString::encode_slice_as(self.file.as_ref(), Tag::IA5_STRING),
BitString::encode_slice(self.hash.as_ref(), 0),
))
}
}
impl<F: AsRef<[u8]>, H: AsRef<[u8]>> AsRef<Self> for FileAndHash<F, H> {
fn as_ref(&self) -> &Self {
self
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct ManifestHash {
hash: Bytes,
algorithm: DigestAlgorithm,
}
impl ManifestHash {
pub fn new(hash: Bytes, algorithm: DigestAlgorithm) -> Self {
Self { hash, algorithm }
}
pub fn verify<T: AsRef<[u8]>>(
&self,
t: T
) -> Result<(), ManifestHashMismatch> {
ring::constant_time::verify_slices_are_equal(
self.hash.as_ref(),
self.algorithm.digest(t.as_ref()).as_ref()
).map_err(|_| ManifestHashMismatch(()))
}
pub fn algorithm(&self) -> DigestAlgorithm {
self.algorithm
}
pub fn as_slice(&self) -> &[u8] {
self.hash.as_ref()
}
}
#[derive(Clone, Copy, Debug)]
pub struct ManifestHashMismatch(());
impl fmt::Display for ManifestHashMismatch {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("manifest hash mismatch")
}
}
impl From<ManifestHashMismatch> for VerificationError {
fn from(_: ManifestHashMismatch) -> VerificationError {
VerificationError::new("manifest hash mismatch")
}
}
#[cfg(test)]
mod test {
use crate::repository::cert::Cert;
use crate::repository::tal::TalInfo;
use super::*;
#[test]
fn decode() {
let talinfo = TalInfo::from_name("foo".into()).into_arc();
let at = Time::utc(2019, 5, 1, 0, 0, 0);
let issuer = Cert::decode(
include_bytes!("../../test-data/ta.cer").as_ref()
).unwrap();
let issuer = issuer.validate_ta_at(talinfo, false, at).unwrap();
let obj = Manifest::decode(
include_bytes!("../../test-data/ta.mft").as_ref(),
false
).unwrap();
obj.validate_at(&issuer, false, at).unwrap();
let obj = Manifest::decode(
include_bytes!("../../test-data/ca1.mft").as_ref(),
false
).unwrap();
assert!(obj.validate_at(&issuer, false, at).is_err());
}
}
#[cfg(all(test, feature = "softkeys"))]
mod signer_test {
use std::str::FromStr;
use bcder::encode::Values;
use crate::uri;
use crate::repository::cert::{KeyUsage, Overclaim, TbsCert};
use crate::crypto::{PublicKeyFormat, Signer};
use crate::crypto::softsigner::OpenSslSigner;
use crate::repository::resources::{Asn, Prefix};
use crate::repository::tal::TalInfo;
use crate::repository::x509::Validity;
use super::*;
fn make_test_manifest() -> Manifest {
let signer = OpenSslSigner::new();
let key = signer.create_key(PublicKeyFormat::Rsa).unwrap();
let pubkey = signer.get_key_info(&key).unwrap();
let uri = uri::Rsync::from_str("rsync://example.com/m/p").unwrap();
let mut cert = TbsCert::new(
12u64.into(), pubkey.to_subject_name(),
Validity::from_secs(86400), None, pubkey, KeyUsage::Ca,
Overclaim::Trim
);
cert.set_basic_ca(Some(true));
cert.set_ca_repository(Some(uri.clone()));
cert.set_rpki_manifest(Some(uri.clone()));
cert.build_v4_resource_blocks(|b| b.push(Prefix::new(0, 0)));
cert.build_v6_resource_blocks(|b| b.push(Prefix::new(0, 0)));
cert.build_as_resource_blocks(|b| b.push((Asn::MIN, Asn::MAX)));
let cert = cert.into_cert(&signer, &key).unwrap();
let content = ManifestContent::new(
12u64.into(), Time::now(), Time::next_week(),
DigestAlgorithm::default(),
[
FileAndHash::new(b"file".as_ref(), b"hash".as_ref()),
FileAndHash::new(b"file".as_ref(), b"hash".as_ref()),
].iter()
);
let manifest = content.into_manifest(
SignedObjectBuilder::new(
12u64.into(), Validity::from_secs(86400), uri.clone(),
uri.clone(), uri
),
&signer, &key
).unwrap();
let manifest = manifest.encode_ref().to_captured(Mode::Der);
let manifest = Manifest::decode(manifest.as_slice(), true).unwrap();
let cert = cert.validate_ta(
TalInfo::from_name("foo".into()).into_arc(), true
).unwrap();
manifest.clone().validate(&cert, true).unwrap();
manifest
}
#[test]
fn encode_manifest() {
make_test_manifest();
}
#[test]
#[cfg(feature = "serde")]
fn serde_manifest() {
let mft = make_test_manifest();
let serialized = serde_json::to_string(&mft).unwrap();
let deser_mft: Manifest = serde_json::from_str(&serialized).unwrap();
assert_eq!(
mft.to_captured().into_bytes(),
deser_mft.to_captured().into_bytes()
);
}
}