Zonemaster/Engine/Nameserver.pm

filter: Statementstmt 93.7% 30 / 32 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 11 / 11 Podpod n/a totaltotal 95.3% 41 / 43 CC 1 SCAR 0.3
CC
1
Cov
94%
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;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Zonemaster::Engine::Packet;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use Zonemaster::Engine::Nameserver::Cache;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use Zonemaster::Engine::Recursor;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use Zonemaster::Engine::Constants qw( :ip :misc );
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use Zonemaster::LDNS;
Subroutine BEGIN: called CC=1 SCAR=2.6
17  
18 use Net::IP::XS;
19 use Time::HiRes qw[time];
20 use JSON::PP;
21 use MIME::Base64;
22 use Module::Find qw[useall];
23 use Carp qw( confess croak );
24 use List::Util qw[max min sum];
25 use Digest::MD5;
26 use POSIX ();
27 use Scalar::Util qw[ blessed ];
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 $md5 = Digest::MD5->new;
290  
291 $md5->add( q{NAME} , $name,
292 q{TYPE} , "\U$type",
293 q{CLASS} , "\U$class",
294 q{DNSSEC} , $dnssec,
295 q{USEVC} , $usevc,
296 q{RECURSE} , $recurse );
297  
298 if ( exists $href->{edns_details} ) {
299 $md5->add( q{EDNS_VERSION} , $href->{edns_details}{version} // 0,
300 q{EDNS_Z} , $href->{edns_details}{z} // 0,
301 q{EDNS_EXTENDED_RCODE} , $href->{edns_details}{rcode} // 0,
302 q{EDNS_DATA} , $href->{edns_details}{data} // q{} );
303 $edns_size = $href->{edns_details}{size} // ( $href->{edns_size} // ( $dnssec ? $EDNS_UDP_PAYLOAD_DNSSEC_DEFAULT : $EDNS_UDP_PAYLOAD_DEFAULT ) );
304 }
305  
306 croak "edns_size (or edns_details->size) parameter must be a value between 0 and 65535" if $edns_size > 65535 or $edns_size < 0;
307  
308 $md5->add( q{EDNS_UDP_SIZE} , $edns_size );
309  
310 my $idx = $md5->b64digest();
311  
312 my ( $in_cache, $p ) = $self->cache->get_key( $idx );
313 if ( not $in_cache ) {
314 $p = $self->_query( $name, $type, $href );
315 $self->cache->set_key( $idx, $p );
316 }
317  
318 Zonemaster::Engine->logger->add( CACHED_RETURN => { packet => ( $p ? $p->string : 'undef' ) } );
319  
320 return $p;
321 } ## end sub query
322  
323 sub add_fake_delegation {
324 my ( $self, $domain, $href ) = @_;
325 my %delegation;
326  
327 $domain = q{} . Zonemaster::Engine::DNSName->new( $domain );
328 foreach my $name ( keys %{$href} ) {
329 push @{ $delegation{authority} }, Zonemaster::LDNS::RR->new( sprintf( '%s IN NS %s', $domain, $name ) );
330 foreach my $ip ( @{ $href->{$name} } ) {
331 if ( Net::IP::XS->new( $ip )->ip eq $self->address->ip ) {
332 Zonemaster::Engine->logger->add( FAKE_DELEGATION_TO_SELF => { ns => "$self", domain => $domain, data => $href } );
333 return;
334 }
335  
336 push @{ $delegation{additional} },
337 Zonemaster::LDNS::RR->new( sprintf( '%s IN %s %s', $name, ( Net::IP::XS::ip_is_ipv6( $ip ) ? 'AAAA' : 'A' ), $ip ) );
338 }
339 }
340  
341 $self->fake_delegations->{$domain} = \%delegation;
342 Zonemaster::Engine->logger->add( FAKE_DELEGATION_ADDED => { ns => "$self", domain => $domain, data => $href } );
343  
344 # We're changing the world, so the cache can't be trusted
345 Zonemaster::Engine::Recursor->clear_cache;
346  
347 return;
348 } ## end sub add_fake_delegation
349  
350 sub add_fake_ds {
351 my ( $self, $domain, $aref ) = @_;
352 my @ds;
353  
354 if ( not ref $domain ) {
355 $domain = Zonemaster::Engine::DNSName->new( $domain );
356 }
357  
358 foreach my $href ( @{$aref} ) {
359 push @ds,
360 Zonemaster::LDNS::RR->new(
361 sprintf(
362 '%s IN DS %d %d %d %s',
363 "$domain", $href->{keytag}, $href->{algorithm}, $href->{type}, $href->{digest}
364 )
365 );
366 }
367  
368 $self->fake_ds->{ lc( "$domain" ) } = \@ds;
369 Zonemaster::Engine->logger->add( FAKE_DS_ADDED => { domain => lc( "$domain" ), data => $aref, ns => "$self" } );
370  
371 # We're changing the world, so the cache can't be trusted
372 Zonemaster::Engine::Recursor->clear_cache;
373  
374 return;
375 } ## end sub add_fake_ds
376  
377 sub _query {
378 my ( $self, $name, $type, $href ) = @_;
379 my %flags;
380  
381 $type //= 'A';
382 $href->{class} //= 'IN';
383  
384 if ( Zonemaster::Engine::Profile->effective->get( q{no_network} ) ) {
385 croak sprintf
386 "External query for %s, %s attempted to %s while running with no_network",
387 $name, $type, $self->string;
388 }
389  
390 Zonemaster::Engine->logger->add(
391 'external_query',
392 {
393 name => "$name",
394 type => $type,
395 flags => $href,
396 ip => $self->address->short
397 }
398 );
399  
400 # Make sure we have a value for each flag
401 $flags{q{retry}} = $href->{q{retry}} // Zonemaster::Engine::Profile->effective->get( q{resolver.defaults.retry} );
402 $flags{q{retrans}} = $href->{q{retrans}}
403 // Zonemaster::Engine::Profile->effective->get( q{resolver.defaults.retrans} );
404 $flags{q{dnssec}} = $href->{q{dnssec}} // 0;
405 $flags{q{usevc}} = $href->{q{usevc}} // 0;
406 $flags{q{igntc}} = $href->{q{igntc}} // 0;
407 $flags{q{fallback}} = $href->{q{fallback}}
408 // Zonemaster::Engine::Profile->effective->get( q{resolver.defaults.fallback} );
409 $flags{q{recurse}} = $href->{q{recurse}} // 0;
410 $flags{q{timeout}} = $href->{q{timeout}}
411 // Zonemaster::Engine::Profile->effective->get( q{resolver.defaults.timeout} );
412  
413 if ( exists $href->{edns_details} ) {
414 $flags{q{dnssec}} = $href->{edns_details}{do} // $flags{q{dnssec}};
415 $flags{q{edns_size}} = $href->{edns_details}{size} // ( $href->{q{edns_size}} // ( $flags{q{dnssec}} ? $EDNS_UDP_PAYLOAD_DNSSEC_DEFAULT : $EDNS_UDP_PAYLOAD_DEFAULT ) );
416 }
417 else {
418 $flags{q{edns_size}} = $href->{q{edns_size}} // ( $flags{q{dnssec}} ? $EDNS_UDP_PAYLOAD_DNSSEC_DEFAULT : 0 );
419 }
420  
421 # Set flags for this query
422 foreach my $flag ( keys %flags ) {
423 $self->dns->$flag( $flags{$flag} );
424 }
425  
426 my $before = time();
427 my $res;
428 if ( $BLACKLISTING_ENABLED and $self->blacklisted->{ $flags{usevc} } ) {
429 Zonemaster::Engine->logger->add(
430 IS_BLACKLISTED => {
431 message => "Server transport has been blacklisted due to previous failure",
432 ns => "$self",
433 name => "$name",
434 type => $type,
435 class => $href->{class},
436 proto => $flags{usevc} ? q{TCP} : q{UDP},
437 dnssec => $flags{dnssec},
438 edns_size => $flags{q{edns_size}}
439 }
440 );
441 }
442 else {
443 if ( exists $href->{edns_details} ) {
444 my $pkt = Zonemaster::LDNS::Packet->new("$name", $type, $href->{class} );
445 $pkt->set_edns_present();
446  
447 $pkt->do($flags{q{dnssec}});
448 $pkt->edns_size($flags{q{edns_size}});
449  
450 if ( exists $href->{edns_details}{version} ) {
451 $pkt->edns_version($href->{edns_details}{version});
452 }
453 if ( exists $href->{edns_details}{z} ) {
454 $pkt->edns_z($href->{edns_details}{z});
455 }
456 if ( exists $href->{edns_details}{rcode} ) {
457 $pkt->edns_rcode($href->{edns_details}{rcode});
458 }
459 if ( exists $href->{edns_details}{data} ) {
460 $pkt->edns_data($href->{edns_details}{data});
461 }
462  
463 $res = eval { $self->dns->query_with_pkt( $pkt ) };
464 }
465 else {
466 $res = eval { $self->dns->query( "$name", $type, $href->{class} ) };
467 }
468  
469 if ( $@ ) {
470 my $msg = "$@";
471 my $trailing_info = " at ".__FILE__;
472  
473 chomp( $msg );
474 $msg =~ s/$trailing_info.*/\./;
475  
476 Zonemaster::Engine->logger->add( LOOKUP_ERROR =>
477 { message => $msg, ns => "$self", domain => "$name", type => $type, class => $href->{class} } );
478  
479 if ( not $href->{q{blacklisting_disabled}} and $type eq q{SOA} and $flags{q{edns_size}} == 0 ) {
480 $self->blacklisted->{ $flags{usevc} } = 1;
481 Zonemaster::Engine->logger->add( BLACKLISTING =>
482 { ns => "$self", proto => $flags{usevc} ? q{TCP} : q{UDP} } );
483 }
484 }
485 }
486  
487 push @{ $self->times }, ( time() - $before );
488  
489 if ( $res ) {
490 my $p = Zonemaster::Engine::Packet->new( { packet => $res } );
491 my $size = length( $p->data );
492 if ( $size > $EDNS_UDP_PAYLOAD_COMMON_LIMIT ) {
493 my $command = sprintf q{dig @%s %s%s %s}, $self->address->short, $flags{dnssec} ? q{+dnssec } : q{},
494 "$name", $type;
495 Zonemaster::Engine->logger->add(
496 PACKET_BIG => { size => $size, command => $command } );
497 }
498 Zonemaster::Engine->logger->add( EXTERNAL_RESPONSE => { packet => $p->string } );
499 return $p;
500 }
501 else {
502 Zonemaster::Engine->logger->add( EMPTY_RETURN => {} );
503 return;
504 }
505 } ## end sub _query
506  
507 sub string {
508 return $_[0]->{_string};
509 }
510  
511 sub compare {
512 my ( $self, $other, $reverse ) = @_;
513  
514 return $self->string cmp $other->string;
515 }
516  
517 sub save {
518 my ( $class, $filename ) = @_;
519  
520 my $old = POSIX::setlocale( POSIX::LC_ALL, 'C' );
521 my $json = JSON::PP->new->allow_blessed->convert_blessed;
522 $json = $json->canonical( 1 );
523  
524 open my $fh, '>', $filename or die "Cache save failed: $!";
525 foreach my $name ( sort keys %object_cache ) {
526 foreach my $addr ( sort keys %{ $object_cache{$name} } ) {
527 say $fh "$name $addr " . $json->encode( $object_cache{$name}{$addr}->cache->data );
528 }
529 }
530  
531 close $fh or die $!;
532  
533 Zonemaster::Engine->logger->add( SAVED_NS_CACHE => { file => $filename } );
534  
535 POSIX::setlocale( POSIX::LC_ALL, $old );
536 return;
537 }
538  
539 sub restore {
540 my ( $class, $filename ) = @_;
541  
542 useall 'Zonemaster::LDNS::RR';
543 my $decode = JSON::PP->new->filter_json_single_key_object(
544 'Zonemaster::LDNS::Packet' => sub {
545 my ( $ref ) = @_;
546 ## no critic (Modules::RequireExplicitInclusion)
547 my $obj = Zonemaster::LDNS::Packet->new_from_wireformat( decode_base64( $ref->{data} ) );
548 $obj->answerfrom( $ref->{answerfrom} );
549 $obj->timestamp( $ref->{timestamp} );
550  
551 return $obj;
552 }
553 )->filter_json_single_key_object(
554 'Zonemaster::Engine::Packet' => sub {
555 my ( $ref ) = @_;
556  
557 return Zonemaster::Engine::Packet->new( { packet => $ref } );
558 }
559 );
560  
561 my $cache_type = Zonemaster::Engine::Nameserver::Cache->get_cache_type( Zonemaster::Engine::Profile->effective );
562 my $cache_class = Zonemaster::Engine::Nameserver::Cache->get_cache_class( $cache_type );
563  
564 open my $fh, '<', $filename or die "Failed to open restore data file: $!\n";
565 while ( my $line = <$fh> ) {
566 my ( $name, $addr, $data ) = split( / /, $line, 3 );
567 my $ref = $decode->decode( $data );
568 my $ns = Zonemaster::Engine::Nameserver->new(
569 {
570 name => $name,
571 address => Net::IP::XS->new($addr),
572 cache => $cache_class->new( { data => $ref, address => Net::IP::XS->new( $addr ) } )
573 }
574 );
575 }
576 close $fh;
577  
578 Zonemaster::Engine->logger->add( RESTORED_NS_CACHE => { file => $filename } );
579  
580 return;
581 } ## end sub restore
582  
583 sub max_time {
584 my ( $self ) = @_;
585  
586 return max( @{ $self->times } ) // 0;
587 }
588  
589 sub min_time {
590 my ( $self ) = @_;
591  
592 return min( @{ $self->times } ) // 0;
593 }
594  
595 sub sum_time {
596 my ( $self ) = @_;
597  
598 return sum( @{ $self->times } ) // 0;
599 }
600  
601 sub average_time {
602 my ( $self ) = @_;
603  
604 return 0 if @{ $self->times } == 0;
605  
606 return ( $self->sum_time / scalar( @{ $self->times } ) );
607 }
608  
609 sub median_time {
610 my ( $self ) = @_;
611  
612 my @t = sort { $a <=> $b } @{ $self->times };
613 my $c = scalar( @t );
614 if ( $c == 0 ) {
615 return 0;
616 }
617 elsif ( $c % 2 == 0 ) {
618 return ( $t[ $c / 2 ] + $t[ ( $c / 2 ) - 1 ] ) / 2;
619 }
620 else {
621 return $t[ int( $c / 2 ) ];
622 }
623 }
624  
625 sub stddev_time {
626 my ( $self ) = @_;
627  
628 my $avg = $self->average_time;
629 my $c = scalar( @{ $self->times } );
630  
631 return 0 if $c == 0;
632  
633 return sqrt( sum( map { ( $_ - $avg )**2 } @{ $self->times } ) / $c );
634 }
635  
636 sub all_known_nameservers {
637 my @res;
638  
639 foreach my $n ( values %object_cache ) {
640 push @res, values %{$n};
641 }
642  
643 return @res;
644 }
645  
646 sub axfr {
647 my ( $self, $domain, $callback, $class ) = @_;
648 $class //= 'IN';
649  
650 if ( Zonemaster::Engine::Profile->effective->get( q{no_network} ) ) {
651 croak sprintf
652 "External AXFR query for %s attempted to %s while running with no_network",
653 $domain, $self->string;
654 }
655  
656 if ( $self->address->version == 4 and not Zonemaster::Engine::Profile->effective->get( q{net.ipv4} ) ) {
657 Zonemaster::Engine->logger->add( IPV4_BLOCKED => { ns => $self->string } );
658 return;
659 }
660  
661 if ( $self->address->version == 6 and not Zonemaster::Engine::Profile->effective->get( q{net.ipv6} ) ) {
662 Zonemaster::Engine->logger->add( IPV6_BLOCKED => { ns => $self->string } );
663 return;
664 }
665  
666 return $self->dns->axfr( $domain, $callback, $class );
667 } ## end sub axfr
668  
669 sub source_address {
670 my ( $self ) = @_;
671  
672 my $src_address = Zonemaster::Engine::Profile->effective->get( "resolver.source" . Net::IP::XS::ip_get_version( $self->address->ip ) );
673  
674 return $src_address eq '' ? undef : $src_address;
675 }
676  
677 sub empty_cache {
678 %object_cache = ();
679 %address_object_cache = ();
680 %address_repr_cache = ();
681  
682 Zonemaster::Engine::Nameserver::Cache::empty_cache();
683  
684 return;
685 }
686  
687 1;
688  
689 =head1 NAME
690  
691 Zonemaster::Engine::Nameserver - object representing a DNS nameserver
692  
693 =head1 SYNOPSIS
694  
695 my $ns = Zonemaster::Engine::Nameserver->new({ name => 'ns.nic.se', address => '212.247.7.228' });
696 my $p = $ns->query('www.iis.se', 'AAAA');
697  
698 =head1 DESCRIPTION
699  
700 This is a very central object in the L<Zonemaster::Engine> framework. All DNS
701 communications with the outside world pass through here, so we can do
702 things like synthesizing and recording traffic. All the objects are
703 also unique per name/IP pair, and creating a new one with an already
704 existing pair will return the existing object instead of creating a
705 new one. Queries and their responses are cached by IP address, so that
706 a specific query will only be sent once to each address (even if there
707 are multiple objects for that address with different names).
708  
709 Class methods on this class allows saving and loading cache contents.
710  
711 =head1 ATTRIBUTES
712  
713 =over
714  
715 =item name
716  
717 A L<Zonemaster::Engine::DNSName> object holding the nameserver's name.
718  
719 =item address
720  
721 A L<Net::IP::XS> object holding the nameserver's address.
722  
723 =item dns
724  
725 The L<Zonemaster::LDNS> object used to actually send and receive DNS queries.
726  
727 =item cache
728  
729 A reference to a L<Zonemaster::Engine::Nameserver::Cache> object holding the cache of sent queries. Not meant for external use.
730  
731 =item times
732  
733 A reference to a list with elapsed time values for the queries made through this nameserver.
734  
735 =item blacklisted
736  
737 A reference to a hash used to prevent sending subsequent queries to the name server after specific queries have failed.
738  
739 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
740 on a per query basis with L<blacklisting_disabled>, or globally with L<Zonemaster::Engine::Constants/$BLACKLISTING_ENABLED>.
741  
742 =back
743  
744 =head1 CLASS METHODS
745  
746 =over
747  
748 =item new
749  
750 Construct a new object.
751  
752 =item save($filename)
753  
754 Save the entire object cache to the given filename, using the
755 byte-order-independent Storable format.
756  
757 =item restore($filename)
758  
759 Replace the entire object cache with the contents of the named file.
760  
761 =item all_known_nameservers()
762  
763 Class method that returns a list of all nameserver objects in the global cache.
764  
765 =item empty_cache()
766  
767 Remove all cached nameserver objects and queries.
768  
769 =back
770  
771 =head1 INSTANCE METHODS
772  
773 =over
774  
775 =item query($name, $type, $flagref)
776  
777 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
778 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.
779 The available flags are as follows. All but 'class' and 'edns_details' directly correspond to methods in the L<Zonemaster::LDNS> object.
780  
781 =over
782  
783 =item class
784  
785 Defaults to 'IN' if not set.
786  
787 =item usevc
788  
789 Send the query via TCP (only).
790  
791 =item retrans
792  
793 The retransmission interval.
794  
795 =item dnssec
796  
797 Set the DO flag in the query. Defaults to false.
798  
799 If set to true, it becomes an EDNS query.
800 Value overridden by C<edns_details{do}> (if also given). More details in L<edns_details> below.
801  
802 =item debug
803  
804 Set the debug flag in the resolver, producing output on STDERR as the query process proceeds.
805  
806 =item recurse
807  
808 Set the RD flag in the query.
809  
810 =item timeout
811  
812 Set the timeout for the outgoing sockets. May or may not be observed by the underlying network stack.
813  
814 =item retry
815  
816 Set the number of times the query is tried.
817  
818 =item igntc
819  
820 If set to true, incoming response packets with the TC flag set are not automatically retried over TCP.
821  
822 =item fallback
823  
824 If set to true, incoming response packets with the TC flag set fall back to EDNS and/or TCP.
825  
826 =item blacklisting_disabled
827  
828 If set to true, prevents a name server from being blacklisted.
829  
830 =item edns_size
831  
832 Set the EDNS0 UDP maximum size. The value must be comprised between 0 and 65535.
833 Defaults to 0, or 512 if the query is a non-DNSSEC EDNS query, or 1232 if the query is a DNSSEC query.
834  
835 Setting a value other than 0 will also implicitly enable EDNS for the query.
836 Value overridden by C<edns_details-E<gt>{size}> (if also given). More details in L<edns_details> below.
837  
838 =item edns_details
839  
840 A hash. An empty hash or a hash with any keys below will enable EDNS for the query.
841  
842 The currently supported keys are 'version', 'z', 'do', 'rcode', 'size' and 'data'.
843 See L<Zonemaster::LDNS::Packet> for more details (key names prefixed with 'edns_').
844  
845 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
846 latter will take precedence if both are given.
847  
848 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
849 latter will take precedence if both are given.
850  
851 =back
852  
853 =item string()
854  
855 Returns a string representation of the object. Normally this is just the name and IP address separated by a slash.
856  
857 =item compare($other)
858  
859 Used for overloading comparison operators.
860  
861 =item sum_time()
862  
863 Returns the total time spent sending queries and waiting for responses.
864  
865 =item min_time()
866  
867 Returns the shortest time spent on a query.
868  
869 =item max_time()
870  
871 Returns the longest time spent on a query.
872  
873 =item average_time()
874  
875 Returns the average time spent on queries.
876  
877 =item median_time()
878  
879 Returns the median query time.
880  
881 =item stddev_time()
882  
883 Returns the standard deviation for the whole set of query times.
884  
885 =item add_fake_delegation($domain,$data)
886  
887 Adds fake delegation information to this specific nameserver object. Takes the
888 same arguments as the similarly named method in L<Zonemaster::Engine>. This is
889 primarily used for internal information, and using it directly will likely give
890 confusing results (but may be useful to model certain kinds of
891 misconfigurations).
892  
893 =item add_fake_ds($domain, $data)
894  
895 Adds fake DS information to this nameserver object. Takes the same arguments as
896 the similarly named method in L<Zonemaster::Engine>.
897  
898 =item axfr( $domain, $callback, $class )
899  
900 Does an AXFR for the requested domain from the nameserver. The callback
901 function will be called once for each received RR, with that RR as its only
902 argument. To continue getting more RRs, the callback must return a true value.
903 If it returns a true value, the AXFR will be aborted. See L<Zonemaster::LDNS::axfr>
904 for more details.
905  
906 =item source_address()
907  
908 my $src_address = source_address();
909  
910 Returns the configured IPv4 or IPv6 source address to be used by the underlying DNS resolver for sending queries,
911 or C<undef> if the source address is the empty string.
912  
913 =item empty_cache()
914  
915 Clears the caches of Zonemaster::Engine::Nameserver (name server names and IP addresses) and Zonemaster::Engine::Nameserver::Cache (query and response packets) objects.
916  
917 =back
918  
919 =cut
« Zonemaster/Engine.pm ↑ Summary