-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathdspam
714 lines (533 loc) · 19.9 KB
/
dspam
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
#!perl -w
=head1 NAME
dspam - dspam integration for qpsmtpd
=head1 DESCRIPTION
Uses dspam to classify messages. Use B<spamassassin>, B<karma>, and B<naughty>
to train dspam.
Adds the X-DSPAM-Result and X-DSPAM-Signature headers to messages. The latter is essential for
training dspam and the former is useful to MDAs, MUAs, and humans.
Adds a transaction note to the qpsmtpd transaction. The note is a hashref
with at least the 'class' field (Spam,Innocent,Whitelisted). It will normally
contain a probability and confidence rating.
=head1 TRAINING DSPAM
If you enable dspam rejection without training first, you will lose valid
mail. The dspam false positive rate is high when untrained. The good news is;
dspam learns very, very fast.
The best method way to train dspam is to feed it two large equal sized
corpuses of spam and ham from your mail server. The dspam authors suggest
avoiding public corpuses. I train dspam as follows:
=over 4
=item learn from SpamAssassin
See the SPAMASSASSIN section.
=item periodic training
I have a script that searches the contents of every users maildir. Any read
messages that have changed since the last processing run are learned as ham
or spam.
The ham message list consists of read messages in any folder not named like
Spam, Junk, Trash, or Deleted. This catches messages that users have read
and left in their inbox or filed away into subfolders.
=item on-the-fly training
The dovecot IMAP server has an antispam plugin that will train dspam when
messages are moved to/from the Spam folder.
=back
=head1 CONFIG
=head2 dspam_bin
The path to the dspam binary. If yours is installed somewhere other
than /usr/local/bin/dspam, set this.
=head2 autolearn [ naughty | karma | spamassassin | any ]
=over 4
=item naughty
learn naughty messages as spam (see plugins/naughty)
=item karma
learn messages with negative karma as spam (see plugins/karma)
=item spamassassin
learn from spamassassins messages with autolearn=(ham|spam). See SPAMASSASSIN.
=item any
all of the above, and any future tests too!
=back
=head2 reject
Set to a floating point value between 0 and 1.00 where 0 is no confidence
and 1.0 is 100% confidence.
If dspam's confidence is greater than or equal to this threshold, the
message will be rejected. The default is 1.00.
dspam reject .95
To only reject mail if dspam and spamassassin both think the message is spam,
set I<reject agree>.
=head2 reject_type
reject_type [ perm | temp | disconnect ]
By default, rejects are permanent (5xx). Set I<reject_type temp> to
defer mail instead of rejecting it.
Set I<reject_type disconnect> if you'd prefer to immediately disconnect
the connection when a spam is encountered. This prevents the remote server
from issuing a reset and attempting numerous times in a single connection.
=head1 dspam.conf
dspam must be configured and working properly. I had to modify the following
settings on my system:
=over 4
=item mysql storage
=item Trust smtpd
=item TrainingMode tum
=item Tokenizer osb
=item Preference "trainingMode=TOE"
=item Preference "spamAction=deliver"
=item Preference "signatureLocation=headers"
=item TrainPristine off
=item ParseToHeaders off
=back
Of those changes, the most important is the signature location. This plugin
only supports storing the signature in the headers. If you want to train dspam
after delivery (ie, users moving messages to/from spam folders), then the
dspam signature must be in the headers.
When using the dspam MySQL backend, use InnoDB tables. DSPAM training
is dramatically slowed by MyISAM table locks and dspam requires a lot
of training. InnoDB has row level locking and updates are much faster.
=head1 DSPAM periodic maintenance
Install this cron job to clean up your DSPAM database.
http://dspam.git.sourceforge.net/git/gitweb.cgi?p=dspam/dspam;a=tree;f=contrib/dspam_maintenance;hb=HEAD
=head1 SPAMASSASSIN
DSPAM can be trained by SpamAssassin. This relationship between them requires
attention to several important details:
=over 4
=item 1
dspam must be listed B<after> spamassassin in the config/plugins file.
Because SA runs first, I set the SA reject_threshold up above 100 so that
all spam messages will be used to train dspam.
Once dspam is trained and errors are rare, I plan to run dspam first and
reduce the SA load.
=item 2
For I<autolearn spamassassin> to work, autolearn must be enabled and
configured in SpamAssassin. SA autolearn will
determine if a message is learned by dspam. The settings to pay careful
attention to in your SA local.cf file are I<bayes_auto_learn_threshold_spam>
and I<bayes_auto_learn_threshold_nonspam>. Make sure they are set to
conservative values that will yield no false positives.
If you are using I<autolearn spamassassin> and I<reject>, messages that exceed
the SA threshholds will cause dspam to reject them. Again I say, make sure
the SA autolearn threshholds are set high enough to avoid false positives.
=back
=head1 MULTIPLE RECIPIENT BEHAVIOR
For messages with multiple recipients, the user that dspam is running as will
be the dspam username.
When messages have a single recipient, the recipient address is used as the
dspam username. For dspam to trust qpsmtpd with modifying the username, you
B<must> add the username that qpsmtpd is running to to the dspamd.conf file.
ie, (Trust smtpd).
=head1 CHANGES
2012-06 - Matt Simerson - added karma & naughty learning support
- worked around the DESTROY bug in dspam_process
=head1 AUTHOR
2012 - Matt Simerson
=cut
use strict;
use warnings;
use Qpsmtpd::Constants;
use Qpsmtpd::DSN;
use IO::Handle;
use Socket qw(:DEFAULT :crlf);
sub register {
my $self = shift;
my $qp = shift;
$self->log(LOGERROR, "Bad parameters for the dspam plugin") if @_ % 2;
$self->{_args} = {@_};
$self->{_args}{reject} = 1 if !defined $self->{_args}{reject};
$self->{_args}{reject_type} ||= 'perm';
$self->{_args}{dspam_bin} ||= '/usr/local/bin/dspam';
$self->get_dspam_bin() or return DECLINED;
$self->register_hook('data_post', 'data_post_handler');
}
sub get_dspam_bin {
my $self = shift;
my $bin = $self->{_args}{dspam_bin};
if (!-e $bin) {
$self->log(LOGERROR,
"error, dspam CLI binary not found: install dspam and/or set dspam_bin"
);
return;
}
if (!-x $bin) {
$self->log(LOGERROR, "error, no permission to run $bin");
return;
}
return $bin;
}
sub data_post_handler {
my $self = shift;
my $transaction = shift || $self->qp->transaction;
return DECLINED if $self->is_immune();
if ($transaction->data_size > 500_000) {
$self->log(LOGINFO, "skip, too big (" . $transaction->data_size . ")");
return DECLINED;
}
my $user = $self->select_username($transaction);
my $bin = $self->{_args}{dspam_bin};
my $filtercmd =
"$bin --user $user --mode=tum --process --deliver=summary --stdout";
$self->log(LOGDEBUG, $filtercmd);
my $response = $self->dspam_process($filtercmd, $transaction);
if (!$response->{result}) {
$self->log(LOGWARN, "error, no dspam response. Check logs for errors.");
return DECLINED;
}
$transaction->notes('dspam', $response);
$self->attach_headers($response, $transaction);
$self->autolearn($response, $transaction);
return $self->log_and_return($transaction);
}
sub select_username {
my ($self, $transaction) = @_;
my $recipient_count = scalar $transaction->recipients;
$self->log(LOGDEBUG, "Message has $recipient_count recipients");
if ($recipient_count > 1) {
$self->log(LOGINFO,
"multiple recipients ($recipient_count), ignoring user prefs");
return getpwuid($>);
}
# use the recipients email address as username. This enables user prefs
my $username = ($transaction->recipients)[0]->address;
return lc($username);
}
sub assemble_message {
my ($self, $transaction) = @_;
my $message =
"X-Envelope-From: "
. $transaction->sender->format . "\n"
. $transaction->header->as_string . "\n\n";
$transaction->body_resetpos;
while (my $line = $transaction->body_getline) { $message .= $line; }
$message = join(CRLF, split /\n/, $message);
return $message . CRLF;
}
sub parse_response {
my $self = shift;
my $response = shift or do {
$self->log(LOGDEBUG, "missing dspam response!");
return;
};
# example DSPAM results:
# [email protected]; result="Spam"; class="Spam"; probability=1.0000; confidence=1.00; signature=N/A
# smtpd; result="Innocent"; class="Innocent"; probability=0.0023; confidence=1.00; signature=4f8dae6a446008399211546
#return $self->parse_response_regexp( $response ); # probably slower
my ($user, $result, $class, $prob, $conf, $sig) = split /; /, $response;
(undef, $result) = split /=/, $result;
(undef, $class) = split /=/, $class;
(undef, $prob) = split /=/, $prob;
(undef, $conf) = split /=/, $conf;
(undef, $sig) = split /=/, $sig;
$result = substr($result, 1, -1); # strip off quotes
$class = substr($class, 1, -1);
return {
class => $class,
result => $result,
probability => $prob,
confidence => $conf,
signature => $sig,
};
}
sub parse_response_regexp {
my ($self, $response) = @_;
my ($result, $class, $prob, $conf, $sig) = $response =~ /
result=\"(Spam|Innocent)\";\s
class=\"(Spam|Innocent)\";\s
probability=([\d\.]+);\s
confidence=([\d\.]+);\s
signature=(.*)
/x;
return {
class => $class,
result => $result,
probability => $prob,
confidence => $conf,
signature => $sig,
};
}
sub dspam_process {
my ($self, $filtercmd, $transaction) = @_;
my $response = $self->dspam_process_backticks($filtercmd);
#my $response = $self->dspam_process_open2( $filtercmd, $transaction );
#my $response = $self->dspam_process_fork( $filtercmd );
return $self->parse_response($response);
}
sub dspam_process_fork {
my ($self, $filtercmd, $transaction) = @_;
# yucky. This method (which forks) exercises a bug in qpsmtpd. When the
# child exits, the Transaction::DESTROY method is called, which deletes
# the spooled file from disk. The contents of $self->qp->transaction
# needed to spool it again are also destroyed. Don't use this.
my $message = $self->assemble_message($transaction);
my $in_fh;
if (!open($in_fh, '-|')) { # forks child for writing
open(my $out_fh, "|$filtercmd") or die "Can't run $filtercmd: $!\n";
print $out_fh $message;
close $out_fh;
exit(0);
}
my $response = <$in_fh>;
close $in_fh;
chomp $response;
$self->log(LOGDEBUG, $response);
return $response;
}
sub dspam_process_backticks {
my ($self, $filtercmd) = @_;
my $transaction = $self->qp->transaction;
my $message = $self->temp_file();
open my $fh, '>', $message;
print $fh "X-Envelope-From: "
. $transaction->sender->format
. CRLF
. $transaction->header->as_string
. CRLF
. CRLF;
$transaction->body_resetpos;
while (my $line = $transaction->body_getline) { print $fh $line; }
close $fh;
my ($line1) = split /[\r|\n]/, `$filtercmd < $message`;
$self->log(LOGDEBUG, $line1);
return $line1;
}
sub dspam_process_open2 {
my ($self, $filtercmd, $transaction) = @_;
my $message = $self->assemble_message($transaction);
# not sure why, but this is not as reliable as I'd like. What's a dspam
# error -5 mean anyway?
use FileHandle;
use IPC::Open3;
my ($read, $write, $err);
use Symbol 'gensym';
$err = gensym;
my $pid = open3($write, $read, $err, $filtercmd);
print $write $message;
close $write;
#my $response = join('', <$dspam_out>); # get full response
my $response = <$read>; # get first line only
waitpid $pid, 0;
my $child_exit_status = $? >> 8;
#$self->log(LOGINFO, "exit status: $child_exit_status");
if ($response) {
chomp $response;
$self->log(LOGDEBUG, $response);
}
my $err_msg = <$err>;
if ($err_msg) {
$self->log(LOGDEBUG, $err_msg);
}
return $response;
}
sub log_and_return {
my $self = shift;
my $transaction = shift || $self->qp->transaction;
my $d = $self->get_dspam_results($transaction) or return DECLINED;
if (!$d->{class}) {
$self->log(LOGWARN, "skip, no dspam class detected");
return DECLINED;
}
my $status = "$d->{class}, $d->{confidence} c.";
my $reject = $self->{_args}{reject} or do {
$self->log(LOGINFO, "skip, reject disabled ($status)");
return DECLINED;
};
if ($reject eq 'agree') {
return $self->reject_agree($transaction);
}
if ($d->{class} eq 'Innocent') {
$self->log(LOGINFO, "pass, $status");
return DECLINED;
}
if ($self->qp->connection->relay_client) {
$self->log(LOGINFO,
"skip, allowing spam, user authenticated ($status)");
return DECLINED;
}
if ($d->{probability} <= $reject) {
$self->log(LOGINFO,
"pass, $d->{class} probability is too low ($d->{probability} < $reject)"
);
return DECLINED;
}
if ($d->{confidence} != 1) {
$self->log(LOGINFO,
"pass, $d->{class} confidence is too low ($d->{confidence})");
return DECLINED;
}
# dspam is more than $reject percent sure this message is spam
$self->log(LOGINFO, "fail, $d->{class}, ($d->{confidence} confident)");
my $deny = $self->get_reject_type();
return Qpsmtpd::DSN->media_unsupported($deny, 'dspam says, no spam please');
}
sub reject_agree {
my ($self, $transaction) = @_;
my $sa = $transaction->notes('spamassassin');
my $d = $transaction->notes('dspam');
my $status = "$d->{class}, $d->{confidence} c";
if (!$sa->{is_spam}) {
$self->log(LOGINFO, "pass, cannot agree, SA results missing ($status)");
return DECLINED;
}
if ($d->{class} eq 'Spam') {
if ($sa->{is_spam} eq 'Yes') {
$self->adjust_karma(-2);
$self->log(LOGINFO, "fail, agree, $status");
my $reject = $self->get_reject_type();
return $reject, 'we agree, no spam please';
}
$self->log(LOGINFO, "fail, disagree, $status");
return DECLINED;
}
if ($d->{class} eq 'Innocent') {
if ($sa->{is_spam} eq 'No') {
if ($d->{confidence} > .9) {
$self->adjust_karma(1);
}
$self->log(LOGINFO, "pass, agree, $status");
return DECLINED;
}
$self->log(LOGINFO, "pass, disagree, $status");
return DECLINED;
}
$self->log(LOGINFO, "pass, other $status");
return DECLINED;
}
sub get_dspam_results {
my $self = shift;
my $transaction = shift || $self->qp->transaction;
if ($transaction->notes('dspam')) {
return $transaction->notes('dspam');
}
my $string = $transaction->header->get('X-DSPAM-Result') or do {
$self->log(LOGWARN, "get_dspam_results: failed to find the header");
return;
};
my @bits = split /,\s+/, $string;
chomp @bits;
my $class = shift @bits;
my %d;
foreach (@bits) {
my ($key, $val) = split /=/, $_;
$d{$key} = $val;
}
$d{class} = $class;
my $message = $d{class};
if (defined $d{probability} && defined $d{confidence}) {
$message .= ", prob: $d{probability}, conf: $d{confidence}";
}
$self->log(LOGDEBUG, $message);
$transaction->notes('dspam', \%d);
return \%d;
}
sub attach_headers {
my ($self, $r, $transaction) = @_;
$transaction ||= $self->qp->transaction;
my $header_str =
"$r->{result}, probability=$r->{probability}, confidence=$r->{confidence}";
$self->log(LOGDEBUG, $header_str);
my $name = 'X-DSPAM-Result';
$transaction->header->delete($name) if $transaction->header->get($name);
$transaction->header->add($name, $header_str, 0);
# the signature header is required if you intend to train dspam later.
# In dspam.conf, set: Preference "signatureLocation=headers"
$transaction->header->add('X-DSPAM-Signature', $r->{signature}, 0);
}
sub train_error_as_ham {
my $self = shift;
my $transaction = shift;
my $user = $self->select_username($transaction);
my $dspam_bin = $self->{_args}{dspam_bin} || '/usr/local/bin/dspam';
my $cmd =
"$dspam_bin --user $user --mode=toe --source=error --class=innocent --deliver=summary --stdout";
$self->dspam_process($cmd, $transaction);
return;
}
sub train_error_as_spam {
my $self = shift;
my $transaction = shift;
my $user = $self->select_username($transaction);
my $dspam_bin = $self->{_args}{dspam_bin} || '/usr/local/bin/dspam';
my $cmd =
"$dspam_bin --user $user --mode=toe --source=error --class=spam --deliver=summary --stdout";
$self->dspam_process($cmd, $transaction);
return;
}
sub autolearn {
my ($self, $response, $transaction) = @_;
defined $self->{_args}{autolearn} or return;
if ( $self->{_args}{autolearn} ne 'any'
&& $self->{_args}{autolearn} ne 'karma'
&& $self->{_args}{autolearn} ne 'naughty'
&& $self->{_args}{autolearn} ne 'spamassassin')
{
$self->log(LOGERROR,
"bad autolearn setting! Read 'perldoc plugins/dspam' again!");
return;
}
# only train once.
$self->autolearn_naughty($response, $transaction) and return;
$self->autolearn_karma($response, $transaction) and return;
$self->autolearn_spamassassin($response, $transaction) and return;
return;
}
sub autolearn_naughty {
my ($self, $response, $transaction) = @_;
my $learn = $self->{_args}{autolearn} or return;
if ($learn ne 'naughty' && $learn ne 'any') {
$self->log(LOGDEBUG, "skipping naughty autolearn");
return;
}
if ( $self->is_naughty() && $response->{result} eq 'Innocent') {
$self->log(LOGINFO, "training naughty FN message as spam");
$self->train_error_as_spam($transaction);
return 1;
}
$self->log(LOGDEBUG, "falling through naughty autolearn");
return;
}
sub autolearn_karma {
my ($self, $response, $transaction) = @_;
my $learn = $self->{_args}{autolearn} or return;
return if ($learn ne 'karma' && $learn ne 'any');
my $karma = $self->connection->notes('karma');
return if !defined $karma;
if ($karma < -2 && $response->{result} eq 'Innocent') {
$self->log(LOGINFO, "training bad karma ($karma) FN as spam");
$self->train_error_as_spam($transaction);
return 1;
}
if ($karma > 2 && $response->{result} eq 'Spam') {
$self->log(LOGINFO, "training good karma ($karma) FP as ham");
$self->train_error_as_ham($transaction);
return 1;
}
return;
}
sub autolearn_spamassassin {
my ($self, $response, $transaction) = @_;
my $learn = $self->{_args}{autolearn} or return;
return if ($learn ne 'spamassassin' && $learn ne 'any');
my $sa = $transaction->notes('spamassassin');
if (!$sa || !$sa->{is_spam}) {
if (!$self->is_naughty()) {
$self->log(LOGERROR, "SA results missing"); # SA skips naughty
}
return;
}
if (!$sa->{autolearn}) {
$self->log(LOGERROR, "SA autolearn unset");
return;
}
if ( $sa->{is_spam} eq 'Yes'
&& $sa->{autolearn} eq 'spam'
&& $response->{result} eq 'Innocent')
{
$self->log(LOGINFO, "training SA FN as spam");
$self->train_error_as_spam($transaction);
return 1;
};
if ( $sa->{is_spam} eq 'No'
&& $sa->{autolearn} eq 'ham'
&& $response->{result} eq 'Spam')
{
$self->log(LOGINFO, "training SA FP as ham");
$self->train_error_as_ham($transaction);
return 1;
}
return;
}