hickory_proto/rr/dnssec/
signer.rs

1// Copyright 2015-2023 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! signer is a structure for performing many of the signing processes of the DNSSEC specification
9use tracing::debug;
10
11#[cfg(feature = "dnssec")]
12use std::time::Duration;
13
14#[cfg(feature = "dnssec")]
15use crate::{
16    error::DnsSecResult,
17    rr::{
18        dnssec::{
19            rdata::{DNSSECRData, DNSKEY, KEY, SIG},
20            tbs, Algorithm, KeyPair, Private, TBS,
21        },
22        {DNSClass, Name, RData, RecordType},
23    },
24    serialize::binary::BinEncoder,
25};
26use crate::{
27    error::{ProtoErrorKind, ProtoResult},
28    op::{Message, MessageFinalizer, MessageVerifier},
29    rr::Record,
30    serialize::binary::BinEncodable,
31};
32
33/// Use for performing signing and validation of DNSSEC based components. The SigSigner can be used for singing requests and responses with SIG0, or DNSSEC RRSIG records. The format is based on the SIG record type.
34///
35/// TODO: warning this struct and it's impl are under high volatility, expect breaking changes
36///
37/// [RFC 4035](https://tools.ietf.org/html/rfc4035), DNSSEC Protocol Modifications, March 2005
38///
39/// ```text
40/// 5.3.  Authenticating an RRset with an RRSIG RR
41///
42///    A validator can use an RRSIG RR and its corresponding DNSKEY RR to
43///    attempt to authenticate RRsets.  The validator first checks the RRSIG
44///    RR to verify that it covers the RRset, has a valid time interval, and
45///    identifies a valid DNSKEY RR.  The validator then constructs the
46///    canonical form of the signed data by appending the RRSIG RDATA
47///    (excluding the Signature Field) with the canonical form of the
48///    covered RRset.  Finally, the validator uses the public key and
49///    signature to authenticate the signed data.  Sections 5.3.1, 5.3.2,
50///    and 5.3.3 describe each step in detail.
51///
52/// 5.3.1.  Checking the RRSIG RR Validity
53///
54///    A security-aware resolver can use an RRSIG RR to authenticate an
55///    RRset if all of the following conditions hold:
56///
57///    o  The RRSIG RR and the RRset MUST have the same owner name and the
58///       same class.
59///
60///    o  The RRSIG RR's Signer's Name field MUST be the name of the zone
61///       that contains the RRset.
62///
63///    o  The RRSIG RR's Type Covered field MUST equal the RRset's type.
64///
65///    o  The number of labels in the RRset owner name MUST be greater than
66///       or equal to the value in the RRSIG RR's Labels field.
67///
68///    o  The validator's notion of the current time MUST be less than or
69///       equal to the time listed in the RRSIG RR's Expiration field.
70///
71///    o  The validator's notion of the current time MUST be greater than or
72///       equal to the time listed in the RRSIG RR's Inception field.
73///
74///    o  The RRSIG RR's Signer's Name, Algorithm, and Key Tag fields MUST
75///       match the owner name, algorithm, and key tag for some DNSKEY RR in
76///       the zone's apex DNSKEY RRset.
77///
78///    o  The matching DNSKEY RR MUST be present in the zone's apex DNSKEY
79///       RRset, and MUST have the Zone Flag bit (DNSKEY RDATA Flag bit 7)
80///       set.
81///
82///    It is possible for more than one DNSKEY RR to match the conditions
83///    above.  In this case, the validator cannot predetermine which DNSKEY
84///    RR to use to authenticate the signature, and it MUST try each
85///    matching DNSKEY RR until either the signature is validated or the
86///    validator has run out of matching public keys to try.
87///
88///    Note that this authentication process is only meaningful if the
89///    validator authenticates the DNSKEY RR before using it to validate
90///    signatures.  The matching DNSKEY RR is considered to be authentic if:
91///
92///    o  the apex DNSKEY RRset containing the DNSKEY RR is considered
93///       authentic; or
94///
95///    o  the RRset covered by the RRSIG RR is the apex DNSKEY RRset itself,
96///       and the DNSKEY RR either matches an authenticated DS RR from the
97///       parent zone or matches a trust anchor.
98///
99/// 5.3.2.  Reconstructing the Signed Data
100///
101///    Once the RRSIG RR has met the validity requirements described in
102///    Section 5.3.1, the validator has to reconstruct the original signed
103///    data.  The original signed data includes RRSIG RDATA (excluding the
104///    Signature field) and the canonical form of the RRset.  Aside from
105///    being ordered, the canonical form of the RRset might also differ from
106///    the received RRset due to DNS name compression, decremented TTLs, or
107///    wildcard expansion.  The validator should use the following to
108///    reconstruct the original signed data:
109///
110///          signed_data = RRSIG_RDATA | RR(1) | RR(2)...  where
111///
112///             "|" denotes concatenation
113///
114///             RRSIG_RDATA is the wire format of the RRSIG RDATA fields
115///                with the Signature field excluded and the Signer's Name
116///                in canonical form.
117///
118///             RR(i) = name | type | class | OrigTTL | RDATA length | RDATA
119///
120///                name is calculated according to the function below
121///
122///                class is the RRset's class
123///
124///                type is the RRset type and all RRs in the class
125///
126///                OrigTTL is the value from the RRSIG Original TTL field
127///
128///                All names in the RDATA field are in canonical form
129///
130///                The set of all RR(i) is sorted into canonical order.
131///
132///             To calculate the name:
133///                let rrsig_labels = the value of the RRSIG Labels field
134///
135///                let fqdn = RRset's fully qualified domain name in
136///                                canonical form
137///
138///                let fqdn_labels = Label count of the fqdn above.
139///
140///                if rrsig_labels = fqdn_labels,
141///                    name = fqdn
142///
143///                if rrsig_labels < fqdn_labels,
144///                   name = "*." | the rightmost rrsig_label labels of the
145///                                 fqdn
146///
147///                if rrsig_labels > fqdn_labels
148///                   the RRSIG RR did not pass the necessary validation
149///                   checks and MUST NOT be used to authenticate this
150///                   RRset.
151///
152///    The canonical forms for names and RRsets are defined in [RFC4034].
153///
154///    NSEC RRsets at a delegation boundary require special processing.
155///    There are two distinct NSEC RRsets associated with a signed delegated
156///    name.  One NSEC RRset resides in the parent zone, and specifies which
157///    RRsets are present at the parent zone.  The second NSEC RRset resides
158///    at the child zone and identifies which RRsets are present at the apex
159///    in the child zone.  The parent NSEC RRset and child NSEC RRset can
160///    always be distinguished as only a child NSEC RR will indicate that an
161///    SOA RRset exists at the name.  When reconstructing the original NSEC
162///    RRset for the delegation from the parent zone, the NSEC RRs MUST NOT
163///    be combined with NSEC RRs from the child zone.  When reconstructing
164///    the original NSEC RRset for the apex of the child zone, the NSEC RRs
165///    MUST NOT be combined with NSEC RRs from the parent zone.
166///
167///    Note that each of the two NSEC RRsets at a delegation point has a
168///    corresponding RRSIG RR with an owner name matching the delegated
169///    name, and each of these RRSIG RRs is authoritative data associated
170///    with the same zone that contains the corresponding NSEC RRset.  If
171///    necessary, a resolver can tell these RRSIG RRs apart by checking the
172///    Signer's Name field.
173///
174/// 5.3.3.  Checking the Signature
175///
176///    Once the resolver has validated the RRSIG RR as described in Section
177///    5.3.1 and reconstructed the original signed data as described in
178///    Section 5.3.2, the validator can attempt to use the cryptographic
179///    signature to authenticate the signed data, and thus (finally!)
180///    authenticate the RRset.
181///
182///    The Algorithm field in the RRSIG RR identifies the cryptographic
183///    algorithm used to generate the signature.  The signature itself is
184///    contained in the Signature field of the RRSIG RDATA, and the public
185///    key used to verify the signature is contained in the Public Key field
186///    of the matching DNSKEY RR(s) (found in Section 5.3.1).  [RFC4034]
187///    provides a list of algorithm types and provides pointers to the
188///    documents that define each algorithm's use.
189///
190///    Note that it is possible for more than one DNSKEY RR to match the
191///    conditions in Section 5.3.1.  In this case, the validator can only
192///    determine which DNSKEY RR is correct by trying each matching public
193///    key until the validator either succeeds in validating the signature
194///    or runs out of keys to try.
195///
196///    If the Labels field of the RRSIG RR is not equal to the number of
197///    labels in the RRset's fully qualified owner name, then the RRset is
198///    either invalid or the result of wildcard expansion.  The resolver
199///    MUST verify that wildcard expansion was applied properly before
200///    considering the RRset to be authentic.  Section 5.3.4 describes how
201///    to determine whether a wildcard was applied properly.
202///
203///    If other RRSIG RRs also cover this RRset, the local resolver security
204///    policy determines whether the resolver also has to test these RRSIG
205///    RRs and how to resolve conflicts if these RRSIG RRs lead to differing
206///    results.
207///
208///    If the resolver accepts the RRset as authentic, the validator MUST
209///    set the TTL of the RRSIG RR and each RR in the authenticated RRset to
210///    a value no greater than the minimum of:
211///
212///    o  the RRset's TTL as received in the response;
213///
214///    o  the RRSIG RR's TTL as received in the response;
215///
216///    o  the value in the RRSIG RR's Original TTL field; and
217///
218///    o  the difference of the RRSIG RR's Signature Expiration time and the
219///       current time.
220///
221/// 5.3.4.  Authenticating a Wildcard Expanded RRset Positive Response
222///
223///    If the number of labels in an RRset's owner name is greater than the
224///    Labels field of the covering RRSIG RR, then the RRset and its
225///    covering RRSIG RR were created as a result of wildcard expansion.
226///    Once the validator has verified the signature, as described in
227///    Section 5.3, it must take additional steps to verify the non-
228///    existence of an exact match or closer wildcard match for the query.
229///    Section 5.4 discusses these steps.
230///
231///    Note that the response received by the resolver should include all
232///    NSEC RRs needed to authenticate the response (see Section 3.1.3).
233/// ```
234#[cfg(feature = "dnssec")]
235#[cfg_attr(docsrs, doc(cfg(feature = "dnssec")))]
236pub struct SigSigner {
237    // TODO: this should really be a trait and generic struct over KEY and DNSKEY
238    key_rdata: RData,
239    key: KeyPair<Private>,
240    algorithm: Algorithm,
241    signer_name: Name,
242    sig_duration: Duration,
243    is_zone_signing_key: bool,
244}
245
246/// Placeholder type for when OpenSSL and *ring* are disabled; enable OpenSSL and Ring for support
247#[cfg(not(feature = "dnssec"))]
248#[allow(missing_copy_implementations)]
249pub struct SigSigner;
250
251/// See [`SigSigner`](crate::rr::dnssec::SigSigner)
252#[deprecated(note = "renamed to SigSigner")]
253pub type Signer = SigSigner;
254
255#[cfg(feature = "dnssec")]
256#[cfg_attr(docsrs, doc(cfg(feature = "dnssec")))]
257impl SigSigner {
258    /// Version of Signer for verifying RRSIGs and SIG0 records.
259    ///
260    /// # Arguments
261    ///
262    /// * `key_rdata` - the DNSKEY and public key material
263    /// * `key` - the private key for signing, unless validating, where just the public key is necessary
264    /// * `signer_name` - name in the zone to which this DNSKEY is bound
265    /// * `sig_duration` - time period for which this key is valid, 0 when verifying
266    /// * `is_zone_update_auth` - this key may be used for updating the zone
267    pub fn dnssec(
268        key_rdata: DNSKEY,
269        key: KeyPair<Private>,
270        signer_name: Name,
271        sig_duration: Duration,
272    ) -> Self {
273        let algorithm = key_rdata.algorithm();
274        let is_zone_signing_key = key_rdata.zone_key();
275
276        Self {
277            key_rdata: key_rdata.into(),
278            key,
279            algorithm,
280            signer_name,
281            sig_duration,
282            is_zone_signing_key,
283        }
284    }
285
286    /// Version of Signer for verifying RRSIGs and SIG0 records.
287    ///
288    /// # Arguments
289    ///
290    /// * `key_rdata` - the KEY and public key material
291    /// * `key` - the private key for signing, unless validating, where just the public key is necessary
292    /// * `signer_name` - name in the zone to which this DNSKEY is bound
293    /// * `is_zone_update_auth` - this key may be used for updating the zone
294    pub fn sig0(key_rdata: KEY, key: KeyPair<Private>, signer_name: Name) -> Self {
295        let algorithm = key_rdata.algorithm();
296
297        Self {
298            key_rdata: key_rdata.into(),
299            key,
300            algorithm,
301            signer_name,
302            // can be Duration::ZERO after min Rust version 1.53
303            sig_duration: Duration::new(0, 0),
304            is_zone_signing_key: false,
305        }
306    }
307
308    /// Version of Signer for signing RRSIGs and SIG0 records.
309    #[deprecated(note = "use SIG0 or DNSSEC constructors")]
310    pub fn new(
311        algorithm: Algorithm,
312        key: KeyPair<Private>,
313        signer_name: Name,
314        sig_duration: Duration,
315        is_zone_signing_key: bool,
316        _: bool,
317    ) -> Self {
318        let dnskey = key
319            .to_dnskey(algorithm)
320            .expect("something went wrong, use one of the SIG0 or DNSSEC constructors");
321
322        Self {
323            key_rdata: dnskey.into(),
324            key,
325            algorithm,
326            signer_name,
327            sig_duration,
328            is_zone_signing_key,
329        }
330    }
331
332    /// Return the key used for validation/signing
333    pub fn key(&self) -> &KeyPair<Private> {
334        &self.key
335    }
336
337    /// Returns the duration that this signature is valid for
338    pub fn sig_duration(&self) -> Duration {
339        self.sig_duration
340    }
341
342    /// A hint to the DNSKey associated with this Signer can be used to sign/validate records in the zone
343    pub fn is_zone_signing_key(&self) -> bool {
344        self.is_zone_signing_key
345    }
346
347    /// Signs a hash.
348    ///
349    /// This will panic if the `key` is not a private key and can be used for signing.
350    ///
351    /// # Arguments
352    ///
353    /// * `hash` - the hashed resource record set, see `rrset_tbs`.
354    ///
355    /// # Return value
356    ///
357    /// The signature, ready to be stored in an `RData::RRSIG`.
358    pub fn sign(&self, tbs: &TBS) -> ProtoResult<Vec<u8>> {
359        self.key
360            .sign(self.algorithm, tbs)
361            .map_err(|e| ProtoErrorKind::Msg(format!("signing error: {e}")).into())
362    }
363
364    /// Returns the algorithm this Signer will use to either sign or validate a signature
365    pub fn algorithm(&self) -> Algorithm {
366        self.algorithm
367    }
368
369    /// The name of the signing entity, e.g. the DNS server name.
370    ///
371    /// This should match the name on key in the zone.
372    pub fn signer_name(&self) -> &Name {
373        &self.signer_name
374    }
375
376    // TODO: move this to DNSKEY/KEY?
377    /// The key tag is calculated as a hash to more quickly lookup a DNSKEY.
378    ///
379    /// [RFC 1035](https://tools.ietf.org/html/rfc1035), DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION, November 1987
380    ///
381    /// ```text
382    /// RFC 2535                DNS Security Extensions               March 1999
383    ///
384    /// 4.1.6 Key Tag Field
385    ///
386    ///  The "key Tag" is a two octet quantity that is used to efficiently
387    ///  select between multiple keys which may be applicable and thus check
388    ///  that a public key about to be used for the computationally expensive
389    ///  effort to check the signature is possibly valid.  For algorithm 1
390    ///  (MD5/RSA) as defined in [RFC 2537], it is the next to the bottom two
391    ///  octets of the public key modulus needed to decode the signature
392    ///  field.  That is to say, the most significant 16 of the least
393    ///  significant 24 bits of the modulus in network (big endian) order. For
394    ///  all other algorithms, including private algorithms, it is calculated
395    ///  as a simple checksum of the KEY RR as described in Appendix C.
396    ///
397    /// Appendix C: Key Tag Calculation
398    ///
399    ///  The key tag field in the SIG RR is just a means of more efficiently
400    ///  selecting the correct KEY RR to use when there is more than one KEY
401    ///  RR candidate available, for example, in verifying a signature.  It is
402    ///  possible for more than one candidate key to have the same tag, in
403    ///  which case each must be tried until one works or all fail.  The
404    ///  following reference implementation of how to calculate the Key Tag,
405    ///  for all algorithms other than algorithm 1, is in ANSI C.  It is coded
406    ///  for clarity, not efficiency.  (See section 4.1.6 for how to determine
407    ///  the Key Tag of an algorithm 1 key.)
408    ///
409    ///  /* assumes int is at least 16 bits
410    ///     first byte of the key tag is the most significant byte of return
411    ///     value
412    ///     second byte of the key tag is the least significant byte of
413    ///     return value
414    ///     */
415    ///
416    ///  int keytag (
417    ///
418    ///          unsigned char key[],  /* the RDATA part of the KEY RR */
419    ///          unsigned int keysize, /* the RDLENGTH */
420    ///          )
421    ///  {
422    ///  long int    ac;    /* assumed to be 32 bits or larger */
423    ///
424    ///  for ( ac = 0, i = 0; i < keysize; ++i )
425    ///      ac += (i&1) ? key[i] : key[i]<<8;
426    ///  ac += (ac>>16) & 0xFFFF;
427    ///  return ac & 0xFFFF;
428    ///  }
429    /// ```
430    pub fn calculate_key_tag(&self) -> ProtoResult<u16> {
431        let mut bytes: Vec<u8> = Vec::with_capacity(512);
432        {
433            let mut e = BinEncoder::new(&mut bytes);
434            self.key_rdata.emit(&mut e)?;
435        }
436        Ok(DNSKEY::calculate_key_tag_internal(&bytes))
437    }
438
439    /// Signs the given message, returning the signature bytes.
440    ///
441    /// # Arguments
442    ///
443    /// * `message` - the message to sign
444    ///
445    /// [rfc2535](https://tools.ietf.org/html/rfc2535#section-4.1.8.1), Domain Name System Security Extensions, 1999
446    ///
447    /// ```text
448    /// 4.1.8.1 Calculating Transaction and Request SIGs
449    ///
450    ///  A response message from a security aware server may optionally
451    ///  contain a special SIG at the end of the additional information
452    ///  section to authenticate the transaction.
453    ///
454    ///  This SIG has a "type covered" field of zero, which is not a valid RR
455    ///  type.  It is calculated by using a "data" (see Section 4.1.8) of the
456    ///  entire preceding DNS reply message, including DNS header but not the
457    ///  IP header and before the reply RR counts have been adjusted for the
458    ///  inclusion of any transaction SIG, concatenated with the entire DNS
459    ///  query message that produced this response, including the query's DNS
460    ///  header and any request SIGs but not its IP header.  That is
461    ///
462    ///  data = full response (less transaction SIG) | full query
463    ///
464    ///  Verification of the transaction SIG (which is signed by the server
465    ///  host key, not the zone key) by the requesting resolver shows that the
466    ///  query and response were not tampered with in transit, that the
467    ///  response corresponds to the intended query, and that the response
468    ///  comes from the queried server.
469    ///
470    ///  A DNS request may be optionally signed by including one or more SIGs
471    ///  at the end of the query. Such SIGs are identified by having a "type
472    ///  covered" field of zero. They sign the preceding DNS request message
473    ///  including DNS header but not including the IP header or any request
474    ///  SIGs at the end and before the request RR counts have been adjusted
475    ///  for the inclusions of any request SIG(s).
476    ///
477    ///  WARNING: Request SIGs are unnecessary for any currently defined
478    ///  request other than update [RFC 2136, 2137] and will cause some old
479    ///  DNS servers to give an error return or ignore a query.  However, such
480    ///  SIGs may in the future be needed for other requests.
481    ///
482    ///  Except where needed to authenticate an update or similar privileged
483    ///  request, servers are not required to check request SIGs.
484    /// ```
485    ///  ---
486    ///
487    /// NOTE: In classic RFC style, this is unclear, it implies that each SIG record is not included in
488    ///  the Additional record count, but this makes it more difficult to process and calculate more
489    ///  than one SIG0 record. Annoyingly, it means that the Header is signed with different material
490    ///  (i.e. additional record count - #SIG0 records), so the exact header sent is NOT the header
491    ///  being verified.
492    ///
493    ///  ---
494    pub fn sign_message(&self, message: &Message, pre_sig0: &SIG) -> ProtoResult<Vec<u8>> {
495        tbs::message_tbs(message, pre_sig0).and_then(|tbs| self.sign(&tbs))
496    }
497
498    /// Extracts a public KEY from this Signer
499    pub fn to_dnskey(&self) -> DnsSecResult<DNSKEY> {
500        // TODO: this interface should allow for setting if this is a secure entry point vs. ZSK
501        self.key
502            .to_public_bytes()
503            .map(|bytes| DNSKEY::new(self.is_zone_signing_key, true, false, self.algorithm, bytes))
504    }
505
506    /// Test that this key is capable of signing and verifying data
507    pub fn test_key(&self) -> DnsSecResult<()> {
508        // use proto::rr::dnssec::PublicKey;
509
510        // // TODO: why doesn't this work for ecdsa_256 and 384?
511        // let test_data = TBS::from(b"DEADBEEF" as &[u8]);
512
513        // let signature = self.sign(&test_data).map_err(|e| {println!("failed to sign, {:?}", e); e})?;
514        // let pk = self.key.to_public_key()?;
515        // pk.verify(self.algorithm, test_data.as_ref(), &signature).map_err(|e| {println!("failed to verify, {:?}", e); e})?;
516
517        Ok(())
518    }
519}
520
521impl MessageFinalizer for SigSigner {
522    #[cfg(feature = "dnssec")]
523    fn finalize_message(
524        &self,
525        message: &Message,
526        current_time: u32,
527    ) -> ProtoResult<(Vec<Record>, Option<MessageVerifier>)> {
528        debug!("signing message: {message:?}");
529        let key_tag: u16 = self.calculate_key_tag()?;
530
531        // this is based on RFCs 2535, 2931 and 3007
532
533        // 'For all SIG(0) RRs, the owner name, class, TTL, and original TTL, are
534        //  meaningless.' - 2931
535        let mut sig0 = Record::new();
536
537        // The TTL fields SHOULD be zero
538        sig0.set_ttl(0);
539
540        // The CLASS field SHOULD be ANY
541        sig0.set_dns_class(DNSClass::ANY);
542
543        // The owner name SHOULD be root (a single zero octet).
544        sig0.set_name(Name::root());
545        let num_labels = sig0.name().num_labels();
546
547        let expiration_time: u32 = current_time + (5 * 60); // +5 minutes in seconds
548
549        sig0.set_rr_type(RecordType::SIG);
550        let pre_sig0 = SIG::new(
551            // type covered in SIG(0) is 0 which is what makes this SIG0 vs a standard SIG
552            RecordType::ZERO,
553            self.algorithm(),
554            num_labels,
555            // see above, original_ttl is meaningless, The TTL fields SHOULD be zero
556            0,
557            // recommended time is +5 minutes from now, to prevent timing attacks, 2 is probably good
558            expiration_time,
559            // current time, this should be UTC
560            // unsigned numbers of seconds since the start of 1 January 1970, GMT
561            current_time,
562            key_tag,
563            // can probably get rid of this clone if the ownership is correct
564            self.signer_name().clone(),
565            Vec::new(),
566        );
567        let signature: Vec<u8> = self.sign_message(message, &pre_sig0)?;
568        sig0.set_data(Some(RData::DNSSEC(DNSSECRData::SIG(
569            pre_sig0.set_sig(signature),
570        ))));
571
572        Ok((vec![sig0], None))
573    }
574
575    #[cfg(not(feature = "dnssec"))]
576    fn finalize_message(
577        &self,
578        _: &Message,
579        _: u32,
580    ) -> ProtoResult<(Vec<Record>, Option<MessageVerifier>)> {
581        Err(
582            ProtoErrorKind::Message("the ring or openssl feature must be enabled for signing")
583                .into(),
584        )
585    }
586}
587
588#[cfg(test)]
589#[cfg(feature = "openssl")]
590mod tests {
591    #![allow(clippy::dbg_macro, clippy::print_stdout)]
592
593    use openssl::bn::BigNum;
594    use openssl::pkey::Private;
595    use openssl::rsa::Rsa;
596
597    use crate::op::{Message, Query};
598    use crate::rr::dnssec::rdata::key::KeyUsage;
599    use crate::rr::dnssec::rdata::{DNSSECRData, RRSIG, SIG};
600    use crate::rr::dnssec::*;
601    use crate::rr::rdata::NS;
602    use crate::rr::{DNSClass, Name, Record, RecordType};
603
604    use super::*;
605
606    fn assert_send_and_sync<T: Send + Sync>() {}
607
608    #[test]
609    fn test_send_and_sync() {
610        assert_send_and_sync::<SigSigner>();
611    }
612
613    fn pre_sig0(signer: &SigSigner, inception_time: u32, expiration_time: u32) -> SIG {
614        SIG::new(
615            // type covered in SIG(0) is 0 which is what makes this SIG0 vs a standard SIG
616            RecordType::ZERO,
617            signer.algorithm(),
618            0,
619            // see above, original_ttl is meaningless, The TTL fields SHOULD be zero
620            0,
621            // recommended time is +5 minutes from now, to prevent timing attacks, 2 is probably good
622            expiration_time,
623            // current time, this should be UTC
624            // unsigned numbers of seconds since the start of 1 January 1970, GMT
625            inception_time,
626            signer.calculate_key_tag().unwrap(),
627            // can probably get rid of this clone if the ownership is correct
628            signer.signer_name().clone(),
629            Vec::new(),
630        )
631    }
632
633    #[test]
634    fn test_sign_and_verify_message_sig0() {
635        let origin: Name = Name::parse("example.com.", None).unwrap();
636        let mut question: Message = Message::new();
637        let mut query: Query = Query::new();
638        query.set_name(origin);
639        question.add_query(query);
640
641        let rsa = Rsa::generate(2048).unwrap();
642        let key = KeyPair::from_rsa(rsa).unwrap();
643        let sig0key = key.to_sig0key(Algorithm::RSASHA256).unwrap();
644        let signer = SigSigner::sig0(sig0key.clone(), key, Name::root());
645
646        let pre_sig0 = pre_sig0(&signer, 0, 300);
647        let sig = signer.sign_message(&question, &pre_sig0).unwrap();
648        println!("sig: {sig:?}");
649
650        assert!(!sig.is_empty());
651
652        assert!(sig0key.verify_message(&question, &sig, &pre_sig0).is_ok());
653
654        // now test that the sig0 record works correctly.
655        assert!(question.sig0().is_empty());
656        question.finalize(&signer, 0).expect("should have signed");
657        assert!(!question.sig0().is_empty());
658
659        let sig = signer.sign_message(&question, &pre_sig0);
660        println!("sig after sign: {sig:?}");
661
662        if let Some(RData::DNSSEC(DNSSECRData::SIG(ref sig))) = question.sig0()[0].data() {
663            assert!(sig0key.verify_message(&question, sig.sig(), sig).is_ok());
664        }
665    }
666
667    #[test]
668    #[allow(deprecated)]
669    fn test_sign_and_verify_rrset() {
670        let rsa = Rsa::generate(2048).unwrap();
671        let key = KeyPair::from_rsa(rsa).unwrap();
672        let sig0key = key
673            .to_sig0key_with_usage(Algorithm::RSASHA256, KeyUsage::Zone)
674            .unwrap();
675        let signer = SigSigner::sig0(sig0key, key, Name::root());
676
677        let origin: Name = Name::parse("example.com.", None).unwrap();
678        let rrsig = Record::new()
679            .set_name(origin.clone())
680            .set_ttl(86400)
681            .set_rr_type(RecordType::RRSIG)
682            .set_dns_class(DNSClass::IN)
683            .set_data(Some(RRSIG::new(
684                RecordType::NS,
685                Algorithm::RSASHA256,
686                origin.num_labels(),
687                86400,
688                5,
689                0,
690                signer.calculate_key_tag().unwrap(),
691                origin.clone(),
692                vec![],
693            )))
694            .clone();
695        let rrset = vec![
696            Record::new()
697                .set_name(origin.clone())
698                .set_ttl(86400)
699                .set_rr_type(RecordType::NS)
700                .set_dns_class(DNSClass::IN)
701                .set_data(Some(RData::NS(NS(Name::parse(
702                    "a.iana-servers.net.",
703                    None,
704                )
705                .unwrap()))))
706                .clone(),
707            Record::new()
708                .set_name(origin)
709                .set_ttl(86400)
710                .set_rr_type(RecordType::NS)
711                .set_dns_class(DNSClass::IN)
712                .set_data(Some(RData::NS(NS(Name::parse(
713                    "b.iana-servers.net.",
714                    None,
715                )
716                .unwrap()))))
717                .clone(),
718        ];
719
720        let tbs = tbs::rrset_tbs_with_rrsig(&rrsig, &rrset).unwrap();
721        let sig = signer.sign(&tbs).unwrap();
722
723        let pub_key = signer.key().to_public_bytes().unwrap();
724        let pub_key = PublicKeyEnum::from_public_bytes(&pub_key, Algorithm::RSASHA256).unwrap();
725
726        assert!(pub_key
727            .verify(Algorithm::RSASHA256, tbs.as_ref(), &sig)
728            .is_ok());
729    }
730
731    fn get_rsa_from_vec(params: &[u32]) -> Result<Rsa<Private>, openssl::error::ErrorStack> {
732        Rsa::from_private_components(
733            BigNum::from_u32(params[0]).unwrap(), // modulus: n
734            BigNum::from_u32(params[1]).unwrap(), // public exponent: e,
735            BigNum::from_u32(params[2]).unwrap(), // private exponent: de,
736            BigNum::from_u32(params[3]).unwrap(), // prime1: p,
737            BigNum::from_u32(params[4]).unwrap(), // prime2: q,
738            BigNum::from_u32(params[5]).unwrap(), // exponent1: dp,
739            BigNum::from_u32(params[6]).unwrap(), // exponent2: dq,
740            BigNum::from_u32(params[7]).unwrap(), // coefficient: qi
741        )
742    }
743
744    #[test]
745    #[allow(deprecated)]
746    #[allow(clippy::unreadable_literal)]
747    fn test_calculate_key_tag() {
748        let test_vectors = [
749            (vec![33, 3, 21, 11, 3, 1, 1, 1], 9739),
750            (
751                vec![
752                    0xc2fedb69, 0x10001, 0x6ebb9209, 0xf743, 0xc9e3, 0xd07f, 0x6275, 0x1095,
753                ],
754                42354,
755            ),
756        ];
757
758        for &(ref input_data, exp_result) in test_vectors.iter() {
759            let rsa = get_rsa_from_vec(input_data).unwrap();
760            let rsa_pem = rsa.private_key_to_pem().unwrap();
761            println!("pkey:\n{}", String::from_utf8(rsa_pem).unwrap());
762
763            let key = KeyPair::from_rsa(rsa).unwrap();
764            let sig0key = key
765                .to_sig0key_with_usage(Algorithm::RSASHA256, KeyUsage::Zone)
766                .unwrap();
767            let signer = SigSigner::sig0(sig0key, key, Name::root());
768            let key_tag = signer.calculate_key_tag().unwrap();
769
770            assert_eq!(key_tag, exp_result);
771        }
772    }
773
774    #[test]
775    #[allow(deprecated)]
776    fn test_calculate_key_tag_pem() {
777        let x = "-----BEGIN RSA PRIVATE KEY-----
778MC0CAQACBQC+L6pNAgMBAAECBQCYj0ZNAgMA9CsCAwDHZwICeEUCAnE/AgMA3u0=
779-----END RSA PRIVATE KEY-----
780";
781
782        let rsa = Rsa::private_key_from_pem(x.as_bytes()).unwrap();
783        let rsa_pem = rsa.private_key_to_pem().unwrap();
784        println!("pkey:\n{}", String::from_utf8(rsa_pem).unwrap());
785
786        let key = KeyPair::from_rsa(rsa).unwrap();
787        let sig0key = key
788            .to_sig0key_with_usage(Algorithm::RSASHA256, KeyUsage::Zone)
789            .unwrap();
790        let signer = SigSigner::sig0(sig0key, key, Name::root());
791        let key_tag = signer.calculate_key_tag().unwrap();
792
793        assert_eq!(key_tag, 28551);
794    }
795
796    // TODO: these tests technically came from TBS in hickory_proto
797    #[cfg(feature = "openssl")]
798    #[allow(clippy::module_inception)]
799    #[cfg(test)]
800    mod tests {
801        use openssl::rsa::Rsa;
802
803        use crate::rr::dnssec::rdata::RRSIG;
804        use crate::rr::dnssec::tbs::*;
805        use crate::rr::dnssec::*;
806        use crate::rr::rdata::{CNAME, NS};
807        use crate::rr::*;
808
809        #[test]
810        fn test_rrset_tbs() {
811            let rsa = Rsa::generate(2048).unwrap();
812            let key = KeyPair::from_rsa(rsa).unwrap();
813            let sig0key = key.to_sig0key(Algorithm::RSASHA256).unwrap();
814            let signer = SigSigner::sig0(sig0key, key, Name::root());
815
816            let origin: Name = Name::parse("example.com.", None).unwrap();
817            let rrsig = Record::new()
818                .set_name(origin.clone())
819                .set_ttl(86400)
820                .set_rr_type(RecordType::RRSIG)
821                .set_dns_class(DNSClass::IN)
822                .set_data(Some(RRSIG::new(
823                    RecordType::NS,
824                    Algorithm::RSASHA256,
825                    origin.num_labels(),
826                    86400,
827                    5,
828                    0,
829                    signer.calculate_key_tag().unwrap(),
830                    origin.clone(),
831                    vec![],
832                )))
833                .clone();
834            let rrset = vec![
835                Record::new()
836                    .set_name(origin.clone())
837                    .set_ttl(86400)
838                    .set_rr_type(RecordType::NS)
839                    .set_dns_class(DNSClass::IN)
840                    .set_data(Some(RData::NS(NS(Name::parse(
841                        "a.iana-servers.net.",
842                        None,
843                    )
844                    .unwrap()))))
845                    .clone(),
846                Record::new()
847                    .set_name(origin.clone())
848                    .set_ttl(86400)
849                    .set_rr_type(RecordType::NS)
850                    .set_dns_class(DNSClass::IN)
851                    .set_data(Some(RData::NS(NS(Name::parse(
852                        "b.iana-servers.net.",
853                        None,
854                    )
855                    .unwrap()))))
856                    .clone(),
857            ];
858
859            let tbs = rrset_tbs_with_rrsig(&rrsig, &rrset).unwrap();
860            assert!(!tbs.as_ref().is_empty());
861
862            let rrset = vec![
863                Record::new()
864                    .set_name(origin.clone())
865                    .set_ttl(86400)
866                    .set_rr_type(RecordType::CNAME)
867                    .set_dns_class(DNSClass::IN)
868                    .set_data(Some(RData::CNAME(CNAME(
869                        Name::parse("a.iana-servers.net.", None).unwrap(),
870                    ))))
871                    .clone(), // different type
872                Record::new()
873                    .set_name(Name::parse("www.example.com.", None).unwrap())
874                    .set_ttl(86400)
875                    .set_rr_type(RecordType::NS)
876                    .set_dns_class(DNSClass::IN)
877                    .set_data(Some(RData::NS(NS(Name::parse(
878                        "a.iana-servers.net.",
879                        None,
880                    )
881                    .unwrap()))))
882                    .clone(), // different name
883                Record::new()
884                    .set_name(origin.clone())
885                    .set_ttl(86400)
886                    .set_rr_type(RecordType::NS)
887                    .set_dns_class(DNSClass::CH)
888                    .set_data(Some(RData::NS(NS(Name::parse(
889                        "a.iana-servers.net.",
890                        None,
891                    )
892                    .unwrap()))))
893                    .clone(), // different class
894                Record::new()
895                    .set_name(origin.clone())
896                    .set_ttl(86400)
897                    .set_rr_type(RecordType::NS)
898                    .set_dns_class(DNSClass::IN)
899                    .set_data(Some(RData::NS(NS(Name::parse(
900                        "a.iana-servers.net.",
901                        None,
902                    )
903                    .unwrap()))))
904                    .clone(),
905                Record::new()
906                    .set_name(origin)
907                    .set_ttl(86400)
908                    .set_rr_type(RecordType::NS)
909                    .set_dns_class(DNSClass::IN)
910                    .set_data(Some(RData::NS(NS(Name::parse(
911                        "b.iana-servers.net.",
912                        None,
913                    )
914                    .unwrap()))))
915                    .clone(),
916            ];
917
918            let filtered_tbs = rrset_tbs_with_rrsig(&rrsig, &rrset).unwrap();
919            assert!(!filtered_tbs.as_ref().is_empty());
920            assert_eq!(tbs.as_ref(), filtered_tbs.as_ref());
921        }
922    }
923}