#!/usr/bin/env perl
# Copyright 2015-2017 Glenn ten Cate, Frank Breedijk
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------------
# This program converts an zap.xml file to the IVIL format
# ------------------------------------------------------------------------------

use strict;
use SeccubusV2;
use IVIL;

use Getopt::Long;
use Carp;
use XML::Simple;
use Data::Dumper;

my (
	$scanname,
	$scanner,
	$scannerversion,
	$help,
	$verbose,
	$workspace,
	$timestamp,
	$infile,
	$outfile,
   );

$help = 0;

# Create default values
$scanner = "ZAP";
$timestamp = make_timestamp();

GetOptions(	'scan=s'		=> \$scanname,
		'scanner=s'		=> \$scanner,
		'scannerversion=s'	=> \$scannerversion,
		'help|h!'		=> \$help,
		'verbose|v!'		=> \$verbose,
		'workspace=s'		=> \$workspace,
		'timestamp=s'		=> \$timestamp,
		'infile=s'		=> \$infile,
		'outfile=s'		=> \$outfile,
	  );

help() if $help;
$scanname = $workspace unless $scanname;

if ( ! $infile || ! -e $infile ) {
	print "You must specify the infile parameter";
	help();
} elsif ( ( $workspace && ! $scanname ) || ( ! $workspace && $scanname ) ) {
	print "workspace and scan have to specified both or not at all";
	help();
};

print "Reading in ZAP xml report file\n" if $verbose;

my $zap = XMLin($infile,
		   forceArray	=> [ 'host', 'uri', 'sites', 'findings', 'alertitem','hostname' ],
		   KeyAttr	=> undef,
	          );

unless ( $outfile ) {
	$outfile = $infile;
	$outfile =~ s/\.xml$//;
	$outfile .= ".ivil.xml";
}
print "Opening file $outfile for output\n" if $verbose;
open(my $OUT, ">", "$outfile") or die "Unable to open output file $outfile";
print $OUT xml_header();
print $OUT ivil_open();

if ($workspace) {
	print "Creating addressee block\n" if $verbose;
	print $OUT ivil_addressee("Seccubus", {
						"workspace" => $workspace,
						"scan"		=> $scanname,
			 		     });
}

print "Creating findings\n" if $verbose;
print $OUT "<findings>\n";

print "Handling scaninfo\n" if $verbose;

my $finding = {};
$finding->{ip} = "scaninfo";
$finding->{port} = $zap->{site}->{port};
$finding->{id} = "scaninfo";
$finding->{finding} = "
SSL Enabled       : $zap->{site}->{ssl}
Website scanned   : $zap->{site}->{name}";
print $OUT ivil_finding($finding);

print "Iterating over findings\n" if $verbose;
my $j = 0;

foreach my $item ( @{$zap->{site}->{alerts}->{alertitem}} ) {

	$finding = {};
	$finding->{port} = $zap->{site}->{port};
	$finding->{hostname} = $zap->{site}->{name};
	$finding->{id} = $item->{pluginid};
        $finding->{ip} = $zap->{site}->{host};
        $finding->{finding} = "Vulnerability: \r\n".$item->{alert}."\r\n\r\n";
        my $uri = $item->{uri};
        foreach my $poc ($uri) {
            if(ref($poc->[0]) eq 'HASH'){
                $finding->{finding} .= "PoC/URL: \r\n".$poc->[0]->{content}->[0]."\r\n\r\n";
            }else{
                $finding->{finding} .= "PoC/URL: \r\n".$poc->[0]."\r\n\r\n";
            }
        }

        my $param = $item->{param};
        foreach my $par ($param) {
            if(ref($par) eq 'HASH'){
                $finding->{finding} .= "Vulnerable Parameter: \r\n".$par->{content}->[0]."\r\n\r\n";
            }else{
                $finding->{finding} .= "Vulnerable Parameter: \r\n".$par."\r\n\r\n";
            }
        }

        my $attackv = $item->{attack};
        foreach my $atk ($attackv) {
            if(ref($atk) eq 'HASH'){
                $finding->{finding} .= "Used attack vector: \r\n".$atk->{content}->[0].$atk->{content}->[1]."\r\n\r\n";
            }else{
                $finding->{finding} .= "Used attack vector: \r\n".$atk."\r\n\r\n";
            }
        }

	if($item->{riskcode} == 0){
	   $finding->{severity} = 2;
	}else{
	   $finding->{severity} = $item->{riskcode};
	}

	foreach my $obj ( $item->{desc}->{p} ) {
	      if(ref($obj) eq 'ARRAY'){
                      $finding->{finding} .= "Description Finding:\r\n";
	           foreach ($obj) {
		       $finding->{finding} .= $obj->[0]."\r\n";
                       $finding->{finding} .= $obj->[1]."\r\n";
		       $finding->{finding} .= $obj->[3]."\r\n";
		       $finding->{finding} .= $obj->[4]."\r\n";
		   }
   	       }else{
	           my $desc = $obj;
    		   $finding->{finding} .= "Description Finding:\r\n";
                   if(ref($desc) ne "HASH"){
                       $finding->{finding} .= $desc."\r\n";
                   }

	    }
	}

        foreach my $obj ( $item->{solution}->{p} ) {
              if(ref($obj) eq 'ARRAY'){
                      $finding->{finding} .= "Solution for Finding:\r\n";
                   foreach ($obj) {
                       $finding->{finding} .= $obj->[0]."\r\n";
                       $finding->{finding} .= $obj->[1]."\r\n";
                       $finding->{finding} .= $obj->[2]."\r\n";
                   }
               }else{
                   my $sol = $obj;
		   $finding->{finding} .= "Solution for Finding:\r\n";
		   if(ref($sol) ne "HASH"){
                     $finding->{finding} .= $sol."\r\n";
		   }
            }
        }

        foreach my $obj ( $item->{reference}->{p} ) {
              if(ref($obj) eq 'ARRAY'){
                      $finding->{finding} .= "Reference for Finding:\r\n";
                   foreach ($obj) {
                       $finding->{finding} .= $obj->[0]."\r\n";
                       $finding->{finding} .= $obj->[1]."\r\n";
                       $finding->{finding} .= $obj->[2]."\r\n";
                   }
               }else{
                   my $ref = $obj;
                   $finding->{finding} .= "Reference for Finding:\r\n";
		   if(ref($ref) ne "HASH"){
                       $finding->{finding} .= $ref."\r\n";
		   }
            }
        }

	$j++;
	print $OUT ivil_finding($finding);
}

print $OUT "</findings>\n";
print $OUT ivil_close();
close $OUT;
print "Total Ammount of issues found:\r\n".$j."\r\n";

exit();

sub help() {
	print "

Usage: zap2ivil --scanner <scanner> [--scannerversion <versionstring>] \\
                --timestamp <timestamp> [--workspace <workspacename>] \\
		[--scan <scanname>] --infile <filename input> \\
		[--outfile <filename output>] [--verbose] [--help]

Arguments:
--scanner	- Optional: The name of the scanner used to create the zap
		  .xml report file. Defaults to 'ZAP'
--scannerversion- Optional: the version of the scanner used to create the zap
		  .xml report file
--timestamp	- Optional: Timestamp of when the file was created in the
		  format YYYYMMDDhhmmss or YYYYMMDDhhmm so
		  11 december 2011 1:14:00 pm is 20111211131400 or 201112111314
		  Defaults to the current date and time
--workspace	- Optional: Which Seccubus workspace do you want to load this
		  in, this informaiton is used to create the addressee block.
		  If no value is given for workspace no addressee block is
		  generated
--scan		- Optional: Which Seccubus scan do you want to load this in,
		  this informaiton is used to create the addressee block. If
		  scan is not specified then the value for workspace is used.
--infile	- This defines the .nbe file that will be converted to IVIL
--outfile	- Optional: This defines the name of the file used to output
		  IVIL. If no filename is given, the infile value is used,
		  a trailing .nbe is removed (if it exists) and .ivil.xml is
		  appended
--verbose (-v)	- Be verbose
--help (-h)	- Print this message
";
	exit();
}

sub make_timestamp() {
        my ($second, $minute, $hour, $day, $month, $year) = localtime();
	$month++;
	$second = "0" . $second if $second < 10;
	$minute = "0" . $minute if $minute <10;
	$hour = "0". $hour if $hour < 10;
	$day = "0". $day if $day <10;
	$month = "0" . $month if $month <10;
	$year += 1900;

	"$year$month$day$hour$minute$second";
}
