#!/usr/bin/perl
#
# $Id: nessus_run.pl,v 1.7 2004/11/19 04:40:29 greg_k Exp $
#

################################################################################
#			      Last update: 09.10.2004			      #
#-----------------------------------------------------------------------------#
#				     Inprotect				      #
#-----------------------------------------------------------------------------#
# Copyright (C) 2002 - 2004 Inprotect.com				      #
#									      #
# This program is free software; you can redistribute it and/or modify it     #
# under the terms of version 2 of the GNU General Public License as published #
# by the Free Software Foundation.					      #
#									      #
# This program is distributed in the hope that it will be useful, but WITHOUT #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       #
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    #
# more details.								      #
#									      #
# You should have received a copy of the GNU General Public License along     #
# with this program; if not, write to the Free Software Foundation, Inc.,     #
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA			      #
#									      #
# Contact Information:							      #
# Alex Zimin (alex@inprotect.com)					      #
# http://www.inprotect.com						      #
###############################################################################
# See the README.txt and/or help files for more information on how to use &   #
# configuration.							      #
# See the LICENSE.txt file for more information on the License this software  #
# is distributed under.							      #
#									      #
# This program is intended for use in an authorized manner only, and the      #
# author can not be held liable for anything done with this program, code, or #
# items discovered with this program's use.				      #
###############################################################################

use strict;
use warnings;

#Read settings from the inprotect.cfg file
use vars qw/%CONFIG/;
load_configs();

#Redirect output to the log file
my $nessuslog = "$CONFIG{'NESSUSLOG'}";
my $debug = 0;
my $serverid = "$CONFIG{'SERVERID'}";
open(LOG,">>$nessuslog") or die "Failed to create $nessuslog: $!\n";
*STDERR=*LOG;
*STDOUT=*LOG;

print localtime(time)." nessus_run: Start\n";

#Use Perl modules
use Parallel::ForkManager;
use DBI;

#Declare constants
use constant TRUE => 1;
use constant FALSE => 0;

#Declare variables to use
my $outfile = "";
my $outdir = "$CONFIG{'OUTDIR'}";
my $targetfile = "";
my $nessus_cfg = "";
my $failedfile = "";
my $servreg;
my($stopq, $stopid, $stopcmd, $schedid, $username, $email, $schedule_type, $day_of_week, $day_of_month, $time);
my ($stime, $scantime, $sid, $sth_sel, $scanq, $pm);
my ($infield1, $infield2, $infield3, $infield4, $infield5, $infield6, $infield7 );
my ($id, $host, $str, $dbh, $sth, $sth_ins, $sth_upd, $timeout, $catcount );

#Connecting to the database
$dbh = DBI->connect("$CONFIG{'DATABASEDSN'}:$CONFIG{'DATABASENAME'}:$CONFIG{'DATABASEHOST'}","$CONFIG{'DATABASEUSER'}","$CONFIG{'DATABASEPASSWORD'}", {
	PrintError => 0,
	RaiseError => 1,
	AutoCommit => 1 } ) or die("Failed to connect : $DBI::errstr\n");

$sth=$dbh->prepare(qq{
	UPDATE nessus_servers
	SET checkin_time=now()
	WHERE id=$serverid
});

$sth->execute;

#Select server attributes
$sth = $dbh->prepare(qq{
	SELECT hostname, port, user, password
	FROM nessus_servers
	WHERE id=$serverid
	} );
$sth->execute;

my($nessushost, $nessusport, $nessususer, $nessuspassword)=$sth->fetchrow_array;

#Check for scans to stop
$sth_sel = $dbh->prepare(qq{
	SELECT process_id
	FROM nessus_scan
	WHERE status = "P"
	AND server_id=$serverid
	});
$sth_sel->execute;
while(($stopid)=$sth_sel->fetchrow_array) {
	my $stopcmd = qq{$CONFIG{'NESSUSPATH'} -qx $nessushost $nessusport };
	for (my $i=0; $i<=length($nessususer)+length($nessuspassword); $i++) {
		$stopcmd=$stopcmd." ";
		}
	$stopcmd=$stopcmd." ${outdir}/target_s${stopid} ${outdir}/nessus_s${stopid}.out -V -T nbe -c ${outdir}/nessus_s${stopid}.cfg";
	`ps -auxwww \| grep \"$stopcmd\" \| perl -pe '(\$_)=/root {3,9}(\\d+)/;\`kill \$_\`'`;
	if ($debug) {print localtime(time)." nessus_run: kill: $stopcmd\n";}
} #end of loop
$sth_sel->finish;
$sth = $dbh->prepare(qq{
	SELECT count(*)
	FROM nessus_scan
	WHERE status = "S"
	AND server_id=$serverid
	} );
$sth->execute;
($scanq)=$sth->fetchrow_array;

# Open a ForkManager handle limiting the number of children
# to MAX_FORKS
$pm = new Parallel::ForkManager($scanq);

#Select scheduled scans to run.
$sth = $dbh->prepare(qq{
	SELECT scan.host, scan.sched_id, sched.sid, sched.timeout, sched.username, sched.next_scan
	FROM nessus_scan scan, nessus_schedule sched
	WHERE scan.status = "S"
	AND scan.server_id=$serverid
	AND scan.sched_id=sched.id
	} );
$sth->execute;

while(($host, $schedid, $sid, $timeout, $username, $scantime)=$sth->fetchrow_array){
	$pm->start and next; # Do the fork
	my $dbhf;

	$dbhf = DBI->connect("$CONFIG{'DATABASEDSN'}:$CONFIG{'DATABASENAME'}:$CONFIG{'DATABASEHOST'}","$CONFIG{'DATABASEUSER'}","$CONFIG{'DATABASEPASSWORD'}", {
		PrintError => 0,
		RaiseError => 1,
		AutoCommit => 1 } ) or die("Failed to connect : $DBI::errstr\n");

	$sth_upd = $dbhf->prepare(qq{
		UPDATE nessus_scan
		SET status="R", start_dttm=now(), process_id=$$
		WHERE server_id=$serverid
		AND sched_id=$schedid
		AND host="$host"
		} );
	$sth_upd->execute;

	$outfile="${outdir}/nessus_s$$.out";
	$targetfile="${outdir}/target_s$$";
	$nessus_cfg="${outdir}/nessus_s$$.cfg";

	unlink $targetfile if -e $targetfile;
	unlink $outfile if -e $outfile;
	unlink $nessus_cfg if -e $nessus_cfg;

	open(TARGET,">>$targetfile") or die "Failed to create $targetfile: $!\n";
	print TARGET "$host,";
	close TARGET;

	create_profile ($nessus_cfg, $sid, $dbhf, $schedid, $host, $username);
	if (!run_nessus($outfile, $targetfile, $timeout, $username, $dbhf, $schedid, $host)) {
		$sth_upd=$dbhf->prepare(qq{
			UPDATE nessus_scan
			SET status="F", end_dttm=now()
			WHERE sched_id=$schedid
			AND server_id=$serverid
			AND host="$host"
		});
		$sth_upd->execute;
	}
	else {
		#Mark scan completed
		$sth_upd = $dbhf->prepare(qq{
			UPDATE nessus_scan
			SET status="C", end_dttm=now()
			WHERE sched_id=$schedid
			AND server_id=$serverid
			AND host="$host"
			} );
		$sth_upd->execute;
	}

	$sth_upd=$dbhf->prepare(qq{
		DELETE from nessus_live_stats
		WHERE sid=$schedid
		AND host="$host"
		});
	$sth_upd->execute;

	$sth_upd=$dbhf->prepare(qq{
		UPDATE nessus_servers
		SET current_scans=current_scans-1
		WHERE id=$serverid
		});
	$sth_upd->execute;

	#Load Nessus results into the db

	load_nessus_results($outfile,$dbhf,$sth_ins,$username, $schedid, $sid, $scantime);

	unlink $targetfile if -e $targetfile;
	unlink $outfile if -e $outfile;
	unlink $nessus_cfg if -e $nessus_cfg;

	# Temporary update query to fix formatting error in results table
	$sth_upd=$dbhf->prepare(qq{
		UPDATE nessus_results SET service=LEFT(service, LENGTH(service)-1) WHERE RIGHT(service,1) = CHAR(10)
		});
	$sth_upd->execute;

	$sth_upd->finish;
	$sth_ins->finish;


	#Close DB Connection
	$dbhf->disconnect or die("Failed to disconnect : $DBI::errstr\n");
	$pm->finish;

};

$sth->finish;

$pm->wait_all_children;

#Close DB connection
$dbh->disconnect or die("Failed to disconnect : $DBI::errstr\n");


print localtime(time)." nessus_run: Finish\n";
close LOG;

exit 0;



sub run_nessus {
	my ( $outfile, $targetfile, $timeout, $username, $dbhf, $schedid, $host ) = @_;
	my ($cmd);
	my ($sth_ins);

	# Make sure we dont get dupes in live stats - delete for current schedid/hostid
	$sth_ins=$dbhf->prepare(qq{
		DELETE FROM nessus_live_stats
		WHERE sid=$schedid
		AND host = "$host"
		});
	$sth_ins->execute;

	$sth_ins=$dbhf->prepare(qq{
		INSERT INTO nessus_live_stats
		(sid, host, action, percent, username)
		VALUES ($schedid, "$host", "Starting", 0, "$username")
		});
	$sth_ins->execute;

	print localtime(time)." nessus_run: Scanning host - $host, User - $username\n";

	$cmd = qq{$CONFIG{'NESSUSPATH'} -qx $nessushost $nessusport $nessususer $nessuspassword $targetfile $outfile -V -T nbe -c $nessus_cfg};
	my $cmdkill = qq{$CONFIG{'NESSUSPATH'} -qx $nessushost $nessusport };

	for (my $i=0; $i<=length($nessususer)+length($nessuspassword); $i++) {
		$cmdkill=$cmdkill." ";
	}

	$cmdkill=$cmdkill." $targetfile $outfile -V -T nbe -c $nessus_cfg";

	eval {
		local $SIG{ALRM} = sub { die "NessusTimeout\n" };
		alarm $timeout;
		open(LOGFILE,">>$CONFIG{'NESSUSLOG'}");
		open(PROC,"$cmd |") or die "failed to fork :$!\n";
		my (@arr);
		while(<PROC>){
			@arr = split/\|/;
#			if ( $arr[2] == $pid ) {
#				$pid_kill = $arr[1];
#			}
			$sth_ins=$dbhf->prepare(qq{
				update nessus_live_stats
				SET action="$arr[0]", percent=$arr[2]/$arr[3]*100
				WHERE sid=$schedid
				AND host="$arr[1]"
				});
			$sth_ins->execute;
#			print LOGFILE "$arr[0], $arr[1], $arr[2], $arr[3]\n";
		}
		close PROC;
		close LOGFILE;
		print localtime(time)." nessus_run: Scan ended - $host, user - $username\n";
		alarm 0;
	};
	if ($@ && $@ eq "NessusTimeout\n" ) {
		warn "Nessus Scan timed out for $host\n";

		`ps -auxwww \| grep \"$cmdkill\" \| perl -pe '(\$_)=/root {3,9}(\\d+)/;\`kill \$_\`'`;
		return FALSE;
	}
	else {
		return TRUE;
	};
}

sub create_profile {

	my ($nessus_cfg, $sid, $dbh, $schedid, $host, $username) = @_;

	my ($sth_selp, $sth_selp1, $sth_selp2, $nessus_id, $nessus_value);


	#Find if the host was tested before
	$sth_selp=$dbh->prepare(qq{
		SELECT count(host)
		FROM nessus_results
		WHERE username="$username"
		AND host="$host"
		AND sched_id=$schedid
		AND sid=$sid
		});
	$sth_selp->execute;

	my($scancount)=$sth_selp->fetchrow_array;
	my($scantime)=0;

	if($scancount>0) {
		#Find when the host was last time tested
		$sth_selp=$dbh->prepare(qq{
			SELECT scantime
			FROM nessus_results
			WHERE username="$username"
			AND sched_id=$schedid
			AND sid=$sid
			AND host="$host"
			ORDER BY scantime DESC
			LIMIT 1
			});
		$sth_selp->execute;
		($scantime)=$sth_selp->fetchrow_array;
	} #end if

	open(PROFILE,">$nessus_cfg") or die "Failed to create $nessus_cfg: $!\n";

	$sth_selp=$dbh->prepare(qq{
		SELECT autoenable FROM nessus_settings
		WHERE id=$sid
		});
	$sth_selp->execute;

	my ($autoenable)=$sth_selp->fetchrow_array;

	$sth_selp=$dbh->prepare(qq{
		SELECT nessus_id, value FROM nessus_settings_preferences
		WHERE category IS NULL AND sid=$sid
		} );
	$sth_selp->execute;

	while (($nessus_id, $nessus_value)=$sth_selp->fetchrow_array ) {
		# Exclude null nessus_value records
		if ($nessus_value) {
			print PROFILE "$nessus_id = $nessus_value\n";
		}
		else {
			print PROFILE "$nessus_id\n";
		}
	}

	$sth_selp=$dbh->prepare(qq{
		SELECT t1.id, t1.enabled from nessus_settings_plugins as t1, plugins as t2
		where t1.id=t2.id and t2.category ='scanner' and t1.sid=$sid order by id
		} );
	$sth_selp->execute;

	print PROFILE "begin(SCANNER_SET)\n";

	while (($nessus_id, $nessus_value)=$sth_selp->fetchrow_array ) {
		if ($nessus_value eq "N") {
			$nessus_value="no";
		}
		else {
			$nessus_value="yes";
		}
		print PROFILE " $nessus_id = $nessus_value\n";
	}
	print PROFILE "end(SCANNER_SET)\n\n";

	$sth_selp=$dbh->prepare(qq{
		SELECT nessus_id, value FROM nessus_settings_preferences
		WHERE category='SERVER_PREFS' AND sid=$sid
		} );
	$sth_selp->execute;
	print PROFILE "begin(SERVER_PREFS)\n";

	while (($nessus_id, $nessus_value)=$sth_selp->fetchrow_array ) {
		print PROFILE " $nessus_id = $nessus_value\n";
	}

	print PROFILE "end(SERVER_PREFS)\n\n";

	$sth_selp=$dbh->prepare(qq{
		SELECT nessus_id, value FROM nessus_settings_preferences
		WHERE category='PLUGINS_PREFS' AND sid=$sid
		} );
	$sth_selp->execute;

	print PROFILE "begin(PLUGINS_PREFS)\n";

	while (($nessus_id, $nessus_value)=$sth_selp->fetchrow_array ) {
		print PROFILE " $nessus_id = $nessus_value\n";
	}

	print PROFILE "end(PLUGINS_PREFS)\n\n";

	print PROFILE "\n\nbegin(PLUGIN_SET)\n";

	if ($autoenable eq "C") {
		$sth_selp=$dbh->prepare(qq{
			SELECT t1.cid, t1.status from nessus_settings_category t1, nessus_category t2
			WHERE t2.name<>"scanner"
			AND t2.id=t1.cid
			AND t1.sid=$sid
			ORDER BY t2.id
			});
		$sth_selp->execute;
		while(my($catid, $catstatus)=$sth_selp->fetchrow_array) {
			if ($catstatus==5 and $scancount>0) {
				$sth_selp1=$dbh->prepare(qq{
					SELECT count( t2.scriptid )
					FROM nessus_plugins t1, nessus_results t2
					WHERE t2.username = "$username"
					AND t2.host = "$host"
					AND t1.id = t2.scriptid
					AND t1.category=$catid
					AND t2.sid=$sid
					AND t2.sched_id=$schedid
					});
				$sth_selp1->execute;

				($catcount)=$sth_selp1->fetchrow_array;

				if ($catcount>0) {
					#Scan for existing good plugins within this category
					$sth_selp2=$dbh->prepare(qq{
						SELECT distinct t1.scriptid from nessus_results t1, nessus_plugins t2
						WHERE t1.scriptid=t2.id
						AND t2.category=$catid
						AND t1.sid=$sid
						AND t1.sched_id=$schedid
						AND t1.host="$host"
						AND t2.created <=$scantime
						AND t2.deleted is NULL
						OR t1.scriptid=t2.id
						AND t2.category=$catid
						AND t1.sid=$sid
						AND t1.sched_id=$schedid
						AND t1.host="$host"
						AND t2.modified <=$scantime
						AND t2.deleted is NULL
						ORDER BY t1.scriptid
						});
					$sth_selp2->execute;
					while(($nessus_id)=$sth_selp2->fetchrow_array) {
						print PROFILE " $nessus_id = yes\n";
					}

					#Scan new/modified plugins
					$sth_selp2=$dbh->prepare(qq{
						SELECT id
						FROM nessus_plugins
						WHERE modified > $scantime
						AND category=$catid
						AND deleted is NULL
						OR created > $scantime
						AND category=$catid
						AND deleted is NULL
						ORDER by id
						});
					$sth_selp2->execute;
					while(($nessus_id)=$sth_selp2->fetchrow_array) {
						print PROFILE " $nessus_id = yes\n";
					}#end loop

					#Do not scan other plugins in this category
					$sth_selp2=$dbh->prepare(qq{
						SELECT DISTINCT nessus_plugins.id
						FROM nessus_plugins
						LEFT JOIN nessus_results on nessus_plugins.id = nessus_results.scriptid
						AND nessus_results.sched_id=$schedid
						AND nessus_results.sid=$sid
						AND nessus_results.host="$host"
						WHERE nessus_results.scriptid is null
						AND nessus_plugins.category=$catid
						AND nessus_plugins.deleted is NULL
						ORDER BY nessus_plugins.id
						});
					$sth_selp2->execute;
					while(($nessus_id)=$sth_selp2->fetchrow_array){
						print PROFILE " $nessus_id = no\n";
					}
				}
				else {
					$sth_selp2=$dbh->prepare(qq{
						SELECT id
						FROM nessus_plugins
						WHERE modified > $scantime
						AND category=$catid
						AND deleted is NULL
						OR created > $scantime
						AND category=$catid
						AND deleted is NULL
						ORDER by id
					});
					$sth_selp2->execute;
					while(my($diff_plugin)=$sth_selp2->fetchrow_array) {
						print PROFILE " $diff_plugin = yes\n";
					}#end loop
						$sth_selp2=$dbh->prepare(qq{
							SELECT id
							FROM nessus_plugins
							WHERE modified <= $scantime
							AND category=$catid
							AND deleted is NULL
							OR created <= $scantime
							AND category=$catid
							AND deleted is NULL
							ORDER by id
						});
						$sth_selp2->execute;
						while(my($disable_plugin)=$sth_selp2->fetchrow_array){
							print PROFILE " $disable_plugin = no\n";
						}
					}
				} #end if
				else {

				$sth_selp2=$dbh->prepare(qq{
					SELECT t1.id, t1.enabled from nessus_settings_plugins t1, nessus_plugins t2
					where t1.id=t2.id and t2.category =$catid and t1.sid=$sid order by id
					} );
				$sth_selp2->execute;

				while (($nessus_id, $nessus_value)=$sth_selp2->fetchrow_array ) {
					if ($nessus_value eq "N") {
						$nessus_value="no";
					}
					else {
						$nessus_value="yes";
					}
					print PROFILE " $nessus_id = $nessus_value\n";
				} #end loop
			} #end if
		} #end loop
	} #end if
	elsif ($autoenable eq "F") {
		$sth_selp=$dbh->prepare(qq{
			SELECT t1.fid, t1.status from nessus_settings_family t1, nessus_family t2
			WHERE t2.name<>"Port scanners"
			AND t2.id=t1.fid
			AND t1.sid=$sid
			ORDER BY t2.id
			});
		$sth_selp->execute;
		while(my($famid, $famstatus)=$sth_selp->fetchrow_array) {
			if ($famstatus==5 and $scancount>0) {
				$sth_selp1=$dbh->prepare(qq{
					SELECT count( t2.scriptid )
					FROM nessus_plugins t1, nessus_results t2
					WHERE t2.username = "$username"
					AND t2.host = "$host"
					AND t1.id = t2.scriptid
					AND t1.family=$famid
					AND t2.sid=$sid
					AND t2.sched_id=$schedid
					});
				$sth_selp1->execute;

				($catcount)=$sth_selp1->fetchrow_array;

				if ($catcount>0) {
					#Scan for existing good plugins within this category
					$sth_selp2=$dbh->prepare(qq{
						SELECT distinct t1.scriptid from nessus_results t1, nessus_plugins t2
						WHERE t1.scriptid=t2.id
						AND t2.family=$famid
						AND t1.sid=$sid
						AND t1.sched_id=$schedid
						AND t1.host="$host"
						AND t2.created <=$scantime
						AND t2.deleted is NULL
						OR t1.scriptid=t2.id
						AND t2.family=$famid
						AND t1.sid=$sid
						AND t1.sched_id=$schedid
						AND t1.host="$host"
						AND t2.modified <=$scantime
						AND t2.deleted is NULL
						ORDER BY t1.scriptid
						});
					$sth_selp2->execute;

					while(($nessus_id)=$sth_selp2->fetchrow_array) {
						print PROFILE " $nessus_id = yes\n";
					}

					#Scan new/modified plugins
					$sth_selp2=$dbh->prepare(qq{
						SELECT id
						FROM nessus_plugins
						WHERE modified > $scantime
						AND family=$famid
						AND deleted is NULL
						OR created > $scantime
						AND family=$famid
						AND deleted is NULL
						ORDER by id
						});
					$sth_selp2->execute;

					while(($nessus_id)=$sth_selp2->fetchrow_array) {
						print PROFILE " $nessus_id = yes\n";
					}#end loop

					#Do not scan other plugins in this category
					$sth_selp2=$dbh->prepare(qq{
						SELECT DISTINCT nessus_plugins.id
						FROM nessus_plugins
						LEFT JOIN nessus_results on nessus_plugins.id = nessus_results.scriptid
						AND nessus_results.sched_id=$schedid
						AND nessus_results.sid=$sid
						AND nessus_results.host="$host"
						WHERE nessus_results.scriptid is null
						AND nessus_plugins.family=$famid
						AND nessus_plugins.deleted is NULL
						ORDER BY nessus_plugins.id
						});
					$sth_selp2->execute;

					while(($nessus_id)=$sth_selp2->fetchrow_array){
						print PROFILE " $nessus_id = no\n";
					}
				}
				else {
					$sth_selp2=$dbh->prepare(qq{
						SELECT id
						FROM nessus_plugins
						WHERE modified > $scantime
						AND family=$famid
						AND deleted is NULL
						OR created > $scantime
						AND family=$famid
						AND deleted is NULL
						ORDER by id
					});
					$sth_selp2->execute;
					while(my($diff_plugin)=$sth_selp2->fetchrow_array) {
						print PROFILE " $diff_plugin = yes\n";
					}#end loop
					$sth_selp2=$dbh->prepare(qq{
						SELECT id
						FROM nessus_plugins
						WHERE modified <= $scantime
						AND family=$famid
						AND deleted is NULL
						OR created <= $scantime
						AND family=$famid
						AND deleted is NULL
						ORDER by id
					});
					$sth_selp2->execute;
					while(my($disable_plugin)=$sth_selp2->fetchrow_array){
						print PROFILE " $disable_plugin = no\n";
					}
				}
			} #end if
			else {

				$sth_selp2=$dbh->prepare(qq{
					SELECT t1.id, t1.enabled FROM nessus_settings_plugins t1, nessus_plugins t2
					WHERE t1.id=t2.id and t2.family =$famid AND t1.sid=$sid ORDER BY id
				} );
				$sth_selp2->execute;

				while (($nessus_id, $nessus_value)=$sth_selp2->fetchrow_array ) {
					if ($nessus_value eq "N") {
						$nessus_value="no";
					}
					else {
						$nessus_value="yes";
					}
					print PROFILE " $nessus_id = $nessus_value\n";
				} #end loop
			} #end if
		} #end loop
	}
	else {
		$sth_selp=$dbh->prepare(qq{
			SELECT t1.id, t1.enabled from nessus_settings_plugins as t1, plugins as t2
			WHERE t1.id=t2.id and t2.category <>'scanner' AND t1.sid=$sid ORDER BY id
			} );
		$sth_selp->execute;
		#print PROFILE "\n\nbegin(PLUGIN_SET)\n";

		while (($nessus_id, $nessus_value)=$sth_selp->fetchrow_array ) {
			if ($nessus_value eq "N") {
				$nessus_value="no";
			}
			else {
				$nessus_value="yes";
			}
			print PROFILE " $nessus_id = $nessus_value\n";
		} #end loop

	} #end if


	print PROFILE "end(PLUGIN_SET)\n\n";
	$sth_selp->finish;
#	$sth_selp1->finish;
#	$sth_selp2->finish;


}


sub load_configs
{
	my $configfile="/usr/local/etc/inprotect.cfg";
	my $noconfig=0;
	open(CONF,"<$configfile") || $noconfig++;
	my @CONFILE=<CONF>;
	close(CONF);

	if ($noconfig) { print localtime(time)." nessus_run: No inprotect.cfg file found.\n"; }
	foreach my $line (@CONFILE)
	{
		$line =~ s/\#.*$//;
		chomp($line);
		$line =~ s/\s+$//;
		$line =~ s/^\s+//;
		if ($line eq "") { next; }
		my @temp=split(/=/,$line,2);
		if ($temp[0] ne "") { $CONFIG{$temp[0]}=$temp[1]; }
	}
	return;
}


sub load_nessus_results {

	my ( $outfile, $dbhf, $sth_ins , $username, $schedid, $sid, $scantime) = @_;
	my ( $dupecheck, $sql);


	# Open file for input
	#
	if ($debug) {print localtime(time)." nessus_run: Importing results $outfile\n";}
	open(INPUT,"<$outfile")||die("Can't open report file");


	# loop through input file and insert into table
	#
	while (<INPUT>)
	{
		# Initialize field values each time to ensure the are clear
		#
		$infield1 = " ";
		$infield2 = " ";
		$infield3 = " ";
		$infield4 = " ";
		$infield5 = " ";
		$infield6 = " ";
		$infield7 = " ";


		# Break out fields from input file
		#
		($infield1,$infield2,$infield3,$infield4,$infield5,$infield6,$infield7)=split(/\|/,$_);

		# Some nessus results only have 4 fields - Fix null values here
		if (!$infield5) {
			$infield5 = " ";
		}
		if (!$infield6) {
			$infield6 = " ";
		}
		if (!$infield7) {
			$infield7 = " ";
		}
		
		# Translate ; to \n for newline
		#
		$infield7 =~ s/;/\n/g;

		# Translate " to \"
		#
		$infield7 =~ s/\"/'/gm;

		# Convert "infield6 factor" to infield6 value HIGH/MEDIUM/LOW
		#
		$infield6="7";
		$infield6='1' if ($infield7 =~ "Risk factor : Serious");
		$infield6='2' if ($infield7 =~ "Risk factor : High");
		$infield6='3' if ($infield7 =~ "Risk factor : Medium");
		$infield6='4' if ($infield7 =~ "Risk factor : Medium/Low");
		$infield6='5' if ($infield7 =~ "Risk factor : Low/Medium");
		$infield6='6' if ($infield7 =~ "Risk factor : Low");

		# Remove "infield6 factor" from $infield7 field
		# Using ` vs / due to existing / in field
		#
		$infield7=~ s/`Risk factor : High`//;
		$infield7=~ s/`Risk factor : Serious`//;
		$infield7=~ s/`Risk factor : Medium`//;
		$infield7=~ s/`Risk factor : Medium\/Low`//;
		$infield7=~ s/`Risk factor : Low\/Medium`//;
		$infield7=~ s/`Risk factor : Low`//;


		# Insert values into appropriate table
		#
		if ($infield1 eq "results") {
			# CHECK FOR DUPLICATE ENTRIES
			$sql = "select count(*) from nessus_results 
			where username = '$username' 
				and sched_id = '$schedid' 
				and sid = '$sid' 
				and scantime = '$scantime'
				and scantype = 'A'
				and domain = '$infield2'
				and host = '$infield3'
				and service = '$infield4'
				and scriptid = '$infield5'
				and risk = '$infield6'";

			$sth = $dbhf->prepare(qq{$sql} );
			$sth->execute;
			($dupecheck)= $sth->fetchrow_array;
		
			if ($dupecheck == 0) {
				$dbhf->do("insert into nessus_results
				(username, sched_id, sid, scantime, scantype, domain, host, service, scriptid, risk, msg)
				values ('$username', $schedid, $sid, '$scantime','A','$infield2','$infield3','$infield4'
				,'$infield5','$infield6',\"$infield7\")
				");
			}
			else {
				if ($debug) {print localtime(time)." nessus_run: Duplicate result $infield2|$infield3|$infield4|$infield5|$infield6|$infield7\n";}
			}	
		}
	}
	close INPUT;
}

