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);
52 LogDbg('err', "DXCIDR: $fn read error ($!)");
60 my @in = _read($suffix);
61 return scalar add(@in);
67 my $fn = _fn() . ".$suffix";
69 my $fh = IO::File->new (">$fn.$r");
72 for ($ipv4->list, $ipv6->list) {
77 LogDbg('cmd', "DXCIDR: put (re-)written $fn");
79 LogDbg('err', "DXCIDR: cannot write $fn.$r $!");
86 return 0 unless $active;
93 my $fn = _fn() . ".$suffix";
94 my $fh = IO::File->new;
95 if ($fh->open("$fn", "a+")) {
96 $fh->seek(0, 2); # belt and braces !!
97 print $fh "$_\n" for @in;
100 LogDbg('err', "DXCIDR::append error appending to $fn $!");
103 LogDbg('err', "DXCIDR::append require badip suffix");
110 return 0 unless $active;
114 # protect against stupid or malicious
115 next if $ip =~ /^127\./;
116 next if $ip =~ /^::1$/;
121 } elsif ($ip =~ /:/) {
126 LogDbg('err', "DXCIDR::add non-ip address '$ip' read");
134 return unless $active;
136 if ($ipv4 && $count4) {
140 if ($ipv6 && $count6) {
151 push @in, [inet_pton(m|:|?AF_INET6:AF_INET, $_), split m|/|];
153 @out = sort {$a->[0] <=> $b->[0]} @in;
154 return map { "$_->[1]/$_->[2]"} @out;
159 return () unless $active;
161 push @out, $ipv4->list if $count4;
162 push @out, $ipv6->list if $count6;
168 return 0 unless $active;
169 return 0 unless $_[0];
172 return $ipv4->find($_[0]) if $count4;
174 return $ipv6->find($_[0]) if $count6;
179 eval { require Net::CIDR::Lite };
181 LogDbg('DXProt', "DXCIDR: load (cpanm) the perl module Net::CIDR::Lite to check for bad IP addresses (or CIDR ranges)");
185 import Net::CIDR::Lite;
190 move $fn, "$fn.base";
204 utime ($now, $now, $fn) || open (TMP, ">>$fn") || LogDbg('err', "DXCIDR::touch: Couldn't touch $fn: $!");
209 return 0 unless $active;
216 LogDbg('DXProt', "DXCIDR::reload reload database" );
219 opendir($dir, $main::local_data);
220 while (my $fn = readdir $dir) {
221 next unless my ($suffix) = $fn =~ /^badip\.(\w+)$/;
222 my $c = _load($suffix);
223 LogDbg('DXProt', "DXCIDR::reload: $fn read containing $c ip addresses" );
229 LogDbg('DXProt', "DXCIDR::reload $count ip addresses found (IPV4: $count4 IPV6: $count6) in $files badip files" );
236 return 0 unless $active;
238 $ipv4 = Net::CIDR::Lite->new;
239 $ipv6 = Net::CIDR::Lite->new;
240 $count4 = $count6 = 0;