Mail-SpamAssassin
view release on metacpan or search on metacpan
sa-update.raw view on Meta::CPAN
or die "Unable to verify file hashes! You must install a modern version of Digest::SHA.";
$have_lwp = eval {
require LWP::UserAgent;
require LWP::Protocol::https;
};
if (eval { require IO::Socket::IP }) { # handles IPv6 and IPv4
$io_socket_module_name = 'IO::Socket::IP';
} elsif (eval { require IO::Socket::INET6 }) { # handles IPv6 and IPv4
$io_socket_module_name = 'IO::Socket::INET6';
} elsif (eval { require IO::Socket::INET }) { # IPv4 only
$io_socket_module_name = 'IO::Socket::INET';
}
$have_inet4 = # can we create a PF_INET socket?
defined $io_socket_module_name && eval {
my $sock =
$io_socket_module_name->new(LocalAddr => '0.0.0.0', Proto => 'tcp');
$sock->close or die "error closing socket: $!" if $sock;
$sock ? 1 : undef;
};
$have_inet6 = # can we create a PF_INET6 socket?
defined $io_socket_module_name &&
$io_socket_module_name ne 'IO::Socket::INET' &&
eval {
my $sock =
$io_socket_module_name->new(LocalAddr => '::', Proto => 'tcp');
$sock->close or die "error closing socket: $!" if $sock;
$sock ? 1 : undef;
};
}
# These should already be available
use Mail::SpamAssassin;
use Mail::SpamAssassin::Util qw(untaint_var untaint_file_path
proc_status_ok exit_status_str am_running_on_windows
secure_tmpfile secure_tmpdir);
# Make the main dbg() accessible in our package w/o an extra function
*dbg=\&Mail::SpamAssassin::dbg;
sub dbg;
$| = 1; # autoflushing STDOUT makes verbose output consistent with warnings
# Clean up PATH appropriately
Mail::SpamAssassin::Util::clean_path_in_taint_mode();
##############################################################################
# Default list of GPG keys allowed to sign update releases
#
# pub 4096R/5244EC45 2005-12-20
# Key fingerprint = 5E54 1DC9 59CB 8BAC 7C78 DFDC 4056 A61A 5244 EC45
# uid updates.spamassassin.org Signing Key <release@spamassassin.org>
# sub 4096R/24F434CE 2005-12-20
#
# note for gpg newbs: these are "long" gpg keyids. It's common to also
# use the last 8 hex digits as a shorter keyid string.
#
my %valid_GPG = (
'0C2B1D7175B852C64B3CDC716C55397824F434CE' => 1,
'5E541DC959CB8BAC7C78DFDC4056A61A5244EC45' => 1,
);
# Default list of channels to update against
#
my @channels = ( 'updates.spamassassin.org' );
my $IGNORE_MIRBY_OLDER_THAN = (24 * 60 * 60 * 7); # 1 week
##############################################################################
my %opt;
@{$opt{'gpgkey'}} = ();
@{$opt{'channel'}} = ();
my $GPG_ENABLED = 1;
$opt{'gpghomedir'} = File::Spec->catfile($LOCAL_RULES_DIR, 'sa-update-keys');
Getopt::Long::Configure(
qw(bundling no_getopt_compat no_auto_abbrev no_ignore_case));
GetOptions(
'debug|D:s' => \$opt{'debug'},
'version|V' => \$opt{'version'},
'help|h|?' => \$opt{'help'},
'verbose|v+' => \$opt{'verbose'},
'checkonly' => \$opt{'checkonly'},
'allowplugins' => \$opt{'allowplugins'},
'reallyallowplugins' => \$opt{'reallyallowplugins'},
'refreshmirrors' => \$opt{'refreshmirrors'},
'forcemirror=s' => \$opt{'forcemirror'},
'httputil=s' => \$opt{'httputil'},
'score-multiplier=s' => \$opt{'score-multiplier'},
'score-limit=s' => \$opt{'score-limit'},
# allow multiple of these on the commandline
'gpgkey=s' => $opt{'gpgkey'},
'gpghomedir=s' => \$opt{'gpghomedir'},
'channel=s' => $opt{'channel'},
'install=s' => \$opt{'install'},
'import=s' => \$opt{'import'},
'gpgkeyfile=s' => \$opt{'gpgkeyfile'},
'channelfile=s' => \$opt{'channelfile'},
'updatedir=s' => \$opt{'updatedir'},
'gpg!' => \$GPG_ENABLED,
'4' => sub { $opt{'force_pf'} = 'inet' },
'6' => sub { $opt{'force_pf'} = 'inet6' },
# backward compatibility
'usegpg' => \$GPG_ENABLED,
) or print_usage_and_exit();
if ( defined $opt{'help'} ) {
print_usage_and_exit("For more information read the sa-update man page.\n", 0);
}
if ( defined $opt{'version'} ) {
print_version();
exit(0);
}
if ( $opt{'allowplugins'} && !$opt{'reallyallowplugins'} ) {
warn "Security warning: dangerous option --allowplugins used:\n".
"- there should never be need to use this option, see man sa-update(1)\n".
"- specify --reallyallowplugins to allow activating plugins\n";
exit 2;
}
$use_inet4 = $have_inet4 && ( !$opt{'force_pf'} || $opt{'force_pf'} eq 'inet' );
$use_inet6 = $have_inet6 && ( !$opt{'force_pf'} || $opt{'force_pf'} eq 'inet6' );
if ( $opt{'force_pf'} && $opt{'force_pf'} eq 'inet' && !$have_inet4 ) {
warn "Option -4 specified but support for the ".
"INET protocol family is not available.\n";
}
if ( $opt{'force_pf'} && $opt{'force_pf'} eq 'inet6' && !$have_inet6 ) {
warn "Option -6 specified but support for the ".
"INET6 protocol family is not available.\n";
}
if ( defined $opt{'httputil'} && $opt{'httputil'} !~ /^(curl|wget|fetch|lwp)$/ ) {
warn "Invalid parameter for --httputil, curl|wget|fetch|lwp wanted\n";
}
if ( defined $opt{'score-multiplier'} && $opt{'score-multiplier'} !~ /^\d+(?:\.\d+)?$/ ) {
die "Invalid parameter for --score-multiplier, integer or float expected.\n";
}
if ( defined $opt{'score-limit'} && $opt{'score-limit'} !~ /^\d+(?:\.\d+)?$/ ) {
die "Invalid parameter for --score-limit, integer or float expected.\n";
}
# Figure out what version of SpamAssassin we're using, and also figure out the
# reverse of it for the DNS query. Handle x.yyyzzz as well as x.yz.
my $SAVersion = $Mail::SpamAssassin::VERSION;
if ($SAVersion =~ /^(\d+)\.(\d{3})(\d{3})$/) {
$SAVersion = join(".", $1+0, $2+0, $3+0);
}
elsif ($SAVersion =~ /^(\d)\.(\d)(\d)$/) {
$SAVersion = "$1.$2.$3";
}
else {
die "fatal: SpamAssassin version number '$SAVersion' is in an unknown format!\n";
}
my $RevSAVersion = join(".", reverse split(/\./, $SAVersion));
# set debug areas, if any specified (only useful for command-line tools)
$opt{'debug'} ||= 'all' if (defined $opt{'debug'});
# Find the default site rule directory, also setup debugging and other M::SA bits
my $SA = Mail::SpamAssassin->new({
debug => $opt{'debug'},
local_tests_only => 1,
dont_copy_prefs => 1,
PREFIX => $PREFIX,
DEF_RULES_DIR => $DEF_RULES_DIR,
LOCAL_RULES_DIR => $LOCAL_RULES_DIR,
LOCAL_STATE_DIR => $LOCAL_STATE_DIR,
});
if (defined $opt{'updatedir'}) {
$opt{'updatedir'} = untaint_file_path($opt{'updatedir'});
}
else {
$opt{'updatedir'} = $SA->sed_path('__local_state_dir__/__version__');
}
# check only disabled gpg
# https://bz.apache.org/SpamAssassin/show_bug.cgi?id=5854
if ( defined $opt{'checkonly'}) {
$GPG_ENABLED=0;
dbg("gpg: Disabling gpg requirement due to checkonly flag.");
}
dbg("generic: sa-update version $VERSION");
dbg("generic: using update directory: $opt{'updatedir'}");
# doesn't really display useful things for this script, but we do want
# a module/version listing, etc. sa-update may be used for older versions
# of SA that don't include this function, so eval around it.
eval { $SA->debug_diagnostics(); 1; };
$SA->finish();
# untaint the command-line args; since the root user supplied these, and
# we're not a setuid script, we trust them
foreach my $optkey (keys %opt) {
next if ref $opt{$optkey};
untaint_var(\$opt{$optkey});
}
##############################################################################
# Deal with gpg-related options
if (@{$opt{'gpgkey'}}) {
$GPG_ENABLED = 1;
foreach my $key (@{$opt{'gpgkey'}}) {
unless (is_valid_gpg_key_id($key)) {
dbg("gpg: invalid gpgkey parameter $key");
next;
}
$key = uc $key;
dbg("gpg: adding key id $key");
$valid_GPG{$key} = 1;
}
}
if (defined $opt{'gpgkeyfile'}) {
$GPG_ENABLED = 1;
open(GPG, $opt{'gpgkeyfile'})
or die "cannot open $opt{'gpgkeyfile'} for reading: $!\n";
dbg("gpg: reading in gpgfile ".$opt{'gpgkeyfile'});
while(my $key = <GPG>) {
chomp $key;
$key =~ s/#.*$//; # remove comments
$key =~ s/^\s+//; # remove leading whitespace
$key =~ s/\s+$//; # remove tailing whitespace
next if $key eq ''; # skip empty lines
unless (is_valid_gpg_key_id($key)) {
dbg("gpg: invalid key id $key");
next;
}
$key = uc $key;
dbg("gpg: adding key id $key");
$valid_GPG{$key} = 1;
}
close(GPG) or die "cannot close $opt{'gpgkeyfile'}: $!";
}
# At this point, we need to know where GPG is ...
my $GPGPath;
if ($GPG_ENABLED || $opt{'import'}) {
# find GPG in the PATH
# bug 4958: for *NIX it's "gpg", in Windows it's "gpg.exe"
$GPGPath = 'gpg' . $Config{_exe};
dbg("gpg: Searching for '$GPGPath'");
if ($GPGPath = Mail::SpamAssassin::Util::find_executable_in_env_path($GPGPath)) {
dbg("gpg: found $GPGPath");
# bug 5030: if GPGPath has a space, put it in quotes
if ($GPGPath =~ / /) {
$GPGPath =~ s/"/\\"/g;
$GPGPath = qq/"$GPGPath"/;
dbg("gpg: path changed to $GPGPath");
}
}
else {
die "error: gpg required but not found! It is not recommended, but you can use \"sa-update\" with the --no-gpg to skip the verification. \n";
}
# GPG was found, and we've been asked to import a key only
if ( $opt{'import'} ) {
my $ex = import_gpg_key($opt{'import'});
exit $ex;
}
# does the sa-update keyring exist? if not, import it
if(!-f File::Spec->catfile($opt{'gpghomedir'}, "trustdb.gpg")) {
import_default_keyring();
# attempt to continue even if this fails, anyway
}
# specify which keys are trusted
dbg("gpg: release trusted key id list: ".join(" ", keys %valid_GPG));
# convert fingerprint gpg ids to keyids
foreach (keys %valid_GPG) {
my $id = substr $_, -8;
$valid_GPG{$id} = 1;
}
}
##############################################################################
# Deal with channel-related options
if (defined $opt{'channel'} && scalar @{$opt{'channel'}} > 0) {
@channels = @{$opt{'channel'}};
}
if (defined $opt{'channelfile'}) {
open(CHAN, $opt{'channelfile'})
or die "cannot open $opt{'channelfile'} for reading: $!\n";
dbg("channel: reading in channelfile ".$opt{'channelfile'});
@channels = ();
while(my $chan = <CHAN>) {
chomp $chan;
$chan =~ s/#.*$//; # remove comments
$chan =~ s/^\s+//; # remove leading whitespace
$chan =~ s/\s+$//; # remove tailing whitespace
next if $chan eq ''; # skip empty lines
$chan = lc $chan;
dbg("channel: adding $chan");
push(@channels, $chan);
}
close(CHAN) or die "cannot close $opt{'channelfile'}: $!";
}
# untaint the channel listing
for(my $ind = 0; $ind < @channels; $ind++) {
local($1); # bug 5061: prevent random taint flagging of $1
if ($channels[$ind] =~ /^([a-zA-Z0-9._-]+)$/) {
untaint_var(\$channels[$ind]);
}
else {
dbg("channel: skipping invalid channel: $channels[$ind]");
splice @channels, $ind, 1;
$ind--; # the next element takes the place of the deleted one
}
}
my ($res, $ua);
if ($opt{'install'}) {
if (scalar @channels > 1) {
die "fatal: --install cannot be used with multiple --channel switches.\n";
}
} else {
$res = Net::DNS::Resolver->new();
$res->force_v4(1) if $have_inet4 &&
$opt{'force_pf'} && $opt{'force_pf'} eq 'inet';
}
# Generate a temporary file to put channel content in for later use ...
sa-update.raw view on Meta::CPAN
$SHA256 = read_content($path_sha256, 0); # ascii
$preserve_files{$path_sha256} = 1;
}
if (-s $path_asc) {
$GPG = read_content($path_asc, 0); # ascii
$preserve_files{$path_asc} = 1;
}
}
}
unless ($content && (($GPG_ENABLED && $GPG) || (!$GPG_ENABLED && ($SHA512 || $SHA256)))) {
if ($instfile) {
channel_failed("channel '$channel': missing checksum files $instfile\{,.sha512,.sha256\}");
} else {
channel_failed("channel '$channel': could not find working mirror");
}
next;
}
if ( $SHA512 ) {
# Validate the SHA512 signature
{ local($1);
$SHA512 =~ /^([a-fA-F0-9]{128})\b/;
$SHA512 = defined $1 ? lc($1) : 'INVALID';
}
my $digest = sha512_hex($content);
dbg("sha512: verification wanted: $SHA512");
dbg("sha512: verification result: $digest");
unless ($digest eq $SHA512) {
channel_failed("channel '$channel': SHA512 verification failed");
next;
}
}
if ( $SHA256 ) {
# Validate the SHA256 signature
{ local($1);
$SHA256 =~ /^([a-fA-F0-9]{64})\b/;
$SHA256 = defined $1 ? lc($1) : 'INVALID';
}
my $digest = sha256_hex($content);
dbg("sha256: verification wanted: $SHA256");
dbg("sha256: verification result: $digest");
unless ($digest eq $SHA256) {
channel_failed("channel '$channel': SHA256 verification failed");
next;
}
}
# Write the content out to a temp file for GPG/Archive::Tar interaction
dbg("channel: populating temp content file %s", $content_file);
open(TMP, ">$content_file")
or die "fatal: cannot create content temp file $content_file: $!\n";
binmode TMP
or die "fatal: cannot set binmode on content temp file $content_file: $!\n";
print TMP $content
or die "fatal: cannot write to content temp file $content_file: $!\n";
close TMP
or die "fatal: cannot close content temp file $content_file: $!\n";
# to sign : gpg -bas file
# to verify: gpg --verify --batch --no-tty --status-fd=1 -q --logger-fd=1 file.asc file
# look for : [GNUPG:] GOODSIG 6C55397824F434CE updates.spamassassin.org [...]
# [GNUPG:] VALIDSIG 0C2B1D7175B852C64B3CDC716C55397824F434CE [...]
# [GNUPG:] NO_PUBKEY 6C55397824F434CE
if ($GPG) {
dbg("gpg: populating temp signature file");
my $sig_file;
($sig_file, $tfh) = secure_tmpfile();
$tfh
or die "fatal: couldn't create temp file for GPG signature: $!\n";
binmode $tfh
or die "fatal: cannot set binmode on temp file for GPG signature: $!\n";
print $tfh $GPG
or die "fatal: cannot write temp file for GPG signature: $!\n";
close $tfh
or die "fatal: cannot close temp file for GPG signature: $!\n";
undef $tfh;
dbg("gpg: calling gpg");
my $gpghome = interpolate_gpghomedir();
# TODO: we could also use "--keyserver pgp.mit.edu" or similar,
# to autodownload missing keys...
my $CMD = "$GPGPath $gpghome --verify --batch ".
"--no-tty --status-fd=1 -q --logger-fd=1";
unless (open(CMD, "$CMD $sig_file $content_file|")) {
unlink $sig_file or warn "error: cannot unlink $sig_file: $!\n";
die "fatal: couldn't execute $GPGPath: $!\n";
}
# Determine the fate of the signature
my $signer = '';
my $missingkeys = '';
while(my $GNUPG = <CMD>) {
chop $GNUPG;
dbg ("gpg: $GNUPG");
if ($GNUPG =~ /^gpg: fatal:/) {
warn $GNUPG."\n"; # report bad news
}
local($1);
if ($GNUPG =~ /^\Q[GNUPG:]\E NO_PUBKEY \S+(\S{8})$/) {
$missingkeys .= $1." ";
}
next unless ($GNUPG =~ /^\Q[GNUPG:]\E (?:VALID|GOOD)SIG (\S{8,40})/);
my $key = $1;
# we want either a keyid (8) or a fingerprint (40)
if (length $key > 8 && length $key < 40) {
substr($key, 8) = '';
}
# use the longest match we can find
$signer = $key if length $key > length $signer;
}
my $errno = 0; close CMD or $errno = $!;
proc_status_ok($?,$errno)
or warn("gpg: process '$GPGPath' finished: ".
exit_status_str($?,$errno)."\n");
unlink $sig_file or warn "cannot unlink $sig_file: $!\n";
if ($signer) {
my $keyid = substr $signer, -8;
dbg("gpg: found signature made by key $signer");
if (exists $valid_GPG{$signer}) {
dbg("gpg: key id $signer is release trusted");
}
elsif (exists $valid_GPG{$keyid}) {
dbg("gpg: key id $keyid is release trusted");
}
else {
dbg("gpg: key id $keyid is not release trusted");
$signer = undef;
}
}
unless ($signer) {
warn "error: GPG validation failed!\n";
if ($missingkeys) {
warn <<ENDOFVALIDATIONERR;
The update downloaded successfully, but it was not signed with a trusted GPG
key. Instead, it was signed with the following keys:
$missingkeys
Perhaps you need to import the channel's GPG key? For example:
wget https://spamassassin.apache.org/updates/GPG.KEY
sa-update --import GPG.KEY
ENDOFVALIDATIONERR
} else {
warn <<ENDOFVALIDATIONERR;
The update downloaded successfully, but the GPG signature verification
failed.
ENDOFVALIDATIONERR
}
channel_failed("channel '$channel': GPG validation failed");
next;
}
}
# OK, we're all validated at this point, install the new version
dbg("channel: file verification passed, testing update");
dbg("channel: extracting archive");
if (!taint_safe_archive_extract($UPDTmp, $content_file)) {
channel_failed("channel '$channel': archive extraction failed");
next;
}
# check --lint
if (!lint_check_dir($UPDTmp)) {
channel_failed("channel '$channel': lint check of update failed");
next;
}
dbg("channel: lint check succeeded, extracting archive to $UPDDir...");
my @totry = (
{
'try' => sub {
if (-d $UPDDir) {
# ok that worked, too late to stop now! At this stage, if there are
# errors, we have to attempt to carry on regardless, since we've already
sa-update.raw view on Meta::CPAN
return $mirrors[0];
}
##############################################################################
sub check_mirror_af {
my ($mirror) = @_;
# RFC 3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
$mirror =~ s{^([a-z][a-z0-9.+-]*)://}{}si; # strip scheme like http://
my $scheme = lc($1);
# No DNS check needed for proxied connections (caveat: no_proxy is not checked)
my $http_proxy = (defined $ENV{"http_proxy"} && $ENV{"http_proxy"} =~ /\S/) ||
(defined $ENV{"HTTP_PROXY"} && $ENV{"HTTP_PROXY"} =~ /\S/);
my $https_proxy = (defined $ENV{"https_proxy"} && $ENV{"https_proxy"} =~ /\S/) ||
(defined $ENV{"HTTPS_PROXY"} && $ENV{"HTTPS_PROXY"} =~ /\S/);
return 1 if $scheme eq "http" && $http_proxy;
return 1 if $scheme eq "https" && $https_proxy;
# No DNS check needed for IPv4 or IPv6 address literal
return 1 if $use_inet4 && $mirror =~ m{^\d+\.\d+\.\d+\.\d+(?:[:/]|$)};
return 1 if $use_inet6 && $mirror =~ m{^\[};
$mirror =~ s{[:/].*}{}s; # strip all starting from :port or /path
return 1 if $use_inet4 && do_dns_query($mirror, "A");
return 1 if $use_inet6 && do_dns_query($mirror, "AAAA");
return 0;
}
##############################################################################
sub print_version {
printf("sa-update version %s\n running on Perl version %s\n", $VERSION,
join(".", map( 0+($_||0), ( $] =~ /(\d)\.(\d{3})(\d{3})?/ ))));
}
##############################################################################
sub print_usage_and_exit {
my ( $message, $exitval ) = @_;
$exitval ||= 64;
if ($exitval == 0) {
print_version();
print("\n");
}
pod2usage(
-verbose => 0,
-message => $message,
-exitval => $exitval,
);
}
##############################################################################
sub usage {
my ( $verbose, $message ) = @_;
print "sa-update version $VERSION\n";
pod2usage( -verbose => $verbose, -message => $message, -exitval => 64 );
}
##############################################################################
sub interpolate_gpghomedir {
my $gpghome = '';
if ($opt{'gpghomedir'}) {
$gpghome = $opt{'gpghomedir'};
if (am_running_on_windows()) {
# windows is single-quote-phobic; bug 4958 cmt 7
$gpghome =~ s/\"/\\\"/gs;
$gpghome = "--homedir=\"$gpghome\"";
} else {
$gpghome =~ s/\'/\\\'/gs;
$gpghome = "--homedir='$gpghome'";
}
}
return $gpghome;
}
##############################################################################
sub check_gpghomedir {
unless (-d $opt{gpghomedir}) {
dbg("gpg: creating gpg home dir ".$opt{gpghomedir});
# use 0700 to avoid "unsafe permissions" warning
mkpath([$opt{gpghomedir}], 0, 0700)
or die "cannot mkpath $opt{gpghomedir}: $!";
}
}
##############################################################################
sub import_gpg_key {
my $keyfile = shift;
my $gpghome = interpolate_gpghomedir();
check_gpghomedir();
my $CMD = "$GPGPath $gpghome --batch ".
"--no-tty --status-fd=1 -q --logger-fd=1 --import";
unless (open(CMD, "$CMD $keyfile|")) {
die "fatal: couldn't execute $GPGPath: $!\n";
}
# Determine the fate of the signature
while(my $GNUPG = <CMD>) {
chop $GNUPG;
dbg ("gpg: $GNUPG");
if ($GNUPG =~ /^gpg: /) {
warn $GNUPG."\n"; # report bad news
}
if ($GNUPG =~ /^IMPORTED /) {
dbg("gpg: gpg key imported successfully");
}
}
my $errno = 0; close CMD or $errno = $!;
proc_status_ok($?,$errno)
or warn("gpg: process '$CMD' finished: ".exit_status_str($?,$errno)."\n");
return ($? >> 8);
}
##############################################################################
sub import_default_keyring {
my $defkey = File::Spec->catfile ($DEF_RULES_DIR, "sa-update-pubkey.txt");
unless (-f $defkey) {
dbg("gpg: import of default keyring failed, couldn't find sa-update-pubkey.txt");
return;
}
dbg("gpg: importing default keyring to ".$opt{gpghomedir});
check_gpghomedir();
import_gpg_key($defkey);
}
##############################################################################
sub is_valid_gpg_key_id {
# either a keyid (8 bytes) or a fingerprint (40 bytes)
return ($_[0] =~ /^[a-fA-F0-9]+$/ && (length $_[0] == 8 || length $_[0] == 40));
}
##############################################################################
sub clean_update_dir {
my($dir, $preserve_files_ref) = @_;
dbg("generic: cleaning directory %s", $dir);
unless (opendir(DIR, $dir)) {
warn "error: cannot opendir $dir: $!\n";
dbg("generic: attempt to opendir ($dir) failed");
return;
}
while(my $file = readdir(DIR)) {
next if $file eq '.' || $file eq '..';
my $path = File::Spec->catfile($dir, $file);
if ($preserve_files_ref && $preserve_files_ref->{$path}) {
dbg("generic: preserving $file");
next;
}
untaint_var(\$path);
next unless -f $path;
dbg("generic: unlinking $file");
if (!unlink $path) {
warn "error: cannot remove file $path: $!\n";
closedir(DIR) or die "cannot close directory $dir: $!";
return;
}
}
closedir(DIR) or die "cannot close directory $dir: $!";
return 1;
}
sub delete_files {
my(@filenames) = @_;
foreach my $path (@filenames) {
dbg("generic: unlinking $path");
unlink $path or warn "error: cannot unlink file $path: $!\n";
}
return 1;
}
##############################################################################
sub lint_check_dir {
my $dir = shift;
# due to the Logger module's globalness (all M::SA objects share the same
# Logger setup), we can't change the debug level here to only include
# "config" or otherwise be more terse. :(
my $spamtest = Mail::SpamAssassin->new( {
rules_filename => $dir,
site_rules_filename => $LOCAL_RULES_DIR,
ignore_site_cf_files => 1,
userprefs_filename => File::Spec->catfile($dir, "doesnotexist"),
local_tests_only => 1,
dont_copy_prefs => 1,
PREFIX => $PREFIX,
DEF_RULES_DIR => $DEF_RULES_DIR,
LOCAL_RULES_DIR => $LOCAL_RULES_DIR,
LOCAL_STATE_DIR => $LOCAL_STATE_DIR,
});
# need to kluge disabling bayes since it may try to expire the DB, and
# without the proper config it's not going to be good.
$spamtest->{conf}->{use_bayes} = 0;
my $res = $spamtest->lint_rules();
$spamtest->finish();
return $res == 0;
}
##############################################################################
=head1 NAME
sa-update - automate SpamAssassin rule updates
=head1 SYNOPSIS
B<sa-update> [options]
Options:
--channel channel Retrieve updates from this channel
Use multiple times for multiple channels
--channelfile file Retrieve updates from the channels in the file
--checkonly Check for update availability, do not install
--install file Install updates directly from this file. Signature
verification will use "file.asc", or "file.sha512"
or "file.sha256".
--allowplugins Allow updates to load plugin code (DANGEROUS)
--gpgkey key Trust the key id to sign releases
Use multiple times for multiple keys
--gpgkeyfile file Trust the key ids in the file to sign releases
--gpghomedir path Store the GPG keyring in this directory
--gpg and --nogpg Use (or do not use) GPG to verify updates
(--gpg is assumed by use of the above
--gpgkey and --gpgkeyfile options)
--import file Import GPG key(s) from file into sa-update's
keyring. Use multiple times for multiple files
--updatedir path Directory to place updates, defaults to the
SpamAssassin site rules directory
(default: @@LOCAL_STATE_DIR@@/@@VERSION@@)
--refreshmirrors Force the MIRRORED.BY file to be updated
--forcemirror url Use a specific mirror instead of downloading from
official mirrors
--httputil util Force used download tool. By default first found
from these is used: curl, wget, fetch, lwp
--score-multiplier x.x Adjust all scores from update channel, multiply
with given value (integer or float).
--score-limit x.x Adjust all scores from update channel, limit
to given value (integer or float). Limiting
is done after possible multiply operation.
-D, --debug [area=n,...] Print debugging messages
-v, --verbose Be verbose, like print updated channel names;
For more verbosity specify multiple times
-V, --version Print version
-h, --help Print usage message
-4 Force using the inet protocol (IPv4), not inet6
-6 Force using the inet6 protocol (IPv6), not inet
=head1 DESCRIPTION
sa-update automates the process of downloading and installing new rules and
configuration, based on channels. The default channel is
I<updates.spamassassin.org>, which has updated rules since the previous
release.
NOTE: channel names are domain names, but DO NOT typically have any DNS
records other than (maybe) NS records. There is a tree of records below that
name which denote the SpamAssassin version and resolve that name to the
version number of the latest rules, e.g. to find the latest update
version number for SpamAssassin v4.0.0:
$ host -t txt 0.0.4.updates.spamassassin.org
0.0.4.updates.spamassassin.org is an alias for 3.3.3.updates.spamassassin.org.
3.3.3.updates.spamassassin.org descriptive text "1907730"
That also illuminates the fact that the current ruleset is supposed to be
backward-compatible to v3.3.3.
Update archives are verified using GPG signatures by default. If GPG is
disabled (not recommended), file integrity is checked with SHA512 or SHA256
checksums.
Note that C<sa-update> will not restart C<spamd> or otherwise cause
a scanner to reload the now-updated ruleset automatically. Instead,
C<sa-update> is typically used in something like the following manner:
sa-update && /etc/init.d/spamassassin reload
This works because C<sa-update> only returns an exit status of C<0> if
it has successfully downloaded and installed an updated ruleset.
The program sa-update uses the underlying operating system umask for the
updated rule files it installs. You may wish to run sa-update from a script
that sets the umask prior to calling sa-update. For example:
#!/bin/sh
umask 022
sa-update
=head1 OPTIONS
=over 4
=item B<--channel>
sa-update can update multiple channels at the same time. By default, it will
only access "updates.spamassassin.org", but more channels can be specified via
this option. If there are multiple additional channels, use the option
multiple times, once per channel. i.e.:
sa-update --channel foo.example.com --channel bar.example.com
=item B<--channelfile>
Similar to the B<--channel> option, except specify the additional channels in a
file instead of on the commandline. This is useful when there are a
lot of additional channels.
=item B<--checkonly>
Only check if an update is available, don't actually download and install it.
The exit code will be C<0> or C<1> as described below.
=item B<--install>
Install updates "offline", from the named tar.gz file, instead of performing
DNS lookups and HTTP invocations.
Files named B<file>.asc, B<file>.sha512, or B<file>.sha256 will be used for
GPG signature, and the SHA256 and SHA512 checksums, respectively. The
filename provided must contain a version number of at least 3 digits, which
will be used as the channel's update version number.
Multiple B<--channel> switches cannot be used with B<--install>. To install
multiple channels from tarballs, run C<sa-update> multiple times with different
B<--channel> and B<--install> switches, e.g.:
sa-update --channel foo.example.com --install foo-34958.tgz
sa-update --channel bar.example.com --install bar-938455.tgz
=item B<--allowplugins>
Allow downloaded updates to activate plugins. The default is not to
activate plugins; any C<loadplugin> or C<tryplugin> lines will be commented
in the downloaded update rules files.
You should never enable this for 3rd party update channels, since plugins
can execute unrestricted code on your system, even possibly as root! This
includes spamassassin official updates, which have no need to include
running code.
Use --reallyallowplugins option to bypass warnings and make it work.
=item B<--gpg>, B<--nogpg>
sa-update by default will verify update archives by use of GPG signature.
If you wish to skip GPG verification (very unsafe), you can use the
B<--nogpg> option to disable its use. Use of the following gpgkey-related
options will override B<--nogpg> and keep GPG verification enabled.
If GPG is disabled, only SHA512 or SHA256 checksums are used to verify
whether or not the downloaded archive has been corrupted, but it does not
offer any form of security regarding whether or not the downloaded archive
is legitimate (aka: non-modifed by evildoers).
Note: Only GnuPG is supported (ie: not any other PGP software).
=item B<--gpgkey>
sa-update has the concept of "release trusted" GPG keys. When an archive is
downloaded and the signature verified, sa-update requires that the signature
be from one of these "release trusted" keys or else verification fails. This
prevents third parties from manipulating the files on a mirror, for instance,
and signing with their own key.
By default, sa-update trusts key ids C<24F434CE> and C<5244EC45>, which are
the standard SpamAssassin release key and its sub-key. Use this option to
trust additional keys. See the B<--import> option for how to add keys to
sa-update's keyring. For sa-update to use a key it must be in sa-update's
keyring and trusted.
For multiple keys, use the option multiple times. i.e.:
sa-update --gpgkey E580B363 --gpgkey 298BC7D0
Note: use of this option automatically enables GPG verification.
=item B<--gpgkeyfile>
Similar to the B<--gpgkey> option, except specify the additional keys in a file
instead of on the commandline. This is extremely useful when there are a lot
of additional keys that you wish to trust.
=item B<--gpghomedir>
Specify a directory path to use as a storage area for the C<sa-update> GPG
keyring. By default, this is
@@LOCAL_RULES_DIR@@/sa-update-keys
=item B<--import>
Use to import GPG key(s) from a file into the sa-update keyring which is
located in the directory specified by B<--gpghomedir>. Before using channels
from third party sources, you should use this option to import the GPG key(s)
used by those channels. You must still use the B<--gpgkey> or B<--gpgkeyfile>
options above to get sa-update to trust imported keys.
To import multiple keys, use the option multiple times. i.e.:
sa-update --import channel1-GPG.KEY --import channel2-GPG.KEY
Note: use of this option automatically enables GPG verification.
=item B<--refreshmirrors>
Force the list of sa-update mirrors for each channel, stored in the MIRRORED.BY
file, to be updated. By default, the MIRRORED.BY file will be cached for up to
7 days after each time it is downloaded.
=item B<--forcemirror>
Force the download from a specific host instead of relying on mirrors listed
in MIRRORED.BY.
=item B<--updatedir>
By default, C<sa-update> will use the system-wide rules update directory:
@@LOCAL_STATE_DIR@@/@@VERSION@@
If the updates should be stored in another location, specify it here.
Note that use of this option is not recommended; if you're just using sa-update
to download updated rulesets for a scanner, and sa-update is placing updates in
the wrong directory, you probably need to rebuild SpamAssassin with different
C<Makefile.PL> arguments, instead of overriding sa-update's runtime behaviour.
=item B<-D> [I<area,...>], B<--debug> [I<area,...>]
Produce debugging output. If no areas are listed, all debugging information is
printed. Diagnostic output can also be enabled for each area individually;
I<area> is the area of the code to instrument. For example, to produce
diagnostic output on channel, gpg, and http, use:
sa-update -D channel,gpg,http
For more information about which areas (also known as channels) are
available, please see the documentation at
L<https://wiki.apache.org/spamassassin/DebugChannels>.
=item B<-h>, B<--help>
Print help message and exit.
=item B<-V>, B<--version>
Print sa-update version and exit.
=back
=head1 EXIT CODES
In absence of a --checkonly option, an exit code of C<0> means:
an update was available, and was downloaded and installed successfully.
If --checkonly was specified, an exit code of C<0> means: an update was
available.
An exit code of C<1> means no fresh updates were available.
An exit code of C<2> means that at least one update is available but that a
lint check of the site pre files failed. The site pre files must pass a lint
check before any updates are attempted.
An exit code of C<3> means that at least one update succeeded while
other channels failed. If using sa-compile, you should proceed with it.
An exit code of C<4> or higher, indicates that errors occurred while
attempting to download and extract updates, and no channels were updated.
=head1 SEE ALSO
Mail::SpamAssassin(3)
Mail::SpamAssassin::Conf(3)
spamassassin(1)
spamd(1)
E<lt>https://wiki.apache.org/spamassassin/RuleUpdatesE<gt>
=head1 PREREQUISITES
C<Mail::SpamAssassin>
=head1 BUGS
See E<lt>https://bz.apache.org/SpamAssassin/E<gt>
=head1 AUTHORS
The Apache SpamAssassin(tm) Project E<lt>https://spamassassin.apache.org/E<gt>
=head1 LICENSE AND COPYRIGHT
SpamAssassin is distributed under the Apache License, Version 2.0, as
described in the file C<LICENSE> included with the distribution.
Copyright (C) 2015 The Apache Software Foundation
( run in 0.778 second using v1.01-cache-2.11-cpan-df04353d9ac )