#!/usr/bin/perl
###############################################################################
#			      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 DBI;

use vars qw/%CONFIG/;

&load_configs;

#Redirect output to the log file
my $updatepluginslog = "$CONFIG{'UPDATEPLUGINSLOG'}";
my $updateplugins="$CONFIG{'UPDATEPLUGINSTABLE'}";
open(LOG,">>$updatepluginslog") or die "Failed to create $updatepluginslog: $!\n";
#*STDERR=*LOG;
#*STDOUT=*LOG;

my($nessususer, $nessuspassw, $nessussvr, $nessusport, $nessusdb, $nessustable, $sid, $sautoenable, $status, $statusvalue, $serverid);

#Update these variables:
$serverid = "$CONFIG{'SERVERID'}";			#Nessus server id 
$nessustable = "nessus_preferences_defaults";		#Final table with Nessus plugins
$dbusername = "$CONFIG{'DATABASEUSER'}"; 		#Username to connect to database
$dbpass = "$CONFIG{'DATABASEPASSWORD'}";		#Password to connect to database
$dbdsn = "$CONFIG{'DATABASEDSN'}";			#Database DSN

my ($risk, $dbh, $sth_ins, $sth_upd, $sth_sel2, $sth_sel3, $sth_selc, $sth_self, $sth_insc, $sth_insf, $catid, $setid, $plugincount, $pid, $pname, $pfamily, $pcategory, $pcopyright, $psummary, $pdescription, $pversion, $pcve_id,$pluginversion, $pbugtraq_id);

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);

$year+=1900;
my $now;
$mon++;
if ($mon<10){ $mon="0".$mon;};
if ($mday<10) { $mday="0".$mday;};
if ($hour<10){ $hour="0".$hour;};
if ($min<10){ $min="0".$min;};
if ($sec<10){ $sec="0".$sec;}; $now=$year.$mon.$mday.$hour.$min.$sec;

main();
close LOG;
exit(0);

sub main {

	#Establish db connection
	$dbh=conn_db();

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

	# Create a table the first time we run this program if needed
	$sth = $dbh->prepare(qq{show tables like "nessus_preferences_defaults"});
	$sth->execute;

	$foo=$sth->fetchrow_array;
	if (!$foo) {
		$sql = "CREATE TABLE $nessustable (
		nessus_id varchar(255) NOT NULL,
		nessusgroup varchar(255) ,
		type varchar(255),
		field varchar(255),
		value varchar(255),
		category varchar(255),
		flag char(1),
		PRIMARY KEY  (nessus_id)
		)";
		$sth = $dbh->prepare(qq{$sql});
		
		$sth->execute;
	}

	$sth = $dbh->prepare(qq{
		update nessus_preferences_defaults set flag=null
		} );
	$sth->execute;

	my ($cmd);
	my ($f0, $f1, $f2, $f3, $f4, $rhs, $rhs2, $sql);
		
	$cmd = qq{$CONFIG{'NESSUSPATH'} -qxP $nessushost $nessusport $nessususer $nessuspassword};
	open(PROC, "$cmd |") or die "failed to fork :$!\n";
	while (<PROC>){
		if (/\]:/) {
			# PLUGINS_PREFS
			$f5 = "PLUGINS_PREFS";
			($f1,$rhs) = split(/\[/);
			($f2,$rhs2) = split(/\]:/,$rhs);
			($f3,$f4) = split(/=/, $rhs2);

			$f4 =~ s/^ //;	# Remove leading whitespace
			$f4 =~ s/\n$//;	# Remove trailing newline

			$f0 = $f1."[".$f2."]:".$f3;

			$f2 =~ s/entry/T/;	# Text box
			$f2 =~ s/radio/R/;	# Radio button
			$f2 =~ s/checkbox/C/;	# Checkbox
			$f2 =~ s/password/P/;	# Password
			$f2 =~ s/file/T/;	# File
		}
		else {
			# SERVER_PREFS
			$f5 = "SERVER_PREFS";
			
			$f1 = "ServerPrefs";
			($f3,$f4) = split(/=/);
			
			$f4 =~ s/\n$//;	# Remove trailing newline
			$f4 =~ s/^ //;  # Remove leading whitespace
			$f2 = "T";
			$f0 = $f3;
		}

		# Does the current record exist? If not
		$sql = "select count(*) from $nessustable where nessus_id = \"$f0\"";
		$sth = $dbh->prepare(qq{$sql} );
		$sth->execute;
		$foo=$sth->fetchrow_array;
		if ($foo == 0) {
			$sql = "insert into $nessustable (nessus_id, nessusgroup, type, field, value, category,flag)
			values (\"$f0\", \"$f1\", \"$f2\", \"$f3\", \"$f4\", \"$f5\",\"T\")";
		}
		else {
			$sql = "UPDATE $nessustable set nessusgroup=\"$f1\",
			type=\"$f2\",
			field=\"$f3\",
			value=\"$f4\",
			category=\"$f5\",
			flag=\"T\"
			where nessus_id = \"$f0\"
			";
		}
		
		$sth = $dbh->prepare(qq{$sql
			} );
		$sth->execute;
	}
	$sql = "UPDATE $nessustable set type = 'C' WHERE nessusgroup = 'ServerPrefs' and value in ('yes', 'no')";
	$sth = $dbh->prepare(qq{$sql} );
	$sth->execute;


	$sql = "DELETE FROM $nessustable where flag is null";
	$sth = $dbh->prepare(qq{$sql} );
	$sth->execute;

}

sub conn_db {
	my($dbh);
	$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");
	return $dbh;
}

sub disconn_db {
	my ($dbh) = @_;
	$dbh->disconnect or die "Failed to disconnect : $DBI::errstr\n";
}

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)." updateplugins: 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;
}
