Debian Codegraph @

plugins/uribl

raw
1 #!perl -w
2
3 =head1 NAME
4
5 uribl - URIBL blocking plugin for qpsmtpd
6
7 =head1 DESCRIPTION
8
9 This plugin implements DNSBL lookups for URIs found in spam, such as that
10 implemented by SURBL (see E<lt>http://surbl.org/E<gt>). Incoming messages are
11 scanned for URIs, which are then checked against one or more URIBLs in a
12 fashion similar to DNSBL systems.
13
14 =head1 CONFIGURATION
15
16 To enable the plugin, add it to I<~qpsmtpd/config/plugins>. The list of
17 URIBLs to check should be placed in I<uribl_zones> in the config directory
18 (typically I<~qpsmtpd/config>).
19
20 The format of the I<uribl_zones> file is a list of URIBL DNS zones, one per
21 line, consisting of one or more columns separated by whitespace. The first
22 column (the only mandatoy one) should consist of the URIBL zone.
23
24 The second column may contain a comma-delimited list of integers selecting
25 mask values to be applied to the A record(s) returned from a URIBL. This
26 enables the use of composite DNSBLs, such as multi.surbl.org, where several
27 lists are combined so they may be accessed with a single query; any returns
28 are checked against the mask of lists you're interested in. If unspecified,
29 or if a negative number is given, all lists in a composite URIBL will be
30 checked. URIBL operators prefer that you use the composite lists to reduce
31 their own query load, and it's more efficient for qpsmtpd as well.
32
33 The third column specifies an action, which overrides the default action
34 configured with the I<action> setting discussed below.
35
36 For example:
37
38 =over 4
39
40 multi.surbl.org 2,8 deny
41 ob.surbl.org 1 add-header
42
43 =back
44
45 You may specify the following config option(s) in the I<qpsmtpd/config> file:
46
47 =over 4
48
49 =item action
50
51 Specifies what to do when a URI is matched in a URIBL. Available options are
52 I<add-header> (the default) I<deny> and I<denysoft>. If set to add-header, an
53 X-URIBL-Match: header will be added explaining the URIBL entry found. If set
54 to 'deny,' the delivery will be declined with a hard failure. If set to
55 denysoft, the delivery will be soft failed (this is probably not a good idea.)
56
57 =item timeout
58
59 Timeout for DNS requests, in seconds. The default is 30 seconds. DNS
60 requests are issued asynchronously and in parallel for all hosts found
61 in URIs in the mail; the same timeout will apply to each; see the
62 Net::DNS documentation for details.
63
64 =item scan-headers
65
66 If set true, any headers found in the URIs will be checked as well. Disabled
67 by default.
68
69 =back
70
71 =head1 CAUTIONS
72
73 When used in I<deny> or I<denysoft> mode, a URIBL check can block not
74 only the original spam containing a listed URI, but mail unintentionally
75 carrying that URI, such as forwarded complaints. The uribl checks should
76 only be used in these modes if you know what you're doing.
77
78 The URI scanner used by the uribl plugin is quite aggressive, and attempts to
79 detect all forms of URIs supported by typical MUAs (even those that lack a
80 protocol specification, for example.) However, it does not attempt to detect
81 URIs that have been mangled beyond programmatic reconstruction. Even so, it
82 may issue spurious lookups on unintended URIs, especially those in non-text
83 sections of the mail.
84
85 =head1 COPYRIGHT
86
87 uribl is copyright 2004-2007 by Devin Carraway E<lt>[email protected]<gt>. It
88 may be used and redistributed under the same terms as qpsmtpd itself.
89
90 =cut
91
92 use strict;
93 use warnings;
94
95 use Qpsmtpd::Constants;
96
97 use Net::DNS::Resolver;
98 use Time::HiRes qw(time);
99 use IO::Select;
100
101 # ccTLDs that allocate domain names within a strict two-level hierarchy,
102 # as in *.co.uk
103 my %strict_twolevel_cctlds = (
104 'ac' => 1,
105 'ae' => 1,
106 'uk' => 1,
107 'ai' => 1,
108 'ar' => 1,
109 'at' => 1,
110 'au' => 1,
111 'az' => 1,
112 'bb' => 1,
113 'bh' => 1,
114 'bm' => 1,
115 'br' => 1,
116 'bs' => 1,
117 'ca' => 1,
118 'ck' => 1,
119 'cn' => 1,
120 'co' => 1,
121 'cr' => 1,
122 'cu' => 1,
123 'cy' => 1,
124 'do' => 1,
125 'et' => 1,
126 'ge' => 1,
127 'hk' => 1,
128 'id' => 1,
129 'il' => 1,
130 'jp' => 1,
131 'kr' => 1,
132 'kw' => 1,
133 'lv' => 1,
134 'sg' => 1,
135 'za' => 1,
136 );
137
138 # async version: OK
139 sub init {
140 my ($self, $qp, %args) = @_;
141
142 $self->{action} = $args{action} || 'add-header';
143 $self->{timeout} = $args{timeout} || 30;
144
145 # scan-headers was the originally documented name for this option, while
146 # check-headers actually implements it, so tolerate both.
147 $self->{check_headers} = $args{'check-headers'} || $args{'scan-headers'};
148
149 $args{mask} ||= 0x00ffffff;
150 $self->{mask} = 0;
151
152 my @zones = $self->qp->config('uribl_zones');
153 for (@zones) {
154 chomp;
155 next if !$_ or /^\s*#/;
156 my @z = split(/\s+/, $_);
157 next unless $z[0];
158
159 my $mask = 0;
160 $z[1] ||= 0x00ffffff;
161 for (split /,/, $z[1]) {
162 unless (/^(-?\d+)$/) {
163 $self->log(LOGERROR, "Malformed mask $_ for $z[0]");
164 return undef;
165 }
166 $mask |= $1 >= 0 ? $1 : 0x00ffffff;
167 }
168 my $action = $z[2] || $self->{action};
169 unless ($action =~ /^(add-header|deny|denysoft|log)$/) {
170 $self->log(LOGERROR, "Unknown action $action for $z[0]");
171 return undef;
172 }
173
174 $self->{uribl_zones}->{$z[0]} = {
175 mask => $mask,
176 action => $action,
177 };
178 }
179 keys %{$self->{uribl_zones}} or return 0;
180
181 my @whitelist = $self->qp->config('uribl_whitelist_domains');
182 $self->{whitelist_zones} = {(map { ($_ => 1) } @whitelist)};
183
184 $self->init_resolver;
185 }
186
187 # async version: not used
188 sub register {
189 my $self = shift;
190
191 $self->register_hook('data_post', 'data_handler');
192 }
193
194 # async version: not used
195 sub send_query {
196 my $self = shift;
197 my $name = shift || return undef;
198 my $count = 0;
199
200 $self->{socket_select} ||= new IO::Select or return undef;
201 for my $z (keys %{$self->{uribl_zones}}) {
202 my ($s, $s1);
203 my $index = {
204 zone => $z,
205 name => $name,
206 };
207
208 next unless $z;
209 next if exists $self->{sockets}->{$z}->{$name};
210 $s = $self->{resolver}->bgsend("$name.$z", 'A');
211 if (defined $s) {
212 $self->{sockets}->{$z}->{$name}->{'a'} = $s;
213 $self->{socket_select}->add($s);
214 $self->{socket_idx}->{"$s"} = $index;
215 $count++;
216 }
217 else {
218 $self->log(LOGERROR,
219 "Couldn't open socket for A record '$name.$z': "
220 . ($self->{resolver}->errorstring || 'unknown error')
221 );
222 }
223
224 $s1 = $self->{resolver}->bgsend("$name.$z", 'TXT');
225 if (defined $s1) {
226 $self->{sockets}->{$z}->{$name}->{'txt'} = $s1;
227 $self->{socket_select}->add($s1);
228 $self->{socket_idx}->{"$s1"} = $index;
229 $count++;
230 }
231 else {
232 $self->log(LOGERROR,
233 "Couldn't open socket for TXT record '$name.$z': "
234 . ($self->{resolver}->errorstring || 'unknown error')
235 );
236 }
237
238 $self->{sockets}->{$z}->{$name} = {};
239 }
240 $count;
241 }
242
243 # async version: not used
244 sub lookup_finish {
245 my $self = shift;
246 $self->{socket_idx} = {};
247 $self->{sockets} = {};
248 undef $self->{socket_select};
249 }
250
251 # async version: OK
252 sub evaluate {
253 my $self = shift;
254 my $zone = shift || return undef;
255 my $a = shift || return undef;
256
257 my $mask = $self->{uribl_zones}->{$zone}->{mask} || $self->{mask};
258 $a =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ or return undef;
259 my $v =
260 (($1 & 0xff) << 24) | (($2 & 0xff) << 16) | (($3 & 0xff) << 8) |
261 ($4 & 0xff);
262 return ($v & $mask);
263 }
264
265 # async version: OK
266 sub lookup_start {
267 my ($self, $transaction, $start_query) = @_;
268
269 my $l;
270 my $queries = 0;
271 my %pending;
272 my @qp_continuations;
273
274 $transaction->body_resetpos;
275
276 # if we're not looking for URIs in the headers, read past that point
277 # before starting to actually look for any
278 while (!$self->{check_headers} and $l = $transaction->body_getline) {
279 chomp $l;
280 last if !$l;
281 }
282 while ($l = $transaction->body_getline) {
283 chomp $l;
284
285 if ($l =~ /(.*)=$/) {
286 push @qp_continuations, $1;
287 }
288 elsif (@qp_continuations) {
289 $l = join('', @qp_continuations, $l);
290 @qp_continuations = ();
291 }
292
293 # Undo URI escape munging
294 $l =~ s/[=%]([0-9A-Fa-f]{2,2})/chr(hex($1))/ge;
295
296 # Undo HTML entity munging (e.g. in parameterized redirects)
297 $l =~ s/&#(\d{2,3});?/chr($1)/ge;
298
299 # Dodge inserted-semicolon munging
300 $l =~ tr/;//d;
301
302 while (
303 $l =~ m{
304 \w{3,16}:/+ # protocol
305 (?:\S+@)? # user/pass
306 (\d{7,}) # raw-numeric IP
307 (?::\d*)?([/?\s]|$) # port, slash
308 # or EOL
309 }gx
310 )
311 {
312 my @octets = (
313 (($1 >> 24) & 0xff),
314 (($1 >> 16) & 0xff),
315 (($1 >> 8) & 0xff),
316 ($1 & 0xff)
317 );
318 my $fwd = join('.', @octets);
319 my $rev = join('.', reverse @octets);
320 $self->log(LOGDEBUG,
321 "uribl: matched pure-integer ipaddr $1 ($fwd)");
322 unless (exists $pending{$rev}) {
323 $queries += $start_query->($self, $rev);
324 $pending{$rev} = 1;
325 }
326 }
327 while (
328 $l =~ m{
329 \w{3,16}:/+ # protocol
330 (?:\S+@)? # user/pass
331 (\d+|0[xX][0-9A-Fa-f]+)\. # IP address
332 (\d+|0[xX][0-9A-Fa-f]+)\.
333 (\d+|0[xX][0-9A-Fa-f]+)\.
334 (\d+|0[xX][0-9A-Fa-f]+)
335 }gx
336 )
337 {
338 my @octets = ($1, $2, $3, $4);
339
340 # return any octal/hex octets in the IP addr back
341 # to decimal form (e.g. http://0x7f.0.0.00001)
342 for (0 .. $#octets) {
343 $octets[$_] =~ s/^0([0-7]+)$/oct($1)/e;
344 $octets[$_] =~ s/^0x([0-9a-fA-F]+)$/hex($1)/e;
345 }
346 my $fwd = join('.', @octets);
347 my $rev = join('.', reverse @octets);
348 $self->log(LOGDEBUG, "uribl: matched URI ipaddr $fwd");
349 unless (exists $pending{$rev}) {
350 $queries += $start_query->($self, $rev);
351 $pending{$rev} = 1;
352 }
353 }
354 while (
355 $l =~ m{
356 ((?:www\.)? # www?
357 [a-zA-Z0-9][a-zA-Z0-9\-.]+\. # hostname
358 (?:aero|arpa|asia|biz|cat|com|coop| # tld
359 edu|gov|info|int|jobs|mil|mobi|
360 museum|name|net|org|pro|tel|travel|
361 [a-zA-Z]{2})
362 )(?!\w)
363 }gix
364 )
365 {
366 my $host = lc $1;
367 my @host_domains = split /\./, $host;
368 $self->log(LOGDEBUG, "uribl: matched 'www.' hostname $host");
369
370 my $cutoff =
371 exists $strict_twolevel_cctlds{$host_domains[$#host_domains]}
372 ? 3
373 : 2;
374 if (
375 exists $self->{whitelist_zones}->{
376 join('.',
377 @host_domains[($#host_domains - $cutoff + 1)
378 .. $#host_domains])
379 }
380 )
381 {
382 $self->log(LOGINFO, "Skipping whitelist URI domain '$host'");
383 }
384 else {
385 while (@host_domains >= $cutoff) {
386 my $subhost = join('.', @host_domains);
387 unless (exists $pending{$subhost}) {
388 $self->log(LOGINFO,
389 "URIBL: checking sub-host $subhost");
390 $queries += $start_query->($self, $subhost);
391 $pending{$subhost} = 1;
392 }
393 shift @host_domains;
394 }
395 }
396 }
397 while (
398 $l =~ m{
399 \w{3,16}:/+ # protocol
400 (?:\S+@)? # user/pass
401 (
402 [a-zA-Z0-9][a-zA-Z0-9\-.]+\. # hostname
403 (?:aero|arpa|asia|biz|cat|com|coop| # tld
404 edu|gov|info|int|jobs|mil|mobi|
405 museum|name|net|org|pro|tel|travel|
406 [a-zA-Z]{2})
407 )
408 }gix
409 )
410 {
411 my $host = lc $1;
412 my @host_domains = split /\./, $host;
413 $self->log(LOGDEBUG, "uribl: matched full URI hostname $host");
414
415 my $cutoff =
416 exists $strict_twolevel_cctlds{$host_domains[$#host_domains]}
417 ? 3
418 : 2;
419 if (
420 exists $self->{whitelist_zones}
421 ->{join('.', @host_domains[($cutoff - 1) .. $#host_domains])})
422 {
423
424 $self->log(LOGINFO, "Skipping whitelist URI domain '$host'");
425 }
426 else {
427 while (@host_domains >= $cutoff) {
428 my $subhost = join('.', @host_domains);
429 unless (exists $pending{$subhost}) {
430 $self->log(LOGINFO,
431 "URIBL: checking sub-host $subhost");
432 $queries += $start_query->($self, $subhost);
433 $pending{$subhost} = 1;
434 }
435 shift @host_domains;
436 }
437 }
438 }
439 }
440 $transaction->body_resetpos;
441
442 return $queries;
443 }
444
445 # async version: not used
446 sub collect_results {
447 my ($self, $transaction) = @_;
448
449 my $matches = 0;
450 my $complete = 0;
451 my $start_time = time;
452 while ($self->{socket_select}->handles) {
453 my $timeout = ($start_time + $self->{timeout}) - time;
454 last if $timeout <= 0;
455
456 my @ready = $self->{socket_select}->can_read($timeout);
457
458 SOCK: for my $s (@ready) {
459 $self->{socket_select}->remove($s);
460 my $r = $self->{socket_idx}->{"$s"} or next SOCK;
461 $self->log(LOGDEBUG,
462 "from $r: socket $s: "
463 . join(', ', map { "$_=$r->{$_}" } keys %{$r})
464 );
465 my $zone = $r->{zone};
466 my $name = $r->{name};
467 my $h = $self->{sockets}->{$zone}->{$name};
468 my $packet = $self->{resolver}->bgread($s)
469 or next SOCK;
470
471 for my $a ($packet->answer) {
472 if ($a->type eq 'TXT') {
473 $h->{txt} = $a->txtdata;
474 }
475 elsif ($a->type eq 'A') {
476 $h->{a} = $a->address;
477 if ($self->evaluate($zone, $h->{a})) {
478 $self->log(LOGDEBUG, "match in $zone");
479 $h->{match} = 1;
480 $matches++;
481 }
482 }
483 }
484
485 $complete++;
486 }
487 }
488 my $elapsed = time - $start_time;
489 $self->log(LOGINFO,
490 sprintf(
491 "$complete lookup%s finished in %.2f sec (%d match%s)",
492 $complete == 1 ? '' : 's', $elapsed,
493 $matches, $matches == 1 ? '' : 'es'
494 )
495 );
496
497 my @matches = ();
498 for my $z (keys %{$self->{sockets}}) {
499 for my $n (keys %{$self->{sockets}->{$z}}) {
500 my $h = $self->{sockets}->{$z}->{$n};
501 next unless $h->{match};
502 push @matches,
503 {
504 action => $self->{uribl_zones}->{$z}->{action},
505 desc => "$n in $z: " . ($h->{txt} || $h->{a}),
506 };
507 }
508 }
509
510 $self->lookup_finish;
511
512 return \@matches;
513 }
514
515 # async version: not used
516 sub data_handler {
517 my ($self, $transaction) = @_;
518
519 return (DECLINED) if $self->is_immune();
520
521 my $queries = $self->lookup_start(
522 $transaction,
523 sub {
524 my ($self, $name) = @_;
525 return $self->send_query($name);
526 }
527 );
528
529 unless ($queries) {
530 $self->log(LOGINFO, "pass, No URIs found in mail");
531 return DECLINED;
532 }
533
534 my $matches = $self->collect_results($transaction);
535 for (@$matches) {
536 $self->log(LOGWARN, $_->{desc});
537 if ($_->{action} eq 'add-header') {
538 $transaction->header->add('X-URIBL-Match', $_->{desc}, 0);
539 }
540 elsif ($_->{action} eq 'deny') {
541 return (DENY, $_->{desc});
542 }
543 elsif ($_->{action} eq 'denysoft') {
544 return (DENYSOFT, $_->{desc});
545 }
546 }
547 return DECLINED;
548 }
549
550 # async version: not used
551 sub init_resolver {
552 my $self = shift;
553
554 $self->{resolver} = new Net::DNS::Resolver or return undef;
555 $self->{resolver}->udp_timeout($self->{timeout});
556 }
557