#!/usr/bin/env perl
# Copyright 2016-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 a testssl json file to the IVIL format
# ------------------------------------------------------------------------------

use strict;
use SeccubusV2;
use IVIL;
use XML::Simple;
use JSON;
use utf8;
use Data::Dumper;

use Getopt::Long;
use Carp;

my (
    $scanname,
    $scanner,
    $help,
    $verbose,
    $workspace,
    $timestamp,
    $infile,
    $outfile,
    @findings,
    $quiet,
    $onlybad,
   );

# Create default values
$help = 0;
$scanner = "testssl";

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

help() if $help;
$scanname = $workspace unless $scanname;
$verbose = undef if $quiet;

if ( ! $timestamp ) {
    print "You must specify a timestamp";
    help();
} elsif ( ! $infile ) {
    print "You must specify the infile parameter";
    help();
};

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,
                         });
}

# Scanner version
my $scanner_version = "1.0";
print "Creating sender block\n" if $verbose;
print $OUT ivil_sender($scanner, $scanner_version, $timestamp);

print "Opening file $infile for input\n" if $verbose;
open(my $FH, "<", $infile) or die "Unable to open '$infile'";
my $json = join "", <$FH>;
close $FH;

foreach my $element ( @{decode_json($json)} ) {
    my @hostname = split /\//, $element->{'ip'};
    my %finding = ();
    $finding{ip} = $element->{ip};
    $finding{hostname} = $hostname[0];
    $finding{port} = $element->{'port'} . "/tcp";
    if ( $element->{severity} eq "OK" | $element->{severity} eq "INFO" ) {
        $finding{severity} = 0; # Note
    } elsif ( $element->{severity} eq "LOW" ) {
        $finding{severity} = 3; # Note
    } elsif ( $element->{severity} eq "MEDIUM" ) {
        $finding{severity} = 2; # Low
    } elsif ( $element->{severity} eq "HIGH" || $element->{severity} eq "CRITICAL" ) {
        $finding{severity} = 1; # Note
    } else { # DEBUG and WARN
        $finding{severity} = 0; # Note
    }
    $finding{finding} = $element->{'finding'};
    $finding{id} = $element->{'id'};
    print "Done processing key $element->{'ip'}/$element->{id}\n" if $verbose;
    push @findings, \%finding;
}

print $OUT ivil_findings(\@findings) if (@findings);
print $OUT ivil_close();
close $OUT;

exit();

sub help() {
    print "

Usage: testssl2ivil [--scanner <scanner>] --timestamp <timestamp> \\
           [--workspace <workspace>] [--scan <scan>] \\
           --infile <.xml file> [--outfile <.ivil.xml file>] \\
           [--verbose] [--help]

Arguments:
--scanner (--sc)- Optional: The name of the scanner used to create the .xml file
          Default value: testssl
--timestamp - 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
--workspace (-w)- Optional: Which Seccubus workspace do you want to load this
          in, this informaiton is used to create the addressee block.
          If not value is given for workspace no addressee block is
          generated
--scan(-s)  - 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 .xml 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 .xml is removed (if it exists) and .ivil.xml is
          appended
--verbose (-v)  - Be verbose
--help (-h) - Print this message
";
    exit();
}

