bin/submit_abuse_report

filter: Statementstmt 56.0% 175 / 312 Branchbran 30.7% 35 / 114 Conditioncond 28.8% 13 / 45 MC/DCmcdc 0.0% 0 / 25 Subroutinesub 85.0% 17 / 20 Podpod n/a totaltotal 46.5% 240 / 516 CC 59 SCAR 39.3
CC
59
Cov
47%
_send_report
182.0
_dry_run_report
48.1
_build_feedback_report
21.2
CRAP 50.8
« blib/lib/Email/Abuse/Investigator.pm ↑ Summary /usr/local/bin/perldoc »
1 #!/usr/bin/env perl
2 # -----------------------------------------------------------------------
3 # submit_abuse_report -- analyse a spam/phishing email and send abuse
4 # reports to all relevant parties.
5 #
6 # Usage:
7 # submit_abuse_report [options] spam.eml
8 # submit_abuse_report [options] < spam.eml
9 #
10 # Options:
11 # --dry-run Show what would be sent and to whom; do not
12 # actually connect to any mail server.
13 # -i, --interactive Prompt for confirmation before each send.
14 # --bcc Send a copy to the --from address for monitoring.
15 # --bcc-to ADDRESS Send a copy to an explicit address.
16 # --from ADDRESS Envelope / From: address for the outgoing
17 # reports (required unless --dry-run).
18 # --smtp HOST[:PORT] SMTP relay to use (default: localhost:25).
19 # --trusted CIDR Trusted relay CIDR to skip in Received: chain.
20 # May be repeated for multiple relays.
21 # --timeout SECS Network timeout in seconds (default: 15).
22 # --verbose Print analysis progress to STDERR.
23 # --help Show this help text.
24 #
25 # Examples:
26 # # Dry run -- see what would be sent without sending anything
27 # submit_abuse_report --dry-run spam.eml
28 #
29 # # Send reports via the local MTA
30 # submit_abuse_report --from postmaster@myisp.example spam.eml
31 #
32 # # Send via a specific SMTP relay, skipping our own outbound IP
33 # submit_abuse_report \
34 # --from abuse-reporter@example.com \
35 # --smtp mail.example.com:587 \
36 # --trusted 203.0.113.0/24 \
37 # spam.eml
38 # -----------------------------------------------------------------------
39 6 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 6 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 6 ▶use open qw(:std :encoding(UTF-8));
Subroutine BEGIN: called CC=1 SCAR=0.0
44  
45 6 ▶use Getopt::Long qw(GetOptions);
Subroutine BEGIN: called CC=1 SCAR=0.0
46 6 ▶use Pod::Usage qw(pod2usage);
Subroutine BEGIN: called CC=1 SCAR=0.0
47 6 ▶use Net::SMTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
48 6 ▶use MIME::Base64 qw(encode_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
49 6 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
50 6 ▶use File::Basename qw(basename);
Subroutine BEGIN: called CC=1 SCAR=0.0
51 6 ▶use lib '.'; # find Email/Abuse/Investigator.pm in development tree
Subroutine BEGIN: called CC=1 SCAR=0.0
52 6 ▶use Email::Abuse::Investigator;
Subroutine BEGIN: called CC=1 SCAR=0.0
53  
54 # -----------------------------------------------------------------------
55 # Command-line options
56 # -----------------------------------------------------------------------
57 6 my $dry_run = 0;
58 6 my $interactive = 0;
59 6 my $bcc = 0; # --bcc flag: copy to --from address
60 6 my $bcc_to = ''; # --bcc-to ADDRESS: copy to explicit address
61 6 my $from = '';
62 6 my $smtp_arg = 'localhost:25';
63 6 my $timeout = 15;
64 6 my $verbose = 0;
65 6 my $help = 0;
66 6 my @trusted;
67  
68 6 ▶GetOptions(
Branch: 1 branch
BranchTrueFalseTotal
&GetOptions("dry-run", \$dry_run, "interactive|i", \$interactive, "bcc", \$bcc, "bcc-to=s", \$bcc_to, "from=s", \$from, "smtp=s", \$smtp_arg, "trusted=s", \@trusted, "timeout=i", \$timeout, "verbose", \$verbose, "help", \$help) or pod2usage(2) 0 6 6
69 'dry-run' => \$dry_run,
70 'interactive|i' => \$interactive,
71 'bcc' => \$bcc,
72 'bcc-to=s' => \$bcc_to,
73 'from=s' => \$from,
74 'smtp=s' => \$smtp_arg,
75 'trusted=s' => \@trusted,
76 'timeout=i' => \$timeout,
77 'verbose' => \$verbose,
78 'help' => \$help,
79 ) or pod2usage(2);
80  
81 6 ▶pod2usage( -exitval => 0, -verbose => 2 ) if $help;
Branch: 1 branch
BranchTrueFalseTotal
if $help 2 4 6
82  
83 4 ▶unless ($dry_run || $from) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dry_run or $from) 0 4 4
Condition33%1/3
$dry_run or $from
l!l&&r!l&&!r
400
MC/DC0%0/2
$dry_run or $from
$dry_run $from
Truth table33%1/3
A or B
A= $dry_runB= $from
ABresult
1X1
011
000
84 0 die basename($0) . ": --from ADDRESS is required unless --dry-run is used.\n"
85 . "Run with --help for usage.\n";
86 }
87  
88 4 ▶if ($from && $from !~ /\@/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from and not $from =~ /\@/) 0 4 4
Condition33%1/3
$from and not $from =~ /\@/
!ll&&!rl&&r
400
MC/DC0%0/2
$from and not $from =~ /\@/
$from not $from =~ /\@/
Truth table33%1/3
A and not(B)
A= $fromB= not $from =~ /\@/
ABresult
0X0
100
111
89 0 die basename($0) . ": --from value '$from' does not look like an email address.\n";
90 }
91  
92 4 my ($smtp_host, $smtp_port) = split /:/, $smtp_arg, 2;
93  
94 # Resolve BCC address.
95 # --bcc alone copies to --from; --bcc-to ADDRESS uses an explicit address.
96 4 my $bcc_addr = undef;
97 4 ▶if ($bcc_to) {
Branch: 2 branches
BranchTrueFalseTotal
if ($bcc_to) { } 0 4 4
elsif ($bcc) { } 0 4 4
98 0 ▶ die basename($0) . ": --bcc-to value '$bcc_to' does not look like an email address.\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $bcc_to =~ /\@/ 0 0 0
99 unless $bcc_to =~ /\@/;
100 0 $bcc_addr = $bcc_to;
101 } elsif ($bcc) {
102 0 ▶ die basename($0) . ": --bcc requires --from to be set.\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $from 0 0 0
103 unless $from;
104 0 $bcc_addr = $from;
105 }
106 4 ▶$smtp_port //= 25;
Condition50%1/2
$smtp_port //= 25
l!l
40
MC/DC0%0/1
$smtp_port //= 25
$smtp_port
Truth table50%1/2
A
A= $smtp_port
Aresult
11
00
107  
108 # -----------------------------------------------------------------------
109 # Read the raw email
110 # -----------------------------------------------------------------------
111 4 my $raw;
112 4 ▶if (@ARGV) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ARGV) { } 4 0 4
113 4 ▶ open my $fh, '<:raw', $ARGV[0] or die basename($0), ": cannot open '$ARGV[0]': $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $ARGV[0] or die basename($0), ": cannot open '$ARGV[0]': $!" 0 4 4
114 4 local $/;
115 4 $raw = <$fh>;
116 4 close $fh;
117 } else {
118 0 binmode STDIN, ':raw';
119 0 local $/;
120 0 $raw = <STDIN>;
121 }
122  
123 4 ▶die basename($0) . ": no email data supplied.\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw and length $raw 0 4 4
Condition33%1/3
defined $raw and length $raw
!ll&&!rl&&r
004
MC/DC0%0/2
defined $raw and length $raw
defined $raw length $raw
Truth table33%1/3
A and B
A= defined $rawB= length $raw
ABresult
0X0
100
111
124 unless defined $raw && length $raw;
125  
126 # -----------------------------------------------------------------------
127 # Analyse
128 # -----------------------------------------------------------------------
129 4 ▶print STDERR "Analysing message...\n" if $verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $verbose 0 4 4
130  
131 4 my $inv = Email::Abuse::Investigator->new(
132 timeout => $timeout,
133 trusted_relays => \@trusted,
134 verbose => $verbose,
135 );
136 4 $inv->parse_email(\$raw);
137  
138 4 my @contacts = $inv->abuse_contacts();
139  
140 4 ▶unless (@contacts) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@contacts) 2 2 4
141 2 print STDERR "No abuse contacts could be determined. Nothing to send.\n";
142  
143 # List any domains and URL hosts that were found but could not be
144 # resolved to an abuse contact, so the user knows where to look.
145 2 _print_unresolved($inv, \*STDERR);
146 2 exit 0;
147 }
148  
149 # -----------------------------------------------------------------------
150 # _print_unresolved( $inv, $fh )
151 #
152 # Print a list of domains and URL hosts found in the message that could
153 # not be resolved to an abuse contact, so the user knows where to look.
154 # -----------------------------------------------------------------------
155 sub _print_unresolved {
156 4 ▶ my ($inv, $fh) = @_;
Subroutine _print_unresolved: called CC=4 SCAR=13.9
157  
158 # Delegate to the module's unresolved_contacts() method which handles
159 # all the filtering logic (spoofable headers, already-covered domains).
160 4 my @unresolved = $inv->unresolved_contacts();
161 4 ▶ return unless @unresolved;
Branch: 1 branch
BranchTrueFalseTotal
unless @unresolved 0 4 4
162  
163 4 print $fh "\nDomains found in this message with no abuse contact determined\n";
164 4 print $fh "(consider investigating or reporting manually):\n\n";
165 4 for my $u (@unresolved) {
166 4 ▶ if ($u->{type} eq 'url_host') {
Branch: 1 branch
BranchTrueFalseTotal
if ($u->{'type'} eq 'url_host') { } 3 1 4
167 3 print $fh " URL host : $u->{domain}\n";
168 } else {
169 1 print $fh " Domain : $u->{domain}\n";
170 }
171 }
172 4 print $fh "\n";
173 }
174  
175 2 my $report_text = $inv->abuse_report_text();
176  
177 # Append a note to the human-readable part so recipients know the
178 # original message is attached and why.
179 2 $report_text .= join("\n",
180 "",
181 "-" x 72,
182 "The original spam/phishing message is attached below as a",
183 "message/rfc822 MIME part. Please use the full Received: headers",
184 "to locate the relevant SMTP session in your mail logs.",
185 "-" x 72,
186 "");
187  
188 2 my $orig = $inv->originating_ip();
189 2 my $risk = $inv->risk_assessment();
190  
191 # Build a consistent subject line for all outgoing reports
192 2 my $subject = _build_subject($orig, $risk);
193  
194 # -----------------------------------------------------------------------
195 # Dry run: describe what would be sent
196 # -----------------------------------------------------------------------
197 2 ▶if ($dry_run) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dry_run) 2 0 2
198 2 _dry_run_report(\@contacts, $subject, $report_text, \$raw, $inv, $bcc_addr);
199 2 exit 0;
200 }
201  
202 # -----------------------------------------------------------------------
203 # Live run: send one email per unique abuse contact
204 # -----------------------------------------------------------------------
205 0 my $sent = 0;
206 0 my $failed = 0;
207  
208 0 for my $contact (@contacts) {
209 0 my $to = $contact->{address};
210 0 my $role = $contact->{role};
211  
212 0 ▶ if ($interactive) {
Branch: 1 branch
BranchTrueFalseTotal
if ($interactive) 0 0 0
213 0 printf "\nSend abuse report to: %s\n", $to;
214 0 printf "Reason : %s\n", $role;
215 0 print "Send? [y/N] ";
216 0 my $ans = _read_tty();
217 0 ▶ unless (defined $ans && lc($ans) eq 'y') {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ans and lc $ans eq "y") 0 0 0
Condition0%0/3
defined $ans and lc $ans eq "y"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $ans and lc $ans eq "y"
defined $ans lc $ans eq "y"
Truth table0%0/3
A and B
A= defined $ansB= lc $ans eq "y"
ABresult
0X0
100
111
218 0 printf "Skipped: %-45s %s\n", $to, $role;
219 0 next;
220 }
221 }
222  
223 0 ▶ print STDERR "Sending to $to ($role)...\n" if $verbose;
Branch: 1 branch
BranchTrueFalseTotal
if $verbose 0 0 0
224  
225 0 my $ok = _send_report(
226 smtp_host => $smtp_host,
227 smtp_port => $smtp_port,
228 from => $from,
229 to => $to,
230 bcc => $bcc_addr,
231 subject => $subject,
232 body => $report_text,
233 original => \$raw,
234 inv => $inv,
235 timeout => $timeout,
236 );
237  
238 0 ▶ if ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) { } 0 0 0
239 0 printf "Sent : %-45s %s\n", $to, $role;
240 0 $sent++;
241 } else {
242 0 printf "FAILED : %-45s %s\n", $to, $role;
243 0 $failed++;
244 }
245 }
246  
247 0 printf "\nDone: %d sent, %d failed.\n", $sent, $failed;
248 0 _print_unresolved($inv, \*STDOUT);
249 0 ▶exit( $failed ? 1 : 0 );
Branch: 1 branch
BranchTrueFalseTotal
$failed ? : 0 0 0
250  
251 # -----------------------------------------------------------------------
252 # _dry_run_report( \@contacts, $subject, $report_text, \$raw, $inv )
253 #
254 # Print a full description of what would be sent without sending anything.
255 # -----------------------------------------------------------------------
256 sub _dry_run_report {
257 2 ▶ my ($contacts, $subject, $body, $raw_ref, $inv, $bcc) = @_;
Subroutine _dry_run_report: called CC=23 SCAR=38.7
258  
259 2 my $bar = '=' x 72;
260 2 print "$bar\n";
261 2 print " DRY RUN -- no email will be sent\n";
262 2 print "$bar\n\n";
263  
264 2 printf "Subject : %s\n\n", $subject;
265 2 print "Envelope sender: <> (null reverse-path per RFC 6650 s.3)\n";
266 2 ▶ printf "BCC copy to : %s\n", $bcc if $bcc;
Branch: 1 branch
BranchTrueFalseTotal
if $bcc 0 2 2
267 2 print "\n";
268  
269 2 printf "%-3s %-45s %s\n", '#', 'Recipient', 'Role';
270 2 printf "%-3s %-45s %s\n", '-' x 3, '-' x 45, '-' x 24;
271  
272 2 my $n = 1;
273 2 for my $c (@{$contacts}) {
274 2 printf "%-3d %-45s %s\n", $n++, $c->{address}, $c->{role};
275 printf " via: %-42s note: %s\n",
276 2 ▶ $c->{via}, ($c->{note} || '');
Condition50%1/2
$c->{'note'} || ''
l!l
20
MC/DC0%0/1
$c->{'note'} || ''
$c->{'note'}
Truth table50%1/2
A
A= $c->{'note'}
Aresult
11
00
277 2 print "\n";
278 }
279  
280 # Part 1
281 2 print "$bar\n";
282 2 print " PART 1: HUMAN-READABLE REPORT (text/plain)\n";
283 2 print " (identical text sent to every recipient above)\n";
284 2 print "$bar\n\n";
285 2 print $body;
286  
287 # Part 2: feedback-report fields
288 2 print "\n$bar\n";
289 2 print " PART 2: ARF METADATA (message/feedback-report)\n";
290 2 print " RFC 5965 s.3 -- machine-readable fields for automated processing\n";
291 2 print "$bar\n\n";
292 2 my $fbr = _build_feedback_report($inv);
293 2 print " $_\n" for split /\r?\n/, $fbr;
294  
295 # Part 3: original message preview
296 2 print "\n$bar\n";
297 2 print " PART 3: ORIGINAL MESSAGE (message/rfc822)\n";
298 2 print " RFC 5965 s.2 -- verbatim original; MUST be included\n";
299 2 print "$bar\n";
300 2 ▶ if (defined $raw_ref && length $$raw_ref) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $raw_ref and length $$raw_ref) { } 2 0 2
Condition33%1/3
defined $raw_ref and length $$raw_ref
!ll&&!rl&&r
002
MC/DC0%0/2
defined $raw_ref and length $$raw_ref
defined $raw_ref length $$raw_ref
Truth table33%1/3
A and B
A= defined $raw_refB= length $$raw_ref
ABresult
0X0
100
111
301 2 my @lines = split /\r?\n/, $$raw_ref;
302 2 my $preview = 20;
303 2 my $total = scalar @lines;
304 2 ▶ printf " [Showing first %d of %d lines]\n\n",
Branch: 1 branch
BranchTrueFalseTotal
$total < $preview ? : 2 0 2
305 ($total < $preview ? $total : $preview), $total;
306 2 ▶ print " $_\n" for @lines[ 0 .. ($total < $preview ? $total - 1 : $preview - 1) ];
Branch: 1 branch
BranchTrueFalseTotal
$total < $preview ? : 2 0 2
307 2 ▶ print " ...\n" if $total > $preview;
Branch: 1 branch
BranchTrueFalseTotal
if $total > $preview 0 2 2
308 } else {
309 0 print " (no original message available)\n";
310 }
311  
312 2 print "\n$bar\n";
313  
314 # abuse_contacts() now merges duplicate addresses, so @contacts has one
315 # entry per unique address with 'role' already set to the combined string.
316 # Count the total discovery routes (sum of all roles arrays) to show
317 # in the annotation when merging occurred.
318 2 my $n_contacts = scalar @{$contacts};
319 2 my $n_routes = 0;
320 2 ▶ $n_routes += scalar @{ $_->{roles} // [$_->{role}] } for @{$contacts};
Condition50%1/2
$_->{"roles"} // [$_->{"role"}]
l!l
20
MC/DC0%0/1
$_->{"roles"} // [$_->{"role"}]
$_->{"roles"}
Truth table50%1/2
A
A= $_->{"roles"}
Aresult
11
00
321  
322 2 ▶ if ($n_routes > $n_contacts) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_routes > $n_contacts) { } 0 2 2
323 # Some addresses cover more than one discovery route -- note the merge
324 0 ▶ printf " Total: %d recipient%s (%d contact route%s merged)\n",
Branch: 2 branches
BranchTrueFalseTotal
$n_contacts == 1 ? : 0 0 0
$n_routes == 1 ? : 0 0 0
325 $n_contacts, $n_contacts == 1 ? '' : 's',
326 $n_routes, $n_routes == 1 ? '' : 's';
327 } else {
328 2 ▶ printf " Total: %d recipient%s\n",
Branch: 1 branch
BranchTrueFalseTotal
$n_contacts == 1 ? : 2 0 2
329 $n_contacts, $n_contacts == 1 ? '' : 's';
330 }
331 2 print "\n";
332  
333 # One line per recipient; 'role' is already the merged string
334 2 for my $c (@{$contacts}) {
335 2 printf " %s (%s)\n", $c->{address}, $c->{role};
336 }
337  
338 # Web-form contacts -- providers that do not accept email
339 2 my @form_cs = $inv->form_contacts();
340 2 ▶ if (@form_cs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@form_cs) 0 2 2
341 0 print "\n$bar\n";
342 0 print " MANUAL ACTION REQUIRED -- WEB FORM SUBMISSION\n";
343 0 print " The following parties do not accept email abuse reports.\n";
344 0 print " Open each URL in a browser and complete the form as instructed.\n";
345 0 print "$bar\n\n";
346 0 for my $c (@form_cs) {
347 0 printf " Role : %s\n", $c->{role};
348 0 printf " Form URL : %s\n", $c->{form};
349 0 ▶ printf " Domain : %s\n", $c->{form_domain} if $c->{form_domain};
Branch: 1 branch
BranchTrueFalseTotal
if $c->{"form_domain"} 0 0 0
350 0 ▶ if ($c->{form_paste}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->{"form_paste"}) 0 0 0
351 0 printf " Paste : %s\n", $c->{form_paste};
352 }
353 0 ▶ if ($c->{form_upload}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->{"form_upload"}) 0 0 0
354 0 printf " Upload : %s\n", $c->{form_upload};
355 }
356 0 print "\n";
357 }
358 }
359  
360 2 print "$bar\n";
361  
362 2 _print_unresolved($inv, \*STDOUT);
363 }
364  
365 # -----------------------------------------------------------------------
366 # _read_tty() -> string | undef
367 #
368 # Read a single line from the controlling terminal. Extracted into its
369 # own sub so tests can override it without spawning a pseudo-terminal.
370 # Returns the chomped input string, or undef if /dev/tty is unavailable.
371 # -----------------------------------------------------------------------
372 sub _read_tty {
373 0 ▶ my $tty;
Subroutine _read_tty: not called CC=3 SCAR=24.8
374 0 ▶ unless (open $tty, '<', '/dev/tty') {
Branch: 1 branch
BranchTrueFalseTotal
unless (open $tty, "<", "/dev/tty") 0 0 0
375 0 warn "Cannot open /dev/tty for interactive prompt; skipping\n";
376 0 return undef;
377 }
378 0 my $ans = <$tty>;
379 0 close $tty;
380 0 ▶ chomp $ans if defined $ans;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ans 0 0 0
381 0 return $ans;
382 }
383  
384 # -----------------------------------------------------------------------
385 # _send_report( %args ) -> bool
386 #
387 # Send a single ARF-compliant abuse report via SMTP.
388 # Returns 1 on success, 0 on failure.
389 # Errors are printed to STDERR; the caller continues to the next recipient.
390 #
391 # Envelope sender is the null reverse-path (<>) per RFC 6650 s.3, which
392 # requires this to prevent mail loops and DSN storms. The From: header
393 # still carries the reporter's address for human reply purposes.
394 # -----------------------------------------------------------------------
395 sub _send_report {
396 0 ▶ my (%a) = @_;
Subroutine _send_report: not called CC=13 SCAR=52.0
397  
398 0 my $date = strftime('%a, %d %b %Y %H:%M:%S +0000', gmtime);
399 my $msg_id = sprintf '<%s.%d@%s>',
400 strftime('%Y%m%d%H%M%S', gmtime),
401 $$,
402 0 do { (my $h = $a{from}) =~ s/.*\@//; $h };
403  
404 my $mail = _build_mime_message(
405 date => $date,
406 from => $a{from},
407 to => $a{to},
408 bcc => $a{bcc},
409 subject => $a{subject},
410 msg_id => $msg_id,
411 body => $a{body},
412 original => $a{original},
413 inv => $a{inv},
414 0 );
415  
416 # Developer aid: set SUBMIT_ABUSE_DUMP_MIME=path to write the raw MIME
417 # message to a file for inspection (e.g. SUBMIT_ABUSE_DUMP_MIME=/tmp/out.eml).
418 0 ▶ if (my $dump = $ENV{SUBMIT_ABUSE_DUMP_MIME}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $dump = $ENV{"SUBMIT_ABUSE_DUMP_MIME"}) 0 0 0
419 0 ▶ if (open my $fh, '>', $dump) {
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, ">", $dump) 0 0 0
420 0 print $fh $mail;
421 0 close $fh;
422 0 warn "MIME message written to $dump\n";
423 }
424 }
425  
426 0 my $smtp = eval {
427 Net::SMTP->new(
428 $a{smtp_host},
429 Port => $a{smtp_port},
430 Timeout => $a{timeout},
431 0 );
432 };
433  
434 0 ▶ unless ($smtp) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($smtp) 0 0 0
435 0 warn "SMTP connect to $a{smtp_host}:$a{smtp_port} failed: $@\n";
436 0 return 0;
437 }
438  
439 0 my $ok = eval {
440 # Null reverse-path per RFC 6650 s.3 -- prevents DSN/mail loops
441 0 ▶ $smtp->mail( '' ) or die "MAIL FROM failed\n";
Branch: 1 branch
BranchTrueFalseTotal
$smtp->mail("") or die "MAIL FROM failed\n" 0 0 0
442 0 ▶ $smtp->to( $a{to} ) or die "RCPT TO failed\n";
Branch: 1 branch
BranchTrueFalseTotal
$smtp->to($a{"to"}) or die "RCPT TO failed\n" 0 0 0
443 $smtp->to( $a{bcc} ) or die "RCPT TO (bcc) failed\n"
444 0 ▶ if $a{bcc};
Branch: 1 branch
BranchTrueFalseTotal
if $a{"bcc"} 0 0 0
Condition0%0/5
$a{'bcc'} && ($smtp->to($a{'bcc'}) || die("RCPT TO (bcc) failed\n"))
!ll&&!rl&&r
000
$smtp->to($a{"bcc"}) or die "RCPT TO (bcc) failed\n"
l!l
00
MC/DC0%0/2
$a{'bcc'} && ($smtp->to($a{'bcc'}) || die("RCPT TO (bcc) failed\n"))
$a{'bcc'} $smtp->to($a{"bcc"})
Truth table0%0/3
A && B
A= $a{'bcc'}B= $smtp->to($a{"bcc"})
ABresult
0X0
100
111
445 0 ▶ $smtp->data() or die "DATA failed\n";
Branch: 1 branch
BranchTrueFalseTotal
$smtp->data or die "DATA failed\n" 0 0 0
446 0 ▶ $smtp->datasend($mail) or die "datasend failed\n";
Branch: 1 branch
BranchTrueFalseTotal
$smtp->datasend($mail) or die "datasend failed\n" 0 0 0
447 0 ▶ $smtp->dataend() or die "dataend failed\n";
Branch: 1 branch
BranchTrueFalseTotal
$smtp->dataend or die "dataend failed\n" 0 0 0
448 0 $smtp->quit();
449 0 1;
450 };
451  
452 0 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
453 0 ▶ my $err = $@ || 'unknown SMTP error';
Condition0%0/2
$@ || 'unknown SMTP error'
l!l
00
MC/DC0%0/1
$@ || 'unknown SMTP error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
454 0 $err =~ s/\s+$//;
455 0 warn "SMTP error sending to $a{to}: $err\n";
456 0 return 0;
457 }
458  
459 0 return 1;
460 }
461  
462 # -----------------------------------------------------------------------
463 # _build_feedback_report( $inv ) -> string
464 #
465 # Constructs the body of the message/feedback-report MIME part (Part 2)
466 # as defined in RFC 5965 s.3. The returned string uses CRLF line endings
467 # and contains only 7-bit ASCII, as required by the RFC.
468 #
469 # Fields included:
470 # Feedback-Type -- always "abuse"
471 # User-Agent -- module name and version
472 # Version -- always "1" (RFC 5965 version)
473 # Source-IP -- originating IP from Received: chain analysis
474 # Original-Mail-From -- Return-Path: or From: of the spam
475 # Original-Rcpt-To -- To: of the spam
476 # Arrival-Date -- Date: header of the spam (as received)
477 # Reported-Domain -- primary contact domain (first of all_domains())
478 # Reported-Uri -- each HTTP/HTTPS URL found in the spam body
479 # Authentication-Results -- forwarded from the spam's own header
480 # -----------------------------------------------------------------------
481 sub _build_feedback_report {
482 2 ▶ my ($inv) = @_;
Subroutine _build_feedback_report: called CC=16 SCAR=30.5
483  
484 2 my @fields;
485  
486 # Required fields (RFC 5965 s.3.1)
487 2 push @fields, 'Feedback-Type: abuse';
488 2 push @fields, 'User-Agent: Email::Abuse::Investigator/'
489 . $Email::Abuse::Investigator::VERSION;
490 2 push @fields, 'Version: 1';
491  
492 # Source-IP -- the identified originating address
493 2 my $orig = $inv->originating_ip();
494 2 ▶ push @fields, "Source-IP: $orig->{ip}" if $orig && $orig->{ip};
Branch: 1 branch
BranchTrueFalseTotal
if $orig and $orig->{"ip"} 0 2 2
Condition33%1/3
$orig and $orig->{"ip"}
!ll&&!rl&&r
200
MC/DC0%0/2
$orig and $orig->{"ip"}
$orig $orig->{"ip"}
Truth table33%1/3
A and B
A= $origB= $orig->{"ip"}
ABresult
0X0
100
111
495  
496 # Original-Mail-From -- envelope sender of the spam
497 # Prefer Return-Path (true envelope sender); fall back to From:
498 2 ▶ my $mail_from = $inv->header_value('return-path')
Condition40%2/5
($inv->header_value("return-path") // $inv->header_value("from")) // ""
l!l
20
$inv->header_value("return-path") // $inv->header_value("from")
l!l&&r!l&&!r
020
MC/DC0%0/2
($inv->header_value("return-path") // $inv->header_value("from")) // ""
$inv->header_value("return-path") $inv->header_value("from")
Truth table33%1/3
A // B
A= $inv->header_value("return-path")B= $inv->header_value("from")
ABresult
1X1
011
000
499 // $inv->header_value('from')
500 // '';
501 2 $mail_from =~ s/^\s*<?\s*|\s*>?\s*$//g; # strip angle brackets and whitespace
502 2 ▶ push @fields, "Original-Mail-From: <$mail_from>" if $mail_from;
Branch: 1 branch
BranchTrueFalseTotal
if $mail_from 2 0 2
503  
504 # Original-Rcpt-To -- envelope recipient(s) of the spam
505 # Use the To: header; for each distinct address found
506 2 ▶ my $rcpt_to = $inv->header_value('to') // '';
Condition50%1/2
$inv->header_value("to") // ""
l!l
20
MC/DC0%0/1
$inv->header_value("to") // ""
$inv->header_value("to")
Truth table50%1/2
A
A= $inv->header_value("to")
Aresult
11
00
507 # Extract individual addresses (bare addr@domain or <addr@domain>)
508 2 my %rcpt_seen;
509 2 ▶ while ($rcpt_to =~ /<?([^\s<>,;]+\@[\w.-]+)>?/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rcpt_to =~ /<?([^\s<>,;]+\@[\w.-]+)>?/g) 2 2 4
510 2 my $addr = lc $1;
511 2 ▶ push @fields, "Original-Rcpt-To: <$addr>" unless $rcpt_seen{$addr}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $rcpt_seen{$addr}++ 2 0 2
512 }
513  
514 # Arrival-Date -- when we (the reporter) received the spam
515 2 ▶ my $arrival = $inv->header_value('date') // '';
Condition50%1/2
$inv->header_value("date") // ""
l!l
20
MC/DC0%0/1
$inv->header_value("date") // ""
$inv->header_value("date")
Truth table50%1/2
A
A= $inv->header_value("date")
Aresult
11
00
516 2 ▶ push @fields, "Arrival-Date: $arrival" if $arrival;
Branch: 1 branch
BranchTrueFalseTotal
if $arrival 2 0 2
517  
518 # Reported-Domain -- the primary contact domain
519 2 my ($rdomain) = $inv->all_domains();
520 2 ▶ push @fields, "Reported-Domain: $rdomain" if $rdomain;
Branch: 1 branch
BranchTrueFalseTotal
if $rdomain 2 0 2
521  
522 # Reported-Uri -- each distinct URL in the spam body
523 2 my %uri_seen;
524 2 for my $u ($inv->embedded_urls()) {
525 push @fields, "Reported-Uri: $u->{url}"
526 2 ▶ unless $uri_seen{ $u->{url} }++;
Branch: 1 branch
BranchTrueFalseTotal
unless $uri_seen{$u->{"url"}}++ 2 0 2
527 }
528  
529 # Authentication-Results -- forwarded verbatim from the spam headers
530 2 ▶ my $auth_res = $inv->header_value('authentication-results') // '';
Condition50%1/2
$inv->header_value("authentication-results") // ""
l!l
02
MC/DC0%0/1
$inv->header_value("authentication-results") // ""
$inv->header_value("authentication-results")
Truth table50%1/2
A
A= $inv->header_value("authentication-results")
Aresult
11
00
531 2 ▶ push @fields, "Authentication-Results: $auth_res" if $auth_res;
Branch: 1 branch
BranchTrueFalseTotal
if $auth_res 0 2 2
532  
533 2 return join("\r\n", @fields) . "\r\n";
534 }
535  
536 # -----------------------------------------------------------------------
537 # _build_mime_message( %args ) -> string
538 #
539 # Constructs a fully RFC 5965 compliant multipart/report MIME message
540 # suitable for transmission via Net::SMTP->datasend().
541 #
542 # Three-part structure per RFC 5965 s.2:
543 # Part 1 text/plain; charset=UTF-8 -- human-readable abuse report
544 # Part 2 message/feedback-report -- ARF machine-readable metadata
545 # Part 3 message/rfc822 -- original spam message verbatim
546 #
547 # All line endings in the returned string are CRLF (\r\n).
548 # Part 2 uses 7bit encoding (required by RFC 5965 s.3).
549 # -----------------------------------------------------------------------
550 sub _build_mime_message {
551 0 ▶ my (%a) = @_;
Subroutine _build_mime_message: not called CC=4 SCAR=30.0
552  
553 # Boundary unique per message; must not appear in any part body
554 0 my $boundary = sprintf 'arf_report_%s_%d',
555 strftime('%Y%m%d%H%M%S', gmtime), $$;
556  
557 # Normalise line endings to CRLF throughout, then encode to raw UTF-8
558 # bytes. Net::SMTP->datasend() calls syswrite() on a raw socket and
559 # cannot handle Perl strings with the Unicode flag set (wide characters).
560 # The body may contain non-ASCII characters (e.g. emoji in decoded subject
561 # lines) so we must encode explicitly rather than rely on the socket layer.
562 0 (my $body_crlf = $a{body}) =~ s/\r?\n/\r\n/g;
563 0 my $original_crlf = '';
564 0 ▶ if (defined $a{original} && length ${ $a{original} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $a{"original"} and length ${$a{"original"};}) 0 0 0
Condition0%0/3
defined $a{"original"} and length ${$a{"original"};}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $a{"original"} and length ${$a{"original"};}
defined $a{"original"} length ${$a{"original"};}
Truth table0%0/3
A and B
A= defined $a{"original"}B= length ${$a{"original"};}
ABresult
0X0
100
111
565 0 ($original_crlf = ${ $a{original} }) =~ s/\r?\n/\r\n/g;
566 }
567 0 my $feedback_report = _build_feedback_report($a{inv});
568  
569 # ---- Outer envelope headers ----
570 0 my @msg;
571 0 push @msg, "Date: $a{date}";
572 0 push @msg, "From: $a{from}";
573 0 push @msg, "To: $a{to}";
574 0 push @msg, "Subject: $a{subject}";
575 0 push @msg, "Message-ID: $a{msg_id}";
576 0 push @msg, "MIME-Version: 1.0";
577 # multipart/report with report-type=feedback-report per RFC 5965 s.2
578 0 push @msg, "Content-Type: multipart/report;";
579 0 push @msg, " report-type=feedback-report;";
580 0 push @msg, " boundary=\"$boundary\"";
581 0 push @msg, "X-Mailer: Email::Abuse::Investigator submit_abuse_report";
582 0 ▶ push @msg, "X-Report-Monitor: $a{bcc}" if $a{bcc};
Branch: 1 branch
BranchTrueFalseTotal
if $a{"bcc"} 0 0 0
583 0 push @msg, "";
584  
585 # Preamble for non-MIME clients
586 0 push @msg, "This is an ARF (Abuse Reporting Format) feedback report.";
587 0 push @msg, "See https://datatracker.ietf.org/doc/html/rfc5965";
588 0 push @msg, "";
589  
590 # ---- Part 1: human-readable summary (RFC 5965 s.2 "first part") ----
591 0 push @msg, "--$boundary";
592 0 push @msg, "Content-Type: text/plain; charset=UTF-8";
593 0 push @msg, "Content-Transfer-Encoding: 8bit";
594 0 push @msg, "Content-Disposition: inline";
595 0 push @msg, "";
596 0 push @msg, $body_crlf;
597  
598 # ---- Part 2: ARF machine-readable metadata (RFC 5965 s.3) ----
599 0 push @msg, "--$boundary";
600 0 push @msg, "Content-Type: message/feedback-report";
601 0 push @msg, "Content-Transfer-Encoding: 7bit"; # required by RFC 5965
602 0 push @msg, "";
603 0 push @msg, $feedback_report;
604  
605 # ---- Part 3: original spam message (RFC 5965 s.2 "third part") ----
606 # Use base64 encoding so Outlook and other clients reliably show
607 # it as a downloadable .eml attachment rather than rendering it
608 # inline or discarding it.
609 0 my $original_b64 = MIME::Base64::encode_base64($original_crlf, "\r\n");
610 0 push @msg, "--$boundary";
611 0 push @msg, "Content-Type: application/octet-stream; name=\"original_message.eml.txt\"";
612 0 push @msg, "Content-Transfer-Encoding: base64";
613 0 push @msg, "Content-Disposition: attachment;";
614 0 push @msg, " filename=\"original_message.eml.txt\"";
615 0 push @msg, "Content-Description: Original spam/phishing message";
616 0 push @msg, "";
617 0 push @msg, $original_b64;
618  
619 # Closing boundary
620 0 push @msg, "--${boundary}--";
621 0 push @msg, "";
622  
623 0 require Encode;
624 0 my $result = join("\r\n", @msg);
625 0 return Encode::encode('UTF-8', $result);
626 }
627  
628 # -----------------------------------------------------------------------
629 # _build_subject( $orig_hashref, $risk_hashref ) -> string
630 #
631 # Build a concise, informative subject line for the abuse report.
632 # -----------------------------------------------------------------------
633 sub _build_subject {
634 2 ▶ my ($orig, $risk) = @_;
Subroutine _build_subject: called CC=2 SCAR=7.0
635  
636 2 ▶ my $ip_part = $orig ? $orig->{ip} : 'unknown origin';
Branch: 1 branch
BranchTrueFalseTotal
$orig ? : 0 2 2
637 2 my $level = $risk->{level};
638 2 my $date_part = strftime('%Y-%m-%d', gmtime);
639  
640 2 return "Abuse report [$level]: spam/phishing from $ip_part ($date_part)";
641 }
642  
643 __END__
644  
645 =head1 NAME
646  
647 submit_abuse_report -- analyse a spam/phishing email and send abuse
648 reports to all relevant parties
649  
650 =head1 SYNOPSIS
651  
652 submit_abuse_report [options] spam.eml
653 submit_abuse_report [options] < spam.eml
654  
655 =head1 OPTIONS
656  
657 =over 4
658  
659 =item B<--dry-run>
660  
661 Analyse the message and print a full description of what would be sent
662 and to whom, but do not connect to any mail server or send anything.
663 Useful for reviewing before committing to sending.
664  
665 =item B<-i>, B<--interactive>
666  
667 Prompt for confirmation before sending each abuse report, similar to
668 C<rm -i>. For each recipient the address and the reason for contacting
669 them are displayed, followed by a C<Send? [y/N]> prompt. Only reports
670 where the user answers C<y> (case-insensitive) are sent; all others are
671 skipped and counted in the summary. Has no effect in B<--dry-run> mode.
672  
673 =item B<--bcc>
674  
675 Send a blind carbon copy of every report to the B<--from> address.
676 The most common use case: keep a personal record of every report sent
677 without specifying a separate address.
678  
679 =item B<--bcc-to ADDRESS>
680  
681 Send a blind carbon copy of every report to ADDRESS. Use this when the
682 monitoring address differs from B<--from>. The BCC recipient receives
683 the same ARF-compliant message as the primary abuse contact but their
684 address is not visible to the recipient (it is added as a separate SMTP
685 C<RCPT TO> envelope recipient without a C<Bcc:> header in the message).
686 In B<--dry-run> mode the BCC address is shown in the output but no mail
687 is sent.
688  
689 =item B<--from ADDRESS>
690  
691 The envelope sender and From: address for all outgoing reports.
692 Required unless B<--dry-run> is used.
693  
694 =item B<--smtp HOST[:PORT]>
695  
696 SMTP relay to use for sending. Defaults to C<localhost:25>. Supply a
697 port by appending it after a colon, e.g. C<mail.example.com:587>.
698  
699 =item B<--trusted CIDR>
700  
701 A trusted relay IP or CIDR block to skip when identifying the true
702 originating IP. List your own mail server infrastructure here. The
703 option may be repeated for multiple relays:
704  
705 --trusted 10.0.0.0/8 --trusted 192.168.1.1
706  
707 =item B<--timeout SECS>
708  
709 Network timeout in seconds for DNS, WHOIS, RDAP, and SMTP operations.
710 Default: 15.
711  
712 =item B<--verbose>
713  
714 Print analysis progress messages to STDERR.
715  
716 =item B<--help>
717  
718 Print this help text and exit.
719  
720 =back
721  
722 =head1 DESCRIPTION
723  
724 Reads a raw RFC 2822 spam or phishing email (from a file or STDIN),
725 analyses it using C<Email::Abuse::Investigator>, and sends an abuse
726 report to each identified contact: the sending ISP, URL hosts, domain
727 registrars, account providers, DKIM signers, and ESPs.
728  
729 Each outgoing report is a fully RFC 5965 compliant ARF (Abuse Reporting
730 Format) message. The three-part C<multipart/report> structure is:
731  
732 =over 4
733  
734 =item Part 1 -- C<text/plain>
735  
736 The human-readable abuse report generated by
737 C<Email::Abuse::Investigator::abuse_report_text()>, including risk level,
738 red flags, originating IP, and a list of all abuse contacts found.
739 Readable by any mail client, including low-end ticketing systems.
740  
741 =item Part 2 -- C<message/feedback-report>
742  
743 The machine-readable ARF metadata part (RFC 5965 s.3), containing
744 structured fields including C<Feedback-Type>, C<Source-IP>,
745 C<Original-Mail-From>, C<Original-Rcpt-To>, C<Arrival-Date>,
746 C<Reported-Domain>, C<Reported-Uri>, and C<Authentication-Results>.
747 Parsed automatically by ARF-aware abuse desk systems and feedback loops.
748  
749 =item Part 3 -- C<message/rfc822>
750  
751 The original spam or phishing message verbatim, as an attachment named
752 C<original_message.eml>. Required by RFC 5965 s.2. ISP abuse teams
753 use the full C<Received:> headers to locate the SMTP session in their
754 logs; without this part a report is rarely actionable.
755  
756 =back
757  
758 The envelope sender is set to the null reverse-path (C<MAIL FROM:E<lt>E<gt>>)
759 per RFC 6650 s.3, which prevents mail loops and DSN storms. The C<From:>
760 header still carries the reporter's address for human reply purposes.
761  
762 All recipients receive identical report content. The subject line
763 includes the risk level and originating IP for easy triage.
764  
765 Use B<--dry-run> first to review the analysis, confirm the recipients,
766 and inspect both the ARF metadata fields and the first 20 lines of the
767 original message attachment before committing to sending.
768  
769 =head1 RFC 5965 COMPLIANCE (ARF)
770  
771 This script generates fully compliant ARF (Abuse Reporting Format) messages
772 as defined by RFC 5965. Compliance covers:
773  
774 =over 4
775  
776 =item *
777  
778 C<multipart/report; report-type=feedback-report> outer MIME type (s.2).
779  
780 =item *
781  
782 C<message/feedback-report> second part with C<Feedback-Type: abuse>,
783 C<Version: 1>, C<User-Agent>, C<Source-IP>, C<Original-Mail-From>,
784 C<Original-Rcpt-To>, C<Arrival-Date>, C<Reported-Domain>,
785 C<Reported-Uri> (one per URL), and C<Authentication-Results> (s.3).
786  
787 =item *
788  
789 C<message/rfc822> third part containing the verbatim original message,
790 which RFC 5965 s.2 states MUST be included (s.2 item (d)).
791  
792 =item *
793  
794 Null reverse-path envelope sender (C<MAIL FROM:E<lt>E<gt>>) per
795 RFC 6650 s.3 to prevent DSN storms and mail loops.
796  
797 =item *
798  
799 C<message/feedback-report> part encoded as 7bit ASCII as required
800 by the MIME type registration in RFC 5965 s.7.1.
801  
802 =back
803  
804 The one deviation from strict RFC 5965 s.2(f) is that the C<Subject:>
805 header of the report is not identical to the subject of the original
806 spam message -- it is set to a descriptive summary including the risk
807 level and originating IP. This is intentional: abuse desk triage is
808 served better by a consistent, informative subject than by reproducing
809 the spam subject verbatim.
810  
811 =head1 EXIT STATUS
812  
813 0 All reports sent successfully (or --dry-run completed).
814 1 One or more reports failed to send.
815 2 Bad command-line options or missing required argument.
816  
817 With B<--interactive>, skipped reports (answered N) are not counted as
818 failures; exit status 0 is returned if all attempted sends succeeded.
819  
820 =head1 DEPENDENCIES
821  
822 Email::Abuse::Investigator
823 Net::SMTP (core since Perl 5)
824 Getopt::Long (core since Perl 5)
825 Pod::Usage (core since Perl 5.6)
826 POSIX (core since Perl 5)
827  
828 =head1 SEE ALSO
829  
830 L<Email::Abuse::Investigator>
831  
832 RFC 5965 -- An Extensible Format for Email Feedback Reports (ARF):
833 L<https://datatracker.ietf.org/doc/html/rfc5965>
834  
835 RFC 6650 -- Creation and Use of Email Feedback Reports (ARF applicability):
836 L<https://datatracker.ietf.org/doc/html/rfc6650>
837  
838 =cut
« blib/lib/Email/Abuse/Investigator.pm ↑ Summary /usr/local/bin/perldoc »