2 # IP Address block list / checker
4 # This is a DXSpider compatible, optional skin over Net::CIDR::Lite
5 # If Net::CIDR::Lite is not present, then a find will always returns 0
20 use Socket qw(AF_INET AF_INET6 inet_pton inet_ntop);
23 our $badipfn = "badip";
31 return localdata($badipfn);
38 $fn .= ".$suffix" if $suffix;
39 my $fh = IO::File->new($fn);
51 LogDbg('err', "DXCIDR: $fn read error ($!)");
59 my @in = _read($suffix);
60 return scalar add(@in);
66 my $fn = _fn() . ".$suffix";
68 my $fh = IO::File->new (">$fn.$r");
71 for ($ipv4->list, $ipv6->list) {
76 LogDbg('cmd', "DXCIDR: put (re-)written $fn");
78 LogDbg('err', "DXCIDR: cannot write $fn.$r $!");
90 my $fn = _fn() . ".$suffix";
92 my $fh = IO::File->new (">>$fn.$r");
94 print $fh "$_\n" for @in;
98 LogDbg('err', "DXCIDR::append error appending to $fn.$r $!");
101 LogDbg('err', "DXCIDR::append require badip suffix");
111 # protect against stupid or malicious
112 next if $ip =~ /^127\./;
113 next if $ip =~ /^::1$/;
118 } elsif ($ip =~ /:/) {
123 LogDbg('err', "DXCIDR::add non-ip address '$ip' read");
131 if ($ipv4 && $count4) {
135 if ($ipv6 && $count6) {
146 push @in, [inet_pton(m|:|?AF_INET6:AF_INET, $_), split m|/|];
148 @out = sort {$a->[0] <=> $b->[0]} @in;
149 return map { "$_->[1]/$_->[2]"} @out;
155 push @out, $ipv4->list if $count4;
156 push @out, $ipv6->list if $count6;
162 return 0 unless $active;
163 return 0 unless $_[0];
166 return $ipv4->find($_[0]) if $count4;
168 return $ipv6->find($_[0]) if $count6;
173 eval { require Net::CIDR::Lite };
175 LogDbg('DXProt', "DXCIDR: load (cpanm) the perl module Net::CIDR::Lite to check for bad IP addresses (or CIDR ranges)");
179 import Net::CIDR::Lite;
184 move $fn, "$fn.base";
198 utime ($now, $now, $fn) || open (TMP, ">>$fn") || LogDbg('err', "DXCIDR::touch: Couldn't touch $fn: $!");
208 LogDbg('DXProt', "DXCIDR::reload reload database" );
211 opendir($dir, $main::local_data);
212 while (my $fn = readdir $dir) {
213 next unless my ($suffix) = $fn =~ /^badip\.(\w+)$/;
214 my $c = _load($suffix);
215 LogDbg('DXProt', "DXCIDR::reload: $fn read containing $c ip addresses" );
221 LogDbg('DXProt', "DXCIDR::reload $count ip addresses found (IPV4: $count4 IPV6: $count6) in $files badip files" );
228 $ipv4 = Net::CIDR::Lite->new;
229 $ipv6 = Net::CIDR::Lite->new;
230 $count4 = $count6 = 0;