| 1 | package Zonemaster::ASNLookup v1.0.0; | ||
| 2 | |||
| 3 | use 5.014002; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Net::IP::XS; | ||
| 7 | |||
| 8 | use Zonemaster; | ||
| 9 | use Zonemaster::Nameserver; | ||
| 10 | |||
| 11 | our @roots; | ||
| 12 | |||
| 13 | sub get_with_prefix { | ||
| 14 | my ( $class, $ip ) = @_; | ||
| 15 | |||
| 16 | if ( not @roots ) { | ||
| 17 | @roots = map { Zonemaster->zone( $_ ) } @{ Zonemaster->config->asnroots }; | ||
| 18 | } | ||
| 19 | |||
| 20 | if ( not ref( $ip ) or not $ip->isa( 'Net::IP::XS' ) ) { | ||
| 21 | $ip = Net::IP::XS->new( $ip ); | ||
| 22 | } | ||
| 23 | |||
| 24 | my $reverse = $ip->reverse_ip; | ||
| 25 | foreach my $zone ( @roots ) { | ||
| 26 | my $domain = $zone->name->string; | ||
| 27 | my $pair = { | ||
| 28 | 'in-addr.arpa.' => "origin.$domain", | ||
| 29 | 'ip6.arpa.' => "origin6.$domain", | ||
| 30 | }; | ||
| 31 | foreach my $root ( keys %$pair ) { | ||
| 32 | if ( $reverse =~ s/$root/$pair->{$root}/i ) { | ||
| 33 | my $p = $zone->query_persistent( $reverse, 'TXT' ); | ||
| 34 | next if not $p; | ||
| 35 | |||
| 36 | my ( $rr ) = $p->get_records( 'TXT' ); | ||
| 37 | return if not $rr; | ||
| 38 | |||
| 39 | my $str = $rr->txtdata; | ||
| 40 | $str =~ s/"([^"]+)"/$1/; | ||
| 41 | my @fields = split( / \| ?/, $str ); | ||
| 42 | my @asns = split( /\s+/, $fields[0] ); | ||
| 43 | |||
| 44 | return \@asns, Net::IP::XS->new( $fields[1] ); | ||
| 45 | } | ||
| 46 | } | ||
| 47 | } ## end foreach my $zone ( @roots ) | ||
| 48 | return; | ||
| 49 | } ## end sub get_with_prefix | ||
| 50 | |||
| 51 | sub get { | ||
| 52 | my ( $class, $ip ) = @_; | ||
| 53 | |||
| 54 | my ( $asnref, $prefix ) = $class->get_with_prefix( $ip ); | ||
| 55 | |||
| 56 | if ( $asnref ) { | ||
| 57 | return @$asnref; | ||
| 58 | } | ||
| 59 | else { | ||
| 60 | return; | ||
| 61 | } | ||
| 62 | } | ||
| 63 | |||
| 64 | 1; | ||
| 65 | |||
| 66 | =head1 NAME | ||
| 67 | |||
| 68 | Zonemaster::ASNLookup - do lookups of ASNs for IP addresses | ||
| 69 | |||
| 70 | =head1 SYNOPSIS | ||
| 71 | |||
| 72 | my ($asnref, $prefix) = Zonemaster::ASNLookup->get_with_prefix( '8.8.4.4' ); | ||
| 73 | my $asnref = Zonemaster::ASNLookup->get( '192.168.0.1' ); | ||
| 74 | |||
| 75 | =head1 FUNCTION | ||
| 76 | |||
| 77 | =over | ||
| 78 | |||
| 79 | =item get($addr) | ||
| 80 | |||
| 81 | Takes a string (or a L<Net::IP> object) with a single IP address, does a lookup | ||
| 82 | in a Cymru-style DNS zone and returns a list of AS numbers for the address, if | ||
| 83 | any can be found. | ||
| 84 | |||
| 85 | =item get_with_prefix($addr) | ||
| 86 | |||
| 87 | As L<get()>, except it returns a list of a reference to a list with the AS | ||
| 88 | numbers, and a Net::IP object representing the prefix of the AS. | ||
| 89 | |||
| 90 | =back | ||
| 91 | |||
| 92 | =cut |