]> git.bitcoin.ninja Git - dnssec-prover/blob - src/query.rs
Add support for DNAME resolution
[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.
97 // Further, if we're querying over DoH, the RFC says we SHOULD use a transaction ID of 0 here.
98 const TXID: u16 = 0;
99
100 fn build_query(domain: &Name, ty: u16) -> QueryBuf {
101         let mut query = QueryBuf::new_zeroed(0);
102         query.extend_from_slice(&TXID.to_be_bytes());
103         query.extend_from_slice(&[0x01, 0x20]); // Flags: Recursive, Authenticated Data
104         query.extend_from_slice(&[0, 1, 0, 0, 0, 0, 0, 1]); // One question, One additional
105         write_name(&mut query, domain);
106         query.extend_from_slice(&ty.to_be_bytes());
107         query.extend_from_slice(&1u16.to_be_bytes()); // INternet class
108         query.extend_from_slice(&[0, 0, 0x29]); // . OPT
109         query.extend_from_slice(&0u16.to_be_bytes()); // 0 UDP payload size
110         query.extend_from_slice(&[0, 0]); // EDNS version 0
111         query.extend_from_slice(&0x8000u16.to_be_bytes()); // Accept DNSSEC RRs
112         query.extend_from_slice(&0u16.to_be_bytes()); // No additional data
113         query
114 }
115
116 #[cfg(fuzzing)]
117 /// Read some input and parse it as if it came from a server, for fuzzing.
118 pub fn fuzz_response(response: &[u8]) {
119         let (mut proof, mut names) = (Vec::new(), Vec::new());
120         let _ = handle_response(response, &mut proof, &mut names);
121 }
122
123 fn handle_response(resp: &[u8], proof: &mut Vec<u8>, rrsig_key_names: &mut Vec<Name>) -> Result<u32, ()> {
124         let mut read: &[u8] = resp;
125         if read_u16(&mut read)? != TXID { return Err(()); }
126         // 2 byte transaction ID
127         let flags = read_u16(&mut read)?;
128         if flags & 0b1000_0000_0000_0000 == 0 {
129                 return Err(());
130         }
131         if flags & 0b0111_1010_0000_0111 != 0 {
132                 return Err(());
133         }
134         if flags & 0b10_0000 == 0 {
135                 return Err(());
136         }
137         let questions = read_u16(&mut read)?;
138         if questions != 1 { return Err(()); }
139         let answers = read_u16(&mut read)?;
140         if answers == 0 { return Err(()); }
141         let _authorities = read_u16(&mut read)?;
142         let _additional = read_u16(&mut read)?;
143
144         for _ in 0..questions {
145                 read_wire_packet_name(&mut read, resp)?;
146                 read_u16(&mut read)?; // type
147                 read_u16(&mut read)?; // class
148         }
149
150         // Only read the answers (skip authorities and additional) as that's all we care about.
151         let mut min_ttl = u32::MAX;
152         for _ in 0..answers {
153                 let (rr, ttl) = parse_wire_packet_rr(&mut read, &resp)?;
154                 write_rr(&rr, ttl, proof);
155                 min_ttl = cmp::min(min_ttl, ttl);
156                 if let RR::RRSig(rrsig) = rr { rrsig_key_names.push(rrsig.key_name); }
157         }
158         Ok(min_ttl)
159 }
160
161 #[cfg(fuzzing)]
162 /// Read a stream of responses and handle them it as if they came from a server, for fuzzing.
163 pub fn fuzz_proof_builder(mut response_stream: &[u8]) {
164         let (mut builder, _) = ProofBuilder::new(&"example.com.".try_into().unwrap(), Txt::TYPE);
165         while builder.awaiting_responses() {
166                 let len = if let Ok(len) = read_u16(&mut response_stream) { len } else { return };
167                 let mut buf = QueryBuf::new_zeroed(len);
168                 if response_stream.len() < len as usize { return; }
169                 buf.copy_from_slice(&response_stream[..len as usize]);
170                 response_stream = &response_stream[len as usize..];
171                 let _ = builder.process_response(&buf);
172         }
173         let _ = builder.finish_proof();
174 }
175
176 const MAX_REQUESTS: usize = 10;
177 /// A simple state machine which will generate a series of queries and process the responses until
178 /// it has built a DNSSEC proof.
179 ///
180 /// A [`ProofBuilder`] driver starts with [`ProofBuilder::new`], fetching the state machine and
181 /// initial query. As long as [`ProofBuilder::awaiting_responses`] returns true, responses should
182 /// be read from the resolver. For each query response read from the DNS resolver,
183 /// [`ProofBuilder::process_response`] should be called, and each fresh query returned should be
184 /// sent to the resolver. Once [`ProofBuilder::awaiting_responses`] returns false,
185 /// [`ProofBuilder::finish_proof`] should be called to fetch the resulting proof.
186 ///
187 /// To build a DNSSEC proof using a DoH server, take each [`QueryBuf`], encode it as base64url, and
188 /// make a query to `https://doh-server/endpoint?dns=base64url_encoded_query` with an `Accept`
189 /// header of `application/dns-message`. Each response, in raw binary, can be fed directly into
190 /// [`ProofBuilder::process_response`].
191 pub struct ProofBuilder {
192         proof: Vec<u8>,
193         min_ttl: u32,
194         dnskeys_requested: Vec<Name>,
195         pending_queries: usize,
196         queries_made: usize,
197 }
198
199 impl ProofBuilder {
200         /// Constructs a new [`ProofBuilder`] and an initial query to send to the recursive resolver to
201         /// begin the proof building process.
202         ///
203         /// Given a correctly-functioning resolver the proof will ultimately be able to prove the
204         /// contents of any records with the given `ty`pe at the given `name` (as long as the given
205         /// `ty`pe is supported by this library).
206         ///
207         /// You can find constants for supported standard types in the [`crate::rr`] module.
208         pub fn new(name: &Name, ty: u16) -> (ProofBuilder, QueryBuf) {
209                 let initial_query = build_query(name, ty);
210                 (ProofBuilder {
211                         proof: Vec::new(),
212                         min_ttl: u32::MAX,
213                         dnskeys_requested: Vec::with_capacity(MAX_REQUESTS),
214                         pending_queries: 1,
215                         queries_made: 1,
216                 }, initial_query)
217         }
218
219         /// Returns true as long as further responses are expected from the resolver.
220         ///
221         /// As long as this returns true, responses should be read from the resolver and passed to
222         /// [`Self::process_response`]. Once this returns false, [`Self::finish_proof`] should be used
223         /// to (possibly) get the final proof.
224         pub fn awaiting_responses(&self) -> bool {
225                 self.pending_queries > 0 && self.queries_made <= MAX_REQUESTS
226         }
227
228         /// Processes a query response from the recursive resolver, returning a list of new queries to
229         /// send to the resolver.
230         pub fn process_response(&mut self, resp: &QueryBuf) -> Result<Vec<QueryBuf>, ()> {
231                 if self.pending_queries == 0 { return Err(()); }
232
233                 let mut rrsig_key_names = Vec::new();
234                 let min_ttl = handle_response(&resp, &mut self.proof, &mut rrsig_key_names)?;
235                 self.min_ttl = cmp::min(self.min_ttl, min_ttl);
236                 self.pending_queries -= 1;
237
238                 rrsig_key_names.sort_unstable();
239                 rrsig_key_names.dedup();
240
241                 let mut new_queries = Vec::with_capacity(2);
242                 for key_name in rrsig_key_names.drain(..) {
243                         if !self.dnskeys_requested.contains(&key_name) {
244                                 new_queries.push(build_query(&key_name, DnsKey::TYPE));
245                                 self.pending_queries += 1;
246                                 self.queries_made += 1;
247                                 self.dnskeys_requested.push(key_name.clone());
248
249                                 if key_name.as_str() != "." {
250                                         new_queries.push(build_query(&key_name, DS::TYPE));
251                                         self.pending_queries += 1;
252                                         self.queries_made += 1;
253                                 }
254                         }
255                 }
256                 if self.queries_made <= MAX_REQUESTS {
257                         Ok(new_queries)
258                 } else {
259                         Ok(Vec::new())
260                 }
261         }
262
263         /// Finalizes the proof, if one is available, and returns it as well as the TTL that should be
264         /// used to cache the proof (i.e. the lowest TTL of all records which were used to build the
265         /// proof).
266         pub fn finish_proof(self) -> Result<(Vec<u8>, u32), ()> {
267                 if self.pending_queries > 0 || self.queries_made > MAX_REQUESTS {
268                         Err(())
269                 } else {
270                         Ok((self.proof, self.min_ttl))
271                 }
272         }
273 }
274
275 #[cfg(feature = "std")]
276 fn send_query(stream: &mut TcpStream, query: &[u8]) -> Result<(), Error> {
277         stream.write_all(&(query.len() as u16).to_be_bytes())?;
278         stream.write_all(&query)?;
279         Ok(())
280 }
281
282 #[cfg(feature = "tokio")]
283 async fn send_query_async(stream: &mut TokioTcpStream, query: &[u8]) -> Result<(), Error> {
284         stream.write_all(&(query.len() as u16).to_be_bytes()).await?;
285         stream.write_all(&query).await?;
286         Ok(())
287 }
288
289 #[cfg(feature = "std")]
290 fn read_response(stream: &mut TcpStream) -> Result<QueryBuf, Error> {
291         let mut len_bytes = [0; 2];
292         stream.read_exact(&mut len_bytes)?;
293         let mut buf = QueryBuf::new_zeroed(u16::from_be_bytes(len_bytes));
294         stream.read_exact(&mut buf)?;
295         Ok(buf)
296 }
297
298 #[cfg(feature = "tokio")]
299 async fn read_response_async(stream: &mut TokioTcpStream) -> Result<QueryBuf, Error> {
300         let mut len_bytes = [0; 2];
301         stream.read_exact(&mut len_bytes).await?;
302         let mut buf = QueryBuf::new_zeroed(u16::from_be_bytes(len_bytes));
303         stream.read_exact(&mut buf).await?;
304         Ok(buf)
305 }
306
307 #[cfg(feature = "std")]
308 macro_rules! build_proof_impl {
309         ($stream: ident, $send_query: ident, $read_response: ident, $domain: expr, $ty: expr $(, $async_ok: tt)?) => { {
310                 // We require the initial query to have already gone out, and assume our resolver will
311                 // return any CNAMEs all the way to the final record in the response. From there, we just
312                 // have to take any RRSIGs in the response and walk them up to the root. We do so
313                 // iteratively, sending DNSKEY and DS lookups after every response, deduplicating requests
314                 // using `dnskeys_requested`.
315                 let (mut builder, initial_query) = ProofBuilder::new($domain, $ty);
316                 $send_query(&mut $stream, &initial_query)
317                         $(.await?; $async_ok)??; // Either await?; Ok(())?, or just ?
318                 while builder.awaiting_responses() {
319                         let response = $read_response(&mut $stream)
320                                 $(.await?; $async_ok)??; // Either await?; Ok(())?, or just ?
321                         let new_queries = builder.process_response(&response)
322                                 .map_err(|()| Error::new(ErrorKind::Other, "Bad response"))?;
323                         for query in new_queries {
324                                 $send_query(&mut $stream, &query)
325                                         $(.await?; $async_ok)??; // Either await?; Ok(())?, or just ?
326                         }
327                 }
328
329                 builder.finish_proof()
330                         .map_err(|()| Error::new(ErrorKind::Other, "Too many requests required"))
331         } }
332 }
333
334 #[cfg(feature = "std")]
335 fn build_proof(resolver: SocketAddr, domain: &Name, ty: u16) -> Result<(Vec<u8>, u32), Error> {
336         let mut stream = TcpStream::connect(resolver)?;
337         build_proof_impl!(stream, send_query, read_response, domain, ty)
338 }
339
340 #[cfg(feature = "tokio")]
341 async fn build_proof_async(resolver: SocketAddr, domain: &Name, ty: u16) -> Result<(Vec<u8>, u32), Error> {
342         let mut stream = TokioTcpStream::connect(resolver).await?;
343         build_proof_impl!(stream, send_query_async, read_response_async, domain, ty, { Ok::<(), Error>(()) })
344 }
345
346 /// Builds a DNSSEC proof for an A record by querying a recursive resolver, returning the proof as
347 /// well as the TTL for the proof provided by the recursive resolver.
348 ///
349 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
350 /// module to validate the records contained.
351 #[cfg(feature = "std")]
352 pub fn build_a_proof(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
353         build_proof(resolver, domain, A::TYPE)
354 }
355
356 /// Builds a DNSSEC proof for an AAAA record by querying a recursive resolver, returning the proof
357 /// as well as the TTL for the proof provided by the recursive resolver.
358 ///
359 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
360 /// module to validate the records contained.
361 #[cfg(feature = "std")]
362 pub fn build_aaaa_proof(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
363         build_proof(resolver, domain, AAAA::TYPE)
364 }
365
366 /// Builds a DNSSEC proof for an TXT record by querying a recursive resolver, returning the proof
367 /// as well as the TTL for the proof provided by the recursive resolver.
368 ///
369 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
370 /// module to validate the records contained.
371 #[cfg(feature = "std")]
372 pub fn build_txt_proof(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
373         build_proof(resolver, domain, Txt::TYPE)
374 }
375
376 /// Builds a DNSSEC proof for an TLSA record by querying a recursive resolver, returning the proof
377 /// as well as the TTL for the proof provided by the recursive resolver.
378 ///
379 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
380 /// module to validate the records contained.
381 #[cfg(feature = "std")]
382 pub fn build_tlsa_proof(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
383         build_proof(resolver, domain, TLSA::TYPE)
384 }
385
386
387 /// Builds a DNSSEC proof for an A record by querying a recursive resolver, returning the proof as
388 /// well as the TTL for the proof provided by the recursive resolver.
389 ///
390 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
391 /// module to validate the records contained.
392 #[cfg(feature = "tokio")]
393 pub async fn build_a_proof_async(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
394         build_proof_async(resolver, domain, A::TYPE).await
395 }
396
397 /// Builds a DNSSEC proof for an AAAA record by querying a recursive resolver, returning the proof
398 /// as well as the TTL for the proof provided by the recursive resolver.
399 ///
400 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
401 /// module to validate the records contained.
402 #[cfg(feature = "tokio")]
403 pub async fn build_aaaa_proof_async(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
404         build_proof_async(resolver, domain, AAAA::TYPE).await
405 }
406
407 /// Builds a DNSSEC proof for an TXT record by querying a recursive resolver, returning the proof
408 /// as well as the TTL for the proof provided by the recursive resolver.
409 ///
410 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
411 /// module to validate the records contained.
412 #[cfg(feature = "tokio")]
413 pub async fn build_txt_proof_async(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
414         build_proof_async(resolver, domain, Txt::TYPE).await
415 }
416
417 /// Builds a DNSSEC proof for an TLSA record by querying a recursive resolver, returning the proof
418 /// as well as the TTL for the proof provided by the recursive resolver.
419 ///
420 /// Note that this proof is NOT verified in any way, you need to use the [`crate::validation`]
421 /// module to validate the records contained.
422 #[cfg(feature = "tokio")]
423 pub async fn build_tlsa_proof_async(resolver: SocketAddr, domain: &Name) -> Result<(Vec<u8>, u32), Error> {
424         build_proof_async(resolver, domain, TLSA::TYPE).await
425 }
426
427 #[cfg(all(feature = "validation", feature = "std", test))]
428 mod tests {
429         use super::*;
430         use crate::validation::*;
431
432         use rand::seq::SliceRandom;
433
434         use std::net::ToSocketAddrs;
435         use std::time::SystemTime;
436
437         #[test]
438         fn test_cloudflare_txt_query() {
439                 let sockaddr = "8.8.8.8:53".to_socket_addrs().unwrap().next().unwrap();
440                 let query_name = "cloudflare.com.".try_into().unwrap();
441                 let (proof, _) = build_txt_proof(sockaddr, &query_name).unwrap();
442
443                 let mut rrs = parse_rr_stream(&proof).unwrap();
444                 rrs.shuffle(&mut rand::rngs::OsRng);
445                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
446                 assert!(verified_rrs.verified_rrs.len() > 1);
447
448                 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
449                 assert!(verified_rrs.valid_from < now);
450                 assert!(verified_rrs.expires > now);
451         }
452
453         #[test]
454         fn test_sha1_query() {
455                 let sockaddr = "8.8.8.8:53".to_socket_addrs().unwrap().next().unwrap();
456                 let query_name = "benthecarman.com.".try_into().unwrap();
457                 let (proof, _) = build_a_proof(sockaddr, &query_name).unwrap();
458
459                 let mut rrs = parse_rr_stream(&proof).unwrap();
460                 rrs.shuffle(&mut rand::rngs::OsRng);
461                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
462                 assert!(verified_rrs.verified_rrs.len() >= 1);
463
464                 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
465                 assert!(verified_rrs.valid_from < now);
466                 assert!(verified_rrs.expires > now);
467         }
468
469         #[test]
470         fn test_txt_query() {
471                 let sockaddr = "8.8.8.8:53".to_socket_addrs().unwrap().next().unwrap();
472                 let query_name = "matt.user._bitcoin-payment.mattcorallo.com.".try_into().unwrap();
473                 let (proof, _) = build_txt_proof(sockaddr, &query_name).unwrap();
474
475                 let mut rrs = parse_rr_stream(&proof).unwrap();
476                 rrs.shuffle(&mut rand::rngs::OsRng);
477                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
478                 assert_eq!(verified_rrs.verified_rrs.len(), 1);
479
480                 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
481                 assert!(verified_rrs.valid_from < now);
482                 assert!(verified_rrs.expires > now);
483         }
484
485         #[test]
486         fn test_cname_query() {
487                 for resolver in ["1.1.1.1:53", "8.8.8.8:53", "9.9.9.9:53"] {
488                         let sockaddr = resolver.to_socket_addrs().unwrap().next().unwrap();
489                         let query_name = "cname_test.matcorallo.com.".try_into().unwrap();
490                         let (proof, _) = build_txt_proof(sockaddr, &query_name).unwrap();
491
492                         let mut rrs = parse_rr_stream(&proof).unwrap();
493                         rrs.shuffle(&mut rand::rngs::OsRng);
494                         let verified_rrs = verify_rr_stream(&rrs).unwrap();
495                         assert_eq!(verified_rrs.verified_rrs.len(), 2);
496
497                         let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
498                         assert!(verified_rrs.valid_from < now);
499                         assert!(verified_rrs.expires > now);
500
501                         let resolved_rrs = verified_rrs.resolve_name(&query_name);
502                         assert_eq!(resolved_rrs.len(), 1);
503                         if let RR::Txt(txt) = &resolved_rrs[0] {
504                                 assert_eq!(txt.name.as_str(), "txt_test.matcorallo.com.");
505                                 assert_eq!(txt.data, b"dnssec_prover_test");
506                         } else { panic!(); }
507                 }
508         }
509
510         #[cfg(feature = "tokio")]
511         use tokio_crate as tokio;
512
513         #[cfg(feature = "tokio")]
514         #[tokio::test]
515         async fn test_txt_query_async() {
516                 let sockaddr = "8.8.8.8:53".to_socket_addrs().unwrap().next().unwrap();
517                 let query_name = "matt.user._bitcoin-payment.mattcorallo.com.".try_into().unwrap();
518                 let (proof, _) = build_txt_proof_async(sockaddr, &query_name).await.unwrap();
519
520                 let mut rrs = parse_rr_stream(&proof).unwrap();
521                 rrs.shuffle(&mut rand::rngs::OsRng);
522                 let verified_rrs = verify_rr_stream(&rrs).unwrap();
523                 assert_eq!(verified_rrs.verified_rrs.len(), 1);
524
525                 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
526                 assert!(verified_rrs.valid_from < now);
527                 assert!(verified_rrs.expires > now);
528         }
529
530         #[cfg(feature = "tokio")]
531         #[tokio::test]
532         async fn test_cross_domain_cname_query_async() {
533                 for resolver in ["1.1.1.1:53", "8.8.8.8:53", "9.9.9.9:53"] {
534                         let sockaddr = resolver.to_socket_addrs().unwrap().next().unwrap();
535                         let query_name = "wildcard.x_domain_cname_wild.matcorallo.com.".try_into().unwrap();
536                         let (proof, _) = build_txt_proof_async(sockaddr, &query_name).await.unwrap();
537
538                         let mut rrs = parse_rr_stream(&proof).unwrap();
539                         rrs.shuffle(&mut rand::rngs::OsRng);
540                         let verified_rrs = verify_rr_stream(&rrs).unwrap();
541                         assert_eq!(verified_rrs.verified_rrs.len(), 2);
542
543                         let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
544                         assert!(verified_rrs.valid_from < now);
545                         assert!(verified_rrs.expires > now);
546
547                         let resolved_rrs = verified_rrs.resolve_name(&query_name);
548                         assert_eq!(resolved_rrs.len(), 1);
549                         if let RR::Txt(txt) = &resolved_rrs[0] {
550                                 assert_eq!(txt.name.as_str(), "matt.user._bitcoin-payment.mattcorallo.com.");
551                                 assert!(txt.data.starts_with(b"bitcoin:"));
552                         } else { panic!(); }
553                 }
554         }
555
556         #[cfg(feature = "tokio")]
557         #[tokio::test]
558         async fn test_dname_wildcard_query_async() {
559                 for resolver in ["1.1.1.1:53", "8.8.8.8:53", "9.9.9.9:53"] {
560                         let sockaddr = resolver.to_socket_addrs().unwrap().next().unwrap();
561                         let query_name = "wildcard_a.wildcard_b.dname_test.dnssec_proof_tests.bitcoin.ninja.".try_into().unwrap();
562                         let (proof, _) = build_txt_proof_async(sockaddr, &query_name).await.unwrap();
563
564                         let mut rrs = parse_rr_stream(&proof).unwrap();
565                         rrs.shuffle(&mut rand::rngs::OsRng);
566                         let verified_rrs = verify_rr_stream(&rrs).unwrap();
567                         assert_eq!(verified_rrs.verified_rrs.len(), 3);
568
569                         let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
570                         assert!(verified_rrs.valid_from < now);
571                         assert!(verified_rrs.expires > now);
572
573                         let resolved_rrs = verified_rrs.resolve_name(&query_name);
574                         assert_eq!(resolved_rrs.len(), 1);
575                         if let RR::Txt(txt) = &resolved_rrs[0] {
576                                 assert_eq!(txt.name.as_str(), "cname.wildcard_test.dnssec_proof_tests.bitcoin.ninja.");
577                                 assert_eq!(txt.data, b"wildcard_test");
578                         } else { panic!(); }
579                 }
580         }
581
582 }