-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathdnssec.rs
2980 lines (2654 loc) · 82.3 KB
/
dnssec.rs
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Record data from [RFC 4034]: DS, DNSKEY, RRSIG, and NSEC records.
//!
//! This RFC defines the record types for DNSSEC.
//!
//! [RFC 4034]: https://tools.ietf.org/html/rfc4034
use crate::base::cmp::CanonicalOrd;
use crate::base::iana::{DigestAlg, Rtype, SecAlg};
use crate::base::name::{FlattenInto, ParsedName, ToName};
use crate::base::rdata::{
ComposeRecordData, LongRecordData, ParseRecordData, RecordData,
};
use crate::base::scan::{Scan, Scanner, ScannerError};
use crate::base::serial::Serial;
use crate::base::wire::{Compose, Composer, FormError, Parse, ParseError};
use crate::base::zonefile_fmt::{self, Formatter, ZonefileFmt};
use crate::base::Ttl;
use crate::utils::{base16, base64};
use core::cmp::Ordering;
use core::convert::TryInto;
use core::{cmp, fmt, hash, str};
use octseq::builder::{
EmptyBuilder, FreezeBuilder, FromBuilder, OctetsBuilder, Truncate,
};
use octseq::octets::{Octets, OctetsFrom, OctetsInto};
use octseq::parse::Parser;
#[cfg(feature = "serde")]
use octseq::serde::{DeserializeOctets, SerializeOctets};
#[cfg(feature = "std")]
use std::vec::Vec;
use time::{Date, Month, PrimitiveDateTime, Time};
//------------ Dnskey --------------------------------------------------------
#[derive(Clone)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(bound(
serialize = "
Octs: octseq::serde::SerializeOctets + AsRef<[u8]>
",
deserialize = "
Octs: FromBuilder + octseq::serde::DeserializeOctets<'de>,
<Octs as FromBuilder>::Builder:
OctetsBuilder + EmptyBuilder,
",
))
)]
pub struct Dnskey<Octs> {
flags: u16,
protocol: u8,
algorithm: SecAlg,
#[cfg_attr(
feature = "serde",
serde(with = "crate::utils::base64::serde")
)]
public_key: Octs,
}
impl Dnskey<()> {
/// The rtype of this record data type.
pub(crate) const RTYPE: Rtype = Rtype::DNSKEY;
}
impl<Octs> Dnskey<Octs> {
pub fn new(
flags: u16,
protocol: u8,
algorithm: SecAlg,
public_key: Octs,
) -> Result<Self, LongRecordData>
where
Octs: AsRef<[u8]>,
{
LongRecordData::check_len(
usize::from(
u16::COMPOSE_LEN + u8::COMPOSE_LEN + SecAlg::COMPOSE_LEN,
)
.checked_add(public_key.as_ref().len())
.expect("long key"),
)?;
Ok(Dnskey {
flags,
protocol,
algorithm,
public_key,
})
}
/// Creates new DNSKEY record data without checking.
///
/// # Safety
///
/// The caller needs to ensure that wire format representation of the
/// record data is at most 65,535 octets long.
pub unsafe fn new_unchecked(
flags: u16,
protocol: u8,
algorithm: SecAlg,
public_key: Octs,
) -> Self {
Dnskey {
flags,
protocol,
algorithm,
public_key,
}
}
pub fn flags(&self) -> u16 {
self.flags
}
pub fn protocol(&self) -> u8 {
self.protocol
}
pub fn algorithm(&self) -> SecAlg {
self.algorithm
}
pub fn public_key(&self) -> &Octs {
&self.public_key
}
pub fn into_public_key(self) -> Octs {
self.public_key
}
pub fn convert<Other: From<Octs>>(self) -> Dnskey<Other> {
Dnskey {
flags: self.flags,
protocol: self.protocol,
algorithm: self.algorithm,
public_key: self.public_key.into(),
}
}
/// Returns whether the Revoke flag is set.
///
/// See [RFC 5011, Section 3].
///
/// [RFC 5011, Section 3]: https://tools.ietf.org/html/rfc5011#section-3
pub fn is_revoked(&self) -> bool {
self.flags() & 0b0000_0000_1000_0000 != 0
}
/// Returns whether the the Secure Entry Point (SEP) flag is set.
///
/// See [RFC 4034, Section 2.1.1]:
///
/// > This flag is only intended to be a hint to zone signing or
/// > debugging software as to the intended use of this DNSKEY record;
/// > validators MUST NOT alter their behavior during the signature
/// > validation process in any way based on the setting of this bit.
///
/// [RFC 4034, Section 2.1.1]: https://tools.ietf.org/html/rfc4034#section-2.1.1
pub fn is_secure_entry_point(&self) -> bool {
self.flags() & 0b0000_0000_0000_0001 != 0
}
/// Returns whether the Zone Key flag is set.
///
/// If the flag is not set, the key MUST NOT be used to verify RRSIGs that
/// cover RRSETs. See [RFC 4034, Section 2.1.1].
///
/// [RFC 4034, Section 2.1.1]: https://tools.ietf.org/html/rfc4034#section-2.1.1
pub fn is_zone_key(&self) -> bool {
self.flags() & 0b0000_0001_0000_0000 != 0
}
/// Returns the key tag for this DNSKEY data.
pub fn key_tag(&self) -> u16
where
Octs: AsRef<[u8]>,
{
if self.algorithm == SecAlg::RSAMD5 {
// The key tag is third-to-last and second-to-last octets of the
// key as a big-endian u16. If we don’t have enough octets in the
// key, we return 0.
let len = self.public_key.as_ref().len();
if len > 2 {
u16::from_be_bytes(
self.public_key.as_ref()[len - 3..len - 1]
.try_into()
.unwrap(),
)
} else {
0
}
} else {
// Treat record data as a octet sequence. Add octets at odd
// indexes as they are, add octets at even indexes shifted left
// by 8 bits.
let mut res = u32::from(self.flags);
res += u32::from(self.protocol) << 8;
res += u32::from(self.algorithm.to_int());
let mut iter = self.public_key().as_ref().iter();
// I find this clearer with a loop.
#[allow(clippy::while_let_loop)]
loop {
match iter.next() {
Some(&x) => res += u32::from(x) << 8,
None => break,
}
match iter.next() {
Some(&x) => res += u32::from(x),
None => break,
}
}
res += (res >> 16) & 0xFFFF;
(res & 0xFFFF) as u16
}
}
pub(super) fn convert_octets<Target: OctetsFrom<Octs>>(
self,
) -> Result<Dnskey<Target>, Target::Error> {
Ok(unsafe {
Dnskey::new_unchecked(
self.flags,
self.protocol,
self.algorithm,
self.public_key.try_octets_into()?,
)
})
}
pub(super) fn flatten<Target: OctetsFrom<Octs>>(
self,
) -> Result<Dnskey<Target>, Target::Error> {
self.convert_octets()
}
pub fn parse<'a, Src: Octets<Range<'a> = Octs> + ?Sized>(
parser: &mut Parser<'a, Src>,
) -> Result<Self, ParseError> {
let len = match parser.remaining().checked_sub(4) {
Some(len) => len,
None => return Err(ParseError::ShortInput),
};
Ok(unsafe {
Self::new_unchecked(
u16::parse(parser)?,
u8::parse(parser)?,
SecAlg::parse(parser)?,
parser.parse_octets(len)?,
)
})
}
pub fn scan<S: Scanner<Octets = Octs>>(
scanner: &mut S,
) -> Result<Self, S::Error>
where
Octs: AsRef<[u8]>,
{
Self::new(
u16::scan(scanner)?,
u8::scan(scanner)?,
SecAlg::scan(scanner)?,
scanner.convert_entry(base64::SymbolConverter::new())?,
)
.map_err(|err| S::Error::custom(err.as_str()))
}
}
//--- OctetsFrom
impl<Octs, SrcOcts> OctetsFrom<Dnskey<SrcOcts>> for Dnskey<Octs>
where
Octs: OctetsFrom<SrcOcts>,
{
type Error = Octs::Error;
fn try_octets_from(source: Dnskey<SrcOcts>) -> Result<Self, Self::Error> {
Ok(unsafe {
Dnskey::new_unchecked(
source.flags,
source.protocol,
source.algorithm,
Octs::try_octets_from(source.public_key)?,
)
})
}
}
//--- PartialEq and Eq
impl<Octs, Other> PartialEq<Dnskey<Other>> for Dnskey<Octs>
where
Octs: AsRef<[u8]>,
Other: AsRef<[u8]>,
{
fn eq(&self, other: &Dnskey<Other>) -> bool {
self.flags == other.flags
&& self.protocol == other.protocol
&& self.algorithm == other.algorithm
&& self.public_key.as_ref() == other.public_key.as_ref()
}
}
impl<Octs: AsRef<[u8]>> Eq for Dnskey<Octs> {}
//--- PartialOrd, CanonicalOrd, and Ord
impl<Octs, Other> PartialOrd<Dnskey<Other>> for Dnskey<Octs>
where
Octs: AsRef<[u8]>,
Other: AsRef<[u8]>,
{
fn partial_cmp(&self, other: &Dnskey<Other>) -> Option<Ordering> {
Some(self.canonical_cmp(other))
}
}
impl<Octs, Other> CanonicalOrd<Dnskey<Other>> for Dnskey<Octs>
where
Octs: AsRef<[u8]>,
Other: AsRef<[u8]>,
{
fn canonical_cmp(&self, other: &Dnskey<Other>) -> Ordering {
match self.flags.cmp(&other.flags) {
Ordering::Equal => {}
other => return other,
}
match self.protocol.cmp(&other.protocol) {
Ordering::Equal => {}
other => return other,
}
match self.algorithm.cmp(&other.algorithm) {
Ordering::Equal => {}
other => return other,
}
self.public_key.as_ref().cmp(other.public_key.as_ref())
}
}
impl<Octs: AsRef<[u8]>> Ord for Dnskey<Octs> {
fn cmp(&self, other: &Self) -> Ordering {
self.canonical_cmp(other)
}
}
//--- Hash
impl<Octs: AsRef<[u8]>> hash::Hash for Dnskey<Octs> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.flags.hash(state);
self.protocol.hash(state);
self.algorithm.hash(state);
self.public_key.as_ref().hash(state);
}
}
//--- RecordData, ParseRecordData, ComposeRecordData
impl<Octs> RecordData for Dnskey<Octs> {
fn rtype(&self) -> Rtype {
Dnskey::RTYPE
}
}
impl<'a, Octs> ParseRecordData<'a, Octs> for Dnskey<Octs::Range<'a>>
where
Octs: Octets + ?Sized,
{
fn parse_rdata(
rtype: Rtype,
parser: &mut Parser<'a, Octs>,
) -> Result<Option<Self>, ParseError> {
if rtype == Dnskey::RTYPE {
Self::parse(parser).map(Some)
} else {
Ok(None)
}
}
}
impl<Octs: AsRef<[u8]>> ComposeRecordData for Dnskey<Octs> {
fn rdlen(&self, _compress: bool) -> Option<u16> {
Some(
u16::try_from(self.public_key.as_ref().len())
.expect("long key")
.checked_add(
u16::COMPOSE_LEN + u8::COMPOSE_LEN + SecAlg::COMPOSE_LEN,
)
.expect("long key"),
)
}
fn compose_rdata<Target: Composer + ?Sized>(
&self,
target: &mut Target,
) -> Result<(), Target::AppendError> {
self.flags.compose(target)?;
self.protocol.compose(target)?;
self.algorithm.compose(target)?;
target.append_slice(self.public_key.as_ref())
}
fn compose_canonical_rdata<Target: Composer + ?Sized>(
&self,
target: &mut Target,
) -> Result<(), Target::AppendError> {
self.compose_rdata(target)
}
}
//--- Display
impl<Octs: AsRef<[u8]>> fmt::Display for Dnskey<Octs> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {} {} ", self.flags, self.protocol, self.algorithm)?;
base64::display(&self.public_key, f)
}
}
//--- Debug
impl<Octs: AsRef<[u8]>> fmt::Debug for Dnskey<Octs> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Dnskey")
.field("flags", &self.flags)
.field("protocol", &self.protocol)
.field("algorithm", &self.algorithm)
.field("public_key", &self.public_key.as_ref())
.finish()
}
}
//--- ZonefileFmt
impl<Octs: AsRef<[u8]>> ZonefileFmt for Dnskey<Octs> {
fn fmt(&self, p: &mut impl Formatter) -> zonefile_fmt::Result {
let revoked = self.is_revoked();
let sep = self.is_secure_entry_point();
let zone_key = self.is_zone_key();
p.block(|p| {
p.write_token(self.flags)?;
p.write_comment(format_args!(
"flags:{}{}{}{}",
if revoked { " revoked" } else { "" },
if sep { " sep" } else { "" },
if zone_key { " zone_key" } else { "" },
if self.flags == 0 { " <none>" } else { "" },
))?;
p.write_token(self.protocol)?;
p.write_comment("protocol")?;
p.write_show(self.algorithm)?;
p.write_token(base64::encode_display(&self.public_key))?;
p.write_comment(format_args!("key tag: {}", self.key_tag()))
})
}
}
//------------ ProtoRrsig ----------------------------------------------------
/// The RRSIG RDATA to be included when creating the signature.
#[derive(Clone)]
pub struct ProtoRrsig<Name> {
type_covered: Rtype,
algorithm: SecAlg,
labels: u8,
original_ttl: Ttl,
expiration: Timestamp,
inception: Timestamp,
key_tag: u16,
signer_name: Name,
}
impl<Name> ProtoRrsig<Name> {
#[allow(clippy::too_many_arguments)] // XXX Consider changing.
pub fn new(
type_covered: Rtype,
algorithm: SecAlg,
labels: u8,
original_ttl: Ttl,
expiration: Timestamp,
inception: Timestamp,
key_tag: u16,
signer_name: Name,
) -> Self {
ProtoRrsig {
type_covered,
algorithm,
labels,
original_ttl,
expiration,
inception,
key_tag,
signer_name,
}
}
pub fn into_rrsig<Octs: AsRef<[u8]>>(
self,
signature: Octs,
) -> Result<Rrsig<Octs, Name>, LongRecordData>
where
Name: ToName,
{
Rrsig::new(
self.type_covered,
self.algorithm,
self.labels,
self.original_ttl,
self.expiration,
self.inception,
self.key_tag,
self.signer_name,
signature,
)
}
}
impl<Name: ToName> ProtoRrsig<Name> {
pub fn compose<Target: Composer + ?Sized>(
&self,
target: &mut Target,
) -> Result<(), Target::AppendError> {
self.compose_head(target)?;
self.signer_name.compose(target)
}
pub fn compose_canonical<Target: Composer + ?Sized>(
&self,
target: &mut Target,
) -> Result<(), Target::AppendError> {
self.compose_head(target)?;
self.signer_name.compose_canonical(target)
}
fn compose_head<Target: Composer + ?Sized>(
&self,
target: &mut Target,
) -> Result<(), Target::AppendError> {
self.type_covered.compose(target)?;
self.algorithm.compose(target)?;
self.labels.compose(target)?;
self.original_ttl.compose(target)?;
self.expiration.compose(target)?;
self.inception.compose(target)?;
self.key_tag.compose(target)
}
}
//--- OctetsFrom and FlattenInto
impl<Name, SrcName> OctetsFrom<ProtoRrsig<SrcName>> for ProtoRrsig<Name>
where
Name: OctetsFrom<SrcName>,
{
type Error = Name::Error;
fn try_octets_from(
source: ProtoRrsig<SrcName>,
) -> Result<Self, Self::Error> {
Ok(ProtoRrsig::new(
source.type_covered,
source.algorithm,
source.labels,
source.original_ttl,
source.expiration,
source.inception,
source.key_tag,
Name::try_octets_from(source.signer_name)?,
))
}
}
impl<Name, TName> FlattenInto<ProtoRrsig<TName>> for ProtoRrsig<Name>
where
Name: FlattenInto<TName>,
{
type AppendError = Name::AppendError;
fn try_flatten_into(
self,
) -> Result<ProtoRrsig<TName>, Name::AppendError> {
Ok(ProtoRrsig::new(
self.type_covered,
self.algorithm,
self.labels,
self.original_ttl,
self.expiration,
self.inception,
self.key_tag,
self.signer_name.try_flatten_into()?,
))
}
}
//------------ Timestamp ------------------------------------------------------
/// A Timestamp for RRSIG Records.
///
/// DNS uses 32 bit timestamps that are conceptionally
/// viewed as the 32 bit modulus of a larger number space. Because of that,
/// special rules apply when processing these values.
/// [RFC 4034] defines Timestamps as the number of seconds elepased since
/// since 1 January 1970 00:00:00 UTC, ignoring leap seconds. Timestamps
/// are compared using so-called "Serial number arithmetic", as defined in
/// [RFC 1982].
/// The RFC defines the semantics for doing arithmetics in the
/// face of these wrap-arounds. This type implements these semantics atop a
/// native `u32`. The RFC defines two operations: addition and comparison.
///
/// For addition, the amount added can only be a positive number of up to
/// `2^31 - 1`. Because of this, we decided to not implement the
/// `Add` trait but rather have a dedicated method `add` so as to not cause
/// surprise panics.
///
/// Timestamps only implement a partial ordering. That is, there are
/// pairs of values that are not equal but there still isn’t one value larger
/// than the other. Since this is neatly implemented by the `PartialOrd`
/// trait, the type implements that.
///
/// [RFC 1982]: https://tools.ietf.org/html/rfc1982
/// [RFC 4034]: https://tools.ietf.org/html/rfc4034
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Timestamp(Serial);
impl Timestamp {
/// Returns a serial number for the current Unix time.
#[cfg(feature = "std")]
#[must_use]
pub fn now() -> Self {
Self(Serial::now())
}
/// Scan a serial represention signature time value.
///
/// In [RRSIG] records, the expiration and inception times are given as
/// serial values. Their representation format can either be the
/// value or a specific date in `YYYYMMDDHHmmSS` format.
///
/// [RRSIG]: Rrsig
pub fn scan<S: Scanner>(scanner: &mut S) -> Result<Self, S::Error> {
let mut pos = 0;
let mut buf = [0u8; 14];
scanner.scan_symbols(|symbol| {
if pos >= 14 {
return Err(S::Error::custom("illegal signature time"));
}
buf[pos] = symbol
.into_digit(10)
.map_err(|_| S::Error::custom("illegal signature time"))?
as u8;
pos += 1;
Ok(())
})?;
if pos <= 10 {
// We have an integer. We generate it into a u64 to deal
// with possible overflows.
let mut res = 0u64;
for ch in &buf[..pos] {
res = res * 10 + (u64::from(*ch));
}
if res > u64::from(u32::MAX) {
Err(S::Error::custom("illegal signature time"))
} else {
Ok(Self(Serial(res as u32)))
}
} else if pos == 14 {
let year = u32_from_buf(&buf[0..4]) as i32;
let month = Month::try_from(u8_from_buf(&buf[4..6]))
.map_err(|_| S::Error::custom("illegal signature time"))?;
let day = u8_from_buf(&buf[6..8]);
let hour = u8_from_buf(&buf[8..10]);
let minute = u8_from_buf(&buf[10..12]);
let second = u8_from_buf(&buf[12..14]);
Ok(Self(Serial(
PrimitiveDateTime::new(
Date::from_calendar_date(year, month, day).map_err(
|_| S::Error::custom("illegal signature time"),
)?,
Time::from_hms(hour, minute, second).map_err(|_| {
S::Error::custom("illegal signature time")
})?,
)
.assume_utc()
.unix_timestamp() as u32,
)))
} else {
Err(S::Error::custom("illegal signature time"))
}
}
/// Returns the timestamp as a raw integer.
#[must_use]
pub fn into_int(self) -> u32 {
self.0.into_int()
}
}
/// # Parsing and Composing
///
impl Timestamp {
pub const COMPOSE_LEN: u16 = Serial::COMPOSE_LEN;
pub fn parse<Octs: AsRef<[u8]> + ?Sized>(
parser: &mut Parser<Octs>,
) -> Result<Self, ParseError> {
Serial::parse(parser).map(Self)
}
pub fn compose<Target: Composer + ?Sized>(
&self,
target: &mut Target,
) -> Result<(), Target::AppendError> {
self.0.compose(target)
}
}
//--- From and FromStr
impl From<u32> for Timestamp {
fn from(item: u32) -> Self {
Self(Serial::from(item))
}
}
impl str::FromStr for Timestamp {
type Err = IllegalSignatureTime;
/// Parses a timestamp value from a string.
///
/// The presentation format can either be their integer value or a
/// specific date in `YYYYMMDDHHmmSS` format.
fn from_str(src: &str) -> Result<Self, Self::Err> {
if !src.is_ascii() {
return Err(IllegalSignatureTime(()));
}
if src.len() == 14 {
let year = u32::from_str(&src[0..4])
.map_err(|_| IllegalSignatureTime(()))?
as i32;
let month = Month::try_from(
u8::from_str(&src[4..6])
.map_err(|_| IllegalSignatureTime(()))?,
)
.map_err(|_| IllegalSignatureTime(()))?;
let day = u8::from_str(&src[6..8])
.map_err(|_| IllegalSignatureTime(()))?;
let hour = u8::from_str(&src[8..10])
.map_err(|_| IllegalSignatureTime(()))?;
let minute = u8::from_str(&src[10..12])
.map_err(|_| IllegalSignatureTime(()))?;
let second = u8::from_str(&src[12..14])
.map_err(|_| IllegalSignatureTime(()))?;
Ok(Timestamp(Serial(
PrimitiveDateTime::new(
Date::from_calendar_date(year, month, day)
.map_err(|_| IllegalSignatureTime(()))?,
Time::from_hms(hour, minute, second)
.map_err(|_| IllegalSignatureTime(()))?,
)
.assume_utc()
.unix_timestamp() as u32,
)))
} else {
Serial::from_str(src)
.map(Timestamp)
.map_err(|_| IllegalSignatureTime(()))
}
}
}
//--- Display
impl fmt::Display for Timestamp {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
//--- ZonefileFmt
impl ZonefileFmt for Timestamp {
fn fmt(&self, p: &mut impl Formatter) -> zonefile_fmt::Result {
p.write_token(self.0)
}
}
//--- PartialOrd and CanonicalOrd
impl cmp::PartialOrd for Timestamp {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl CanonicalOrd for Timestamp {
fn canonical_cmp(&self, other: &Self) -> cmp::Ordering {
self.0.canonical_cmp(&other.0)
}
}
//------------ Helper Functions ----------------------------------------------
fn u8_from_buf(buf: &[u8]) -> u8 {
let mut res = 0;
for ch in buf {
res = res * 10 + *ch;
}
res
}
fn u32_from_buf(buf: &[u8]) -> u32 {
let mut res = 0;
for ch in buf {
res = res * 10 + (u32::from(*ch));
}
res
}
//------------ Rrsig ---------------------------------------------------------
#[derive(Clone)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(bound(
serialize = "
Octs: octseq::serde::SerializeOctets + AsRef<[u8]>,
Name: serde::Serialize,
",
deserialize = "
Octs: FromBuilder + octseq::serde::DeserializeOctets<'de>,
<Octs as FromBuilder>::Builder:
OctetsBuilder + EmptyBuilder,
Name: serde::Deserialize<'de>,
",
))
)]
pub struct Rrsig<Octs, Name> {
type_covered: Rtype,
algorithm: SecAlg,
labels: u8,
original_ttl: Ttl,
expiration: Timestamp,
inception: Timestamp,
key_tag: u16,
signer_name: Name,
#[cfg_attr(
feature = "serde",
serde(with = "crate::utils::base64::serde")
)]
signature: Octs,
}
impl Rrsig<(), ()> {
/// The rtype of this record data type.
pub(crate) const RTYPE: Rtype = Rtype::RRSIG;
}
impl<Octs, Name> Rrsig<Octs, Name> {
#[allow(clippy::too_many_arguments)] // XXX Consider changing.
pub fn new(
type_covered: Rtype,
algorithm: SecAlg,
labels: u8,
original_ttl: Ttl,
expiration: Timestamp,
inception: Timestamp,
key_tag: u16,
signer_name: Name,
signature: Octs,
) -> Result<Self, LongRecordData>
where
Octs: AsRef<[u8]>,
Name: ToName,
{
LongRecordData::check_len(
usize::from(
Rtype::COMPOSE_LEN
+ SecAlg::COMPOSE_LEN
+ u8::COMPOSE_LEN
+ u32::COMPOSE_LEN
+ Timestamp::COMPOSE_LEN
+ Timestamp::COMPOSE_LEN
+ u16::COMPOSE_LEN
+ signer_name.compose_len(),
)
.checked_add(signature.as_ref().len())
.expect("long signature"),
)?;
Ok(unsafe {
Rrsig::new_unchecked(
type_covered,
algorithm,
labels,
original_ttl,
expiration,
inception,
key_tag,
signer_name,
signature,
)
})
}
/// Creates new RRSIG record data without checking.
///
/// # Safety
///
/// The caller needs to ensure that wire format representation of the
/// record data is at most 65,535 octets long.
#[allow(clippy::too_many_arguments)] // XXX Consider changing.
pub unsafe fn new_unchecked(
type_covered: Rtype,
algorithm: SecAlg,
labels: u8,
original_ttl: Ttl,
expiration: Timestamp,
inception: Timestamp,
key_tag: u16,
signer_name: Name,
signature: Octs,
) -> Self {
Rrsig {
type_covered,
algorithm,
labels,
original_ttl,
expiration,
inception,
key_tag,
signer_name,
signature,
}
}
pub fn type_covered(&self) -> Rtype {
self.type_covered
}
pub fn algorithm(&self) -> SecAlg {
self.algorithm
}
pub fn labels(&self) -> u8 {
self.labels
}
pub fn original_ttl(&self) -> Ttl {
self.original_ttl
}
pub fn expiration(&self) -> Timestamp {
self.expiration
}
pub fn inception(&self) -> Timestamp {
self.inception
}
pub fn key_tag(&self) -> u16 {
self.key_tag
}
pub fn signer_name(&self) -> &Name {
&self.signer_name
}
pub fn signature(&self) -> &Octs {
&self.signature
}
pub fn set_signature(&mut self, signature: Octs) {
self.signature = signature
}
pub(super) fn convert_octets<TOcts, TName>(
self,
) -> Result<Rrsig<TOcts, TName>, TOcts::Error>
where
TOcts: OctetsFrom<Octs>,
TName: OctetsFrom<Name, Error = TOcts::Error>,
{
Ok(unsafe {
Rrsig::new_unchecked(
self.type_covered,
self.algorithm,
self.labels,
self.original_ttl,
self.expiration,
self.inception,
self.key_tag,
TName::try_octets_from(self.signer_name)?,