#!/usr/bin/perl -w
# ------------------------------------------------------------------------------
# $Id: update-nessusrc,v 1.5 2010/07/05 12:17:04 frank_breedijk Exp $
# ------------------------------------------------------------------------------
# update-nessusrc from http://www.tifaware.com/code/update-nessusrc 
# slightly modified to ignore SSL certificate mismatches and take settings for
# host, user, password, etc from the environment.
# Also the script can no longer run with taint checks as the command line comes
# from %ENV
# ------------------------------------------------------------------------------
#
# File modified by i.b. for use with Seccubus and Nessus 4.2
# Seccubus 1.4 ships with an older version of update-nessusrc
#
# Changes made to lines 205, 206, 207, 208, 418, 448, 439
#
#
#
#
# Start - original file
#
# ----------------------------------------------------------------------
# update-nessusrc
#
# Written by George A. Theall, theall@tifaware.com
#
# Copyright (c) 2003-2010, George A. Theall. All rights reserved.
#
# This module is free software; you can redistribute it and/or modify
# it under the same terms as Perl itself.
#
# $Id: update-nessusrc,v 1.5 2010/07/05 12:17:04 frank_breedijk Exp $
# ---------------------------------------------------------------------


=head1 NAME

update-nessusrc - Updates Nessus configuration file with new plugins.


=head1 SYNOPSIS

  # updates nessusrc using default settings (eg, non-dangerous plugins
  #   and ping / tcp_connect scanners in the script as distributed).
  update-nessusrc /home/seccubus/.nessusrc

  # same as above but also print a summary of the changes.
  update-nessusrc -s /home/seccubus/.nessusrc

  # produces an alternate nessusrc without replacing original and
  #   also prints lots of debugging info.
  update-nessusrc -d /home/seccubus/.nessusrc

  # updates a special nessusrc to use tcp_connect scanner (plugin #10335) 
  #   and test just for MS RPC interface buffer overruns (plugin #11835).
  update-nessusrc -c "" -f "" -r "" -i "10335,11835" .nessusrc-ms03-039

  # updates a special nessusrc w/ destructive plugins and tcp_connect
  #   scanner.
  update-nessusrc -c "denial,destructive_attack,flood,kill_host" -i 10335 /home/seccubus/.nessusrc-destructive

  # updates a special nessusrc w/ plugins associated with SMTP servers in
  #   all categories.
  update-nessusrc -c "_all_" -f "SMTP problems" /home/seccubus/.nessusrc-smtp

  # updates a special nessusrc w/ plugins associated with SMTP servers in
  #   all categories except destructive_attack.
  update-nessusrc -c "_all_" -c !destructive_attack -f "SMTP problems" /home/seccubus/.nessusrc-smtp

  # updates a special nessusrc w/ plugins that scan only for critical-
  #   and high-risk vulnerabilities.
  update-nessusrc -r "(Critical|High)" /home/seccubus/.nessusrc-risky

  # updates a special nessusrc to scan for SANS Top 20 Vulnerabilities.
  update-nessusrc -t /home/seccubus/.nessusrc-top20


=head1 DESCRIPTION

This script queries a Nessus server for its list of available plugins
and updates a Nessus client configuration file specified on the
commandline.  Specifically, it completely updates the sections
C<SCANNER_SET> and C<PLUGIN_SET> whenever it is run.  Use it
periodically (eg, via cron) to keep abreast of additions (and deletions)
in the set of plugins available through that server. 

Much of the script's behaviour is controlled by variables set either in
the script itself or in a separate script configuration file, specified
by C<$script_config>.  If it exists, the script configuration file is
treated as Perl code and evaluated in a I<sandbox>, which supports only
variable definitions.  Use of a separate script configuration file makes
it possible for several people to share B<update-nessusrc> on the same
system and promises to make upgrading the script much easier. 

The decision about which plugins to enable can be controlled either by
one or more configurable variables or by commandline arguments. 

    Variable            Commandline         Purpose
    @plugin_cats        -c|--categories     Enables plugin categories.
    @plugin_fams        -f|--families       Enables plugin families.
    @plugin_excludes    -x|--excludes       Excludes plugin ids explicitly.
    @plugin_includes    -i|--includes       Includes plugin ids explicitly.
    @plugin_risks       -r|--risks          Enables plugin based on risk factors.
    n/a                 -t|--top20          Enables plugins for SANS Top 20.

Plugins explicitly excluded will never be used regardless of the other
variables or commandline options.  Also, commandline arguments take
precedence over variables defined in the script or a separate
configuration file; thus, for example, you can disable all plugin
categories by using the commandline argument C<-c "">. 

Other settings include:

    Variable            Commandline         Purpose
    $DEBUG              -d|--debug          Turn on debugging.  NB: leaves
                                                rc file unchanged.
    $summary            -s|--summary        Print a summary report of 
                                                changes made in plugins.

B<update-nessusrc> is written in Perl and calls the Nessus client to
obtain a list of current plugins (using the option "-qp").  It should
work on any unix-like system with Perl 5.003 or later and Nessus 1.1.13
or later.  It also requires the following Perl modules:

    o Carp
    o Getopt::Long
    o IPC::Open2
    o LWP::UserAgent
    o LWP::Debug
    o Safe

If your system does not have these modules installed already, visit CPAN
(L<http://search.cpan.org/>).  Note that C<Safe> must be at least
version 2.0, which does not work with versions of Perl older than 5.003. 
Note also that C<LWP::Debug> and C<LWP::UserAgent> are not included with
the default Perl distribution so you may need to install them yourself;
they're included as part of the C<LWP library>
(L<http://search.cpan.org/dist/libwww-perl/>). 


=head1 KNOWN BUGS AND CAVEATS

Currently, I am not aware of any bugs in this script. 

As of August 2005, SANS appears to be adjusting their content based on
the I<browser's> user agent and, in the case of my script, it redirects
to a non-existent page.  A work-around is to change the user-agent
string, C<$useragent>, to something more common; eg,

  Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6

You can make the change either in the script itself or in the file
C</home/seccubus/.update-nessusrc>. 

This script is not a substitute for the Nessus client in terms of
managing a configuration file.  On one hand, it requires that a
configuration file already exists.  On the other, several plugins
require additional configuration - simply adding them to the list of
plugins used may not be optimal. 

There is a limit to the size of the arguments passed to
C<script_cve_id()>, which sets the CVE IDs of the flaws tested by each
plugin.  Additional CVE IDs, which by convention are listed in comments,
are not handled by this script since they can not be reliably
identified.  Thus, you would do well to review the report of Top 20
Vulnerabilities for which no plugins were found and update the
configuration file manually after examining plugins available on your
server.  Otherwise, you risk generating a configuration file that's not
quite comprehensive. 

To ensure an accurate scan for the SANS Top 20 Vulnerabilities, you must
make sure C<auto_enable_dependencies> is set to C<yes> in the
configuration file; B<update-nessusrc> will B<not> do this for you. 

Finally, realize that this script along with its script configuration
files may hold userids and passwords used to connect to a Nessus server;
protect them accordingly!


=head1 DIAGNOSTICS

Fatal errors will be reported using croak; these include the inability
to run the Nessus client and failures to read / write the configuration
files. 


=head1 SEE ALSO

L<nessus-update-plugins(5)>, L<http://www.nessus.org/plugins/>,
L<http://www.tifaware.com/perl/update-nessusrc/>. 

=cut


############################################################################
# Make sure we have access to the required modules.
use 5.003;
use strict;
use Carp;
use Getopt::Long;
use IPC::Open2;
use Safe 2.0;


############################################################################
# Initialize variables.
#
# nb: global variables (declared with "our") in this section may also be 
#     defined in a script configuration file.
$| = 1;
delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};   # Make %ENV safer
$ENV{PATH} = '/opt/nessus/bin:/usr/bin:/usr/local/bin'; # nb: should be where nessus is.
our $DEBUG = 0;
our $nessusd_host = $ENV{HOST};             # CALLS VARIBLE FROM seccubus CONGFIG FILE
our $nessusd_port = $ENV{PORT};             # CALLS VARIBLE FROM seccubus CONGFIG FILE
our $nessusd_user = $ENV{USER};             # CALLS VARIBLE FROM seccubus CONGFIG FILE
our $nessusd_user_pass = $ENV{PASS};        # CALLS VARIBLE FROM seccubus CONGFIG FILE
our @plugin_cats = (                        # categories of plugins to enable
    '_all_',                                # - all categories
    '!denial',                              # -   except DoS
    '!destructive_attack',                  # -   except kill services / software
    '!flood',                               # -   except flood target w/ packets.
    '!kill_host',                           # -   except kill the OS.
    '!scanner',                             # -   except port scanners (we'll include individually)
);
our @plugin_fams = (                        # families of plugins to enable
    '_all_',                                # - all families
);
our @plugin_excludes = (
    # empty
);
our @plugin_includes = (
    '10180',                                # Ping the remote host
    '10335',                                # tcp_connect scan
);
our @plugin_risks = (                       # risk factors for plugins to enable
                                            # nb: this should be a regex
    '.',                                    # - all risk factors
);
# nb: sample http proxy settings
#     - no proxy.
our $proxy = '';
#     - unauthenticated proxy via proxy1.domain.com.
# our $proxy = 'http://proxy1.domain.com';
#     - authenticated as user 'user' w/ password 'pass' via proxy2.domain.com.
# our $proxy = 'http://user:pass@proxy2.domain.com';
my $script_config =                         # config file for update-nessusrc itself.
    (exists $ENV{HOME} ? $ENV{HOME} : '') .
        '/.update-nessusrc';
our $summary = 0;                           # Print summary report?
our $timeout = 120;                         # timeout used w/ http GET
our $top20_url = 'http://www.sans.org/top20/';  # location of SANS Top20
our $useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6';


############################################################################
# Process script configuration file, if it exists.
#
# nb: untaint $script_config in case it contains $ENV{HOME} or 
#     something like that. Here, we require it consists of
#     alphanumerics, '-', '.', or '/' only.
if ($script_config =~ /^([\w\-\.\/]+)$/) {
    $script_config = $1;
}
else {
    croak "Can't untaint '$script_config'!\n";
}
# nb: processing is done in a sandbox with the Safe module that restricts
#     what code in the script config file can do to basically just
#     defining variables. Further, values are brought back into the
#     main namespace only for the configurable variables above.
if (-r $script_config) {
    warn "debug: processing '$script_config'.\n" if $DEBUG;
    my $sandbox = new Safe;
    $sandbox->permit_only(':base_core', ':base_mem');
    $sandbox->rdo($script_config);
    croak "Can't parse '$script_config' - $@!\n" if ($@);

    no strict 'vars', 'refs';
    # Bring back values for these scalars.
    foreach my $var (
        'DEBUG',
        'nessusd_host', 
        'nessusd_port',
        'nessusd_user',
        'nessusd_user_pass',
        'proxy',
        'summary',
        'timeout',
        'top20_url',
        'useragent',
    ) {
        local *symname = $sandbox->varglob($var);

        # Skip unless $var is defined in the script config.
        next unless (defined $symname);

        # Skip if values are the same in the script and the script config file.
        next if (defined ${$var} and ${$var} eq $symname);

        if ($DEBUG) {
            warn "debug:   updating '\$$var'.\n";
            warn "debug:     old value: '", ${$var} || '', "'\n";
        }
        ${$var} = $symname;
        if ($DEBUG) {
            warn "debug:     new value: '", ${$var} || '', "'\n";
        }
    }
    # Bring back values for these arrays.
    foreach my $var (
        'plugin_cats',
        'plugin_fams',
        'plugin_excludes',
        'plugin_includes',
        'plugin_risks',
    ) {
        local *symname = $sandbox->varglob($var);

        # Skip unless $var is an array in the script config.
        next unless (*symname{ARRAY});

        # Skip if arrays elements are the same in the script and 
        # the script config file.
        if (scalar(@symname) == scalar(@{$var})) {
            my %elements;
            grep($elements{$_}++, @{$var});
            next unless (grep(!$elements{$_}, @symname));
        }

        if ($DEBUG) {
            warn "debug:   updating '\@$var'.\n";
            warn "debug:     old values:\n";
            foreach (@{$var}) {
                warn "debug:       '$_'\n";
            }
        }
        @{$var} = ();
        grep(push(@{$var}, $_), @symname);
        if ($DEBUG) {
            warn "debug:     new values:\n";
            foreach (@{$var}) {
                warn "debug:       '$_'\n";
            }
        }
    }
    use strict 'refs', 'vars';
}
croak "*** You must set \$nessusd_host! ***\n" unless ($nessusd_host);
croak "*** You must set \$nessusd_port! ***\n" unless ($nessusd_port);
croak "*** You must set \$nessusd_user! ***\n" unless ($nessusd_user);
croak "*** You must set \$nessusd_user_pass! ***\n" unless ($nessusd_user_pass);


############################################################################
# Process commandline arguments.
my %options = (
    'debug'    => \$DEBUG,
    'summary'  => \$summary,
);
Getopt::Long::Configure('bundling');
GetOptions(
    \%options,
    "categories|c=s@",
    "families|f=s@",
    "debug|d!",
    "help|h|?!",
    "excludes|x=s@",
    "includes|i=s@",
    "risks|r=s@",
    "summary|s!",
    "top20|t!",
) or $options{help} = 1;
my $rcfile = shift || '';
$options{help} = 1 
    if (
        $options{top20} and ($options{categories} or $options{families}) or
        !$rcfile
    );
$0 =~ s/^.+\///;
if ($options{help}) {
    warn "\n",
        "Usage: $0 [options] rcfile\n",
        "\n",
        "Options:\n",
        "  -?, -h, --help             Display this help and exit.\n",
        "  -c, --categories <cats>    Enable plugins in the specified categories.\n",
        "  -d, --debug                Display copious debugging messages and create\n",
        "                               a scratch config file but don't actually\n",
        "                               replace the original.\n",
        "  -f, --families <fams>      Enable plugins in the specified families.\n",
        "  -i, --includes <ids>       Enable specified plugin ids.\n",
        "  -r, --risks <risks>        Enable plugins that scan for vulnerabilities\n",
        "                               with the specified risk factors, which\n",
        "                               should be regular expressions.\n",
        "  -s, --summary              Display summary of changes.\n",
        "  -t, --top20                Include plugins to scan for the SANS Top 20\n",
        "                               Vulnerabilities. Can not be combined with\n",
        "                               '--categories', '--families', or '-risks'.\n",
        "  -x, --excludes <ids>       Disable specified plugin ids.\n";
    exit(9);
}
unless (-s $rcfile) {
    croak "'$rcfile' does not exist or is empty!\n";
}
if ($rcfile =~ /^([\/\w\d\-\._]+)$/) {
    $rcfile = $1;
}
else {
    croak "Invalid characters in argument '$rcfile'!\n";
}
@plugin_cats = split(/,\s*/, join(',', @{$options{categories}})) 
    if ($options{categories});
@plugin_fams = split(/,\s*/, join(',', @{$options{families}})) 
    if ($options{families});
@plugin_excludes = split(/,\s*/, join(',', @{$options{excludes}}))
    if ($options{excludes});
@plugin_includes = split(/,\s*/, join(',', @{$options{includes}}))
    if ($options{includes});
@plugin_risks = split(/,\s*/, join(',', @{$options{risks}})) 
    if ($options{risks});


############################################################################
# Get list of plugins currently available.
warn "debug: determining nessus version.\n" if $DEBUG;
my $cmd = "$ENV{NESSUSBIN} -v";
warn "debug:   running '$cmd'\n" if $DEBUG;
my $nessus_version;
open(CMD, "$cmd 2>&1 |") or croak "Can't run '$cmd' - $!\n";
while (<CMD>) {
    chomp;
    warn "debug:   reading >>$_<<\n" if $DEBUG;

    $nessus_version = $1 if (/nessus .+ (\S+) (\[build|for) /);
}
close(CMD);
my $rc = $? >> 8;
croak "Can't run '$cmd' (rc=$rc)!\n" if ($rc);
croak "Can't determine nessus version!\n" unless ($nessus_version);
warn "debug:   nessus version is >>$nessus_version<<.\n" if $DEBUG;

# nb: there are 9 fields in Nessus v1.1.13 - 2.0.7; 
#     11 in versions 2.0.8 - 3.x;
#     8 in versions 4.x.
warn "debug: determining number of available fields in plugins list output.\n" if $DEBUG;
my $nfields = 11;
if ($nessus_version =~ /^(1\.|2\.0\.[0-7])/) {
    $nfields = 9;
}
elsif ($nessus_version =~ /^4\./) {
    $nfields = 8;
}
warn "debug:   $nfields available fields in plugins list output.\n" if $DEBUG;

warn "debug: getting list of available plugins.\n" if $DEBUG;
$cmd = "$ENV{NESSUSBIN}";
my $cmd_args = "-c $rcfile -x -qp $nessusd_host $nessusd_port $nessusd_user $nessusd_user_pass";
warn "debug:   running '$cmd $cmd_args'\n" if $DEBUG;
my(%categories, $CMD_READ, $CMD_WRITE, @errors, %families, %ids, %plugin);
my $got_cert = 0;
our(@plugins_new, @scanners_new);       # nb: must be valid globals!
my $pid = open2(
    \*CMD_READ, 
    \*CMD_WRITE, 
    $cmd, 
    split(/\s+/, $cmd_args)
) or croak "Can't run '$cmd $cmd_args' - $!\n";
binmode(CMD_READ);                      # avoid "Malformed UTF-8 character" warnings.
while (<CMD_READ>) {
    chomp;
    warn "debug:   reading >>$_<<\n" if $DEBUG;

    # If line doesn't start with id, check whether it's a cert and
    # save it for later.
    unless (/^\d+\|/) {
        # nb: to recognize that we've read the full cert, we check for
        #     three things. The first doesn't matter very much but
        #     must occur between the two instances of the second.
        $got_cert = 1 if ($got_cert == 0 && /^\s+Subject Public Key Info:/);
        $got_cert = 2 if ($got_cert == 1 && /^\s+Signature Algorithm:\s+/);
        if ($got_cert == 2 && /^$/) {
            # At this point, we've gotten the cert so display it and
            # ask whether to accept it.
            print STDERR join("\n", @errors), "\n",
                  "\n",
                  "Do you accept it ? (y/n) ";
            my $ans;
            chomp($ans = <STDIN>);
            $ans = 'n' unless ($ans eq 'y');
            # Send answer along to nessus.
            print CMD_WRITE "$ans\n";
            # If cert was not accepted, exit. NB: nessus itself will
            # display an informative error.
            exit if ($ans eq 'n');
            # Otherwise, reset some variables and iterate.
            $got_cert = 0;
            @errors = ();
            next;
        }
        push(@errors, $_);
        next;
    }

    # nb: field order is specified in _cli_dump_plugins() in 
    #     nessus-core/nessus/cli.c.
    my($id, @fields) = split(/\|/, $_, $nfields);
    croak "Can't parse plugins list ($_)!\n" unless (@fields == ($nfields-1));
    warn "debug:     id=>>$id<<\n" if $DEBUG;
    my @field_names = (
                'family', 
                'name', 
                'category', 
                'copyright', 
                'summary', 
                'version', 
    );
    push(@field_names, 'cve-id') if ($nfields == 9);
    push(@field_names, 'cve-id', 'bugtraq-id', 'xref') if ($nfields == 11);
    push(@field_names, 'description');
    foreach my $label (@field_names) {
        $_ = shift @fields;
        # nb: determine the risk factor of the vulnerability scanned 
        #     for by the plugin.
        if ($label eq 'description') {
            my $risk = 'n/a';
            if (/.+(Risk|Risk\s+factor)\s*:\s*(\\n)*(\S+\s+\/\s+CVSS .+?\\n\(.+\)|.+?)\s*(\\n|$)/is) {
                $risk = $3;
                $risk =~ s/\s*(;|\\n)\s*/ /g;
                $risk =~ s/^\s*(\S.*)\s*$/$1/g;
            }
            $plugin{$id}{risk} = $risk;
            warn "debug:     risk=>>$risk<<\n" if $DEBUG;
        }
        # nb: some fields we'll skip to save memory.
        next if (grep(/^$label$/, ('copyright', 'description')));
        # nb: create master lists of categories and families.
        $categories{$_}++ if ($label eq 'category');
        $families{$_}++ if ($label eq 'family');
        # nb: strip extraneous characters from version string.
        s/^\$Revision: 1.5 $$/$1/ if ($label eq 'version');
        # 
        $plugin{$id}{$label} = $_;
        warn "debug:     $label=>>$_<<\n" if $DEBUG;
    }
    # create master list of ids too!
    $ids{$id}++;
    if ($plugin{$id}{'category'} eq 'scanner') {
        push(@scanners_new, $id);
    }
    else {
        push(@plugins_new, $id);
    }
}
close(CMD_READ);
close(CMD_WRITE);
waitpid($pid, 0);
$rc = $? >> 8;
if ($rc) {
    my $errmsg = pop(@errors) || 'Unknown error running nessus';
    if (@errors) {
        $_ = pop(@errors);
        $errmsg .= " - $_" if (s/^\S+ : (.)(.*)$/\L$1\E$2/);
    }
    croak "$errmsg (rc=$rc)!\n";
}
@scanners_new = sort(@scanners_new);
@plugins_new = sort(@plugins_new);


############################################################################
# Adjust selected plugins as necessary.
my(@negates, @ranges);
# - categories.
@negates = grep(s/^!//, @plugin_cats);
@plugin_cats = split(/,/, join(',', keys %categories))
    if (grep($_ eq '_all_', @plugin_cats));
foreach my $negate (@negates) {
    @plugin_cats = grep($_ ne $negate, @plugin_cats);
}
@plugin_cats = sort(@plugin_cats);
if ($DEBUG) {
    warn "debug: plugin categories to enable:\n";
    foreach (@plugin_cats) {
        warn "debug:   $_\n";
    }
}
# - excludes.
@ranges = ();
@plugin_excludes = grep(
    (/^!?\d+\s*\-\s*\d+$/ && push(@ranges, $_), !/^!?\d+\s*\-\s*\d+$/), 
    @plugin_excludes
);
foreach (@ranges) {
    if (/^(!?)(\d+)\s*\-\s*(\d+)$/) {
        push(@plugin_excludes, "$1${_}") foreach ($2..$3);
    }
}
@negates = grep(s/^!//, @plugin_excludes);
@plugin_excludes = split(/,/, join(',', keys %ids))
    if (grep($_ eq '_all_', @plugin_excludes));
foreach my $negate (@negates) {
    @plugin_excludes = grep($_ ne $negate, @plugin_excludes);
}
@plugin_excludes = sort(@plugin_excludes);
if ($DEBUG) {
    warn "debug: plugin ids to explicitly exclude:\n";
    foreach (@plugin_excludes) {
        warn "debug:   $_\n";
    }
}
# - families.
@negates = grep(s/^!//, @plugin_fams);
@plugin_fams = split(/,/, join(',', keys %families))
    if (grep($_ eq '_all_', @plugin_fams));
foreach my $negate (@negates) {
    @plugin_fams = grep($_ ne $negate, @plugin_fams);
}
@plugin_fams = sort(@plugin_fams);
if ($DEBUG) {
    warn "debug: plugin families to enable:\n";
    foreach (@plugin_fams) {
        warn "debug:   $_\n";
    }
}
# - includes.
@ranges = ();
@plugin_includes = grep(
    (/^!?\d+\s*\-\s*\d+$/ && push(@ranges, $_), !/^!?\d+\s*\-\s*\d+$/), 
    @plugin_includes
);
foreach (@ranges) {
    if (/^(!?)(\d+)\s*\-\s*(\d+)$/) {
        push(@plugin_includes, "$1${_}") foreach ($2..$3);
    }
}
@negates = grep(s/^!//, @plugin_includes);
@plugin_includes = split(/,/, join(',', keys %ids))
    if (grep($_ eq '_all_', @plugin_includes));
foreach my $negate (@negates) {
    @plugin_includes = grep($_ ne $negate, @plugin_includes);
}
@plugin_includes = sort(@plugin_includes);
if ($DEBUG) {
    warn "debug: plugin ids to enable:\n";
    foreach (@plugin_includes) {
        warn "debug:   $_\n";
    }
}
# - risks.
#   nb: negation isn't allowed here; instead, we expect regular expressions.
@plugin_risks = sort(@plugin_risks);
if ($DEBUG) {
    warn "debug: plugin risks to enable:\n";
    foreach (@plugin_risks) {
        warn "debug:   $_\n";
    }
}


############################################################################
# Warn about selections not currently available.
foreach my $cat (@plugin_cats) {
    warn "warning: no plugins found matching category '$cat'.\n"
        unless (grep($cat eq $_, keys %categories));
}
foreach my $fam (@plugin_fams) {
    warn "warning: no plugins found matching family '$fam'.\n"
        unless (grep($fam eq $_, keys %families));
}
foreach my $id (@plugin_excludes, @plugin_includes) {
    warn "warning: no plugins found matching id '$id'.\n"
        unless (grep($id eq $_, keys %ids));
}
# nb: we can't warn about risks since we allow for regular expressions.


############################################################################
# Determine whether plugins should now be enabled.
#
# - if Top 20 option selected, generate list of plugins to use dynamically.
if ($options{top20}) {
    use LWP::UserAgent;

    # Retrieve Top 20 list.
    if ($DEBUG) {
        warn "debug: retrieving '$top20_url'.\n";
        require LWP::Debug; import LWP::Debug qw(+);
    }

    my $ua = LWP::UserAgent->new(
        agent => $useragent,
        timeout => $timeout,
    );
    if (defined($proxy)) {
        $ua->proxy('http', $proxy);
    }
    my $response = $ua->get(
        $top20_url,
    );
    unless ($response->is_success) {
        croak "*** can't retrieve '$top20_url' - ", $response->status_line, "! ***\n";
    }

    # Extract CVE / CAN numbers.
    #
    # nb: parsing the HTML would ensure accuracy, but errors in the
    #     HTML suggest a simpler approach.
    #
    # nb: keep in mind CVE / CAN numbers may be duplicated since the top 
    #     20 list is actually two top 10 lists (for Windows and Unix).
    my(%top20_cves, %unique);
    my @top20_cves = grep(
        !/(CVE|CAN)$/i && ($_ = uc($_)) && !$unique{$_}++,
        sort($response->content =~ /http:\/\/.+\b((cve|can)-\d{4}-\d{4})\b/ig)
    );

    # Update arrays to use plugins associated with Top 20 vulnerabilities.
    @plugin_cats = ('settings');
    @plugin_fams = ('Settings');
    @plugin_risks = ('.');
    foreach my $id (keys %plugin) {
        next unless (exists $plugin{$id}{'cve-id'});
        my $cve = $plugin{$id}{'cve-id'};
        foreach my $top20_cve (@top20_cves) {
            if ($cve =~ /\b$top20_cve\b/i) {
                $top20_cves{$top20_cve} .= "$id & ";
                push(@plugin_includes, $id);
            }
        }
    }
    if ($DEBUG) {
        warn "debug: Top 20 vulnerabilities matched with plugins:\n";
        foreach my $cve (sort keys %top20_cves) {
            my $id = $top20_cves{$cve};
            $id =~ s/ & $//;
            warn "debug:   $cve -> plugin(s) $id\n";
        }
    }

    if (grep(!exists $top20_cves{$_}, @top20_cves)) {
        print "Note: No Plugins are Available for the Following Top 20 Vulnerabilities:\n",
              "  ", join("\n  ", grep(!exists $top20_cves{$_}, @top20_cves)),
            "\n",
            "\n";
    }
}

# - determine whether to enable available plugins.
warn "debug: determining whether to enable plugins.\n" if $DEBUG;
foreach my $id (@scanners_new, @plugins_new) {
    my $category = $plugin{$id}{category};
    my $family = $plugin{$id}{family};
    my $risk = $plugin{$id}{risk};

    my $use = 'no';
    # nb: use plugin if...
    $use = 'yes' 
        if (
            # the plugin was not explicitly excluded and...
            !grep(/^$id$/, @plugin_excludes) and
            (
                # either the Id is explicitly included or...
                grep(/^$id$/, @plugin_includes) or 
                # the category, family, and risk match what was selected.
                (
                    grep(/^$category$/, @plugin_cats) and
                    grep(/^$family$/, @plugin_fams) and
                    grep($risk =~ /$_/i, @plugin_risks)
                )
            )
        );
    warn "debug:   id=>>$id<<; ",
                    "category=>>$category<<; ",
                    "family=>>$family<<; ",
                    "risk=>>$risk<<; ",
                    "use=>>$use<<\n" if $DEBUG;
    # nb: status is used to track both old and new status.
    $plugin{$id}{status} = ($use eq 'yes') * 10;
}


############################################################################
# Read old configuration file.
warn "debug: reading contents of existing config file '$rcfile'.\n" if $DEBUG;
open(RC, $rcfile) or croak "Can't read $rcfile - $!\n";
# nb: lines from the config file will be stored as:
#     @plugins_old - non-scanner plugin settings
#     @scanners_old - scanner plugin settings
#     @lines - everything else
my(@lines, $set, $skip);
our(@plugins_old, @scanners_old);       # nb: must be valid globals!
while (<RC>) {
    chomp;
    warn "debug:   reading >>$_<<\n" if $DEBUG;
    push(@lines, $_) unless ($skip);

    # If starting to process a plugin or scanner set, initialize some vars.
    if (/^\s*begin\((PLUGIN|SCANNER)_SET\)\s*$/i) {
        warn "debug:   found the start of $1 set\n" if $DEBUG;
        $set = lc($1) . 's';
        $skip = 1;
    }
    # If at end of set, reset some vars.
    elsif (/^\s*end\((PLUGIN|SCANNER)_SET\)\s*$/i) {
        warn "debug:   found the end of $1 set\n" if $DEBUG;
        $set = "";
        $skip = 0;
        push(@lines, $_);               # nb: we'd otherwise skip this!!!
    }
    # If in set, keep track of old plugins for later.
    elsif ($set and /^\s*(\d+)\s*=\s*(yes|no)\s*$/) {
        no strict 'refs';
        push(@{"${set}_old"}, $1);
        use strict 'refs';
        # nb: old is used to keep track of old plugins if summarizing.
        $plugin{$1}{old} = 1 if ($summary);
        # nb: status is used to track both old and new status.
        $plugin{$1}{status} += ($2 =~ /^yes$/i);
    }
}
close(RC);

# Add SCANNER_SET and/or PLUGIN_SET sections if missing.
unless (@scanners_old) {
    warn "warning: no scanner set found in '$rcfile'; adding an empty one.\n";
    push(@lines, 'begin(SCANNER_SET)', 'end(SCANNER_SET)');
}
unless (@plugins_old) {
    warn "warning: no plugin set found in '$rcfile'; adding an empty one.\n";
    push(@lines, 'begin(PLUGIN_SET)', 'end(PLUGIN_SET)');
}


############################################################################
# Summarize changes.
if ($summary) {
    print "Summary of Changes ", 
        ($DEBUG ? "to be " : ""), 
        "Made to '$rcfile':\n";
    foreach my $id (sort keys %plugin) {
        my $status;
        if (!exists $plugin{$id}{old}) {
            $status = 'added / ' .
                ($plugin{$id}{status} == 10 ? 'on' : 'off');
        }
        # nb: all new plugins have names.
        elsif (!exists $plugin{$id}{name}) {
            $status = 'removed';
        }
        elsif ($plugin{$id}{status} == 10) {
            $status = 'enabled';
        }
        elsif ($plugin{$id}{status} == 1) {
            $status = 'disabled';
        }
        else {
            next;
        }
        print "  Id:             ", $id, "\n",
              "  Name:           ", ($plugin{$id}{name}         || 'n/a'), "\n",
              "  Family:         ", ($plugin{$id}{family}       || 'n/a'), "\n",
              "  Risk:           ", ($plugin{$id}{risk}         || 'n/a'), "\n",
              "  Category:       ", ($plugin{$id}{category}     || 'n/a'), "\n",
              "  Summary:        ", ($plugin{$id}{summary}      || 'n/a'), "\n",
              "  Version:        ", ($plugin{$id}{version}      || 'n/a'), "\n",
              "  CVE-ID:         ", ($plugin{$id}{'cve-id'}     || 'n/a'), "\n",
         ($nfields == 9 ? 
              "" :
              (
              "  BugTraq ID(s):  ", ($plugin{$id}{'bugtraq-id'} || 'n/a'), "\n",
              "  X-Reference:    ", ($plugin{$id}{xref}         || 'n/a'), "\n",
              )
          ),
              "  Status:         ", $status, "\n",
              "\n";
    }
}


############################################################################
# Regenerate configuration file.
#
# nb: in debug mode, configuration file will not be replaced; instead,
#     a separate file will be created.
my($mode, $uid, $gid) = (stat($rcfile))[2, 4, 5];
$rcfile .= ".$$" if ($DEBUG);
open(RC, ">$rcfile") or croak "Can't write to $rcfile - $!\n";
if ($DEBUG) {
    chmod $mode, "$rcfile" or 
        croak "Can't change mode of $rcfile to $mode - $!\n";
    chown $uid, $gid, "$rcfile" or 
        croak "Can't change ownership of $rcfile to $uid:gid - $!\n";
}
foreach (@lines) {
    print RC "$_\n";
    if (/^begin\((PLUGIN|SCANNER)_SET\)/) {
        $set = lc($1) . 's';
        no strict 'refs';
        foreach my $id (@{"${set}_new"}) {
            print RC " $id = ",
                ($plugin{$id}{status} >= 10 ? 'yes' : 'no'),
                "\n";
        }
        use strict 'refs';
    }
}
close(RC);
if ($DEBUG) {
    warn "debug: updated configuration file available as '$rcfile'\n";
}
