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
// Copyright 2015-2023 Benjamin Fry <benjaminfry@me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// https://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! DNSSEC related Proof of record authenticity

use std::{fmt, ops::BitOr};

use bitflags::bitflags;
#[cfg(feature = "serde-config")]
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{
    error::{DnsSecError, ProtoError},
    op::Query,
    rr::{Name, RecordType},
};

use super::Algorithm;

/// Represents the status of a DNSSEC verified record.
///
/// see [RFC 4035, DNSSEC Protocol Modifications, March 2005](https://datatracker.ietf.org/doc/html/rfc4035#section-4.3)
/// ```text
/// 4.3.  Determining Security Status of Data
///
///   A security-aware resolver MUST be able to determine whether it should
///   expect a particular RRset to be signed.  More precisely, a
///   security-aware resolver must be able to distinguish between four
///   cases:
/// ```
#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
#[must_use = "Proof is a flag on Record data, it should be interrogated before using a record"]
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd)]
#[repr(u8)]
pub enum Proof {
    /// An RRset for which the resolver is able to build a chain of
    ///   signed DNSKEY and DS RRs from a trusted security anchor to the
    ///   RRset.  In this case, the RRset should be signed and is subject to
    ///   signature validation, as described above.
    Secure = 3,

    /// An RRset for which the resolver knows that it has no chain
    ///   of signed DNSKEY and DS RRs from any trusted starting point to the
    ///   RRset.  This can occur when the target RRset lies in an unsigned
    ///   zone or in a descendent of an unsigned zone.  In this case, the
    ///   RRset may or may not be signed, but the resolver will not be able
    ///   to verify the signature.
    Insecure = 2,

    /// An RRset for which the resolver believes that it ought to be
    ///   able to establish a chain of trust but for which it is unable to
    ///   do so, either due to signatures that for some reason fail to
    ///   validate or due to missing data that the relevant DNSSEC RRs
    ///   indicate should be present.  This case may indicate an attack but
    ///   may also indicate a configuration error or some form of data
    ///   corruption.
    Bogus = 1,

    /// An RRset for which the resolver is not able to
    ///   determine whether the RRset should be signed, as the resolver is
    ///   not able to obtain the necessary DNSSEC RRs.  This can occur when
    ///   the security-aware resolver is not able to contact security-aware
    ///   name servers for the relevant zones.
    #[default]
    Indeterminate = 0,
}

impl Proof {
    /// Returns true if this Proof represents a validated DNSSEC record
    #[inline]
    pub fn is_secure(&self) -> bool {
        *self == Self::Secure
    }

    /// Returns true if this Proof represents a validated to be insecure DNSSEC record,
    ///   meaning the zone is known to be not signed
    #[inline]
    pub fn is_insecure(&self) -> bool {
        *self == Self::Insecure
    }

    /// Returns true if this Proof represents a DNSSEC record that failed validation,
    ///   meaning that the DNSSEC is bad, or other DNSSEC records are incorrect
    #[inline]
    pub fn is_bogus(&self) -> bool {
        *self == Self::Bogus
    }

    /// Either the record has not been verified or there were network issues fetching DNSSEC records
    #[inline]
    pub fn is_indeterminate(&self) -> bool {
        *self == Self::Indeterminate
    }
}

impl fmt::Display for Proof {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::Secure => "Secure",
            Self::Insecure => "Insecure",
            Self::Bogus => "Bogus",
            Self::Indeterminate => "Indeterminate",
        };

        f.write_str(s)
    }
}

impl std::error::Error for Proof {}

#[test]
fn test_order() {
    assert!(Proof::Secure > Proof::Insecure);
    assert!(Proof::Insecure > Proof::Bogus);
    assert!(Proof::Bogus > Proof::Indeterminate);
}

bitflags! {
    /// Represents a set of flags.
    pub struct ProofFlags: u32 {
        /// Represents Proof::Secure
        const SECURE = 1 << Proof::Secure as u8;
        /// Represents Proof::Insecure
        const INSECURE = 1 << Proof::Insecure as u8;
        /// Represents Proof::Bogus
        const BOGUS = 1 << Proof::Bogus as u8;
        /// Represents Proof::Indeterminate
        const INDETERMINATE = 1 << Proof::Indeterminate as u8;
    }
}

impl From<Proof> for ProofFlags {
    fn from(proof: Proof) -> Self {
        match proof {
            Proof::Secure => Self::SECURE,
            Proof::Insecure => Self::INSECURE,
            Proof::Bogus => Self::BOGUS,
            Proof::Indeterminate => Self::INDETERMINATE,
        }
    }
}

impl BitOr for Proof {
    type Output = ProofFlags;

    // rhs is the "right-hand side" of the expression `a | b`
    fn bitor(self, rhs: Self) -> Self::Output {
        ProofFlags::from(self) | ProofFlags::from(rhs)
    }
}

/// The error kind for dnssec errors that get returned in the crate
#[allow(unreachable_pub)]
#[derive(Debug, Error, Clone)]
#[non_exhaustive]
pub enum ProofErrorKind {
    /// An error with an arbitrary message, referenced as &'static str
    #[error("{0}")]
    Message(&'static str),

    /// An error with an arbitrary message, stored as String
    #[error("{0}")]
    Msg(String),

    /// Algorithm mismatch between rrsig and dnskey
    #[error("algorithm mismatch rrsig: {rrsig} dnskey: {dnskey}")]
    AlgorithmMismatch {
        /// Algorithm specified in the RRSIG
        rrsig: Algorithm,
        /// Algorithm supported in the DNSKEY
        dnskey: Algorithm,
    },

    /// A DNSSEC validation error, occured
    #[error("ssl error: {0}")]
    DnsSecError(#[from] DnsSecError),

    /// A DnsKey verification of rrset and rrsig failed
    #[error("dnskey and rrset failed to verify: {name} key_tag: {key_tag}")]
    DnsKeyVerifyRrsig {
        /// The name/label of the DNSKEY
        name: Name,
        /// The key tag derived from the DNSKEY
        key_tag: u16,
        /// The Error that occurred during validation
        error: ProtoError,
    },

    /// There was no DNSKEY found for verifying the DNSSEC of the zone
    #[error("no dnskey was found: {name}")]
    DnskeyNotFound {
        /// The name of the missing DNSKEY
        name: Name,
    },

    /// A DnsKey was revoked and could not be used for validation
    #[error("dnskey revoked: {name}, key_tag: {key_tag}")]
    DnsKeyRevoked {
        /// The name of the DNSKEY that was revoked
        name: Name,
        /// The key tag derived from the DNSKEY
        key_tag: u16,
    },

    /// No DNSSEC records returned with for the DS record
    #[error("ds has no dnssec proof: {name}")]
    DsHasNoDnssecProof {
        /// DS record name
        name: Name,
    },

    /// DS record exists but not a DNSKEY that matches
    #[error("ds record exists, but no dnskey: {name}")]
    DsRecordsButNoDnskey {
        /// Name of the missing DNSKEY
        name: Name,
    },

    /// DS record parent exists, but child does not
    #[error("ds record should exist: {name}")]
    DsRecordShouldExist {
        /// Name fo the missing DS key
        name: Name,
    },

    /// The DS response was empty
    #[error("ds response empty: {name}")]
    DsResponseEmpty {
        /// No records for the DS query were returned
        name: Name,
    },

    /// DS record does not exist, and this was proven with an NSEC
    #[error("ds record does not exist: {name}")]
    DsResponseNsec {
        /// The name of the DS record
        name: Name,
    },

    /// The DnsKey is not marked as a zone key
    #[error("not a zone signing key: {name} key_tag: {key_tag}")]
    NotZoneDnsKey {
        /// Name of the DNSKEY
        name: Name,
        /// The key tag derived from the DNSKEY
        key_tag: u16,
    },

    /// There was a protocol error when looking up DNSSEC records
    #[error("communication failure for query: {query}: {proto}")]
    Proto {
        /// Query that failed
        query: Query,
        /// Resons fo the failure
        proto: ProtoError,
    },

    /// The RRSIGs for the rrset are not present.
    ///    It's indeterminate if DS records can't be found
    ///    It's bogus if the DS records are present
    #[error("rrsigs are not present for: {name} record_type: {record_type}")]
    RrsigsNotPresent {
        /// Name that RRSIGS are missing for
        name: Name,
        /// The record type in question
        record_type: RecordType,
    },

    /// The RRSIGs could not be verified or failed validation
    #[error("rrsigs were not able to be verified: {name}, type: {record_type}")]
    RrsigsUnverified {
        /// Name that RRSIGS failed for
        name: Name,
        /// The record type in question
        record_type: RecordType,
    },

    /// The self-signed dnskey is invalid
    #[error("self-signed dnskey is invalid: {name}")]
    SelfSignedKeyInvalid {
        /// Name of the DNSKEY
        name: Name,
    },
}

/// The error type for dnssec errors that get returned in the crate
#[derive(Debug, Clone, Error)]
pub struct ProofError {
    /// The proof derived from the failed state
    pub proof: Proof,
    /// The kind of error
    pub kind: ProofErrorKind,
}

impl ProofError {
    /// Create an error with the given Proof and Associated Error
    pub fn new(proof: Proof, kind: ProofErrorKind) -> Self {
        Self { proof, kind }
    }

    /// Get the kind of the error
    pub fn kind(&self) -> &ProofErrorKind {
        &self.kind
    }
}

impl fmt::Display for ProofError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.proof, self.kind)
    }
}

/// A wrapper type to ensure that the state of a DNSSEC proof is evaluated before use
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Proven<T> {
    proof: Proof,
    value: T,
}

impl<T> Proven<T> {
    /// Wrap the value with the given proof
    pub fn new(proof: Proof, value: T) -> Self {
        Self { proof, value }
    }

    /// Get the associated proof
    pub fn proof(&self) -> Proof {
        self.proof
    }

    /// Attempts to borrow the value only if it matches flags, returning the associated proof on failure
    ///
    /// ```
    /// use hickory_proto::rr::dnssec::{Proof, Proven};
    ///
    /// let proven = Proven::new(Proof::Bogus, 42u32);
    ///
    /// assert_eq!(*proven.require_as_ref(Proof::Bogus).unwrap(), 42_u32);
    /// assert_eq!(*proven.require_as_ref(Proof::Bogus | Proof::Indeterminate).unwrap(), 42_u32);
    /// assert_eq!(proven.require_as_ref(Proof::Secure | Proof::Insecure).unwrap_err(), Proof::Bogus);
    /// ```
    pub fn require_as_ref<I: Into<ProofFlags>>(&self, flags: I) -> Result<&T, Proof> {
        if flags.into().contains(ProofFlags::from(self.proof)) {
            Ok(&self.value)
        } else {
            Err(self.proof)
        }
    }

    /// Attempts to take the value only if it matches flags, returning the associated proof on failure
    ///
    /// ```
    /// use hickory_proto::rr::dnssec::{Proof, Proven};
    ///
    /// let proven = Proven::new(Proof::Bogus, 42u32);
    ///
    /// assert_eq!(proven.clone().require(Proof::Bogus).unwrap(), 42_u32);
    /// assert_eq!(proven.clone().require(Proof::Bogus | Proof::Indeterminate).unwrap(), 42_u32);
    /// assert!(proven.require(Proof::Secure | Proof::Insecure).is_err());
    /// ```
    pub fn require<I: Into<ProofFlags>>(self, flags: I) -> Result<T, Self> {
        if flags.into().contains(ProofFlags::from(self.proof)) {
            Ok(self.value)
        } else {
            Err(self)
        }
    }

    /// Map the value with the associated function, carrying forward the proof
    pub fn map<U, F>(self, f: F) -> Proven<U>
    where
        F: FnOnce(T) -> U,
    {
        Proven {
            proof: self.proof,
            value: f(self.value),
        }
    }

    /// Unwraps the Proven type into it's parts
    pub fn into_parts(self) -> (Proof, T) {
        let Self { proof, value } = self;

        (proof, value)
    }
}

impl<T> Proven<Option<T>> {
    /// If the inner type is an Option this will transpose them so that it's an option wrapped Proven
    pub fn transpose(self) -> Option<Proven<T>> {
        if let Some(value) = self.value {
            Some(Proven {
                proof: self.proof,
                value,
            })
        } else {
            None
        }
    }
}