Debian Codegraph @

plugins/dspam

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