MtPolicyd/Plugin/Greylist.pm

filter: Statementstmt 22.6% 34 / 150 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 15 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 20.8% 5 / 24 Podpod 14.2% 2 / 14 totaltotal 16.6% 41 / 247 CC 23 SCAR 34.4
CC
23
Cov
17%
run
110.0
success
30.0
is_autowl
20.0
CRAP 31.3
« MtPolicyd/Plugin/GeoIPAction.pm ↑ Summary MtPolicyd/Request.pm »
1 package Mail::MtPolicyd::Plugin::Greylist;
2  
3 1 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 1 our $VERSION = '1.11'; # VERSION
7 # ABSTRACT: mtpolicyd plugin for checking the client-address against an RBL
8  
9 1 extends 'Mail::MtPolicyd::Plugin';
10 1 with 'Mail::MtPolicyd::Plugin::Role::Scoring';
11 1 with 'Mail::MtPolicyd::Plugin::Role::UserConfig' => {
12 'uc_attributes' => [ 'enabled' ],
13 };
14  
15 1 ▶use Mail::MtPolicyd::Plugin::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use Time::Piece::MySQL;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use Time::Seconds;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19  
20 1 has 'enabled' => ( is => 'rw', isa => 'Str', default => 'on' );
21  
22 1 has 'score' => ( is => 'rw', isa => 'Maybe[Num]' );
23 1 has 'mode' => ( is => 'rw', isa => 'Str', default => 'passive');
24  
25 1 has 'defer_message' => ( is => 'rw', isa => 'Str', default => 'defer greylisting is active');
26 1 has 'append_waittime' => ( is => 'rw', isa => 'Bool', default => 1 );
27  
28 1 has 'min_retry_wait' => ( is => 'rw', isa => 'Int', default => 60*5 );
29 1 has 'max_retry_wait' => ( is => 'rw', isa => 'Int', default => 60*60*2 );
30  
31 1 has 'use_autowl' => ( is => 'rw', isa => 'Bool', default => 1 );
32 1 has 'autowl_threshold' => ( is => 'rw', isa => 'Int', default => 3 );
33 1 has 'autowl_expire_days' => ( is => 'rw', isa => 'Int', default => 60 );
34  
35 1 has 'autowl_table' => ( is => 'rw', isa => 'Str', default => 'autowl' );
36  
37 1 has 'query_autowl' => ( is => 'rw', isa => 'Bool', default => 1 );
38 1 has 'create_ticket' => ( is => 'rw', isa => 'Bool', default => 1 );
39  
40 sub run {
41 0 ▶ my ( $self, $r ) = @_;
Subroutine run: not called CC=10 SCAR=47.0
Pod documented
42 0 my $ip = $r->attr('client_address');
43 0 my $sender = $r->attr('sender');
44 0 my $recipient = $r->attr('recipient');
45 0 my @triplet = ($sender, $ip, $recipient);
46 0 my $session = $r->session;
47  
48 0 my $enabled = $self->get_uc( $session, 'enabled' );
49 0 ▶ if( $enabled eq 'off' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($enabled eq "off") 0 0 0
50 0 return;
51 }
52  
53 0 ▶ if( $self->use_autowl && $self->query_autowl ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->use_autowl and $self->query_autowl) 0 0 0
Condition0%0/3
$self->use_autowl and $self->query_autowl
!ll&&!rl&&r
000
MC/DC0%0/2
$self->use_autowl and $self->query_autowl
$self->use_autowl $self->query_autowl
Truth table0%0/3
A and B
A= $self->use_autowlB= $self->query_autowl
ABresult
0X0
100
111
54 my ( $is_autowl ) = $r->do_cached('greylist-is_autowl', sub {
55 0 ▶ $self->is_autowl( $r, @triplet );
Subroutine __ANON__: not called CC=1 SCAR=6.9
56 0 } );
57 0 ▶ if( $is_autowl ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_autowl) 0 0 0
58 0 $self->log($r, 'client on greylist autowl');
59 0 return $self->success( $r );
60 }
61 }
62  
63 0 ▶ my ( $ticket ) = $r->do_cached('greylist-ticket', sub { $self->get_ticket($r, @triplet) } );
Subroutine __ANON__: not called CC=1 SCAR=6.9
64 0 ▶ if( defined $ticket ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ticket) 0 0 0
65 0 ▶ if( $self->is_valid_ticket( $ticket ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_valid_ticket($ticket)) 0 0 0
66 0 $self->log($r, join(',', @triplet).' has a valid greylisting ticket');
67 0 ▶ if( $self->use_autowl && ! $r->is_already_done('greylist-autowl-add') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->use_autowl and not $r->is_already_done("greylist-autowl-add")) 0 0 0
Condition0%0/3
$self->use_autowl and not $r->is_already_done("greylist-autowl-add")
!ll&&!rl&&r
000
MC/DC0%0/2
$self->use_autowl and not $r->is_already_done("greylist-autowl-add")
$self->use_autowl not $r->is_already_done("greylist-autowl-add")
Truth table0%0/3
A and not(B)
A= $self->use_autowlB= not $r->is_already_done("greylist-autowl-add")
ABresult
0X0
100
111
68 0 $self->add_autowl( $r, @triplet );
69 }
70 0 $self->remove_ticket( $r, @triplet );
71 0 return $self->success( $r );
72 }
73 0 $self->log($r, join(',', @triplet).' has a invalid greylisting ticket. wait again');
74 0 return( $self->defer( $ticket ) );
75 }
76  
77 0 ▶ if( $self->create_ticket ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->create_ticket) 0 0 0
78 0 $self->log($r, 'creating new greylisting ticket');
79 0 $self->do_create_ticket($r, @triplet);
80 0 return( $self->defer );
81 }
82 0 return;
83 }
84  
85 sub defer {
86 0 ▶ my ( $self, $ticket ) = @_;
Subroutine defer: not called CC=3 SCAR=24.8
Pod documented
87 0 my $message = $self->defer_message;
88 0 ▶ if( defined $ticket && $self->append_waittime ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ticket and $self->append_waittime) 0 0 0
Condition0%0/3
defined $ticket and $self->append_waittime
!ll&&!rl&&r
000
MC/DC0%0/2
defined $ticket and $self->append_waittime
defined $ticket $self->append_waittime
Truth table0%0/3
A and B
A= defined $ticketB= $self->append_waittime
ABresult
0X0
100
111
89 0 $message .= ' ('.( $ticket - time ).'s left)'
90 }
91 0 return( Mail::MtPolicyd::Plugin::Result->new(
92 action => $message,
93 abort => 1,
94 ) );
95 }
96  
97 sub success {
98 0 ▶ my ( $self, $r ) = @_;
Subroutine success: not called CC=5 SCAR=34.0
Pod undocumented
99 0 ▶ if( defined $self->score && ! $r->is_already_done('greylist-score') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->score and not $r->is_already_done("greylist-score")) 0 0 0
Condition0%0/3
defined $self->score and not $r->is_already_done("greylist-score")
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->score and not $r->is_already_done("greylist-score")
defined $self->score not $r->is_already_done("greylist-score")
Truth table0%0/3
A and not(B)
A= defined $self->scoreB= not $r->is_already_done("greylist-score")
ABresult
0X0
100
111
100 0 $self->add_score($r, $self->name => $self->score);
101 }
102 0 ▶ if( $self->mode eq 'accept' || $self->mode eq 'dunno' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->mode eq "accept" or $self->mode eq "dunno") 0 0 0
Condition0%0/3
$self->mode eq "accept" or $self->mode eq "dunno"
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->mode eq "accept" or $self->mode eq "dunno"
$self->mode eq "accept" $self->mode eq "dunno"
Truth table0%0/3
A or B
A= $self->mode eq "accept"B= $self->mode eq "dunno"
ABresult
1X1
011
000
103 0 return( Mail::MtPolicyd::Plugin::Result->new(
104 action => $self->mode,
105 abort => 1,
106 ) );
107 }
108 0 return;
109 }
110  
111 sub _extract_sender_domain {
112 0 ▶ my ( $self, $sender ) = @_;
Subroutine _extract_sender_domain: not called CC=2 SCAR=17.9
113 0 my $sender_domain;
114  
115 0 ▶ if( $sender =~ /@/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sender =~ /@/) { } 0 0 0
116 0 ( $sender_domain ) = $sender =~ /@([^@]+)$/;
117 } else { # fallback to just the sender?
118 0 $sender_domain = $sender;
119 }
120  
121 0 return($sender_domain);
122 }
123  
124 sub is_autowl {
125 0 ▶ my ( $self, $r, $sender, $client_ip ) = @_;
Subroutine is_autowl: not called CC=4 SCAR=30.0
Pod undocumented
126 0 my $sender_domain = $self->_extract_sender_domain( $sender );
127  
128 my ( $row ) = $r->do_cached('greylist-autowl-row', sub {
129 0 ▶ $self->get_autowl_row( $r, $sender_domain, $client_ip );
Subroutine __ANON__: not called CC=1 SCAR=6.9
130 0 } );
131  
132 0 ▶ if( ! defined $row ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $row) 0 0 0
133 0 $self->log($r, 'client is not on autowl');
134 0 return(0);
135 }
136  
137 0 my $last_seen = Time::Piece->from_mysql_datetime($row->{'last_seen'});
138 0 my $expires = Time::Piece->new + ( ONE_DAY * $self->autowl_expire_days );
139 0 ▶ if( $last_seen > $expires ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($last_seen > $expires) 0 0 0
140 0 $self->log($r, 'removing expired autowl row');
141 0 $self->remove_autowl_row( $r, $sender_domain, $client_ip );
142 0 return(0);
143 }
144  
145 0 ▶ if( $row->{'count'} < $self->autowl_threshold ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($row->{"count"} < $self->autowl_threshold) 0 0 0
146 0 $self->log($r, 'client has not yet reached autowl_threshold');
147 0 return(0);
148 }
149  
150 0 $self->log($r, 'client has valid autowl row. updating row');
151 0 $self->incr_autowl_row( $r, $sender_domain, $client_ip );
152 0 return(1);
153 }
154  
155 sub add_autowl {
156 0 ▶ my ( $self, $r, $sender, $client_ip ) = @_;
Subroutine add_autowl: not called CC=2 SCAR=17.9
Pod undocumented
157 0 my $sender_domain = $self->_extract_sender_domain( $sender );
158  
159 my ( $row ) = $r->do_cached('greylist-autowl-row', sub {
160 0 ▶ $self->get_autowl_row( $r, $sender_domain, $client_ip );
Subroutine __ANON__: not called CC=1 SCAR=6.9
161 0 } );
162  
163 0 ▶ if( defined $row ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $row) 0 0 0
164 0 $self->log($r, 'client already on autowl, just incrementing count');
165 0 $self->incr_autowl_row( $r, $sender_domain, $client_ip );
166 0 return;
167 }
168  
169 0 $self->log($r, 'creating initial autowl entry');
170 0 $self->create_autowl_row( $r, $sender_domain, $client_ip );
171 0 return;
172 }
173  
174 sub execute_sql {
175 0 ▶ my ( $self, $r, $sql, @params ) = @_;
Subroutine execute_sql: not called CC=1 SCAR=6.9
Pod undocumented
176 0 my $dbh = $r->server->get_dbh;
177 0 my $sth = $dbh->prepare( $sql );
178 0 $sth->execute( @params );
179 0 return $sth;
180 }
181  
182  
183 sub get_autowl_row {
184 0 ▶ my ( $self, $r, $sender_domain, $client_ip ) = @_;
Subroutine get_autowl_row: not called CC=1 SCAR=6.9
Pod undocumented
185 0 my $sql = sprintf("SELECT * FROM %s WHERE sender_domain=? AND client_ip=?",
186 $self->autowl_table );
187 0 return $self->execute_sql($r, $sql, $sender_domain, $client_ip)->fetchrow_hashref;
188 }
189  
190 sub create_autowl_row {
191 0 ▶ my ( $self, $r, $sender_domain, $client_ip ) = @_;
Subroutine create_autowl_row: not called CC=1 SCAR=6.9
Pod undocumented
192 0 my $sql = sprintf("INSERT INTO %s VALUES(NULL, ?, ?, 1, NULL)",
193 $self->autowl_table );
194 0 $self->execute_sql($r, $sql, $sender_domain, $client_ip);
195 0 return;
196 }
197  
198 sub incr_autowl_row {
199 0 ▶ my ( $self, $r, $sender_domain, $client_ip ) = @_;
Subroutine incr_autowl_row: not called CC=1 SCAR=6.9
Pod undocumented
200 0 my $sql = sprintf("UPDATE %s SET count=count+1 WHERE sender_domain=? AND client_ip=?",
201 $self->autowl_table );
202 0 $self->execute_sql($r, $sql, $sender_domain, $client_ip);
203 0 return;
204 }
205 sub remove_autowl_row {
206 0 ▶ my ( $self, $r, $sender_domain, $client_ip ) = @_;
Subroutine remove_autowl_row: not called CC=1 SCAR=6.9
Pod undocumented
207 0 my $sql = sprintf("DELETE FROM %s WHERE sender_domain=? AND client_ip=?",
208 $self->autowl_table );
209 0 $self->execute_sql($r, $sql, $sender_domain, $client_ip);
210 0 return;
211 }
212  
213 sub get_ticket {
214 0 ▶ my ( $self, $r, $sender, $ip, $rcpt ) = @_;
Subroutine get_ticket: not called CC=2 SCAR=17.9
Pod undocumented
215 0 my $key = join(",", $sender, $ip, $rcpt );
216 0 ▶ if( my $ticket = $r->server->memcached->get( $key ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ticket = $r->server->memcached->get($key)) 0 0 0
217 0 return( $ticket );
218 }
219 0 return;
220 }
221  
222 sub is_valid_ticket {
223 0 ▶ my ( $self, $ticket ) = @_;
Subroutine is_valid_ticket: not called CC=2 SCAR=17.9
Pod undocumented
224 0 ▶ if( time > $ticket ) {
Branch: 1 branch
BranchTrueFalseTotal
if (time > $ticket) 0 0 0
225 0 return 1;
226 }
227 0 return 0;
228 }
229  
230 sub remove_ticket {
231 0 ▶ my ( $self, $r, $sender, $ip, $rcpt ) = @_;
Subroutine remove_ticket: not called CC=1 SCAR=6.9
Pod undocumented
232 0 my $key = join(",", $sender, $ip, $rcpt );
233 0 $r->server->memcached->delete( $key );
234 0 return;
235 }
236  
237 sub do_create_ticket {
238 0 ▶ my ( $self, $r, $sender, $ip, $rcpt ) = @_;
Subroutine do_create_ticket: not called CC=1 SCAR=6.9
Pod undocumented
239 0 my $ticket = time + $self->min_retry_wait;
240 0 my $key = join(",", $sender, $ip, $rcpt );
241 0 $r->server->memcached->set( $key, $ticket, $self->max_retry_wait );
242 0 return;
243 }
244  
245 1 __PACKAGE__->meta->make_immutable;
246  
247 1 1;
248  
249  
250 __END__
251 =pod
252  
253 =head1 NAME
254  
255 Mail::MtPolicyd::Plugin::Greylist - mtpolicyd plugin for checking the client-address against an RBL
256  
257 =head1 VERSION
258  
259 version 1.11
260  
261 =head1 DESCRIPTION
262  
263 This plugin implements a greylisting mechanism with an auto whitelist.
264  
265 If a client connects it will return an defer and create a greylisting "ticket"
266 for the combination of the address of the sender, the senders address and the
267 recipient address. The ticket will be stored in memcached and will contain the time
268 when the client was seen for the first time. The ticket will expire after
269 the max_retry_wait timeout.
270  
271 The client will be defered until the min_retry_wait timeout has been reached.
272 Only in the time between the min_retry_wait and max_retry_wait the request will
273 pass the greylisting test.
274  
275 When the auto-whitelist is enabled (default) a record for every client which
276 passes the greylisting test will be stored in the autowl_table.
277 The table is based on the combination of the sender domain and client_address.
278 If a client passed the test at least autowl_threshold (default 3) times the greylisting
279 test will be skipped.
280 Additional an last_seen timestamp is stored in the record and records which are older
281 then the autowl_expire_days will expire.
282  
283 Please note the greylisting is done on a triplet based on the
284  
285 client_address + sender + recipient
286  
287 The auto-white list is based on the
288  
289 client_address + sender_domain
290  
291 =head1 PARAMETERS
292  
293 =over
294  
295 =item (uc_)enabled (default: on)
296  
297 Enable/disable this check.
298  
299 =item score (default: empty)
300  
301 Apply an score to this message if it _passed_ the greylisting test. In most cases you want to assign a negative score. (eg. -10)
302  
303 =item mode (default: passive)
304  
305 The default is to return no action if the client passed the greylisting test and continue.
306  
307 You can set this 'accept' or 'dunno' if you want skip further checks.
308  
309 =item defer_message (default: defer greylisting is active)
310  
311 This action is returned to the MTA if a message is defered.
312  
313 If a client retries too fast the time left till min_retry_wait is reach will be appended to the string.
314  
315 =item min_retry_wait (default: 300 (5m))
316  
317 A client will have to wait at least for this timeout. (in seconds)
318  
319 =item max_retry_wait (default: 7200 (2h))
320  
321 A client must retry to deliver the message before this timeout. (in seconds)
322  
323 =item use_autowl (default: 1)
324  
325 Could be used to disable the use of the auto-whitelist.
326  
327 =item autowl_threshold (default: 3)
328  
329 How often a client/sender_domain pair must pass the check before it is whitelisted.
330  
331 =item autowl_expire_days (default: 60)
332  
333 After how many days an auto-whitelist entry will expire if no client with this client/sender pair is seen.
334  
335 =item autowl_table (default: autowl)
336  
337 The name of the table to use.
338  
339 The database handle specified in the global configuration will be used. (see man mtpolicyd)
340  
341 =item query_autowl, create_ticket (default: 1)
342  
343 This options could be used to disable the creation of a new ticket or to query the autowl.
344  
345 This can be used to catch early retries at the begin of your configuration before more expensive checks a processes.
346  
347 Example:
348  
349 <Plugin greylist>
350 module = "Greylist"
351 score = -5
352 mode = "passive"
353 create_ticket = 0
354 query_autowl = 0
355 </Plugin>
356 # ... a lot of RBL checks, etc...
357 <Plugin ScoreGreylist>
358 module = "ScoreAction"
359 threshold = 5
360 <Plugin greylist>
361 module = "Greylist"
362 score = -5
363 mode = "passive"
364 </Plugin>
365 </Plugin>
366  
367 This will prevent early retries from running thru all checks.
368  
369 =back
370  
371 =head1 AUTOWL TABLE CREATE SQL SCRIPT
372  
373 The following statement could be used to create the autowl table within a Maria/MySQL database:
374  
375 CREATE TABLE `autowl` (
376 `id` int(11) NOT NULL AUTO_INCREMENT,
377 `sender_domain` VARCHAR(255) NOT NULL,
378 `client_ip` VARCHAR(39) NOT NULL,
379 `count` INT UNSIGNED NOT NULL,
380 `last_seen` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
381 PRIMARY KEY (`id`),
382 UNIQUE KEY `domain_ip` (`client_ip`, `sender_domain`),
383 KEY(`client_ip`),
384 KEY(`sender_domain`)
385 ) ENGINE=MyISAM DEFAULT CHARSET=latin1
386  
387 =head1 AUTHOR
388  
389 Markus Benning <ich@markusbenning.de>
390  
391 =head1 COPYRIGHT AND LICENSE
392  
393 This software is Copyright (c) 2014 by Markus Benning <ich@markusbenning.de>.
394  
395 This is free software, licensed under:
396  
397 The GNU General Public License, Version 2, June 1991
398  
399 =cut
400  
« MtPolicyd/Plugin/GeoIPAction.pm ↑ Summary MtPolicyd/Request.pm »