Zonemaster/Engine/Nameserver.pm

filter: Statementstmt 93.1% 27 / 29 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 10 / 10 Podpod n/a totaltotal 94.8% 37 / 39 CC 1 SCAR 0.3
CC
1
Cov
93%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Zonemaster/Engine.pm ↑ Summary
1 package Zonemaster::Engine::Nameserver;
2  
3 1 ▶use v5.16.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 1 ▶use version; our $VERSION = version->declare("v1.1.16");
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶use Class::Accessor qw[ antlers ];
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 1 ▶use Zonemaster::Engine::DNSName;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Zonemaster::Engine::Packet;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Zonemaster::Engine::Nameserver::Cache;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use Zonemaster::Engine::Recursor;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use Zonemaster::Engine::Constants qw( :ip :misc );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use Zonemaster::LDNS;
Subroutine BEGIN: called CC=1 SCAR=2.6
16  
17 use Carp qw( confess croak );
18 use CBOR::XS;
19 use Digest::MD5;
20 use Fcntl qw( SEEK_SET );
21 use List::Util qw( max min sum );
22 use MIME::Base64;
23 use Module::Find qw( useall );
24 use Net::IP::XS;
25 use POSIX ();
26 use Scalar::Util qw( blessed );
27 use Time::HiRes qw( gettimeofday time tv_interval );
28  
29 our @ISA = qw( Class::Accessor );
30  
31 use overload
32 '""' => \&string,
33 'cmp' => \&compare;
34  
35 has 'name' => ( is => 'ro' );
36 has 'address' => ( is => 'ro' );
37  
38 has 'dns' => ( is => 'ro' );
39 has 'cache' => ( is => 'ro' );
40 has 'times' => ( is => 'ro' );
41  
42 has 'fake_delegations' => ( is => 'ro' );
43 has 'fake_ds' => ( is => 'ro' );
44  
45 has 'blacklisted' => ( is => 'rw' );
46  
47 ###
48 ### Variables
49 ###
50  
51 our %object_cache;
52 our %address_object_cache;
53 our %address_repr_cache;
54  
55 ###
56 ### Build methods for attributes
57 ###
58  
59 sub new {
60 my $class = shift;
61 my $attrs = shift;
62  
63 my %lazy_attrs;
64 $lazy_attrs{dns} = delete $attrs->{dns} if exists $attrs->{dns};
65 $lazy_attrs{cache} = delete $attrs->{cache} if exists $attrs->{cache};
66  
67 # Required arguments
68 confess "Attribute \(address\) is required"
69 if !defined $attrs->{address};
70  
71 # Type coercions
72 $attrs->{name} = Zonemaster::Engine::DNSName->from_string( $attrs->{name} )
73 if !blessed $attrs->{name} || !$attrs->{name}->isa( 'Zonemaster::Engine::DNSName' );
74  
75 my $name = lc( q{} . $attrs->{name} );
76 $name = '$$$NONAME' if $name eq q{};
77  
78 my $address;
79  
80 # Use a object cache for IP type coercion (don't parse IP unless it is needed)
81 if (!blessed $attrs->{address} || !$attrs->{address}->isa( 'Net::IP::XS' )) {
82 if (!exists $address_object_cache{$attrs->{address}}) {
83 $address_object_cache{$attrs->{address}} = Net::IP::XS->new($attrs->{address});
84 $address_repr_cache{$attrs->{address}} = $address_object_cache{$attrs->{address}}->short;
85 }
86 # Fetch IP object from the address cache (avoid object creation and method call)
87 $address = $address_repr_cache{$attrs->{address}};
88 $attrs->{address} = $address_object_cache{$attrs->{address}};
89 } else {
90 $address = $attrs->{address}->short;
91 }
92  
93 # Return Nameserver object as soon as possible
94 if ( exists $object_cache{$name}{$address} ) {
95 return $object_cache{$name}{$address};
96 }
97  
98 # Type constraints
99 confess "Argument must be coercible into a Zonemaster::Engine::DNSName: name"
100 if !$attrs->{name}->isa( 'Zonemaster::Engine::DNSName' );
101 confess "Argument must be coercible into a Net::IP::XS: address"
102 if exists $attrs->{address}
103 && !$attrs->{address}->isa( 'Net::IP::XS' );
104 confess "Argument must be an ARRAYREF: times"
105 if exists $attrs->{times}
106 && ref $attrs->{times} ne 'ARRAY';
107 confess "Argument must be a HASHREF: fake_delegations"
108 if exists $attrs->{fake_delegations}
109 && ref $attrs->{fake_delegations} ne 'HASH';
110 confess "Argument must be a HASHREF: fake_ds"
111 if exists $attrs->{fake_ds}
112 && ref $attrs->{fake_ds} ne 'HASH';
113 confess "Argument must be a HASHREF: blacklisted"
114 if exists $attrs->{blacklisted}
115 && ref $attrs->{blacklisted} ne 'HASH';
116 confess "Argument must be a Zonemaster::LDNS: dns"
117 if exists $lazy_attrs{dns}
118 && ( !blessed $lazy_attrs{dns} || !$lazy_attrs{dns}->isa( 'Zonemaster::LDNS' ) );
119 confess "Argument must be a Zonemaster::Engine::Nameserver::Cache: cache"
120 if exists $lazy_attrs{cache}
121 && ( !blessed $lazy_attrs{cache} || !$lazy_attrs{cache}->isa( 'Zonemaster::Engine::Nameserver::Cache' ) );
122  
123 # Default values
124 $attrs->{blacklisted} //= {};
125 $attrs->{fake_delegations} //= {};
126 $attrs->{fake_ds} //= {};
127 $attrs->{times} //= [];
128  
129 my $obj = Class::Accessor::new( $class, $attrs );
130 $obj->{_dns} = $lazy_attrs{dns} if exists $lazy_attrs{dns};
131 $obj->{_cache} = $lazy_attrs{cache} if exists $lazy_attrs{cache};
132  
133 $obj->{_string} = $name . q{/} . $address;
134  
135 Zonemaster::Engine->logger->add( NS_CREATED => { name => $name, ip => $address } );
136 $object_cache{$name}{$address} = $obj;
137  
138 return $obj;
139 }
140  
141 sub dns {
142 my $self = shift;
143  
144 # Lazy default value
145 if ( !exists $self->{_dns} ) {
146 $self->{_dns} = $self->_build_dns();
147 }
148  
149 return $self->{_dns};
150 }
151  
152 sub cache {
153 my $self = shift;
154  
155 # Lazy default value
156 if ( !exists $self->{_cache} ) {
157 $self->{_cache} = $self->_build_cache();
158 }
159  
160 return $self->{_cache};
161 }
162  
163 sub _build_dns {
164 my ( $self ) = @_;
165  
166 my $res = Zonemaster::LDNS->new( $self->address->ip );
167  
168 $res->recurse( 0 );
169 $res->dnssec( 0 );
170 $res->edns_size( 0 );
171  
172 $res->retry( Zonemaster::Engine::Profile->effective->get( q{resolver.defaults.retry} ) );
173 $res->retrans( Zonemaster::Engine::Profile->effective->get( q{resolver.defaults.retrans} ) );
174 $res->debug( Zonemaster::Engine::Profile->effective->get( q{resolver.defaults.debug} ) );
175 $res->timeout( Zonemaster::Engine::Profile->effective->get( q{resolver.defaults.timeout} ) );
176  
177 my $src_address = $self->source_address();
178 if ( defined( $src_address ) ) {
179 $res->source( $src_address );
180 }
181  
182 return $res;
183 }
184  
185 sub _build_cache {
186 my ( $self ) = @_;
187  
188 my $cache_type = Zonemaster::Engine::Nameserver::Cache->get_cache_type( Zonemaster::Engine::Profile->effective );
189 my $cache_class = Zonemaster::Engine::Nameserver::Cache->get_cache_class( $cache_type );
190  
191 $cache_class->new( { address => $self->address } );
192 }
193  
194 ###
195 ### Public Methods (and helpers)
196 ###
197  
198 sub query {
199 my ( $self, $name, $type, $href ) = @_;
200 $type //= 'A';
201  
202 my $address = $self->address;
203 my $profile = Zonemaster::Engine::Profile->effective;
204  
205 if ( $address->version == 4 and not $profile->get( q{net.ipv4} ) ) {
206 Zonemaster::Engine->logger->add( IPV4_BLOCKED => { ns => $self->string } );
207 return;
208 }
209  
210 if ( $address->version == 6 and not $profile->get( q{net.ipv6} ) ) {
211 Zonemaster::Engine->logger->add( IPV6_BLOCKED => { ns => $self->string } );
212 return;
213 }
214  
215 Zonemaster::Engine->logger->add(
216 'QUERY',
217 {
218 name => "$name",
219 type => $type,
220 flags => $href,
221 ip => $address->short
222 }
223 );
224  
225 my $class = $href->{class} // 'IN';
226 my $dnssec = $href->{dnssec} // 0;
227 my $usevc = $href->{usevc} // 0;
228 my $recurse = $href->{recurse} // 0;
229  
230 if ( exists $href->{edns_details} and exists $href->{edns_details}{do} ) {
231 $dnssec = $href->{edns_details}{do};
232 }
233  
234 my $edns_size = $href->{edns_size} // ( $dnssec ? $EDNS_UDP_PAYLOAD_DNSSEC_DEFAULT : 0 );
235  
236 # Fake a DS answer
237 if ( $type eq 'DS' and $class eq 'IN' and $self->fake_ds->{ lc( $name ) } ) {
238 my $p = Zonemaster::LDNS::Packet->new( $name, $type, $class );
239  
240 $p->qr( 1 );
241 $p->aa( 1 );
242 $p->do( $dnssec );
243 $p->rd( $recurse );
244  
245 foreach my $rr ( @{ $self->fake_ds->{ lc( $name ) } } ) {
246 $p->unique_push( 'answer', $rr );
247 }
248  
249 my $res = Zonemaster::Engine::Packet->new( { packet => $p } );
250 Zonemaster::Engine->logger->add( FAKE_DS_RETURNED => { name => "$name", type => $type, class => $class, from => "$self" } );
251 Zonemaster::Engine->logger->add( FAKE_PACKET_RETURNED => { packet => $res->string } );
252 return $res;
253 }
254  
255 # Fake a delegation
256 foreach my $fname ( sort keys %{ $self->fake_delegations } ) {
257 if ( $name =~ m/([.]|\A)\Q$fname\E\z/xi ) {
258 my $p = Zonemaster::LDNS::Packet->new( $name, $type, $class );
259  
260 if ( lc( $name ) eq lc( $fname ) and $type eq 'NS' ) {
261 my $name = $self->fake_delegations->{$fname}{authority};
262 my $addr = $self->fake_delegations->{$fname}{additional};
263 $p->unique_push( 'answer', $_ ) for @{$name};
264 $p->unique_push( 'additional', $_ ) for @{$addr};
265 }
266 elsif ( $type eq 'DS' ) {
267 $p->aa( 1 );
268 }
269 else {
270 while ( my ( $section, $aref ) = each %{ $self->fake_delegations->{$fname} } ) {
271 $p->unique_push( $section, $_ ) for @{$aref};
272 }
273 }
274  
275 $p->aa( 0 ) unless ( $type eq 'DS' );
276 $p->qr( 1 );
277 $p->do( $dnssec );
278 $p->rd( $recurse );
279 $p->answerfrom( $address->ip );
280  
281 Zonemaster::Engine->logger->add( FAKE_DELEGATION_RETURNED => { name => "$name", type => $type, class => $class, from => "$self" } );
282  
283 my $res = Zonemaster::Engine::Packet->new( { packet => $p } );
284 Zonemaster::Engine->logger->add( FAKE_PACKET_RETURNED => { packet => $res->string } );
285 return $res;
286 } ## end if ( $name =~ m/([.]|\A)\Q$fname\E\z/xi)
287 } ## end foreach my $fname ( sort keys...)
288  
289 my $idx = $self->_key_for_query_cache( $name, $type, $href );
290  
291 croak "edns_size (or edns_details->size) parameter must be a value between 0 and 65535" if $edns_size > 65535 or $edns_size < 0;
292  
293 my ( $in_cache, $p ) = $self->cache->get_key( $idx );
294 if ( not $in_cache ) {
295 $p = $self->_query( $name, $type, $href );
296 $self->cache->set_key( $idx, $p );
297 }
298  
299 Zonemaster::Engine->logger->add( CACHED_RETURN => { packet => ( $p ? $p->string : 'undef' ) } );
300  
301 return $p;
302 } ## end sub query
303  
304 sub add_fake_delegation {
305 my ( $self, $domain, $href ) = @_;
306 my %delegation;
307  
308 $domain = q{} . Zonemaster::Engine::DNSName->new( $domain );
309 foreach my $name ( keys %{$href} ) {
310 push @{ $delegation{authority} }, Zonemaster::LDNS::RR->new( sprintf( '%s IN NS %s', $domain, $name ) );
311 foreach my $ip ( @{ $href->{$name} } ) {
312 if ( Net::IP::XS->new( $ip )->ip eq $self->address->ip ) {
313 Zonemaster::Engine->logger->add( FAKE_DELEGATION_TO_SELF => { ns => "$self", domain => $domain, data => $href } );
314 return;
315 }
316  
317 push @{ $delegation{additional} },
318 Zonemaster::LDNS::RR->new( sprintf( '%s IN %s %s', $name, ( Net::IP::XS::ip_is_ipv6( $ip ) ? 'AAAA' : 'A' ), $ip ) );
319 }
320 }
321  
322 $self->fake_delegations->{$domain} = \%delegation;
323 Zonemaster::Engine->logger->add( FAKE_DELEGATION_ADDED => { ns => "$self", domain => $domain, data => $href } );
324  
325 # We're changing the world, so the cache can't be trusted
326 Zonemaster::Engine::Recursor->clear_cache;
327  
328 return;
329 } ## end sub add_fake_delegation
330  
331 sub add_fake_ds {
332 my ( $self, $domain, $aref ) = @_;
333 my @ds;
334  
335 if ( not ref $domain ) {
336 $domain = Zonemaster::Engine::DNSName->new( $domain );
337 }
338  
339 foreach my $href ( @{$aref} ) {
340 push @ds,
341 Zonemaster::LDNS::RR->new(
342 sprintf(
343 '%s IN DS %d %d %d %s',
344 "$domain", $href->{keytag}, $href->{algorithm}, $href->{type}, $href->{digest}
345 )
346 );
347 }
348  
349 $self->fake_ds->{ lc( "$domain" ) } = \@ds;
350 Zonemaster::Engine->logger->add( FAKE_DS_ADDED => { domain => lc( "$domain" ), data => $aref, ns => "$self" } );
351  
352 # We're changing the world, so the cache can't be trusted
353 Zonemaster::Engine::Recursor->clear_cache;
354  
355 return;
356 } ## end sub add_fake_ds
357  
358  
359 # Builds the Zonemaster::LDNS::Packet object that would be sent for a query,
360 # taking options into account.
361  
362 sub _make_query_packet {
363 my ( $self, $qname, $qtype, $opts ) = @_;
364  
365 $qtype //= 'A';
366 my $qclass = $opts->{class} //= 'IN';
367  
368 my $dnssec = do {
369 if ( exists $opts->{edns_details} and exists $opts->{edns_details}{do} ) {
370 $opts->{edns_details}{do};
371 }
372 elsif ( exists $opts->{dnssec} ) {
373 $opts->{dnssec};
374 }
375 else {
376 0;
377 }
378 };
379  
380 my $edns_size = do {
381 if ( exists $opts->{edns_details} and exists $opts->{edns_details}{size} ) {
382 $opts->{edns_details}{size};
383 }
384 elsif ( exists $opts->{edns_size} ) {
385 $opts->{edns_size};
386 }
387 elsif ( $dnssec ) {
388 $EDNS_UDP_PAYLOAD_DNSSEC_DEFAULT;
389 }
390 elsif ( exists $opts->{edns_details} ) {
391 $EDNS_UDP_PAYLOAD_DEFAULT;
392 }
393 else {
394 0;
395 }
396 };
397  
398 die "Invalid value $edns_size for EDNS payload size (should be in 0..65535 range)"
399 unless $edns_size >= 0 and $edns_size <= 65535;
400  
401 my $packet = Zonemaster::LDNS::Packet->new( "$qname", $qtype, $qclass );
402 $packet->rd($opts->{recurse} // 0);
403  
404 if ( exists $opts->{edns_details} ) {
405 $packet->set_edns_present();
406  
407 if ( exists $opts->{edns_details}{version} ) {
408 $packet->edns_version($opts->{edns_details}{version});
409 }
410 if ( exists $opts->{edns_details}{z} ) {
411 $packet->edns_z($opts->{edns_details}{z});
412 }
413 if ( exists $opts->{edns_details}{rcode} ) {
414 $packet->edns_rcode($opts->{edns_details}{rcode});
415 }
416 if ( exists $opts->{edns_details}{data} ) {
417 $packet->edns_data($opts->{edns_details}{data});
418 }
419 }
420  
421 $packet->do($dnssec);
422 $packet->edns_size($edns_size);
423  
424 return $packet;
425 }
426  
427  
428 # Computes the key to use to search the cache for a packet corresponding to a
429 # query we have previously sent.
430  
431 sub _key_for_query_cache {
432 my ( $self, $name, $type, $href ) = @_;
433  
434 my $usevc = $href->{usevc} // 0;
435  
436 my $pkt = $self->_make_query_packet( $name, $type, $href );
437  
438 # Repurpose the ID field. We want this field to be zeroed out
439 # in order to match queries with the exact same contents (except
440 # transaction ID), but we may want cache keys to differ on other
441 # attributes, for example transport.
442 #
443 # Currently the layout is as follows:
444 #
445 # 15 8
446 # +-----+-----+-----+-----+-----+-----+-----+-----+
447 # | TCP | (set to 0) |
448 # +-----+-----+-----+-----+-----+-----+-----+-----+
449 #
450 # 7 0
451 # +-----+-----+-----+-----+-----+-----+-----+-----+
452 # | (set to 0) |
453 # +-----+-----+-----+-----+-----+-----+-----+-----+
454 #
455 # where:
456 # * bit 15 is set to 1 if the query is sent over TCP, 0 otherwise
457  
458 my $fake_id = 0;
459 $fake_id |= (1 << 15) if $usevc;
460  
461 $pkt->id($fake_id);
462  
463 return $pkt->wireformat();
464 }
465  
466 sub _query {
467 my ( $self, $name, $type, $href ) = @_;
468 my %flags;
469  
470 $type //= 'A';
471 $href->{class} //= 'IN';
472  
473 if ( Zonemaster::Engine::Profile->effective->get( q{no_network} ) ) {
474 croak sprintf
475 "External query for %s, %s attempted to %s while running with no_network",
476 $name, $type, $self->string;
477 }
478  
479 Zonemaster::Engine->logger->add(
480 'external_query',
481 {
482 name => "$name",
483 type => $type,
484 flags => $href,
485 ip => $self->address->short
486 }
487 );
488  
489 # Make sure we have a value for each flag
490 $flags{q{retry}} = $href->{q{retry}} // Zonemaster::Engine::Profile->effective->get( q{resolver.defaults.retry} );
491 $flags{q{retrans}} = $href->{q{retrans}}
492 // Zonemaster::Engine::Profile->effective->get( q{resolver.defaults.retrans} );
493 $flags{q{dnssec}} = $href->{q{dnssec}} // 0;
494 $flags{q{usevc}} = $href->{q{usevc}} // 0;
495 $flags{q{igntc}} = $href->{q{igntc}} // 0;
496 $flags{q{fallback}} = $href->{q{fallback}}
497 // Zonemaster::Engine::Profile->effective->get( q{resolver.defaults.fallback} );
498 $flags{q{recurse}} = $href->{q{recurse}} // 0;
499 $flags{q{timeout}} = $href->{q{timeout}}
500 // Zonemaster::Engine::Profile->effective->get( q{resolver.defaults.timeout} );
501  
502 if ( exists $href->{edns_details} ) {
503 $flags{q{dnssec}} = $href->{edns_details}{do} // $flags{q{dnssec}};
504 $flags{q{edns_size}} = $href->{edns_details}{size} // ( $href->{q{edns_size}} // ( $flags{q{dnssec}} ? $EDNS_UDP_PAYLOAD_DNSSEC_DEFAULT : $EDNS_UDP_PAYLOAD_DEFAULT ) );
505 }
506 else {
507 $flags{q{edns_size}} = $href->{q{edns_size}} // ( $flags{q{dnssec}} ? $EDNS_UDP_PAYLOAD_DNSSEC_DEFAULT : 0 );
508 }
509  
510 # Set flags for this query
511 foreach my $flag ( keys %flags ) {
512 $self->dns->$flag( $flags{$flag} );
513 }
514  
515 my $before = time();
516 my $res;
517 if ( $BLACKLISTING_ENABLED and $self->blacklisted->{ $flags{usevc} } ) {
518 Zonemaster::Engine->logger->add(
519 IS_BLACKLISTED => {
520 message => "Server transport has been blacklisted due to previous failure",
521 ns => "$self",
522 name => "$name",
523 type => $type,
524 class => $href->{class},
525 proto => $flags{usevc} ? q{TCP} : q{UDP},
526 dnssec => $flags{dnssec},
527 edns_size => $flags{q{edns_size}}
528 }
529 );
530 }
531 else {
532 my $pkt = $self->_make_query_packet( $name, $type, $href );
533 $res = eval { $self->dns->query_with_pkt( $pkt ) };
534  
535 if ( $@ ) {
536 my $msg = "$@";
537 my $trailing_info = " at ".__FILE__;
538  
539 chomp( $msg );
540 $msg =~ s/$trailing_info.*/\./;
541  
542 Zonemaster::Engine->logger->add( LOOKUP_ERROR =>
543 { message => $msg, ns => "$self", domain => "$name", type => $type, class => $href->{class} } );
544  
545 if ( not $href->{q{blacklisting_disabled}} and $type eq q{SOA} and $flags{q{edns_size}} == 0 ) {
546 $self->blacklisted->{ $flags{usevc} } = 1;
547 Zonemaster::Engine->logger->add( BLACKLISTING =>
548 { ns => "$self", proto => $flags{usevc} ? q{TCP} : q{UDP} } );
549 }
550 }
551 }
552  
553 push @{ $self->times }, ( time() - $before );
554  
555 if ( $res ) {
556 my $p = Zonemaster::Engine::Packet->new( { packet => $res } );
557 my $size = length( $p->data );
558 if ( $size > $EDNS_UDP_PAYLOAD_COMMON_LIMIT ) {
559 my $command = sprintf q{dig @%s %s%s %s}, $self->address->short, $flags{dnssec} ? q{+dnssec } : q{},
560 "$name", $type;
561 Zonemaster::Engine->logger->add(
562 PACKET_BIG => { size => $size, command => $command } );
563 }
564 Zonemaster::Engine->logger->add( EXTERNAL_RESPONSE => { packet => $p->string } );
565 return $p;
566 }
567 else {
568 Zonemaster::Engine->logger->add( EMPTY_RETURN => {} );
569 return;
570 }
571 } ## end sub _query
572  
573 sub string {
574 return $_[0]->{_string};
575 }
576  
577 sub compare {
578 my ( $self, $other, $reverse ) = @_;
579  
580 return $self->string cmp $other->string;
581 }
582  
583  
584 # Converts a Zonemaster::Engine::Packet object to a predictable representation
585 # as an array, which can then be turned into CBOR.
586  
587 sub _serialize_packet {
588 my ( $packet ) = @_;
589  
590 return undef if not defined $packet;
591  
592 return [
593 $packet->packet->wireformat(),
594 $packet->packet->answerfrom(),
595 $packet->packet->timestamp(),
596 $packet->packet->querytime(),
597 ];
598 }
599  
600 sub save {
601 my ( $class, $filename ) = @_;
602  
603 open my $fh, '>', $filename or die "Cache save failed: $!";
604  
605 my $dumped_contents = {
606 format_version => 1,
607 engine_version => Zonemaster::Engine->VERSION(),
608 packets => do {
609 # Gives an array of (nameserver, cached packets) pairs.
610 # A nameserver is itself a (name, IP) pair and each cached packet
611 # is represented as a (bytes, source IP, timestamp, query time) tuple,
612 # or undef if there was no response.
613 my @result;
614 foreach my $name ( sort keys %object_cache ) {
615 foreach my $addr ( sort keys %{ $object_cache{$name} } ) {
616 my @ns_packets;
617 my $cached_data = $object_cache{$name}{$addr}->cache->data;
618  
619 next if scalar %$cached_data == 0;
620  
621 foreach my $entry_key ( sort keys %$cached_data ) {
622 push @ns_packets, [ $entry_key, _serialize_packet($cached_data->{$entry_key}) ];
623 }
624 push @result, [ [ $name, $addr ], \@ns_packets ];
625 }
626 };
627 \@result;
628 }
629 };
630  
631 my $cbor = CBOR::XS->new();
632  
633 # We begin the file with the CBOR magic value deliberately, so that we can
634 # reject files that do not start with that signature on loading.
635 print $fh $CBOR::XS::MAGIC, $cbor->encode($dumped_contents);
636  
637 close $fh or die $!;
638  
639 Zonemaster::Engine->logger->add( SAVED_NS_CACHE => { file => $filename } );
640 }
641  
642  
643 # Performs the inverse operation of _serialize_packet(): from a deserialized
644 # CBOR array, reconstructs a Zonemaster::Engine::Packet object.
645  
646 sub _deserialize_packet {
647 my ( $cbor_packet ) = @_;
648  
649 return undef if not defined $cbor_packet;
650  
651 my ( $bytes, $answerfrom, $timestamp, $querytime ) = @$cbor_packet;
652 my $packet = Zonemaster::Engine::Packet->new(
653 { packet => Zonemaster::LDNS::Packet->new_from_wireformat( $bytes ) }
654 );
655 $packet->answerfrom( $answerfrom ) if defined $answerfrom;
656 $packet->timestamp( $timestamp ) if defined $timestamp;
657 $packet->querytime( $querytime ) if defined $querytime;
658  
659 return $packet;
660 }
661  
662 sub restore {
663 my ( $class, $filename ) = @_;
664  
665 open my $fh, '<', $filename or die "Failed to open restore data file: $!\n";
666  
667  
668 # Expect CBOR magic string at beginning of file.
669 my $found_magic = do {
670 my $buf;
671 my $len = read($fh, $buf, length($CBOR::XS::MAGIC));
672 seek($fh, 0, SEEK_SET) or die "seek: $!";
673 ($len == 3 and $buf eq $CBOR::XS::MAGIC);
674 };
675 croak "The restore data file seems to be corrupted" if not $found_magic;
676  
677 my $cbor = CBOR::XS->new();
678 my $saved_contents = $cbor->decode(do { local $/; <$fh> });
679 close $fh;
680  
681 my $format_version = $saved_contents->{format_version};
682 croak "Unsupported format version $format_version" if $format_version != 1;
683  
684 my $cache_type = Zonemaster::Engine::Nameserver::Cache->get_cache_type( Zonemaster::Engine::Profile->effective );
685 my $cache_class = Zonemaster::Engine::Nameserver::Cache->get_cache_class( $cache_type );
686  
687 foreach my $entry ( @{ $saved_contents->{packets} } ) {
688 my ( $ns_pair, $ns_packets ) = @$entry;
689  
690 my $data = {};
691 foreach my $ns_cache_entry ( @$ns_packets ) {
692 my ( $key, $value ) = @$ns_cache_entry;
693 $data->{$key} = _deserialize_packet($value);
694 }
695  
696 my $addr = Net::IP::XS->new( $ns_pair->[1] );
697 my $ns = Zonemaster::Engine::Nameserver->new(
698 {
699 name => $ns_pair->[0],
700 address => $addr,
701 cache => $cache_class->new( { data => $data, address => $addr } )
702 }
703 );
704 }
705  
706 Zonemaster::Engine->logger->add( RESTORED_NS_CACHE => { file => $filename } );
707  
708 return;
709 }
710  
711 sub max_time {
712 my ( $self ) = @_;
713  
714 return max( @{ $self->times } ) // 0;
715 }
716  
717 sub min_time {
718 my ( $self ) = @_;
719  
720 return min( @{ $self->times } ) // 0;
721 }
722  
723 sub sum_time {
724 my ( $self ) = @_;
725  
726 return sum( @{ $self->times } ) // 0;
727 }
728  
729 sub average_time {
730 my ( $self ) = @_;
731  
732 return 0 if @{ $self->times } == 0;
733  
734 return ( $self->sum_time / scalar( @{ $self->times } ) );
735 }
736  
737 sub median_time {
738 my ( $self ) = @_;
739  
740 my @t = sort { $a <=> $b } @{ $self->times };
741 my $c = scalar( @t );
742 if ( $c == 0 ) {
743 return 0;
744 }
745 elsif ( $c % 2 == 0 ) {
746 return ( $t[ $c / 2 ] + $t[ ( $c / 2 ) - 1 ] ) / 2;
747 }
748 else {
749 return $t[ int( $c / 2 ) ];
750 }
751 }
752  
753 sub stddev_time {
754 my ( $self ) = @_;
755  
756 my $avg = $self->average_time;
757 my $c = scalar( @{ $self->times } );
758  
759 return 0 if $c == 0;
760  
761 return sqrt( sum( map { ( $_ - $avg )**2 } @{ $self->times } ) / $c );
762 }
763  
764 sub all_known_nameservers {
765 my @res;
766  
767 foreach my $n ( values %object_cache ) {
768 push @res, values %{$n};
769 }
770  
771 return @res;
772 }
773  
774 sub axfr {
775 my ( $self, $domain, $callback, $class ) = @_;
776 $class //= 'IN';
777  
778 my $idx = $self->_key_for_query_cache( $domain, 'AXFR', { class => $class, usevc => 1 } );
779 my ( $in_cache, $p ) = $self->cache->get_key( $idx );
780  
781 if ( $in_cache ) {
782 if ( $p->rcode() ne 'NOERROR' ) {
783 # Croak with the same error message the real AXFR croaked with.
784 my ( undef, $ede_text ) = $p->packet->first_ede();
785 croak $ede_text // "AXFR transfer error: REFUSED";
786 }
787  
788 my $last_ret = 1;
789 foreach my $rr ( $p->answer() ) {
790 $last_ret = $callback->($rr);
791 last if $last_ret == 0;
792 }
793 return $last_ret;
794 }
795 else {
796 my ( $ret, $error, $p ) = $self->_axfr( $domain, $callback, $class );
797 $self->cache->set_key( $idx, $p );
798 croak $error if defined $error;
799 return $ret;
800 }
801 }
802  
803 sub _axfr {
804 my ( $self, $domain, $callback, $class ) = @_;
805  
806 if ( Zonemaster::Engine::Profile->effective->get( q{no_network} ) ) {
807 croak sprintf
808 "External AXFR query for %s attempted to %s while running with no_network",
809 $domain, $self->string;
810 }
811  
812 if ( $self->address->version == 4 and not Zonemaster::Engine::Profile->effective->get( q{net.ipv4} ) ) {
813 Zonemaster::Engine->logger->add( IPV4_BLOCKED => { ns => $self->string } );
814 return;
815 }
816  
817 if ( $self->address->version == 6 and not Zonemaster::Engine::Profile->effective->get( q{net.ipv6} ) ) {
818 Zonemaster::Engine->logger->add( IPV6_BLOCKED => { ns => $self->string } );
819 return;
820 }
821  
822 my @rrs;
823 my $wrapped_callback = sub {
824 push @rrs, $_[0];
825 return $callback->( @_ );
826 };
827  
828 my $t0 = [gettimeofday];
829 my $ret = eval { $self->dns->axfr( $domain, $wrapped_callback, $class ) };
830 my $error = $@ if not defined $ret;
831 my $querytime = tv_interval($t0);
832  
833 # Build a synthetic packet containing all the resource records we
834 # collected, so that this AXFR can be cached (and therefore replayed)
835 # adequately.
836 my $p = Zonemaster::Engine::Packet->new({
837 packet => Zonemaster::LDNS::Packet->new( $domain, 'AXFR', $class )
838 });
839  
840 $p->timestamp(time());
841 $p->querytime($querytime * 1000);
842 $p->answerfrom($self->address->short);
843 $p->id(0);
844 $p->packet->qr(1);
845 if ( defined $error ) {
846 $p->rcode('REFUSED');
847 # Use an Extended DNS Error 13 (Cached Error) in the synthetic packet
848 # to store the original error message.
849 my $file = __FILE__;
850 chomp $error;
851 $error =~ s/ at $file line \d+\.$//;
852 $p->packet->first_ede( 13, $error );
853 }
854 $p->packet->aa(1);
855 $p->unique_push( 'answer', $_ ) foreach @rrs;
856  
857 return $ret, $error, $p;
858 }
859  
860 sub source_address {
861 my ( $self ) = @_;
862  
863 my $src_address = Zonemaster::Engine::Profile->effective->get( "resolver.source" . Net::IP::XS::ip_get_version( $self->address->ip ) );
864  
865 return $src_address eq '' ? undef : $src_address;
866 }
867  
868 sub empty_cache {
869 %object_cache = ();
870 %address_object_cache = ();
871 %address_repr_cache = ();
872  
873 Zonemaster::Engine::Nameserver::Cache::empty_cache();
874  
875 return;
876 }
877  
878 1;
879  
880 =head1 NAME
881  
882 Zonemaster::Engine::Nameserver - object representing a DNS nameserver
883  
884 =head1 SYNOPSIS
885  
886 my $ns = Zonemaster::Engine::Nameserver->new({ name => 'ns.nic.se', address => '212.247.7.228' });
887 my $p = $ns->query('www.iis.se', 'AAAA');
888  
889 =head1 DESCRIPTION
890  
891 This is a very central object in the L<Zonemaster::Engine> framework. All DNS
892 communications with the outside world pass through here, so we can do
893 things like synthesizing and recording traffic. All the objects are
894 also unique per name/IP pair, and creating a new one with an already
895 existing pair will return the existing object instead of creating a
896 new one. Queries and their responses are cached by IP address, so that
897 a specific query will only be sent once to each address (even if there
898 are multiple objects for that address with different names).
899  
900 Class methods on this class allows saving and loading cache contents.
901  
902 =head1 ATTRIBUTES
903  
904 =over
905  
906 =item name
907  
908 A L<Zonemaster::Engine::DNSName> object holding the nameserver's name.
909  
910 =item address
911  
912 A L<Net::IP::XS> object holding the nameserver's address.
913  
914 =item dns
915  
916 The L<Zonemaster::LDNS> object used to actually send and receive DNS queries.
917  
918 =item cache
919  
920 A reference to a L<Zonemaster::Engine::Nameserver::Cache> object holding the cache of sent queries. Not meant for external use.
921  
922 =item times
923  
924 A reference to a list with elapsed time values for the queries made through this nameserver.
925  
926 =item blacklisted
927  
928 A reference to a hash used to prevent sending subsequent queries to the name server after specific queries have failed.
929  
930 The mechanism will only trigger on no response from non-EDNS SOA queries and is protocol dependent (i.e. TCP/UDP). It can be disabled
931 on a per query basis with L<blacklisting_disabled>, or globally with L<Zonemaster::Engine::Constants/$BLACKLISTING_ENABLED>.
932  
933 =back
934  
935 =head1 CLASS METHODS
936  
937 =over
938  
939 =item new
940  
941 Construct a new object.
942  
943 =item save($filename)
944  
945 Save the entire object cache to the given filename, using the
946 byte-order-independent Storable format.
947  
948 =item restore($filename)
949  
950 Replace the entire object cache with the contents of the named file.
951  
952 =item all_known_nameservers()
953  
954 Class method that returns a list of all nameserver objects in the global cache.
955  
956 =item empty_cache()
957  
958 Remove all cached nameserver objects and queries.
959  
960 =back
961  
962 =head1 INSTANCE METHODS
963  
964 =over
965  
966 =item query($name, $type, $flagref)
967  
968 Send a DNS query to the nameserver the object represents. C<$name> and C<$type> are the name and type that will be queried for (C<$type> defaults
969 to 'A' if it's left undefined). C<$flagref> is a reference to a hash, the keys of which are flags and the values are their corresponding values.
970 The available flags are as follows. All but 'class' and 'edns_details' directly correspond to methods in the L<Zonemaster::LDNS> object.
971  
972 =over
973  
974 =item class
975  
976 Defaults to 'IN' if not set.
977  
978 =item usevc
979  
980 Send the query via TCP (only).
981  
982 =item retrans
983  
984 The retransmission interval.
985  
986 =item dnssec
987  
988 Set the DO flag in the query. Defaults to false.
989  
990 If set to true, it becomes an EDNS query.
991 Value overridden by C<edns_details{do}> (if also given). More details in L<edns_details> below.
992  
993 =item debug
994  
995 Set the debug flag in the resolver, producing output on STDERR as the query process proceeds.
996  
997 =item recurse
998  
999 Set the RD flag in the query.
1000  
1001 =item timeout
1002  
1003 Set the timeout for the outgoing sockets. May or may not be observed by the underlying network stack.
1004  
1005 =item retry
1006  
1007 Set the number of times the query is tried.
1008  
1009 =item igntc
1010  
1011 If set to true, incoming response packets with the TC flag set are not automatically retried over TCP.
1012  
1013 =item fallback
1014  
1015 If set to true, incoming response packets with the TC flag set fall back to EDNS and/or TCP.
1016  
1017 =item blacklisting_disabled
1018  
1019 If set to true, prevents a name server from being blacklisted.
1020  
1021 =item edns_size
1022  
1023 Set the EDNS0 UDP maximum size. The value must be comprised between 0 and 65535.
1024 Defaults to 0, or 512 if the query is a non-DNSSEC EDNS query, or 1232 if the query is a DNSSEC query.
1025  
1026 Setting a value other than 0 will also implicitly enable EDNS for the query.
1027 Value overridden by C<edns_details-E<gt>{size}> (if also given). More details in L<edns_details> below.
1028  
1029 =item edns_details
1030  
1031 A hash. An empty hash or a hash with any keys below will enable EDNS for the query.
1032  
1033 The currently supported keys are 'version', 'z', 'do', 'rcode', 'size' and 'data'.
1034 See L<Zonemaster::LDNS::Packet> for more details (key names prefixed with 'edns_').
1035  
1036 Note that flag L<edns_size> also exists (see above) and has the same effect as C<edns_details-E<gt>{size}>, although the value of the
1037 latter will take precedence if both are given.
1038  
1039 Similarly, note that flag L<dnssec> also exists (see above) and has the same effect as C<edns_details-E<gt>{do}>, although the value of the
1040 latter will take precedence if both are given.
1041  
1042 =back
1043  
1044 =item string()
1045  
1046 Returns a string representation of the object. Normally this is just the name and IP address separated by a slash.
1047  
1048 =item compare($other)
1049  
1050 Used for overloading comparison operators.
1051  
1052 =item sum_time()
1053  
1054 Returns the total time spent sending queries and waiting for responses.
1055  
1056 =item min_time()
1057  
1058 Returns the shortest time spent on a query.
1059  
1060 =item max_time()
1061  
1062 Returns the longest time spent on a query.
1063  
1064 =item average_time()
1065  
1066 Returns the average time spent on queries.
1067  
1068 =item median_time()
1069  
1070 Returns the median query time.
1071  
1072 =item stddev_time()
1073  
1074 Returns the standard deviation for the whole set of query times.
1075  
1076 =item add_fake_delegation($domain,$data)
1077  
1078 Adds fake delegation information to this specific nameserver object. Takes the
1079 same arguments as the similarly named method in L<Zonemaster::Engine>. This is
1080 primarily used for internal information, and using it directly will likely give
1081 confusing results (but may be useful to model certain kinds of
1082 misconfigurations).
1083  
1084 =item add_fake_ds($domain, $data)
1085  
1086 Adds fake DS information to this nameserver object. Takes the same arguments as
1087 the similarly named method in L<Zonemaster::Engine>.
1088  
1089 =item axfr( $domain, $callback, $class )
1090  
1091 Does an AXFR for the requested domain from the nameserver. The callback
1092 function will be called once for each received RR, with that RR as its only
1093 argument. To continue getting more RRs, the callback must return a true value.
1094 If it returns a true value, the AXFR will be aborted. See L<Zonemaster::LDNS::axfr>
1095 for more details.
1096  
1097 =item source_address()
1098  
1099 my $src_address = source_address();
1100  
1101 Returns the configured IPv4 or IPv6 source address to be used by the underlying DNS resolver for sending queries,
1102 or C<undef> if the source address is the empty string.
1103  
1104 =item empty_cache()
1105  
1106 Clears the caches of Zonemaster::Engine::Nameserver (name server names and IP addresses) and Zonemaster::Engine::Nameserver::Cache (query and response packets) objects.
1107  
1108 =back
1109  
1110 =cut
« Zonemaster/Engine.pm ↑ Summary