Handler/RSpamD.pm untested

filter: Statementstmt 0.0% 0 / 179 Branchbran 0.0% 0 / 42 Conditioncond 0.0% 0 / 11 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 272 CC 22 SCAR 39.2
CC
22
Cov
0%
eom_callback
156.0
header_callback
56.0
remove_header
12.0
CRAP 50.3
1 package Mail::Milter::Authentication::Handler::RSpamD;
2 use strict;
3 use warnings;
4 use Mail::Milter::Authentication 2.20180510;
5 use base 'Mail::Milter::Authentication::Handler';
6 our $VERSION = '2.20180510'; # VERSION
7 # #ABSTRACT: RSpamD scanning for Authentication Milter
8  
9 use English qw{ -no_match_vars };
10 use Sys::Syslog qw{:standard :macros};
11 use HTTP::Tiny;
12 use JSON;
13 use Mail::AuthenticationResults::Header::Entry;
14 use Mail::AuthenticationResults::Header::SubEntry;
15 use Mail::AuthenticationResults::Header::Comment;
16  
17 use Data::Dumper;
18  
19 sub default_config {
20 return {
21 'default_user' => 'nobody',
22 'rs_host' => 'localhost',
23 'rs_port' => '11333',
24 'hard_reject' => 1,
25 'remove_headers' => 'yes',
26 }
27 }
28  
29 sub grafana_rows {
30 my ( $self ) = @_;
31 my @rows;
32 push @rows, $self->get_json( 'RSpamD_metrics' );
33 return \@rows;
34 }
35  
36 sub register_metrics {
37 return {
38 'rspamd_total' => 'The number of emails processed for RSpamD',
39 };
40 }
41  
42 sub get_user {
43 my ( $self ) = @_;
44 my $user_handler = $self->get_handler('UserDB');
45 my $user = $user_handler->{'local_user'};
46 return $user if $user;
47 my $config = $self->handler_config();
48 return $config->{'default_user'};
49 }
50  
51 sub remove_header {
52 my ( $self, $key, $value ) = @_;
53 if ( !exists( $self->{'remove_headers'} ) ) {
54 $self->{'remove_headers'} = {};
55 }
56 if ( !exists( $self->{'remove_headers'}->{ lc $key } ) ) {
57 $self->{'remove_headers'}->{ $key } = [];
58 }
59 push @{ $self->{'remove_headers'}->{ lc $key } }, $value;
60 return;
61 }
62  
63 sub helo_callback {
64 my ( $self, $helo_host ) = @_;
65 $self->{'helo_name'} = $helo_host;
66 return;
67 }
68  
69 sub envfrom_callback {
70 my ($self, $from) = @_;
71 $self->{'lines'} = [];
72 $self->{'rcpt_to'} = [];
73 $self->{'mail_from'} = $from;
74 delete $self->{'header_index'};
75 delete $self->{'remove_headers'};
76 $self->{'metrics_data'} = {};
77 $self->{ 'metrics_data' }->{ 'header_removed' } = 'no';
78 return;
79 }
80  
81 sub envrcpt_callback {
82 my ( $self, $env_to ) = @_;
83 push @{ $self->{'rcpt_to'} }, $env_to;
84 return;
85 }
86  
87 sub header_callback {
88 my ( $self, $header, $value ) = @_;
89 push @{$self->{'lines'}} ,$header . ': ' . $value . "\r\n";
90 my $config = $self->handler_config();
91  
92 return if ( $self->is_trusted_ip_address() );
93 return if ( lc $config->{'remove_headers'} eq 'no' );
94  
95 foreach my $header_type ( qw{ X-Spam-score X-Spam-Status X-Spam-Action } ) {
96 if ( lc $header eq lc $header_type ) {
97 if ( !exists $self->{'header_index'} ) {
98 $self->{'header_index'} = {};
99 }
100 if ( !exists $self->{'header_index'}->{ lc $header_type } ) {
101 $self->{'header_index'}->{ lc $header_type } = 0;
102 }
103 $self->{'header_index'}->{ lc $header_type } =
104 $self->{'header_index'}->{ lc $header_type } + 1;
105 $self->remove_header( $header_type, $self->{'header_index'}->{ lc $header_type } );
106 $self->{ 'metrics_data' }->{ 'header_removed' } = 'yes';
107 if ( lc $config->{'remove_headers'} ne 'silent' ) {
108 my $forged_header =
109 '(Received ' . $header_type . ' header removed by '
110 . $self->get_my_hostname()
111 . ')' . "\n"
112 . ' '
113 . $value;
114 $self->append_header( 'X-Received-' . $header_type,
115 $forged_header );
116 }
117 }
118 }
119  
120 return;
121 }
122  
123 sub eoh_callback {
124 my ( $self ) = @_;
125 push @{$self->{'lines'}} , "\r\n";
126 return;
127 }
128  
129 sub body_callback {
130 my ( $self, $chunk ) = @_;
131 push @{$self->{'lines'}} , $chunk;
132 return;
133 }
134  
135 sub get_auth_name {
136 my ($self) = @_;
137 my $protocol = Mail::Milter::Authentication::Config::get_config()->{'protocol'};
138 if ( $protocol ne 'milter' ) {
139 return 'unauthorized';
140 }
141 my $name = $self->get_symbol('{auth_authen}') || 'unauthorized';
142 return $name;
143 }
144  
145 sub eom_callback {
146 my ($self) = @_;
147  
148 my $config = $self->handler_config();
149  
150 my $host = $config->{'rs_host'} || 'localhost';
151 my $port = $config->{'rs_port'} || 11333;
152 my $user = $self->get_user();
153  
154 $self->dbgout( 'RSpamDUser', $user, LOG_INFO );
155  
156 my $queue_id = $self->get_symbol('i') || q{--};
157  
158 my $message = join( q{} , @{$self->{'lines'} } );
159 my $headers = {
160 'Deliver-To' => $user,
161 'IP' => $self->ip_address(),
162 'Helo' => $self->{'helo_name'},
163 'From' => $self->{'mail_from'},
164 'Queue-Id' => $queue_id,
165 'Rcpt' => $self->{'rcpt_to'},
166 'Pass' => 'all', # all to check all filters
167 'User' => $self->get_auth_name(),
168 };
169  
170 my $http = HTTP::Tiny->new(
171 'keep_alive' => 0,
172 );
173 my $response = $http->post( "http://$host:$port/check", { 'headers' => $headers, 'content' => $message } );
174 if ( ! $response->{'success'} ) {
175 $self->log_error( 'RSpamD could not connect to server - ' . $response->{'status'} . ' - ' . $response->{'reason'} . ' - ' . $response->{'content'} );
176 my $header = Mail::AuthenticationResults::Header::Entry->new()->set_key( 'x-rspam' )->safe_set_value( 'temperror' );
177 $self->add_auth_header( $header );
178 $self->{ 'metrics_data' }->{ 'result' } = 'servererror';
179 $self->metric_count( 'rspamd_total', $self->{ 'metrics_data' } );
180 return;
181 }
182  
183 my $j = JSON->new();
184 my $rspamd_data = eval{ $j->decode( $response->{'content'} ); };
185 $self->handle_exception( $@ );
186 if ( ! exists( $rspamd_data->{'default'} ) ) {
187 $self->log_error( 'RSpamD bad data from server' );
188 my $header = Mail::AuthenticationResults::Header::Entry->new()->set_key( 'x-rspam' )->safe_set_value( 'temperror' );
189 $self->add_auth_header( $header );
190 $self->{ 'metrics_data' }->{ 'result' } = 'serverdataerror';
191 $self->metric_count( 'rspamd_total', $self->{ 'metrics_data' } );
192 return;
193 }
194 my $spam = $rspamd_data->{ 'default' };
195  
196 my $status = join( q{},
197 ( $spam->{'is_spam'} eq 0 ? 'No, ' : 'Yes, ' ),
198 'score=', sprintf( '%.02f', $spam->{'score'} ),
199 ' ',
200 'required=', sprintf( '%.02f', $spam->{'required_score'} ),
201 );
202  
203 my $action = $spam->{'action'};
204  
205 if ( $action eq 'rewrite subject' ) {
206 $action .= ' - ' . $spam->{'subject'};
207 ## ToDo - Rewrite the subject
208 }
209  
210 if ( $action eq 'reject' ) {
211 if ( $config->{'hard_reject'} ) {
212 if ( ( ! $self->is_local_ip_address() ) && ( ! $self->is_trusted_ip_address() ) ) {
213 $self->reject_mail( '550 5.7.0 SPAM policy violation' );
214 $self->dbgout( 'RSpamDReject', "Policy reject", LOG_INFO );
215 }
216 }
217 }
218  
219 $self->prepend_header( 'X-Spam-score', sprintf( '%.02f', $spam->{'score'} ) );
220 $self->prepend_header( 'X-Spam-Status', $status );
221 $self->prepend_header( 'X-Spam-Action', $action );
222  
223 my $header = Mail::AuthenticationResults::Header::Entry->new()->set_key( 'x-rspam' )->safe_set_value( ( $spam->{'is_spam'} eq 0 ? 'pass' : 'fail' ) );
224 $header->add_child( Mail::AuthenticationResults::Header::SubEntry->new()->set_key( 'score' )->safe_set_value( sprintf ( '%.02f', $spam->{'score'} ) ) );
225 $header->add_child( Mail::AuthenticationResults::Header::SubEntry->new()->set_key( 'required' )->safe_set_value( sprintf ( '%.02f', $spam->{'required_score'} ) ) );
226 $self->add_auth_header($header);
227  
228 $self->{ 'metrics_data' }->{ 'result' } = ( $spam->{'is_spam'} eq 0 ? 'pass' : 'fail' );
229  
230 $self->metric_count( 'rspamd_total', $self->{ 'metrics_data' } );
231 return if ( lc $config->{'remove_headers'} eq 'no' );
232  
233 foreach my $header_type ( qw{ X-Spam-score X-Spam-Status X-Spam-Action } ) {
234 if ( exists( $self->{'remove_headers'}->{ lc $header_type } ) ) {
235 foreach my $header ( reverse @{ $self->{'remove_headers'}->{ lc $header_type } } ) {
236 $self->dbgout( 'RemoveSpamHeader', $header_type . ', ' . $header, LOG_DEBUG );
237 $self->change_header( lc $header_type, $header, q{} );
238 }
239 }
240 }
241  
242 return;
243 }
244  
245 sub close_callback {
246 my ( $self ) = @_;
247  
248 delete $self->{'lines'};
249 delete $self->{'mail_from'};
250 delete $self->{'helo_name'};
251 delete $self->{'rcpt_to'};
252 delete $self->{'remove_headers'};
253 delete $self->{'header_index'};
254 delete $self->{'metrics_data'};
255 return;
256 }
257  
258 1;
259  
260 __END__
261  
262 =pod
263  
264 =encoding UTF-8
265  
266 =head1 NAME
267  
268 Mail::Milter::Authentication::Handler::RSpamD
269  
270 =head1 VERSION
271  
272 version 2.20180510
273  
274 =head1 DESCRIPTION
275  
276 Check email for spam using rspamd.
277  
278 =head1 CONFIGURATION
279  
280 "RSpamD" : {
281 "default_user" : "nobody",
282 "rs_host" : "localhost",
283 "rs_port" : "11333",
284 "hard_reject" : "1",
285 "remove_headers" : "yes"
286 },
287  
288 =head2 CONFIG
289  
290 Add a block to the handlers section of your config as follows.
291  
292 "RSpamD" : {
293 "default_user" : "nobody",
294 "rs_host" : "localhost",
295 "rs_port" : "11333",
296 "hard_reject" : "1",
297 "remove_headers" : "yes"
298 },
299  
300 =head1 AUTHOR
301  
302 Marc Bradshaw <marc@marcbradshaw.net>
303  
304 =head1 COPYRIGHT AND LICENSE
305  
306 This software is copyright (c) 2018 by Marc Bradshaw.
307  
308 This is free software; you can redistribute it and/or modify it under
309 the same terms as the Perl 5 programming language system itself.
310  
311 =cut