blib/lib/Email/Abuse/Investigator.pm

filter: Statementstmt 99.1% 2438 / 2460 Branchbran 73.0% 782 / 1070 Conditioncond 46.0% 386 / 838 MC/DCmcdc 31.7% 144 / 453 Subroutinesub 100% 744 / 744 Podpod 100% 21 / 21 totaltotal 80.8% 4515 / 5586 CC 2074 SCAR 41.7
CC
2074
Cov
83%
form_contacts
316.8
form_contacts
316.8
form_contacts
316.8
CRAP 64.9
↑ Summary bin/submit_abuse_report »
1 package Email::Abuse::Investigator;
2  
3 19 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4 19 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
5 19 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 19 ▶use Carp qw(croak carp);
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
8 19 ▶use IO::Select;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
9 19 ▶use IO::Socket::INET;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
10 19 ▶BEGIN { $Sub::Private::config{mode} = 'enforce' }
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
11 19 ▶use Sub::Private;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
12 19 ▶use Sub::Protected;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
13 19 ▶use MIME::QuotedPrint qw( decode_qp );
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
14 19 ▶use MIME::Base64 qw( decode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
15 19 ▶use Object::Configure;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
16 19 ▶use Params::Get;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
17 19 ▶use Params::Validate::Strict 0.34;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
18 19 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
19 19 ▶use Readonly::Values::Months;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
20 19 ▶use Socket qw( inet_aton inet_ntoa AF_INET );
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
21 19 ▶use Time::Piece;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 =head1 NAME
24  
25 Email::Abuse::Investigator - Analyse spam email to identify originating hosts,
26 hosted URLs, and suspicious domains
27  
28 =head1 VERSION
29  
30 Version 0.12
31  
32 =cut
33  
34 130 our $VERSION = '0.12';
35  
36 =head1 SYNOPSIS
37  
38 use Email::Abuse::Investigator;
39  
40 my $analyser = Email::Abuse::Investigator->new( verbose => 1 );
41 $analyser->parse_email($raw_email_text);
42  
43 # Originating IP and its network owner
44 my $origin = $analyser->originating_ip();
45  
46 # All HTTP/HTTPS URLs found in the body
47 my @urls = $analyser->embedded_urls();
48  
49 # All domains extracted from mailto: links and bare addresses in the body
50 my @mdoms = $analyser->mailto_domains();
51  
52 # All domains mentioned anywhere (union of the above)
53 my @adoms = $analyser->all_domains();
54  
55 # Full printable report
56 print $analyser->report();
57  
58 =head1 DESCRIPTION
59  
60 C<Email::Abuse::Investigator> examines the raw source of a spam/phishing e-mail
61 and answers the questions manual abuse investigators ask:
62  
63 =over 4
64  
65 =item 1. Where did the message really come from?
66  
67 Walks the C<Received:> chain, skips private/trusted IPs, and identifies the
68 first external hop. Enriches with rDNS, WHOIS/RDAP org name and abuse
69 contact. Both IPv4 and IPv6 addresses are supported.
70  
71 =item 2. Who hosts the advertised web sites?
72  
73 Extracts every C<http://> and C<https://> URL from both plain-text and HTML
74 parts, resolves each hostname to an IP, and looks up the network owner.
75  
76 =item 3. Who owns the reply-to / contact domains?
77  
78 Extracts domains from C<mailto:> links, bare e-mail addresses in the body,
79 the C<From:>/C<Reply-To:>/C<Sender:>/C<Return-Path:> headers, C<DKIM-Signature: d=>
80 (the signing domain), C<List-Unsubscribe:> (the ESP or bulk-sender domain), and the
81 C<Message-ID:> domain. For each unique domain it gathers:
82  
83 =over 8
84  
85 =item * Domain registrar and registrant (WHOIS)
86  
87 =item * Web-hosting IP and network owner (A record -> RDAP)
88  
89 =item * Mail-hosting IP and network owner (MX record -> RDAP)
90  
91 =item * DNS nameserver operator (NS record -> RDAP)
92  
93 =item * Whether the domain was recently registered (potential flag)
94  
95 =back
96  
97 =back
98  
99 =cut
100  
101 # -----------------------------------------------------------------------
102 # Optional modules -- gracefully degraded when absent
103 # -----------------------------------------------------------------------
104  
105 # Net::DNS enables MX, NS, AAAA lookups; falls back to gethostbyname
106 130 my $HAS_NET_DNS;
107  
108 # LWP::UserAgent enables RDAP queries; falls back to raw WHOIS
109 my $HAS_LWP;
110 16 my $HAS_CONN_CACHE;
111  
112 # HTML::LinkExtor enables structural HTML link extraction
113 21 my $HAS_HTML_LINKEXTOR;
114  
115 # CHI enables a persistent cross-message cache for IP/domain data
116 21 my $HAS_CHI;
117  
118 # IO::Socket::IP provides dual-stack (IPv4+IPv6) socket support
119 23 my $HAS_IO_SOCKET_IP;
120  
121 # Domain::PublicSuffix enables accurate eTLD+1 normalisation
122 23 my $HAS_PUBLIC_SUFFIX;
123  
124 # AnyEvent::DNS enables parallel DNS queries
125 23 my $HAS_ANYEVENT_DNS;
126  
127 BEGIN {
128 19 ▶ $HAS_NET_DNS = eval { require Net::DNS; 1 };
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
129 19 $HAS_LWP = eval { require LWP::UserAgent; 1 };
130 19 $HAS_CONN_CACHE = eval { require LWP::ConnCache; 1 };
131 19 $HAS_HTML_LINKEXTOR= eval { require HTML::LinkExtor; 1 };
132 19 $HAS_CHI = eval { require CHI; 1 };
133 19 $HAS_IO_SOCKET_IP = eval { require IO::Socket::IP; 1 };
134 19 $HAS_PUBLIC_SUFFIX = eval { require Domain::PublicSuffix; 1 };
135 19 $HAS_ANYEVENT_DNS = eval { require AnyEvent::DNS; 1 };
136 }
137  
138 # -----------------------------------------------------------------------
139 # Constants -- all magic numbers and strings live here
140 # -----------------------------------------------------------------------
141  
142 # WHOIS protocol port (IANA-assigned)
143 18 Readonly::Scalar my $WHOIS_PORT => 43;
144  
145 # Bytes to read per sysread() call from a WHOIS socket
146 18 Readonly::Scalar my $WHOIS_READ_CHUNK => 4096;
147  
148 # Maximum WHOIS response bytes stored in whois_raw (keep reports compact)
149 18 Readonly::Scalar my $WHOIS_RAW_MAX => 2048;
150  
151 # Maximum multipart nesting depth (recursion guard -- RFC 2046 has no limit
152 # but we cap it to prevent stack exhaustion on crafted messages)
153 18 Readonly::Scalar my $MAX_MULTIPART_DEPTH => 20;
154  
155 # Number of days before registration that triggers recently_registered flag
156 18 Readonly::Scalar my $RECENT_REG_DAYS => 180;
157  
158 # Number of days ahead of expiry that triggers domain_expires_soon flag
159 17 Readonly::Scalar my $EXPIRY_WARN_DAYS => 30;
160  
161 # Seconds in a day -- used in date arithmetic throughout
162 17 Readonly::Scalar my $SECS_PER_DAY => 86400;
163  
164 # Suspicious date window: dates outside +/- 7 days raise a flag
165 17 Readonly::Scalar my $DATE_SKEW_DAYS => 7;
166  
167 # Maximum positive timezone offset in minutes (+14:00 = Line Islands)
168 18 Readonly::Scalar my $TZ_MAX_POS_MINS => 840;
169  
170 # Maximum negative timezone offset in minutes (-12:00 = Baker Island)
171 18 Readonly::Scalar my $TZ_MAX_NEG_MINS => 720;
172  
173 # High-risk score threshold
174 18 Readonly::Scalar my $SCORE_HIGH => 9;
175  
176 # Medium-risk score threshold
177 18 Readonly::Scalar my $SCORE_MEDIUM => 5;
178  
179 # Low-risk score threshold
180 18 Readonly::Scalar my $SCORE_LOW => 2;
181  
182 # Flag severity weights (contribute to the numeric risk score)
183 18 Readonly::Hash my %FLAG_WEIGHT => (
184 HIGH => 3,
185 MEDIUM => 2,
186 LOW => 1,
187 INFO => 0,
188 );
189  
190 # Maximum merged-role display string length before summarisation kicks in
191 18 Readonly::Scalar my $ROLE_MAX_LEN => 80;
192  
193 # CHI cache TTL in seconds (1 hour -- IP allocations change slowly)
194 18 Readonly::Scalar my $CACHE_TTL_SECS => 3600;
195  
196 # Default constructor timeout for network operations (seconds)
197 18 Readonly::Scalar my $DEFAULT_TIMEOUT => 10;
198  
199 # Maximum role string length before truncation
200 18 Readonly::Scalar my $ROLE_WRAP_LEN => 66;
201  
202 # Maximum redirect hops to follow when resolving shortener/redirect-cloaker URLs
203 18 Readonly::Scalar my $REDIRECT_MAX_HOPS => 3;
204  
205 # Brand names checked in lookalike-domain detection.
206 # Overridable at runtime via Object::Configure.
207 17 Readonly::Array my @LOOKALIKE_BRANDS => qw(
208 paypal apple google amazon microsoft netflix ebay
209 instagram facebook twitter linkedin bankofamerica
210 wellsfargo chase barclays hsbc lloyds santander
211 );
212  
213 # -----------------------------------------------------------------------
214 # Private ranges -- IPs that are never actionable abuse targets
215 # -----------------------------------------------------------------------
216  
217 # Both IPv4 and IPv6 private/reserved ranges. Each entry is a compiled
218 # regex; _is_private() iterates over them and returns true on first match.
219 18 my @PRIVATE_RANGES = (
220 # IPv4 ranges
221 qr/^0\./, # 0.0.0.0/8 this-network (RFC 1122)
222 qr/^127\./, # 127.0.0.0/8 loopback
223 qr/^10\./, # 10.0.0.0/8 RFC 1918
224 qr/^192\.168\./, # 192.168.0.0/16 RFC 1918
225 qr/^172\.(?:1[6-9]|2\d|3[01])\./, # 172.16.0.0/12 RFC 1918
226 qr/^169\.254\./, # 169.254.0.0/16 link-local
227 qr/^100\.(?:6[4-9]|[7-9]\d|1(?:[01]\d|2[0-7]))\./, # 100.64.0.0/10 CGN (RFC 6598)
228 qr/^192\.0\.0\./, # 192.0.0.0/24 IETF protocol (RFC 6890)
229 qr/^192\.0\.2\./, # 192.0.2.0/24 TEST-NET-1 (RFC 5737)
230 qr/^198\.51\.100\./, # 198.51.100.0/24 TEST-NET-2 (RFC 5737)
231 qr/^203\.0\.113\./, # 203.0.113.0/24 TEST-NET-3 (RFC 5737)
232 qr/^255\./, # 255.0.0.0/8 broadcast
233 # IPv6 ranges
234 qr/^::1$/, # IPv6 loopback
235 qr/^fe80:/i, # IPv6 link-local (fe80::/10)
236 qr/^fc/i, # IPv6 ULA fc00::/7
237 qr/^fd/i, # IPv6 ULA fd00::/8
238 qr/^2001:db8:/i, # IPv6 documentation range (RFC 3849)
239 qr/^64:ff9b:/i, # IPv6 NAT64 well-known prefix
240 );
241  
242 # Priority-ordered patterns for extracting IPs from Received: headers.
243 # Covers bracketed IPv4, bracketed IPv6, parenthesised address, and bare dotted-quad.
244 18 my @RECEIVED_IP_RE = (
245 qr/\[\s*([\d.]+)\s*\]/, # [1.2.3.4]
246 qr/\[\s*([0-9a-fA-F:]+)\s*\]/, # [IPv6 address]
247 qr/\(\s*[\w.-]*\s*\[?\s*([\d.]+)\s*\]?\s*\)/, # (hostname [1.2.3.4])
248 qr/from\s+[\w.-]+\s+([\d.]+)/, # from hostname addr
249 qr/([\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3})/, # bare dotted-quad fallback
250 );
251  
252 # -----------------------------------------------------------------------
253 # Default configuration -- overridable via Object::Configure
254 # -----------------------------------------------------------------------
255  
256 # Object::Configure may overlay
257 # values from a file before new() uses them. Use Readonly for constants
258 # that should never be overridden at runtime.
259  
260 # -----------------------------------------------------------------------
261 # Trusted domains (infrastructure -- never report these as abuse targets)
262 # Can be overrideen at runtime by Object::Configure
263 # -----------------------------------------------------------------------
264  
265 18 my %TRUSTED_DOMAINS = map { $_ => 1 } qw(
266 gmail.com googlemail.com yahoo.com outlook.com hotmail.com
267 google.com microsoft.com apple.com amazon.com
268 googlegroups.com groups.google.com
269 fonts.googleapis.com fonts.gstatic.com
270 ajax.googleapis.com maps.googleapis.com
271 w3.org
272 fedex.com ups.com dhl.com usps.com royalmail.com
273 );
274  
275 # -----------------------------------------------------------------------
276 # URL shortener domains (real destination is hidden behind these)
277 # -----------------------------------------------------------------------
278  
279 17 my %URL_SHORTENERS = map { $_ => 1 } qw(
280 bit.ly bitly.com tinyurl.com t.co ow.ly
281 goo.gl is.gd buff.ly ift.tt dlvr.it
282 short.link rebrand.ly tiny.cc cutt.ly rb.gy
283 shorturl.at bl.ink smarturl.it yourls.org clicky.me
284 snip.ly adf.ly bc.vc lnkd.in fb.me
285 youtu.be
286 );
287  
288 # Cloud object-stores and CDN hosting paths commonly abused to serve redirect
289 # pages that hide the real phishing destination (same evasion as a URL shortener
290 # but using legitimate cloud infrastructure to pass spam filters).
291 # Exact-match hosts; suffix patterns are in @REDIRECT_HOST_SUFFIXES below.
292 17 my %REDIRECT_HOSTS = map { $_ => 1 } qw(
293 storage.googleapis.com
294 blob.core.windows.net
295 pages.dev
296 firebaseapp.com
297 web.app
298 );
299  
300 # Subdomain-suffix patterns for bucket-style hosting (e.g. mybucket.s3.amazonaws.com).
301 # Checked by _is_redirect_cloaker() using a suffix match against the bare hostname.
302 58 Readonly::Array my @REDIRECT_HOST_SUFFIXES => qw(
303 .s3.amazonaws.com
304 .s3-website.amazonaws.com
305 .cloudfront.net
306 .github.io
307 .firebaseapp.com
308 .web.app
309 );
310  
311 # -----------------------------------------------------------------------
312 # Well-known provider abuse contacts
313 # Can be overrideen at runtime by Object::Configure
314 # -----------------------------------------------------------------------
315  
316 # Curated table of provider abuse contacts. Entries with only a 'form'
317 # key (no 'email') require web-form submission; abuse_contacts() suppresses
318 # email addresses for those providers and form_contacts() surfaces them.
319 18 my %PROVIDER_ABUSE = (
320 # Google / Gmail
321 'google.com' => { email => 'abuse@google.com', note => 'Also report Gmail accounts via https://support.google.com/mail/contact/abuse' },
322 'gmail.com' => { email => 'abuse@google.com', note => 'Report Gmail spam via https://support.google.com/mail/contact/abuse' },
323 'googlemail.com' => { email => 'abuse@google.com', note => 'Report via https://support.google.com/mail/contact/abuse' },
324 '1e100.net' => { email => 'abuse@google.com', note => 'Google infrastructure' },
325 'blogspot.com' => { email => 'abuse@google.com', note => 'Blogger/Blogspot -- report via https://support.google.com/blogger/answer/76315' },
326 'blogger.com' => { email => 'abuse@google.com', note => 'Blogger platform abuse' },
327 'sites.google.com' => { email => 'abuse@google.com', note => 'Google Sites hosted content' },
328 'storage.googleapis.com' => { email => 'google-cloud-compliance@google.com', note => 'Google Cloud Storage bucket abuse -- also report via https://support.google.com/code/go/gce_abuse_report' },
329 # Microsoft
330 'microsoft.com' => { email => 'abuse@microsoft.com', note => 'Also report via https://www.microsoft.com/en-us/wdsi/support/report-unsafe-site' },
331 'outlook.com' => { email => 'abuse@microsoft.com', note => 'Report Outlook spam: https://support.microsoft.com/en-us/office/report-phishing' },
332 'hotmail.com' => { email => 'abuse@microsoft.com', note => 'Report via https://support.microsoft.com/en-us/office/report-phishing' },
333 'live.com' => { email => 'abuse@microsoft.com', note => 'Microsoft consumer mail' },
334 'office365.com' => { email => 'abuse@microsoft.com', note => 'Microsoft 365 infrastructure' },
335 'protection.outlook.com' => { email => 'abuse@microsoft.com', note => 'Microsoft EOP gateway' },
336 # Yahoo
337 'yahoo.com' => { email => 'abuse@yahoo-inc.com', note => 'Also use https://io.help.yahoo.com/contact/index' },
338 'yahoo.co.uk' => { email => 'abuse@yahoo-inc.com', note => 'Yahoo UK' },
339 # Apple
340 'apple.com' => { email => 'reportphishing@apple.com', note => 'iCloud / Apple Mail abuse' },
341 'icloud.com' => { email => 'reportphishing@apple.com', note => 'iCloud abuse' },
342 'me.com' => { email => 'reportphishing@apple.com', note => 'Apple legacy mail' },
343 # Amazon / AWS
344 'amazon.com' => { email => 'abuse@amazonaws.com', note => 'Also https://aws.amazon.com/forms/report-abuse' },
345 'amazonaws.com' => { email => 'abuse@amazonaws.com', note => 'AWS abuse form: https://aws.amazon.com/forms/report-abuse' },
346 'amazonses.com' => { email => 'abuse@amazonaws.com', note => 'Amazon SES sending infrastructure' },
347 # Cloudflare
348 'cloudflare.com' => { email => 'abuse@cloudflare.com', note => 'Report via https://www.cloudflare.com/abuse/' },
349 # Fastly / Akamai
350 'fastly.net' => { email => 'abuse@fastly.com', note => 'Fastly CDN' },
351 'akamai.com' => { email => 'abuse@akamai.com', note => 'Akamai CDN' },
352 'akamaitechnologies.com' => { email => 'abuse@akamai.com', note => 'Akamai CDN' },
353 # Namecheap
354 'namecheap.com' => { email => 'abuse@namecheap.com', note => 'Registrar abuse' },
355 # GoDaddy -- web form only; email bounces
356 'godaddy.com' => {
357 form => 'https://supportcenter.godaddy.com/AbuseReport',
358 form_paste => 'Select the abuse type (spam, phishing, malware etc). '
359 . 'Enter the domain name in the Domain field. '
360 . 'Paste the originating IP, risk flags, and the relevant '
361 . 'Received: headers from the report below.',
362 form_upload => 'Take a screenshot of the report as a .png or .jpg, '
363 . 'or export it as a .pdf.',
364 note => 'Registrar/host -- email reports not monitored, use web form',
365 },
366 # SendGrid / Twilio
367 'sendgrid.net' => { email => 'abuse@sendgrid.com', note => 'ESP -- include full headers' },
368 'sendgrid.com' => { email => 'abuse@sendgrid.com', note => 'ESP -- include full headers' },
369 # Mailchimp / Mandrill
370 'mailchimp.com' => { email => 'abuse@mailchimp.com', note => 'ESP abuse' },
371 'mandrillapp.com' => { email => 'abuse@mailchimp.com', note => 'Mandrill transactional ESP' },
372 # OVH
373 'ovh.net' => { email => 'abuse@ovh.net', note => 'OVH hosting' },
374 'ovh.com' => { email => 'abuse@ovh.com', note => 'OVH hosting' },
375 # Hetzner
376 'hetzner.com' => { email => 'abuse@hetzner.com', note => 'Hetzner hosting' },
377 # Digital Ocean
378 'digitalocean.com' => { email => 'abuse@digitalocean.com',note => 'DO abuse form: https://www.digitalocean.com/company/contact/#abuse' },
379 # Linode / Akamai
380 'linode.com' => { email => 'abuse@linode.com', note => 'Linode/Akamai Cloud' },
381 # Constant Contact
382 'constantcontact.com' => { email => 'abuse@constantcontact.com', note => 'ESP abuse' },
383 'r.constantcontact.com' => { email => 'abuse@constantcontact.com', note => 'Constant Contact sending infrastructure' },
384 # HubSpot
385 'hubspot.com' => { email => 'abuse@hubspot.com', note => 'ESP abuse' },
386 'hs-analytics.net' => { email => 'abuse@hubspot.com', note => 'HubSpot analytics infrastructure' },
387 # Campaign Monitor
388 'createsend.com' => { email => 'abuse@campaignmonitor.com', note => 'Campaign Monitor ESP' },
389 'cmail20.com' => { email => 'abuse@campaignmonitor.com', note => 'Campaign Monitor sending infrastructure' },
390 # Klaviyo
391 'klaviyo.com' => { email => 'abuse@klaviyo.com', note => 'ESP abuse' },
392 # Brevo (formerly Sendinblue)
393 'sendinblue.com' => { email => 'abuse@sendinblue.com', note => 'ESP abuse' },
394 'brevo.com' => { email => 'abuse@brevo.com', note => 'ESP abuse' },
395 # Mailgun
396 'mailgun.com' => { email => 'abuse@mailgun.com', note => 'ESP abuse' },
397 'mailgun.org' => { email => 'abuse@mailgun.com', note => 'Mailgun sending infrastructure' },
398 # Postmark
399 'postmarkapp.com' => { email => 'abuse@postmarkapp.com', note => 'ESP abuse' },
400 # WordPress.com
401 'wordpress.com' => { email => 'abuse@wordpress.com', note => 'WordPress.com hosted blog -- report via https://en.wordpress.com/abuse/' },
402 'wp.com' => { email => 'abuse@wordpress.com', note => 'WordPress.com short domain' },
403 # Substack
404 'substack.com' => { email => 'abuse@substack.com', note => 'Substack newsletter platform abuse' },
405 # ActiveCampaign
406 'activecampaign.com' => { email => 'abuse@activecampaign.com', note => 'ActiveCampaign ESP' },
407 'ac-tinker.com' => { email => 'abuse@activecampaign.com', note => 'ActiveCampaign tracking infrastructure' },
408 # Salesforce Marketing Cloud
409 'salesforce.com' => { email => 'abuse@salesforce.com', note => 'Salesforce Marketing Cloud / ExactTarget ESP' },
410 'mc.salesforce.com' => { email => 'abuse@salesforce.com', note => 'Salesforce Marketing Cloud sending infrastructure' },
411 'exacttarget.com' => { email => 'abuse@salesforce.com', note => 'ExactTarget / Salesforce Marketing Cloud ESP' },
412 'et.exacttarget.com' => { email => 'abuse@salesforce.com', note => 'ExactTarget sending infrastructure' },
413 # Vultr
414 'vultr.com' => { email => 'abuse@vultr.com', note => 'Vultr hosting' },
415 # Contabo
416 'contabo.com' => { email => 'abuse@contabo.com', note => 'Contabo hosting' },
417 # Leaseweb
418 'leaseweb.com' => { email => 'abuse@leaseweb.com', note => 'Leaseweb hosting' },
419 # M247
420 'm247.com' => { email => 'abuse@m247.com', note => 'M247 hosting' },
421 # MarkMonitor -- web form only
422 'markmonitor.com' => {
423 form => 'https://corp.markmonitor.com/domain/ui/abuse-report',
424 form_paste => 'Complete all fields including the domain name and your '
425 . 'description of the abuse. Paste the originating IP, '
426 . 'risk flags, and the relevant Received: headers from the '
427 . 'report below.',
428 form_upload => 'Take a screenshot of the report as a .png or .jpg, or export it as a .pdf. MarkMonitor does not accept .eml files.',
429 note => 'Brand-protection registrar -- email reports not processed',
430 },
431 # URL shortener operators
432 'is.gd' => { email => 'abuse@is.gd', note => 'URL shortener -- report via https://is.gd/contact.php' },
433 'bitly.com' => { email => 'abuse@bitly.com', note => 'URL shortener abuse' },
434 'bit.ly' => { email => 'abuse@bitly.com', note => 'URL shortener abuse' },
435 'tinyurl.com' => { email => 'abuse@tinyurl.com', note => 'URL shortener abuse' },
436 'ow.ly' => { email => 'abuse@hootsuite.com', note => 'Hootsuite URL shortener' },
437 'buff.ly' => { email => 'abuse@buffer.com', note => 'Buffer URL shortener' },
438 'rb.gy' => { email => 'abuse@rb.gy', note => 'URL shortener abuse' },
439 'cutt.ly' => { email => 'abuse@cutt.ly', note => 'URL shortener abuse' },
440 'shorturl.at' => { email => 'abuse@shorturl.at', note => 'URL shortener abuse' },
441 # Dynadot -- web form only
442 'dynadot.com' => {
443 form => 'https://www.dynadot.com/report-abuse',
444 form_paste => 'Complete all fields including the domain name and your '
445 . 'description of the abuse. Paste the originating IP, '
446 . 'risk flags, and the relevant Received: headers from the '
447 . 'report below.',
448 form_upload => 'Take a screenshot of the report as a .png or .jpg, '
449 . 'or export it as a .pdf.',
450 note => 'Registrar -- email reports not monitored, use web form',
451 },
452 # Global Domain Group -- web form only
453 'globaldomaingroup.com' => {
454 form => 'https://globaldomaingroup.com/report-abuse',
455 form_paste => 'Complete all fields including the domain name and your '
456 . 'description of the abuse. Paste the originating IP, '
457 . 'risk flags, and the relevant Received: headers from the '
458 . 'report below.',
459 form_upload => 'Attach the original spam message as an .eml file.',
460 note => 'Registrar -- email reports explicitly not accepted',
461 },
462 # TPG / Internode (Australia)
463 'tpgi.com.au' => { email => 'abuse@tpg.com.au', note => 'TPG Telecom Australia' },
464 'tpg.com.au' => { email => 'abuse@tpg.com.au', note => 'TPG Telecom Australia' },
465 'internode.on.net' => { email => 'abuse@internode.on.net',note => 'Internode Australia' },
466 );
467  
468 # -----------------------------------------------------------------------
469 # Constructor
470 # -----------------------------------------------------------------------
471  
472 =head1 METHODS
473  
474 =head2 new( %options )
475  
476 Constructs and returns a new C<Email::Abuse::Investigator> analyser object. The
477 object is stateless until C<parse_email()> is called; all analysis results
478 are stored on the object and retrieved via the public accessor methods
479 documented below.
480  
481 A single object may be reused for multiple emails by calling C<parse_email()>
482 again: all per-message cached state from the previous message is discarded
483 automatically. Cross-message IP and domain lookup results are retained
484 in a shared CHI cache (if C<CHI> is installed) to avoid redundant network
485 queries across messages processed in the same process.
486  
487 =head3 Usage
488  
489 # Minimal -- all options take safe defaults
490 my $analyser = Email::Abuse::Investigator->new();
491  
492 # With options
493 my $analyser = Email::Abuse::Investigator->new(
494 timeout => 15,
495 trusted_relays => ['203.0.113.0/24', '10.0.0.0/8'],
496 verbose => 0,
497 );
498  
499 $analyser->parse_email($raw_rfc2822_text);
500 my $origin = $analyser->originating_ip();
501 my @urls = $analyser->embedded_urls();
502 my @domains = $analyser->mailto_domains();
503 my $risk = $analyser->risk_assessment();
504 my @contacts = $analyser->abuse_contacts();
505 print $analyser->report();
506  
507 =head3 Arguments
508  
509 All arguments are optional named parameters passed as a flat key-value list.
510  
511 =over 4
512  
513 =item C<timeout> (integer, default 10)
514  
515 Maximum seconds to wait for any single network operation. Set to 0 to
516 disable timeouts (not recommended for production use).
517  
518 =item C<trusted_relays> (arrayref of strings, default [])
519  
520 IP addresses or CIDR blocks to skip during Received: chain analysis.
521 Each element may be an exact IPv4 address (C<'192.0.2.1'>) or a CIDR
522 block (C<'192.0.2.0/24'>).
523  
524 =item C<verbose> (boolean, default 0)
525  
526 When true, diagnostic messages are written to STDERR.
527  
528 =back
529  
530 =head3 Returns
531  
532 A blessed C<Email::Abuse::Investigator> object. No network I/O is performed
533 during construction.
534  
535 =head3 Side Effects
536  
537 If C<CHI> is installed, a shared in-memory cache is initialised (or
538 re-used if a cache was already created by a prior call to C<new()>).
539 This cache persists for the lifetime of the process.
540  
541 =head3 Notes
542  
543 =over 4
544  
545 =item *
546  
547 Unknown option keys are silently ignored.
548  
549 =item *
550  
551 The object is not thread-safe. Use a separate object per thread.
552  
553 =item *
554  
555 WHOIS read timeouts use C<IO::Select> rather than C<alarm()>, so they
556 work correctly on Windows and in threaded Perl interpreters.
557  
558 =back
559  
560 =head3 API Specification
561  
562 =head4 Input
563  
564 {
565 timeout => {
566 type => 'integer',
567 optional => 1,
568 min => 0,
569 default => 10,
570 },
571 trusted_relays => {
572 type => 'arrayref',
573 element_type => 'string',
574 optional => 1,
575 default => [],
576 },
577 verbose => {
578 type => 'boolean',
579 optional => 1,
580 default => 0,
581 },
582 }
583  
584 =head4 Output
585  
586 {
587 type => 'object',
588 isa => 'Email::Abuse::Investigator',
589 }
590  
591 =cut
592  
593 # Class-level cross-message CHI cache (shared across all instances).
594 # Populated lazily on first call to new() when CHI is available.
595 68 my $_cache;
596  
597 sub new {
598 823 ▶ my $class = shift;
Subroutine new: called CC=4 SCAR=15.7
Subroutine new: called CC=4 SCAR=15.7
Subroutine new: called CC=4 SCAR=15.7
Subroutine new: called CC=4 SCAR=15.7
Pod documented
Pod documented
Pod documented
Pod documented
599  
600 # Accept hash or hashref arguments uniformly
601 823 ▶ my $params = Params::Validate::Strict::validate_strict({
Condition22%2/9
Params::Get::get_params(undef, \@_) || {}
l!l
23797
Params::Get::get_params(undef, \@_) || {}
l!l
000
Params::Get::get_params(undef, \@_) || {}
l!l
00
Params::Get::get_params(undef, \@_) || {}
l!l
00
MC/DC100%1/1
Params::Get::get_params(undef, \@_) || {}
Params::Get::get_params(undef, \@_)
MC/DC0%0/1
Params::Get::get_params(undef, \@_) || {}
Params::Get::get_params(undef, \@_)
MC/DC0%0/1
Params::Get::get_params(undef, \@_) || {}
Params::Get::get_params(undef, \@_)
MC/DC0%0/1
Params::Get::get_params(undef, \@_) || {}
Params::Get::get_params(undef, \@_)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
Truth table0%0/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
Truth table0%0/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
Truth table0%0/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
602 args => Params::Get::get_params(undef, \@_) || {},
603 schema => {
604 timeout => {
605 'type' => 'integer',
606 'optional' => 1,
607 'min' => 0,
608 },
609 trusted_relays => {
610 'type' => 'arrayref',
611 'element_type' => 'string',
612 'optional' => 1,
613 },
614 verbose => {
615 'type' => 'boolean',
616 'optional' => 1,
617 },
618 },
619 });
620  
621 # Merge in any file-based configuration via Object::Configure
622 822 $params = Object::Configure::configure($class, $params);
623  
624 # Initialise the cross-message CHI cache on first construction
625 822 ▶ if ($HAS_CHI && !$_cache) {
Branch: 4 branches
BranchTrueFalseTotal
if ($HAS_CHI and not $_cache) 13 806 819
if ($HAS_CHI and not $_cache) 0 114 114
if ($HAS_CHI and not $_cache) 32 0 32
if ($HAS_CHI and not $_cache) 0 0 0
Condition16%2/12
$HAS_CHI and not $_cache
!ll&&!rl&&r
080613
$HAS_CHI and not $_cache
!ll&&!rl&&r
000
$HAS_CHI and not $_cache
!ll&&!rl&&r
000
$HAS_CHI and not $_cache
!ll&&!rl&&r
000
MC/DC50%1/2
$HAS_CHI and not $_cache
$HAS_CHI not $_cache
MC/DC0%0/2
$HAS_CHI and not $_cache
$HAS_CHI not $_cache
MC/DC0%0/2
$HAS_CHI and not $_cache
$HAS_CHI not $_cache
MC/DC0%0/2
$HAS_CHI and not $_cache
$HAS_CHI not $_cache
Truth table66%2/3
A and not(B)
A= $HAS_CHIB= not $_cache
ABresult
0X0
100
111
Truth table0%0/3
A and not(B)
A= $HAS_CHIB= not $_cache
ABresult
0X0
100
111
Truth table0%0/3
A and not(B)
A= $HAS_CHIB= not $_cache
ABresult
0X0
100
111
Truth table0%0/3
A and not(B)
A= $HAS_CHIB= not $_cache
ABresult
0X0
100
111
626 16 $_cache = CHI->new(
627 driver => 'Memory',
628 global => 1,
629 expires_in => $CACHE_TTL_SECS,
630 );
631 }
632  
633 # Build and bless the object with default slot values
634 return bless {
635 timeout => $DEFAULT_TIMEOUT,
636 trusted_relays => [],
637 verbose => 0,
638 _raw => '',
639 _headers => [],
640 _body_plain => '',
641 _body_html => '',
642 _received => [],
643 _origin => undef,
644 _urls => undef, # lazy-computed by embedded_urls()
645 _mailto_domains=> undef, # lazy-computed by mailto_domains()
646 _contacts => undef, # lazy-computed by abuse_contacts()
647 _domain_info => {}, # per-message domain analysis cache
648 _sending_sw => [], # X-Mailer / X-PHP-Originating-Script etc.
649 _rcvd_tracking => [], # per-hop tracking IDs from Received: headers
650 822 %{$params}, # Overlay Object::Configure and caller-supplied values
651 }, $class;
652 }
653  
654 # -----------------------------------------------------------------------
655 # Public: parse
656 # -----------------------------------------------------------------------
657  
658 =head2 parse_email( $text )
659  
660 Feeds a raw RFC 2822 email message to the analyser and prepares it for
661 subsequent interrogation. This is the only method that must be called
662 before any other public method.
663  
664 If the same object is used for a second message, calling C<parse_email()>
665 again completely replaces all per-message state from the first message.
666 The cross-message CHI cache is B<not> flushed; IP and domain lookups
667 cached from prior messages are retained.
668  
669 =head3 Usage
670  
671 my $raw = do { local $/; <STDIN> };
672 $analyser->parse_email($raw);
673  
674 # Scalar reference (avoids copying large messages)
675 $analyser->parse_email(\$raw);
676  
677 # Chained
678 my $analyser = Email::Abuse::Investigator->new()->parse_email($raw);
679  
680 =head3 Arguments
681  
682 =over 4
683  
684 =item C<$text> (string or string reference, required)
685  
686 Complete raw RFC 2822 email message, including all headers and the body.
687 Both LF-only and CRLF line endings are accepted.
688  
689 =back
690  
691 =head3 Returns
692  
693 The object itself (C<$self>), enabling method chaining.
694  
695 =head3 Side Effects
696  
697 Parses headers, decodes the body (quoted-printable, base64, multipart),
698 extracts sending-software fingerprints, and populates per-hop tracking
699 data. All previously computed lazy results are discarded.
700  
701 =head3 Notes
702  
703 =over 4
704  
705 =item *
706  
707 If C<$text> is empty or contains no header/body separator, all public
708 methods will return empty/safe values.
709  
710 =item *
711  
712 Decoding errors in base64 or quoted-printable payloads are silenced; raw
713 bytes are used in place of correct output to prevent exceptions.
714  
715 =back
716  
717 =head3 API Specification
718  
719 =head4 Input
720  
721 [
722 {
723 type => [ 'string', 'stringref' ]
724 },
725 ]
726  
727 =head4 Output
728  
729 {
730 type => 'object',
731 isa => 'Email::Abuse::Investigator',
732 }
733  
734 =cut
735  
736 # TODO: Allow a Mail::Message object to be passed in
737 sub parse_email {
738 675 ▶ my $self = shift;
Subroutine parse_email: called CC=7 SCAR=20.0
Subroutine parse_email: called CC=7 SCAR=20.0
Subroutine parse_email: called CC=7 SCAR=20.0
Pod documented
Pod documented
Pod documented
739  
740 # Accept both positional string and named 'text' argument
741 675 my $args = Params::Get::get_params('text', \@_);
742 674 my $text = $args->{text};
743  
744 # Dereference a scalar-ref in a single clean pass
745 673 ▶ $text = $$text if ref($text) eq 'SCALAR';
Branch: 3 branches
BranchTrueFalseTotal
if ref $text eq "SCALAR" 1 669 670
if ref $text eq "SCALAR" 0 6 6
if ref $text eq "SCALAR" 1 0 1
746  
747 # Any other reference type is a programming error
748 673 ▶ Carp::croak(__PACKAGE__ . ': parse_email() requires a string or scalar reference') if ref($text);
Branch: 3 branches
BranchTrueFalseTotal
if ref $text 5 666 671
if ref $text 0 6 6
if ref $text 0 1 1
749  
750 # Sanitise: strip control characters that could affect terminal output.
751 # Keep \t (tabs in headers), \n (line endings), \r (CRLF mail format).
752 670 ▶ $text =~ s/[^\x09\x0A\x0D\x20-\x7E\x80-\xFF]//g if defined $text;
Branch: 3 branches
BranchTrueFalseTotal
if defined $text 665 2 667
if defined $text 0 1 1
if defined $text 1 0 1
753  
754 # Store the sanitised raw text for later reproduction in reports
755 670 ▶ $self->{_raw} = $text // '';
Condition33%2/6
$text // ""
l!l
6643
$text // ""
l!l
00
$text // ""
l!l
00
MC/DC100%1/1
$text // ""
$text
MC/DC0%0/1
$text // ""
$text
MC/DC0%0/1
$text // ""
$text
Truth table100%2/2
A
A= $text
Aresult
11
00
Truth table0%0/2
A
A= $text
Aresult
11
00
Truth table0%0/2
A
A= $text
Aresult
11
00
756  
757 # Invalidate all per-message lazy caches
758 671 $self->{_origin} = undef;
759 671 $self->{_urls} = undef;
760 671 $self->{_mailto_domains} = undef;
761 671 $self->{_contacts} = undef;
762 671 $self->{_domain_info} = {};
763 671 $self->{_risk} = undef;
764 671 $self->{_auth_results} = undef;
765 670 $self->{_sending_sw} = [];
766 670 $self->{_rcvd_tracking} = [];
767  
768 # Perform synchronous header/body parsing (no network I/O)
769 670 ▶ $self->_split_message($text) if defined $text && $text =~ /\S/;
Branch: 3 branches
BranchTrueFalseTotal
if defined $text and $text =~ /\S/ 660 7 667
if defined $text and $text =~ /\S/ 1 0 1
if defined $text and $text =~ /\S/ 1 0 1
Condition33%3/9
defined $text and $text =~ /\S/
!ll&&!rl&&r
24661
defined $text and $text =~ /\S/
!ll&&!rl&&r
000
defined $text and $text =~ /\S/
!ll&&!rl&&r
000
MC/DC100%2/2
defined $text and $text =~ /\S/
defined $text $text =~ /\S/
MC/DC0%0/2
defined $text and $text =~ /\S/
defined $text $text =~ /\S/
MC/DC0%0/2
defined $text and $text =~ /\S/
defined $text $text =~ /\S/
Truth table100%3/3
A and B
A= defined $textB= $text =~ /\S/
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= defined $textB= $text =~ /\S/
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= defined $textB= $text =~ /\S/
ABresult
0X0
100
111
770 670 return $self;
771 }
772  
773 # -----------------------------------------------------------------------
774 # Public: originating host
775 # -----------------------------------------------------------------------
776  
777 =head2 originating_ip()
778  
779 Identifies the IP address of the machine that originally injected the
780 message into the mail system by walking the C<Received:> chain, skipping
781 private/trusted hops, and enriching the first external hop with rDNS,
782 WHOIS/RDAP organisation name, abuse contact, and country code.
783  
784 Both IPv4 and IPv6 addresses are extracted and evaluated.
785  
786 The result is cached; subsequent calls return the same hashref without
787 repeating network I/O.
788  
789 =head3 Usage
790  
791 my $orig = $analyser->originating_ip();
792 if (defined $orig) {
793 printf "Origin: %s (%s)\n", $orig->{ip}, $orig->{rdns};
794 printf "Owner: %s\n", $orig->{org};
795 }
796  
797 =head3 Arguments
798  
799 None. C<parse_email()> must have been called first.
800  
801 =head3 Returns
802  
803 A hashref with keys C<ip>, C<rdns>, C<org>, C<abuse>, C<confidence>,
804 C<note>, and C<country> (may be undef). Returns C<undef> if no suitable
805 originating IP can be determined.
806  
807 =head3 Side Effects
808  
809 On first call: one PTR lookup and one RDAP/WHOIS query. Results are cached
810 in the object and in the cross-message CHI cache (if available).
811  
812 =head3 Notes
813  
814 Only the first (oldest) external IP in the chain is reported. See
815 C<received_trail()> for the full chain.
816  
817 =head3 API Specification
818  
819 =head4 Input
820  
821 []
822  
823 =head4 Output
824  
825 {
826 type => [ 'hashref', 'undef' ],
827 keys => {
828 ip => { type => 'string', regex => qr/[\d.:a-fA-F]/ },
829 rdns => { type => 'string' },
830 org => { type => 'string' },
831 abuse => { type => 'string' },
832 confidence => { type => 'string', memberof => [ 'high', 'medium', 'low' ] },
833 note => { type => 'string' },
834 country => { type => 'string', optional => 1 },
835 },
836 }
837  
838 =cut
839  
840 sub originating_ip {
841 768 ▶ my $self = $_[0];
Subroutine originating_ip: called CC=2 SCAR=7.2
Subroutine originating_ip: called CC=2 SCAR=7.2
Pod documented
Pod documented
842  
843 # Return the cached result if we already have it
844 768 ▶ $self->{_origin} //= $self->_find_origin();
Condition50%3/6
$self->{"_origin"} //= $self->_find_origin
l!l&&r!l&&!r
38994283
$self->{"_origin"} //= $self->_find_origin
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"_origin"} //= $self->_find_origin
$self->{"_origin"} $self->_find_origin
MC/DC0%0/2
$self->{"_origin"} //= $self->_find_origin
$self->{"_origin"} $self->_find_origin
Truth table0%0/3
A //= B
A= $self->{"_origin"}B= $self->_find_origin
ABresult
1X1
011
000
Truth table0%0/3
A //= B
A= $self->{"_origin"}B= $self->_find_origin
ABresult
1X1
011
000
845 768 return $self->{_origin};
846 }
847  
848 # -----------------------------------------------------------------------
849 # Public: HTTP/HTTPS URLs
850 # -----------------------------------------------------------------------
851  
852 =head2 embedded_urls()
853  
854 Extracts every HTTP and HTTPS URL from the message body and enriches each
855 one with the hosting IP address, network organisation name, abuse contact,
856 and country code. Both IPv4 and IPv6 host addresses are supported.
857  
858 URL extraction runs across both plain-text and HTML body parts. DNS
859 lookups for each unique hostname are optionally parallelised via
860 C<AnyEvent::DNS> if that module is installed.
861  
862 The result is cached; subsequent calls return the same list without
863 repeating network I/O.
864  
865 =head3 Usage
866  
867 my @urls = $analyser->embedded_urls();
868 for my $u (@urls) {
869 printf "URL: %s host: %s org: %s\n",
870 $u->{url}, $u->{host}, $u->{org};
871 }
872  
873 =head3 Arguments
874  
875 None. C<parse_email()> must have been called first.
876  
877 =head3 Returns
878  
879 A list of hashrefs, one per unique URL, in first-seen order. Returns an
880 empty list if no HTTP/HTTPS URLs are present. Each hashref has keys
881 C<url>, C<host>, C<ip>, C<org>, C<abuse>, C<country>.
882  
883 =head3 Side Effects
884  
885 Per unique hostname: one A/AAAA lookup and one RDAP/WHOIS query. Results
886 are cached in the object and in the cross-message CHI cache.
887  
888 =head3 Notes
889  
890 Only C<http://> and C<https://> URLs are extracted. URL shortener hosts
891 are included in the returned list (they are flagged by C<risk_assessment()>).
892  
893 When L<LWP::UserAgent> is available, URLs whose host is a known URL shortener
894 or cloud-storage redirect cloaker (Google Cloud Storage C<storage.googleapis.com>,
895 Azure Blob Storage C<blob.core.windows.net>, Cloudflare Pages C<pages.dev>,
896 S3 buckets, CloudFront distributions, etc.) are automatically resolved by
897 following HTTP 3xx redirects and HTML C<meta http-equiv="refresh"> or
898 C<window.location> patterns up to C<$REDIRECT_MAX_HOPS> hops. The resolved
899 destination URL is added to the returned list alongside the original, so abuse
900 contacts for the real phishing target are always reported even when the email
901 body contains only an object-store redirect URL.
902  
903 =head3 API Specification
904  
905 =head4 Input
906  
907 []
908  
909 =head4 Output
910  
911 (
912 {
913 type => 'hashref',
914 keys => {
915 url => { type => 'string', regex => qr{^https?://}i },
916 host => { type => 'string' },
917 ip => { type => 'string' },
918 org => { type => 'string' },
919 abuse => { type => 'string' },
920 country => { type => 'string', optional => 1 },
921 },
922 },
923 ...
924 )
925  
926 =cut
927  
928 sub embedded_urls {
929 862 ▶ my $self = $_[0];
Subroutine embedded_urls: called CC=2 SCAR=7.4
Subroutine embedded_urls: called CC=2 SCAR=7.4
Subroutine embedded_urls: called CC=2 SCAR=7.4
Pod documented
930  
931 862 ▶ $self->{_urls} //= $self->_extract_and_resolve_urls();
Condition44%4/9
$self->{"_urls"} //= $self->_extract_and_resolve_urls
l!l&&r!l&&!r
6691874
$self->{"_urls"} //= $self->_extract_and_resolve_urls
l!l&&r!l&&!r
100
$self->{"_urls"} //= $self->_extract_and_resolve_urls
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"_urls"} //= $self->_extract_and_resolve_urls
$self->{"_urls"} $self->_extract_and_resolve_urls
MC/DC0%0/2
$self->{"_urls"} //= $self->_extract_and_resolve_urls
$self->{"_urls"} $self->_extract_and_resolve_urls
MC/DC0%0/2
$self->{"_urls"} //= $self->_extract_and_resolve_urls
$self->{"_urls"} $self->_extract_and_resolve_urls
Truth table0%0/3
A //= B
A= $self->{"_urls"}B= $self->_extract_and_resolve_urls
ABresult
1X1
011
000
Truth table0%0/3
A //= B
A= $self->{"_urls"}B= $self->_extract_and_resolve_urls
ABresult
1X1
011
000
Truth table0%0/3
A //= B
A= $self->{"_urls"}B= $self->_extract_and_resolve_urls
ABresult
1X1
011
000
932 862 return @{ $self->{_urls} };
933 }
934  
935 # -----------------------------------------------------------------------
936 # Public: mailto / reply-to / from domains
937 # -----------------------------------------------------------------------
938  
939 =head2 mailto_domains()
940  
941 Identifies every domain associated with the message as a contact, reply,
942 or delivery address, then runs a full intelligence pipeline on each one
943 (A record, MX, NS, WHOIS) to determine hosting and registration details.
944  
945 The result is cached; subsequent calls return the same list without
946 repeating network I/O.
947  
948 =head3 Usage
949  
950 my @domains = $analyser->mailto_domains();
951 for my $d (@domains) {
952 printf "Domain: %s registrar: %s\n",
953 $d->{domain}, $d->{registrar} // 'unknown';
954 }
955  
956 =head3 Arguments
957  
958 None. C<parse_email()> must have been called first.
959  
960 =head3 Returns
961  
962 A list of hashrefs, one per unique domain. See the main POD for the full
963 set of possible keys. Returns an empty list if no qualifying domains are
964 found.
965  
966 =head3 Side Effects
967  
968 Per unique domain: up to three A lookups, one MX lookup, one NS lookup,
969 and two WHOIS queries. Results are cached in the object and in the
970 cross-message CHI cache.
971  
972 =head3 Notes
973  
974 MX and NS lookups require C<Net::DNS>. Without it those keys are absent
975 from every returned hashref.
976  
977 =head3 API Specification
978  
979 =head4 Input
980  
981 []
982  
983 =head4 Output
984  
985 (
986 {
987 type => 'hashref',
988 keys => {
989 domain => { type => 'string' },
990 source => { type => 'string' },
991 # All other keys optional -- see main POD
992 },
993 },
994 ...
995 )
996  
997 =cut
998  
999 sub mailto_domains {
1000 902 ▶ my $self = $_[0];
Subroutine mailto_domains: called CC=2 SCAR=7.1
Subroutine mailto_domains: called CC=2 SCAR=7.1
Pod documented
1001  
1002 903 ▶ $self->{_mailto_domains} //= $self->_extract_and_analyse_domains();
Condition50%3/6
$self->{"_mailto_domains"} //= $self->_extract_and_analyse_domains
l!l&&r!l&&!r
6782201
$self->{"_mailto_domains"} //= $self->_extract_and_analyse_domains
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"_mailto_domains"} //= $self->_extract_and_analyse_domains
$self->{"_mailto_domains"} $self->_extract_and_analyse_domains
MC/DC0%0/2
$self->{"_mailto_domains"} //= $self->_extract_and_analyse_domains
$self->{"_mailto_domains"} $self->_extract_and_analyse_domains
Truth table0%0/3
A //= B
A= $self->{"_mailto_domains"}B= $self->_extract_and_analyse_domains
ABresult
1X1
011
000
Truth table0%0/3
A //= B
A= $self->{"_mailto_domains"}B= $self->_extract_and_analyse_domains
ABresult
1X1
011
000
1003 792 return @{ $self->{_mailto_domains} };
1004 }
1005  
1006 =head2 all_domains()
1007  
1008 Returns the deduplicated union of every registrable domain seen anywhere
1009 in the message -- URL hosts from C<embedded_urls()> and contact domains
1010 from C<mailto_domains()> -- normalised to eTLD+1 form.
1011  
1012 Triggers C<embedded_urls()> and C<mailto_domains()> lazily.
1013  
1014 =head3 Usage
1015  
1016 my @domains = $analyser->all_domains();
1017 print "$_\n" for @domains;
1018  
1019 =head3 Arguments
1020  
1021 None.
1022  
1023 =head3 Returns
1024  
1025 A list of plain strings (registrable domain names), lower-cased, no
1026 duplicates, in first-seen order.
1027  
1028 =head3 Side Effects
1029  
1030 Triggers C<embedded_urls()> and C<mailto_domains()> if not already cached.
1031  
1032 =head3 Notes
1033  
1034 Normalisation to eTLD+1 uses C<Domain::PublicSuffix> if installed, falling
1035 back to a built-in heuristic otherwise.
1036  
1037 =head3 API Specification
1038  
1039 =head4 Input
1040  
1041 []
1042  
1043 =head4 Output
1044  
1045 (
1046 { type => 'string', regex => qr/^[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/ },
1047 ...
1048 )
1049  
1050 =cut
1051  
1052 sub all_domains {
1053 42 ▶ my $self = $_[0];
Subroutine all_domains: called CC=8 SCAR=22.0
Subroutine all_domains: called CC=8 SCAR=22.0
Pod documented
1054 43 my (%seen, @out);
1055  
1056 # Collect registrable domains from URL hosts first
1057 43 for my $u ($self->embedded_urls()) {
1058 38 my $dom = _registrable($u->{host});
1059 40 ▶ push @out, $dom if $dom && !$seen{$dom}++;
Branch: 2 branches
BranchTrueFalseTotal
if $dom and not $seen{$dom}++ 17 2 19
if $dom and not $seen{$dom}++ 1 0 1
Condition50%3/6
$dom and not $seen{$dom}++
!ll&&!rl&&r
11418
$dom and not $seen{$dom}++
!ll&&!rl&&r
000
MC/DC0%0/2
$dom and not $seen{$dom}++
$dom not $seen{$dom}++
MC/DC0%0/2
$dom and not $seen{$dom}++
$dom not $seen{$dom}++
Truth table33%1/3
A and not(B)
A= $domB= not $seen{$dom}++
ABresult
0X0
100
111
Truth table0%0/3
A and not(B)
A= $domB= not $seen{$dom}++
ABresult
0X0
100
111
1060 }
1061  
1062 # Then from contact domains (normalise subdomains to registrable parent)
1063 45 for my $d ($self->mailto_domains()) {
1064 50 ▶ my $dom = _registrable($d->{domain}) // $d->{domain};
Condition50%3/6
_registrable($d->{"domain"}) // $d->{"domain"}
l!l&&r!l&&!r
4240
_registrable($d->{"domain"}) // $d->{"domain"}
l!l&&r!l&&!r
010
MC/DC0%0/2
_registrable($d->{"domain"}) // $d->{"domain"}
_registrable($d->{"domain"}) $d->{"domain"}
MC/DC0%0/2
_registrable($d->{"domain"}) // $d->{"domain"}
_registrable($d->{"domain"}) $d->{"domain"}
Truth table33%1/3
A // B
A= _registrable($d->{"domain"})B= $d->{"domain"}
ABresult
1X1
011
000
Truth table0%0/3
A // B
A= _registrable($d->{"domain"})B= $d->{"domain"}
ABresult
1X1
011
000
1065 52 ▶ push @out, $dom if $dom && !$seen{$dom}++;
Branch: 2 branches
BranchTrueFalseTotal
if $dom and not $seen{$dom}++ 21 8 29
if $dom and not $seen{$dom}++ 0 1 1
Condition50%3/6
$dom and not $seen{$dom}++
!ll&&!rl&&r
834521
$dom and not $seen{$dom}++
!ll&&!rl&&r
000
MC/DC100%2/2
$dom and not $seen{$dom}++
$dom not $seen{$dom}++
MC/DC0%0/2
$dom and not $seen{$dom}++
$dom not $seen{$dom}++
Truth table100%3/3
A and not(B)
A= $domB= not $seen{$dom}++
ABresult
0X0
100
111
Truth table0%0/3
A and not(B)
A= $domB= not $seen{$dom}++
ABresult
0X0
100
111
1066 }
1067 150 return @out;
1068 }
1069  
1070 =head2 unresolved_contacts()
1071  
1072 Returns a list of domains and URL hosts found in the message for which no
1073 abuse contact could be determined. Useful for surfacing parties that may
1074 warrant manual investigation.
1075  
1076 =head3 Usage
1077  
1078 my @unresolved = $analyser->unresolved_contacts();
1079 for my $u (@unresolved) {
1080 printf "Unresolved: %s (%s) via %s\n",
1081 $u->{domain}, $u->{type}, $u->{source};
1082 }
1083  
1084 =head3 Arguments
1085  
1086 None.
1087  
1088 =head3 Returns
1089  
1090 A list of hashrefs, each with keys C<domain>, C<type> (C<'url_host'> or
1091 C<'domain'>), and C<source> (where the domain was found).
1092  
1093 =head3 Side Effects
1094  
1095 Triggers C<embedded_urls()>, C<mailto_domains()>, C<abuse_contacts()>,
1096 and C<form_contacts()> if not already cached.
1097  
1098 =head3 Notes
1099  
1100 Domains sourced only from spoofable sending headers (C<From:>,
1101 C<Return-Path:>, C<Sender:>) are excluded.
1102  
1103 =head3 API Specification
1104  
1105 =head4 Input
1106  
1107 []
1108  
1109 =head4 Output
1110  
1111 (
1112 {
1113 type => 'hashref',
1114 keys => {
1115 domain => { type => 'string' },
1116 type => { type => 'string', memberof => [ 'url_host', 'domain' ] },
1117 source => { type => 'string' },
1118 },
1119 },
1120 ...
1121 )
1122  
1123 =cut
1124  
1125 sub unresolved_contacts {
1126 162 ▶ my $self = $_[0];
Subroutine unresolved_contacts: called CC=16 SCAR=29.9
Subroutine unresolved_contacts: called CC=16 SCAR=29.9
Pod documented
1127  
1128 # Build a set of domains already covered by email or form contacts
1129 158 my %covered;
1130 158 for my $c ($self->abuse_contacts(), $self->form_contacts()) {
1131 28 my $dom = $c->{form_domain};
1132 24 ▶ unless ($dom) {
Branch: 2 branches
BranchTrueFalseTotal
unless ($dom) 14 0 14
unless ($dom) 1 0 1
1133 # Extract domain from abuse email address
1134 24 ▶ ($dom) = ($c->{address} // '') =~ /\@([\w.-]+)/;
Condition40%2/5
$c->{"address"} // ""
l!l
2450
$c->{"address"} // ""
l!l
00
MC/DC100%1/1
$c->{"address"} // ""
$c->{"address"}
MC/DC0%0/1
$c->{"address"} // ""
$c->{"address"}
Truth table100%2/2
A
A= $c->{"address"}
Aresult
11
00
Truth table0%0/2
A
A= $c->{"address"}
Aresult
11
00
1135 }
1136 24 ▶ $covered{lc $dom}++ if $dom;
Branch: 2 branches
BranchTrueFalseTotal
if $dom 13 0 13
if $dom 0 1 1
1137 }
1138  
1139 # Also mark URL hosts that already have a resolved abuse address
1140 174 for my $u ($self->embedded_urls()) {
1141 157 (my $bare = lc $u->{host}) =~ s/^www\.//;
1142 155 ▶ $covered{$bare}++ if $u->{abuse} && $u->{abuse} ne '(unknown)';
Branch: 2 branches
BranchTrueFalseTotal
if $u->{"abuse"} and $u->{"abuse"} ne "(unknown)" 6 13 19
if $u->{"abuse"} and $u->{"abuse"} ne "(unknown)" 0 0 0
Condition50%3/6
$u->{"abuse"} and $u->{"abuse"} ne "(unknown)"
!ll&&!rl&&r
97556
$u->{"abuse"} and $u->{"abuse"} ne "(unknown)"
!ll&&!rl&&r
000
MC/DC50%1/2
$u->{"abuse"} and $u->{"abuse"} ne "(unknown)"
$u->{"abuse"} $u->{"abuse"} ne "(unknown)"
MC/DC0%0/2
$u->{"abuse"} and $u->{"abuse"} ne "(unknown)"
$u->{"abuse"} $u->{"abuse"} ne "(unknown)"
Truth table66%2/3
A and B
A= $u->{"abuse"}B= $u->{"abuse"} ne "(unknown)"
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $u->{"abuse"}B= $u->{"abuse"} ne "(unknown)"
ABresult
0X0
100
111
1143 }
1144  
1145 175 my (@out, %seen);
1146  
1147 # Check URL hosts first
1148 43 for my $u ($self->embedded_urls()) {
1149 26 (my $bare = lc $u->{host}) =~ s/^www\.//;
1150 26 ▶ next if $covered{$bare};
Branch: 2 branches
BranchTrueFalseTotal
if $covered{$bare} 5 16 21
if $covered{$bare} 0 0 0
1151 22 ▶ next if $seen{"url:$bare"}++;
Branch: 2 branches
BranchTrueFalseTotal
if $seen{"url:$bare"}++ 2 11 13
if $seen{"url:$bare"}++ 1 0 1
1152 push @out, {
1153 domain => $u->{host},
1154 27 type => 'url_host',
1155 source => 'URL in body',
1156 };
1157 }
1158  
1159 # Then check contact domains, skipping spoofable-header-only sources
1160 49 for my $d ($self->mailto_domains()) {
1161 52 my $dom = $d->{domain};
1162 52 ▶ my $source = $d->{source} // '';
Condition50%3/6
$d->{"source"} // ""
l!l
4230
$d->{"source"} // ""
l!l
200
MC/DC100%1/1
$d->{"source"} // ""
$d->{"source"}
MC/DC0%0/1
$d->{"source"} // ""
$d->{"source"}
Truth table100%2/2
A
A= $d->{"source"}
Aresult
11
00
Truth table50%1/2
A
A= $d->{"source"}
Aresult
11
00
1163 43 ▶ next if $source =~ /^(?:From:|Return-Path:|Sender:) header$/;
Branch: 2 branches
BranchTrueFalseTotal
if $source =~ /^(?:From:|Return-Path:|Sender:) header$/ 27 11 38
if $source =~ /^(?:From:|Return-Path:|Sender:) header$/ 1 0 1
1164 17 ▶ next if $covered{lc $dom};
Branch: 2 branches
BranchTrueFalseTotal
if $covered{lc $dom} 1 11 12
if $covered{lc $dom} 0 1 1
1165 16 ▶ next if $seen{"dom:$dom"}++;
Branch: 2 branches
BranchTrueFalseTotal
if $seen{"dom:$dom"}++ 0 11 11
if $seen{"dom:$dom"}++ 1 0 1
1166 16 push @out, {
1167 domain => $dom,
1168 type => 'domain',
1169 source => $source,
1170 };
1171 }
1172  
1173 43 return @out;
1174 }
1175  
1176 # -----------------------------------------------------------------------
1177 # Public: sending software fingerprint
1178 # -----------------------------------------------------------------------
1179  
1180 =head2 sending_software()
1181  
1182 Returns information extracted from headers that identify the software or
1183 server-side infrastructure used to compose or inject the message. Headers
1184 such as C<X-PHP-Originating-Script> reveal the exact PHP script and Unix
1185 account responsible on shared-hosting platforms.
1186  
1187 Data is extracted during C<parse_email()> with no network I/O.
1188  
1189 =head3 Usage
1190  
1191 my @sw = $analyser->sending_software();
1192 for my $s (@sw) {
1193 printf "%-30s : %s\n", $s->{header}, $s->{value};
1194 }
1195  
1196 =head3 Arguments
1197  
1198 None. C<parse_email()> must have been called first.
1199  
1200 =head3 Returns
1201  
1202 A list of hashrefs in alphabetical header-name order. Returns an empty
1203 list if none of the watched headers are present. Each hashref has keys
1204 C<header>, C<value>, and C<note>.
1205  
1206 =head3 Side Effects
1207  
1208 None. Data is pre-collected during C<parse_email()>.
1209  
1210 =head3 Notes
1211  
1212 Header names are lower-cased. Header values are stored verbatim.
1213  
1214 =head3 API Specification
1215  
1216 =head4 Input
1217  
1218 []
1219  
1220 =head4 Output
1221  
1222 (
1223 {
1224 type => 'hashref',
1225 keys => {
1226 header => { type => 'string' },
1227 value => { type => 'string' },
1228 note => { type => 'string' },
1229 },
1230 },
1231 ...
1232 )
1233  
1234 =cut
1235  
1236 sub sending_software {
1237 88 ▶ my $self = $_[0];
Subroutine sending_software: called CC=1 SCAR=0.0
Subroutine sending_software: called CC=1 SCAR=0.0
Pod documented
1238  
1239 89 return @{ $self->{_sending_sw} };
1240 }
1241  
1242 # -----------------------------------------------------------------------
1243 # Public: per-hop tracking IDs
1244 # -----------------------------------------------------------------------
1245  
1246 =head2 received_trail()
1247  
1248 Returns per-hop tracking data extracted from the C<Received:> header chain:
1249 the IP address, envelope recipient address, and server session ID for each
1250 relay. ISP postmasters use these identifiers to locate the SMTP session in
1251 their logs.
1252  
1253 =head3 Usage
1254  
1255 my @trail = $analyser->received_trail();
1256 for my $hop (@trail) {
1257 printf "IP: %s ID: %s\n",
1258 $hop->{ip} // '?', $hop->{id} // '?';
1259 }
1260  
1261 =head3 Arguments
1262  
1263 None. C<parse_email()> must have been called first.
1264  
1265 =head3 Returns
1266  
1267 A list of hashrefs in oldest-first order. Returns an empty list if no
1268 C<Received:> headers are present or none yielded extractable data. Each
1269 hashref has keys C<received>, C<ip> (may be undef), C<for> (may be undef),
1270 C<id> (may be undef).
1271  
1272 =head3 Side Effects
1273  
1274 None. Data is pre-collected during C<parse_email()>.
1275  
1276 =head3 Notes
1277  
1278 Private IPs are NOT filtered here; all IPs including RFC 1918 addresses
1279 are returned as found. Filtering is applied only by C<originating_ip()>.
1280  
1281 =head3 API Specification
1282  
1283 =head4 Input
1284  
1285 []
1286  
1287 =head4 Output
1288  
1289 (
1290 {
1291 type => 'hashref',
1292 keys => {
1293 received => { type => 'string' },
1294 ip => { type => 'string', optional => 1 },
1295 for => { type => 'string', optional => 1 },
1296 id => { type => 'string', optional => 1 },
1297 },
1298 },
1299 ...
1300 )
1301  
1302 =cut
1303  
1304 sub received_trail {
1305 113 ▶ my $self = $_[0];
Subroutine received_trail: called CC=1 SCAR=0.0
Subroutine received_trail: called CC=1 SCAR=0.0
Pod documented
1306  
1307 116 return @{ $self->{_rcvd_tracking} };
1308 }
1309  
1310 # -----------------------------------------------------------------------
1311 # Public: risk assessment
1312 # -----------------------------------------------------------------------
1313  
1314 =head2 risk_assessment()
1315  
1316 Evaluates the message against heuristic checks and returns an overall risk
1317 level, a weighted numeric score, and a list of every specific red flag.
1318  
1319 The assessment covers five categories: originating IP, email authentication,
1320 Date: header validity, identity/header consistency, and URL/domain properties.
1321  
1322 The result is cached; subsequent calls return the same hashref without
1323 repeating any analysis.
1324  
1325 =head3 Usage
1326  
1327 my $risk = $analyser->risk_assessment();
1328 printf "Risk: %s (score: %d)\n", $risk->{level}, $risk->{score};
1329 for my $f (@{ $risk->{flags} }) {
1330 printf " [%s] %s\n", $f->{severity}, $f->{detail};
1331 }
1332  
1333 =head3 Arguments
1334  
1335 None. C<parse_email()> must have been called first.
1336  
1337 =head3 Returns
1338  
1339 A hashref with keys C<level> (HIGH/MEDIUM/LOW/INFO), C<score> (integer),
1340 and C<flags> (arrayref of hashrefs with C<severity>, C<flag>, C<detail>).
1341  
1342 =head3 Side Effects
1343  
1344 Triggers C<originating_ip()>, C<embedded_urls()>, and C<mailto_domains()>
1345 if not already cached.
1346  
1347 =head3 Notes
1348  
1349 Scores: HIGH >= 9, MEDIUM >= 5, LOW >= 2, INFO < 2.
1350 Flag weights: HIGH=3, MEDIUM=2, LOW=1, INFO=0.
1351  
1352 =head3 API Specification
1353  
1354 =head4 Input
1355  
1356 []
1357  
1358 =head4 Output
1359  
1360 {
1361 type => 'hashref',
1362 keys => {
1363 level => { type => 'string', memberof => ['HIGH', 'MEDIUM', 'LOW', 'INFO'] },
1364 score => { type => 'integer' },
1365 flags => { type => 'arrayref' },
1366 },
1367 }
1368  
1369 =cut
1370  
1371 sub risk_assessment {
1372 360 ▶ my $self = $_[0];
Subroutine risk_assessment: called CC=5 SCAR=16.1
Subroutine risk_assessment: called CC=5 SCAR=16.1
Pod documented
1373  
1374 363 ▶ return $self->{_risk} if $self->{_risk};
Branch: 2 branches
BranchTrueFalseTotal
if $self->{"_risk"} 16 340 356
if $self->{"_risk"} 0 1 1
1375  
1376 346 my (@flags, $score);
1377 347 $score = 0;
1378  
1379 # Closure to record a flag and accumulate its weight
1380 my $flag = sub {
1381 432 ▶ my ($severity, $name, $detail) = @_;
Subroutine __ANON__: called CC=2 SCAR=6.9
1382 432 ▶ $score += $FLAG_WEIGHT{$severity} // 1;
Condition100%3/3
$FLAG_WEIGHT{$severity} // 1
l!l
38824
MC/DC0%0/1
$FLAG_WEIGHT{$severity} // 1
$FLAG_WEIGHT{$severity}
Truth table50%1/2
A
A= $FLAG_WEIGHT{$severity}
Aresult
11
00
1383 419 push @flags, { severity => $severity, flag => $name, detail => $detail };
1384 347 };
1385  
1386 347 $self->_risk_check_origin($flag);
1387 344 $self->_risk_check_auth($flag);
1388 344 $self->_risk_check_date($flag);
1389 344 $self->_risk_check_identity($flag);
1390 346 $self->_risk_check_urls_and_domains($flag);
1391  
1392 # Determine overall risk level from accumulated score
1393 346 ▶ my $level = $score >= $SCORE_HIGH ? 'HIGH'
Branch: 6 branches
BranchTrueFalseTotal
$score >= $SCORE_HIGH ? : 6 335 341
$score >= $SCORE_MEDIUM ? : 21 315 336
$score >= $SCORE_LOW ? : 146 169 315
$score >= $SCORE_HIGH ? : 1 0 1
$score >= $SCORE_MEDIUM ? : 1 0 1
$score >= $SCORE_LOW ? : 1 0 1
1394 : $score >= $SCORE_MEDIUM ? 'MEDIUM'
1395 : $score >= $SCORE_LOW ? 'LOW'
1396 : 'INFO';
1397  
1398 346 $self->{_risk} = { level => $level, score => $score, flags => \@flags };
1399 347 return $self->{_risk};
1400 }
1401  
1402 # _risk_check_origin( $flag )
1403 #
1404 # Purpose:
1405 # Evaluate the originating IP for residential rDNS, absent rDNS,
1406 # low-confidence origin, and high-spam-volume country.
1407 #
1408 # Entry criteria:
1409 # $flag -- coderef( severity, name, detail ) that accumulates flags.
1410 #
1411 # Exit status:
1412 # Returns nothing; side effects via $flag closure.
1413  
1414 sub _risk_check_origin :Private {
1415 411 ▶ my ($self, $flag) = @_;
Subroutine _risk_check_origin: called CC=10 SCAR=23.8
Subroutine _risk_check_origin: called CC=10 SCAR=23.8
1416 411 my $orig = $self->originating_ip();
1417 410 ▶ return unless $orig;
Branch: 2 branches
BranchTrueFalseTotal
unless $orig 77 341 418
unless $orig 1 0 1
1418  
1419 346 ▶ return if(!defined($orig->{ip}));
Branch: 2 branches
BranchTrueFalseTotal
unless defined $orig->{"ip"} 3 339 342
unless defined $orig->{"ip"} 0 2 2
1420  
1421 # Residential / broadband rDNS patterns suggest a compromised host
1422 345 ▶ if ($orig->{rdns} && $orig->{rdns} =~ /
Branch: 2 branches
BranchTrueFalseTotal
if ($orig->{"rdns"} and $orig->{"rdns"} =~ / \d+[-_.]\d+[-_.]\d+[-_.]\d+ # dotted-quad in rDNS | (?:dsl|adsl|cable|broad|dial|dynamic|dhcp|ppp| residential|cust|home|pool|client|user| static\d|host\d) /xi) 31 310 341
if ($orig->{"rdns"} and $orig->{"rdns"} =~ / \d+[-_.]\d+[-_.]\d+[-_.]\d+ # dotted-quad in rDNS | (?:dsl|adsl|cable|broad|dial|dynamic|dhcp|ppp| residential|cust|home|pool|client|user| static\d|host\d) /xi) 0 2 2
Condition50%3/6
$orig->{"rdns"} and $orig->{"rdns"} =~ /
!ll&&!rl&&r
5627928
$orig->{"rdns"} and $orig->{"rdns"} =~ /
!ll&&!rl&&r
000
MC/DC100%2/2
$orig->{"rdns"} and $orig->{"rdns"} =~ / \d+[-_.]\d+[-_.]\d+[-_.]\d+ # dotted-quad in rDNS | (?:dsl|adsl|cable|broad|dial|dynamic|dhcp|ppp| residential|cust|home|pool|client|user| static\d|host\d) /xi
$orig->{"rdns"} $orig->{"rdns"} =~ / \d+[-_.]\d+[-_.]\d+[-_.]\d+ # dotted-quad in rDNS | (?:dsl|adsl|cable|broad|dial|dynamic|dhcp|ppp| residential|cust|home|pool|client|user| static\d|host\d) /xi
MC/DC0%0/2
$orig->{"rdns"} and $orig->{"rdns"} =~ / \d+[-_.]\d+[-_.]\d+[-_.]\d+ # dotted-quad in rDNS | (?:dsl|adsl|cable|broad|dial|dynamic|dhcp|ppp| residential|cust|home|pool|client|user| static\d|host\d) /xi
$orig->{"rdns"} $orig->{"rdns"} =~ / \d+[-_.]\d+[-_.]\d+[-_.]\d+ # dotted-quad in rDNS | (?:dsl|adsl|cable|broad|dial|dynamic|dhcp|ppp| residential|cust|home|pool|client|user| static\d|host\d) /xi
Truth table100%3/3
A and B
A= $orig->{"rdns"}B= $orig->{"rdns"} =~ / \d+[-_.]\d+[-_.]\d+[-_.]\d+ # dotted-quad in rDNS | (?:dsl|adsl|cable|broad|dial|dynamic|dhcp|ppp| residential|cust|home|pool|client|user| static\d|host\d) /xi
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $orig->{"rdns"}B= $orig->{"rdns"} =~ / \d+[-_.]\d+[-_.]\d+[-_.]\d+ # dotted-quad in rDNS | (?:dsl|adsl|cable|broad|dial|dynamic|dhcp|ppp| residential|cust|home|pool|client|user| static\d|host\d) /xi
ABresult
0X0
100
111
1423 \d+[-_.]\d+[-_.]\d+[-_.]\d+ # dotted-quad in rDNS
1424 | (?:dsl|adsl|cable|broad|dial|dynamic|dhcp|ppp|
1425 residential|cust|home|pool|client|user|
1426 static\d|host\d)
1427 /xi) {
1428 65 $flag->('HIGH', 'residential_sending_ip',
1429 "Sending IP $orig->{ip} rDNS '$orig->{rdns}' looks like a broadband/residential line, not a legitimate mail server");
1430 }
1431  
1432 # Absence of rDNS is a strong spam indicator
1433 345 ▶ if (!$orig->{rdns} || $orig->{rdns} eq '(no reverse DNS)') {
Branch: 2 branches
BranchTrueFalseTotal
if (not $orig->{"rdns"} or $orig->{"rdns"} eq "(no reverse DNS)") 25 313 338
if (not $orig->{"rdns"} or $orig->{"rdns"} eq "(no reverse DNS)") 0 2 2
Condition50%3/6
not $orig->{"rdns"} or $orig->{"rdns"} eq "(no reverse DNS)"
l!l&&r!l&&!r
615346
not $orig->{"rdns"} or $orig->{"rdns"} eq "(no reverse DNS)"
l!l&&r!l&&!r
000
MC/DC100%2/2
not $orig->{"rdns"} or $orig->{"rdns"} eq "(no reverse DNS)"
not $orig->{"rdns"} $orig->{"rdns"} eq "(no reverse DNS)"
MC/DC0%0/2
not $orig->{"rdns"} or $orig->{"rdns"} eq "(no reverse DNS)"
not $orig->{"rdns"} $orig->{"rdns"} eq "(no reverse DNS)"
Truth table100%3/3
not(A) or B
A= not $orig->{"rdns"}B= $orig->{"rdns"} eq "(no reverse DNS)"
ABresult
1X1
011
000
Truth table0%0/3
not(A) or B
A= not $orig->{"rdns"}B= $orig->{"rdns"} eq "(no reverse DNS)"
ABresult
1X1
011
000
1434 53 $flag->('HIGH', 'no_reverse_dns',
1435 "Sending IP $orig->{ip} has no reverse DNS -- legitimate mail servers always have rDNS");
1436 }
1437  
1438 # Low-confidence origin means the IP came from an unverifiable header
1439 345 ▶ if ($orig->{confidence} eq 'low') {
Branch: 2 branches
BranchTrueFalseTotal
if ($orig->{"confidence"} eq "low") 7 304 311
if ($orig->{"confidence"} eq "low") 1 1 2
1440 42 $flag->('MEDIUM', 'low_confidence_origin',
1441 "Originating IP taken from unverified header ($orig->{note})");
1442 }
1443  
1444 # Statistically high-volume spam countries (informational only)
1445 314 ▶ if ($orig->{country} && $orig->{country} =~ /^(?:CN|RU|NG|VN|IN|PK|BD)$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($orig->{"country"} and $orig->{"country"} =~ /^(?:CN|RU|NG|VN|IN|PK|BD)$/) 34 276 310
if ($orig->{"country"} and $orig->{"country"} =~ /^(?:CN|RU|NG|VN|IN|PK|BD)$/) 1 1 2
Condition50%3/6
$orig->{"country"} and $orig->{"country"} =~ /^(?:CN|RU|NG|VN|IN|PK|BD)$/
!ll&&!rl&&r
2522432
$orig->{"country"} and $orig->{"country"} =~ /^(?:CN|RU|NG|VN|IN|PK|BD)$/
!ll&&!rl&&r
000
MC/DC100%2/2
$orig->{"country"} and $orig->{"country"} =~ /^(?:CN|RU|NG|VN|IN|PK|BD)$/
$orig->{"country"} $orig->{"country"} =~ /^(?:CN|RU|NG|VN|IN|PK|BD)$/
MC/DC0%0/2
$orig->{"country"} and $orig->{"country"} =~ /^(?:CN|RU|NG|VN|IN|PK|BD)$/
$orig->{"country"} $orig->{"country"} =~ /^(?:CN|RU|NG|VN|IN|PK|BD)$/
Truth table100%3/3
A and B
A= $orig->{"country"}B= $orig->{"country"} =~ /^(?:CN|RU|NG|VN|IN|PK|BD)$/
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $orig->{"country"}B= $orig->{"country"} =~ /^(?:CN|RU|NG|VN|IN|PK|BD)$/
ABresult
0X0
100
111
1446 $flag->('INFO', 'high_spam_country',
1447 39 'Sending IP is in ' . _country_name($orig->{country}) .
1448 " ($orig->{country}) -- statistically high spam volume country");
1449 }
1450 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
1451  
1452 # _risk_check_auth( $flag )
1453 #
1454 # Purpose:
1455 # Evaluate SPF, DKIM, DMARC results and DKIM signing domain alignment.
1456 #
1457 # Entry criteria:
1458 # $flag -- accumulator coderef.
1459 #
1460 # Exit status:
1461 # Returns nothing; side effects via $flag closure.
1462  
1463 sub _risk_check_auth :Private {
1464 378 ▶ my ($self, $flag) = @_;
Subroutine _risk_check_auth: called CC=17 SCAR=31.5
Subroutine _risk_check_auth: called CC=17 SCAR=31.5
1465 378 my $auth = $self->_parse_auth_results_cached();
1466  
1467 378 ▶ if (defined $auth->{spf}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $auth->{"spf"}) 34 391 425
if (defined $auth->{"spf"}) 1 1 2
1468 40 ▶ if ($auth->{spf} =~ /^fail/i) {
Branch: 6 branches
BranchTrueFalseTotal
if ($auth->{'spf'} =~ /^fail/i) { } 12 75 87
elsif ($auth->{'spf'} =~ /^softfail/i) { } 59 16 75
elsif (not $auth->{'spf'} =~ /^pass/i) { } 52 16 68
if ($auth->{'spf'} =~ /^fail/i) { } 1 0 1
elsif ($auth->{'spf'} =~ /^softfail/i) { } 1 0 1
elsif (not $auth->{'spf'} =~ /^pass/i) { } 0 2 2
1469 18 $flag->('HIGH', 'spf_fail',
1470 "SPF result: $auth->{spf} -- sending IP not authorised by domain's SPF record");
1471 } elsif ($auth->{spf} =~ /^softfail/i) {
1472 13 $flag->('MEDIUM', 'spf_softfail',
1473 "SPF result: softfail (~all) -- sending IP not explicitly authorised");
1474 } elsif ($auth->{spf} !~ /^pass/i) {
1475 6 $flag->('HIGH', 'spf_fail',
1476 "SPF result: $auth->{spf} -- sending IP not authorised");
1477 }
1478 }
1479 378 ▶ if (defined $auth->{dkim} && $auth->{dkim} !~ /^pass/i) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $auth->{"dkim"} and not $auth->{"dkim"} =~ /^pass/i) 14 360 374
if (defined $auth->{"dkim"} and not $auth->{"dkim"} =~ /^pass/i) 0 0 0
Condition66%4/6
defined $auth->{"dkim"} and not $auth->{"dkim"} =~ /^pass/i
!ll&&!rl&&r
3411715
defined $auth->{"dkim"} and not $auth->{"dkim"} =~ /^pass/i
!ll&&!rl&&r
200
MC/DC100%2/2
defined $auth->{"dkim"} and not $auth->{"dkim"} =~ /^pass/i
defined $auth->{"dkim"} not $auth->{"dkim"} =~ /^pass/i
MC/DC0%0/2
defined $auth->{"dkim"} and not $auth->{"dkim"} =~ /^pass/i
defined $auth->{"dkim"} not $auth->{"dkim"} =~ /^pass/i
Truth table100%3/3
A and not(B)
A= defined $auth->{"dkim"}B= not $auth->{"dkim"} =~ /^pass/i
ABresult
0X0
100
111
Truth table33%1/3
A and not(B)
A= defined $auth->{"dkim"}B= not $auth->{"dkim"} =~ /^pass/i
ABresult
0X0
100
111
1480 20 $flag->('HIGH', 'dkim_fail',
1481 "DKIM result: $auth->{dkim} -- message signature invalid or absent");
1482 }
1483 378 ▶ if (defined $auth->{dmarc} && $auth->{dmarc} !~ /^pass/i) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $auth->{"dmarc"} and not $auth->{"dmarc"} =~ /^pass/i) 8 366 374
if (defined $auth->{"dmarc"} and not $auth->{"dmarc"} =~ /^pass/i) 0 0 0
Condition50%3/6
defined $auth->{"dmarc"} and not $auth->{"dmarc"} =~ /^pass/i
!ll&&!rl&&r
354128
defined $auth->{"dmarc"} and not $auth->{"dmarc"} =~ /^pass/i
!ll&&!rl&&r
000
MC/DC100%2/2
defined $auth->{"dmarc"} and not $auth->{"dmarc"} =~ /^pass/i
defined $auth->{"dmarc"} not $auth->{"dmarc"} =~ /^pass/i
MC/DC0%0/2
defined $auth->{"dmarc"} and not $auth->{"dmarc"} =~ /^pass/i
defined $auth->{"dmarc"} not $auth->{"dmarc"} =~ /^pass/i
Truth table100%3/3
A and not(B)
A= defined $auth->{"dmarc"}B= not $auth->{"dmarc"} =~ /^pass/i
ABresult
0X0
100
111
Truth table0%0/3
A and not(B)
A= defined $auth->{"dmarc"}B= not $auth->{"dmarc"} =~ /^pass/i
ABresult
0X0
100
111
1484 14 $flag->('HIGH', 'dmarc_fail', "DMARC result: $auth->{dmarc}");
1485 }
1486  
1487 # DKIM signing domain vs From: domain mismatch check
1488 378 ▶ return unless $auth->{dkim_domain};
Branch: 2 branches
BranchTrueFalseTotal
unless $auth->{"dkim_domain"} 364 9 373
unless $auth->{"dkim_domain"} 0 0 0
1489 65 ▶ my ($from_domain) = ($self->_header_value('from') // '') =~ /\@([\w.-]+)/;
Condition40%2/5
$self->_header_value("from") // ""
l!l
902
$self->_header_value("from") // ""
l!l
00
MC/DC0%0/1
$self->_header_value("from") // ""
$self->_header_value("from")
MC/DC0%0/1
$self->_header_value("from") // ""
$self->_header_value("from")
Truth table50%1/2
A
A= $self->_header_value("from")
Aresult
11
00
Truth table0%0/2
A
A= $self->_header_value("from")
Aresult
11
00
1490 65 ▶ return unless $from_domain;
Branch: 2 branches
BranchTrueFalseTotal
unless $from_domain 1 9 10
unless $from_domain 0 2 2
1491 65 ▶ my $reg_dkim = _registrable($auth->{dkim_domain}) // $auth->{dkim_domain};
Condition33%2/6
_registrable($auth->{"dkim_domain"}) // $auth->{"dkim_domain"}
l!l&&r!l&&!r
1020
_registrable($auth->{"dkim_domain"}) // $auth->{"dkim_domain"}
l!l&&r!l&&!r
000
MC/DC0%0/2
_registrable($auth->{"dkim_domain"}) // $auth->{"dkim_domain"}
_registrable($auth->{"dkim_domain"}) $auth->{"dkim_domain"}
MC/DC0%0/2
_registrable($auth->{"dkim_domain"}) // $auth->{"dkim_domain"}
_registrable($auth->{"dkim_domain"}) $auth->{"dkim_domain"}
Truth table33%1/3
A // B
A= _registrable($auth->{"dkim_domain"})B= $auth->{"dkim_domain"}
ABresult
1X1
011
000
Truth table0%0/3
A // B
A= _registrable($auth->{"dkim_domain"})B= $auth->{"dkim_domain"}
ABresult
1X1
011
000
1492 65 ▶ my $reg_from = _registrable(lc $from_domain) // lc $from_domain;
Condition33%2/6
_registrable(lc $from_domain) // lc $from_domain
l!l&&r!l&&!r
1101
_registrable(lc $from_domain) // lc $from_domain
l!l&&r!l&&!r
000
MC/DC0%0/2
_registrable(lc $from_domain) // lc $from_domain
_registrable(lc $from_domain) lc $from_domain
MC/DC0%0/2
_registrable(lc $from_domain) // lc $from_domain
_registrable(lc $from_domain) lc $from_domain
Truth table33%1/3
A // B
A= _registrable(lc $from_domain)B= lc $from_domain
ABresult
1X1
011
000
Truth table0%0/3
A // B
A= _registrable(lc $from_domain)B= lc $from_domain
ABresult
1X1
011
000
1493 65 ▶ return if $reg_dkim eq $reg_from;
Branch: 2 branches
BranchTrueFalseTotal
if $reg_dkim eq $reg_from 3 7 10
if $reg_dkim eq $reg_from 0 0 0
1494  
1495 # Passing DKIM with a different domain is normal for ESPs
1496 62 ▶ if ($auth->{dkim} && $auth->{dkim} =~ /^pass/i) {
Branch: 2 branches
BranchTrueFalseTotal
if ($auth->{'dkim'} and $auth->{'dkim'} =~ /^pass/i) { } 3 4 7
if ($auth->{'dkim'} and $auth->{'dkim'} =~ /^pass/i) { } 0 0 0
Condition66%4/6
$auth->{"dkim"} and $auth->{"dkim"} =~ /^pass/i
!ll&&!rl&&r
033
$auth->{"dkim"} and $auth->{"dkim"} =~ /^pass/i
!ll&&!rl&&r
220
MC/DC50%1/2
$auth->{"dkim"} and $auth->{"dkim"} =~ /^pass/i
$auth->{"dkim"} $auth->{"dkim"} =~ /^pass/i
MC/DC0%0/2
$auth->{"dkim"} and $auth->{"dkim"} =~ /^pass/i
$auth->{"dkim"} $auth->{"dkim"} =~ /^pass/i
Truth table66%2/3
A and B
A= $auth->{"dkim"}B= $auth->{"dkim"} =~ /^pass/i
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $auth->{"dkim"}B= $auth->{"dkim"} =~ /^pass/i
ABresult
0X0
100
111
1497 59 $flag->('INFO', 'dkim_domain_mismatch',
1498 "DKIM signed by '$auth->{dkim_domain}' but From: domain is '$from_domain'"
1499 . ' -- message sent via third-party sender (normal for bulk/ESP mail)');
1500 } else {
1501 # Failing DKIM plus mismatched domain is more suspicious
1502 59 $flag->('MEDIUM', 'dkim_domain_mismatch',
1503 "DKIM signed by '$auth->{dkim_domain}' but From: domain is '$from_domain'"
1504 . ' and DKIM did not pass -- possible impersonation');
1505 }
1506 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
1507  
1508 # _risk_check_date( $flag )
1509 #
1510 # Purpose:
1511 # Validate the Date: header for presence, plausible timezone, and
1512 # date not too far in the past or future.
1513 #
1514 # Entry criteria:
1515 # $flag -- accumulator coderef.
1516 #
1517 # Exit status:
1518 # Returns nothing; side effects via $flag closure.
1519  
1520 sub _risk_check_date :Private {
1521 428 ▶ my ($self, $flag) = @_;
Subroutine _risk_check_date: called CC=12 SCAR=27.3
Subroutine _risk_check_date: called CC=12 SCAR=27.3
1522 428 my $date_raw = $self->_header_value('date');
1523  
1524 428 ▶ if (!$date_raw || $date_raw !~ /\S/) {
Branch: 2 branches
BranchTrueFalseTotal
unless ($date_raw and $date_raw =~ /\S/) 45 330 375
unless ($date_raw and $date_raw =~ /\S/) 0 0 0
Condition50%3/6
$date_raw and $date_raw =~ /\S/
!ll&&!rl&&r
440328
$date_raw and $date_raw =~ /\S/
!ll&&!rl&&r
200
MC/DC50%1/2
$date_raw and $date_raw =~ /\S/
$date_raw $date_raw =~ /\S/
MC/DC0%0/2
$date_raw and $date_raw =~ /\S/
$date_raw $date_raw =~ /\S/
Truth table66%2/3
A and B
A= $date_rawB= $date_raw =~ /\S/
ABresult
0X0
100
111
Truth table33%1/3
A and B
A= $date_rawB= $date_raw =~ /\S/
ABresult
0X0
100
111
1525 100 $flag->('MEDIUM', 'missing_date',
1526 'No Date: header -- violates RFC 5322; common in spam');
1527 99 return;
1528 }
1529  
1530 # Check for an implausible timezone offset (outside real-world bounds)
1531 383 ▶ if ($date_raw =~ /([+-])(\d{2})(\d{2})\s*$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($date_raw =~ /([+-])(\d{2})(\d{2})\s*$/) 329 2 331
if ($date_raw =~ /([+-])(\d{2})(\d{2})\s*$/) 1 0 1
1532 383 my ($sign, $hh, $mm) = ($1, $2, $3);
1533 383 my $offset_mins = $hh * 60 + $mm;
1534 383 ▶ my $implausible = $mm >= 60
Condition50%12/24
$mm >= 60 || $sign eq '+' && $offset_mins > $TZ_MAX_POS_MINS || $sign eq '-' && $offset_mins > $TZ_MAX_NEG_MINS
l!l&&r!l&&!r
93316
$mm >= 60 or $sign eq "+" and $offset_mins > $TZ_MAX_POS_MINS
l!l&&r!l&&!r
36319
$sign eq "+" and $offset_mins > $TZ_MAX_POS_MINS
!ll&&!rl&&r
73126
$sign eq "-" and $offset_mins > $TZ_MAX_NEG_MINS
!ll&&!rl&&r
31243
$mm >= 60 || $sign eq '+' && $offset_mins > $TZ_MAX_POS_MINS || $sign eq '-' && $offset_mins > $TZ_MAX_NEG_MINS
l!l&&r!l&&!r
000
$mm >= 60 or $sign eq "+" and $offset_mins > $TZ_MAX_POS_MINS
l!l&&r!l&&!r
000
$sign eq "+" and $offset_mins > $TZ_MAX_POS_MINS
!ll&&!rl&&r
000
$sign eq "-" and $offset_mins > $TZ_MAX_NEG_MINS
!ll&&!rl&&r
000
MC/DC80%4/5
$mm >= 60 || $sign eq '+' && $offset_mins > $TZ_MAX_POS_MINS || $sign eq '-' && $offset_mins > $TZ_MAX_NEG_MINS
$mm >= 60 $sign eq "+" $offset_mins > $TZ_MAX_POS_MINS $sign eq "-" $offset_mins > $TZ_MAX_NEG_MINS
MC/DC0%0/5
$mm >= 60 || $sign eq '+' && $offset_mins > $TZ_MAX_POS_MINS || $sign eq '-' && $offset_mins > $TZ_MAX_NEG_MINS
$mm >= 60 $sign eq "+" $offset_mins > $TZ_MAX_POS_MINS $sign eq "-" $offset_mins > $TZ_MAX_NEG_MINS
Truth table62%5/8
A or B and C || D and E
A= $mm >= 60B= $sign eq "+"C= $offset_mins > $TZ_MAX_POS_MINSD= $sign eq "-"E= $offset_mins > $TZ_MAX_NEG_MINS
ABCDEresult
1XXXX1
011XX1
00X111
010111
00X0X0
00X100
0100X0
010100
Truth table0%0/8
A or B and C || D and E
A= $mm >= 60B= $sign eq "+"C= $offset_mins > $TZ_MAX_POS_MINSD= $sign eq "-"E= $offset_mins > $TZ_MAX_NEG_MINS
ABCDEresult
1XXXX1
011XX1
00X111
010111
00X0X0
00X100
0100X0
010100
1535 || ($sign eq '+' && $offset_mins > $TZ_MAX_POS_MINS)
1536 || ($sign eq '-' && $offset_mins > $TZ_MAX_NEG_MINS);
1537 383 ▶ if ($implausible) {
Branch: 2 branches
BranchTrueFalseTotal
if ($implausible) 12 319 331
if ($implausible) 2 0 2
1538 16 $flag->('MEDIUM', 'implausible_timezone',
1539 "Date: '$date_raw' contains an implausible timezone offset "
1540 . "($sign$hh$mm) -- header is likely forged");
1541 }
1542 }
1543  
1544 # Check for dates more than DATE_SKEW_DAYS outside the analysis window
1545 332 my $date_epoch = _parse_rfc2822_date($date_raw);
1546 332 ▶ return unless defined $date_epoch;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $date_epoch 0 331 331
unless defined $date_epoch 0 1 1
1547 332 my $delta = time() - $date_epoch;
1548 332 ▶ if ($delta > $DATE_SKEW_DAYS * $SECS_PER_DAY) {
Branch: 4 branches
BranchTrueFalseTotal
if ($delta > $DATE_SKEW_DAYS * $SECS_PER_DAY) { } 51 279 330
elsif ($delta < -($DATE_SKEW_DAYS * $SECS_PER_DAY)) { } 6 274 280
if ($delta > $DATE_SKEW_DAYS * $SECS_PER_DAY) { } 0 0 0
elsif ($delta < -($DATE_SKEW_DAYS * $SECS_PER_DAY)) { } 0 0 0
1549 54 $flag->('LOW', 'suspicious_date',
1550 "Date: '$date_raw' is more than $DATE_SKEW_DAYS days in the past");
1551 } elsif ($delta < -($DATE_SKEW_DAYS * $SECS_PER_DAY)) {
1552 9 $flag->('LOW', 'suspicious_date',
1553 "Date: '$date_raw' is more than $DATE_SKEW_DAYS days in the future");
1554 }
1555 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
1556  
1557 # _risk_check_identity( $flag )
1558 #
1559 # Purpose:
1560 # Check From: display-name spoofing, free webmail, Reply-To mismatch,
1561 # undisclosed recipients, and MIME-encoded Subject.
1562 #
1563 # Entry criteria:
1564 # $flag -- accumulator coderef.
1565 #
1566 # Exit status:
1567 # Returns nothing; side effects via $flag closure.
1568  
1569 sub _risk_check_identity :Private {
1570 378 ▶ my ($self, $flag) = @_;
Subroutine _risk_check_identity: called CC=19 SCAR=35.3
Subroutine _risk_check_identity: called CC=19 SCAR=35.3
1571 378 ▶ my $from_raw = $self->_header_value('from') // '';
Condition40%2/5
$self->_header_value("from") // ""
l!l
36930
$self->_header_value("from") // ""
l!l
00
MC/DC100%1/1
$self->_header_value("from") // ""
$self->_header_value("from")
MC/DC0%0/1
$self->_header_value("from") // ""
$self->_header_value("from")
Truth table100%2/2
A
A= $self->_header_value("from")
Aresult
11
00
Truth table0%0/2
A
A= $self->_header_value("from")
Aresult
11
00
1572 378 my $from_decoded = $self->_decode_mime_words($from_raw);
1573  
1574 # Display-name domain spoofing: "PayPal paypal.com" <phish@evil.example>
1575 378 ▶ if ($from_decoded =~ /^"?([^"<]+?)"?\s*<([^>]+)>/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($from_decoded =~ /^"?([^"<]+?)"?\s*<([^>]+)>/) 193 180 373
if ($from_decoded =~ /^"?([^"<]+?)"?\s*<([^>]+)>/) 0 0 0
1576 199 my ($display, $addr) = ($1, $2);
1577 199 ▶ while ($display =~ /\b([\w-]+\.(?:com|net|org|io|co|uk|au|gov|edu))\b/gi) {
Branch: 2 branches
BranchTrueFalseTotal
if ($display =~ /\b([\w-]+\.(?:com|net|org|io|co|uk|au|gov|edu))\b/gi) 6 194 200
if ($display =~ /\b([\w-]+\.(?:com|net|org|io|co|uk|au|gov|edu))\b/gi) 0 0 0
1578 12 my $disp_domain = lc $1;
1579 12 my ($addr_domain) = $addr =~ /\@([\w.-]+)/;
1580 12 ▶ $addr_domain = lc($addr_domain // '');
Condition20%1/5
$addr_domain // ""
l!l
600
$addr_domain // ""
l!l
00
MC/DC0%0/1
$addr_domain // ""
$addr_domain
MC/DC0%0/1
$addr_domain // ""
$addr_domain
Truth table50%1/2
A
A= $addr_domain
Aresult
11
00
Truth table0%0/2
A
A= $addr_domain
Aresult
11
00
1581 12 my $reg_disp = _registrable($disp_domain);
1582 12 my $reg_addr = _registrable($addr_domain);
1583 12 ▶ if ($reg_disp && $reg_addr && $reg_disp ne $reg_addr) {
Branch: 2 branches
BranchTrueFalseTotal
if ($reg_disp and $reg_addr and $reg_disp ne $reg_addr) 7 1 8
if ($reg_disp and $reg_addr and $reg_disp ne $reg_addr) 0 0 0
Condition16%2/12
$reg_disp and $reg_addr and $reg_disp ne $reg_addr
!ll&&!rl&&r
006
$reg_disp and $reg_addr
!ll&&!rl&&r
006
$reg_disp and $reg_addr and $reg_disp ne $reg_addr
!ll&&!rl&&r
000
$reg_disp and $reg_addr
!ll&&!rl&&r
000
MC/DC0%0/3
$reg_disp and $reg_addr and $reg_disp ne $reg_addr
$reg_disp $reg_addr $reg_disp ne $reg_addr
MC/DC0%0/3
$reg_disp and $reg_addr and $reg_disp ne $reg_addr
$reg_disp $reg_addr $reg_disp ne $reg_addr
Truth table25%1/4
A and B and C
A= $reg_dispB= $reg_addrC= $reg_disp ne $reg_addr
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/4
A and B and C
A= $reg_dispB= $reg_addrC= $reg_disp ne $reg_addr
ABCresult
0XX0
10X0
1100
1111
1584 12 $flag->('HIGH', 'display_name_domain_spoof',
1585 "From: display name mentions '$disp_domain' but actual address is <$addr>");
1586 }
1587 }
1588 }
1589  
1590 # Free webmail sender flag (no corporate infrastructure)
1591 377 ▶ if ($from_raw =~ /\@(gmail|yahoo|hotmail|outlook|live|aol|protonmail|yandex)\./i
Branch: 2 branches
BranchTrueFalseTotal
if ($from_raw =~ /\@(gmail|yahoo|hotmail|outlook|live|aol|protonmail|yandex)\./i or $from_raw =~ /\@mail\.ru(?:[\s>]|$)/i) 31 342 373
if ($from_raw =~ /\@(gmail|yahoo|hotmail|outlook|live|aol|protonmail|yandex)\./i or $from_raw =~ /\@mail\.ru(?:[\s>]|$)/i) 0 0 0
Condition50%3/6
$from_raw =~ /\@(gmail|yahoo|hotmail|outlook|live|aol|protonmail|yandex)\./i or $from_raw =~ /\@mail\.ru(?:[\s>]|$)/i
l!l&&r!l&&!r
301341
$from_raw =~ /\@(gmail|yahoo|hotmail|outlook|live|aol|protonmail|yandex)\./i or $from_raw =~ /\@mail\.ru(?:[\s>]|$)/i
l!l&&r!l&&!r
000
MC/DC100%2/2
$from_raw =~ /\@(gmail|yahoo|hotmail|outlook|live|aol|protonmail|yandex)\./i or $from_raw =~ /\@mail\.ru(?:[\s>]|$)/i
$from_raw =~ /\@(gmail|yahoo|hotmail|outlook|live|aol|protonmail|yandex)\./i $from_raw =~ /\@mail\.ru(?:[\s>]|$)/i
MC/DC0%0/2
$from_raw =~ /\@(gmail|yahoo|hotmail|outlook|live|aol|protonmail|yandex)\./i or $from_raw =~ /\@mail\.ru(?:[\s>]|$)/i
$from_raw =~ /\@(gmail|yahoo|hotmail|outlook|live|aol|protonmail|yandex)\./i $from_raw =~ /\@mail\.ru(?:[\s>]|$)/i
Truth table100%3/3
A or B
A= $from_raw =~ /\@(gmail|yahoo|hotmail|outlook|live|aol|protonmail|yandex)\./iB= $from_raw =~ /\@mail\.ru(?:[\s>]|$)/i
ABresult
1X1
011
000
Truth table0%0/3
A or B
A= $from_raw =~ /\@(gmail|yahoo|hotmail|outlook|live|aol|protonmail|yandex)\./iB= $from_raw =~ /\@mail\.ru(?:[\s>]|$)/i
ABresult
1X1
011
000
1592 || $from_raw =~ /\@mail\.ru(?:[\s>]|$)/i) {
1593 36 $flag->('MEDIUM', 'free_webmail_sender',
1594 "Message sent from free webmail address ($from_raw)");
1595 }
1596  
1597 # Reply-To differs from From: -- replies harvested by different address
1598 377 my $reply_to = $self->_header_value('reply-to');
1599 377 ▶ if ($reply_to) {
Branch: 2 branches
BranchTrueFalseTotal
if ($reply_to) 7 366 373
if ($reply_to) 0 0 0
1600 12 my ($from_addr) = $from_raw =~ /([\w.+%-]+\@[\w.-]+)/;
1601 12 my ($reply_addr) = $reply_to =~ /([\w.+%-]+\@[\w.-]+)/;
1602 12 ▶ if ($from_addr && $reply_addr && lc($from_addr) ne lc($reply_addr)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($from_addr and $reply_addr and lc $from_addr ne lc $reply_addr) 6 2 8
if ($from_addr and $reply_addr and lc $from_addr ne lc $reply_addr) 0 0 0
Condition25%3/12
$from_addr and $reply_addr and lc $from_addr ne lc $reply_addr
!ll&&!rl&&r
025
$from_addr and $reply_addr
!ll&&!rl&&r
007
$from_addr and $reply_addr and lc $from_addr ne lc $reply_addr
!ll&&!rl&&r
000
$from_addr and $reply_addr
!ll&&!rl&&r
000
MC/DC33%1/3
$from_addr and $reply_addr and lc $from_addr ne lc $reply_addr
$from_addr $reply_addr lc $from_addr ne lc $reply_addr
MC/DC0%0/3
$from_addr and $reply_addr and lc $from_addr ne lc $reply_addr
$from_addr $reply_addr lc $from_addr ne lc $reply_addr
Truth table50%2/4
A and B and C
A= $from_addrB= $reply_addrC= lc $from_addr ne lc $reply_addr
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/4
A and B and C
A= $from_addrB= $reply_addrC= lc $from_addr ne lc $reply_addr
ABCresult
0XX0
10X0
1100
1111
1603 10 $flag->('MEDIUM', 'reply_to_differs_from_from',
1604 "Reply-To ($reply_addr) differs from From: ($from_addr)");
1605 }
1606 }
1607  
1608 # Undisclosed or absent To: header
1609 377 ▶ my $to = $self->_header_value('to') // '';
Condition60%3/5
$self->_header_value("to") // ""
l!l
33438
$self->_header_value("to") // ""
l!l
100
MC/DC100%1/1
$self->_header_value("to") // ""
$self->_header_value("to")
MC/DC0%0/1
$self->_header_value("to") // ""
$self->_header_value("to")
Truth table100%2/2
A
A= $self->_header_value("to")
Aresult
11
00
Truth table50%1/2
A
A= $self->_header_value("to")
Aresult
11
00
1610 377 ▶ if ($to =~ /undisclosed|:;/ || $to eq '') {
Branch: 2 branches
BranchTrueFalseTotal
if ($to =~ /undisclosed|:;/ or $to eq "") 46 326 372
if ($to =~ /undisclosed|:;/ or $to eq "") 1 5 6
Condition50%3/6
$to =~ /undisclosed|:;/ or $to eq ""
l!l&&r!l&&!r
640326
$to =~ /undisclosed|:;/ or $to eq ""
l!l&&r!l&&!r
000
MC/DC100%2/2
$to =~ /undisclosed|:;/ or $to eq ""
$to =~ /undisclosed|:;/ $to eq ""
MC/DC0%0/2
$to =~ /undisclosed|:;/ or $to eq ""
$to =~ /undisclosed|:;/ $to eq ""
Truth table100%3/3
A or B
A= $to =~ /undisclosed|:;/B= $to eq ""
ABresult
1X1
011
000
Truth table0%0/3
A or B
A= $to =~ /undisclosed|:;/B= $to eq ""
ABresult
1X1
011
000
1611 51 $flag->('MEDIUM', 'undisclosed_recipients',
1612 "To: header is '$to' -- message was bulk-sent with hidden recipient list");
1613 }
1614  
1615 # MIME-encoded Subject (potential filter evasion)
1616 377 ▶ my $subj_raw = $self->_header_value('subject') // '';
Condition50%2/4
$self->_header_value("subject") // ""
l!l
33735
$self->_header_value("subject") // ""
l!l
00
MC/DC100%1/1
$self->_header_value("subject") // ""
$self->_header_value("subject")
MC/DC0%0/1
$self->_header_value("subject") // ""
$self->_header_value("subject")
Truth table100%2/2
A
A= $self->_header_value("subject")
Aresult
11
00
Truth table0%0/2
A
A= $self->_header_value("subject")
Aresult
11
00
1617 377 ▶ if ($subj_raw =~ /=\?[^?]+\?[BQ]\?/i) {
Branch: 2 branches
BranchTrueFalseTotal
if ($subj_raw =~ /=\?[^?]+\?[BQ]\?/i) 11 361 372
if ($subj_raw =~ /=\?[^?]+\?[BQ]\?/i) 0 5 5
1618 17 $flag->('LOW', 'encoded_subject',
1619 "Subject line is MIME-encoded: '$subj_raw' (decoded: '"
1620 . $self->_decode_mime_words($subj_raw) . "')");
1621 }
1622 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
Subroutine BEGIN: called CC=1 SCAR=0.1
1623  
1624 # _risk_check_urls_and_domains( $flag )
1625 #
1626 # Purpose:
1627 # Check embedded URLs for shorteners and plain HTTP, and contact domains
1628 # for recent registration, imminent expiry, and lookalike brand names.
1629 #
1630 # Entry criteria:
1631 # $flag -- accumulator coderef.
1632 #
1633 # Exit status:
1634 # Returns nothing; side effects via $flag closure.
1635  
1636 sub _risk_check_urls_and_domains :Private {
1637 378 ▶ my ($self, $flag) = @_;
Subroutine _risk_check_urls_and_domains: called CC=24 SCAR=36.4
Subroutine _risk_check_urls_and_domains: called CC=24 SCAR=36.4
1638 377 my (%shortener_seen, %cloaker_seen, %url_host_seen);
1639  
1640 377 for my $u ($self->embedded_urls()) {
1641 # Skip trusted infrastructure -- these are not spam indicators
1642 71 ▶ next unless($u->{host});
Branch: 2 branches
BranchTrueFalseTotal
unless $u->{"host"} 1 65 66
unless $u->{"host"} 1 0 1
1643 70 my $bare = lc $u->{host};
1644 70 ▶ next unless defined($bare);
Branch: 2 branches
BranchTrueFalseTotal
unless defined $bare 0 65 65
unless defined $bare 1 0 1
1645 70 $bare =~ s/^www\.//;
1646 70 ▶ next if $self->{trusted_domains}->{$bare};
Branch: 2 branches
BranchTrueFalseTotal
if $self->{"trusted_domains"}{$bare} 0 65 65
if $self->{"trusted_domains"}{$bare} 1 0 1
1647 70 ▶ next if $TRUSTED_DOMAINS{$bare};
Branch: 2 branches
BranchTrueFalseTotal
if $TRUSTED_DOMAINS{$bare} 2 63 65
if $TRUSTED_DOMAINS{$bare} 0 1 1
1648  
1649 # URL shortener hides real destination
1650 68 ▶ if(($URL_SHORTENERS{$bare} || $self->{url_shorteners}->{$bare}) && !$shortener_seen{$bare}++) {
Branch: 2 branches
BranchTrueFalseTotal
if ($URL_SHORTENERS{$bare} || $self->{"url_shorteners"}{$bare} and not $shortener_seen{$bare}++) 8 55 63
if ($URL_SHORTENERS{$bare} || $self->{"url_shorteners"}{$bare} and not $shortener_seen{$bare}++) 1 0 1
Condition33%4/12
$URL_SHORTENERS{$bare} || $self->{"url_shorteners"}{$bare} and not $shortener_seen{$bare}++
!ll&&!rl&&r
5508
$URL_SHORTENERS{$bare} or $self->{"url_shorteners"}{$bare}
l!l&&r!l&&!r
8055
$URL_SHORTENERS{$bare} || $self->{"url_shorteners"}{$bare} and not $shortener_seen{$bare}++
!ll&&!rl&&r
000
$URL_SHORTENERS{$bare} or $self->{"url_shorteners"}{$bare}
l!l&&r!l&&!r
000
MC/DC33%1/3
$URL_SHORTENERS{$bare} || $self->{"url_shorteners"}{$bare} and not $shortener_seen{$bare}++
$URL_SHORTENERS{$bare} $self->{"url_shorteners"}{$bare} not $shortener_seen{$bare}++
MC/DC0%0/3
$URL_SHORTENERS{$bare} || $self->{"url_shorteners"}{$bare} and not $shortener_seen{$bare}++
$URL_SHORTENERS{$bare} $self->{"url_shorteners"}{$bare} not $shortener_seen{$bare}++
Truth table40%2/5
A or B and not(C)
A= $URL_SHORTENERS{$bare}B= $self->{"url_shorteners"}{$bare}C= not $shortener_seen{$bare}++
ABCresult
00X0
1X00
0100
1X11
0111
Truth table0%0/5
A or B and not(C)
A= $URL_SHORTENERS{$bare}B= $self->{"url_shorteners"}{$bare}C= not $shortener_seen{$bare}++
ABCresult
00X0
1X00
0100
1X11
0111
1651 13 $flag->('MEDIUM', 'url_shortener',
1652 "$u->{host} is a URL shortener -- the real destination is hidden");
1653 }
1654 # Cloud object-store / CDN used as a redirect cloaker
1655 68 ▶ if ($self->_is_redirect_cloaker($bare) && !$cloaker_seen{$bare}++) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_is_redirect_cloaker($bare) and not $cloaker_seen{$bare}++) 1 62 63
if ($self->_is_redirect_cloaker($bare) and not $cloaker_seen{$bare}++) 1 0 1
Condition33%2/6
$self->_is_redirect_cloaker($bare) and not $cloaker_seen{$bare}++
!ll&&!rl&&r
6201
$self->_is_redirect_cloaker($bare) and not $cloaker_seen{$bare}++
!ll&&!rl&&r
000
MC/DC50%1/2
$self->_is_redirect_cloaker($bare) and not $cloaker_seen{$bare}++
$self->_is_redirect_cloaker($bare) not $cloaker_seen{$bare}++
MC/DC0%0/2
$self->_is_redirect_cloaker($bare) and not $cloaker_seen{$bare}++
$self->_is_redirect_cloaker($bare) not $cloaker_seen{$bare}++
Truth table66%2/3
A and not(B)
A= $self->_is_redirect_cloaker($bare)B= not $cloaker_seen{$bare}++
ABresult
0X0
100
111
Truth table0%0/3
A and not(B)
A= $self->_is_redirect_cloaker($bare)B= not $cloaker_seen{$bare}++
ABresult
0X0
100
111
1656 5 $flag->('MEDIUM', 'redirect_cloaker',
1657 "$u->{host} is a cloud storage or CDN host used as a redirect cloaker -- the real phishing destination is hidden behind a client-side redirect");
1658 }
1659 # Plain HTTP provides no encryption
1660 67 ▶ if ($u->{url} =~ m{^http://}i && !$url_host_seen{ $u->{host} }++) {
Branch: 2 branches
BranchTrueFalseTotal
if ($u->{"url"} =~ m[^http://]i and not $url_host_seen{$u->{"host"}}++) 9 54 63
if ($u->{"url"} =~ m[^http://]i and not $url_host_seen{$u->{"host"}}++) 1 0 1
Condition33%2/6
$u->{"url"} =~ m[^http://]i and not $url_host_seen{$u->{"host"}}++
!ll&&!rl&&r
5409
$u->{"url"} =~ m[^http://]i and not $url_host_seen{$u->{"host"}}++
!ll&&!rl&&r
000
MC/DC50%1/2
$u->{"url"} =~ m[^http://]i and not $url_host_seen{$u->{"host"}}++
$u->{"url"} =~ m[^http://]i not $url_host_seen{$u->{"host"}}++
MC/DC0%0/2
$u->{"url"} =~ m[^http://]i and not $url_host_seen{$u->{"host"}}++
$u->{"url"} =~ m[^http://]i not $url_host_seen{$u->{"host"}}++
Truth table66%2/3
A and not(B)
A= $u->{"url"} =~ m[^http://]iB= not $url_host_seen{$u->{"host"}}++
ABresult
0X0
100
111
Truth table0%0/3
A and not(B)
A= $u->{"url"} =~ m[^http://]iB= not $url_host_seen{$u->{"host"}}++
ABresult
0X0
100
111
1661 13 $flag->('LOW', 'http_not_https',
1662 "$u->{host} linked over plain HTTP -- no encryption");
1663 }
1664 }
1665  
1666 # Domain-level checks against contact/reply domains
1667 376 for my $d ($self->mailto_domains()) {
1668 # Recently registered domain is a common phishing indicator
1669 183 ▶ if ($d->{recently_registered}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($d->{"recently_registered"}) 8 171 179
if ($d->{"recently_registered"}) 0 1 1
1670 12 $flag->('HIGH', 'recently_registered_domain',
1671 12 "$d->{domain} was registered $d->{registered} (less than ${\$RECENT_REG_DAYS} days ago)");
1672 }
1673  
1674 # Domain expiry checks
1675 183 ▶ if ($d->{expires}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($d->{"expires"}) 17 162 179
if ($d->{"expires"}) 1 0 1
1676 20 ▶ if(my $exp = $self->_parse_date_to_epoch($d->{expires})) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $exp = $self->_parse_date_to_epoch($d->{"expires"})) 17 0 17
if (my $exp = $self->_parse_date_to_epoch($d->{"expires"})) 0 1 1
1677 20 my $now = time();
1678 20 my $remaining = $exp - $now;
1679 20 ▶ if ($remaining > 0 && $remaining < $EXPIRY_WARN_DAYS * $SECS_PER_DAY) {
Branch: 4 branches
BranchTrueFalseTotal
if ($remaining > 0 and $remaining < $EXPIRY_WARN_DAYS * $SECS_PER_DAY) { } 4 13 17
elsif ($remaining <= 0) { } 5 8 13
if ($remaining > 0 and $remaining < $EXPIRY_WARN_DAYS * $SECS_PER_DAY) { } 0 0 0
elsif ($remaining <= 0) { } 0 0 0
Condition50%3/6
$remaining > 0 and $remaining < $EXPIRY_WARN_DAYS * $SECS_PER_DAY
!ll&&!rl&&r
584
$remaining > 0 and $remaining < $EXPIRY_WARN_DAYS * $SECS_PER_DAY
!ll&&!rl&&r
000
MC/DC100%2/2
$remaining > 0 and $remaining < $EXPIRY_WARN_DAYS * $SECS_PER_DAY
$remaining > 0 $remaining < $EXPIRY_WARN_DAYS * $SECS_PER_DAY
MC/DC0%0/2
$remaining > 0 and $remaining < $EXPIRY_WARN_DAYS * $SECS_PER_DAY
$remaining > 0 $remaining < $EXPIRY_WARN_DAYS * $SECS_PER_DAY
Truth table100%3/3
A and B
A= $remaining > 0B= $remaining < $EXPIRY_WARN_DAYS * $SECS_PER_DAY
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $remaining > 0B= $remaining < $EXPIRY_WARN_DAYS * $SECS_PER_DAY
ABresult
0X0
100
111
1680 7 $flag->('HIGH', 'domain_expires_soon',
1681 "$d->{domain} expires $d->{expires} -- may be a throwaway domain");
1682 } elsif ($remaining <= 0) {
1683 8 $flag->('HIGH', 'domain_expired',
1684 "$d->{domain} expired $d->{expires} -- domain has lapsed");
1685 }
1686 }
1687 }
1688  
1689 # Lookalike domain check (brand name in a non-brand domain)
1690 182 for my $brand (@LOOKALIKE_BRANDS) {
1691 3079 ▶ next if(!defined($d->{domain}));
Branch: 2 branches
BranchTrueFalseTotal
unless defined $d->{"domain"} 18 3058 3076
unless defined $d->{"domain"} 1 0 1
1692 3061 ▶ if ($d->{domain} =~ /\Q$brand\E/i &&
Branch: 2 branches
BranchTrueFalseTotal
if ($d->{"domain"} =~ /\Q$brand\E/i and not $d->{"domain"} =~ /^\Q$brand\E\.(?:com|co\.uk|net|org)$/) 9 3049 3058
if ($d->{"domain"} =~ /\Q$brand\E/i and not $d->{"domain"} =~ /^\Q$brand\E\.(?:com|co\.uk|net|org)$/) 1 0 1
Condition66%4/6
$d->{"domain"} =~ /\Q$brand\E/i and not $d->{"domain"} =~ /^\Q$brand\E\.(?:com|co\.uk|net|org)$/
!ll&&!rl&&r
3039109
$d->{"domain"} =~ /\Q$brand\E/i and not $d->{"domain"} =~ /^\Q$brand\E\.(?:com|co\.uk|net|org)$/
!ll&&!rl&&r
200
MC/DC100%2/2
$d->{"domain"} =~ /\Q$brand\E/i and not $d->{"domain"} =~ /^\Q$brand\E\.(?:com|co\.uk|net|org)$/
$d->{"domain"} =~ /\Q$brand\E/i not $d->{"domain"} =~ /^\Q$brand\E\.(?:com|co\.uk|net|org)$/
MC/DC0%0/2
$d->{"domain"} =~ /\Q$brand\E/i and not $d->{"domain"} =~ /^\Q$brand\E\.(?:com|co\.uk|net|org)$/
$d->{"domain"} =~ /\Q$brand\E/i not $d->{"domain"} =~ /^\Q$brand\E\.(?:com|co\.uk|net|org)$/
Truth table100%3/3
A and not(B)
A= $d->{"domain"} =~ /\Q$brand\E/iB= not $d->{"domain"} =~ /^\Q$brand\E\.(?:com|co\.uk|net|org)$/
ABresult
0X0
100
111
Truth table33%1/3
A and not(B)
A= $d->{"domain"} =~ /\Q$brand\E/iB= not $d->{"domain"} =~ /^\Q$brand\E\.(?:com|co\.uk|net|org)$/
ABresult
0X0
100
111
1693 $d->{domain} !~ /^\Q$brand\E\.(?:com|co\.uk|net|org)$/) {
1694 12 $flag->('HIGH', 'lookalike_domain',
1695 "$d->{domain} contains brand name '$brand' but is not the real domain -- possible phishing");
1696 12 last;
1697 }
1698 }
1699 }
1700 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
1701  
1702 # -----------------------------------------------------------------------
1703 # Public: abuse report text
1704 # -----------------------------------------------------------------------
1705  
1706 =head2 abuse_report_text()
1707  
1708 Produces a compact, plain-text string suitable for sending as the body of
1709 an abuse report email. It summarises risk level, red flags, originating IP,
1710 abuse contacts, and original message headers. The message body is omitted
1711 to keep the report concise.
1712  
1713 Use C<abuse_contacts()> to get the recipient addresses and this method for
1714 the body text.
1715  
1716 =head3 Usage
1717  
1718 my $text = $analyser->abuse_report_text();
1719 my @contacts = $analyser->abuse_contacts();
1720 for my $c (@contacts) {
1721 send_email(to => $c->{address}, body => $text);
1722 }
1723  
1724 =head3 Arguments
1725  
1726 None. C<parse_email()> must have been called first.
1727  
1728 =head3 Returns
1729  
1730 A plain scalar string, newline-terminated, Unix line endings. Never empty
1731 or undef.
1732  
1733 =head3 Side Effects
1734  
1735 Calls C<risk_assessment()>, C<originating_ip()>, and C<abuse_contacts()>
1736 if not already cached.
1737  
1738 =head3 Notes
1739  
1740 Output text is sanitised: control characters that could affect terminal or
1741 HTML rendering are stripped from all user-derived content before inclusion.
1742  
1743 =head3 API Specification
1744  
1745 =head4 Input
1746  
1747 []
1748  
1749 =head4 Output
1750  
1751 { type => 'string' }
1752  
1753 =cut
1754  
1755 sub abuse_report_text {
1756 27 ▶ my $self = $_[0];
Subroutine abuse_report_text: called CC=20 SCAR=32.1
Subroutine abuse_report_text: called CC=20 SCAR=32.1
Pod documented
1757 27 my @out;
1758  
1759 27 push @out, 'This is an automated abuse report generated by Email::Abuse::Investigator.',
1760 'Please investigate the following spam/phishing message.',
1761 '';
1762  
1763 27 my $risk = $self->risk_assessment();
1764 27 push @out, "RISK LEVEL: $risk->{level} (score: $risk->{score})",
1765 '';
1766  
1767 # List each red flag with its severity prefix
1768 27 ▶ if (@{ $risk->{flags} }) {
Branch: 2 branches
BranchTrueFalseTotal
if (@{$risk->{"flags"};}) 12 12 24
if (@{$risk->{"flags"};}) 0 1 1
1769 15 push @out, 'RED FLAGS IDENTIFIED:';
1770 15 for my $f (@{ $risk->{flags} }) {
1771 24 push @out, " [$f->{severity}] " . _sanitise_output($f->{detail});
1772 }
1773 15 push @out, '';
1774 }
1775  
1776 # Originating IP summary block
1777 27 my $orig = $self->originating_ip();
1778 27 ▶ if ($orig) {
Branch: 2 branches
BranchTrueFalseTotal
if ($orig) 17 7 24
if ($orig) 1 0 1
1779 push @out, 'ORIGINATING IP: ' . _sanitise_output("$orig->{ip} ($orig->{rdns})"),
1780 20 'NETWORK OWNER: ' . _sanitise_output($orig->{org}),
1781 '';
1782 }
1783  
1784 # List every reported URL so the receiving abuse desk knows exactly
1785 # which resources to investigate or suspend.
1786 27 my @urls = $self->embedded_urls();
1787 27 ▶ if (@urls) {
Branch: 2 branches
BranchTrueFalseTotal
if (@urls) 7 17 24
if (@urls) 0 1 1
1788 10 push @out, 'REPORTED URLs:';
1789 10 for my $u (@urls) {
1790 10 push @out, ' ' . _sanitise_output($u->{url});
1791 10 my @meta;
1792 10 ▶ push @meta, "host: $u->{host}" if $u->{host};
Branch: 2 branches
BranchTrueFalseTotal
if $u->{"host"} 7 0 7
if $u->{"host"} 1 0 1
1793 10 ▶ push @meta, "IP: $u->{ip}" if $u->{ip} && $u->{ip} ne '(unresolved)';
Branch: 2 branches
BranchTrueFalseTotal
if $u->{"ip"} and $u->{"ip"} ne "(unresolved)" 5 2 7
if $u->{"ip"} and $u->{"ip"} ne "(unresolved)" 1 0 1
Condition33%2/6
$u->{"ip"} and $u->{"ip"} ne "(unresolved)"
!ll&&!rl&&r
025
$u->{"ip"} and $u->{"ip"} ne "(unresolved)"
!ll&&!rl&&r
000
MC/DC50%1/2
$u->{"ip"} and $u->{"ip"} ne "(unresolved)"
$u->{"ip"} $u->{"ip"} ne "(unresolved)"
MC/DC0%0/2
$u->{"ip"} and $u->{"ip"} ne "(unresolved)"
$u->{"ip"} $u->{"ip"} ne "(unresolved)"
Truth table66%2/3
A and B
A= $u->{"ip"}B= $u->{"ip"} ne "(unresolved)"
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $u->{"ip"}B= $u->{"ip"} ne "(unresolved)"
ABresult
0X0
100
111
1794 10 ▶ push @meta, "org: $u->{org}" if $u->{org} && $u->{org} ne '(unknown)';
Branch: 2 branches
BranchTrueFalseTotal
if $u->{"org"} and $u->{"org"} ne "(unknown)" 5 2 7
if $u->{"org"} and $u->{"org"} ne "(unknown)" 1 0 1
Condition33%2/6
$u->{"org"} and $u->{"org"} ne "(unknown)"
!ll&&!rl&&r
025
$u->{"org"} and $u->{"org"} ne "(unknown)"
!ll&&!rl&&r
000
MC/DC50%1/2
$u->{"org"} and $u->{"org"} ne "(unknown)"
$u->{"org"} $u->{"org"} ne "(unknown)"
MC/DC0%0/2
$u->{"org"} and $u->{"org"} ne "(unknown)"
$u->{"org"} $u->{"org"} ne "(unknown)"
Truth table66%2/3
A and B
A= $u->{"org"}B= $u->{"org"} ne "(unknown)"
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $u->{"org"}B= $u->{"org"} ne "(unknown)"
ABresult
0X0
100
111
1795 10 ▶ push @out, ' (' . join(' ', @meta) . ')' if @meta;
Branch: 2 branches
BranchTrueFalseTotal
if @meta 7 0 7
if @meta 1 0 1
1796 }
1797 10 push @out, '';
1798 }
1799  
1800 # Email abuse contacts
1801 27 my @contacts = $self->abuse_contacts();
1802 27 ▶ if (@contacts) {
Branch: 2 branches
BranchTrueFalseTotal
if (@contacts) 19 5 24
if (@contacts) 0 1 1
1803 22 push @out, 'ABUSE CONTACTS:';
1804 22 push @out, ' ' . _sanitise_output("$_->{address} ($_->{role})") for @contacts;
1805 22 push @out, '';
1806 }
1807  
1808 # Web-form contacts (providers that reject email)
1809 27 ▶ if(my @form_cs = $self->form_contacts()) {
Branch: 2 branches
BranchTrueFalseTotal
if (my(@form_cs) = $self->form_contacts) 2 22 24
if (my(@form_cs) = $self->form_contacts) 0 1 1
1810 5 push @out, 'WEB-FORM REPORTS REQUIRED:',
1811 ' The following parties do not accept email -- submit manually:';
1812 5 for my $c (@form_cs) {
1813 push @out, " [$c->{role}]",
1814 5 ' Form : ' . _sanitise_output($c->{form});
1815 5 ▶ push @out, ' Domain : ' . _sanitise_output($c->{form_domain}) if $c->{form_domain};
Branch: 2 branches
BranchTrueFalseTotal
if $c->{"form_domain"} 1 1 2
if $c->{"form_domain"} 0 1 1
1816 5 ▶ push @out, ' Paste : ' . _sanitise_output($c->{form_paste}) if $c->{form_paste};
Branch: 2 branches
BranchTrueFalseTotal
if $c->{"form_paste"} 2 0 2
if $c->{"form_paste"} 0 1 1
1817 5 ▶ push @out, ' Upload : ' . _sanitise_output($c->{form_upload}) if $c->{form_upload};
Branch: 2 branches
BranchTrueFalseTotal
if $c->{"form_upload"} 2 0 2
if $c->{"form_upload"} 0 1 1
1818 }
1819 5 push @out, '';
1820 }
1821  
1822 # Separator and raw headers (body excluded for brevity)
1823 27 push @out, '-' x 72,
1824 'ORIGINAL MESSAGE HEADERS:',
1825 '-' x 72;
1826  
1827 27 for my $h (@{ $self->{_headers} }) {
1828 179 push @out, _sanitise_output("$h->{name}: $h->{value}");
1829 }
1830 27 push @out, '';
1831  
1832 27 return join("\n", @out);
1833 }
1834  
1835 # -----------------------------------------------------------------------
1836 # Public: abuse contacts
1837 # -----------------------------------------------------------------------
1838  
1839 =head2 abuse_contacts()
1840  
1841 Collates the complete set of parties that should receive an abuse report:
1842 the sending ISP, URL host operators, contact domain web/mail/DNS/registrar
1843 contacts, account providers identified from key headers, the DKIM signer,
1844 and the ESP identified via List-Unsubscribe.
1845  
1846 Addresses are deduplicated globally; if the same address is found via
1847 multiple routes, a single entry is kept and role strings are merged.
1848  
1849 =head3 Usage
1850  
1851 my @contacts = $analyser->abuse_contacts();
1852 my @addrs = map { $_->{address} } @contacts;
1853  
1854 =head3 Arguments
1855  
1856 None. C<parse_email()> must have been called first.
1857  
1858 =head3 Returns
1859  
1860 A list of hashrefs, one per unique abuse address, in discovery order.
1861 Each hashref has keys C<role>, C<roles> (arrayref), C<address>, C<note>,
1862 C<via>. Returns an empty list if no contacts can be determined.
1863  
1864 =head3 Side Effects
1865  
1866 Triggers C<originating_ip()>, C<embedded_urls()>, and C<mailto_domains()>
1867 if not already cached.
1868  
1869 =head3 Notes
1870  
1871 The result is cached on the object; subsequent calls return the same list
1872 without repeating the contact-collection logic. The underlying per-IP and
1873 per-domain lookups are themselves cached by C<originating_ip()>,
1874 C<embedded_urls()>, and C<mailto_domains()>.
1875  
1876 =head3 API Specification
1877  
1878 =head4 Input
1879  
1880 []
1881  
1882 =head4 Output
1883  
1884 (
1885 {
1886 type => 'hashref',
1887 keys => {
1888 role => { type => 'string' },
1889 roles => { type => 'arrayref' },
1890 address => { type => 'string', regex => qr/\@/ },
1891 note => { type => 'string' },
1892 via => { type => 'string', memberof => [ 'provider-table', 'ip-whois', 'domain-whois' ] }
1893 },
1894 },
1895 ...
1896 )
1897  
1898 =cut
1899  
1900 sub abuse_contacts {
1901 184 ▶ my $self = $_[0];
Subroutine abuse_contacts: called CC=2 SCAR=7.6
Subroutine abuse_contacts: called CC=2 SCAR=7.6
Pod documented
1902 184 ▶ $self->{_contacts} //= [ $self->_compute_abuse_contacts() ];
Condition40%2/5
$self->{"_contacts"} //= [$self->_compute_abuse_contacts]
l!l
221590
$self->{"_contacts"} //= [$self->_compute_abuse_contacts]
l!l
00
MC/DC100%1/1
$self->{"_contacts"} //= [$self->_compute_abuse_contacts]
$self->{"_contacts"}
MC/DC0%0/1
$self->{"_contacts"} //= [$self->_compute_abuse_contacts]
$self->{"_contacts"}
Truth table100%2/2
A
A= $self->{"_contacts"}
Aresult
11
00
Truth table0%0/2
A
A= $self->{"_contacts"}
Aresult
11
00
1903 184 return @{ $self->{_contacts} };
1904 }
1905  
1906 # _compute_abuse_contacts() -> list of contact hashrefs
1907 #
1908 # Purpose:
1909 # Actual implementation of abuse_contacts(). Separated so the public
1910 # method can cache without duplicating logic.
1911 #
1912 # Entry criteria:
1913 # parse_email() must have been called.
1914 #
1915 # Exit status:
1916 # Returns list of deduplicated contact hashrefs.
1917  
1918 sub _compute_abuse_contacts :Private {
1919 194 ▶ my $self = $_[0];
Subroutine _compute_abuse_contacts: called CC=51 SCAR=47.2
Subroutine _compute_abuse_contacts: called CC=51 SCAR=47.2
1920  
1921 194 my (@contacts, %seen_idx);
1922  
1923 # Inner closure: add one contact entry, merging roles for duplicate addresses
1924 my $add = sub {
1925 337 ▶ my (%args) = @_;
Subroutine __ANON__: called CC=19 SCAR=29.4
1926 337 ▶ my $addr = lc($args{address} // '');
Condition100%3/3
$args{"address"} // ""
l!l
306820
MC/DC100%1/1
$args{"address"} // ""
$args{"address"}
Truth table100%2/2
A
A= $args{"address"}
Aresult
11
00
1927 337 ▶ return unless $addr && $addr =~ /\@/;
Branch: 1 branch
BranchTrueFalseTotal
unless $addr and $addr =~ /\@/ 30 304 334
Condition100%3/3
$addr and $addr =~ /\@/
!ll&&!rl&&r
54316
MC/DC100%2/2
$addr and $addr =~ /\@/
$addr $addr =~ /\@/
Truth table100%3/3
A and B
A= $addrB= $addr =~ /\@/
ABresult
0X0
100
111
1928  
1929 # Suppress addresses belonging to form-only providers (no email accepted)
1930 330 ▶ if ($addr =~ /\@([\w.-]+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($addr =~ /\@([\w.-]+)$/) 307 20 327
1931 330 my $dom = $1;
1932 330 my $pa = $self->_provider_abuse_for_host($dom);
1933 330 ▶ return if $pa && $pa->{form} && !$pa->{email};
Branch: 1 branch
BranchTrueFalseTotal
if $pa and $pa->{"form"} and not $pa->{"email"} 27 300 327
Condition83%5/6
$pa and $pa->{"form"} and not $pa->{"email"}
!ll&&!rl&&r
30607
$pa and $pa->{"form"}
!ll&&!rl&&r
2061007
MC/DC66%2/3
$pa and $pa->{"form"} and not $pa->{"email"}
$pa $pa->{"form"} not $pa->{"email"}
Truth table75%3/4
A and B and not(C)
A= $paB= $pa->{"form"}C= not $pa->{"email"}
ABCresult
0XX0
10X0
1100
1111
1934 }
1935  
1936 303 ▶ if (exists $seen_idx{$addr}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $seen_idx{$addr}) 139 174 313
1937 # Merge the new role into the existing entry
1938 163 my $entry = $contacts[ $seen_idx{$addr} ];
1939 160 push @{ $entry->{roles} }, $args{role};
1940  
1941 # Collapse repeated role labels to avoid unreadable strings
1942 163 my (%role_counts, @ordered_roles);
1943 156 for my $r (@{ $entry->{roles} }) {
1944 1220 ▶ push @ordered_roles, $r unless $role_counts{$r}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $role_counts{$r}++ 1186 31 1217
1945 }
1946 my @display = map {
1947 154 ▶ $role_counts{$_} > 1 ? "$_ (x$role_counts{$_})" : $_
Branch: 1 branch
BranchTrueFalseTotal
$role_counts{$_} > 1 ? : 17 1183 1200
1948 } @ordered_roles;
1949 154 my $joined = join(' and ', @display);
1950  
1951 # Summarise if the merged string is too long to read.
1952 # "URL host: hostname" entries are grouped by listing the actual
1953 # hostnames so the summary is actionable (e.g. "URL host: a.example,
1954 # b.example" rather than the unhelpful "URL host, URL host").
1955 # All other role types fall back to stripping at the first [:(\d]
1956 # boundary to produce a compact type label.
1957 154 ▶ if (length($joined) > $ROLE_MAX_LEN) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $joined > $ROLE_MAX_LEN) 79 72 151
1958 82 my (@url_hosts, %seen_short, @short);
1959 93 for my $r (@display) {
1960 1078 ▶ if ($r =~ /^URL host:\s*(.+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($r =~ /^URL host:\s*(.+)$/) { } 40 1037 1077
1961 54 push @url_hosts, $1;
1962 } else {
1963 1078 (my $s = $r) =~ s/[:(\d].*//;
1964 1078 $s =~ s/\s+$//;
1965 1047 ▶ push @short, $s unless $seen_short{$s}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen_short{$s}++ 288 787 1075
1966 }
1967 }
1968 88 my @parts;
1969 79 ▶ if (@url_hosts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@url_hosts) 14 71 85
1970 26 ▶ my $extra = @url_hosts > 3
Branch: 1 branch
BranchTrueFalseTotal
@url_hosts > 3 ? : 5 49 54
1971 ? ' and ' . (@url_hosts - 3) . ' more' : '';
1972 57 ▶ my @shown = @url_hosts > 3 ? @url_hosts[0..2] : @url_hosts;
Branch: 1 branch
BranchTrueFalseTotal
@url_hosts > 3 ? : 5 49 54
1973 19 push @parts, 'URL host: ' . join(', ', @shown) . $extra;
1974 }
1975 119 push @parts, @short;
1976 81 $joined = scalar(@display) . ' routes: ' . join(', ', @parts);
1977 }
1978 180 $entry->{role} = $joined;
1979 145 return;
1980 }
1981  
1982 # First time seeing this address -- record and store
1983 164 $seen_idx{$addr} = scalar @contacts;
1984 168 $args{roles} = [ $args{role} ];
1985 166 push @contacts, \%args;
1986 194 };
1987  
1988 # Route 1 -- Sending ISP (originating IP)
1989 194 my $orig = $self->originating_ip();
1990 163 ▶ if ($orig) {
Branch: 2 branches
BranchTrueFalseTotal
if ($orig) 70 88 158
if ($orig) 0 1 1
1991 75 my $pa = $self->_provider_abuse_for_ip($orig->{ip}, $orig->{rdns});
1992 75 ▶ if ($pa) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pa) 11 59 70
if ($pa) 0 0 0
1993 $add->(
1994 role => 'Sending ISP',
1995 address => $pa->{email},
1996 16 note => "$orig->{ip} ($orig->{rdns}) -- $pa->{note}",
1997 via => 'provider-table',
1998 );
1999 }
2000 73 ▶ if ($orig->{abuse} && $orig->{abuse} ne '(unknown)') {
Branch: 2 branches
BranchTrueFalseTotal
if ($orig->{"abuse"} and $orig->{"abuse"} ne "(unknown)") 45 25 70
if ($orig->{"abuse"} and $orig->{"abuse"} ne "(unknown)") 0 0 0
Condition83%5/6
$orig->{"abuse"} and $orig->{"abuse"} ne "(unknown)"
!ll&&!rl&&r
104845
$orig->{"abuse"} and $orig->{"abuse"} ne "(unknown)"
!ll&&!rl&&r
101
MC/DC50%1/2
$orig->{"abuse"} and $orig->{"abuse"} ne "(unknown)"
$orig->{"abuse"} $orig->{"abuse"} ne "(unknown)"
MC/DC50%1/2
$orig->{"abuse"} and $orig->{"abuse"} ne "(unknown)"
$orig->{"abuse"} $orig->{"abuse"} ne "(unknown)"
Truth table66%2/3
A and B
A= $orig->{"abuse"}B= $orig->{"abuse"} ne "(unknown)"
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= $orig->{"abuse"}B= $orig->{"abuse"} ne "(unknown)"
ABresult
0X0
100
111
2001 $add->(
2002 role => 'Sending ISP',
2003 address => $orig->{abuse},
2004 48 note => "Network owner of originating IP $orig->{ip} ($orig->{org})",
2005 via => 'ip-whois',
2006 );
2007 }
2008 }
2009  
2010 # Route 2 -- URL hosts
2011 161 my %url_host_seen;
2012 161 for my $u ($self->embedded_urls()) {
2013 78 ▶ next if $url_host_seen{ $u->{host} }++;
Branch: 2 branches
BranchTrueFalseTotal
if $url_host_seen{$u->{"host"}}++ 10 66 76
if $url_host_seen{$u->{"host"}}++ 0 1 1
2014 71 my $bare_host = lc $u->{host};
2015 71 $bare_host =~ s/^www\.//;
2016 # Skip trusted infrastructure (Google, W3C, etc.)
2017 71 ▶ next if $self->{trusted_domains}->{$bare_host};
Branch: 2 branches
BranchTrueFalseTotal
if $self->{"trusted_domains"}{$bare_host} 0 66 66
if $self->{"trusted_domains"}{$bare_host} 0 0 0
2018 70 ▶ next if $TRUSTED_DOMAINS{$bare_host};
Branch: 2 branches
BranchTrueFalseTotal
if $TRUSTED_DOMAINS{$bare_host} 3 63 66
if $TRUSTED_DOMAINS{$bare_host} 0 0 0
2019 67 my $pa = $self->_provider_abuse_for_host($u->{host});
2020 67 ▶ if ($pa) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pa) 16 47 63
if ($pa) 0 0 0
2021 $add->(
2022 role => "URL host: $u->{host}",
2023 address => $pa->{email},
2024 20 note => "$u->{host} -- $pa->{note}",
2025 via => 'provider-table',
2026 );
2027 }
2028 67 ▶ if ($u->{abuse} && $u->{abuse} ne '(unknown)') {
Branch: 2 branches
BranchTrueFalseTotal
if ($u->{"abuse"} and $u->{"abuse"} ne "(unknown)") 35 28 63
if ($u->{"abuse"} and $u->{"abuse"} ne "(unknown)") 0 1 1
Condition50%3/6
$u->{"abuse"} and $u->{"abuse"} ne "(unknown)"
!ll&&!rl&&r
03035
$u->{"abuse"} and $u->{"abuse"} ne "(unknown)"
!ll&&!rl&&r
100
MC/DC50%1/2
$u->{"abuse"} and $u->{"abuse"} ne "(unknown)"
$u->{"abuse"} $u->{"abuse"} ne "(unknown)"
MC/DC0%0/2
$u->{"abuse"} and $u->{"abuse"} ne "(unknown)"
$u->{"abuse"} $u->{"abuse"} ne "(unknown)"
Truth table66%2/3
A and B
A= $u->{"abuse"}B= $u->{"abuse"} ne "(unknown)"
ABresult
0X0
100
111
Truth table33%1/3
A and B
A= $u->{"abuse"}B= $u->{"abuse"} ne "(unknown)"
ABresult
0X0
100
111
2029 $add->(
2030 role => "URL host: $u->{host}",
2031 address => $u->{abuse},
2032 38 note => "Hosting $u->{host} ($u->{ip}, $u->{org})",
2033 via => 'ip-whois',
2034 );
2035 }
2036 }
2037  
2038 # Route 3 -- Contact domain hosting and registration
2039 162 for my $d ($self->mailto_domains()) {
2040 149 my $dom = $d->{domain};
2041  
2042 # Web host contact
2043 148 ▶ if ($d->{web_abuse}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($d->{"web_abuse"}) 47 98 145
if ($d->{"web_abuse"}) 0 0 0
2044 51 my $pa = $self->_provider_abuse_for_host($dom);
2045 51 ▶ if ($pa) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pa) 0 47 47
if ($pa) 0 0 0
2046 $add->(role => "Web host of $dom", address => $pa->{email},
2047 4 note => $pa->{note}, via => 'provider-table');
2048 }
2049 $add->(
2050 role => "Web host of $dom",
2051 address => $d->{web_abuse},
2052 note => sprintf('Hosting %s (%s, %s)',
2053 $dom // '(unknown domain)',
2054 $d->{web_ip} // '(unknown IP)',
2055 50 ▶ $d->{web_org} // '(unknown org)'),
Condition38%5/13
$dom // "(unknown domain)"
l!l
4700
$d->{"web_ip"} // "(unknown IP)"
l!l
3712
$d->{"web_org"} // "(unknown org)"
l!l
3612
$dom // "(unknown domain)"
l!l
00
$d->{"web_ip"} // "(unknown IP)"
l!l
00
$d->{"web_org"} // "(unknown org)"
l!l
00
MC/DC0%0/1
$dom // "(unknown domain)"
$dom
MC/DC100%1/1
$d->{"web_ip"} // "(unknown IP)"
$d->{"web_ip"}
MC/DC100%1/1
$d->{"web_org"} // "(unknown org)"
$d->{"web_org"}
MC/DC0%0/1
$dom // "(unknown domain)"
$dom
MC/DC0%0/1
$d->{"web_ip"} // "(unknown IP)"
$d->{"web_ip"}
MC/DC0%0/1
$d->{"web_org"} // "(unknown org)"
$d->{"web_org"}
Truth table50%1/2
A
A= $dom
Aresult
11
00
Truth table100%2/2
A
A= $d->{"web_ip"}
Aresult
11
00
Truth table100%2/2
A
A= $d->{"web_org"}
Aresult
11
00
Truth table0%0/2
A
A= $dom
Aresult
11
00
Truth table0%0/2
A
A= $d->{"web_ip"}
Aresult
11
00
Truth table0%0/2
A
A= $d->{"web_org"}
Aresult
11
00
2056 via => 'ip-whois',
2057 );
2058 }
2059  
2060 # MX (mail host) contact
2061 148 ▶ if ($d->{mx_abuse}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($d->{"mx_abuse"}) 22 123 145
if ($d->{"mx_abuse"}) 0 0 0
2062 $add->(
2063 role => "Mail host (MX) for $dom",
2064 address => $d->{mx_abuse},
2065 note => sprintf('MX %s (%s, %s)',
2066 $d->{mx_host} // '(unknown host)',
2067 $d->{mx_ip} // '(unknown IP)',
2068 22 ▶ $d->{mx_org} // '(unknown org)'),
Condition69%9/13
$d->{"mx_host"} // "(unknown host)"
l!l
518
$d->{"mx_ip"} // "(unknown IP)"
l!l
518
$d->{"mx_org"} // "(unknown org)"
l!l
517
$d->{"mx_host"} // "(unknown host)"
l!l
22
$d->{"mx_ip"} // "(unknown IP)"
l!l
200
$d->{"mx_org"} // "(unknown org)"
l!l
00
MC/DC100%1/1
$d->{"mx_host"} // "(unknown host)"
$d->{"mx_host"}
MC/DC100%1/1
$d->{"mx_ip"} // "(unknown IP)"
$d->{"mx_ip"}
MC/DC100%1/1
$d->{"mx_org"} // "(unknown org)"
$d->{"mx_org"}
MC/DC100%1/1
$d->{"mx_host"} // "(unknown host)"
$d->{"mx_host"}
MC/DC0%0/1
$d->{"mx_ip"} // "(unknown IP)"
$d->{"mx_ip"}
MC/DC0%0/1
$d->{"mx_org"} // "(unknown org)"
$d->{"mx_org"}
Truth table100%2/2
A
A= $d->{"mx_host"}
Aresult
11
00
Truth table100%2/2
A
A= $d->{"mx_ip"}
Aresult
11
00
Truth table100%2/2
A
A= $d->{"mx_org"}
Aresult
11
00
Truth table100%2/2
A
A= $d->{"mx_host"}
Aresult
11
00
Truth table50%1/2
A
A= $d->{"mx_ip"}
Aresult
11
00
Truth table0%0/2
A
A= $d->{"mx_org"}
Aresult
11
00
2069 via => 'ip-whois',
2070 );
2071 }
2072  
2073 # NS (DNS host) contact
2074 148 ▶ if ($d->{ns_abuse}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($d->{"ns_abuse"}) 13 132 145
if ($d->{"ns_abuse"}) 1 0 1
2075 $add->(
2076 role => "DNS host (NS) for $dom",
2077 address => $d->{ns_abuse},
2078 note => sprintf('NS %s (%s, %s)',
2079 $d->{ns_host} // '(unknown host)',
2080 $d->{ns_ip} // '(unknown IP)',
2081 16 ▶ $d->{ns_org} // '(unknown org)'),
Condition46%6/13
$d->{"ns_host"} // "(unknown host)"
l!l
310
$d->{"ns_ip"} // "(unknown IP)"
l!l
310
$d->{"ns_org"} // "(unknown org)"
l!l
310
$d->{"ns_host"} // "(unknown host)"
l!l
00
$d->{"ns_ip"} // "(unknown IP)"
l!l
00
$d->{"ns_org"} // "(unknown org)"
l!l
000
MC/DC100%1/1
$d->{"ns_host"} // "(unknown host)"
$d->{"ns_host"}
MC/DC100%1/1
$d->{"ns_ip"} // "(unknown IP)"
$d->{"ns_ip"}
MC/DC100%1/1
$d->{"ns_org"} // "(unknown org)"
$d->{"ns_org"}
MC/DC0%0/1
$d->{"ns_host"} // "(unknown host)"
$d->{"ns_host"}
MC/DC0%0/1
$d->{"ns_ip"} // "(unknown IP)"
$d->{"ns_ip"}
MC/DC0%0/1
$d->{"ns_org"} // "(unknown org)"
$d->{"ns_org"}
Truth table100%2/2
A
A= $d->{"ns_host"}
Aresult
11
00
Truth table100%2/2
A
A= $d->{"ns_ip"}
Aresult
11
00
Truth table100%2/2
A
A= $d->{"ns_org"}
Aresult
11
00
Truth table0%0/2
A
A= $d->{"ns_host"}
Aresult
11
00
Truth table0%0/2
A
A= $d->{"ns_ip"}
Aresult
11
00
Truth table0%0/2
A
A= $d->{"ns_org"}
Aresult
11
00
2082 via => 'ip-whois',
2083 );
2084 }
2085  
2086 # Domain registrar (skip if domain only seen in spoofable headers)
2087 145 ▶ if ($d->{registrar_abuse}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($d->{"registrar_abuse"}) 28 117 145
if ($d->{"registrar_abuse"}) 1 0 1
2088 my $spoofable_only =
2089 $d->{source} =~ /^(?:From:|Return-Path:|Sender:) header$/ &&
2090 !scalar(grep {
2091 31 ▶ $_->{host} &&
Condition50%3/6
$d->{'source'} =~ /^(?:From:|Return-Path:|Sender:) header$/ && !scalar(grep {$_->{'host'} and _registrable($_->{'host'}) eq (_registrable($dom) // $dom);} $self->embedded_urls)
!ll&&!rl&&r
2224
$d->{'source'} =~ /^(?:From:|Return-Path:|Sender:) header$/ && !scalar(grep {$_->{'host'} and _registrable($_->{'host'}) eq (_registrable($dom) // $dom);} $self->embedded_urls)
!ll&&!rl&&r
000
MC/DC100%2/2
$d->{'source'} =~ /^(?:From:|Return-Path:|Sender:) header$/ && !scalar(grep {$_->{'host'} and _registrable($_->{'host'}) eq (_registrable($dom) // $dom);} $self->embedded_urls)
$d->{'source'} =~ /^(?:From:|Return-Path:|Sender:) header$/ !scalar(grep {$_->{'host'} and _registrable($_->{'host'}) eq (_registrable($dom) // $dom);} $self->embedded_urls)
MC/DC0%0/2
$d->{'source'} =~ /^(?:From:|Return-Path:|Sender:) header$/ && !scalar(grep {$_->{'host'} and _registrable($_->{'host'}) eq (_registrable($dom) // $dom);} $self->embedded_urls)
$d->{'source'} =~ /^(?:From:|Return-Path:|Sender:) header$/ !scalar(grep {$_->{'host'} and _registrable($_->{'host'}) eq (_registrable($dom) // $dom);} $self->embedded_urls)
Truth table100%3/3
A && not(B)
A= $d->{'source'} =~ /^(?:From:|Return-Path:|Sender:) header$/B= !scalar(grep {$_->{'host'} and _registrable($_->{'host'}) eq (_registrable($dom) // $dom);} $self->embedded_urls)
ABresult
0X0
100
111
Truth table0%0/3
A && not(B)
A= $d->{'source'} =~ /^(?:From:|Return-Path:|Sender:) header$/B= !scalar(grep {$_->{'host'} and _registrable($_->{'host'}) eq (_registrable($dom) // $dom);} $self->embedded_urls)
ABresult
0X0
100
111
2092 6 ▶ _registrable($_->{host}) eq (_registrable($dom) // $dom)
Branch: 2 branches
BranchTrueFalseTotal
$_->{"host"} and _registrable($_->{"host"}) eq (_registrable($dom) // $dom) 3 0 3
$_->{"host"} and _registrable($_->{"host"}) eq (_registrable($dom) // $dom) 0 1 1
Condition16%1/6
_registrable($dom) // $dom
l!l&&r!l&&!r
300
_registrable($dom) // $dom
l!l&&r!l&&!r
000
MC/DC0%0/2
_registrable($dom) // $dom
_registrable($dom) $dom
MC/DC0%0/2
_registrable($dom) // $dom
_registrable($dom) $dom
Truth table33%1/3
A // B
A= _registrable($dom)B= $dom
ABresult
1X1
011
000
Truth table0%0/3
A // B
A= _registrable($dom)B= $dom
ABresult
1X1
011
000
2093 } $self->embedded_urls());
2094 31 ▶ unless ($spoofable_only) {
Branch: 2 branches
BranchTrueFalseTotal
unless ($spoofable_only) 24 4 28
unless ($spoofable_only) 0 0 0
2095 $add->(
2096 role => "Domain registrar for $dom",
2097 address => $d->{registrar_abuse},
2098 27 ▶ note => 'Registrar: ' . ($d->{registrar} // '(unknown)'),
Condition50%2/4
$d->{"registrar"} // "(unknown)"
l!l
816
$d->{"registrar"} // "(unknown)"
l!l
00
MC/DC100%1/1
$d->{"registrar"} // "(unknown)"
$d->{"registrar"}
MC/DC0%0/1
$d->{"registrar"} // "(unknown)"
$d->{"registrar"}
Truth table100%2/2
A
A= $d->{"registrar"}
Aresult
11
00
Truth table0%0/2
A
A= $d->{"registrar"}
Aresult
11
00
2099 via => 'domain-whois',
2100 );
2101 }
2102 }
2103 }
2104  
2105 # Route 4 -- From:/Reply-To:/Return-Path:/Sender: account provider
2106 161 for my $hname (qw(from reply-to return-path sender)) {
2107 635 ▶ my $val = $self->_header_value($hname) // next;
Condition40%2/5
$self->_header_value($hname) // (next)
l!l
269363
$self->_header_value($hname) // (next)
l!l
000
MC/DC100%1/1
$self->_header_value($hname) // (next)
$self->_header_value($hname)
MC/DC0%0/1
$self->_header_value($hname) // (next)
$self->_header_value($hname)
Truth table100%2/2
A
A= $self->_header_value($hname)
Aresult
11
00
Truth table0%0/2
A
A= $self->_header_value($hname)
Aresult
11
00
2108  
2109 # Extract addr-spec from angle-bracket form to avoid display-name @-signs
2110 272 ▶ my $addr_spec = ($val =~ /<([^>]*)>\s*$/) ? $1 : $val;
Branch: 2 branches
BranchTrueFalseTotal
$val =~ /<([^>]*)>\s*$/ ? : 217 52 269
$val =~ /<([^>]*)>\s*$/ ? : 0 0 0
2111 272 my ($addr_domain) = $addr_spec =~ /\@([\w.-]+)/;
2112 272 ▶ next unless $addr_domain;
Branch: 2 branches
BranchTrueFalseTotal
unless $addr_domain 1 268 269
unless $addr_domain 0 0 0
2113  
2114 # Skip SRS-rewritten forwarder addresses (not the real sender)
2115 271 ▶ next if $addr_spec =~ /\+SRS[0-9]?=/i;
Branch: 2 branches
BranchTrueFalseTotal
if $addr_spec =~ /\+SRS[0-9]?=/i 2 266 268
if $addr_spec =~ /\+SRS[0-9]?=/i 0 0 0
2116  
2117 269 my $pa = $self->_provider_abuse_for_host($addr_domain);
2118 269 ▶ if ($pa) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pa) 36 230 266
if ($pa) 0 0 0
2119 39 ▶ my $role_addr = $addr_spec =~ /\@/ ? $addr_spec : $val;
Branch: 2 branches
BranchTrueFalseTotal
$addr_spec =~ /\@/ ? : 36 0 36
$addr_spec =~ /\@/ ? : 0 0 0
2120 39 $role_addr =~ s/^\s+|\s+$//g;
2121 $add->(
2122 role => "Account provider ($hname: $role_addr)",
2123 address => $pa->{email},
2124 note => $pa->{note},
2125 39 via => 'provider-table',
2126 );
2127 }
2128 }
2129  
2130 # Route 5 -- DKIM signing organisation
2131 161 my $auth = $self->_parse_auth_results_cached();
2132 161 ▶ if ($auth->{dkim_domain}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($auth->{"dkim_domain"}) 2 156 158
if ($auth->{"dkim_domain"}) 0 0 0
2133 5 my $pa = $self->_provider_abuse_for_host($auth->{dkim_domain});
2134 5 ▶ if ($pa) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pa) 1 1 2
if ($pa) 0 0 0
2135 $add->(
2136 role => "DKIM signer: $auth->{dkim_domain}",
2137 address => $pa->{email},
2138 note => $pa->{note},
2139 4 via => 'provider-table',
2140 );
2141 }
2142 }
2143  
2144 # Route 6 -- List-Unsubscribe ESP domain
2145 161 my $unsub = $self->_header_value('list-unsubscribe');
2146 161 ▶ if ($unsub) {
Branch: 2 branches
BranchTrueFalseTotal
if ($unsub) 0 158 158
if ($unsub) 2 10 12
2147 3 my @unsub_domains;
2148 3 ▶ while ($unsub =~ m{https?://([^/:?\s>]+)}gi) {
Branch: 2 branches
BranchTrueFalseTotal
if ($unsub =~ m[https?://([^/:?\s>]+)]gi) 0 0 0
if ($unsub =~ m[https?://([^/:?\s>]+)]gi) 0 10 10
2149 3 push @unsub_domains, lc $1;
2150 }
2151 3 ▶ while ($unsub =~ m{mailto:[^@\s>]+\@([\w.-]+)}gi) {
Branch: 2 branches
BranchTrueFalseTotal
if ($unsub =~ /mailto:[^\@\s>]+\@([\w.-]+)/gi) 0 0 0
if ($unsub =~ /mailto:[^\@\s>]+\@([\w.-]+)/gi) 0 2 2
2152 3 push @unsub_domains, lc $1;
2153 }
2154 3 my %unsub_seen;
2155 3 for my $dom (grep { !$unsub_seen{$_}++ } @unsub_domains) {
2156 3 my $pa = $self->_provider_abuse_for_host($dom);
2157 3 ▶ if ($pa) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pa) 0 0 0
if ($pa) 2 0 2
2158 $add->(
2159 role => "ESP / bulk sender (List-Unsubscribe: $dom)",
2160 address => $pa->{email},
2161 3 note => "$pa->{note} -- responsible for this bulk delivery",
2162 via => 'provider-table',
2163 );
2164 }
2165 }
2166 }
2167  
2168 # Route 7 -- Reply addresses embedded in the message body
2169 161 my %body_addr_seen;
2170 161 my $combined_body = $self->{_body_plain} . "\n" . $self->{_body_html};
2171 161 for my $addr_dom ($self->_domains_from_text($combined_body)) {
2172 19 ▶ next if $body_addr_seen{$addr_dom}++;
Branch: 2 branches
BranchTrueFalseTotal
if $body_addr_seen{$addr_dom}++ 0 16 16
if $body_addr_seen{$addr_dom}++ 2 0 2
2173 19 my $pa = $self->_provider_abuse_for_host($addr_dom);
2174 19 ▶ next unless $pa && $pa->{email};
Branch: 2 branches
BranchTrueFalseTotal
unless $pa and $pa->{"email"} 12 4 16
unless $pa and $pa->{"email"} 0 2 2
Condition33%2/6
$pa and $pa->{"email"}
!ll&&!rl&&r
1204
$pa and $pa->{"email"}
!ll&&!rl&&r
000
MC/DC50%1/2
$pa and $pa->{"email"}
$pa $pa->{"email"}
MC/DC0%0/2
$pa and $pa->{"email"}
$pa $pa->{"email"}
Truth table66%2/3
A and B
A= $paB= $pa->{"email"}
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $paB= $pa->{"email"}
ABresult
0X0
100
111
2175 7 my ($example_addr) = $combined_body =~ /(\S+\@\Q$addr_dom\E)/i;
2176 7 ▶ $example_addr //= "\@$addr_dom";
Condition25%1/4
$example_addr //= "\@$addr_dom"
l!l
40
$example_addr //= "\@$addr_dom"
l!l
00
MC/DC0%0/1
$example_addr //= "\@$addr_dom"
$example_addr
MC/DC0%0/1
$example_addr //= "\@$addr_dom"
$example_addr
Truth table50%1/2
A
A= $example_addr
Aresult
11
00
Truth table0%0/2
A
A= $example_addr
Aresult
11
00
2177 $add->(
2178 role => "Reply address in body ($example_addr)",
2179 address => $pa->{email},
2180 note => $pa->{note},
2181 7 via => 'provider-table',
2182 );
2183 }
2184  
2185 161 return @contacts;
2186 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
2187  
2188 # -----------------------------------------------------------------------
2189 # Public: form contacts (providers that require web-form submission)
2190 # -----------------------------------------------------------------------
2191  
2192 =head2 form_contacts()
2193  
2194 Returns the list of parties that require abuse reports via a web form
2195 rather than email. These are providers whose C<%PROVIDER_ABUSE> entry
2196 has a C<form> key. Each hashref includes the form URL, paste
2197 instructions, upload instructions, and the discovery role.
2198  
2199 =head3 Usage
2200  
2201 my @forms = $analyser->form_contacts();
2202 for my $c (@forms) {
2203 printf "Open: %s\n", $c->{form};
2204 }
2205  
2206 =head3 Arguments
2207  
2208 None. C<parse_email()> must have been called first.
2209  
2210 =head3 Returns
2211  
2212 A list of hashrefs, one per unique form contact. Each hashref has keys
2213 C<form>, C<role>, C<note>, C<form_paste> (optional), C<form_upload>
2214 (optional), and C<via>. Returns an empty list if no form contacts are found.
2215  
2216 =head3 Side Effects
2217  
2218 Triggers C<originating_ip()>, C<embedded_urls()>, and C<mailto_domains()>
2219 if not already cached.
2220  
2221 =head3 Notes
2222  
2223 Deduplication is by form URL.
2224  
2225 =head3 API Specification
2226  
2227 =head4 Input
2228  
2229 []
2230  
2231 =head4 Output
2232  
2233 (
2234 {
2235 type => 'hashref',
2236 keys => {
2237 form => { type => 'string', regex => qr{^https?://} },
2238 role => { type => 'string' },
2239 note => { type => 'string' },
2240 form_paste => { type => 'string', optional => 1 },
2241 form_upload => { type => 'string', optional => 1 },
2242 via => { type => 'string' },
2243 },
2244 },
2245 ...
2246 )
2247  
2248 =cut
2249  
2250 sub form_contacts {
2251 188 ▶ my $self = $_[0];
Subroutine form_contacts: called CC=53 SCAR=57.6
Subroutine form_contacts: called CC=53 SCAR=57.6
Pod documented
2252  
2253 257 my (@contacts, %seen);
2254  
2255 # Inner closure: add one form-contact entry, deduplicating by form URL
2256 my $add = sub {
2257 35 ▶ my (%args) = @_;
Subroutine __ANON__: called CC=4 SCAR=14.0
2258 35 ▶ my $form = $args{form} // '';
Condition33%1/3
$args{"form"} // ""
l!l
3200
MC/DC100%1/1
$args{"form"} // ""
$args{"form"}
Truth table100%2/2
A
A= $args{"form"}
Aresult
11
00
2259 35 ▶ return unless $form;
Branch: 1 branch
BranchTrueFalseTotal
unless $form 1 31 32
2260 35 ▶ return if $seen{$form}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$form}++ 9 23 32
2261 26 push @contacts, \%args;
2262 210 };
2263  
2264 # Route 1 -- Sending ISP
2265 210 my $orig = $self->originating_ip();
2266 210 ▶ if ($orig) {
Branch: 2 branches
BranchTrueFalseTotal
if ($orig) 99 103 202
if ($orig) 2 0 2
2267 142 my $pa = $self->_provider_abuse_for_ip($orig->{ip}, $orig->{rdns});
2268 142 ▶ if ($pa && $pa->{form}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pa and $pa->{"form"}) 1 94 95
if ($pa and $pa->{"form"}) 2 0 2
Condition33%2/6
$pa and $pa->{"form"}
!ll&&!rl&&r
9760
$pa and $pa->{"form"}
!ll&&!rl&&r
000
MC/DC0%0/2
$pa and $pa->{"form"}
$pa $pa->{"form"}
MC/DC0%0/2
$pa and $pa->{"form"}
$pa $pa->{"form"}
Truth table66%2/3
A and B
A= $paB= $pa->{"form"}
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $paB= $pa->{"form"}
ABresult
0X0
100
111
2269 $add->(
2270 role => 'Sending ISP',
2271 form => $pa->{form},
2272 note => $pa->{note} // '',
2273 form_paste => $pa->{form_paste} // '',
2274 48 ▶ form_upload => $pa->{form_upload} // '',
Condition18%3/16
$pa->{"note"} // ""
l!l
200
$pa->{"form_paste"} // ""
l!l
200
$pa->{"form_upload"} // ""
l!l
200
$pa->{"note"} // ""
l!l
000
$pa->{"form_paste"} // ""
l!l
00
$pa->{"form_upload"} // ""
l!l
00
MC/DC0%0/1
$pa->{"note"} // ""
$pa->{"note"}
MC/DC0%0/1
$pa->{"form_paste"} // ""
$pa->{"form_paste"}
MC/DC0%0/1
$pa->{"form_upload"} // ""
$pa->{"form_upload"}
MC/DC0%0/1
$pa->{"note"} // ""
$pa->{"note"}
MC/DC0%0/1
$pa->{"form_paste"} // ""
$pa->{"form_paste"}
MC/DC0%0/1
$pa->{"form_upload"} // ""
$pa->{"form_upload"}
Truth table50%1/2
A
A= $pa->{"note"}
Aresult
11
00
Truth table50%1/2
A
A= $pa->{"form_paste"}
Aresult
11
00
Truth table50%1/2
A
A= $pa->{"form_upload"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"note"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"form_paste"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"form_upload"}
Aresult
11
00
2275 via => 'provider-table',
2276 );
2277 }
2278 }
2279  
2280 # Route 2 -- URL hosts
2281 168 my %url_host_seen;
2282 168 for my $u ($self->embedded_urls()) {
2283 76 ▶ next if $url_host_seen{ $u->{host} }++;
Branch: 2 branches
BranchTrueFalseTotal
if $url_host_seen{$u->{"host"}}++ 14 61 75
if $url_host_seen{$u->{"host"}}++ 2 0 2
2284 85 my $pa = $self->_provider_abuse_for_host($u->{host});
2285 85 ▶ if ($pa && $pa->{form}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pa and $pa->{"form"}) 42 62 104
if ($pa and $pa->{"form"}) 0 2 2
Condition50%3/6
$pa and $pa->{"form"}
!ll&&!rl&&r
5353
$pa and $pa->{"form"}
!ll&&!rl&&r
000
MC/DC100%2/2
$pa and $pa->{"form"}
$pa $pa->{"form"}
MC/DC0%0/2
$pa and $pa->{"form"}
$pa $pa->{"form"}
Truth table100%3/3
A and B
A= $paB= $pa->{"form"}
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $paB= $pa->{"form"}
ABresult
0X0
100
111
2286 $add->(
2287 role => "URL host: $u->{host}",
2288 form => $pa->{form},
2289 form_domain => $u->{host},
2290 note => $pa->{note} // '',
2291 form_paste => $pa->{form_paste} // '',
2292 6 ▶ form_upload => $pa->{form_upload} // '',
Condition35%5/14
$pa->{"note"} // ""
l!l
50
$pa->{"form_paste"} // ""
l!l
50
$pa->{"form_upload"} // ""
l!l
512
$pa->{"note"} // ""
l!l
000
$pa->{"form_paste"} // ""
l!l
00
$pa->{"form_upload"} // ""
l!l
00
MC/DC0%0/1
$pa->{"note"} // ""
$pa->{"note"}
MC/DC0%0/1
$pa->{"form_paste"} // ""
$pa->{"form_paste"}
MC/DC100%1/1
$pa->{"form_upload"} // ""
$pa->{"form_upload"}
MC/DC0%0/1
$pa->{"note"} // ""
$pa->{"note"}
MC/DC0%0/1
$pa->{"form_paste"} // ""
$pa->{"form_paste"}
MC/DC0%0/1
$pa->{"form_upload"} // ""
$pa->{"form_upload"}
Truth table50%1/2
A
A= $pa->{"note"}
Aresult
11
00
Truth table50%1/2
A
A= $pa->{"form_paste"}
Aresult
11
00
Truth table100%2/2
A
A= $pa->{"form_upload"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"note"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"form_paste"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"form_upload"}
Aresult
11
00
2293 via => 'provider-table',
2294 );
2295 }
2296 }
2297  
2298 # Route 3 -- Contact domains (web host + registrar)
2299 165 for my $d ($self->mailto_domains()) {
2300 165 my $dom = $d->{domain};
2301 188 my $pa = $self->_provider_abuse_for_host($dom);
2302 188 ▶ if ($pa && $pa->{form}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pa and $pa->{"form"}) 7 200 207
if ($pa and $pa->{"form"}) 2 0 2
Condition33%2/6
$pa and $pa->{"form"}
!ll&&!rl&&r
15607
$pa and $pa->{"form"}
!ll&&!rl&&r
000
MC/DC50%1/2
$pa and $pa->{"form"}
$pa $pa->{"form"}
MC/DC0%0/2
$pa and $pa->{"form"}
$pa $pa->{"form"}
Truth table66%2/3
A and B
A= $paB= $pa->{"form"}
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $paB= $pa->{"form"}
ABresult
0X0
100
111
2303 $add->(
2304 role => "Web host of $dom",
2305 form => $pa->{form},
2306 form_domain => $dom,
2307 note => $pa->{note} // '',
2308 form_paste => $pa->{form_paste} // '',
2309 10 ▶ form_upload => $pa->{form_upload} // '',
Condition28%4/14
$pa->{"note"} // ""
l!l
100
$pa->{"form_paste"} // ""
l!l
5247
$pa->{"form_upload"} // ""
l!l
1000
$pa->{"note"} // ""
l!l
000
$pa->{"form_paste"} // ""
l!l
00
$pa->{"form_upload"} // ""
l!l
00
MC/DC0%0/1
$pa->{"note"} // ""
$pa->{"note"}
MC/DC100%1/1
$pa->{"form_paste"} // ""
$pa->{"form_paste"}
MC/DC100%1/1
$pa->{"form_upload"} // ""
$pa->{"form_upload"}
MC/DC0%0/1
$pa->{"note"} // ""
$pa->{"note"}
MC/DC0%0/1
$pa->{"form_paste"} // ""
$pa->{"form_paste"}
MC/DC0%0/1
$pa->{"form_upload"} // ""
$pa->{"form_upload"}
Truth table50%1/2
A
A= $pa->{"note"}
Aresult
11
00
Truth table100%2/2
A
A= $pa->{"form_paste"}
Aresult
11
00
Truth table100%2/2
A
A= $pa->{"form_upload"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"note"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"form_paste"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"form_upload"}
Aresult
11
00
2310 via => 'provider-table',
2311 );
2312 }
2313  
2314 # Registrar identified via WHOIS -- check for form-only registrar
2315 165 ▶ if ($d->{registrar_abuse} && $d->{registrar_abuse} =~ /\@([\w.-]+)/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($d->{"registrar_abuse"} and $d->{"registrar_abuse"} =~ /\@([\w.-]+)/) 21 186 207
if ($d->{"registrar_abuse"} and $d->{"registrar_abuse"} =~ /\@([\w.-]+)/) 0 2 2
Condition33%2/6
$d->{"registrar_abuse"} and $d->{"registrar_abuse"} =~ /\@([\w.-]+)/
!ll&&!rl&&r
141021
$d->{"registrar_abuse"} and $d->{"registrar_abuse"} =~ /\@([\w.-]+)/
!ll&&!rl&&r
000
MC/DC50%1/2
$d->{"registrar_abuse"} and $d->{"registrar_abuse"} =~ /\@([\w.-]+)/
$d->{"registrar_abuse"} $d->{"registrar_abuse"} =~ /\@([\w.-]+)/
MC/DC0%0/2
$d->{"registrar_abuse"} and $d->{"registrar_abuse"} =~ /\@([\w.-]+)/
$d->{"registrar_abuse"} $d->{"registrar_abuse"} =~ /\@([\w.-]+)/
Truth table66%2/3
A and B
A= $d->{"registrar_abuse"}B= $d->{"registrar_abuse"} =~ /\@([\w.-]+)/
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $d->{"registrar_abuse"}B= $d->{"registrar_abuse"} =~ /\@([\w.-]+)/
ABresult
0X0
100
111
2316 24 my $reg_domain = lc $1;
2317 24 my $rpa = $self->_provider_abuse_for_host($reg_domain);
2318 24 ▶ if ($rpa && $rpa->{form}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($rpa and $rpa->{"form"}) 16 50 66
if ($rpa and $rpa->{"form"}) 0 0 0
Condition50%3/6
$rpa and $rpa->{"form"}
!ll&&!rl&&r
6213
$rpa and $rpa->{"form"}
!ll&&!rl&&r
000
MC/DC100%2/2
$rpa and $rpa->{"form"}
$rpa $rpa->{"form"}
MC/DC0%0/2
$rpa and $rpa->{"form"}
$rpa $rpa->{"form"}
Truth table100%3/3
A and B
A= $rpaB= $rpa->{"form"}
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $rpaB= $rpa->{"form"}
ABresult
0X0
100
111
2319 $add->(
2320 role => "Domain registrar for $dom (web form only)",
2321 form => $rpa->{form},
2322 form_domain => $dom,
2323 note => $rpa->{note} // '',
2324 form_paste => $rpa->{form_paste} // '',
2325 16 ▶ form_upload => $rpa->{form_upload} // '',
Condition23%3/13
$rpa->{"note"} // ""
l!l
130
$rpa->{"form_paste"} // ""
l!l
130
$rpa->{"form_upload"} // ""
l!l
130
$rpa->{"note"} // ""
l!l
000
$rpa->{"form_paste"} // ""
l!l
00
$rpa->{"form_upload"} // ""
l!l
00
MC/DC0%0/1
$rpa->{"note"} // ""
$rpa->{"note"}
MC/DC0%0/1
$rpa->{"form_paste"} // ""
$rpa->{"form_paste"}
MC/DC0%0/1
$rpa->{"form_upload"} // ""
$rpa->{"form_upload"}
MC/DC0%0/1
$rpa->{"note"} // ""
$rpa->{"note"}
MC/DC0%0/1
$rpa->{"form_paste"} // ""
$rpa->{"form_paste"}
MC/DC0%0/1
$rpa->{"form_upload"} // ""
$rpa->{"form_upload"}
Truth table50%1/2
A
A= $rpa->{"note"}
Aresult
11
00
Truth table50%1/2
A
A= $rpa->{"form_paste"}
Aresult
11
00
Truth table50%1/2
A
A= $rpa->{"form_upload"}
Aresult
11
00
Truth table0%0/2
A
A= $rpa->{"note"}
Aresult
11
00
Truth table0%0/2
A
A= $rpa->{"form_paste"}
Aresult
11
00
Truth table0%0/2
A
A= $rpa->{"form_upload"}
Aresult
11
00
2326 via => 'provider-table',
2327 );
2328 }
2329 }
2330 }
2331  
2332 # Route 4 -- Account provider headers
2333 165 for my $hname (qw(from reply-to return-path sender)) {
2334 651 ▶ my $val = $self->_header_value($hname) // next;
Condition50%2/4
$self->_header_value($hname) // (next)
l!l
274374
$self->_header_value($hname) // (next)
l!l
00
MC/DC100%1/1
$self->_header_value($hname) // (next)
$self->_header_value($hname)
MC/DC0%0/1
$self->_header_value($hname) // (next)
$self->_header_value($hname)
Truth table100%2/2
A
A= $self->_header_value($hname)
Aresult
11
00
Truth table0%0/2
A
A= $self->_header_value($hname)
Aresult
11
00
2335 277 ▶ my $addr_spec = ($val =~ /<([^>]*)>\s*$/) ? $1 : $val;
Branch: 2 branches
BranchTrueFalseTotal
$val =~ /<([^>]*)>\s*$/ ? : 241 36 277
$val =~ /<([^>]*)>\s*$/ ? : 0 0 0
2336 277 my ($addr_domain) = $addr_spec =~ /\@([\w.-]+)/;
2337 277 ▶ next unless $addr_domain;
Branch: 2 branches
BranchTrueFalseTotal
unless $addr_domain 0 297 297
unless $addr_domain 2 0 2
2338 # Skip SRS forwarder rewrite addresses
2339 300 ▶ next if $addr_spec =~ /\+SRS[0-9]?=/i;
Branch: 2 branches
BranchTrueFalseTotal
if $addr_spec =~ /\+SRS[0-9]?=/i 0 274 274
if $addr_spec =~ /\+SRS[0-9]?=/i 2 0 2
2340 300 my $pa = $self->_provider_abuse_for_host($addr_domain);
2341 300 ▶ if ($pa && $pa->{form}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pa and $pa->{"form"}) 11 286 297
if ($pa and $pa->{"form"}) 0 2 2
Condition50%3/6
$pa and $pa->{"form"}
!ll&&!rl&&r
2441911
$pa and $pa->{"form"}
!ll&&!rl&&r
000
MC/DC100%2/2
$pa and $pa->{"form"}
$pa $pa->{"form"}
MC/DC0%0/2
$pa and $pa->{"form"}
$pa $pa->{"form"}
Truth table100%3/3
A and B
A= $paB= $pa->{"form"}
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $paB= $pa->{"form"}
ABresult
0X0
100
111
2342 17 ▶ my $role_addr = $addr_spec =~ /@/ ? $addr_spec : $val;
Branch: 2 branches
BranchTrueFalseTotal
$addr_spec =~ /@/ ? : 11 0 11
$addr_spec =~ /@/ ? : 2 0 2
2343 17 $role_addr =~ s/^\s+|\s+$//g;
2344 $add->(
2345 role => "Account provider ($hname: $role_addr)",
2346 form => $pa->{form},
2347 note => $pa->{note} // '',
2348 form_paste => $pa->{form_paste} // '',
2349 17 ▶ form_upload => $pa->{form_upload} // '',
Condition23%3/13
$pa->{"note"} // ""
l!l
110
$pa->{"form_paste"} // ""
l!l
110
$pa->{"form_upload"} // ""
l!l
110
$pa->{"note"} // ""
l!l
000
$pa->{"form_paste"} // ""
l!l
00
$pa->{"form_upload"} // ""
l!l
00
MC/DC0%0/1
$pa->{"note"} // ""
$pa->{"note"}
MC/DC0%0/1
$pa->{"form_paste"} // ""
$pa->{"form_paste"}
MC/DC0%0/1
$pa->{"form_upload"} // ""
$pa->{"form_upload"}
MC/DC0%0/1
$pa->{"note"} // ""
$pa->{"note"}
MC/DC0%0/1
$pa->{"form_paste"} // ""
$pa->{"form_paste"}
MC/DC0%0/1
$pa->{"form_upload"} // ""
$pa->{"form_upload"}
Truth table50%1/2
A
A= $pa->{"note"}
Aresult
11
00
Truth table50%1/2
A
A= $pa->{"form_paste"}
Aresult
11
00
Truth table50%1/2
A
A= $pa->{"form_upload"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"note"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"form_paste"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"form_upload"}
Aresult
11
00
2350 via => 'provider-table',
2351 );
2352 }
2353 }
2354  
2355 # Route 5 -- DKIM signer
2356 165 my $auth = $self->_parse_auth_results_cached();
2357 165 ▶ if ($auth->{dkim_domain}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($auth->{"dkim_domain"}) 2 160 162
if ($auth->{"dkim_domain"}) 0 2 2
2358 5 my $pa = $self->_provider_abuse_for_host($auth->{dkim_domain});
2359 28 ▶ if ($pa && $pa->{form}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pa and $pa->{"form"}) 1 1 2
if ($pa and $pa->{"form"}) 2 0 2
Condition33%2/6
$pa and $pa->{"form"}
!ll&&!rl&&r
101
$pa and $pa->{"form"}
!ll&&!rl&&r
000
MC/DC50%1/2
$pa and $pa->{"form"}
$pa $pa->{"form"}
MC/DC0%0/2
$pa and $pa->{"form"}
$pa $pa->{"form"}
Truth table66%2/3
A and B
A= $paB= $pa->{"form"}
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $paB= $pa->{"form"}
ABresult
0X0
100
111
2360 $add->(
2361 role => "DKIM signer: $auth->{dkim_domain}",
2362 form => $pa->{form},
2363 note => $pa->{note} // '',
2364 form_paste => $pa->{form_paste} // '',
2365 4 ▶ form_upload => $pa->{form_upload} // '',
Condition23%3/13
$pa->{"note"} // ""
l!l
10
$pa->{"form_paste"} // ""
l!l
10
$pa->{"form_upload"} // ""
l!l
10
$pa->{"note"} // ""
l!l
000
$pa->{"form_paste"} // ""
l!l
00
$pa->{"form_upload"} // ""
l!l
00
MC/DC0%0/1
$pa->{"note"} // ""
$pa->{"note"}
MC/DC0%0/1
$pa->{"form_paste"} // ""
$pa->{"form_paste"}
MC/DC0%0/1
$pa->{"form_upload"} // ""
$pa->{"form_upload"}
MC/DC0%0/1
$pa->{"note"} // ""
$pa->{"note"}
MC/DC0%0/1
$pa->{"form_paste"} // ""
$pa->{"form_paste"}
MC/DC0%0/1
$pa->{"form_upload"} // ""
$pa->{"form_upload"}
Truth table50%1/2
A
A= $pa->{"note"}
Aresult
11
00
Truth table50%1/2
A
A= $pa->{"form_paste"}
Aresult
11
00
Truth table50%1/2
A
A= $pa->{"form_upload"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"note"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"form_paste"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"form_upload"}
Aresult
11
00
2366 via => 'provider-table',
2367 );
2368 }
2369 }
2370  
2371 # Route 6 -- List-Unsubscribe ESP domains
2372 165 my $unsub = $self->_header_value('list-unsubscribe');
2373 165 ▶ if ($unsub) {
Branch: 2 branches
BranchTrueFalseTotal
if ($unsub) 2 163 165
if ($unsub) 2 0 2
2374 5 my @unsub_domains;
2375 5 ▶ while ($unsub =~ m{https?://([^/:?\s>]+)}gi) { push @unsub_domains, lc $1 }
Branch: 2 branches
BranchTrueFalseTotal
if ($unsub =~ m[https?://([^/:?\s>]+)]gi) 4 2 6
if ($unsub =~ m[https?://([^/:?\s>]+)]gi) 2 0 2
2376 5 ▶ while ($unsub =~ m{mailto:[^@\s>]+\@([\w.-]+)}gi) { push @unsub_domains, lc $1 }
Branch: 2 branches
BranchTrueFalseTotal
if ($unsub =~ /mailto:[^\@\s>]+\@([\w.-]+)/gi) 1 2 3
if ($unsub =~ /mailto:[^\@\s>]+\@([\w.-]+)/gi) 2 0 2
2377 5 my %useen;
2378 5 for my $dom (grep { !$useen{$_}++ } @unsub_domains) {
2379 5 my $pa = $self->_provider_abuse_for_host($dom);
2380 5 ▶ if ($pa && $pa->{form}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pa and $pa->{"form"}) 2 0 2
if ($pa and $pa->{"form"}) 0 2 2
Condition16%1/6
$pa and $pa->{"form"}
!ll&&!rl&&r
002
$pa and $pa->{"form"}
!ll&&!rl&&r
000
MC/DC0%0/2
$pa and $pa->{"form"}
$pa $pa->{"form"}
MC/DC0%0/2
$pa and $pa->{"form"}
$pa $pa->{"form"}
Truth table33%1/3
A and B
A= $paB= $pa->{"form"}
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $paB= $pa->{"form"}
ABresult
0X0
100
111
2381 $add->(
2382 role => "ESP / bulk sender (List-Unsubscribe: $dom)",
2383 form => $pa->{form},
2384 note => $pa->{note} // '',
2385 form_paste => $pa->{form_paste} // '',
2386 5 ▶ form_upload => $pa->{form_upload} // '',
Condition23%3/13
$pa->{"note"} // ""
l!l
20
$pa->{"form_paste"} // ""
l!l
20
$pa->{"form_upload"} // ""
l!l
20
$pa->{"note"} // ""
l!l
000
$pa->{"form_paste"} // ""
l!l
00
$pa->{"form_upload"} // ""
l!l
00
MC/DC0%0/1
$pa->{"note"} // ""
$pa->{"note"}
MC/DC0%0/1
$pa->{"form_paste"} // ""
$pa->{"form_paste"}
MC/DC0%0/1
$pa->{"form_upload"} // ""
$pa->{"form_upload"}
MC/DC0%0/1
$pa->{"note"} // ""
$pa->{"note"}
MC/DC0%0/1
$pa->{"form_paste"} // ""
$pa->{"form_paste"}
MC/DC0%0/1
$pa->{"form_upload"} // ""
$pa->{"form_upload"}
Truth table50%1/2
A
A= $pa->{"note"}
Aresult
11
00
Truth table50%1/2
A
A= $pa->{"form_paste"}
Aresult
11
00
Truth table50%1/2
A
A= $pa->{"form_upload"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"note"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"form_paste"}
Aresult
11
00
Truth table0%0/2
A
A= $pa->{"form_upload"}
Aresult
11
00
2387 via => 'provider-table',
2388 );
2389 }
2390 }
2391 }
2392  
2393 165 return @contacts;
2394 }
2395  
2396 # -----------------------------------------------------------------------
2397 # Public: full analyst report
2398 # -----------------------------------------------------------------------
2399  
2400 =head2 report()
2401  
2402 Produces a comprehensive, analyst-facing plain-text report covering all
2403 findings: envelope fields, risk assessment, originating host, sending
2404 software, received chain tracking IDs, embedded URLs, contact domain
2405 intelligence, and recommended abuse contacts.
2406  
2407 Use C<report()> for human review or ticketing systems. Use
2408 C<abuse_report_text()> for sending to ISP abuse desks.
2409  
2410 =head3 Usage
2411  
2412 print $analyser->report();
2413  
2414 open my $fh, '>', 'report.txt' or croak "Cannot open: $!";
2415 print $fh $analyser->report();
2416 close $fh;
2417  
2418 =head3 Arguments
2419  
2420 None. C<parse_email()> must have been called first.
2421  
2422 =head3 Returns
2423  
2424 A plain scalar string, newline-terminated, Unix line endings. Never empty
2425 or undef.
2426  
2427 =head3 Side Effects
2428  
2429 Triggers all analysis methods if not already cached.
2430  
2431 =head3 Notes
2432  
2433 The report is idempotent: calling it multiple times on the same object
2434 always returns an identical string. All user-derived content is sanitised
2435 before output.
2436  
2437 =head3 API Specification
2438  
2439 =head4 Input
2440  
2441 []
2442  
2443 =head4 Output
2444  
2445 { type => 'string' }
2446  
2447 =cut
2448  
2449 sub report {
2450 71 ▶ my $self = $_[0];
Subroutine report: called CC=66 SCAR=45.4
Subroutine report: called CC=66 SCAR=45.4
Pod documented
2451  
2452 71 my @out;
2453  
2454 # Banner header
2455 70 push @out, '=' x 72;
2456 71 push @out, " Email::Abuse::Investigator Report (v$VERSION)";
2457 71 push @out, '=' x 72;
2458 65 push @out, '';
2459  
2460 # Envelope summary -- decode MIME encoded-words for readability
2461 65 for my $f (qw(from reply-to return-path subject date message-id)) {
2462 370 my $v = $self->_header_value($f);
2463 369 ▶ next unless defined $v;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $v 115 258 373
unless defined $v 0 2 2
2464 255 my $decoded = $self->_decode_mime_words($v);
2465 255 my $label = ucfirst($f);
2466 255 ▶ push @out, sprintf(' %-14s : %s', $label,
Branch: 2 branches
BranchTrueFalseTotal
$decoded ne $v ? : 6 252 258
$decoded ne $v ? : 0 2 2
2467 _sanitise_output($decoded ne $v ? "$decoded [encoded: $v]" : $v));
2468 }
2469 65 push @out, '';
2470  
2471 # Risk assessment section
2472 64 my $risk = $self->risk_assessment();
2473 65 push @out, "[ RISK ASSESSMENT: $risk->{level} (score: $risk->{score}) ]";
2474 64 ▶ if (@{ $risk->{flags} }) {
Branch: 2 branches
BranchTrueFalseTotal
if (@{$risk->{'flags'};}) { } 32 30 62
if (@{$risk->{'flags'};}) { } 0 2 2
2475 35 for my $f (@{ $risk->{flags} }) {
2476 62 push @out, " [$f->{severity}] " . _sanitise_output($f->{detail});
2477 }
2478 } else {
2479 36 push @out, ' (no specific red flags detected)';
2480 }
2481 66 push @out, '';
2482  
2483 # Originating host section
2484 66 push @out, '[ ORIGINATING HOST ]';
2485 66 ▶ if(my $orig = $self->originating_ip()) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $orig = $self->originating_ip) { } 32 30 62
if (my $orig = $self->originating_ip) { } 0 2 2
2486 37 push @out, ' IP : ' . _sanitise_output($orig->{ip});
2487 37 ▶ push @out, ' Reverse DNS : ' . _sanitise_output($orig->{rdns}) if $orig->{rdns};
Branch: 2 branches
BranchTrueFalseTotal
if $orig->{"rdns"} 32 0 32
if $orig->{"rdns"} 0 2 2
2488 37 ▶ push @out, ' Country : ' . _sanitise_output($orig->{country}) if $orig->{country};
Branch: 2 branches
BranchTrueFalseTotal
if $orig->{"country"} 11 23 34
if $orig->{"country"} 0 0 0
2489 35 ▶ push @out, ' Organisation : ' . _sanitise_output($orig->{org}) if $orig->{org};
Branch: 2 branches
BranchTrueFalseTotal
if $orig->{"org"} 32 2 34
if $orig->{"org"} 0 0 0
2490 35 ▶ push @out, ' Abuse addr : ' . _sanitise_output($orig->{abuse}) if $orig->{abuse};
Branch: 2 branches
BranchTrueFalseTotal
if $orig->{"abuse"} 32 2 34
if $orig->{"abuse"} 0 2 2
2491 35 push @out, " Confidence : $orig->{confidence}";
2492 36 ▶ push @out, ' Note : ' . _sanitise_output($orig->{note}) if $orig->{note};
Branch: 2 branches
BranchTrueFalseTotal
if $orig->{"note"} 24 10 34
if $orig->{"note"} 0 0 0
2493 } else {
2494 33 push @out, ' (could not determine originating IP)';
2495 }
2496 64 push @out, '';
2497  
2498 # Sending software section (omitted if none found)
2499 64 my @sw = $self->sending_software();
2500 64 ▶ if (@sw) {
Branch: 2 branches
BranchTrueFalseTotal
if (@sw) 2 59 61
if (@sw) 0 0 0
2501 6 push @out, '[ SENDING SOFTWARE / INFRASTRUCTURE CLUES ]';
2502 6 for my $s (@sw) {
2503 5 push @out, sprintf(' %-14s : %s', $s->{header}, _sanitise_output($s->{value}));
2504 5 push @out, " Note : $s->{note}";
2505 5 push @out, '';
2506 }
2507 }
2508  
2509 # Received chain tracking IDs (only hops with id or for are shown)
2510 64 ▶ my @trail = grep { defined $_->{id} || defined $_->{for} }
Branch: 2 branches
BranchTrueFalseTotal
defined $_->{"id"} or defined $_->{"for"} 49 2 51
defined $_->{"id"} or defined $_->{"for"} 0 0 0
2511 $self->received_trail();
2512 64 ▶ if (@trail) {
Branch: 2 branches
BranchTrueFalseTotal
if (@trail) 1 60 61
if (@trail) 0 2 2
2513 1 push @out, '[ RECEIVED CHAIN TRACKING IDs ]';
2514 4 push @out, ' (Supply these to the relevant ISP abuse team to trace the session)';
2515 4 push @out, '';
2516 4 for my $hop (@trail) {
2517 4 ▶ push @out, ' IP : ' . (_sanitise_output($hop->{ip}) // '(unknown)');
Condition25%1/4
_sanitise_output($hop->{"ip"}) // "(unknown)"
l!l
70
_sanitise_output($hop->{"ip"}) // "(unknown)"
l!l
00
MC/DC0%0/1
_sanitise_output($hop->{"ip"}) // "(unknown)"
_sanitise_output($hop->{"ip"})
MC/DC0%0/1
_sanitise_output($hop->{"ip"}) // "(unknown)"
_sanitise_output($hop->{"ip"})
Truth table50%1/2
A
A= _sanitise_output($hop->{"ip"})
Aresult
11
00
Truth table0%0/2
A
A= _sanitise_output($hop->{"ip"})
Aresult
11
00
2518 5 ▶ push @out, ' Envelope for : ' . _sanitise_output($hop->{for}) if $hop->{for};
Branch: 2 branches
BranchTrueFalseTotal
if $hop->{"for"} 1 1 2
if $hop->{"for"} 0 0 0
2519 5 ▶ push @out, ' Server ID : ' . _sanitise_output($hop->{id}) if $hop->{id};
Branch: 2 branches
BranchTrueFalseTotal
if $hop->{"id"} 1 0 1
if $hop->{"id"} 0 0 0
2520 5 push @out, '';
2521 }
2522 }
2523  
2524 # Embedded URLs section -- grouped by hostname
2525 65 push @out, '[ EMBEDDED HTTP/HTTPS URLs ]';
2526 65 my @urls = $self->embedded_urls();
2527 65 ▶ if (@urls) {
Branch: 2 branches
BranchTrueFalseTotal
if (@urls) { } 18 43 61
if (@urls) { } 0 0 0
2528 22 my (%host_order, %host_meta, %host_paths);
2529 22 my $seq = 0;
2530 21 for my $u (@urls) {
2531 33 my $h = $u->{host};
2532 33 ▶ unless (exists $host_order{$h}) {
Branch: 2 branches
BranchTrueFalseTotal
unless (exists $host_order{$h}) 21 8 29
unless (exists $host_order{$h}) 2 0 2
2533 25 $host_order{$h} = $seq++;
2534 $host_meta{$h} = {
2535 ip => $u->{ip},
2536 org => $u->{org},
2537 abuse => $u->{abuse},
2538 country => $u->{country},
2539 25 };
2540 }
2541 30 push @{ $host_paths{$h} }, $u->{url};
2542 }
2543  
2544 # Output each host group in first-seen order
2545 22 for my $h (sort { $host_order{$a} <=> $host_order{$b} } keys %host_order) {
2546 26 my $m = $host_meta{$h};
2547 26 my $bare = lc $h; $bare =~ s/^www\.//;
2548 push @out, ' Host : ' . _sanitise_output($h) .
2549 26 ▶ (($URL_SHORTENERS{$bare} || $self->{url_shorteners}->{$bare})
Branch: 2 branches
BranchTrueFalseTotal
$URL_SHORTENERS{$bare} || $self->{'url_shorteners'}{$bare} ? : 4 18 22
$URL_SHORTENERS{$bare} || $self->{'url_shorteners'}{$bare} ? : 3 0 3
Condition50%3/6
$URL_SHORTENERS{$bare} or $self->{"url_shorteners"}{$bare}
l!l&&r!l&&!r
3018
$URL_SHORTENERS{$bare} or $self->{"url_shorteners"}{$bare}
l!l&&r!l&&!r
200
MC/DC50%1/2
$URL_SHORTENERS{$bare} or $self->{"url_shorteners"}{$bare}
$URL_SHORTENERS{$bare} $self->{"url_shorteners"}{$bare}
MC/DC0%0/2
$URL_SHORTENERS{$bare} or $self->{"url_shorteners"}{$bare}
$URL_SHORTENERS{$bare} $self->{"url_shorteners"}{$bare}
Truth table66%2/3
A or B
A= $URL_SHORTENERS{$bare}B= $self->{"url_shorteners"}{$bare}
ABresult
1X1
011
000
Truth table0%0/3
A or B
A= $URL_SHORTENERS{$bare}B= $self->{"url_shorteners"}{$bare}
ABresult
1X1
011
000
2550 ? ' *** URL SHORTENER -- real destination hidden ***' : '');
2551 25 ▶ push @out, ' IP : ' . _sanitise_output($m->{ip}) if $m->{ip};
Branch: 2 branches
BranchTrueFalseTotal
if $m->{"ip"} 21 1 22
if $m->{"ip"} 0 2 2
2552 25 ▶ push @out, ' Country : ' . _sanitise_output($m->{country}) if $m->{country};
Branch: 2 branches
BranchTrueFalseTotal
if $m->{"country"} 4 18 22
if $m->{"country"} 0 0 0
2553 25 ▶ push @out, ' Organisation : ' . _sanitise_output($m->{org}) if $m->{org};
Branch: 2 branches
BranchTrueFalseTotal
if $m->{"org"} 21 1 22
if $m->{"org"} 0 0 0
2554 24 ▶ push @out, ' Abuse addr : ' . _sanitise_output($m->{abuse}) if $m->{abuse};
Branch: 2 branches
BranchTrueFalseTotal
if $m->{"abuse"} 21 2 23
if $m->{"abuse"} 0 0 0
2555 25 my @paths = @{ $host_paths{$h} };
2556 27 ▶ if (@paths == 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (@paths == 1) { } 16 7 23
if (@paths == 1) { } 0 0 0
2557 21 push @out, ' URL : ' . _sanitise_output($paths[0]);
2558 } else {
2559 12 push @out, ' URLs (' . scalar(@paths) . ') :';
2560 12 push @out, ' ' . _sanitise_output($_) for @paths;
2561 }
2562 27 push @out, '';
2563 }
2564 } else {
2565 49 push @out, ' (none found)';
2566 46 push @out, '';
2567 }
2568  
2569 # Contact / reply-to domains section
2570 64 push @out, '[ CONTACT / REPLY-TO DOMAINS ]';
2571 64 my @mdoms = $self->mailto_domains();
2572 65 ▶ if (@mdoms) {
Branch: 2 branches
BranchTrueFalseTotal
if (@mdoms) { } 48 14 62
if (@mdoms) { } 0 0 0
2573 52 for my $d (@mdoms) {
2574 56 push @out, ' Domain : ' . _sanitise_output($d->{domain});
2575 56 push @out, ' Found in : ' . _sanitise_output($d->{source});
2576 56 ▶ if ($d->{recently_registered}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($d->{"recently_registered"}) 4 52 56
if ($d->{"recently_registered"}) 0 0 0
2577 6 push @out, ' *** WARNING: RECENTLY REGISTERED - possible phishing domain ***';
2578 }
2579 57 ▶ push @out, ' Registered : ' . $d->{registered} if $d->{registered};
Branch: 2 branches
BranchTrueFalseTotal
if $d->{"registered"} 2 54 56
if $d->{"registered"} 0 0 0
2580 56 ▶ push @out, ' Expires : ' . $d->{expires} if $d->{expires};
Branch: 2 branches
BranchTrueFalseTotal
if $d->{"expires"} 2 54 56
if $d->{"expires"} 0 0 0
2581 56 ▶ push @out, ' Registrar : ' . _sanitise_output($d->{registrar}) if $d->{registrar};
Branch: 1 branch
BranchTrueFalseTotal
if $d->{"registrar"} 7 49 56
2582 56 ▶ push @out, ' Reg. abuse : ' . _sanitise_output($d->{registrar_abuse}) if $d->{registrar_abuse};
Branch: 1 branch
BranchTrueFalseTotal
if $d->{"registrar_abuse"} 7 46 53
2583 56 ▶ if ($d->{web_ip}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($d->{'web_ip'}) { } 20 34 54
2584 23 push @out, ' Web host IP : ' . _sanitise_output($d->{web_ip});
2585 23 ▶ push @out, ' Web host org : ' . _sanitise_output($d->{web_org}) if $d->{web_org};
Branch: 1 branch
BranchTrueFalseTotal
if $d->{"web_org"} 19 1 20
2586 23 ▶ push @out, ' Web abuse : ' . _sanitise_output($d->{web_abuse}) if $d->{web_abuse};
Branch: 1 branch
BranchTrueFalseTotal
if $d->{"web_abuse"} 19 2 21
2587 } else {
2588 36 push @out, ' Web host : (no A record / unreachable)';
2589 }
2590 56 ▶ if ($d->{mx_host}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($d->{'mx_host'}) { } 3 50 53
2591 6 push @out, ' MX host : ' . _sanitise_output($d->{mx_host});
2592 6 ▶ push @out, ' MX IP : ' . _sanitise_output($d->{mx_ip}) if $d->{mx_ip};
Branch: 1 branch
BranchTrueFalseTotal
if $d->{"mx_ip"} 3 0 3
2593 7 ▶ push @out, ' MX org : ' . _sanitise_output($d->{mx_org}) if $d->{mx_org};
Branch: 1 branch
BranchTrueFalseTotal
if $d->{"mx_org"} 3 0 3
2594 7 ▶ push @out, ' MX abuse : ' . _sanitise_output($d->{mx_abuse}) if $d->{mx_abuse};
Branch: 1 branch
BranchTrueFalseTotal
if $d->{"mx_abuse"} 4 0 4
2595 } else {
2596 54 push @out, ' MX host : (none found)';
2597 }
2598 57 ▶ if ($d->{ns_host}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($d->{"ns_host"}) 2 52 54
2599 6 push @out, ' NS host : ' . _sanitise_output($d->{ns_host});
2600 6 ▶ push @out, ' NS IP : ' . _sanitise_output($d->{ns_ip}) if $d->{ns_ip};
Branch: 1 branch
BranchTrueFalseTotal
if $d->{"ns_ip"} 2 1 3
2601 6 ▶ push @out, ' NS org : ' . _sanitise_output($d->{ns_org}) if $d->{ns_org};
Branch: 1 branch
BranchTrueFalseTotal
if $d->{"ns_org"} 2 1 3
2602 6 ▶ push @out, ' NS abuse : ' . _sanitise_output($d->{ns_abuse}) if $d->{ns_abuse};
Branch: 1 branch
BranchTrueFalseTotal
if $d->{"ns_abuse"} 2 1 3
2603 }
2604 56 push @out, '';
2605 }
2606 } else {
2607 17 push @out, ' (none found)';
2608 17 push @out, '';
2609 }
2610  
2611 # Abuse contacts summary
2612 65 push @out, '[ WHERE TO SEND ABUSE REPORTS ]';
2613 65 my @contacts = $self->abuse_contacts();
2614 65 ▶ if (@contacts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@contacts) { } 34 28 62
2615 37 for my $c (@contacts) {
2616 58 push @out, ' Role : ' . _sanitise_output($c->{role});
2617 58 push @out, ' Send to : ' . _sanitise_output($c->{address});
2618 58 ▶ push @out, ' Note : ' . _sanitise_output($c->{note}) if $c->{note};
Branch: 1 branch
BranchTrueFalseTotal
if $c->{"note"} 54 0 54
2619 58 push @out, " Discovered : $c->{via}";
2620 57 push @out, '';
2621 }
2622 } else {
2623 31 push @out, ' (no abuse contacts could be determined)';
2624 30 push @out, '';
2625 }
2626  
2627 # Web-form contacts (providers that require manual form submission)
2628 64 my @form_cs = $self->form_contacts();
2629 64 ▶ if (@form_cs) {
Branch: 1 branch
BranchTrueFalseTotal
if (@form_cs) 5 58 63
2630 6 push @out, '[ WHERE TO FILE WEB-FORM REPORTS ]';
2631 7 push @out, ' The following parties require manual submission via a web form.';
2632 10 push @out, ' Open each URL in a browser, then follow the instructions below it.';
2633 8 push @out, '';
2634 8 for my $c (@form_cs) {
2635 8 push @out, ' Role : ' . _sanitise_output($c->{role});
2636 8 push @out, ' Form URL : ' . _sanitise_output($c->{form});
2637 8 ▶ push @out, ' Domain/URL : ' . _sanitise_output($c->{form_domain}) if $c->{form_domain};
Branch: 1 branch
BranchTrueFalseTotal
if $c->{"form_domain"} 3 2 5
2638 8 ▶ push @out, ' Note : ' . _sanitise_output($c->{note}) if $c->{note};
Branch: 1 branch
BranchTrueFalseTotal
if $c->{"note"} 3 2 5
2639 6 ▶ if ($c->{form_paste}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->{"form_paste"}) 3 2 5
2640 # Word-wrap the paste hint at ROLE_WRAP_LEN characters
2641 6 my $hint = $c->{form_paste};
2642 6 my @words = split /\s+/, $hint;
2643 7 my (@lines, $line);
2644 7 for my $w (@words) {
2645 93 ▶ if (defined $line && length("$line $w") > $ROLE_WRAP_LEN) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $line and length "$line $w" > $ROLE_WRAP_LEN) { } 6 84 90
Condition50%3/6
defined $line and length "$line $w" > $ROLE_WRAP_LEN
!ll&&!rl&&r
3816
defined $line and length "$line $w" > $ROLE_WRAP_LEN
!ll&&!rl&&r
000
MC/DC100%2/2
defined $line and length "$line $w" > $ROLE_WRAP_LEN
defined $line length "$line $w" > $ROLE_WRAP_LEN
MC/DC0%0/2
defined $line and length "$line $w" > $ROLE_WRAP_LEN
defined $line length "$line $w" > $ROLE_WRAP_LEN
Truth table100%3/3
A and B
A= defined $lineB= length "$line $w" > $ROLE_WRAP_LEN
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= defined $lineB= length "$line $w" > $ROLE_WRAP_LEN
ABresult
0X0
100
111
2646 9 push @lines, $line;
2647 9 $line = $w;
2648 } else {
2649 88 ▶ $line = defined $line ? "$line $w" : $w;
Branch: 1 branch
BranchTrueFalseTotal
defined $line ? : 81 4 85
2650 }
2651 }
2652 7 ▶ push @lines, $line if defined $line;
Branch: 1 branch
BranchTrueFalseTotal
if defined $line 3 0 3
2653 6 ▶ push @out, ' Paste : ' . shift @lines if @lines;
Branch: 1 branch
BranchTrueFalseTotal
if @lines 3 1 4
2654 6 push @out, ' ' . $_ for @lines;
2655 }
2656 6 ▶ push @out, ' Upload : ' . _sanitise_output($c->{form_upload}) if $c->{form_upload};
Branch: 1 branch
BranchTrueFalseTotal
if $c->{"form_upload"} 3 0 3
2657 6 push @out, '';
2658 }
2659 }
2660  
2661 64 push @out, '=' x 72;
2662 64 return join("\n", @out) . "\n";
2663 }
2664  
2665 # -----------------------------------------------------------------------
2666 # Private: output sanitisation
2667 # -----------------------------------------------------------------------
2668  
2669 # _sanitise_output( $str ) -> $str
2670 #
2671 # Purpose:
2672 # Strip control characters that could affect terminal rendering or HTML
2673 # injection from any string that will appear in a report or abuse email.
2674 # Preserves printable ASCII, high-bytes (for UTF-8 content), tabs, and
2675 # line endings.
2676 #
2677 # Entry criteria:
2678 # $str -- a defined or undef scalar.
2679 #
2680 # Exit status:
2681 # Returns the sanitised string, or the empty string if $str is undef.
2682 #
2683 # Notes:
2684 # Only strips C0 control characters below 0x20 (except \t) and the DEL
2685 # character (0x7F). High bytes (0x80-0xFF) are preserved because they
2686 # form valid UTF-8 multi-byte sequences in headers and body text.
2687  
2688 sub _sanitise_output :Private {
2689 1673 ▶ my $str = $_[0];
Subroutine _sanitise_output: called CC=2 SCAR=6.9
Subroutine _sanitise_output: called CC=2 SCAR=6.9
2690 1673 ▶ return '' unless defined $str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 6 1669 1675
2691 # Remove C0 controls (except tab) and DEL
2692 1668 $str =~ s/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]//g;
2693 1668 return $str;
2694 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
2695  
2696 # -----------------------------------------------------------------------
2697 # Private: message parsing
2698 # -----------------------------------------------------------------------
2699  
2700 # _split_message( $text )
2701 #
2702 # Purpose:
2703 # Split a raw RFC 2822 email into headers and body, parse all headers,
2704 # decode the body (including multipart), extract sending-software
2705 # fingerprints, and populate per-hop tracking data.
2706 #
2707 # Entry criteria:
2708 # $text -- defined scalar, already dereferenced by parse_email().
2709 # $self->{_sending_sw} and $self->{_rcvd_tracking} reset to [] by caller.
2710 #
2711 # Exit status:
2712 # Returns undef silently if the header block is empty/whitespace-only.
2713 # Otherwise all results are communicated via side effects on $self.
2714 #
2715 # Side effects:
2716 # Populates _headers, _received, _body_plain, _body_html, _sending_sw,
2717 # and _rcvd_tracking.
2718 #
2719 # Notes:
2720 # Delegates to _decode_multipart() for multipart/* content types.
2721 # Lines not matching the header pattern are silently discarded.
2722 # Boundary extraction uses a simple regex; missing boundary causes the
2723 # body to be skipped silently.
2724  
2725 sub _split_message :Private {
2726 715 ▶ my ($self, $text) = @_;
Subroutine _split_message: called CC=17 SCAR=29.1
Subroutine _split_message: called CC=17 SCAR=29.1
2727  
2728 # Split at the first blank line (RFC 2822 header/body separator)
2729 716 my ($header_block, $body_raw) = split /\r?\n\r?\n/, $text, 2;
2730  
2731 716 ▶ return unless defined $header_block && $header_block =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $header_block and $header_block =~ /\S/ 0 716 716
Condition33%2/6
defined $header_block and $header_block =~ /\S/
!ll&&!rl&&r
10711
defined $header_block and $header_block =~ /\S/
!ll&&!rl&&r
000
MC/DC50%1/2
defined $header_block and $header_block =~ /\S/
defined $header_block $header_block =~ /\S/
MC/DC0%0/2
defined $header_block and $header_block =~ /\S/
defined $header_block $header_block =~ /\S/
Truth table66%2/3
A and B
A= defined $header_blockB= $header_block =~ /\S/
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= defined $header_blockB= $header_block =~ /\S/
ABresult
0X0
100
111
2732 721 ▶ $body_raw //= '';
Condition60%3/5
$body_raw //= ""
l!l
70921
$body_raw //= ""
l!l
00
MC/DC0%0/1
$body_raw //= ""
$body_raw
MC/DC0%0/1
$body_raw //= ""
$body_raw
Truth table50%1/2
A
A= $body_raw
Aresult
11
00
Truth table0%0/2
A
A= $body_raw
Aresult
11
00
2733  
2734 # Unfold RFC 2822 continuation lines (s2.2.3)
2735 721 $header_block =~ s/\r?\n([ \t]+)/ $1/g;
2736  
2737 # Parse each header line into a { name, value } pair
2738 720 my @headers;
2739 720 for my $line (split /\r?\n/, $header_block) {
2740 5643 ▶ if ($line =~ /^([\w-]+)\s*:\s*(.*)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^([\w-]+)\s*:\s*(.*)/) 5632 4 5636
2741 5636 push @headers, { name => lc($1), value => $2 };
2742 }
2743 }
2744 715 $self->{_headers} = \@headers;
2745  
2746 # Collect all Received: header values (most-recent first, as in message)
2747 $self->{_received} = [
2748 1621 map { $_->{value} }
2749 716 grep { $_->{name} eq 'received' } @headers
2750 ];
2751  
2752 # Determine content type and transfer encoding from top-level headers
2753 715 my ($ct_h) = grep { $_->{name} eq 'content-type' } @headers;
2754 714 my ($cte_h) = grep { $_->{name} eq 'content-transfer-encoding' } @headers;
2755 717 ▶ my $ct = defined $ct_h ? $ct_h->{value} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $ct_h ? : 389 324 713
2756 717 ▶ my $cte = defined $cte_h ? $cte_h->{value} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $cte_h ? : 353 360 713
2757  
2758 # Decode multipart or single-part body as appropriate
2759 717 ▶ if ($ct =~ /multipart/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ct =~ /multipart/i) { } 17 696 713
2760 21 my ($boundary) = $ct =~ /boundary="?([^";]+)"?/i;
2761 # Pass depth=0 to enforce the MAX_MULTIPART_DEPTH recursion guard
2762 23 ▶ $self->_decode_multipart($body_raw, $boundary, 0) if $boundary;
Branch: 1 branch
BranchTrueFalseTotal
if $boundary 18 2 20
2763 } else {
2764 698 my $decoded = $self->_decode_body($body_raw, $cte);
2765 698 ▶ if ($ct =~ /html/i) { $self->{_body_html} = $decoded }
Branch: 1 branch
BranchTrueFalseTotal
if ($ct =~ /html/i) { } 9 688 697
2766 690 else { $self->{_body_plain} = $decoded }
2767 }
2768  
2769 $self->_debug(sprintf 'Parsed %d headers, %d Received lines',
2770 716 scalar @headers, scalar @{ $self->{_received} });
2771  
2772 # --- Sending software fingerprints ---
2773 # These headers identify the mailer or shared-hosting script that sent
2774 # the message; invaluable for shared-hosting abuse reports.
2775 717 my %sw_notes = (
2776 'x-php-originating-script' => 'PHP script on shared hosting -- report to hosting abuse team',
2777 'x-source' => 'Source file on shared hosting -- report to hosting abuse team',
2778 'x-source-host' => 'Sending hostname injected by shared hosting provider',
2779 'x-source-args' => 'Command-line args injected by shared hosting provider',
2780 'x-mailer' => 'Email client or bulk-mailer identifier',
2781 'user-agent' => 'Email client identifier',
2782 );
2783 717 for my $sw_hdr (sort keys %sw_notes) {
2784 4272 my ($h) = grep { $_->{name} eq $sw_hdr } @headers;
2785 4271 ▶ next unless $h;
Branch: 1 branch
BranchTrueFalseTotal
unless $h 4244 23 4267
2786 26 push @{ $self->{_sending_sw} }, {
2787 header => $sw_hdr,
2788 value => $h->{value},
2789 28 note => $sw_notes{$sw_hdr},
2790 };
2791 }
2792  
2793 # --- Per-hop tracking IDs from Received: chain ---
2794 # Walk oldest-first (reverse) so _rcvd_tracking is oldest-first
2795 714 for my $rcvd (reverse @{ $self->{_received} }) {
2796 1621 my $ip = $self->_extract_ip_from_received($rcvd);
2797 1621 my ($for_addr) = $rcvd =~ /\bfor\s+<?([^\s>]+\@[\w.-]+\.[\w]+)>?/i;
2798 1617 my ($srv_id) = $rcvd =~ /\bid\s+([\w.-]+)/i;
2799 # Skip hops with no actionable tracking data
2800 1617 ▶ next unless defined $ip || defined $for_addr || defined $srv_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ip or defined $for_addr or defined $srv_id 3 1616 1619
Condition41%5/12
defined $ip or defined $for_addr or defined $srv_id
l!l&&r!l&&!r
161501
defined $ip or defined $for_addr
l!l&&r!l&&!r
161601
defined $ip or defined $for_addr or defined $srv_id
l!l&&r!l&&!r
200
defined $ip or defined $for_addr
l!l&&r!l&&!r
000
MC/DC33%1/3
defined $ip or defined $for_addr or defined $srv_id
defined $ip defined $for_addr defined $srv_id
MC/DC0%0/3
defined $ip or defined $for_addr or defined $srv_id
defined $ip defined $for_addr defined $srv_id
Truth table50%2/4
A or B or C
A= defined $ipB= defined $for_addrC= defined $srv_id
ABCresult
1XX1
01X1
0011
0000
Truth table0%0/4
A or B or C
A= defined $ipB= defined $for_addrC= defined $srv_id
ABCresult
1XX1
01X1
0011
0000
2801 1616 push @{ $self->{_rcvd_tracking} }, {
2802 received => $rcvd,
2803 ip => $ip,
2804 for => $for_addr,
2805 id => $srv_id,
2806 };
2807 }
2808 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
2809  
2810 # _decode_multipart( $body, $boundary, $depth )
2811 #
2812 # Purpose:
2813 # Recursively split a MIME multipart body on its boundary and decode each
2814 # text/plain and text/html part. Nested multipart/* containers are
2815 # recursed into up to MAX_MULTIPART_DEPTH levels deep.
2816 #
2817 # Entry criteria:
2818 # $body -- the raw body text of the multipart container.
2819 # $boundary -- the boundary string from the Content-Type header.
2820 # $depth -- current recursion depth (starts at 0 from _split_message).
2821 #
2822 # Exit status:
2823 # Returns undef if $depth >= MAX_MULTIPART_DEPTH (recursion guard).
2824 # Otherwise all results via side effects.
2825 #
2826 # Side effects:
2827 # Appends decoded text to $self->{_body_plain} and $self->{_body_html}.
2828 #
2829 # Notes:
2830 # Whitespace-only MIME segments between boundaries are silently skipped.
2831 # Decoding errors are silenced; raw bytes are used as fallback.
2832  
2833 sub _decode_multipart :Private {
2834 28 ▶ my ($self, $body, $boundary, $depth) = @_;
Subroutine _decode_multipart: called CC=15 SCAR=28.2
Subroutine _decode_multipart: called CC=15 SCAR=28.2
2835 27 ▶ $depth //= 0;
Condition40%2/5
$depth //= 0
l!l
2807
$depth //= 0
l!l
00
MC/DC100%1/1
$depth //= 0
$depth
MC/DC0%0/1
$depth //= 0
$depth
Truth table100%2/2
A
A= $depth
Aresult
11
00
Truth table0%0/2
A
A= $depth
Aresult
11
00
2836  
2837 # Enforce the recursion depth limit to prevent stack exhaustion on
2838 # pathological crafted messages with deeply nested multipart structures.
2839 27 ▶ if ($depth >= $MAX_MULTIPART_DEPTH) {
Branch: 1 branch
BranchTrueFalseTotal
if ($depth >= $MAX_MULTIPART_DEPTH) 7 22 29
2840 7 Carp::carp 'Email::Abuse::Investigator: multipart nesting depth limit',
2841 "($MAX_MULTIPART_DEPTH) exceeded; stopping recursion";
2842 8 return;
2843 }
2844  
2845 # Split on the boundary marker; the (?:--)? suffix handles closing boundary
2846 22 my @parts = split /--\Q$boundary\E(?:--)?/, $body;
2847  
2848 22 for my $part (@parts) {
2849 # Skip whitespace-only segments between boundaries
2850 69 ▶ next unless $part =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $part =~ /\S/ 39 31 70
2851  
2852 30 $part =~ s/^\r?\n//;
2853  
2854 # Each MIME part has its own headers separated from body by a blank line
2855 30 my ($phdr_block, $pbody) = split /\r?\n\r?\n/, $part, 2;
2856 30 ▶ next unless defined $pbody;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pbody 1 29 30
2857  
2858 # Unfold continuation header lines within this part
2859 29 $phdr_block =~ s/\r?\n([ \t]+)/ $1/g;
2860  
2861 # Parse this part's headers into a simple hash
2862 30 my %phdr;
2863 30 for my $line (split /\r?\n/, $phdr_block) {
2864 32 ▶ $phdr{ lc($1) } = $2 if $line =~ /^([\w-]+)\s*:\s*(.*)/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^([\w-]+)\s*:\s*(.*)/ 29 0 29
2865 }
2866  
2867 30 ▶ my $pct = $phdr{'content-type'} // '';
Condition60%3/5
$phdr{"content-type"} // ""
l!l
25312
$phdr{"content-type"} // ""
l!l
00
MC/DC100%1/1
$phdr{"content-type"} // ""
$phdr{"content-type"}
MC/DC0%0/1
$phdr{"content-type"} // ""
$phdr{"content-type"}
Truth table100%2/2
A
A= $phdr{"content-type"}
Aresult
11
00
Truth table0%0/2
A
A= $phdr{"content-type"}
Aresult
11
00
2868 30 ▶ my $pcte = $phdr{'content-transfer-encoding'} // '';
Condition50%3/6
$phdr{"content-transfer-encoding"} // ""
l!l
1260
$phdr{"content-transfer-encoding"} // ""
l!l
200
MC/DC100%1/1
$phdr{"content-transfer-encoding"} // ""
$phdr{"content-transfer-encoding"}
MC/DC0%0/1
$phdr{"content-transfer-encoding"} // ""
$phdr{"content-transfer-encoding"}
Truth table100%2/2
A
A= $phdr{"content-transfer-encoding"}
Aresult
11
00
Truth table50%1/2
A
A= $phdr{"content-transfer-encoding"}
Aresult
11
00
2869  
2870 # Nested multipart/* must be recursed into; without this URLs in
2871 # multipart/alternative inside multipart/mixed would be missed.
2872 29 ▶ if ($pct =~ /multipart/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pct =~ /multipart/i) 5 24 29
2873 7 my ($inner_boundary) = $pct =~ /boundary\s*=\s*"?([^";]+)"?/i;
2874 7 ▶ if ($inner_boundary) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inner_boundary) 5 0 5
2875 6 $inner_boundary =~ s/\s+$//;
2876 # Increment depth counter for the recursion guard
2877 7 $self->_decode_multipart($pbody, $inner_boundary, $depth + 1);
2878 }
2879 7 next;
2880 }
2881  
2882 # Decode transfer encoding and accumulate by content type
2883 25 my $decoded = $self->_decode_body($pbody, $pcte);
2884 25 ▶ if ($pct =~ /text\/html/i) { $self->{_body_html} .= $decoded }
Branch: 2 branches
BranchTrueFalseTotal
if ($pct =~ m[text/html]i) { } 8 17 25
elsif ($pct =~ /text/i or not $pct) { } 15 1 16
2885 16 ▶ elsif ($pct =~ /text/i || !$pct) { $self->{_body_plain} .= $decoded }
Condition50%3/6
$pct =~ /text/i or not $pct
l!l&&r!l&&!r
1132
$pct =~ /text/i or not $pct
l!l&&r!l&&!r
000
MC/DC100%2/2
$pct =~ /text/i or not $pct
$pct =~ /text/i not $pct
MC/DC0%0/2
$pct =~ /text/i or not $pct
$pct =~ /text/i not $pct
Truth table100%3/3
A or not(B)
A= $pct =~ /text/iB= not $pct
ABresult
1X1
011
000
Truth table0%0/3
A or not(B)
A= $pct =~ /text/iB= not $pct
ABresult
1X1
011
000
2886 }
2887 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
2888  
2889 # _decode_body( $body, $cte ) -> string
2890 #
2891 # Purpose:
2892 # Decode a MIME body part according to its Content-Transfer-Encoding.
2893 #
2894 # Entry criteria:
2895 # $body -- raw body string (may be undef).
2896 # $cte -- Content-Transfer-Encoding value string (may be undef).
2897 #
2898 # Exit status:
2899 # Returns the decoded string, or the original string if the encoding is
2900 # 7bit/8bit/binary or unrecognised.
2901 #
2902 # Notes:
2903 # decode_qp and decode_base64 are imported from MIME:: modules; errors
2904 # from malformed content are silenced by the eval wrappers they provide.
2905  
2906 sub _decode_body :Private {
2907 753 ▶ my ($self, $body, $cte) = @_;
Subroutine _decode_body: called CC=5 SCAR=17.6
Subroutine _decode_body: called CC=5 SCAR=17.6
2908 754 ▶ $cte //= '';
Condition40%2/5
$cte //= ""
l!l
75010
$cte //= ""
l!l
00
MC/DC0%0/1
$cte //= ""
$cte
MC/DC0%0/1
$cte //= ""
$cte
Truth table50%1/2
A
A= $cte
Aresult
11
00
Truth table0%0/2
A
A= $cte
Aresult
11
00
2909 754 ▶ return decode_qp($body) if $cte =~ /quoted-printable/i;
Branch: 1 branch
BranchTrueFalseTotal
if $cte =~ /quoted-printable/i 7 744 751
2910 725 ▶ return decode_base64($body) if $cte =~ /base64/i;
Branch: 1 branch
BranchTrueFalseTotal
if $cte =~ /base64/i 48 742 790
2911 720 ▶ return $body // '';
Condition40%2/5
$body // ""
l!l
74110
$body // ""
l!l
00
MC/DC100%1/1
$body // ""
$body
MC/DC0%0/1
$body // ""
$body
Truth table100%2/2
A
A= $body
Aresult
11
00
Truth table0%0/2
A
A= $body
Aresult
11
00
2912 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
2913  
2914 # -----------------------------------------------------------------------
2915 # Private: Received-chain -> originating IP
2916 # -----------------------------------------------------------------------
2917  
2918 # _find_origin()
2919 #
2920 # Purpose:
2921 # Walk the Received: chain (oldest-first) to find the first external IP,
2922 # or fall back to X-Originating-IP. Enrich with rDNS and WHOIS.
2923 #
2924 # Entry criteria:
2925 # $self->{_received} populated by _split_message().
2926 # $self->{trusted_relays} set by new().
2927 #
2928 # Exit status:
2929 # Returns { ip, rdns, org, abuse, country, confidence, note } on success.
2930 # Returns undef if no usable IP can be identified.
2931 #
2932 # Side effects:
2933 # Network I/O via _enrich_ip(): one PTR lookup, one RDAP/WHOIS query.
2934 # Results are also stored in the CHI cross-message cache if available.
2935 #
2936 # Notes:
2937 # confidence 'high' = 2+ distinct external IPs;
2938 # 'medium' = exactly one external IP;
2939 # 'low' = taken from X-Originating-IP.
2940  
2941 sub _find_origin :Private {
2942 444 ▶ my $self = $_[0];
Subroutine _find_origin: called CC=9 SCAR=22.0
Subroutine _find_origin: called CC=9 SCAR=22.0
2943  
2944 442 my @candidates;
2945  
2946 # Walk oldest-first (reverse) to collect external IPs
2947 488 for my $hdr (reverse @{ $self->{_received} }) {
2948 1367 ▶ my $ip = $self->_extract_ip_from_received($hdr) // next;
Condition50%3/6
$self->_extract_ip_from_received($hdr) // (next)
l!l
1341240
$self->_extract_ip_from_received($hdr) // (next)
l!l
200
MC/DC100%1/1
$self->_extract_ip_from_received($hdr) // (next)
$self->_extract_ip_from_received($hdr)
MC/DC0%0/1
$self->_extract_ip_from_received($hdr) // (next)
$self->_extract_ip_from_received($hdr)
Truth table100%2/2
A
A= $self->_extract_ip_from_received($hdr)
Aresult
11
00
Truth table50%1/2
A
A= $self->_extract_ip_from_received($hdr)
Aresult
11
00
2949 1367 ▶ next if $self->_is_private($ip);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_is_private($ip) 1204 162 1366
2950 168 ▶ next if $self->_is_trusted($ip);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_is_trusted($ip) 31 134 165
2951 161 push @candidates, $ip;
2952 }
2953  
2954 # Fall back to X-Originating-IP if no external IPs in Received: chain
2955 446 ▶ unless (@candidates) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@candidates) 310 133 443
2956 318 my $xoip = $self->_header_value('x-originating-ip');
2957 316 ▶ if ($xoip) {
Branch: 1 branch
BranchTrueFalseTotal
if ($xoip) 26 284 310
2958 34 $xoip =~ s/[\[\]\s]//g;
2959 34 ▶ return $self->_enrich_ip($xoip, 'low',
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_is_private($xoip) 7 6 13
2960 'Taken from X-Originating-IP (webmail, unverified)')
2961 unless $self->_is_private($xoip);
2962 }
2963 306 return;
2964 }
2965  
2966 # Report the oldest (first) external IP; confidence depends on count
2967 151 ▶ return $self->_enrich_ip(
Branch: 1 branch
BranchTrueFalseTotal
@candidates > 1 ? : 7 127 134
2968 $candidates[0],
2969 @candidates > 1 ? 'high' : 'medium',
2970 'First external hop in Received: chain',
2971 );
2972 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
2973  
2974 # _extract_ip_from_received( $hdr ) -> ipv4_or_ipv6_string | undef
2975 #
2976 # Purpose:
2977 # Extract the most-significant IP address from a raw Received: header
2978 # value, trying patterns in priority order. Supports both IPv4 dotted-
2979 # quad and IPv6 bracket notation.
2980 #
2981 # Entry criteria:
2982 # $hdr -- a defined Received: header value string.
2983 #
2984 # Exit status:
2985 # Returns the IP string on success, undef if no IP can be extracted.
2986 #
2987 # Notes:
2988 # IPv4 addresses are validated (all octets <= 255).
2989 # IPv6 addresses are returned as-is if they contain colons.
2990  
2991 sub _extract_ip_from_received :Private {
2992 2994 ▶ my ($self, $hdr) = @_;
Subroutine _extract_ip_from_received: called CC=6 SCAR=17.9
Subroutine _extract_ip_from_received: called CC=6 SCAR=17.9
2993 2994 for my $re (@RECEIVED_IP_RE) {
2994 3140 ▶ if ($hdr =~ $re) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hdr =~ /$re/) 2998 122 3120
2995 3002 my $ip = $1;
2996  
2997 # Accept IPv6 addresses (contain colons) without further validation
2998 3004 ▶ return $ip if $ip =~ /:/;
Branch: 1 branch
BranchTrueFalseTotal
if $ip =~ /:/ 5 2996 3001
2999  
3000 # Validate IPv4 format and octet range
3001 2999 ▶ next unless $ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ 26 2972 2998
3002 2973 ▶ next if grep { $_ > 255 } split /\./, $ip;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$_ > 255;} split(/\./, $ip, 0) 8 2963 2971
3003 2962 return $ip;
3004 }
3005 }
3006 9 return;
3007 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3008  
3009 # _is_private( $ip ) -> bool
3010 #
3011 # Purpose:
3012 # Test whether an IP address falls in any private, reserved, or special-
3013 # use range (IPv4 or IPv6) that should never be reported as a spam origin.
3014 #
3015 # Entry criteria:
3016 # $ip -- a scalar IP string (IPv4 or IPv6); may be undef.
3017 #
3018 # Exit status:
3019 # Returns 1 (true) if the IP is private/reserved, 0 (false) otherwise.
3020 # Returns 1 for undef or empty strings.
3021 #
3022 # Notes:
3023 # Uses the module-level @PRIVATE_RANGES array of pre-compiled regexes.
3024 # Covers all ranges listed in RFC 1122, 1918, 5737, 6598, and RFC 4193.
3025  
3026 sub _is_private :Private {
3027 1384 ▶ my ($self, $ip) = @_;
Subroutine _is_private: called CC=5 SCAR=16.5
Subroutine _is_private: called CC=5 SCAR=16.5
3028 1384 ▶ return 1 if !defined($ip) || $ip eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $ip or $ip eq "" 2 1382 1384
Condition50%3/6
not defined $ip or $ip eq ""
l!l&&r!l&&!r
311380
not defined $ip or $ip eq ""
l!l&&r!l&&!r
000
MC/DC100%2/2
not defined $ip or $ip eq ""
not defined $ip $ip eq ""
MC/DC0%0/2
not defined $ip or $ip eq ""
not defined $ip $ip eq ""
Truth table100%3/3
not(A) or B
A= not defined $ipB= $ip eq ""
ABresult
1X1
011
000
Truth table0%0/3
not(A) or B
A= not defined $ipB= $ip eq ""
ABresult
1X1
011
000
3029 1381 ▶ for my $re (@PRIVATE_RANGES) { return 1 if $ip =~ $re }
Branch: 1 branch
BranchTrueFalseTotal
if $ip =~ /$re/ 1230 6649 7879
3030 151 return 0;
3031 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3032  
3033 # _is_trusted( $ip ) -> bool
3034 #
3035 # Purpose:
3036 # Test whether an IP address matches any entry in the caller-supplied
3037 # trusted_relays list (exact IP or CIDR block).
3038 #
3039 # Entry criteria:
3040 # $ip -- a defined IPv4 address string.
3041 # $self->{trusted_relays} -- arrayref of exact IPs or CIDR strings.
3042 #
3043 # Exit status:
3044 # Returns 1 (true) if the IP matches any trusted relay, 0 otherwise.
3045  
3046 sub _is_trusted :Private {
3047 145 ▶ my ($self, $ip) = @_;
Subroutine _is_trusted: called CC=3 SCAR=11.0
Subroutine _is_trusted: called CC=3 SCAR=11.0
3048 146 for my $cidr (@{ $self->{trusted_relays} }) {
3049 20 ▶ return 1 if $self->_ip_in_cidr($ip, $cidr);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_ip_in_cidr($ip, $cidr) 8 12 20
3050 }
3051 139 return 0;
3052 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3053  
3054 # -----------------------------------------------------------------------
3055 # Private: HTTP/HTTPS URL extraction and resolution
3056 # -----------------------------------------------------------------------
3057  
3058 # _extract_and_resolve_urls() -> arrayref of url hashrefs
3059 #
3060 # Purpose:
3061 # Extract all HTTP/HTTPS URLs from the decoded body, resolve each unique
3062 # hostname to an IP, and enrich with WHOIS/RDAP data. Optionally uses
3063 # AnyEvent::DNS to parallelise the DNS resolution step.
3064 #
3065 # Entry criteria:
3066 # $self->{_body_plain} and $self->{_body_html} populated by _split_message().
3067 #
3068 # Exit status:
3069 # Returns an arrayref of url hashrefs (possibly empty).
3070 #
3071 # Side effects:
3072 # Network I/O per unique hostname: one A/AAAA lookup, one RDAP/WHOIS.
3073 # Results stored in the CHI cross-message cache if available.
3074  
3075 sub _extract_and_resolve_urls :Private {
3076 228 ▶ my $self = $_[0];
Subroutine _extract_and_resolve_urls: called CC=27 SCAR=38.9
Subroutine _extract_and_resolve_urls: called CC=27 SCAR=38.9
3077 227 my (%url_seen, %host_cache);
3078 228 my @results;
3079 228 my $combined = $self->{_body_plain} . "\n" . $self->{_body_html};
3080  
3081 # Collect unique URLs from body
3082 227 my @urls = grep { !$url_seen{$_}++ } $self->_extract_http_urls($combined);
3083  
3084 # For URL-shortener and redirect-cloaker hosts, follow the redirect chain to
3085 # discover the real destination (e.g. GCS bucket → phishing landing page).
3086 # Done before DNS resolution so that destination hostnames can be parallelised.
3087 # _follow_redirect_chain() is a :Protected seam that handles LWP availability
3088 # internally — do not guard this block with $HAS_LWP so the seam can be
3089 # stubbed unconditionally in tests regardless of whether LWP is installed.
3090 228 for my $url (@urls) {
3091 644 my ($host) = $url =~ m{https?://([^/:?\s#]+)}i;
3092 643 ▶ next unless $host;
Branch: 1 branch
BranchTrueFalseTotal
unless $host 0 642 642
3093 643 my $bare = lc $host;
3094 644 $bare =~ s/^www\.//;
3095 next unless $URL_SHORTENERS{$bare}
3096 644 ▶ || ($self->{url_shorteners} && $self->{url_shorteners}{$bare})
Branch: 1 branch
BranchTrueFalseTotal
unless $URL_SHORTENERS{$bare} or $self->{"url_shorteners"} and $self->{"url_shorteners"}{$bare} or $self->_is_redirect_cloaker($bare) 634 9 643
Condition38%7/18
$URL_SHORTENERS{$bare} or $self->{"url_shorteners"} and $self->{"url_shorteners"}{$bare} or $self->_is_redirect_cloaker($bare)
l!l&&r!l&&!r
71634
$URL_SHORTENERS{$bare} or $self->{"url_shorteners"} and $self->{"url_shorteners"}{$bare}
l!l&&r!l&&!r
92636
$self->{"url_shorteners"} and $self->{"url_shorteners"}{$bare}
!ll&&!rl&&r
63700
$URL_SHORTENERS{$bare} or $self->{"url_shorteners"} and $self->{"url_shorteners"}{$bare} or $self->_is_redirect_cloaker($bare)
l!l&&r!l&&!r
000
$URL_SHORTENERS{$bare} or $self->{"url_shorteners"} and $self->{"url_shorteners"}{$bare}
l!l&&r!l&&!r
000
$self->{"url_shorteners"} and $self->{"url_shorteners"}{$bare}
!ll&&!rl&&r
000
MC/DC50%2/4
$URL_SHORTENERS{$bare} or $self->{"url_shorteners"} and $self->{"url_shorteners"}{$bare} or $self->_is_redirect_cloaker($bare)
$URL_SHORTENERS{$bare} $self->{"url_shorteners"} $self->{"url_shorteners"}{$bare} $self->_is_redirect_cloaker($bare)
MC/DC0%0/4
$URL_SHORTENERS{$bare} or $self->{"url_shorteners"} and $self->{"url_shorteners"}{$bare} or $self->_is_redirect_cloaker($bare)
$URL_SHORTENERS{$bare} $self->{"url_shorteners"} $self->{"url_shorteners"}{$bare} $self->_is_redirect_cloaker($bare)
Truth table50%3/6
A or B and C or D
A= $URL_SHORTENERS{$bare}B= $self->{"url_shorteners"}C= $self->{"url_shorteners"}{$bare}D= $self->_is_redirect_cloaker($bare)
ABCDresult
1XXX1
011X1
00X11
01011
00X00
01000
Truth table0%0/6
A or B and C or D
A= $URL_SHORTENERS{$bare}B= $self->{"url_shorteners"}C= $self->{"url_shorteners"}{$bare}D= $self->_is_redirect_cloaker($bare)
ABCDresult
1XXX1
011X1
00X11
01011
00X00
01000
3097 || $self->_is_redirect_cloaker($bare);
3098 9 my $dest = $self->_follow_redirect_chain($url);
3099 9 ▶ next unless defined $dest && !$url_seen{$dest}++;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dest and not $url_seen{$dest}++ 4 5 9
Condition66%4/6
defined $dest and not $url_seen{$dest}++
!ll&&!rl&&r
404
defined $dest and not $url_seen{$dest}++
!ll&&!rl&&r
440
MC/DC50%1/2
defined $dest and not $url_seen{$dest}++
defined $dest not $url_seen{$dest}++
MC/DC0%0/2
defined $dest and not $url_seen{$dest}++
defined $dest not $url_seen{$dest}++
Truth table66%2/3
A and not(B)
A= defined $destB= not $url_seen{$dest}++
ABresult
0X0
100
111
Truth table0%0/3
A and not(B)
A= defined $destB= not $url_seen{$dest}++
ABresult
0X0
100
111
3100 5 push @urls, $dest;
3101 }
3102  
3103 # Extract unique hostnames for parallel DNS resolution (including redirect destinations)
3104 227 my %hostname_needed;
3105 227 for my $url (@urls) {
3106 643 my ($host) = $url =~ m{https?://([^/:?\s#]+)}i;
3107 643 ▶ $hostname_needed{$host}++ if $host;
Branch: 1 branch
BranchTrueFalseTotal
if $host 642 0 642
3108 }
3109  
3110 # Parallelise DNS lookups if AnyEvent::DNS is available
3111 227 ▶ if ($HAS_ANYEVENT_DNS && scalar(keys %hostname_needed) > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($HAS_ANYEVENT_DNS and scalar keys %hostname_needed > 1) 0 226 226
Condition50%3/6
$HAS_ANYEVENT_DNS and scalar keys %hostname_needed > 1
!ll&&!rl&&r
22601
$HAS_ANYEVENT_DNS and scalar keys %hostname_needed > 1
!ll&&!rl&&r
400
MC/DC0%0/2
$HAS_ANYEVENT_DNS and scalar keys %hostname_needed > 1
$HAS_ANYEVENT_DNS scalar keys %hostname_needed > 1
MC/DC0%0/2
$HAS_ANYEVENT_DNS and scalar keys %hostname_needed > 1
$HAS_ANYEVENT_DNS scalar keys %hostname_needed > 1
Truth table33%1/3
A and B
A= $HAS_ANYEVENT_DNSB= scalar keys %hostname_needed > 1
ABresult
0X0
100
111
Truth table33%1/3
A and B
A= $HAS_ANYEVENT_DNSB= scalar keys %hostname_needed > 1
ABresult
0X0
100
111
3112 1 $self->_parallel_resolve_hosts(\%hostname_needed, \%host_cache);
3113 }
3114  
3115 # Process each URL: resolve hostname and WHOIS-enrich
3116 227 for my $url (@urls) {
3117 643 my ($host) = $url =~ m{https?://([^/:?\s#]+)}i;
3118 643 ▶ next unless $host;
Branch: 1 branch
BranchTrueFalseTotal
unless $host 0 642 642
3119  
3120 # Resolve and WHOIS once per unique hostname, then cache the result
3121 643 ▶ unless (exists $host_cache{$host}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $host_cache{$host}) 126 517 643
3122 # Check the cross-message CHI cache first
3123 126 ▶ my $cached = $_cache ? $_cache->get("url:$host") : undef;
Branch: 1 branch
BranchTrueFalseTotal
$_cache ? : 126 0 126
3124 126 ▶ if ($cached) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cached) { } 29 97 126
3125 30 $host_cache{$host} = $cached;
3126 } else {
3127 97 ▶ my $ip = $self->_resolve_host($host) // '(unresolved)';
Condition40%2/5
$self->_resolve_host($host) // "(unresolved)"
l!l
58380
$self->_resolve_host($host) // "(unresolved)"
l!l
00
MC/DC100%1/1
$self->_resolve_host($host) // "(unresolved)"
$self->_resolve_host($host)
MC/DC0%0/1
$self->_resolve_host($host) // "(unresolved)"
$self->_resolve_host($host)
Truth table100%2/2
A
A= $self->_resolve_host($host)
Aresult
11
00
Truth table0%0/2
A
A= $self->_resolve_host($host)
Aresult
11
00
3128 97 ▶ my $whois = $ip ne '(unresolved)'
Branch: 1 branch
BranchTrueFalseTotal
$ip ne '(unresolved)' ? : 58 38 96
3129 ? $self->_whois_ip($ip)
3130 : {};
3131  
3132 # Fall back to domain WHOIS if IP lookup returned nothing
3133 97 ▶ if (!$whois->{abuse}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($whois->{"abuse"}) 47 49 96
3134 48 ▶ my $reg = _registrable($host) // $host;
Condition16%1/6
_registrable($host) // $host
l!l&&r!l&&!r
4700
_registrable($host) // $host
l!l&&r!l&&!r
000
MC/DC0%0/2
_registrable($host) // $host
_registrable($host) $host
MC/DC0%0/2
_registrable($host) // $host
_registrable($host) $host
Truth table33%1/3
A // B
A= _registrable($host)B= $host
ABresult
1X1
011
000
Truth table0%0/3
A // B
A= _registrable($host)B= $host
ABresult
1X1
011
000
3135 48 my $dw = $self->_parse_domain_whois_abuse($reg);
3136 48 ▶ $whois = $dw if $dw->{abuse};
Branch: 1 branch
BranchTrueFalseTotal
if $dw->{"abuse"} 6 41 47
3137 }
3138  
3139 my $entry = {
3140 ip => $ip,
3141 org => $whois->{org} // '(unknown)',
3142 abuse => $whois->{abuse} // '(unknown)',
3143 country => $whois->{country} // undef,
3144 97 ▶ };
Condition46%7/15
$whois->{"org"} // "(unknown)"
l!l
56402
$whois->{"abuse"} // "(unknown)"
l!l
55410
$whois->{"country"} // undef
l!l
690
$whois->{"org"} // "(unknown)"
l!l
00
$whois->{"abuse"} // "(unknown)"
l!l
000
$whois->{"country"} // undef
l!l
00
MC/DC100%1/1
$whois->{"org"} // "(unknown)"
$whois->{"org"}
MC/DC100%1/1
$whois->{"abuse"} // "(unknown)"
$whois->{"abuse"}
MC/DC100%1/1
$whois->{"country"} // undef
$whois->{"country"}
MC/DC0%0/1
$whois->{"org"} // "(unknown)"
$whois->{"org"}
MC/DC0%0/1
$whois->{"abuse"} // "(unknown)"
$whois->{"abuse"}
MC/DC0%0/1
$whois->{"country"} // undef
$whois->{"country"}
Truth table100%2/2
A
A= $whois->{"org"}
Aresult
11
00
Truth table100%2/2
A
A= $whois->{"abuse"}
Aresult
11
00
Truth table100%2/2
A
A= $whois->{"country"}
Aresult
11
00
Truth table0%0/2
A
A= $whois->{"org"}
Aresult
11
00
Truth table0%0/2
A
A= $whois->{"abuse"}
Aresult
11
00
Truth table0%0/2
A
A= $whois->{"country"}
Aresult
11
00
3145 98 $host_cache{$host} = $entry;
3146  
3147 # Store in cross-message cache for reuse across messages
3148 98 ▶ $_cache->set("url:$host", $entry) if $_cache;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache 96 0 96
3149 }
3150 }
3151  
3152 658 push @results, { url => $url, host => $host, %{ $host_cache{$host} } };
3153 }
3154 242 return \@results;
3155 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3156  
3157 # _is_redirect_cloaker( $bare_host ) -> bool
3158 #
3159 # Purpose:
3160 # Return true if $bare_host is a known cloud-storage or CDN host that is
3161 # commonly abused to serve client-side redirect pages hiding the real
3162 # phishing destination. Checks the exact-match %REDIRECT_HOSTS table and
3163 # the suffix patterns in @REDIRECT_HOST_SUFFIXES.
3164 #
3165 # Entry criteria:
3166 # $bare_host -- lowercase hostname with any leading "www." already stripped.
3167 #
3168 # Exit status:
3169 # Returns 1 (true) or empty string (false).
3170  
3171 sub _is_redirect_cloaker :Private {
3172 714 ▶ my (undef, $host) = @_;
Subroutine _is_redirect_cloaker: called CC=5 SCAR=17.8
Subroutine _is_redirect_cloaker: called CC=5 SCAR=17.8
3173 714 ▶ return 1 if $REDIRECT_HOSTS{$host};
Branch: 1 branch
BranchTrueFalseTotal
if $REDIRECT_HOSTS{$host} 2 696 698
3174 712 for my $suffix (@REDIRECT_HOST_SUFFIXES) {
3175 4192 ▶ return 1 if length($host) > length($suffix)
Branch: 1 branch
BranchTrueFalseTotal
if length $host > length $suffix and substr($host, -length($suffix)) eq $suffix 0 4176 4176
Condition33%2/6
length $host > length $suffix and substr($host, -length($suffix)) eq $suffix
!ll&&!rl&&r
260115750
length $host > length $suffix and substr($host, -length($suffix)) eq $suffix
!ll&&!rl&&r
000
MC/DC0%0/2
length $host > length $suffix and substr($host, -length($suffix)) eq $suffix
length $host > length $suffix substr($host, -length($suffix)) eq $suffix
MC/DC0%0/2
length $host > length $suffix and substr($host, -length($suffix)) eq $suffix
length $host > length $suffix substr($host, -length($suffix)) eq $suffix
Truth table66%2/3
A and B
A= length $host > length $suffixB= substr($host, -length($suffix)) eq $suffix
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= length $host > length $suffixB= substr($host, -length($suffix)) eq $suffix
ABresult
0X0
100
111
3176 && substr($host, -length($suffix)) eq $suffix;
3177 }
3178 787 return '';
3179 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3180  
3181 # _follow_redirect_chain( $url ) -> $final_url | undef
3182 #
3183 # Purpose:
3184 # Follow up to $REDIRECT_MAX_HOPS HTTP hops for a given URL and return the
3185 # final destination. Detects HTTP 3xx Location: redirects, HTML
3186 # <meta http-equiv="refresh" content="...url=..."> tags, and
3187 # window.location.replace() / window.location.href JavaScript patterns.
3188 # Used to expose the real phishing landing page hidden behind a cloud
3189 # object-store redirect page (e.g. a GCS bucket containing only a
3190 # meta-refresh pointing to the attacker-controlled domain).
3191 #
3192 # Entry criteria:
3193 # $url -- an https?:// URL string whose host has already been identified
3194 # as a URL shortener or redirect cloaker.
3195 # LWP::UserAgent must be installed ($HAS_LWP must be true).
3196 #
3197 # Exit status:
3198 # Returns the first URL that differs from the input after following the
3199 # chain, or undef if no redirect was found or LWP is unavailable.
3200 # Never returns the input $url unchanged.
3201 #
3202 # Side effects:
3203 # Up to $REDIRECT_MAX_HOPS HTTP GET requests.
3204 # Successful result cached in the cross-message CHI cache keyed
3205 # "redirect:<url>" to avoid re-fetching across messages.
3206  
3207 sub _follow_redirect_chain :Protected {
3208 95 ▶ my ($self, $url) = @_;
Subroutine _follow_redirect_chain: called CC=18 SCAR=29.3
Subroutine _follow_redirect_chain: called CC=18 SCAR=29.3
3209 79 ▶ return undef unless $HAS_LWP;
Branch: 1 branch
BranchTrueFalseTotal
unless $HAS_LWP 0 4 4
3210  
3211 # Serve from cache when available
3212 79 ▶ if ($_cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_cache) 4 0 4
3213 79 my $cached = $_cache->get("redirect:$url");
3214 20 ▶ return $cached if defined $cached;
Branch: 1 branch
BranchTrueFalseTotal
if defined $cached 16 78 94
3215 }
3216  
3217 # Dedicated no-follow UA so we can inspect each redirect hop manually.
3218 # Stored separately from the RDAP UA ($self->{ua}) which needs auto-follow.
3219 20 ▶ unless (defined $self->{_ua_nofollow}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"_ua_nofollow"}) 7 71 78
3220 my $ua = LWP::UserAgent->new(
3221 timeout => $self->{timeout},
3222 20 agent => "Email-Abuse-Investigator/$VERSION",
3223 max_redirect => 0,
3224 );
3225 20 ▶ if ($HAS_CONN_CACHE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($HAS_CONN_CACHE) 14 5 19
3226 20 my $cc = LWP::ConnCache->new();
3227 17 $cc->total_capacity(4);
3228 17 $ua->conn_cache($cc);
3229 }
3230 24 $ua->env_proxy(1);
3231 12 $self->{_ua_nofollow} = $ua;
3232 }
3233 22 my $ua = $self->{_ua_nofollow};
3234  
3235 22 my $current = $url;
3236 22 my $final;
3237 20 for my $hop (1 .. $REDIRECT_MAX_HOPS) {
3238 27 my $res = eval { $ua->get($current) };
3239 27 ▶ last unless $res;
Branch: 1 branch
BranchTrueFalseTotal
unless $res 15 9 24
3240  
3241 27 ▶ if ($res->is_redirect()) {
Branch: 2 branches
BranchTrueFalseTotal
if ($res->is_redirect) { } 20 4 24
elsif ($res->is_success) { } 5 14 19
3242 # HTTP 3xx: extract Location header
3243 23 my $loc = $res->header('Location');
3244 21 ▶ last unless defined $loc;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $loc 17 5 22
3245  
3246 # Resolve relative Location URLs against the current base
3247 8 ▶ if ($loc !~ m{^https?://}i) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($loc =~ m[^https?://]i) 15 7 22
3248 18 require URI;
3249 18 $loc = URI->new_abs($loc, $current)->as_string();
3250 }
3251 23 $final = $loc;
3252 7 $current = $loc;
3253 } elsif ($res->is_success()) {
3254 # 2xx: inspect body for client-side redirect patterns
3255 5 ▶ my $body = $res->decoded_content() // '';
Condition20%1/5
$res->decoded_content // ""
l!l
100
$res->decoded_content // ""
l!l
00
MC/DC0%0/1
$res->decoded_content // ""
$res->decoded_content
MC/DC0%0/1
$res->decoded_content // ""
$res->decoded_content
Truth table50%1/2
A
A= $res->decoded_content
Aresult
11
00
Truth table0%0/2
A
A= $res->decoded_content
Aresult
11
00
3256 4 my $dest;
3257  
3258 # <meta http-equiv="refresh" content="N; url=https://...">
3259 4 ▶ if ($body =~ m{<meta[^>]+http-equiv\s*=\s*["']?refresh["']?[^>]+
Branch: 2 branches
BranchTrueFalseTotal
if ($body =~ m[<meta[^>]+http-equiv\s*=\s*["']?refresh["']?[^>]+ content\s*=\s*["'][^"']*url\s*=\s*(https?://[^"'\s>]+)]xi) { } 15 3 18
elsif ($body =~ m[window\.location(?:\.replace\s*\(\s*|\.href\s*=\s*) ["'](https?://[^"']+)["']]xi) { } 2 16 18
3260 content\s*=\s*["'][^"']*url\s*=\s*(https?://[^"'\s>]+)}xi) {
3261 3 $dest = $1;
3262 }
3263 # window.location.replace("...") or window.location.href = "..."
3264 elsif ($body =~ m{window\.location(?:\.replace\s*\(\s*|\.href\s*=\s*)
3265 ["'](https?://[^"']+)["']}xi) {
3266 17 $dest = $1;
3267 }
3268  
3269 19 ▶ last unless defined $dest;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dest 14 4 18
3270 25 $final = $dest;
3271 7 $current = $dest;
3272 } else {
3273 9 last;
3274 }
3275 }
3276  
3277 # Cache for reuse across messages in this session
3278 10 ▶ $_cache->set("redirect:$url", $final) if $_cache && defined $final;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache and defined $final 4 17 21
Condition33%2/6
$_cache and defined $final
!ll&&!rl&&r
013
$_cache and defined $final
!ll&&!rl&&r
000
MC/DC50%1/2
$_cache and defined $final
$_cache defined $final
MC/DC0%0/2
$_cache and defined $final
$_cache defined $final
Truth table66%2/3
A and B
A= $_cacheB= defined $final
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $_cacheB= defined $final
ABresult
0X0
100
111
3279  
3280 10 return $final;
3281 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3282  
3283 # _parallel_resolve_hosts( \%hostnames, \%cache )
3284 #
3285 # Purpose:
3286 # Resolve multiple hostnames to IPs in parallel using AnyEvent::DNS.
3287 # Populates the cache with resolved IPs so the sequential loop in
3288 # _extract_and_resolve_urls() can skip the DNS step for pre-resolved hosts.
3289 #
3290 # Entry criteria:
3291 # $hostnames_ref -- hashref keyed by hostname (values ignored).
3292 # $cache_ref -- hashref to populate with { ip => '...' } results.
3293 # AnyEvent::DNS must be installed ($HAS_ANYEVENT_DNS is true).
3294 #
3295 # Exit status:
3296 # Returns undef; all results written to %$cache_ref via side effects.
3297 #
3298 # Notes:
3299 # Errors (NXDOMAIN, timeout) are silently swallowed; the sequential
3300 # resolution loop will return '(unresolved)' for those hosts.
3301  
3302 sub _parallel_resolve_hosts :Private {
3303 6 ▶ my ($self, $hostnames_ref, $cache_ref) = @_;
Subroutine _parallel_resolve_hosts: called CC=4 SCAR=15.2
Subroutine _parallel_resolve_hosts: called CC=4 SCAR=15.2
3304 # Guard both conditions together: an empty hash must never reach condvar
3305 # creation because $cv->recv would block forever with $pending == 0.
3306 6 ▶ return unless $HAS_ANYEVENT_DNS && %$hostnames_ref;
Branch: 1 branch
BranchTrueFalseTotal
unless $HAS_ANYEVENT_DNS and %$hostnames_ref 1 0 1
Condition0%0/6
$HAS_ANYEVENT_DNS and %$hostnames_ref
!ll&&!rl&&r
000
$HAS_ANYEVENT_DNS and %$hostnames_ref
!ll&&!rl&&r
000
MC/DC0%0/2
$HAS_ANYEVENT_DNS and %$hostnames_ref
$HAS_ANYEVENT_DNS %$hostnames_ref
MC/DC0%0/2
$HAS_ANYEVENT_DNS and %$hostnames_ref
$HAS_ANYEVENT_DNS %$hostnames_ref
Truth table0%0/3
A and B
A= $HAS_ANYEVENT_DNSB= %$hostnames_ref
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $HAS_ANYEVENT_DNSB= %$hostnames_ref
ABresult
0X0
100
111
3307  
3308 # Build an AnyEvent condvar to wait for all lookups to complete
3309 2 my $cv = AnyEvent->condvar;
3310 2 my $pending = scalar keys %$hostnames_ref;
3311  
3312 # AnyEvent::DNS::resolve is a method, not a standalone function.
3313 # Use the global resolver singleton; passing a bare string as the
3314 # first arg would make Perl treat the hostname as the invocant.
3315 16 my $resolver = AnyEvent::DNS::resolver();
3316  
3317 18 for my $host (keys %$hostnames_ref) {
3318 # Fire an async A query for each hostname
3319 $resolver->resolve(
3320 $host, 'a',
3321 sub {
3322 8 ▶ my @answers = @_;
Subroutine __ANON__: called CC=3 SCAR=11.0
3323 8 ▶ if (@answers) {
Branch: 1 branch
BranchTrueFalseTotal
if (@answers) 5 0 5
3324 # Cache the first A record result
3325 13 $cache_ref->{$host} = { ip => $answers[0][4] };
3326 }
3327 # Decrement the pending counter; signal when all done
3328 13 ▶ $cv->send if --$pending <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if --$pending <= 0 7 12 19
3329 },
3330 18 );
3331 }
3332  
3333 # Block until all DNS queries complete (subject to AnyEvent's own timeouts)
3334 8 $cv->recv;
3335 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3336  
3337 # _extract_http_urls( $body ) -> list of url strings
3338 #
3339 # Purpose:
3340 # Extract all HTTP and HTTPS URLs from a body string, using both
3341 # structural HTML parsing (if HTML::LinkExtor is available) and a
3342 # plain-text regex pass. Deduplicates and strips trailing punctuation.
3343 #
3344 # Entry criteria:
3345 # $body -- combined plain+HTML body string.
3346 #
3347 # Exit status:
3348 # Returns a list of URL strings (possibly empty), deduplicated.
3349  
3350 sub _extract_http_urls :Private {
3351 238 ▶ my ($self, $body) = @_;
Subroutine _extract_http_urls: called CC=5 SCAR=16.1
Subroutine _extract_http_urls: called CC=5 SCAR=16.1
3352 238 my @urls;
3353  
3354 # Structural HTML link extraction (handles quoted attributes correctly)
3355 240 ▶ if ($HAS_HTML_LINKEXTOR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($HAS_HTML_LINKEXTOR) 237 6 243
3356 my $p = HTML::LinkExtor->new(sub {
3357 25 ▶ my ($tag, %attrs) = @_;
Subroutine __ANON__: called CC=5 SCAR=16.1
3358 25 for my $attr (qw(href src action)) {
3359 57 ▶ my $val = $attrs{$attr} // '';
Condition66%2/3
$attrs{$attr} // ""
l!l
17320
MC/DC100%1/1
$attrs{$attr} // ""
$attrs{$attr}
Truth table100%2/2
A
A= $attrs{$attr}
Aresult
11
00
3360 56 ▶ if ($val =~ m{^https?://}i) {
Branch: 2 branches
BranchTrueFalseTotal
if ($val =~ m[^https?://]i) { } 14 44 58
elsif ($val =~ m[^//[\w.-]]) { } 10 34 44
3361 14 push @urls, $val;
3362 } elsif ($val =~ m{^//[\w.-]}) {
3363 # Protocol-relative -- assume https
3364 4 push @urls, 'https:' . $val;
3365 }
3366 }
3367 240 });
3368 237 $p->parse($body);
3369 }
3370  
3371 # Plain-text regex pass for bare URLs not in HTML attributes
3372 231 ▶ while ($body =~ m{(https?://[^\s<>"'\)\]]+)}gi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body =~ m<(https?://[^\s<>"'\)\]]+)>gi) 1141 240 1381
3373 1149 push @urls, $1;
3374 }
3375  
3376 # Protocol-relative URLs not caught above
3377 238 ▶ while ($body =~ m{(?:^|[\s"'=])(//[\w.-][^\s<>"'\)\]]*)}gim) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body =~ m<(?:^|[\s"'=])(//[\w.-][^\s<>"'\)\]]*)>mig) 10 229 239
3378 11 push @urls, 'https:' . $1;
3379 }
3380  
3381 # Deduplicate and strip trailing punctuation
3382 238 my %seen;
3383 238 my @all = grep { !$seen{$_}++ } @urls;
3384 238 s/[.,;:!?\)>\]]+$// for @all;
3385 238 return @all;
3386 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3387  
3388 # -----------------------------------------------------------------------
3389 # Private: domain extraction and full analysis
3390 # -----------------------------------------------------------------------
3391  
3392 # _extract_and_analyse_domains() -> arrayref of domain hashrefs
3393 #
3394 # Purpose:
3395 # Collect all non-infrastructure contact domains from headers and body,
3396 # run the full domain intelligence pipeline on each, and return an arrayref
3397 # suitable for storage in $self->{_mailto_domains}.
3398 #
3399 # Entry criteria:
3400 # _split_message() must have been called.
3401 #
3402 # Exit status:
3403 # Always returns an arrayref; never undef.
3404 #
3405 # Side effects:
3406 # Network I/O per domain via _analyse_domain().
3407 # Results stored in $self->{_domain_info} and CHI cache.
3408  
3409 sub _extract_and_analyse_domains :Private {
3410 221 ▶ my $self = $_[0];
Subroutine _extract_and_analyse_domains: called CC=26 SCAR=33.1
Subroutine _extract_and_analyse_domains: called CC=26 SCAR=33.1
3411 221 my (%seen, @domains_with_source);
3412  
3413 # Build a set of recipient domains to exclude (victims, not senders)
3414 221 my %recipient_domains;
3415 228 for my $hname (qw(to cc)) {
3416 440 ▶ my $val = $self->_header_value($hname) // next;
Condition50%2/4
$self->_header_value($hname) // (next)
l!l
195229
$self->_header_value($hname) // (next)
l!l
00
MC/DC100%1/1
$self->_header_value($hname) // (next)
$self->_header_value($hname)
MC/DC0%0/1
$self->_header_value($hname) // (next)
$self->_header_value($hname)
Truth table100%2/2
A
A= $self->_header_value($hname)
Aresult
11
00
Truth table0%0/2
A
A= $self->_header_value($hname)
Aresult
11
00
3417 211 for my $dom ($self->_domains_from_text($val)) {
3418 208 ▶ my $reg = _registrable($dom) // $dom;
Condition16%1/6
_registrable($dom) // $dom
l!l&&r!l&&!r
19200
_registrable($dom) // $dom
l!l&&r!l&&!r
000
MC/DC0%0/2
_registrable($dom) // $dom
_registrable($dom) $dom
MC/DC0%0/2
_registrable($dom) // $dom
_registrable($dom) $dom
Truth table33%1/3
A // B
A= _registrable($dom)B= $dom
ABresult
1X1
011
000
Truth table0%0/3
A // B
A= _registrable($dom)B= $dom
ABresult
1X1
011
000
3419 221 $recipient_domains{$dom}++;
3420 221 $recipient_domains{$reg}++;
3421 }
3422 }
3423  
3424 # Also exclude domains from Received: "for" envelope recipients
3425 241 for my $hop (@{ $self->{_rcvd_tracking} }) {
3426 230 ▶ next unless $hop->{for} && $hop->{for} =~ /\@([\w.-]+)/;
Branch: 1 branch
BranchTrueFalseTotal
unless $hop->{"for"} and $hop->{"for"} =~ /\@([\w.-]+)/ 207 4 211
Condition66%2/3
$hop->{"for"} and $hop->{"for"} =~ /\@([\w.-]+)/
!ll&&!rl&&r
19902
MC/DC50%1/2
$hop->{"for"} and $hop->{"for"} =~ /\@([\w.-]+)/
$hop->{"for"} $hop->{"for"} =~ /\@([\w.-]+)/
Truth table66%2/3
A and B
A= $hop->{"for"}B= $hop->{"for"} =~ /\@([\w.-]+)/
ABresult
0X0
100
111
3427 31 my $dom = lc $1;
3428 31 ▶ my $reg = _registrable($dom) // $dom;
Condition33%1/3
_registrable($dom) // $dom
l!l&&r!l&&!r
300
MC/DC0%0/2
_registrable($dom) // $dom
_registrable($dom) $dom
Truth table33%1/3
A // B
A= _registrable($dom)B= $dom
ABresult
1X1
011
000
3429 31 $recipient_domains{$dom}++;
3430 31 $recipient_domains{$reg}++;
3431 }
3432  
3433 # Inner closure: record a domain if it passes all filters
3434 my $record = sub {
3435 810 ▶ my ($dom, $source) = @_;
Subroutine __ANON__: called CC=9 SCAR=22.0
3436 810 $dom = lc $dom;
3437 825 $dom =~ s/\.$//;
3438 825 ▶ next if $self->{trusted_domains}->{$dom};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"trusted_domains"}{$dom} 3 834 837
3439 811 ▶ return if $TRUSTED_DOMAINS{$dom};
Branch: 1 branch
BranchTrueFalseTotal
if $TRUSTED_DOMAINS{$dom} 46 791 837
3440 768 ▶ return if $recipient_domains{$dom};
Branch: 1 branch
BranchTrueFalseTotal
if $recipient_domains{$dom} 10 784 794
3441 766 ▶ return if $recipient_domains{ _registrable($dom) // $dom };
Branch: 1 branch
BranchTrueFalseTotal
if $recipient_domains{_registrable($dom) // $dom} 8 764 772
Condition100%3/3
_registrable($dom) // $dom
l!l&&r!l&&!r
668971
MC/DC0%0/2
_registrable($dom) // $dom
_registrable($dom) $dom
Truth table66%2/3
A // B
A= _registrable($dom)B= $dom
ABresult
1X1
011
000
3442 # Discard non-routable hostnames (single-label, pseudo-TLDs, etc.)
3443 766 ▶ return unless $dom =~ /\.[a-zA-Z]{2,}$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $dom =~ /\.[a-zA-Z]{2,}$/ 105 667 772
3444 669 ▶ return if $dom =~ /\.(?:local|internal|lan|localdomain|arpa)$/i;
Branch: 1 branch
BranchTrueFalseTotal
if $dom =~ /\.(?:local|internal|lan|localdomain|arpa)$/i 3 692 695
3445 667 ▶ return if $seen{$dom}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$dom}++ 192 474 666
3446 476 push @domains_with_source, { domain => $dom, source => $source };
3447 221 };
3448  
3449 # Collect from standard sender/reply headers
3450 221 my %header_sources = (
3451 'from' => 'From: header',
3452 'reply-to' => 'Reply-To: header',
3453 'return-path' => 'Return-Path: header',
3454 'sender' => 'Sender: header',
3455 );
3456 221 for my $hname (sort keys %header_sources) {
3457 869 ▶ my $val = $self->_header_value($hname) // next;
Condition100%2/2
$self->_header_value($hname) // (next)
l!l
374474
MC/DC100%1/1
$self->_header_value($hname) // (next)
$self->_header_value($hname)
Truth table100%2/2
A
A= $self->_header_value($hname)
Aresult
11
00
3458 $record->($_, $header_sources{$hname})
3459 403 for $self->_domains_from_text($val);
3460 }
3461  
3462 # Message-ID domain often reveals the real bulk-sending platform
3463 214 my $mid = $self->_header_value('message-id');
3464 214 ▶ if ($mid && $mid =~ /\@([\w.-]+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mid and $mid =~ /\@([\w.-]+)/) 201 19 220
Condition66%2/3
$mid and $mid =~ /\@([\w.-]+)/
!ll&&!rl&&r
180194
MC/DC50%1/2
$mid and $mid =~ /\@([\w.-]+)/
$mid $mid =~ /\@([\w.-]+)/
Truth table66%2/3
A and B
A= $midB= $mid =~ /\@([\w.-]+)/
ABresult
0X0
100
111
3465 196 my $mid_dom = lc $1;
3466 196 ▶ my $mid_reg = _registrable($mid_dom) // $mid_dom;
Condition66%2/3
_registrable($mid_dom) // $mid_dom
l!l&&r!l&&!r
97970
MC/DC0%0/2
_registrable($mid_dom) // $mid_dom
_registrable($mid_dom) $mid_dom
Truth table66%2/3
A // B
A= _registrable($mid_dom)B= $mid_dom
ABresult
1X1
011
000
3467 $record->($mid_dom, 'Message-ID: header')
3468 222 ▶ unless $TRUSTED_DOMAINS{$mid_dom} || $TRUSTED_DOMAINS{$mid_reg} || $self->{trusted_domains}->{$mid_dom} || $self->{trusted_domains}->{$mid_reg};
Branch: 1 branch
BranchTrueFalseTotal
unless $TRUSTED_DOMAINS{$mid_dom} or $TRUSTED_DOMAINS{$mid_reg} or $self->{"trusted_domains"}{$mid_dom} or $self->{"trusted_domains"}{$mid_reg} 207 2 209
Condition66%6/9
$TRUSTED_DOMAINS{$mid_dom} or $TRUSTED_DOMAINS{$mid_reg} or $self->{"trusted_domains"}{$mid_dom} or $self->{"trusted_domains"}{$mid_reg}
l!l&&r!l&&!r
40192
$TRUSTED_DOMAINS{$mid_dom} or $TRUSTED_DOMAINS{$mid_reg} or $self->{"trusted_domains"}{$mid_dom}
l!l&&r!l&&!r
20192
$TRUSTED_DOMAINS{$mid_dom} or $TRUSTED_DOMAINS{$mid_reg}
l!l&&r!l&&!r
02192
MC/DC25%1/4
$TRUSTED_DOMAINS{$mid_dom} or $TRUSTED_DOMAINS{$mid_reg} or $self->{"trusted_domains"}{$mid_dom} or $self->{"trusted_domains"}{$mid_reg}
$TRUSTED_DOMAINS{$mid_dom} $TRUSTED_DOMAINS{$mid_reg} $self->{"trusted_domains"}{$mid_dom} $self->{"trusted_domains"}{$mid_reg}
Truth table40%2/5
A or B or C or D
A= $TRUSTED_DOMAINS{$mid_dom}B= $TRUSTED_DOMAINS{$mid_reg}C= $self->{"trusted_domains"}{$mid_dom}D= $self->{"trusted_domains"}{$mid_reg}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
3469 }
3470  
3471 # DKIM signing domain(s) -- the organisation that vouches for the message
3472 241 my $auth = $self->_parse_auth_results_cached();
3473 214 ▶ for my $dkim_d (@{ $auth->{dkim_domains} // [] }) {
Condition100%2/2
$auth->{"dkim_domains"} // []
l!l
6206
MC/DC100%1/1
$auth->{"dkim_domains"} // []
$auth->{"dkim_domains"}
Truth table100%2/2
A
A= $auth->{"dkim_domains"}
Aresult
11
00
3474 10 $record->($dkim_d, 'DKIM-Signature: d= (signing domain)');
3475 }
3476  
3477 # List-Unsubscribe identifies the ESP or bulk sender
3478 214 my $unsub = $self->_header_value('list-unsubscribe');
3479 241 ▶ if ($unsub) {
Branch: 1 branch
BranchTrueFalseTotal
if ($unsub) 4 236 240
3480 3 ▶ while ($unsub =~ m{https?://([^/:?\s>]+)}gi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($unsub =~ m[https?://([^/:?\s>]+)]gi) 4 27 31
3481 2 $record->(lc $1, 'List-Unsubscribe: header');
3482 }
3483 18 ▶ while ($unsub =~ m{mailto:[^@\s>]+\@([\w.-]+)}gi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($unsub =~ /mailto:[^\@\s>]+\@([\w.-]+)/gi) 4 27 31
3484 17 $record->(lc $1, 'List-Unsubscribe: header');
3485 }
3486 }
3487  
3488 # Body email addresses (mailto: and bare user@domain forms)
3489 228 my $combined = $self->{_body_plain} . "\n" . $self->{_body_html};
3490 $record->($_, 'email address / mailto in body')
3491 228 for $self->_domains_from_text($combined);
3492  
3493 # Run the full intelligence pipeline on each collected domain
3494 237 my @results;
3495 237 for my $entry (@domains_with_source) {
3496 499 my $info = $self->_analyse_domain($entry->{domain});
3497 499 push @results, { %$entry, %$info };
3498 }
3499 237 return \@results;
3500 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3501  
3502 # _domains_from_text( $text ) -> list of domain strings
3503 #
3504 # Purpose:
3505 # Extract unique domain names from mailto: links and bare user@domain
3506 # addresses in a block of text.
3507 #
3508 # Entry criteria:
3509 # $text -- a defined scalar of decoded body or header text.
3510 #
3511 # Exit status:
3512 # Returns a list of lower-cased domain strings (possibly empty).
3513  
3514 sub _domains_from_text :Private {
3515 973 ▶ my ($self, $text) = @_;
Subroutine _domains_from_text: called CC=5 SCAR=16.1
Subroutine _domains_from_text: called CC=5 SCAR=16.1
3516 973 my (%seen, @out);
3517  
3518 # mailto: links (including HTML-entity-encoded @ signs from QP)
3519 973 ▶ while ($text =~ /mailto:(?:[^@\s<>"]+)@([\w.-]+)/gi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /mailto:(?:[^\@\s<>"]+)@([\w.-]+)/gi) 14 971 985
3520 15 my $dom = lc $1; $dom =~ s/\.$//;
3521 15 ▶ push @out, $dom unless $seen{$dom}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$dom}++ 13 1 14
3522 }
3523  
3524 # Bare user@domain patterns
3525 973 ▶ while ($text =~ /\b[\w.+%-]+@([\w.-]+\.[a-zA-Z]{2,})\b/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /\b[\w.+%-]+@([\w.-]+\.[a-zA-Z]{2,})\b/g) 840 998 1838
3526 871 my $dom = lc $1; $dom =~ s/\.$//;
3527 842 ▶ push @out, $dom unless $seen{$dom}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$dom}++ 818 22 840
3528 }
3529 1001 return @out;
3530 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3531  
3532 # _analyse_domain( $domain ) -> hashref
3533 #
3534 # Purpose:
3535 # Run the complete intelligence pipeline for a single domain: A record
3536 # (web hosting), MX record (mail hosting), NS record (DNS hosting),
3537 # and WHOIS (registrar, creation/expiry dates, abuse contact).
3538 # Each IP is enriched via RDAP/WHOIS. Results are cached per domain
3539 # in $self->{_domain_info} and in the CHI cross-message cache.
3540 #
3541 # Entry criteria:
3542 # $domain -- lower-cased, no trailing dot, not in TRUSTED_DOMAINS.
3543 # $self->{timeout} used for all network operations.
3544 #
3545 # Exit status:
3546 # Always returns a hashref reference; never undef; may be empty ({}).
3547 # Possible keys: web_ip, web_org, web_abuse, mx_host, mx_ip, mx_org,
3548 # mx_abuse, ns_host, ns_ip, ns_org, ns_abuse, registrar,
3549 # registrar_abuse, registered, expires, recently_registered, whois_raw.
3550 #
3551 # Side effects:
3552 # Network I/O; writes result to $self->{_domain_info}{$domain} and CHI.
3553 #
3554 # Notes:
3555 # MX/NS lookups require Net::DNS; absent without it.
3556 # recently_registered is set to 1 (not 0) when the threshold is met.
3557 # whois_raw is truncated to WHOIS_RAW_MAX bytes.
3558  
3559 sub _analyse_domain :Private {
3560 479 ▶ my ($self, $domain) = @_;
Subroutine _analyse_domain: called CC=33 SCAR=35.1
Subroutine _analyse_domain: called CC=33 SCAR=35.1
3561  
3562 # Return the per-message cached result if already analysed
3563 return $self->{_domain_info}{$domain}
3564 479 ▶ if $self->{_domain_info}{$domain};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_domain_info"}{$domain} 5 473 478
3565  
3566 # Check the cross-message CHI cache before hitting the network
3567 475 ▶ if ($_cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_cache) 474 0 474
3568 475 my $cached = $_cache->get("dom:$domain");
3569 475 ▶ if ($cached) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cached) 180 308 488
3570 181 $self->{_domain_info}{$domain} = $cached;
3571 181 return $cached;
3572 }
3573 }
3574  
3575 309 $self->_debug("Analysing domain: $domain");
3576 310 my %info;
3577  
3578 # --- A record -> web hosting IP ---
3579 310 my $web_ip = $self->_resolve_host($domain);
3580 310 ▶ if ($web_ip) {
Branch: 1 branch
BranchTrueFalseTotal
if ($web_ip) 49 283 332
3581 27 $info{web_ip} = $web_ip;
3582 27 my $w = $self->_whois_ip($web_ip);
3583 27 ▶ $info{web_org} = $w->{org} if $w->{org};
Branch: 1 branch
BranchTrueFalseTotal
if $w->{"org"} 23 17 40
3584 32 ▶ $info{web_abuse} = $w->{abuse} if $w->{abuse};
Branch: 1 branch
BranchTrueFalseTotal
if $w->{"abuse"} 22 4 26
3585 }
3586  
3587 # MX and NS lookups require Net::DNS
3588 315 ▶ if ($HAS_NET_DNS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($HAS_NET_DNS) 1 308 309
3589 my $res = Net::DNS::Resolver->new(
3590 tcp_timeout => $self->{timeout},
3591 udp_timeout => $self->{timeout},
3592 6 );
3593  
3594 # --- MX record -> mail hosting ---
3595 6 ▶ if(my $mxq = $res->search($domain, 'MX')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $mxq = $res->search($domain, "MX")) 1 0 1
3596 2 my ($best) = sort { $a->preference <=> $b->preference }
3597 6 grep { $_->type eq 'MX' } $mxq->answer;
3598 2 ▶ if ($best) {
Branch: 1 branch
BranchTrueFalseTotal
if ($best) 2 29 31
3599 2 (my $mx_host = lc $best->exchange) =~ s/\.$//;
3600 2 $info{mx_host} = $mx_host;
3601 2 my $mx_ip = $self->_resolve_host($mx_host);
3602 1 ▶ if ($mx_ip) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mx_ip) 28 1 29
3603 2 $info{mx_ip} = $mx_ip;
3604 1 my $mw = $self->_whois_ip($mx_ip);
3605 1 ▶ $info{mx_org} = $mw->{org} if $mw->{org};
Branch: 1 branch
BranchTrueFalseTotal
if $mw->{"org"} 1 0 1
3606 2 ▶ $info{mx_abuse} = $mw->{abuse} if $mw->{abuse};
Branch: 1 branch
BranchTrueFalseTotal
if $mw->{"abuse"} 1 0 1
3607 }
3608 }
3609 }
3610  
3611 # --- NS record -> DNS hosting ---
3612 2 ▶ if(my $nsq = $res->search($domain, 'NS')) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $nsq = $res->search($domain, "NS")) 1 0 1
3613 # Sort alphabetically so DNS round-robin ordering never changes which
3614 # nameserver we record -- both runs of the same domain always agree.
3615 2 my ($first) = sort { $a->nsdname cmp $b->nsdname } grep { $_->type eq 'NS' } $nsq->answer;
3616 2 ▶ if ($first) {
Branch: 1 branch
BranchTrueFalseTotal
if ($first) 1 5 6
3617 2 (my $ns_host = lc $first->nsdname) =~ s/\.$//;
3618 2 $info{ns_host} = $ns_host;
3619 2 my $ns_ip = $self->_resolve_host($ns_host);
3620 1 ▶ if ($ns_ip) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ns_ip) 0 5 5
3621 2 $info{ns_ip} = $ns_ip;
3622 2 my $nw = $self->_whois_ip($ns_ip);
3623 2 ▶ $info{ns_org} = $nw->{org} if $nw->{org};
Branch: 1 branch
BranchTrueFalseTotal
if $nw->{"org"} 1 0 1
3624 1 ▶ $info{ns_abuse} = $nw->{abuse} if $nw->{abuse};
Branch: 1 branch
BranchTrueFalseTotal
if $nw->{"abuse"} 1 0 1
3625 }
3626 }
3627 }
3628 }
3629  
3630 # --- Domain WHOIS -> registrar + dates ---
3631 309 ▶ if(my $domain_whois = $self->_domain_whois($domain)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $domain_whois = $self->_domain_whois($domain)) 21 288 309
3632 # Truncate raw WHOIS for storage but parse structured fields from full text
3633 21 $info{whois_raw} = substr($domain_whois, 0, $WHOIS_RAW_MAX);
3634  
3635 # Registrar name
3636 21 ▶ if ($domain_whois =~ /Registrar:\s*(.+)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($domain_whois =~ /Registrar:\s*(.+)/i) 16 5 21
3637 17 ($info{registrar} = $1) =~ s/\s+$//;
3638 }
3639  
3640 # Registrar abuse contact email (try multiple field names)
3641 22 for my $pat (
3642 qr/Registrar Abuse Contact Email:\s*(\S+@\S+)/i,
3643 qr/Abuse Contact Email:\s*(\S+@\S+)/i,
3644 qr/abuse-contact:\s*(\S+@\S+)/i,
3645 ) {
3646 62 ▶ if (!$info{registrar_abuse} && $domain_whois =~ $pat) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $info{"registrar_abuse"} and $domain_whois =~ /$pat/) 14 47 61
Condition100%3/3
not $info{"registrar_abuse"} and $domain_whois =~ /$pat/
!ll&&!rl&&r
242413
MC/DC100%2/2
not $info{"registrar_abuse"} and $domain_whois =~ /$pat/
not $info{"registrar_abuse"} $domain_whois =~ /$pat/
Truth table100%3/3
not(A) and B
A= not $info{"registrar_abuse"}B= $domain_whois =~ /$pat/
ABresult
0X0
100
111
3647 15 ($info{registrar_abuse} = $1) =~ s/\s+$//;
3648 }
3649 }
3650  
3651 # Domain creation date (multiple registrar field name variations)
3652 21 for my $pat (
3653 qr/Creation Date:\s*(\S+)/i,
3654 qr/Created(?:\s+On)?:\s*(\S+)/i,
3655 qr/Registration Time:\s*(\S+)/i,
3656 qr/^registered:\s*(\S+)/im,
3657 ) {
3658 81 ▶ if (!$info{registered} && $domain_whois =~ $pat) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $info{"registered"} and $domain_whois =~ /$pat/) 15 66 81
Condition100%3/3
not $info{"registered"} and $domain_whois =~ /$pat/
!ll&&!rl&&r
353114
MC/DC100%2/2
not $info{"registered"} and $domain_whois =~ /$pat/
not $info{"registered"} $domain_whois =~ /$pat/
Truth table100%3/3
not(A) and B
A= not $info{"registered"}B= $domain_whois =~ /$pat/
ABresult
0X0
100
111
3659 15 ($info{registered} = $1) =~ s/[TZ].*//;
3660 }
3661 }
3662  
3663 # Domain expiry date
3664 21 for my $pat (
3665 qr/Registry Expiry Date:\s*(\S+)/i,
3666 qr/Expir(?:y|ation)(?: Date)?:\s*(\S+)/i,
3667 qr/paid-till:\s*(\S+)/i,
3668 ) {
3669 61 ▶ if (!$info{expires} && $domain_whois =~ $pat) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $info{"expires"} and $domain_whois =~ /$pat/) 13 48 61
Condition100%3/3
not $info{"expires"} and $domain_whois =~ /$pat/
!ll&&!rl&&r
202812
MC/DC100%2/2
not $info{"expires"} and $domain_whois =~ /$pat/
not $info{"expires"} $domain_whois =~ /$pat/
Truth table100%3/3
not(A) and B
A= not $info{"expires"}B= $domain_whois =~ /$pat/
ABresult
0X0
100
111
3670 13 ($info{expires} = $1) =~ s/[TZ].*//;
3671 }
3672 }
3673  
3674 # Flag recently-registered domains (< RECENT_REG_DAYS old)
3675 21 ▶ if ($info{registered}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($info{"registered"}) 14 7 21
3676 15 my $epoch = $self->_parse_date_to_epoch($info{registered});
3677 16 ▶ $info{recently_registered} = 1
Branch: 1 branch
BranchTrueFalseTotal
if $epoch and time - $epoch < $RECENT_REG_DAYS * $SECS_PER_DAY 7 8 15
Condition66%2/3
$epoch and time - $epoch < $RECENT_REG_DAYS * $SECS_PER_DAY
!ll&&!rl&&r
086
MC/DC50%1/2
$epoch and time - $epoch < $RECENT_REG_DAYS * $SECS_PER_DAY
$epoch time - $epoch < $RECENT_REG_DAYS * $SECS_PER_DAY
Truth table66%2/3
A and B
A= $epochB= time - $epoch < $RECENT_REG_DAYS * $SECS_PER_DAY
ABresult
0X0
100
111
3678 if $epoch && (time() - $epoch) < $RECENT_REG_DAYS * $SECS_PER_DAY;
3679 }
3680 }
3681  
3682 # Store in per-message and cross-message caches
3683 310 $self->{_domain_info}{$domain} = \%info;
3684 310 ▶ $_cache->set("dom:$domain", \%info) if $_cache;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache 308 1 309
3685  
3686 310 return \%info;
3687 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3688  
3689 # -----------------------------------------------------------------------
3690 # Private: DNS helpers
3691 # -----------------------------------------------------------------------
3692  
3693 # _resolve_host( $host ) -> ip_string | undef
3694 #
3695 # Purpose:
3696 # Resolve a hostname to an IPv4 (or IPv6) address. Uses Net::DNS for
3697 # both A and AAAA queries when available; falls back to inet_aton for
3698 # pure IPv4 resolution.
3699 #
3700 # Entry criteria:
3701 # $host -- hostname string or already-numeric IP.
3702 #
3703 # Exit status:
3704 # Returns the first resolved IP string, or undef on failure.
3705 #
3706 # Notes:
3707 # When the input is already a dotted-quad IPv4 it is returned immediately.
3708 # AAAA records are tried if the A query fails and Net::DNS is available.
3709  
3710 sub _resolve_host :Protected {
3711 10 ▶ my ($self, $host) = @_;
Subroutine _resolve_host: called CC=14 SCAR=26.8
Subroutine _resolve_host: called CC=14 SCAR=26.8
3712 10 ▶ return $host if $host =~ /^\d{1,3}(?:\.\d{1,3}){3}$/;
Branch: 1 branch
BranchTrueFalseTotal
if $host =~ /^\d{1,3}(?:\.\d{1,3}){3}$/ 1 7 8
3713  
3714 # Check the CHI cache before hitting DNS
3715 9 ▶ if ($_cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_cache) 7 0 7
3716 9 my $cached_ip = $_cache->get("resolve:$host");
3717 9 ▶ return $cached_ip if defined $cached_ip;
Branch: 1 branch
BranchTrueFalseTotal
if defined $cached_ip 1 7 8
3718 }
3719  
3720 9 my $ip;
3721  
3722 9 ▶ if ($HAS_NET_DNS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($HAS_NET_DNS) { } 1 7 8
3723 my $res = Net::DNS::Resolver->new(
3724 tcp_timeout => $self->{timeout},
3725 udp_timeout => $self->{timeout},
3726 2 );
3727  
3728 # Try A record first, then AAAA for IPv6
3729 2 for my $type (qw(A AAAA)) {
3730 1 my $query = $res->search($host, $type);
3731 2 ▶ if ($query) {
Branch: 1 branch
BranchTrueFalseTotal
if ($query) 0 1 1
3732 2 for my $rr ($query->answer) {
3733 2 ▶ if ($rr->type eq 'A') {
Branch: 2 branches
BranchTrueFalseTotal
if ($rr->type eq 'A') { } 1 0 1
elsif ($rr->type eq 'AAAA') { } 0 1 1
3734 2 $ip = $rr->address;
3735 2 last;
3736 } elsif ($rr->type eq 'AAAA') {
3737 2 $ip = $rr->address;
3738 2 last;
3739 }
3740 }
3741 }
3742 2 ▶ last if defined $ip;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ip 1 0 1
3743 }
3744 } else {
3745 # Fallback: gethostbyname (IPv4 only)
3746 9 my $packed = eval { inet_aton($host) };
3747 9 ▶ $ip = $packed ? inet_ntoa($packed) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$packed ? : 1 7 8
3748 }
3749  
3750 # Cache the result (including undef as '' to avoid repeated failed lookups)
3751 9 ▶ if ($_cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_cache) 8 0 8
3752 8 ▶ $_cache->set("resolve:$host", $ip // '');
Condition66%2/3
$ip // ""
l!l
380
MC/DC100%1/1
$ip // ""
$ip
Truth table100%2/2
A
A= $ip
Aresult
11
00
3753 }
3754  
3755 8 return $ip;
3756 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3757  
3758 # _reverse_dns( $ip ) -> hostname | undef
3759 #
3760 # Purpose:
3761 # Perform a PTR (reverse DNS) lookup for an IP address. Supports both
3762 # IPv4 and IPv6 via Net::DNS when available; falls back to gethostbyaddr.
3763 #
3764 # Entry criteria:
3765 # $ip -- a defined IPv4 or IPv6 address string.
3766 #
3767 # Exit status:
3768 # Returns the PTR hostname string, or undef if no record exists.
3769  
3770 sub _reverse_dns :Protected {
3771 24 ▶ my ($self, $ip) = @_;
Subroutine _reverse_dns: called CC=6 SCAR=18.2
Subroutine _reverse_dns: called CC=6 SCAR=18.2
3772 23 ▶ return unless $ip;
Branch: 1 branch
BranchTrueFalseTotal
unless $ip 1 22 23
3773  
3774 23 ▶ if ($HAS_NET_DNS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($HAS_NET_DNS) 0 24 24
3775 2 my $res = Net::DNS::Resolver->new(tcp_timeout => $self->{timeout});
3776 2 my $query = $res->search($ip, 'PTR');
3777 2 ▶ if ($query) {
Branch: 1 branch
BranchTrueFalseTotal
if ($query) 0 2 2
3778 2 for my $rr ($query->answer) {
3779 3 ▶ return $rr->ptrdname if $rr->type eq 'PTR';
Branch: 1 branch
BranchTrueFalseTotal
if $rr->type eq "PTR" 0 2 2
3780 }
3781 }
3782 3 return;
3783 }
3784  
3785 # Fallback for IPv4 only
3786 25 return scalar gethostbyaddr(inet_aton($ip), AF_INET);
3787 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3788  
3789 # -----------------------------------------------------------------------
3790 # Private: WHOIS / RDAP
3791 # -----------------------------------------------------------------------
3792  
3793 # _whois_ip( $ip ) -> hashref
3794 #
3795 # Purpose:
3796 # Enrich an IP address with organisation name, abuse contact, and country
3797 # code. Tries RDAP first (if LWP is available), then falls back to raw
3798 # WHOIS via IANA referral. Results are cached in CHI if available.
3799 #
3800 # Entry criteria:
3801 # $ip -- a defined IPv4 or IPv6 address string.
3802 #
3803 # Exit status:
3804 # Returns { org, abuse, country } hashref; keys absent when unknown.
3805  
3806 sub _whois_ip :Protected {
3807 26 ▶ my ($self, $ip) = @_;
Subroutine _whois_ip: called CC=10 SCAR=23.1
Subroutine _whois_ip: called CC=10 SCAR=23.1
3808  
3809 # Check CHI cache before going to the network
3810 28 ▶ if ($_cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_cache) 25 2 27
3811 28 my $cached = $_cache->get("whois_ip:$ip");
3812 28 ▶ return $cached if $cached;
Branch: 1 branch
BranchTrueFalseTotal
if $cached 18 9 27
3813 }
3814  
3815 10 ▶ my $result = $HAS_LWP ? $self->_rdap_lookup($ip) : {};
Branch: 1 branch
BranchTrueFalseTotal
$HAS_LWP ? : 8 1 9
3816  
3817 # Fall back to raw WHOIS if RDAP returned no organisation
3818 10 ▶ unless ($result->{org}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result->{"org"}) 4 4 8
3819 5 my $raw = $self->_raw_whois($ip, 'whois.iana.org');
3820 5 ▶ if ($raw) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw) 3 1 4
3821 4 my ($ref) = $raw =~ /whois:\s*([\w.-]+)/i;
3822 4 ▶ my $detail = $ref ? $self->_raw_whois($ip, $ref) : $raw;
Branch: 1 branch
BranchTrueFalseTotal
$ref ? : 1 3 4
3823 5 ▶ $result = $self->_parse_whois_text($detail) if $detail;
Branch: 1 branch
BranchTrueFalseTotal
if $detail 2 0 2
3824 }
3825 }
3826  
3827 # Cache the enrichment result
3828 8 ▶ $_cache->set("whois_ip:$ip", $result) if $_cache && $result;
Branch: 1 branch
BranchTrueFalseTotal
if $_cache and $result 7 0 7
Condition66%2/3
$_cache and $result
!ll&&!rl&&r
307
MC/DC50%1/2
$_cache and $result
$_cache $result
Truth table66%2/3
A and B
A= $_cacheB= $result
ABresult
0X0
100
111
3829  
3830 8 return $result;
3831 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3832  
3833 # _domain_whois( $domain ) -> raw_whois_string | undef
3834 #
3835 # Purpose:
3836 # Perform a two-step WHOIS lookup for a domain: first ask IANA for the
3837 # TLD's authoritative WHOIS server, then query that server.
3838 #
3839 # Entry criteria:
3840 # $domain -- a lower-cased domain name string.
3841 #
3842 # Exit status:
3843 # Returns the raw WHOIS response string, or undef on failure.
3844  
3845 sub _domain_whois :Protected {
3846 12 ▶ my ($self, $domain) = @_;
Subroutine _domain_whois: called CC=3 SCAR=11.0
Subroutine _domain_whois: called CC=3 SCAR=11.0
3847 12 ▶ my $iana = $self->_raw_whois($domain, 'whois.iana.org') // return;
Condition66%2/3
$self->_raw_whois($domain, "whois.iana.org") // (return)
l!l
740
MC/DC100%1/1
$self->_raw_whois($domain, "whois.iana.org") // (return)
$self->_raw_whois($domain, "whois.iana.org")
Truth table100%2/2
A
A= $self->_raw_whois($domain, "whois.iana.org")
Aresult
11
00
3848 10 my ($server) = $iana =~ /whois:\s*([\w.-]+)/i;
3849 10 ▶ return unless $server;
Branch: 1 branch
BranchTrueFalseTotal
unless $server 6 1 7
3850 2 return $self->_raw_whois($domain, $server);
3851 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3852  
3853 # _parse_domain_whois_abuse( $domain ) -> hashref
3854 #
3855 # Purpose:
3856 # Lightweight domain WHOIS lookup to extract only registrar name and
3857 # abuse contact. Used as a fallback in _extract_and_resolve_urls() when
3858 # a URL host cannot be resolved to an IP.
3859 #
3860 # Entry criteria:
3861 # $domain -- a registrable domain name string.
3862 #
3863 # Exit status:
3864 # Returns { org, abuse } hashref; empty hashref on failure.
3865  
3866 sub _parse_domain_whois_abuse :Private {
3867 51 ▶ my ($self, $domain) = @_;
Subroutine _parse_domain_whois_abuse: called CC=6 SCAR=17.9
Subroutine _parse_domain_whois_abuse: called CC=6 SCAR=17.9
3868 51 ▶ my $raw = $self->_domain_whois($domain) // return {};
Condition66%2/3
$self->_domain_whois($domain) // (return {})
l!l
8420
MC/DC100%1/1
$self->_domain_whois($domain) // (return {})
$self->_domain_whois($domain)
Truth table100%2/2
A
A= $self->_domain_whois($domain)
Aresult
11
00
3869 9 my %info;
3870 11 ▶ if ($raw =~ /Registrar:\s*(.+)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($raw =~ /Registrar:\s*(.+)/i) 8 2 10
3871 9 ($info{org} = $1) =~ s/\s+$//;
3872 }
3873 # Try multiple field name patterns for the abuse email
3874 9 for my $pat (
3875 qr/Registrar Abuse Contact Email:\s*(\S+\@\S+)/i,
3876 qr/Abuse Contact Email:\s*(\S+\@\S+)/i,
3877 qr/abuse-contact:\s*(\S+\@\S+)/i,
3878 ) {
3879 26 ▶ if (!$info{abuse} && $raw =~ $pat) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $info{"abuse"} and $raw =~ /$pat/) 8 16 24
Condition100%3/3
not $info{"abuse"} and $raw =~ /$pat/
!ll&&!rl&&r
1518
MC/DC100%2/2
not $info{"abuse"} and $raw =~ /$pat/
not $info{"abuse"} $raw =~ /$pat/
Truth table100%3/3
not(A) and B
A= not $info{"abuse"}B= $raw =~ /$pat/
ABresult
0X0
100
111
3880 10 ($info{abuse} = $1) =~ s/\s+$//;
3881 }
3882 }
3883 10 return \%info;
3884 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3885  
3886 # _rdap_lookup( $ip ) -> hashref
3887 #
3888 # Purpose:
3889 # Query the ARIN RDAP API for IP block ownership information. RDAP is
3890 # preferred over raw WHOIS because it returns structured JSON.
3891 #
3892 # Entry criteria:
3893 # $ip -- a defined IPv4 or IPv6 address string.
3894 # LWP::UserAgent must be installed.
3895 #
3896 # Exit status:
3897 # Returns { org, abuse, country } hashref; empty hashref on failure.
3898  
3899 sub _rdap_lookup :Protected {
3900 6 ▶ my ($self, $ip) = @_;
Subroutine _rdap_lookup: called CC=11 SCAR=24.7
Subroutine _rdap_lookup: called CC=11 SCAR=24.7
3901 7 ▶ return {} unless $HAS_LWP;
Branch: 1 branch
BranchTrueFalseTotal
unless $HAS_LWP 0 4 4
3902  
3903 7 my $ua = $self->{ua};
3904 7 ▶ if(!defined($ua)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ua) 4 0 4
3905 $ua = LWP::UserAgent->new(
3906 timeout => $self->{timeout},
3907 7 agent => "Email-Abuse-Investigator/$VERSION",
3908 );
3909  
3910 7 ▶ if($HAS_CONN_CACHE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($HAS_CONN_CACHE) 5 0 5
3911 5 my $conn_cache = LWP::ConnCache->new();
3912 5 $conn_cache->total_capacity(10);
3913 6 $ua->conn_cache($conn_cache);
3914 }
3915  
3916 6 $ua->env_proxy(1);
3917 5 $self->{ua} = $ua;
3918 }
3919  
3920 # Use the ARIN RDAP endpoint; it covers the ARIN region and redirects
3921 # for RIPE/APNIC/LACNIC/AfriNIC allocations.
3922 5 my $res = eval { $ua->get("https://rdap.arin.net/registry/ip/$ip") };
3923 5 ▶ return {} unless $res && $res->is_success();
Branch: 1 branch
BranchTrueFalseTotal
unless $res and $res->is_success 2 4 6
Condition33%1/3
$res and $res->is_success
!ll&&!rl&&r
004
MC/DC0%0/2
$res and $res->is_success
$res $res->is_success
Truth table33%1/3
A and B
A= $resB= $res->is_success
ABresult
0X0
100
111
3924  
3925 5 my $j = $res->decoded_content();
3926 5 my %info;
3927  
3928 # Extract organisation name from the JSON response
3929 5 ▶ if ($j =~ /"name"\s*:\s*"([^"]+)"/) { $info{org} = $1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($j =~ /"name"\s*:\s*"([^"]+)"/) 4 1 5
3930 5 ▶ if ($j =~ /"handle"\s*:\s*"([^"]+)"/) { $info{handle} = $1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($j =~ /"handle"\s*:\s*"([^"]+)"/) 4 0 4
3931  
3932 # Extract abuse email from the vcardArray contact block
3933 5 ▶ if ($j =~ /"abuse".*?"email"\s*:\s*"([^"]+)"/s) {
Branch: 2 branches
BranchTrueFalseTotal
if ($j =~ /"abuse".*?"email"\s*:\s*"([^"]+)"/s) { } 0 4 4
elsif ($j =~ /"email"\s*:\s*"([^\@"]+\@[^"]+)"/) { } 0 4 4
3934 1 $info{abuse} = $1;
3935 } elsif ($j =~ /"email"\s*:\s*"([^@"]+@[^"]+)"/) {
3936 1 $info{abuse} = $1;
3937 }
3938  
3939 # Country code from the network's country field
3940 5 ▶ if ($j =~ /"country"\s*:\s*"([A-Z]{2})"/) { $info{country} = $1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($j =~ /"country"\s*:\s*"([A-Z]{2})"/) 4 0 4
3941  
3942 5 return \%info;
3943 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3944  
3945 # _raw_whois( $query, $server ) -> string | undef
3946 #
3947 # Purpose:
3948 # Open a TCP connection to a WHOIS server on port 43, send the query,
3949 # and return the full response as a string. Uses IO::Select for read
3950 # timeouts so that alarm() is never needed (alarm() is unreliable on
3951 # Windows and in threaded Perl). Supports IPv6 WHOIS servers via
3952 # IO::Socket::IP when that module is available.
3953 #
3954 # Entry criteria:
3955 # $query -- the domain name or IP to query (defined, non-empty).
3956 # $server -- the WHOIS server hostname (default: 'whois.iana.org').
3957 # $self->{timeout} -- seconds used for connect and per-read waits.
3958 #
3959 # Exit status:
3960 # Returns the raw WHOIS response string, or undef on connection/write failure.
3961 #
3962 # Notes:
3963 # Uses IO::Socket::IP (dual-stack) when available, falling back to
3964 # IO::Socket::INET (IPv4 only) otherwise. The IO::Select loop reads
3965 # until the server closes the connection or the per-read timeout expires.
3966  
3967 sub _raw_whois :Protected {
3968 10 ▶ my ($self, $query, $server) = @_;
Subroutine _raw_whois: called CC=13 SCAR=27.6
Subroutine _raw_whois: called CC=13 SCAR=27.6
3969 10 ▶ $server //= 'whois.iana.org';
Condition33%1/3
$server //= "whois.iana.org"
l!l
900
MC/DC0%0/1
$server //= "whois.iana.org"
$server
Truth table50%1/2
A
A= $server
Aresult
11
00
3970 10 $self->_debug("WHOIS $server -> $query");
3971  
3972 # Choose the socket class based on what is installed.
3973 # IO::Socket::IP supports both IPv4 and IPv6 WHOIS servers.
3974 10 ▶ my $sock_class = $HAS_IO_SOCKET_IP ? 'IO::Socket::IP' : 'IO::Socket::INET';
Branch: 1 branch
BranchTrueFalseTotal
$HAS_IO_SOCKET_IP ? : 9 0 9
3975  
3976 # Attempt TCP connection to port 43 on the WHOIS server
3977 10 my $sock = eval {
3978 $sock_class->new(
3979 PeerAddr => $server,
3980 PeerPort => $WHOIS_PORT,
3981 Proto => 'tcp',
3982 Timeout => $self->{timeout},
3983 10 );
3984 };
3985 10 ▶ return unless $sock;
Branch: 1 branch
BranchTrueFalseTotal
unless $sock 3 6 9
3986  
3987 # Send the WHOIS query in wire format (CRLF-terminated per RFC 3912)
3988 8 ▶ $sock->print("$query\r\n") or do { $sock->close(); return };
Branch: 1 branch
BranchTrueFalseTotal
$sock->print("$query\r\n") or do { $sock->close; return } 0 6 6
3989  
3990 # Use IO::Select to implement per-read timeouts without alarm()
3991 7 my $sel = IO::Select->new($sock);
3992 7 my $response = '';
3993 7 my $buf = '';
3994  
3995 # Read until EOF (server closes) or timeout
3996 7 ▶ while ($sel->can_read($self->{timeout})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sel->can_read($self->{"timeout"})) 12 0 12
3997 # Wrap in eval to catch 'Connection reset by peer' thrown by Fatal/autodie
3998 13 my $n = eval { sysread($sock, $buf, $WHOIS_READ_CHUNK) };
3999  
4000 13 ▶ if ($@ || !defined $n || $n <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not defined $n or $n <= 0) 6 6 12
Condition50%3/6
$@ or not defined $n or $n <= 0
l!l&&r!l&&!r
066
$@ or not defined $n
l!l&&r!l&&!r
0012
MC/DC33%1/3
$@ or not defined $n or $n <= 0
$@ not defined $n $n <= 0
Truth table50%2/4
A or not(B) or C
A= $@B= not defined $nC= $n <= 0
ABCresult
1XX1
01X1
0011
0000
4001 7 ▶ $self->_debug("WHOIS read failed: $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 6 6
4002 7 last;
4003 }
4004 7 ▶ last if !defined($n) || $n <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $n or $n <= 0 0 6 6
Condition33%1/3
not defined $n or $n <= 0
l!l&&r!l&&!r
006
MC/DC0%0/2
not defined $n or $n <= 0
not defined $n $n <= 0
Truth table33%1/3
not(A) or B
A= not defined $nB= $n <= 0
ABresult
1X1
011
000
4005 7 $response .= $buf;
4006 }
4007  
4008 7 $sock->close();
4009 7 ▶ return $response || undef;
Condition50%1/2
$response || undef
l!l
60
MC/DC0%0/1
$response || undef
$response
Truth table50%1/2
A
A= $response
Aresult
11
00
4010 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4011  
4012 # _parse_whois_text( $text ) -> hashref
4013 #
4014 # Purpose:
4015 # Parse a raw WHOIS IP block response to extract organisation name,
4016 # abuse contact email, and country code.
4017 #
4018 # Entry criteria:
4019 # $text -- a defined WHOIS response string.
4020 #
4021 # Exit status:
4022 # Returns { org, abuse, country } hashref; keys absent when not found.
4023  
4024 sub _parse_whois_text :Private {
4025 36 ▶ my ($self, $text) = @_;
Subroutine _parse_whois_text: called CC=11 SCAR=24.0
Subroutine _parse_whois_text: called CC=11 SCAR=24.0
4026 36 ▶ return {} unless $text;
Branch: 1 branch
BranchTrueFalseTotal
unless $text 2 33 35
4027 34 my %info;
4028  
4029 # Try multiple field names for the organisation name
4030 34 for my $pat (
4031 qr/^OrgName:\s*(.+)/mi, qr/^org-name:\s*(.+)/mi,
4032 qr/^owner:\s*(.+)/mi, qr/^descr:\s*(.+)/mi,
4033 ) {
4034 133 ▶ if (!$info{org} && $text =~ $pat) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $info{"org"} and $text =~ /$pat/) 18 114 132
Condition100%3/3
not $info{"org"} and $text =~ /$pat/
!ll&&!rl&&r
427218
MC/DC100%2/2
not $info{"org"} and $text =~ /$pat/
not $info{"org"} $text =~ /$pat/
Truth table100%3/3
not(A) and B
A= not $info{"org"}B= $text =~ /$pat/
ABresult
0X0
100
111
4035 19 ($info{org} = $1) =~ s/\s+$//;
4036 }
4037 }
4038  
4039 # Try multiple field names for the abuse email
4040 34 for my $pat (
4041 qr/OrgAbuseEmail:\s*(\S+@\S+)/mi,
4042 qr/abuse-mailbox:\s*(\S+@\S+)/mi,
4043 ) {
4044 67 ▶ if (!$info{abuse} && $text =~ $pat) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $info{"abuse"} and $text =~ /$pat/) 7 59 66
Condition100%3/3
not $info{"abuse"} and $text =~ /$pat/
!ll&&!rl&&r
5547
MC/DC100%2/2
not $info{"abuse"} and $text =~ /$pat/
not $info{"abuse"} $text =~ /$pat/
Truth table100%3/3
not(A) and B
A= not $info{"abuse"}B= $text =~ /$pat/
ABresult
0X0
100
111
4045 8 ($info{abuse} = $1) =~ s/\s+$//;
4046 }
4047 }
4048  
4049 # Last-resort: any abuse@ address in the response
4050 34 ▶ if (!$info{abuse} && $text =~ /(abuse\@[\w.-]+)/i) { $info{abuse} = $1 }
Branch: 1 branch
BranchTrueFalseTotal
if (not $info{"abuse"} and $text =~ /(abuse\@[\w.-]+)/i) 3 30 33
Condition100%3/3
not $info{"abuse"} and $text =~ /(abuse\@[\w.-]+)/i
!ll&&!rl&&r
8233
MC/DC100%2/2
not $info{"abuse"} and $text =~ /(abuse\@[\w.-]+)/i
not $info{"abuse"} $text =~ /(abuse\@[\w.-]+)/i
Truth table100%3/3
not(A) and B
A= not $info{"abuse"}B= $text =~ /(abuse\@[\w.-]+)/i
ABresult
0X0
100
111
4051  
4052 # Country code (case-insensitive match, normalised to uppercase)
4053 34 ▶ if ($text =~ /^country:\s*([A-Za-z]{2})\s*$/m) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /^country:\s*([A-Za-z]{2})\s*$/m) 6 27 33
4054 7 $info{country} = uc $1;
4055 }
4056 34 return \%info;
4057 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4058  
4059 # -----------------------------------------------------------------------
4060 # Private: authentication results parsing
4061 # -----------------------------------------------------------------------
4062  
4063 # _parse_auth_results_cached() -> hashref
4064 #
4065 # Purpose:
4066 # Parse the Authentication-Results: header(s) from the message once,
4067 # cache the result, and return it. Extracts SPF, DKIM, DMARC, ARC
4068 # results and the DKIM signing domain(s).
4069 #
4070 # Entry criteria:
4071 # $self->{_headers} populated by _split_message().
4072 #
4073 # Exit status:
4074 # Returns { spf, dkim, dmarc, arc, dkim_domain, dkim_domains } hashref.
4075 # Keys absent when the corresponding header or field is not present.
4076  
4077 sub _parse_auth_results_cached :Private {
4078 822 ▶ my $self = $_[0];
Subroutine _parse_auth_results_cached: called CC=14 SCAR=26.4
Subroutine _parse_auth_results_cached: called CC=14 SCAR=26.4
4079 822 ▶ return $self->{_auth_results} if $self->{_auth_results};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_auth_results"} 340 481 821
4080  
4081 482 my %auth;
4082  
4083 # Concatenate all Authentication-Results: header values
4084 my $raw = join('; ',
4085 52 map { $_->{value} }
4086 3398 grep { $_->{name} eq 'authentication-results' }
4087 482 @{ $self->{_headers} }
4088 );
4089  
4090 # Extract individual authentication mechanism results
4091 482 ▶ if ($raw =~ /\bspf=(\S+)/i) { $auth{spf} = $1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($raw =~ /\bspf=(\S+)/i) 37 444 481
4092 482 ▶ if ($raw =~ /\bdkim=(\S+)/i) { $auth{dkim} = $1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($raw =~ /\bdkim=(\S+)/i) 32 449 481
4093 482 ▶ if ($raw =~ /\bdmarc=(\S+)/i) { $auth{dmarc} = $1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($raw =~ /\bdmarc=(\S+)/i) 21 460 481
4094 482 ▶ if ($raw =~ /\barc=(\S+)/i) { $auth{arc} = $1 }
Branch: 1 branch
BranchTrueFalseTotal
if ($raw =~ /\barc=(\S+)/i) 2 479 481
4095  
4096 # Strip trailing punctuation captured by the greedy \S+
4097 482 for my $k (qw(spf dkim dmarc arc)) {
4098 1925 ▶ $auth{$k} =~ s/[;,\s]+$// if defined $auth{$k};
Branch: 1 branch
BranchTrueFalseTotal
if defined $auth{$k} 92 1832 1924
4099 }
4100  
4101 # Extract DKIM signing domains from all DKIM-Signature: d= tags.
4102 # Prefer the first domain that matches the provider table (identifies ESP).
4103 482 my @dkim_domains;
4104 482 for my $h (grep { $_->{name} eq 'dkim-signature' } @{ $self->{_headers} }) {
4105 19 ▶ if ($h->{value} =~ /\bd=([^;,\s]+)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($h->{"value"} =~ /\bd=([^;,\s]+)/) 18 0 18
4106 19 push @dkim_domains, lc $1;
4107 }
4108 }
4109  
4110 482 ▶ if (@dkim_domains) {
Branch: 1 branch
BranchTrueFalseTotal
if (@dkim_domains) 13 468 481
4111 # Check if any signing domain matches a known provider
4112 14 my $preferred;
4113 14 for my $d (@dkim_domains) {
4114 18 ▶ if ($self->_provider_abuse_for_host($d)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_provider_abuse_for_host($d)) 5 13 18
4115 6 $preferred = $d;
4116 6 last;
4117 }
4118 }
4119 14 ▶ $auth{dkim_domain} = $preferred // $dkim_domains[0];
Condition66%2/3
$preferred // $dkim_domains[0]
l!l&&r!l&&!r
580
MC/DC0%0/2
$preferred // $dkim_domains[0]
$preferred $dkim_domains[0]
Truth table66%2/3
A // B
A= $preferredB= $dkim_domains[0]
ABresult
1X1
011
000
4120 14 $auth{dkim_domains} = \@dkim_domains;
4121 }
4122  
4123 482 $self->{_auth_results} = \%auth;
4124 482 return \%auth;
4125 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4126  
4127 # -----------------------------------------------------------------------
4128 # Private: provider-table lookups
4129 # -----------------------------------------------------------------------
4130  
4131 # _provider_abuse_for_host( $host ) -> hashref | undef
4132 #
4133 # Purpose:
4134 # Look up a hostname (and each of its parent domains, stripping one label
4135 # at a time from the left) in the %PROVIDER_ABUSE table.
4136 #
4137 # Entry criteria:
4138 # $host -- a defined hostname or domain string.
4139 #
4140 # Exit status:
4141 # Returns the %PROVIDER_ABUSE entry hashref on match, undef otherwise.
4142  
4143 sub _provider_abuse_for_host :Private {
4144 1612 ▶ my ($self, $host) = @_;
Subroutine _provider_abuse_for_host: called CC=4 SCAR=13.9
Subroutine _provider_abuse_for_host: called CC=4 SCAR=13.9
4145 1612 $host = lc $host;
4146 # Strip successive subdomains until we find a match or exhaust labels
4147 1535 ▶ while ($host =~ /\./) {
Branch: 1 branch
BranchTrueFalseTotal
if ($host =~ /\./) 1684 1252 2936
4148 1650 ▶ return $self->{provider_abuse}->{$host} if $self->{provider_abuse}->{$host};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"provider_abuse"}{$host} 5 1644 1649
4149 1615 ▶ return $PROVIDER_ABUSE{$host} if $PROVIDER_ABUSE{$host};
Branch: 1 branch
BranchTrueFalseTotal
if $PROVIDER_ABUSE{$host} 288 1361 1649
4150 1707 $host =~ s/^[^.]+\.//;
4151 }
4152 1253 return;
4153 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4154  
4155 # _provider_abuse_for_ip( $ip, $rdns ) -> hashref | undef
4156 #
4157 # Purpose:
4158 # Look up an IP's reverse-DNS hostname in the %PROVIDER_ABUSE table to
4159 # identify well-known provider networks by rDNS pattern.
4160 #
4161 # Entry criteria:
4162 # $ip -- IPv4 or IPv6 address string (used as fallback if $rdns absent).
4163 # $rdns -- optional rDNS hostname string.
4164 #
4165 # Exit status:
4166 # Returns the %PROVIDER_ABUSE entry on match, undef otherwise.
4167  
4168 sub _provider_abuse_for_ip :Private {
4169 229 ▶ my ($self, $ip, $rdns) = @_;
Subroutine _provider_abuse_for_ip: called CC=2 SCAR=6.9
Subroutine _provider_abuse_for_ip: called CC=2 SCAR=6.9
4170 192 ▶ return $self->_provider_abuse_for_host($rdns) if $rdns;
Branch: 1 branch
BranchTrueFalseTotal
if $rdns 187 41 228
4171 45 return;
4172 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4173  
4174 # -----------------------------------------------------------------------
4175 # Private: eTLD+1 normalisation
4176 # -----------------------------------------------------------------------
4177  
4178 # _registrable( $host ) -> string | undef
4179 #
4180 # Purpose:
4181 # Return the registrable eTLD+1 form of a hostname. Uses
4182 # Domain::PublicSuffix when installed for accurate results; falls back
4183 # to a built-in heuristic for the common two-letter ccTLD+2 pattern.
4184 #
4185 # Entry criteria:
4186 # $host -- a hostname string (may include subdomains).
4187 #
4188 # Exit status:
4189 # Returns the registrable domain string, or undef for single-label
4190 # hostnames (e.g. 'localhost').
4191 #
4192 # Notes:
4193 # The heuristic handles co.uk, com.au, net.jp, org.nz etc. but not
4194 # uncommon second-level delegations like ltd.uk or plc.uk.
4195  
4196 sub _registrable :Private {
4197 1316 ▶ my $host = $_[0];
Subroutine _registrable: called CC=8 SCAR=20.8
Subroutine _registrable: called CC=8 SCAR=20.8
4198 1351 ▶ return unless $host && $host =~ /\./;
Branch: 1 branch
BranchTrueFalseTotal
unless $host and $host =~ /\./ 203 1148 1351
Condition100%3/3
$host and $host =~ /\./
!ll&&!rl&&r
42011106
MC/DC100%2/2
$host and $host =~ /\./
$host $host =~ /\./
Truth table100%3/3
A and B
A= $hostB= $host =~ /\./
ABresult
0X0
100
111
4199  
4200 # Use Domain::PublicSuffix for accurate PSL-based normalisation
4201 1110 ▶ if ($HAS_PUBLIC_SUFFIX) {
Branch: 1 branch
BranchTrueFalseTotal
if ($HAS_PUBLIC_SUFFIX) 14 1260 1274
4202 43 my $psl = Domain::PublicSuffix->new();
4203 0 my $root = $psl->get_root_domain(lc $host);
4204 43 ▶ return $root if $root;
Branch: 1 branch
BranchTrueFalseTotal
if $root 2 0 2
4205 }
4206  
4207 # Built-in heuristic fallback
4208 1275 my @labels = split /\./, lc $host;
4209 1149 ▶ return $host if @labels <= 2;
Branch: 1 branch
BranchTrueFalseTotal
if @labels <= 2 996 152 1148
4210  
4211 # Detect common ccTLD second-level patterns (e.g. co.uk, com.au)
4212 155 ▶ if ($labels[-1] =~ /^[a-z]{2}$/ &&
Branch: 1 branch
BranchTrueFalseTotal
if ($labels[-1] =~ /^[a-z]{2}$/ and $labels[-2] =~ /^(?:co|com|net|org|gov|edu|ac|me)$/) 66 48 114
Condition100%3/3
$labels[-1] =~ /^[a-z]{2}$/ and $labels[-2] =~ /^(?:co|com|net|org|gov|edu|ac|me)$/
!ll&&!rl&&r
44365
MC/DC100%2/2
$labels[-1] =~ /^[a-z]{2}$/ and $labels[-2] =~ /^(?:co|com|net|org|gov|edu|ac|me)$/
$labels[-1] =~ /^[a-z]{2}$/ $labels[-2] =~ /^(?:co|com|net|org|gov|edu|ac|me)$/
Truth table100%3/3
A and B
A= $labels[-1] =~ /^[a-z]{2}$/B= $labels[-2] =~ /^(?:co|com|net|org|gov|edu|ac|me)$/
ABresult
0X0
100
111
4213 $labels[-2] =~ /^(?:co|com|net|org|gov|edu|ac|me)$/) {
4214 447 return join('.', @labels[-3..-1]);
4215 }
4216 90 return join('.', @labels[-2..-1]);
4217 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4218  
4219 # -----------------------------------------------------------------------
4220 # Private: utilities
4221 # -----------------------------------------------------------------------
4222  
4223 # _enrich_ip( $ip, $confidence, $note ) -> origin hashref
4224 #
4225 # Purpose:
4226 # Perform rDNS and WHOIS/RDAP for a single IP and package the results
4227 # into the standard origin hashref returned by originating_ip().
4228 #
4229 # Entry criteria:
4230 # $ip -- a defined, non-private IPv4 or IPv6 address string.
4231 # $confidence -- 'high', 'medium', or 'low'.
4232 # $note -- human-readable explanation of why this IP was chosen.
4233 #
4234 # Exit status:
4235 # Returns { ip, rdns, org, abuse, country, confidence, note } hashref.
4236  
4237 sub _enrich_ip :Private {
4238 99 ▶ my ($self, $ip, $confidence, $note) = @_;
Subroutine _enrich_ip: called CC=5 SCAR=16.2
Subroutine _enrich_ip: called CC=5 SCAR=16.2
4239 99 my $rdns = $self->_reverse_dns($ip);
4240 139 my $whois = $self->_whois_ip($ip);
4241 return {
4242 ip => $ip,
4243 rdns => $rdns // '(no reverse DNS)',
4244 org => $whois->{org} // '(unknown)',
4245 abuse => $whois->{abuse} // '(unknown)',
4246 country => $whois->{country} // undef,
4247 99 ▶ confidence => $confidence,
Condition80%8/10
$rdns // "(no reverse DNS)"
l!l
48490
$whois->{"org"} // "(unknown)"
l!l
61350
$whois->{"abuse"} // "(unknown)"
l!l
4056
$whois->{"country"} // undef
l!l
2670
MC/DC100%1/1
$rdns // "(no reverse DNS)"
$rdns
MC/DC100%1/1
$whois->{"org"} // "(unknown)"
$whois->{"org"}
MC/DC100%1/1
$whois->{"abuse"} // "(unknown)"
$whois->{"abuse"}
MC/DC100%1/1
$whois->{"country"} // undef
$whois->{"country"}
Truth table100%2/2
A
A= $rdns
Aresult
11
00
Truth table100%2/2
A
A= $whois->{"org"}
Aresult
11
00
Truth table100%2/2
A
A= $whois->{"abuse"}
Aresult
11
00
Truth table100%2/2
A
A= $whois->{"country"}
Aresult
11
00
4248 note => $note,
4249 };
4250 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4251  
4252 # _header_value( $name ) -> value_string | undef
4253 #
4254 # Purpose:
4255 # Return the value of the first header matching the given lower-cased
4256 # header name.
4257 =head2 header_value( $name )
4258  
4259 Returns the value of the first occurrence of a named header field, or
4260 C<undef> if the header is absent. The name comparison is case-insensitive.
4261  
4262 =head3 Usage
4263  
4264 my $subj = $analyser->header_value('Subject');
4265 my $from = $analyser->header_value('From');
4266 my $msgid = $analyser->header_value('Message-ID');
4267  
4268 =head3 Arguments
4269  
4270 =over 4
4271  
4272 =item C<$name> (string, required)
4273  
4274 The header field name, e.g. C<'Subject'>, C<'From'>, C<'X-Mailer'>.
4275 Comparison is case-insensitive.
4276  
4277 =back
4278  
4279 =head3 Returns
4280  
4281 The raw header value string (not decoded), or C<undef> if the named header
4282 is not present. When the same header appears more than once, only the value
4283 of the first occurrence is returned.
4284  
4285 =head3 Side Effects
4286  
4287 None. Header data is pre-parsed during C<parse_email()>.
4288  
4289 =head3 Notes
4290  
4291 Header values are returned verbatim, including any MIME encoded-word sequences
4292 (C<=?charset?B/Q?...?=>). Pass the result through C<_decode_mime_words()>
4293 internally if human-readable output is needed.
4294  
4295 =head3 API Specification
4296  
4297 =head4 Input
4298  
4299 {
4300 name => { type => 'string', required => 1 },
4301 }
4302  
4303 =head4 Output
4304  
4305 { type => [ 'string', 'undef' ] }
4306  
4307 =head3 Messages
4308  
4309 None -- returns C<undef> on a missing header, never throws.
4310  
4311 =cut
4312  
4313 sub header_value {
4314 82 ▶ my $self = shift;
Subroutine header_value: called CC=5 SCAR=16.5
Subroutine header_value: called CC=5 SCAR=16.5
Pod documented
4315  
4316 82 ▶ my $params = Params::Validate::Strict::validate_strict({
Condition66%2/3
Params::Get::get_params('name', \@_) || {}
l!l
7910
MC/DC100%1/1
Params::Get::get_params('name', \@_) || {}
Params::Get::get_params('name', \@_)
Truth table100%2/2
A
A= Params::Get::get_params('name', \@_)
Aresult
11
00
4317 args => Params::Get::get_params('name', \@_) || {},
4318 schema => {
4319 name => {
4320 'type' => 'string',
4321 'optional' => 0,
4322 }
4323 }
4324 });
4325  
4326 81 ▶ return if((!defined($params)) || !defined($params->{name}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $params and defined $params->{"name"} 0 37 37
Condition100%3/3
defined $params and defined $params->{"name"}
!ll&&!rl&&r
38437
MC/DC0%0/2
defined $params and defined $params->{"name"}
defined $params defined $params->{"name"}
Truth table33%1/3
A and B
A= defined $paramsB= defined $params->{"name"}
ABresult
0X0
100
111
4327 81 ▶ return if ref($params->{name});
Branch: 1 branch
BranchTrueFalseTotal
if ref $params->{"name"} 0 37 37
4328 40 return $self->_header_value($params->{name});
4329 }
4330  
4331 #
4332 # _header_value( $name ) -> string | undef
4333 #
4334 # Purpose:
4335 # Internal implementation for header_value(). Walks _headers list and
4336 # returns the value of the first matching header.
4337 #
4338 # Entry criteria:
4339 # $name -- a lower-cased header name string.
4340 # $self->{_headers} populated by _split_message().
4341 #
4342 # Exit status:
4343 # Returns the value string, or undef if the header is not present.
4344  
4345 sub _header_value :Private {
4346 5266 ▶ my ($self, $name) = @_;
Subroutine _header_value: called CC=3 SCAR=11.0
Subroutine _header_value: called CC=3 SCAR=11.0
4347 5306 for my $h (@{ $self->{_headers} }) {
4348 28035 ▶ return $h->{value} if $h->{name} eq lc($name);
Branch: 1 branch
BranchTrueFalseTotal
if $h->{"name"} eq lc $name 2647 25387 28034
4349 }
4350 2617 return;
4351 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4352  
4353 # _ip_in_cidr( $ip, $cidr ) -> bool
4354 #
4355 # Purpose:
4356 # Test whether an IPv4 address falls within a CIDR block or is an exact
4357 # match (when $cidr contains no '/' separator).
4358 #
4359 # Entry criteria:
4360 # $ip -- a defined dotted-quad IPv4 address string.
4361 # $cidr -- a CIDR string like '10.0.0.0/8' or an exact IP.
4362 #
4363 # Exit status:
4364 # Returns 1 (true) if the IP is within the CIDR block, 0 otherwise.
4365  
4366 sub _ip_in_cidr :Private {
4367 849 ▶ my ($self, $ip, $cidr) = @_;
Subroutine _ip_in_cidr: called CC=7 SCAR=19.8
Subroutine _ip_in_cidr: called CC=7 SCAR=19.8
4368 849 ▶ return $ip eq $cidr unless $cidr =~ m{/};
Branch: 1 branch
BranchTrueFalseTotal
unless $cidr =~ m[/] 457 4656 5113
4369 843 my ($net_addr, $prefix) = split m{/}, $cidr;
4370 5108 ▶ return 0 if !defined($prefix) || $prefix !~ /^\d+$/ || $prefix > 32;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $prefix && $prefix =~ /^\d+$/ or $prefix > 32 1 39 40
Condition100%6/6
not defined $prefix && $prefix =~ /^\d+$/ or $prefix > 32
l!l&&r!l&&!r
36739
defined $prefix && $prefix =~ /^\d+$/
!ll&&!rl&&r
93340
MC/DC33%1/3
not defined $prefix && $prefix =~ /^\d+$/ or $prefix > 32
defined $prefix $prefix =~ /^\d+$/ $prefix > 32
Truth table50%2/4
not(A && B) or C
A= defined $prefixB= $prefix =~ /^\d+$/C= $prefix > 32
ABCresult
0XX1
10X1
1111
1100
4371  
4372 # Compute the network mask and compare masked network addresses
4373 391 my $mask = ~0 << (32 - $prefix);
4374 40 ▶ my $net_n = unpack 'N', (inet_aton($net_addr) // return 0);
Condition33%1/3
inet_aton($net_addr) // (return 0)
l!l
4000
MC/DC100%1/1
inet_aton($net_addr) // (return 0)
inet_aton($net_addr)
Truth table100%2/2
A
A= inet_aton($net_addr)
Aresult
11
00
4375 40 ▶ my $ip_n = unpack 'N', (inet_aton($ip) // return 0);
Condition33%1/3
inet_aton($ip) // (return 0)
l!l
3900
MC/DC0%0/1
inet_aton($ip) // (return 0)
inet_aton($ip)
Truth table50%1/2
A
A= inet_aton($ip)
Aresult
11
00
4376 40 return ($ip_n & $mask) == ($net_n & $mask);
4377 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4378  
4379 # _decode_mime_words( $str ) -> decoded_string
4380 #
4381 # Purpose:
4382 # Decode MIME encoded-words (=?charset?B/Q?...?=) in a header value
4383 # string for human-readable display in reports.
4384 #
4385 # Entry criteria:
4386 # $str -- a defined header value string; may be undef.
4387 #
4388 # Exit status:
4389 # Returns the decoded string, or '' if $str is undef.
4390  
4391 sub _decode_mime_words :Private {
4392 618 ▶ my ($self, $str) = @_;
Subroutine _decode_mime_words: called CC=2 SCAR=6.9
Subroutine _decode_mime_words: called CC=2 SCAR=6.9
4393 618 ▶ return '' unless defined $str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 2 615 617
4394 # Replace each encoded-word with its decoded equivalent
4395 616 $str =~ s/=\?([^?]+)\?([BbQq])\?([^?]*)\?=/_decode_ew($1,$2,$3)/ge;
4396 616 return $str;
4397 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4398  
4399 # _decode_ew( $charset, $enc, $text ) -> decoded_bytes
4400 #
4401 # Purpose:
4402 # Decode a single MIME encoded-word component (base64 or quoted-printable).
4403 #
4404 # Notes:
4405 # Non-UTF-8 charsets return raw bytes; good enough for display-name spoof
4406 # detection which only needs ASCII matching.
4407  
4408 sub _decode_ew :Private {
4409 152 ▶ my ($charset, $enc, $text) = @_;
Subroutine _decode_ew: called CC=2 SCAR=6.9
Subroutine _decode_ew: called CC=2 SCAR=6.9
4410 152 my $raw;
4411 152 ▶ if (uc($enc) eq 'B') {
Branch: 1 branch
BranchTrueFalseTotal
if (uc $enc eq 'B') { } 33 118 151
4412 40 $raw = decode_base64($text);
4413 } else {
4414 # Quoted-printable encoded-word uses underscore for space
4415 114 $text =~ s/_/ /g;
4416 5 $raw = decode_qp($text);
4417 }
4418 38 return $raw;
4419 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4420  
4421 # _parse_date_to_epoch( $str ) -> epoch_int | undef
4422 #
4423 # Purpose:
4424 # Parse common WHOIS date strings to a Unix epoch integer.
4425 # Handles YYYY-MM-DD, YYYY-MM-DDThh:mm:ssZ, and DD-Mon-YYYY formats.
4426 #
4427 # Entry criteria:
4428 # $str -- a defined date string; may be undef.
4429 #
4430 # Exit status:
4431 # Returns epoch integer on success, undef if the string cannot be parsed.
4432  
4433 sub _parse_date_to_epoch :Private {
4434 71 ▶ my ($self, $str) = @_;
Subroutine _parse_date_to_epoch: called CC=12 SCAR=24.9
Subroutine _parse_date_to_epoch: called CC=12 SCAR=24.9
4435 71 ▶ return unless $str;
Branch: 1 branch
BranchTrueFalseTotal
unless $str 7 63 70
4436  
4437 # Clean the string of trailing whitespace/newlines
4438 70 $str =~ s/^\s+|\s+$//g;
4439  
4440 # Guard Regex: Validates the strict YYYY-MM-DDThh:mm:ssZ format
4441 70 ▶ if ($str =~ /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.\d+)?Z$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.\d+)?Z$/) 2 61 63
4442 # Parse the string
4443 # We use 'strptime' to create a Time::Piece object.
4444 # The 'Z' indicates UTC (Zulu time).
4445 3 my $epoch = eval {
4446 3 my $t = Time::Piece->strptime($1, '%Y-%m-%dT%H:%M:%S');
4447  
4448 # Return seconds since the epoch
4449 # Time::Piece handles the timezone offset internally when calling ->epoch
4450  
4451 # strptime returns a local time object.
4452 # We must subtract the local timezone offset to get the true UTC epoch.
4453 9 return $t->epoch - $t->tzoffset->seconds;
4454 };
4455 3 ▶ return $epoch if defined $epoch;
Branch: 1 branch
BranchTrueFalseTotal
if defined $epoch 2 0 2
4456 }
4457 62 my ($y, $m, $d);
4458  
4459 62 ▶ if ($str =~ /^(\d{4})-(\d{2})-(\d{2})/) { ($y,$m,$d)=($1,$2,$3) }
Branch: 3 branches
BranchTrueFalseTotal
if ($str =~ /^(\d{4})-(\d{2})-(\d{2})/) { } 42 19 61
elsif ($str =~ /^(\d{2})-([A-Za-z]{3})-(\d{4})/) { } 17 2 19
elsif ($str =~ m[^(\d{2})/(\d{2})/(\d{4})]) { } 1 1 2
4460 18 ▶ elsif ($str =~ /^(\d{2})-([A-Za-z]{3})-(\d{4})/) { ($d,$m,$y)=($1,$Readonly::Values::Months::months{lc$2}//0,$3) }
Condition100%3/3
$Readonly::Values::Months::months{lc $2} // 0
l!l
1615
MC/DC100%1/1
$Readonly::Values::Months::months{lc $2} // 0
$Readonly::Values::Months::months{lc $2}
Truth table100%2/2
A
A= $Readonly::Values::Months::months{lc $2}
Aresult
11
00
4461 2 elsif ($str =~ /^(\d{2})\/(\d{2})\/(\d{4})/) { ($m,$d,$y)=($1,$2,$3) }
4462  
4463 62 ▶ return unless $y && $m && $d;
Branch: 1 branch
BranchTrueFalseTotal
unless $y and $m and $d 1 59 60
Condition83%5/6
$y and $m and $d
!ll&&!rl&&r
2064
$y and $m
!ll&&!rl&&r
6159
MC/DC66%2/3
$y and $m and $d
$y $m $d
Truth table75%3/4
A and B and C
A= $yB= $mC= $d
ABCresult
0XX0
10X0
1100
1111
4464  
4465 60 ▶ if (eval { require Time::Local; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require Time::Local; 1 } }) 59 0 59
4466 60 return eval { Time::Local::timegm(0,0,0,$d,$m-1,$y-1900) };
4467 }
4468 # Approximate fallback without Time::Local
4469 1 return ($y-1970)*365.25*$SECS_PER_DAY + ($m-1)*30.5*$SECS_PER_DAY + ($d-1)*$SECS_PER_DAY;
4470 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4471  
4472 # _parse_rfc2822_date( $str ) -> epoch_int | undef
4473 #
4474 # Purpose:
4475 # Parse an RFC 2822 Date: header value to a Unix epoch integer.
4476 # Timezone offsets are intentionally ignored; the function returns a
4477 # UTC-equivalent value. For the 7-day suspicious_date window the
4478 # maximum error is ~14 hours, well within the tolerance.
4479 #
4480 # Entry criteria:
4481 # $str -- a defined Date: header value string.
4482 #
4483 # Exit status:
4484 # Returns epoch integer on success, undef if the string cannot be parsed.
4485  
4486 sub _parse_rfc2822_date :Private {
4487 331 ▶ my $str = $_[0];
Subroutine _parse_rfc2822_date: called CC=6 SCAR=17.9
Subroutine _parse_rfc2822_date: called CC=6 SCAR=17.9
4488 331 ▶ return unless $str;
Branch: 1 branch
BranchTrueFalseTotal
unless $str 2 328 330
4489  
4490 # Match: DD Mon YYYY HH:MM:SS (timezone offset ignored)
4491 329 ▶ if ($str =~ /(\d{1,2})\s+([A-Za-z]{3})\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /(\d{1,2})\s+([A-Za-z]{3})\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})/) 325 3 328
4492 my ($d, $m, $y, $H, $M, $S) =
4493 326 ▶ ($1, $Readonly::Values::Months::months{ lc $2 } // 0, $3, $4, $5, $6);
Condition100%2/2
$Readonly::Values::Months::months{lc $2} // 0
l!l
3313
MC/DC100%1/1
$Readonly::Values::Months::months{lc $2} // 0
$Readonly::Values::Months::months{lc $2}
Truth table100%2/2
A
A= $Readonly::Values::Months::months{lc $2}
Aresult
11
00
4494 326 ▶ return unless $m;
Branch: 1 branch
BranchTrueFalseTotal
unless $m 1 324 325
4495 325 ▶ if (eval { require Time::Local; 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require Time::Local; 1 } }) 324 0 324
4496 325 return eval { Time::Local::timegm($S, $M, $H, $d, $m - 1, $y - 1900) };
4497 }
4498 }
4499 4 return;
4500 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4501  
4502 # _country_name( $cc ) -> country_name_string
4503 #
4504 # Purpose:
4505 # Return a human-readable country name for a two-letter ISO 3166-1
4506 # alpha-2 country code. Only the small set of statistically high-volume
4507 # spam-originating countries is covered; other codes are returned as-is.
4508 #
4509 # Entry criteria:
4510 # $cc -- a two-letter uppercase country code string.
4511 #
4512 # Exit status:
4513 # Returns the country name string, or the code itself if not in the table.
4514  
4515 sub _country_name :Private {
4516 92 ▶ my $cc = $_[0];
Subroutine _country_name: called CC=2 SCAR=7.0
Subroutine _country_name: called CC=2 SCAR=7.0
4517 92 my %names = (
4518 CN => 'China', RU => 'Russia', NG => 'Nigeria',
4519 VN => 'Vietnam', IN => 'India', PK => 'Pakistan',
4520 BD => 'Bangladesh',
4521 );
4522 92 ▶ return $names{$cc} // $cc;
Condition66%2/3
$names{$cc} // $cc
l!l&&r!l&&!r
8760
MC/DC0%0/2
$names{$cc} // $cc
$names{$cc} $cc
Truth table66%2/3
A // B
A= $names{$cc}B= $cc
ABresult
1X1
011
000
4523 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4524  
4525 # _debug( $msg )
4526 #
4527 # Purpose:
4528 # Write a diagnostic message to STDERR when verbose mode is enabled.
4529 #
4530 # Entry criteria:
4531 # $msg -- a defined message string.
4532 #
4533 # Notes:
4534 # Messages are prefixed with the class name for easy grepping.
4535  
4536 sub _debug :Private {
4537 981 ▶ my ($self, $msg) = @_;
Subroutine _debug: called CC=3 SCAR=11.0
Subroutine _debug: called CC=3 SCAR=11.0
4538  
4539 982 ▶ if($self->{verbose}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"verbose"}) 2 978 980
4540 36 ▶ if (my $logger = $self->{logger}) { # Set via Object::Configure
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{'logger'}) { } 32 2 34
4541 34 $logger->debug("[Email::Abuse::Investigator] $msg");
4542 } else {
4543 36 print STDERR "[Email::Abuse::Investigator] $msg\n";
4544 }
4545 }
4546 19 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
4547  
4548 17 1;
4549  
4550 __END__
4551  
4552 =head1 ALGORITHM: DOMAIN INTELLIGENCE PIPELINE
4553  
4554 For each unique non-infrastructure domain found in the email, the module
4555 runs the following pipeline:
4556  
4557 Domain name
4558 |
4559 +-- A/AAAA record --> web hosting IP --> RDAP --> org + abuse contact
4560 |
4561 +-- MX record --> mail server hostname --> A --> RDAP --> org + abuse
4562 |
4563 +-- NS record --> nameserver hostname --> A --> RDAP --> org + abuse
4564 |
4565 +-- WHOIS (TLD whois server via IANA referral)
4566 +-- Registrar name + abuse contact
4567 +-- Creation date (-> recently-registered flag if < 180 days)
4568 +-- Expiry date (-> expires-soon or expired flags)
4569  
4570 Domains are collected from:
4571  
4572 From:/Reply-To:/Sender:/Return-Path: headers
4573 DKIM-Signature: d= (signing domain)
4574 List-Unsubscribe: (ESP / bulk sender domain)
4575 Message-ID: (often reveals real sending platform)
4576 mailto: links and bare addresses in the body
4577  
4578 =head1 CACHING
4579  
4580 Two levels of caching are used:
4581  
4582 =over 4
4583  
4584 =item Per-message cache (C<$self-E<gt>{_domain_info}>)
4585  
4586 Stores domain analysis results for the lifetime of one C<parse_email()>
4587 call. Invalidated by each call to C<parse_email()>.
4588  
4589 =item Cross-message cache (CHI Memory driver, if C<CHI> is installed)
4590  
4591 Stores IP WHOIS, DNS resolution, and domain analysis results across all
4592 messages processed by the same process. TTL is one hour. Prevents
4593 redundant WHOIS queries for infrastructure that appears in multiple
4594 messages in the same run (e.g. a sending ISP seen in 500 spam messages).
4595  
4596 =back
4597  
4598 =head1 IPV6 SUPPORT
4599  
4600 IPv6 addresses are extracted from C<Received:> headers using bracketed
4601 notation (C<[2001:db8::1]>). They are tested against the private range
4602 list (which covers ::1, fe80::/10, fc00::/7, fd00::/8, and the
4603 documentation range 2001:db8::/32) and passed through C<_whois_ip()> and
4604 C<_rdap_lookup()> in the same way as IPv4 addresses.
4605  
4606 C<_resolve_host()> attempts both A and AAAA lookups when C<Net::DNS> is
4607 installed. C<_raw_whois()> uses C<IO::Socket::IP> for dual-stack WHOIS
4608 connections when that module is installed.
4609  
4610 =head1 SEE ALSO
4611  
4612 =over 4
4613  
4614 =item * L<Configure an Object at Runtime|Object::Configure>
4615  
4616 The provider_abuse, trusted_domains and url_shorteners tables can all be overridden at runtime
4617  
4618 =item * L<Test Dashboard|https://nigelhorne.github.io/Email-Abuse-Investigator/coverage/>
4619  
4620 =item * L<ARIN RDAP|https://rdap.arin.net/>
4621  
4622 =item * L<Net::DNS>, L<LWP::UserAgent>, L<HTML::LinkExtor>
4623  
4624 =item * L<CHI>, L<AnyEvent::DNS>, L<IO::Socket::IP>, L<Domain::PublicSuffix>
4625  
4626 =back
4627  
4628 =head1 REPOSITORY
4629  
4630 L<https://github.com/nigelhorne/Email-Abuse-Investigator>
4631  
4632 =head1 SUPPORT
4633  
4634 This module is provided as-is without any warranty.
4635  
4636 Please report any bugs or feature requests to C<bug-email-abuse-investigator at rt.cpan.org>,
4637 or through the web interface at
4638 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Email-Abuse-Investigator>.
4639 I will be notified, and then you'll
4640 automatically be notified of progress on your bug as I make changes.
4641  
4642 You can find documentation for this module with the perldoc command.
4643  
4644 perldoc Email::Abuse::Investigator
4645  
4646 You can also look for information at:
4647  
4648 =over 4
4649  
4650 =item * MetaCPAN
4651  
4652 L<https://metacpan.org/dist/Email-Abuse-Investigator>
4653  
4654 =item * RT: CPAN's request tracker
4655  
4656 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Email-Abuse-Investigator>
4657  
4658 =item * CPAN Testers' Matrix
4659  
4660 L<http://matrix.cpantesters.org/?dist=Email-Abuse-Investigator>
4661  
4662 =item * CPAN Testers Dependencies
4663  
4664 L<http://deps.cpantesters.org/?module=Email-Abuse-Investigator>
4665  
4666 =back
4667  
4668 =head1 REQUIRED MODULES
4669  
4670 The following modules are mandatory:
4671  
4672 Readonly::Values::Months
4673 Socket (core since Perl 5)
4674 IO::Socket::INET (core since Perl 5)
4675 MIME::QuotedPrint (core since Perl 5.8)
4676 MIME::Base64 (core since Perl 5.8)
4677  
4678 The following are optional but strongly recommended:
4679  
4680 Net::DNS -- enables MX, NS, AAAA record lookups
4681 LWP::UserAgent -- enables RDAP (faster and richer than raw WHOIS)
4682 and following redirect chains for URL shorteners
4683 and cloud-storage redirect cloakers
4684 LWP::ConnCache -- enables HTTP connection reuse (used with LWP::UserAgent)
4685 HTML::LinkExtor -- enables structural HTML link extraction with entity decoding
4686 CHI -- enables cross-message IP/domain result caching
4687 IO::Socket::IP -- enables IPv6 WHOIS connections
4688 Domain::PublicSuffix -- enables accurate eTLD+1 domain normalisation
4689 AnyEvent::DNS -- enables parallel DNS resolution for multiple URL hosts
4690  
4691 =head1 LIMITATIONS
4692  
4693 =over 4
4694  
4695 =item No charset conversion
4696  
4697 Body text is stored as raw bytes. Non-ASCII content (UTF-8, Latin-1,
4698 ISO-2022-JP, etc.) is not decoded to Perl's internal Unicode representation.
4699 URL and domain extraction from non-ASCII bodies may miss or misparse content.
4700 Use C<Email::MIME> if full charset support is needed.
4701  
4702 =item Hand-rolled MIME parser
4703  
4704 The built-in MIME parser handles common cases but is not a conforming
4705 implementation of RFC 2045/2046. It silently drops parts it cannot decode,
4706 does not handle C<message/rfc822> attachments, and does not parse
4707 C<Content-Disposition> filenames. Replace with C<Email::MIME> or
4708 C<MIME::Entity> for production use with untrusted input.
4709  
4710 =item IPv4-only CIDR matching for trusted_relays
4711  
4712 C<_ip_in_cidr()> and the C<trusted_relays> constructor argument only support
4713 IPv4 CIDR notation. IPv6 trusted relay entries are accepted but silently
4714 never match.
4715  
4716 =item WHOIS rate-limiting not handled
4717  
4718 C<_raw_whois()> does not retry on rate-limit responses (typically a
4719 "quota exceeded" reply). Under high-volume processing the module will
4720 silently return empty enrichment data for affected IPs and domains.
4721  
4722 =item Not thread-safe
4723  
4724 The class-level C<$_cache> variable and the optional-module C<$HAS_*> flags
4725 are shared across all threads. Create a separate object per thread and do
4726 not share objects across threads.
4727  
4728 =item DMARC policy not fetched
4729  
4730 The module reads the C<Authentication-Results: dmarc=> result from the
4731 message headers but does not perform live C<_dmarc.domain> TXT record
4732 lookups. A missing DMARC result in the headers is not independently flagged.
4733  
4734 =item C<abuse_contacts()> routes duplicated in C<form_contacts()>
4735  
4736 Both methods iterate the same six discovery routes independently. Any new
4737 discovery route must be added to both. A future refactor should share a
4738 single routing pass.
4739  
4740 =item CHI cache is a class-level mutable global
4741  
4742 The cross-message cache is shared across all instances in the process.
4743 Tests that populate the cache will affect subsequent tests. Pass the cache
4744 in via C<new()> (not currently supported) to enable proper isolation.
4745  
4746 =back
4747  
4748 =encoding utf-8
4749  
4750 =head1 FORMAL SPECIFICATION
4751  
4752 =head2 new
4753  
4754 -- Z notation (simplified)
4755 new == [
4756 timeout : N;
4757 trusted_relays : seq STRING;
4758 verbose : BOOL;
4759 _raw : STRING;
4760 _headers : seq (STRING x STRING);
4761 _origin? : IP_INFO | undefined;
4762 _urls? : seq URL_INFO | undefined;
4763 _risk? : RISK_INFO | undefined
4764 ]
4765 pre: timeout >= 0
4766 post: self.timeout = params.timeout /\ self._raw = ''
4767  
4768 =head2 parse_email
4769  
4770 -- Z notation
4771 parse_email == [
4772 Delta Email::Abuse::Investigator;
4773 text? : STRING | ref STRING
4774 ]
4775 pre: defined text?
4776 post: self._raw = deref(text?) /\
4777 self._origin = undefined /\
4778 self._urls = undefined /\
4779 self._risk = undefined
4780  
4781 =head2 originating_ip
4782  
4783 -- Z notation
4784 originating_ip == [
4785 Xi Email::Abuse::Investigator;
4786 result! : IP_INFO | undefined
4787 ]
4788 pre: self._raw /= ''
4789 post: result! = self._origin /\
4790 (result! /= undefined => result!.ip in EXTERNAL_IPS)
4791  
4792 =head2 embedded_urls
4793  
4794 -- Z notation
4795 embedded_urls == [
4796 Xi Email::Abuse::Investigator;
4797 result! : seq URL_INFO
4798 ]
4799 pre: self._raw /= ''
4800 post: result! = self._urls /\
4801 forall u : result! @ u.url =~ m{^https?://}i
4802  
4803 =head2 mailto_domains
4804  
4805 -- Z notation
4806 mailto_domains == [
4807 Xi Email::Abuse::Investigator;
4808 result! : seq DOMAIN_INFO
4809 ]
4810 pre: self._raw /= ''
4811 post: result! = self._mailto_domains /\
4812 forall d : result! @ d.domain =~ /\.[a-zA-Z]{2,}$/
4813  
4814 =head2 all_domains
4815  
4816 -- Z notation
4817 all_domains == [
4818 Xi Email::Abuse::Investigator;
4819 result! : seq STRING
4820 ]
4821 post: result! = deduplicate(
4822 map(_registrable, url_hosts union mailto_domains)
4823 )
4824  
4825 =head2 unresolved_contacts
4826  
4827 -- Z notation
4828 unresolved_contacts == [
4829 Xi Email::Abuse::Investigator;
4830 result! : seq UNRESOLVED_INFO
4831 ]
4832 post: forall u : result! @
4833 u.domain not_in covered_domains(abuse_contacts, form_contacts)
4834  
4835 =head2 sending_software
4836  
4837 -- Z notation
4838 sending_software == [
4839 Xi Email::Abuse::Investigator;
4840 result! : seq SW_INFO
4841 ]
4842 post: result! = self._sending_sw
4843  
4844 =head2 received_trail
4845  
4846 -- Z notation
4847 received_trail == [
4848 Xi Email::Abuse::Investigator;
4849 result! : seq HOP_INFO
4850 ]
4851 post: result! = self._rcvd_tracking
4852  
4853 =head2 risk_assessment
4854  
4855 -- Z notation
4856 risk_assessment == [
4857 Xi Email::Abuse::Investigator;
4858 result! : RISK_INFO
4859 ]
4860 post: result!.score = sum({ w(f.severity) | f in result!.flags }) /\
4861 result!.level = classify(result!.score)
4862 where:
4863 w(HIGH) = 3; w(MEDIUM) = 2; w(LOW) = 1; w(INFO) = 0
4864 classify(s) = HIGH if s >= 9
4865 | MEDIUM if s >= 5
4866 | LOW if s >= 2
4867 | INFO otherwise
4868  
4869 =head2 abuse_report_text
4870  
4871 -- Z notation
4872 abuse_report_text == [
4873 Xi Email::Abuse::Investigator;
4874 result! : STRING
4875 ]
4876 post: result! /= '' /\ result! ends_with '\n'
4877  
4878 =head2 abuse_contacts
4879  
4880 -- Z notation
4881 abuse_contacts == [
4882 Xi Email::Abuse::Investigator;
4883 result! : seq CONTACT_INFO
4884 ]
4885 post: forall c : result! @ c.address contains '@' /\
4886 forall c1, c2 : result! @ c1 /= c2 => c1.address /= c2.address
4887  
4888 =head2 form_contacts
4889  
4890 -- Z notation
4891 form_contacts == [
4892 Xi Email::Abuse::Investigator;
4893 result! : seq FORM_CONTACT_INFO
4894 ]
4895 post: forall c : result! @ c.form =~ m{^https?://} /\
4896 forall c1, c2 : result! @ c1 /= c2 => c1.form /= c2.form
4897  
4898 =head2 report
4899  
4900 -- Z notation
4901 report == [
4902 Xi Email::Abuse::Investigator;
4903 result! : STRING
4904 ]
4905 post: result! /= '' /\ result! ends_with '\n'
4906  
4907 =head2 header_value
4908  
4909 header_value : Object × FieldName → Maybe FieldValue
4910 header_value(o, n) ≜ first { lc(h.name) = lc(n) } o._headers .value
4911  
4912 =head1 LICENCE AND COPYRIGHT
4913  
4914 Copyright 2026 Nigel Horne.
4915  
4916 Usage is subject to GPL2 licence terms.
4917 If you use it,
4918 please let me know.
4919  
4920 =cut
4921  
4922 1;
↑ Summary bin/submit_abuse_report »