#!/usr/bin/env perl

# Summarise DMARC aggregate reports: one row per source IP.
#
# What matters in a report is whether a message was ours.  Our own failures are
# bugs to fix; anybody else's "fail" is a forgery attempt, which is the traffic
# a quarantine or reject policy is there to catch.  For that reason every row
# says whether the source address is one of ours, and the NOTE column separates
# the two ways DKIM can fail: no signature at all (somebody else claiming our
# domain) from a signature that does not verify (our own key or body).

use strict;
use warnings;

use Getopt::Long qw(GetOptions);
use IO::Uncompress::Gunzip qw($GunzipError);
use IO::Uncompress::Unzip qw($UnzipError);
use Pod::Usage qw(pod2usage);
use POSIX qw(strftime);
use Socket qw(inet_aton AF_INET);
use XML::PP;

my $home = $ENV{'HOME'} || (getpwuid($<))[7] || '.';

# Reporters send plain, gzipped and zipped XML, so all three are candidates.
my @DEFAULT_GLOBS = map { "$home/Downloads/$_" } qw(*.xml *.xml.gz *.zip);

# Where dmarc-weekly.sh puts the reports it has dealt with.
my $ARCHIVE_DIR = $ENV{'DMARC_ARCHIVE_DIR'} || "$home/dmarc-archive";

# Reports are kilobytes.  A file, or what it expands to, that is far bigger is
# not one, and is not worth filling memory with.
my $MAX_FILE_BYTES = 10 * 1024 * 1024;
my $MAX_XML_BYTES = 20 * 1024 * 1024;

# Company forms a registry appends to the same provider's name.
my @LEGAL_SUFFIXES = qw(llc inc incorporated ltd limited gmbh bv b v sl s l ab oy as sas sarl
	pty corp corporation co company plc ag srl spa kk pte llp);

# Our sending addresses, so that our own failures can be told from forgeries.
my @ours = grep { length } split(/[\s,]+/, $ENV{'DMARC_EXPECTED'} // '');
my $whois = 1;

# Reports are cut daily, so the newest window any of them covers is the only
# evidence this has that reporting is still happening: a corpus that stops
# moving looks like a quiet domain unless somebody reads the dates.  Three days
# leaves room for a reporter to be late and is short enough to notice a silence.
my $max_age = 3;	# days

GetOptions(
	'ours=s' => sub { push @ours, grep { length } split(/,/, $_[1]) },
	'no-whois' => sub { $whois = 0 },
	'max-age=i' => \$max_age,
	'help|h' => sub { pod2usage(-verbose => 1, -exitval => 0) },
) or pod2usage(-verbose => 0, -exitval => 2);

my @files = expand(@ARGV ? @ARGV : @DEFAULT_GLOBS);
if(!@files) {
	# The reports may all have been archived, and the last of them long ago.
	_warn_if_stale(undef) unless(@ARGV);
	print STDERR 'No report files found',
		(@ARGV ? '' : ' (looked for ' . join(' ', @DEFAULT_GLOBS) . ')'), "\n";
	exit(2);
}

my %OWNERS;
my %BY_OWNER;
my %LABEL;
my %TOTAL = ('files' => 0, 'messages' => 0, 'ours' => 0, 'failing' => 0);
my $newest;	# the end of the newest report window read, as an epoch

foreach my $file (@files) {
	summarise($file);
}

_warn_if_stale($newest);

if(@files > 1) {
	printf("\nTOTAL: %d files, %d messages, %d from our IPs, %d failing DMARC\n",
		@TOTAL{qw(files messages ours failing)});
	rollup();
}

exit(0);

sub summarise {
	my $file = shift;

	my $xml = eval { _read_report($file) };
	if(!defined($xml)) {
		my $error = $@;
		$error =~ s/\s+\z//;
		warn 'Skipping ', _clean($file), ': ', _clean($error), "\n";
		return;
	}

	# Anything that is not XML is turned away before it reaches the parser,
	# which would otherwise complain about a CSV or a tarball parked in the
	# same directory.
	if($xml !~ /\A\s*</) {
		warn 'Skipping ', _clean($file), ": not a DMARC aggregate report\n";
		return;
	}

	# XML::PP is pure Perl, so it installs where the C parsers do not; a
	# parse that does not leave a root element is not a report.
	my $root = eval { XML::PP->new()->parse($xml) };
	if(!$root || ref($root) ne 'HASH' || !defined($root->{'name'})) {
		warn 'Skipping ', _clean($file), ": not a DMARC aggregate report\n";
		return;
	}

	my $metadata = _child($root, 'report_metadata');
	my $policy = _child($root, 'policy_published');
	my $domain = _field($policy, 'domain') // '-';
	my $dates = _child($metadata, 'date_range');
	my $end = _field($dates, 'end');
	if(defined($end) && $end =~ /\A\d+\z/ && (!defined($newest) || $end > $newest)) {
		$newest = $end;
	}

	printf("\n%s\n", _clean($file));
	printf("\t%s <%s>  domain %s  p=%s sp=%s pct=%s adkim=%s aspf=%s\n",
		_field($metadata, 'org_name') // '?',
		_field($metadata, 'email') // '?',
		$domain,
		_field($policy, 'p') // '-',
		_field($policy, 'sp') // '-',
		_field($policy, 'pct') // '-',
		_field($policy, 'adkim') // '-',
		_field($policy, 'aspf') // '-');
	printf("\treport %s  %s -> %s\n\n",
		_field($metadata, 'report_id') // '?',
		_window(_field($dates, 'begin')),
		_window($end));

	printf("\t%-15s %3s  %-6s %-9s %-11s %-4s %-31s %s\n",
		'IP', 'N', 'DKIM', 'SPF', 'DISPOSITION', 'OURS', 'OWNER', 'NOTE');

	my ($messages, $mine, $failing) = (0, 0, 0);

	foreach my $record (_children($root, 'record')) {
		my $row = _child($record, 'row');
		my $evaluated = _child($row, 'policy_evaluated');
		my $ip = _field($row, 'source_ip') // '?';
		my $count = _field($row, 'count') // 1;
		my $dkim = _field($evaluated, 'dkim') // '-';
		my $spf = _field($evaluated, 'spf') // '-';
		my $disposition = _field($evaluated, 'disposition') // '-';

		my $is_ours = grep { $_ eq $ip } @ours;
		my $who = owner($ip);
		my $key = _owner_key($who);

		$messages += $count;
		$mine += $count if($is_ours);
		$failing += $count if($dkim ne 'pass' && $spf ne 'pass');
		$BY_OWNER{$key} += $count;
		$LABEL{$key} = $who
			if(!defined($LABEL{$key}) || length($who) > length($LABEL{$key}));

		printf("\t%-15s %3d  %-6s %-9s %-11s %-4s %-31.31s %s\n",
			$ip, $count, $dkim, $spf, $disposition,
			$is_ours ? 'yes' : 'no', $who, note($record, $domain));
	}

	printf("\n\t%d message%s, %d from our IPs, %d failing DMARC\n",
		$messages, ($messages == 1 ? '' : 's'), $mine, $failing);

	$TOTAL{'files'}++;
	$TOTAL{'messages'} += $messages;
	$TOTAL{'ours'} += $mine;
	$TOTAL{'failing'} += $failing;
}

# One network can be most of the corpus without any single address being the
# busiest, so the totals are also given by owner: the per-IP rows say who sent a
# message, and this says how much of the traffic that owner accounts for.  The
# name is not truncated, because a rollup that cuts two owners down to the same
# 31 columns would silently add them together.
sub rollup {
	my $total = $TOTAL{'messages'} || 1;

	printf("\n\t%-43s %8s  %s\n", 'OWNER', 'MESSAGES', 'SHARE');

	foreach my $key (sort { $BY_OWNER{$b} <=> $BY_OWNER{$a} || $LABEL{$a} cmp $LABEL{$b} } keys %BY_OWNER) {
		printf("\t%-43s %8d  %5.1f%%\n", $LABEL{$key}, $BY_OWNER{$key}, 100 * $BY_OWNER{$key} / $total);
	}

	return;
}

# One provider is spelled several ways by the registries: a range with an
# OrgName gives DigitalOcean, LLC and the next, with only a NetName, gives
# DIGITALOCEAN.  The rollup groups on this form - case, punctuation and a
# trailing legal suffix taken off - so the provider is one line, while names
# that describe different organisations stay apart.  The list lives with the
# other settings at the top, because nothing below exit(0) is ever run.
sub _owner_key {
	my $name = shift;

	my $key = lc($name // '');
	$key =~ s/[^a-z0-9]+/ /g;
	$key =~ s/\A\s+//;
	$key =~ s/\s+\z//;

	# Whole trailing words only, and repeatedly, so "Foo Co., Ltd." loses both.
	my $suffix = join('|', map { quotemeta } @LEGAL_SUFFIXES);
	1 while($key =~ s/(?:\A|\s)(?:$suffix)\z//);

	$key =~ s/\s+\z//;

	return length($key) ? $key : 'unknown';
}

# The signature evidence behind the verdicts.  A dkim=fail with no signature
# listed means the message was not signed at all; a signature that is listed
# and did not verify is ours to investigate.
sub note {
	my ($record, $domain) = @_;

	my @notes;
	my @signatures;

	foreach my $results (_children($record, 'auth_results')) {
		push @signatures, _children($results, 'dkim');
	}

	if(@signatures) {
		foreach my $signature (@signatures) {
			push @notes, sprintf('signed d=%s s=%s %s',
				_field($signature, 'domain') // '?',
				_field($signature, 'selector') // '?',
				_field($signature, 'result') // '?');
		}
	} else {
		push @notes, 'unsigned';
	}

	my $header_from = _field(_child($record, 'identifiers'), 'header_from');
	push @notes, "header_from=$header_from" if(defined($header_from) && $header_from ne $domain);

	my $row = _child($record, 'row');
	my $evaluated = _child($row, 'policy_evaluated');
	foreach my $reason (_children($evaluated, 'reason')) {
		my $type = _field($reason, 'type') // $reason->{'attributes'}{'type'};
		$type = _clean($type) if(defined($type));
		push @notes, "reason=$type" if(defined($type) && length($type));
	}

	return join('; ', @notes) || '-';
}

# Registries disagree about the field: ARIN has OrgName, RIPE org-name or
# descr, and the whois command itself has to be given a bare address.
sub owner {
	my $ip = shift;

	return $OWNERS{$ip} if(exists($OWNERS{$ip}));

	unless($ip =~ /\A[0-9a-fA-F:.]+\z/) {
		return $OWNERS{$ip} = '?';
	}

	my %seen;
	if($whois) {
		foreach my $line (split(/\n/, qx{timeout 10 whois $ip 2>/dev/null})) {
			$line =~ s/\A\s+//;
			next unless($line =~ /\A([A-Za-z][A-Za-z -]*?)\s*:\s*(\S.*?)\s*\z/);
			my ($key, $value) = (lc($1), $2);
			$value =~ s/\s*#.*\z//;
			$seen{$key} = $value unless(exists($seen{$key}));
		}
	}

	foreach my $key (qw(orgname org-name owner organization descr netname)) {
		return $OWNERS{$ip} = _clean($seen{$key}) if($seen{$key});
	}

	my $name = $ip =~ /\A\d+\./ ? gethostbyaddr(inet_aton($ip), AF_INET) : undef;

	return $OWNERS{$ip} = _clean($name || 'unknown');
}

# Reports are named after their domain and window, so a pattern is at least as
# likely as a list of paths; directories of reports are the third case.
sub expand {
	my @found;

	foreach my $pattern (@_) {
		if(-d $pattern) {
			push @found, glob("$pattern/*.xml"), glob("$pattern/*.xml.gz"), glob("$pattern/*.zip");
		} elsif($pattern =~ /[*?\[]/) {
			push @found, glob($pattern);
		} else {
			push @found, $pattern;
		}
	}

	my @reports = sort grep { -f $_ } @found;

	return @reports;
}

# Reporters send plain XML, a gzip stream or a zip.  Compression is detected
# from the leading bytes rather than the name, because the name is not evidence
# of anything.
sub _read_report {
	my $file = shift;

	my $size = -s $file;
	die "too large to be a report\n" if(defined($size) && $size > $MAX_FILE_BYTES);

	open(my $handle, '<', $file) or die "cannot open: $!\n";
	binmode($handle);
	my $magic = '';
	read($handle, $magic, 2);

	if($magic eq "\x1f\x8b") {
		close($handle);
		my $gz = IO::Uncompress::Gunzip->new($file) or die "cannot decompress: $GunzipError\n";
		return _read_bounded($gz);
	}

	if($magic eq 'PK') {
		close($handle);
		my $zip = IO::Uncompress::Unzip->new($file) or die "cannot unzip: $UnzipError\n";
		my $status = 1;
		while($status > 0) {
			return _read_bounded($zip) if(($zip->getHeaderInfo()->{'Name'} // '') =~ /\.xml\z/i);
			$status = $zip->nextStream();
		}
		die "no XML inside\n";
	}

	seek($handle, 0, 0);
	local $/;
	my $xml = <$handle>;
	close($handle);

	return $xml;
}

# The rest of a compressed stream, giving up when it is too big to be a report.
sub _read_bounded {
	my $stream = shift;

	my $xml = '';
	while(1) {
		my $read = $stream->read(my $chunk, 65536);
		die "cannot decompress\n" if(!defined($read) || $read < 0);
		last if($read == 0);
		$xml .= $chunk;
		die "expands too far to be a report\n" if(length($xml) > $MAX_XML_BYTES);
	}

	return $xml;
}

# The element children of a node, by local name: a report from one reporter
# prefixes its elements and one from another does not, and XML::PP keeps the
# prefix apart from the name either way.
sub _children {
	my ($node, $name) = @_;

	return () unless($node && ref($node) eq 'HASH');

	return grep { defined($_->{'name'}) && $_->{'name'} eq $name } @{$node->{'children'} || []};
}

sub _child {
	my ($node, $name) = @_;

	my ($child) = _children($node, $name);

	return $child;
}

# All the text under a node, as textContent would give it; text nodes are the
# children that have no element name.
sub _text {
	my $node = shift;

	return '' unless($node && ref($node) eq 'HASH');

	return join('', map { defined($_->{'name'}) ? _text($_) : ($_->{'text'} // '') } @{$node->{'children'} || []});
}

sub _field {
	my ($node, $name) = @_;

	my $child = _child($node, $name);
	return unless($child);

	my $text = _text($child);
	$text =~ s/\A\s+//;
	$text =~ s/\s+\z//;

	return _clean($text);
}

# Text from a report, or from whois, is somebody else's: control characters in
# it must not reach a terminal or a mail.
sub _clean {
	my $text = shift;

	if(utf8::is_utf8($text)) {
		$text =~ s/[\x00-\x1f\x7f-\x9f]/ /g;
	} else {
		$text =~ s/[\x00-\x1f\x7f]|\xc2[\x80-\x9f]/ /g;
	}

	return $text;
}

# The end of the report window in a file, or nothing when it has none to give.
sub _report_end {
	my $file = shift;

	my $root = eval { XML::PP->new()->parse(_read_report($file)) };
	return unless($root && ref($root) eq 'HASH');

	my $end = _field(_child(_child($root, 'report_metadata'), 'date_range'), 'end');

	return (defined($end) && $end =~ /\A\d+\z/) ? $end : undef;
}

# Warn when reporting looks to have stopped.  A run over the default places
# looks in the archive too before saying so, since that is where the weekly
# run leaves the newest reports.
sub _warn_if_stale {
	my $end = shift;

	if(!@ARGV && (!defined($end) || defined(_staleness($end, $max_age)))) {
		foreach my $file (expand($ARCHIVE_DIR)) {
			my $archived = _report_end($file);
			$end = $archived if(defined($archived) && (!defined($end) || $archived > $end));
		}
	}

	if(my $stale = _staleness($end, $max_age)) {
		warn "$stale\n";
	}

	return;
}

# A report covers one day and ends when that day did, so the newest end is when
# a reporter last had something to say.  Undef while the corpus is current,
# and the warning to give once it is not.
sub _staleness {
	my ($end, $max_age) = @_;

	return unless(defined($end));

	my $age = time() - $end;
	return unless($age > $max_age * 86400);

	return sprintf('Warning: the newest report period ends %s, %d days ago; DMARC reporting may have stopped (--max-age=%d)',
		_window($end), int($age / 86400), $max_age);
}

sub _window {
	my $epoch = shift;

	return '?' unless(defined($epoch) && $epoch =~ /\A\d+\z/);

	return strftime('%Y-%m-%d %H:%MZ', gmtime($epoch));
}

__END__

=head1 NAME

dmarc-summary - summarise DMARC aggregate reports, one row per source IP

=head1 SYNOPSIS

	dmarc-summary [options] [file|pattern|directory ...]

	# every report that has landed in ~/Downloads
	dmarc-summary

	# one file, with an extra address counted as ours
	dmarc-summary --ours=192.0.2.10 '~/Downloads/*.xml'

	# complain when the newest report read is more than two days old
	dmarc-summary --max-age=2

=head1 DESCRIPTION

Reads DMARC aggregate reports (C<feedback> XML, as sent by Outlook.com,
Google and others, plain, gzipped or zipped) and prints, for each report, the published
policy and one
line per source IP: how many messages came from it, the DKIM and SPF verdicts,
the disposition applied, whether the address is one of ours, who owns it, and
the signature evidence behind the verdicts.

A C<dkim=fail> row with C<unsigned> in the last column is a message that
carried no signature at all - somebody else sending mail as our domain.  A row
that names a signature and still fails is our own problem to investigate.

When more than one report is read, the grand total is followed by a rollup by
owner, largest first, with each owner's share of the messages read.  The
per-IP rows say who sent a message; the rollup says how much of the traffic one
network accounts for, which is what a decision to block a provider rests on.
The owners are the ones in the OWNER column, so they come from the same whois
lookup; under B<--no-whois> the rollup falls back to the reverse DNS names
that column shows instead.

Registries spell one provider several ways - a range with an C<OrgName> gives
C<DigitalOcean, LLC> and the next, with only a C<NetName>, gives
C<DIGITALOCEAN> - so the rollup groups names with the case, punctuation and a
trailing legal suffix (C<LLC>, C<Ltd>, C<Inc> and the like) taken off, and
prints the longest variant that was seen for each group.  Only the spelling is
normalised: owners whose names differ in their words remain separate lines.

A report covers one day, so the newest window in the corpus is evidence that
reporting is still going on.  When the newest window read ended more than
B<--max-age> days ago the programme warns on standard error: either nothing is
being sent as the domain, or the reports are not arriving.  A silence nobody
notices is what this check is for.

The owner of each address is looked up with whois(1), run through
timeout(1), so each address in the reports is sent to a whois server unless
B<--no-whois> is given.  Where either programme is missing, as timeout(1) often
is on macOS, the reverse DNS name is shown instead.

A file over 10 MB, or one that expands to more than 20 MB, is skipped.  Control
characters in what the reports and whois say are printed as spaces.

=head1 OPTIONS

=over 4

=item B<--ours>=I<address>[,I<address>...]

Add source addresses that count as ours, to those in C<DMARC_EXPECTED>;
repeatable.  With neither, no address counts as ours.

=item B<--no-whois>

Do not ask whois for the owner of each source address; the reverse DNS name is
shown instead.  Faster, and useful when the whois servers are unreachable or
the addresses should not be sent to them.

=item B<--max-age>=I<days>

Warn when the newest report period read ended more than I<days> days ago.
Defaults to 3.

=item B<-h>, B<--help>

Show this documentation.

=back

=head1 FILES

Without arguments, every F<*.xml>, F<*.xml.gz> and F<*.zip> in F<~/Downloads>
is read, since that is where DMARC reports in this mailbox land.  Arguments may be
paths, shell patterns or directories of reports; anything that is not a
parseable report is skipped with a warning.

Before such a run warns that reporting has stopped, and when it finds nothing
to read, it also looks at the dates of the reports archived in
C<DMARC_ARCHIVE_DIR>, which are not otherwise summarised.

Gzip and zip are detected from the file's leading bytes, not from its name, so a report
saved without the F<.gz> suffix is still read.

=head1 ENVIRONMENT

=over 4

=item B<HOME>

Where the search without arguments starts: the reports in F<~/Downloads> are
read, and F<~> is B<HOME>.

=item B<DMARC_EXPECTED>

Our sending addresses, separated by commas or spaces, as F<dmarc-report.pl>
reads them.

=item B<DMARC_ARCHIVE_DIR>

The archive whose dates are looked at.  Default F<~/dmarc-archive>.

=back

=head1 EXIT STATUS

0 when the reports that could be read were summarised, including when some
files were skipped for not being reports.  A corpus whose newest report is
older than B<--max-age> days is a warning on standard error, not a different
status: the reports that were read were summarised.

2 when the options were not usable, or when there were no report files to read
at all.

=head1 AUTHOR

Nigel Horne, C<< <njh at nigelhorne.com> >>

=head1 LICENCE

Copyright 2026 Nigel Horne.

GNU General Public License, version 2, as in the F<LICENSE> file.

=cut
