Expose `QueryBuf` constructors and utilities
[dnssec-prover] / src / query.rs
1 //! This module exposes utilities for building DNSSEC proofs by directly querying a recursive
2 //! resolver.
3
4 use core::{cmp, ops};
5 use alloc::vec;
6 use alloc::vec::Vec;
7
8 #[cfg(feature = "std")]
9 use std::net::{SocketAddr, TcpStream};
10 #[cfg(feature = "std")]
11 use std::io::{Read, Write, Error, ErrorKind};
12
13 #[cfg(feature = "tokio")]
14 use tokio_crate::net::TcpStream as TokioTcpStream;
15 #[cfg(feature = "tokio")]
16 use tokio_crate::io::{AsyncReadExt, AsyncWriteExt};
17
18 use crate::rr::*;
19 use crate::ser::*;
20
21 // In testing use a rather small buffer to ensure we hit the allocation paths sometimes. In
22 // production, we should generally never actually need to go to heap as DNS messages are rarely
23 // larger than a KiB or two.
24 #[cfg(any(test, fuzzing))]
25 const STACK_BUF_LIMIT: u16 = 32;
26 #[cfg(not(any(test, fuzzing)))]
27 const STACK_BUF_LIMIT: u16 = 2048;
28
29 /// A buffer for storing queries and responses.
30 #[derive(Clone, PartialEq, Eq)]
31 pub struct QueryBuf {
32         buf: [u8; STACK_BUF_LIMIT as usize],
33         heap_buf: Vec<u8>,
34         len: u16,
35 }
36 impl QueryBuf {
37         /// Generates a new buffer of the given length, consisting of all zeros.
38         pub fn new_zeroed(len: u16) -> Self {
39                 let heap_buf = if len > STACK_BUF_LIMIT { vec![0; len as usize] } else { Vec::new() };
40                 Self {
41                         buf: [0; STACK_BUF_LIMIT as usize],
42                         heap_buf,
43                         len
44                 }
45         }
46         /// Extends the size of this buffer by appending the given slice.
47         ///
48         /// If the total length of this buffer exceeds [`u16::MAX`] after appending, the buffer's state
49         /// is undefined, however pushing data beyond [`u16::MAX`] will not panic.
50         pub fn extend_from_slice(&mut self, sl: &[u8]) {
51                 let new_len = self.len.saturating_add(sl.len() as u16);
52                 let was_heap = self.len > STACK_BUF_LIMIT;
53                 let is_heap = new_len > STACK_BUF_LIMIT;
54                 if was_heap != is_heap {
55                         self.heap_buf = vec![0; new_len as usize];
56                         self.heap_buf[..self.len as usize].copy_from_slice(&self.buf[..self.len as usize]);
57                 }
58                 let target = if is_heap {
59                         self.heap_buf.resize(new_len as usize, 0);
60                         &mut self.heap_buf[self.len as usize..]
61                 } else {
62                         &mut self.buf[self.len as usize..new_len as usize]
63                 };
64                 target.copy_from_slice(sl);
65                 self.len = new_len;
66         }
67         /// Converts this query into its bytes on the heap
68         pub fn into_vec(self) -> Vec<u8> {
69                 if self.len > STACK_BUF_LIMIT {
70                         self.heap_buf
71                 } else {
72                         self.buf[..self.len as usize].to_vec()
73                 }
74         }
75 }
76 impl ops::Deref for QueryBuf {
77         type Target = [u8];
78         fn deref(&self) -> &[u8] {
79                 if self.len > STACK_BUF_LIMIT {
80                         &self.heap_buf
81                 } else {
82                         &self.buf[..self.len as usize]
83                 }
84         }
85 }
86 impl ops::DerefMut for QueryBuf {
87         fn deref_mut(&mut self) -> &mut [u8] {
88                 if self.len > STACK_BUF_LIMIT {
89                         &mut self.heap_buf
90                 } else {
91                         &mut self.buf[..self.len as usize]
92                 }
93         }
94 }
95
96 // We don't care about transaction IDs as we're only going to accept signed data. Thus, we use
97 // this constant instead of a random value.
98 const TXID: u16 = 0x4242;
99
100 fn build_query(domain: &Name, ty: u16) -> QueryBuf {
101         let mut query = QueryBuf::new_zeroed(0);
102         let query_msg_len: u16 = 2 + 2 + 8 + 2 + 2 + name_len(domain) + 11;
103         query.extend_from_slice(&query_msg_len.to_be_bytes());
104         query.extend_from_slice(&TXID.to_be_bytes());
105         query.extend_from_slice(&[0x01, 0x20]); // Flags: Recursive, Authenticated Data
106         query.extend_from_slice(&[0, 1, 0, 0, 0, 0, 0, 1]); // One question, One additional
107         write_name(&mut query, domain);
108         query.extend_from_slice(&ty.to_be_bytes());
109         query.extend_from_slice(&1u16.to_be_bytes()); // INternet class
110         query.extend_from_slice(&[0, 0, 0x29]); // . OPT
111         query.extend_from_slice(&0u16.to_be_bytes()); // 0 UDP payload size
112         query.extend_from_slice(&[0, 0]); // EDNS version 0
113         query.extend_from_slice(&0x8000u16.to_be_bytes()); // Accept DNSSEC RRs
114         query.extend_from_slice(&0u16.to_be_bytes()); // No additional data
115         query
116 }
117
118 #[cfg(fuzzing)]
119 /// Read some input and parse it as if it came from a server, for fuzzing.
120 pub fn fuzz_response(response: &[u8]) {
121         let (mut proof, mut names) = (Vec::new(), Vec::new());
122         let _ = handle_response(response, &mut proof, &mut names);
123 }
124
125 fn handle_response(resp: &[u8], proof: &mut Vec<u8>, rrsig_key_names: &mut Vec<Name>) -> Result<u32, ()> {
126         let mut read: &[u8] = resp;
127         if read_u16(&mut read)? != TXID { return Err(()); }
128         // 2 byte transaction ID
129         let flags = read_u16(&mut read)?;
130         if flags & 0b1000_0000_0000_0000 == 0 {
131                 return Err(());
132         }
133         if flags & 0b0111_1010_0000_0111 != 0 {
134                 return Err(());
135         }
136         if flags & 0b10_0000 == 0 {
137                 return Err(());
138         }
139         let questions = read_u16(&mut read)?;
140         if questions != 1 { return Err(()); }
141         let answers = read_u16(&mut read)?;
142         if answers == 0 { return Err(()); }
143         let _authorities = read_u16(&mut read)?;
144         let _additional = read_u16(&mut read)?;
145
146         for _ in 0..questions {
147                 read_wire_packet_name(&mut read, resp)?;
148                 read_u16(&mut read)?; // type
149                 read_u16(&mut read)?; // class
150         }
151
152         // Only read the answers (skip authorities and additional) as that's all we care about.
153         let mut min_ttl = u32::MAX;
154         for _ in 0..answers {
155                 let (rr, ttl) = parse_wire_packet_rr(&mut read, &resp)?;
156                 write_rr(&rr, ttl, proof);
157                 min_ttl = cmp::min(min_ttl, ttl);
158                 if let RR::RRSig(rrsig) = rr { rrsig_key_names.push(rrsig.key_name); }
159         }
160         Ok(min_ttl)
161 }
162
163 #[cfg(fuzzing)]
164 /// Read a stream of responses and handle them it as if they came from a server, for fuzzing.
165 pub fn fuzz_proof_builder(mut response_stream: &[u8]) {
166         let (mut builder, _) = ProofBuilder::new(&"example.com.".try_into().unwrap(), Txt::TYPE);
167         while builder.awaiting_responses() {
168                 let len = if let Ok(len) = read_u16(&mut response_stream) { len } else { return };
169                 let mut buf = QueryBuf::new_zeroed(len);
170                 if response_stream.len() < len as usize { return; }
171                 buf.copy_from_slice(&response_stream[..len as usize]);
172                 response_stream = &response_stream[len as usize..];
173                 let _ = builder.process_response(&buf);
174         }
175         let _ = builder.finish_proof();
176 }
177
178 const MAX_REQUESTS: usize = 10;
179 /// A simple state machine which will generate a series of queries and process the responses until
180 /// it has built a DNSSEC proof.
181 ///
182 /// A [`ProofBuilder`] driver starts with [`ProofBuilder::new`], fetching the state machine and
183 /// initial query. As long as [`ProofBuilder::awaiting_responses`] returns true, responses should
184 /// be read from the resolver. For each query response read from the DNS resolver,
185 /// [`ProofBuilder::process_response`] should be called, and each fresh query returned should be
186 /// sent to the resolver. Once [`ProofBuilder::awaiting_responses`] returns false,
187 /// [`ProofBuilder::finish_proof`] should be called to fetch the resulting proof.
188 pub struct ProofBuilder {
189         proof: Vec<u8>,
190         min_ttl: u32,
191         dnskeys_requested: Vec<Name>,
192         pending_queries: usize,
193         queries_made: usize,
194 }
195
196 impl ProofBuilder {
197         /// Constructs a new [`ProofBuilder`] and an initial query to send to the recursive resolver to
198         /// begin the proof building process.
199         ///
200         /// Given a correctly-functioning resolver the proof will ultimately be able to prove the
201         /// contents of any records with the given `ty`pe at the given `name` (as long as the given
202         /// `ty`pe is supported by this library).
203         ///
204         /// You can find constants for supported standard types in the [`crate::rr`] module.
205         pub fn new(name: &Name, ty: u16) -> (ProofBuilder, QueryBuf) {
206                 let initial_query = build_query(name, ty);
207                 (ProofBuilder {
208                         proof: Vec::new(),
209                         min_ttl: u32::MAX,
210                         dnskeys_requested: Vec::with_capacity(MAX_REQUESTS),
211                         pending_queries: 1,
212                         queries_made: 1,
213                 }, initial_query)
214         }
215
216         /// Returns true as long as further responses are expected from the resolver.
217         ///
218         /// As long as this returns true, responses should be read from the resolver and passed to
219         /// [`Self::process_response`]. Once this returns false, [`Self::finish_proof`] should be used
220         /// to (possibly) get the final proof.
221         pub fn awaiting_responses(&self) -> bool {
222                 self.pending_queries > 0 && self.queries_made <= MAX_REQUESTS
223         }
224
225         /// Processes a query response from the recursive resolver, returning a list of new queries to
226         /// send to the resolver.
227         pub fn process_response(&mut self, resp: &QueryBuf) -> Result<Vec<QueryBuf>, ()> {
228                 if self.pending_queries == 0 { return Err(()); }
229
230                 let mut rrsig_key_names = Vec::new();
231                 let min_ttl = handle_response(&resp, &mut self.proof, &mut rrsig_key_names)?;
232                 self.min_ttl = cmp::min(self.min_ttl, min_ttl);
233                 self.pending_queries -= 1;
234
235                 rrsig_key_names.sort_unstable();
236                 rrsig_key_names.dedup();
237
238                 let mut new_queries = Vec::with_capacity(2);
239                 for key_name in rrsig_key_names.drain(..) {
240                         if !self.dnskeys_requested.contains(&key_name) {
241                                 new_queries.push(build_query(&key_name, DnsKey::TYPE));
242                                 self.pending_queries += 1;
243                                 self.queries_made += 1;
244                                 self.dnskeys_requested.push(key_name.clone());
245
246                                 if key_name.as_str() != "." {
247                                         new_queries.push(build_query(&key_name, DS::TYPE));
248                                         self.pending_queries += 1;
249                                         self.queries_made += 1;
250                                 }
251                         }
252                 }
253                 if self.queries_made <= MAX_REQUESTS {
254                         Ok(new_queries)
255                 } else {
256                         Ok(Vec::new())
257                 }
258         }
259
260         /// Finalizes the proof, if one is available, and returns it as well as the TTL that should be
261         /// used to cache the proof (i.e. the lowest TTL of all records which were used to build the
262         /// proof).
263         pub fn finish_proof(self) -> Result<(Vec<u8>, u32), ()> {
264                 if self.pending_queries > 0 || self.queries_made > MAX_REQUESTS {
265                         Err(())
266                 } else {
267                         Ok((self.proof, self.min_ttl))
268                 }
269         }
270 }
271
272 #[cfg(feature = "std")]
273 fn send_query(stream: &mut TcpStream, query: &[u8]) -> Result<(), Error> {
274         stream.write_all(&query)?;
275         Ok(())
276 }
277
278 #[cfg(feature = "tokio")]
279 async fn send_query_async(stream: &mut TokioTcpStream, query: &[u8]) -> Result<(), Error> {
280         stream.write_all(&query).await?;
281         Ok(())
282 }
283
284 #[cfg(feature = "std")]
285 fn read_response(stream: &mut TcpStream) -> Result<QueryBuf, Error> {
286         let mut len_bytes = [0; 2];
287         stream.read_exact(&mut len_bytes)?;
288         let mut buf = QueryBuf::new_zeroed(u16::from_be_bytes(len_bytes));
289         stream.read_exact(&mut buf)?;
290         Ok(buf)
291 }
292
293 #[cfg(feature = "tokio")]
294 async fn read_response_async(stream: &mut TokioTcpStream) -> Result<QueryBuf, Error> {
295         let mut len_bytes = [0; 2];
296         stream.read_exact(&mut len_bytes).await?;
297         let mut buf = QueryBuf::new_zeroed(u16::from_be_bytes(len_bytes));
298         stream.read_exact(&mut buf).await?;
299         Ok(buf)
300 }
301
302 #[cfg(feature = "std")]
303 macro_rules! build_proof_impl {
304         ($stream: ident, $send_query: ident, $read_response: ident, $domain: expr, $ty: expr $(, $async_ok: tt)?) => { {
305                 // We require the initial query to have already gone out, and assume our resolver will
306                 // return any CNAMEs all the way to the final record in the response. From there, we just
307                 // have to take any RRSIGs in the response and walk them up to the root. We do so
308                 // iteratively, sending DNSKEY and DS lookups after every response, deduplicating requests
309                 // using `dnskeys_requested`.
310                 let (mut builder, initial_query) = ProofBuilder::new($domain, $ty);
311                 $send_query(&mut $stream, &initial_query)
312                         $(.await?; $async_ok)??; // Either await?; Ok(())?, or just ?
313                 while builder.awaiting_responses() {
314                         let response = $read_response(&mut $stream)
315                                 $(.await?; $async_ok)??; // Either await?; Ok(())?, or just ?
316                         let new_queries = builder.process_response(&response)
317                                 .map_err(|()| Error::new(ErrorKind::Other, "Bad response"))?;
318                         for query in new_queries {
319                                 $send_query(&mut $stream, &query)
320                                         $(.await?; $async_ok)??; // Either await?; Ok(())?, or just ?
321                         }
322                 }
323
324                 builder.finish_proof()
325                         .map_err(|()| Error::new(ErrorKind::Other, "Too many requests required"))
326         } }
327 }
328
329 #[cfg(feature = "std")]
330 fn build_proof(resolver: SocketAddr, domain: &Name, ty: u16) -> Result<(Vec<u8>, u32), Error> {
331         let mut stream = TcpStream::connect(resolver)?;
332         build_proof_impl!(stream, send_query, read_response, domain, ty)
333 }
334
335 #[cfg(feature = "tokio")]
336 async fn build_proof_async(resolver: SocketAddr, domain: &Name, ty: u16) -> Result<(Vec<u8>, u32), Error> {
337         let mut stream = TokioTcpStream::connect(resolver).await?;
338         build_proof_impl!(stream, send_query_async, read_response_async, domain, ty, { Ok::<(), Error>(()) })
339 }
340
341 /// Builds a DNSSEC proof for an A record by querying a recursive resolver, returning the proof as
342 /// well as the TTL for the proof provided by the recursive resolver.
343 ///
344 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
345 /// module to validate the records contained.
346 #[cfg(feature = "std")]
347 pub fn build_a_proof(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
348         build_proof(resolver, domain, A::TYPE)
349 }
350
351 /// Builds a DNSSEC proof for an AAAA record by querying a recursive resolver, returning the proof
352 /// as well as the TTL for the proof provided by the recursive resolver.
353 ///
354 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
355 /// module to validate the records contained.
356 #[cfg(feature = "std")]
357 pub fn build_aaaa_proof(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
358         build_proof(resolver, domain, AAAA::TYPE)
359 }
360
361 /// Builds a DNSSEC proof for an TXT record by querying a recursive resolver, returning the proof
362 /// as well as the TTL for the proof provided by the recursive resolver.
363 ///
364 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
365 /// module to validate the records contained.
366 #[cfg(feature = "std")]
367 pub fn build_txt_proof(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
368         build_proof(resolver, domain, Txt::TYPE)
369 }
370
371 /// Builds a DNSSEC proof for an TLSA record by querying a recursive resolver, returning the proof
372 /// as well as the TTL for the proof provided by the recursive resolver.
373 ///
374 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
375 /// module to validate the records contained.
376 #[cfg(feature = "std")]
377 pub fn build_tlsa_proof(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
378         build_proof(resolver, domain, TLSA::TYPE)
379 }
380
381
382 /// Builds a DNSSEC proof for an A record by querying a recursive resolver, returning the proof as
383 /// well as the TTL for the proof provided by the recursive resolver.
384 ///
385 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
386 /// module to validate the records contained.
387 #[cfg(feature = "tokio")]
388 pub async fn build_a_proof_async(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
389         build_proof_async(resolver, domain, A::TYPE).await
390 }
391
392 /// Builds a DNSSEC proof for an AAAA record by querying a recursive resolver, returning the proof
393 /// as well as the TTL for the proof provided by the recursive resolver.
394 ///
395 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
396 /// module to validate the records contained.
397 #[cfg(feature = "tokio")]
398 pub async fn build_aaaa_proof_async(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
399         build_proof_async(resolver, domain, AAAA::TYPE).await
400 }
401
402 /// Builds a DNSSEC proof for an TXT record by querying a recursive resolver, returning the proof
403 /// as well as the TTL for the proof provided by the recursive resolver.
404 ///
405 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
406 /// module to validate the records contained.
407 #[cfg(feature = "tokio")]
408 pub async fn build_txt_proof_async(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
409         build_proof_async(resolver, domain, Txt::TYPE).await
410 }
411
412 /// Builds a DNSSEC proof for an TLSA record by querying a recursive resolver, returning the proof
413 /// as well as the TTL for the proof provided by the recursive resolver.
414 ///
415 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
416 /// module to validate the records contained.
417 #[cfg(feature = "tokio")]
418 pub async fn build_tlsa_proof_async(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
419         build_proof_async(resolver, domain, TLSA::TYPE).await
420 }
421
422 #[cfg(all(feature = "validation", feature = "std", test))]
423 mod tests {
424         use super::*;
425         use crate::validation::*;
426
427         use rand::seq::SliceRandom;
428
429         use std::net::ToSocketAddrs;
430         use std::time::SystemTime;
431
432         #[test]
433         fn test_cloudflare_txt_query() {
434                 let sockaddr = "8.8.8.8:53".to_socket_addrs().unwrap().next().unwrap();
435                 let query_name = "cloudflare.com.".try_into().unwrap();
436                 let (proof, _) = build_txt_proof(sockaddr, &query_name).unwrap();
437
438                 let mut rrs = parse_rr_stream(&proof).unwrap();
439                 rrs.shuffle(&mut rand::rngs::OsRng);
440                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
441                 assert!(verified_rrs.verified_rrs.len() > 1);
442
443                 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
444                 assert!(verified_rrs.valid_from < now);
445                 assert!(verified_rrs.expires > now);
446         }
447
448         #[test]
449         fn test_sha1_query() {
450                 let sockaddr = "8.8.8.8:53".to_socket_addrs().unwrap().next().unwrap();
451                 let query_name = "benthecarman.com.".try_into().unwrap();
452                 let (proof, _) = build_a_proof(sockaddr, &query_name).unwrap();
453
454                 let mut rrs = parse_rr_stream(&proof).unwrap();
455                 rrs.shuffle(&mut rand::rngs::OsRng);
456                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
457                 assert!(verified_rrs.verified_rrs.len() >= 1);
458
459                 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
460                 assert!(verified_rrs.valid_from < now);
461                 assert!(verified_rrs.expires > now);
462         }
463
464         #[test]
465         fn test_txt_query() {
466                 let sockaddr = "8.8.8.8:53".to_socket_addrs().unwrap().next().unwrap();
467                 let query_name = "matt.user._bitcoin-payment.mattcorallo.com.".try_into().unwrap();
468                 let (proof, _) = build_txt_proof(sockaddr, &query_name).unwrap();
469
470                 let mut rrs = parse_rr_stream(&proof).unwrap();
471                 rrs.shuffle(&mut rand::rngs::OsRng);
472                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
473                 assert_eq!(verified_rrs.verified_rrs.len(), 1);
474
475                 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
476                 assert!(verified_rrs.valid_from < now);
477                 assert!(verified_rrs.expires > now);
478         }
479
480         #[test]
481         fn test_cname_query() {
482                 for resolver in ["1.1.1.1:53", "8.8.8.8:53", "9.9.9.9:53"] {
483                         let sockaddr = resolver.to_socket_addrs().unwrap().next().unwrap();
484                         let query_name = "cname_test.matcorallo.com.".try_into().unwrap();
485                         let (proof, _) = build_txt_proof(sockaddr, &query_name).unwrap();
486
487                         let mut rrs = parse_rr_stream(&proof).unwrap();
488                         rrs.shuffle(&mut rand::rngs::OsRng);
489                         let verified_rrs = verify_rr_stream(&rrs).unwrap();
490                         assert_eq!(verified_rrs.verified_rrs.len(), 2);
491
492                         let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
493                         assert!(verified_rrs.valid_from < now);
494                         assert!(verified_rrs.expires > now);
495
496                         let resolved_rrs = verified_rrs.resolve_name(&query_name);
497                         assert_eq!(resolved_rrs.len(), 1);
498                         if let RR::Txt(txt) = &resolved_rrs[0] {
499                                 assert_eq!(txt.name.as_str(), "txt_test.matcorallo.com.");
500                                 assert_eq!(txt.data, b"dnssec_prover_test");
501                         } else { panic!(); }
502                 }
503         }
504
505         #[cfg(feature = "tokio")]
506         use tokio_crate as tokio;
507
508         #[cfg(feature = "tokio")]
509         #[tokio::test]
510         async fn test_txt_query_async() {
511                 let sockaddr = "8.8.8.8:53".to_socket_addrs().unwrap().next().unwrap();
512                 let query_name = "matt.user._bitcoin-payment.mattcorallo.com.".try_into().unwrap();
513                 let (proof, _) = build_txt_proof_async(sockaddr, &query_name).await.unwrap();
514
515                 let mut rrs = parse_rr_stream(&proof).unwrap();
516                 rrs.shuffle(&mut rand::rngs::OsRng);
517                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
518                 assert_eq!(verified_rrs.verified_rrs.len(), 1);
519
520                 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
521                 assert!(verified_rrs.valid_from < now);
522                 assert!(verified_rrs.expires > now);
523         }
524
525         #[cfg(feature = "tokio")]
526         #[tokio::test]
527         async fn test_cross_domain_cname_query_async() {
528                 for resolver in ["1.1.1.1:53", "8.8.8.8:53", "9.9.9.9:53"] {
529                         let sockaddr = resolver.to_socket_addrs().unwrap().next().unwrap();
530                         let query_name = "wildcard.x_domain_cname_wild.matcorallo.com.".try_into().unwrap();
531                         let (proof, _) = build_txt_proof_async(sockaddr, &query_name).await.unwrap();
532
533                         let mut rrs = parse_rr_stream(&proof).unwrap();
534                         rrs.shuffle(&mut rand::rngs::OsRng);
535                         let verified_rrs = verify_rr_stream(&rrs).unwrap();
536                         assert_eq!(verified_rrs.verified_rrs.len(), 2);
537
538                         let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
539                         assert!(verified_rrs.valid_from < now);
540                         assert!(verified_rrs.expires > now);
541
542                         let resolved_rrs = verified_rrs.resolve_name(&query_name);
543                         assert_eq!(resolved_rrs.len(), 1);
544                         if let RR::Txt(txt) = &resolved_rrs[0] {
545                                 assert_eq!(txt.name.as_str(), "matt.user._bitcoin-payment.mattcorallo.com.");
546                                 assert!(txt.data.starts_with(b"bitcoin:"));
547                         } else { panic!(); }
548                 }
549         }
550 }