blib/lib/Net/Blacklist/Client.pm untested

filter: Statementstmt 0.0% 0 / 111 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 27 MC/DCmcdc 0.0% 0 / 14 Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 218 CC 18 SCAR 30.4
CC
18
Cov
0%
collect_responses
56.0
decode_packet
42.0
new
12.0
CRAP 20.9
1 package Net::Blacklist::Client;
2  
3 # Many thanks to Asher Blum <asher@wildspark.com> for the original
4 # Net::RBLClient, from which this module unashamedly steals.
5  
6 use strict;
7 use warnings;
8  
9 use IO::Socket;
10 use Time::HiRes qw(time);
11 use Net::DNS::Packet;
12  
13 use vars qw($VERSION $ip_re $domain_re);
14 $ip_re = qr(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3});
15 $domain_re = qr([a-zA-Z0-9-]{1,63}(?:\.[a-zA-Z0-9-]{1,63})*\.[a-zA-Z0-9]{1,6});
16  
17 $VERSION = '0.3';
18  
19 sub new {
20 my($class, %args) = @_;
21 my $self = {
22 lists_domain => [ lists_domain() ],
23 lists_ip => [ lists_ip() ],
24 query_txt => 1,
25 max_time => 8,
26 timeout => 1,
27 max_hits => 1000,
28 max_replies => 1000,
29 udp_maxlen => 4000,
30 server => 'resolv.conf',
31 };
32 bless($self, $class);
33  
34 foreach my $key (keys %args) {
35 defined($self->{$key}) or die "Invalid key: $key";
36 $self->{$key} = $args{$key};
37 }
38  
39 # Read the contents of resolv.conf and set the server to the first
40 # nameserver we find listed, if the server is set to 'resolv.conf'
41 if ($self->{server} eq 'resolv.conf'){
42 open my $resolv_fh, '/etc/resolv.conf' or die "Can't open resolv.conf: $!";
43 local $/;
44 my $resolv = <$resolv_fh>;
45  
46 if ($resolv =~ /^nameserver\s+($ip_re)/m){
47 $self->{server} = $1;
48 }else{
49 die "No nameserver found in resolv.conf; specify a nameserver IP in constructor";
50 }
51 }
52 return $self;
53 }
54  
55 sub lookup_domain{
56 my ($self, $domain) = @_;
57 die "Do not recognise domain '$domain'" unless $domain =~ /^$domain_re$/;
58 return $self->lookup_all(lc($domain), $self->{lists_domain});
59 }
60 sub lookup_ip{
61 my ($self, $ip) = @_;
62 die "Do not recognise IP address '$ip'" unless $ip =~ /^$ip_re$/;
63 my $reverse_ip = join '.', reverse split(/\./, $ip);
64 return $self->lookup_all($reverse_ip, $self->{lists_ip});
65 }
66  
67 sub lookup_all{
68 my ($self, $partial, $lists) = @_;
69 foreach my $list (@$lists){
70 my $query = join '.', ($partial, $list);
71  
72 # Send the A lookup
73 $self->send_packet_a($query);
74  
75 # optionally send the TXT lookup
76 if ($self->{query_txt}){
77 $self->send_packet_txt($query);
78 }
79 }
80 return $self->collect_responses;
81 }
82  
83 sub collect_responses{
84 my ($self) = @_;
85  
86 my $hits = my $replies = 0;
87 my $deadline = time + $self->{max_time};
88 my $results = {};
89  
90 # Continue receiving packets until:
91 # * There are no more pending
92 # * The timeout is exceeded
93 # * Max hits or max replies are met
94 while ($self->{_pending} > 0 && time < $deadline) {
95 my $msg = '';
96 eval{
97 local $SIG{ALRM} = sub{ die "alarm time out" };
98 alarm $self->{timeout};
99 $self->sock->recv($msg, $self->{udp_maxlen}) || die "recv: $!";
100 alarm 0;
101 1;
102 };
103 if ($msg){
104 my ($domain, $res, $type) = decode_packet($msg);
105 if (defined $type && $type eq 'TXT' && $self->{query_txt}) {
106 $results->{$domain}{txt} = $res;
107 }elsif ($res){
108 $replies++;
109 $hits++ if $res;
110 if ($self->{query_txt}){
111 $results->{$domain}{a} = $res;
112 }else{
113 $results->{$domain} = $res;
114 }
115 return 1 if $hits >= $self->{max_hits} ||
116 $replies >= $self->{max_replies};
117 }
118 $self->{_pending}--;
119 }
120 }
121 $self->{_pending} = 0;
122 return $results;
123 }
124  
125  
126 sub decode_packet{
127 # takes a raw DNS response packet
128 # returns domain, response
129 my $data = shift;
130 my $packet = Net::DNS::Packet->new(\$data);
131 my @answer = $packet->answer;
132 {
133 my ($res, $domain, $type);
134 foreach my $answer (@answer) {
135 {
136 # removed $answer->answerfrom because it caused an error
137 # with some types of answers
138  
139 my $name = lc $answer->name;
140 #warn "Packet contained answers to different domains ($domain != $name)"
141 # if defined $domain && $name ne $domain;
142 $domain = $name;
143 }
144 $domain =~ s/^\d+\.\d+\.\d+\.\d+\.//;
145 $type = $answer->type;
146 $res = $type eq 'A' ? inet_ntoa($answer->rdata) :
147 $type eq 'CNAME' ? cleanup($answer->rdata) :
148 $type eq 'TXT' ? (defined $res && "$res; ")
149 . $answer->txtdata :
150 '?';
151 last unless $type eq 'TXT';
152 }
153 return $domain, $res, $type if defined $res;
154 }
155
156 # OK, there were no answers -
157 # need to determine which domain
158 # sent the packet.
159  
160 my @question = $packet->question;
161 foreach my $question(@question) {
162 my $domain = $question->qname;
163 $domain =~ s/^\d+\.\d+\.\d+\.\d+\.//;
164 return ($domain, undef);
165 }
166 }
167  
168 sub cleanup {
169 # remove control chars and stuff
170 $_[ 0 ] =~ tr/a-zA-Z0-9./ /cs;;
171 $_[ 0 ];
172 }
173  
174  
175 # Packet generation
176 sub send_packet_a{
177 my ($self, $query) = @_;
178 $self->send_packet($query, 'A');
179 }
180 sub send_packet_txt{
181 my ($self, $query) = @_;
182 $self->send_packet($query, 'TXT', 'IN');
183 }
184 sub send_packet{
185 my ($self, $query, @pkt_args) = @_;
186 my ($packet, $error) = Net::DNS::Packet->new($query, @pkt_args);
187 die "Cannot build DNS query for $query, type $pkt_args[0]: $error" unless $packet;
188 $self->sock->send($packet->data) || die "Could not sent $pkt_args[0] packet for query '$query': $!";
189 $self->{_pending}++;
190 }
191  
192 # returns a UDP socket connected to the specified server
193 sub sock{
194 my ($self) = @_;
195 $self->{_sock} ||= IO::Socket::INET->new(
196 Proto => 'udp',
197 PeerPort => 53,
198 PeerAddr => $self->{server},
199 ) or die "Failed to create UDP client";
200 return $self->{_sock};
201 }
202  
203  
204 # Lists of lists..
205  
206 sub lists_domain{
207 return qw(
208 multi.uribl.com
209 multi.surbl.org
210 );
211 }
212  
213 sub lists_ip{
214 return qw(
215 0spam.fusionzero.com
216 dnsbl.ahbl.org
217 opm.blitzed.org
218 cbl.abuseat.org
219 bl.csma.biz
220 sbl.csma.biz
221 dnsbl.cyberlogic.net
222 bl.deadbeef.com
223 spamsources.dnsbl.info
224 dnsbl.net.au
225 t1.dnsbl.net.au
226 dun.dnsrbl.net
227 spam.dnsrbl.net
228 list.dsbl.org
229 unconfirmed.dsbl.org
230 multihop.dsbl.org
231 spamsources.fabel.dk
232 blackholes.five-ten-sg.com
233 hil.habeas.com
234 blocked.hilli.dk
235 blackholes.intersil.net
236 ipwhois.rfc-ignorant.org
237 dnsbl.jammconsulting.com
238 3y.spam.mrs.kithrup.com
239 relays.bl.kundenserver.de
240 spamguard.leadmon.net
241 relays.nether.net
242 unsure.nether.net
243 combined.njabl.org
244 no-more-funn.moensted.dk
245 dnsbl.antispam.or.id
246 relays.ordb.org
247 psbl.surriel.com
248 dnsbl.rangers.eu.org
249 access.redhawk.org
250 dnsbl.regedit64.net
251 relays.visi.com
252 sbbl.they.com
253 sbl.spamhaus.org
254 xbl.spamhaus.org
255 rbl.snark.net
256 dnsbl.solid.net
257 dnsbl.sorbs.net
258 blacklist.spambag.org
259 bl.spamcannibal.org
260 bl.spamcop.net
261 map.spam-rbl.com
262 bl.spamthwart.com
263 l1.spews.dnsbl.sorbs.net
264 l2.spews.dnsbl.sorbs.net
265 block.dnsbl.sorbs.net
266 bl.technovision.dk
267 blackholes.uceb.org
268 dnsbl-1.uceprotect.net
269 dnsbl-2.uceprotect.net
270 virbl.dnsbl.bit.nl
271 vox.schpider.com
272 db.wpbl.info
273 ubl.unsubscore.com
274 dnsbl.tqmcube.com
275 abuse.rfc-ignorant.org
276 bogusmx.rfc-ignorant.org
277 dsn.rfc-ignorant.org
278 postmaster.rfc-ignorant.org
279 whois.rfc-ignorant.org
280 ex.dnsbl.org
281 in.dnsbl.org
282 unconfirmed.dsbl.org
283 list.dsbl.org
284 );
285 }
286  
287 =head1 NAME
288  
289 Net::Blacklist::Client - Queries multiple RBLs or URIBLs in parallel.
290  
291 =head1 SYNOPSIS
292  
293 use Net::Blacklist::Client;
294 my $rbl = Net::Blacklist::Client->new;
295 my $result = $rbl->lookup_ip('127.0.0.2');
296 foreach my $list (keys %$result){
297 printf "%s: %s (%s)\n", $list, $result->{$list}->{a}, $result->{$list}->{txt};
298 }
299  
300 =head1 DESCRIPTION
301  
302 This module is used to discover what RBL's are listing a particular IP
303 address. It parallelizes requests for fast response.
304  
305 This module is heavily based on L<Net::RBLClient> by Asher Blum. It adds
306 an updated list of RBLs and removes many dead ones, the ability to look
307 up domains in domain-specific RBLs, and changes the output format.
308 Although it is very similar and does the same job, due to the changes in
309 the output formats, it is not suitable as a drop-in replacement.
310  
311 An RBL, or Realtime Blackhole List, is a list of IP addresses meeting some
312 criteria such as involvement in Unsolicited Bulk Email. Each RBL has
313 its own criteria for addition and removal of addresses. If you want to
314 block email or other traffic to/from your network based on one or more
315 RBLs, you should carefully study the behavior of those RBLs before and
316 during such blocking.
317  
318 =head1 CONSTRUCTOR
319  
320 =over 4
321  
322 =item new( [ARGS] )
323  
324 Takes an optional hash of arguments:
325  
326 =over 4
327  
328 =item lists_ip
329  
330 An arraref of domains representing IP address RBL root domains. Each element
331 in the array should be a string representing the root domain for the RBL you
332 wish to use, for example 'bl.spamcop.net' is the root domain of Spamcop's
333 blacklist. Use this if you want to query a specific list of RBLs - if this
334 argument is omitted, a large list of default RBLs is used.
335  
336 =item lists_domain
337  
338 Similar to lists_ip, but these are used when querying domains with
339 lookup_domain. Note that IP and domain RBLs are usually separate, so using
340 a list of IP RBLs to check domains is a bad plan. Currently, the URIBL and
341 SURBL services are used by default.
342  
343 =item query_txt
344  
345 This option controls whether Net::Blacklist::Client looks up corresponding
346 TXT records. The TXT record is used by many RBL's store additional
347 information about the reason for including an IP address or links to pages
348 that contain such information.
349  
350 Default: True
351  
352 =item max_time
353  
354 The maximum time in seconds that the lookup function should take. In fact,
355 the function can take up to C<max_time + timeout> seconds. Max_time need
356 not be integer. Of course, if the lookup returns due to max_time, some
357 DNS replies will be missed.
358  
359 Default: 8 seconds.
360  
361 =item timeout
362  
363 The maximum time in seconds spent awaiting each DNS reply packet. The
364 only reason to change this is if C<max_time> is decreased to a small value.
365  
366 Default: 1 second.
367  
368 =item max_hits
369  
370 A hit is an affirmative response, stating that the IP address is on a certain
371 list. If C<max_hits> hits are received, C<lookup()> returns immediately.
372 This lets the calling program save time.
373  
374 Default: 1000 (effectively out of the picture).
375  
376 =item max_replies
377  
378 A reply from an RBL could be affirmative or negative. Either way, it counts
379 towards C<max_replies>. C<Lookup()> returns when C<max_replies> replies
380 have been received.
381  
382 =item udp_maxlen
383  
384 The maximum number of bytes read from a DNS reply packet. There's probably
385 no reason to change this.
386  
387 Default: 4000
388  
389 =item server
390  
391 The local nameserver to use for all queries. Should be either a resolvable
392 hostname or a dotted quad IP address.
393  
394 By default, the first nameserver in /etc/resolv.conf will be used.
395  
396 =back
397  
398 =head1 METHODS
399  
400 =item lookup_ip( IPADDR )
401  
402 Lookup one IP address on all RBL's previously defined. The IP address
403 must be expressed in dotted quad notation, like '1.2.3.4'. C<lookup_ip>
404 returns a reference to a hash with each list the IP appears on as keys.
405 The values depend on the status of the C<query_txt> constructor option, if
406 it is enabled, than a the value of the hash returned by C<lookup_ip> will
407 by a hashref with the keys C<a> and C<txt>, containing the A and TXT
408 records returned by the RBL. If it is disabled then the value is simply
409 set to the IP address returned by the A record request.
410  
411 =item lookup_domain( DOMAIN )
412  
413 Exactly the same as C<lookup_ip>, except it accepts a domain, and uses
414 a different list of domain-specific RBLs. The hash reference returned is
415 in exactly the same format.
416  
417 =back
418  
419 =head1 AUTHOR
420  
421 Dan Thomas E<lt>F<dan@cpan.org>E<gt>
422  
423 Based on L<Net::RBLClient> by Asher Blum E<lt>F<asher@wildspark.com>E<gt>
424  
425 =head1 COPYRIGHT
426  
427 Copyright (C) 2007 Dan Thomas. The original Net::RBLClient is Copyright
428 (C) 2002 Asher Blum. All rights reserved.
429  
430 This code is free software; you can redistribute it and/or modify it under
431 the same terms as Perl itself.
432  
433 =cut
434  
435 1;