#!/usr/bin/perl5.8.4
#
# 
# http.sara5: version 3.01 25 Dec 02, 21:00:00, last mod by todd
# http.sara5: version 3.02 06 Jun 03  21:00:00  last mod by todd
# http.sara:  version 4.01 30 May 06  21:00:00, last mod by todd
#
require 'config/programs';
require 'config/paths.pl';
require 'perllib/getopts.pl';
require 'perl/misc.pl';
require 'perl/hostname.pl';
require 'rules/http.rules';

$sid_file = "rules/sid.def";

Getopts("s:v");
$bogus  = "";
$bogus_string = "sara_probe_test";
$bogus_sid    = "HTTP-000";
$target = "$ARGV[1]";
if (!$target) {
  print "Usage bin/http.sara [-v] [-s <sid>] <port> <host>\n";
  exit;
}

$port ="$ARGV[0]";
if($ARGV[0] =~ /\:/) {
   $port =~ s/\:TCP//;
} else {
   open(SERVICES, $SERVICES) or die "$0: cannot open $SERVICES: $!\n";
   while(<SERVICES>) {
      $port_name{$1} = $2 if /(\S+)\s+([0-9]+)\/tcp/;
   }
   $port = $port_name{$ARGV[0]} if $port_name{$ARGV[0]};
}

if (!$port) {
   $port = getservbyname($ARGV[0], "tcp");
}
foreach (keys %ENV) {
  $level_flag=$ENV{SARA_LEVEL};
}
for (@rules_http) {
  ($sid,$input,$output,$attack,$support,$support_output) = split(/\|/);
   next if ($attack && $attack != $level_flag);
   next if ($opt_s && ($opt_s ne "$sid"));
  if ($input !~ /ditto/) {
    $input =~ s/\~/\|/g;
    $input =~ s/$/\\n\\n\\n/g;
    print "$input\n" if $opt_v;
    $string_output = "";
    $input =~ s/\\n/\n/g;
    $input =~ s/\\r/\r/g;
    if (($port == 443 || $port eq "https") && $OPENSSL) {
       $args = "\"$input\n\n\"";
       open(SCAN, "bin/https $target $args|");
    } else {
       $args = "-b -s \"$input\n\n\" $target $port";
       die "Can't open $TCP_SCAN: $!\n" unless open(SCAN, "$TCP_SCAN $args|");
    }
    while(<SCAN>) {
      chomp;
      $string_output .= "$_\\n";
    }
  }
  $_ = $string_output;
  print "$_\n\n" if ($opt_v && $input !~ /ditto/);
  if (eval($output) == 1) {
    if ($input =~ /$bogus_string/  && $output =~ / OK/) {
     $bogus = "TRUE";
    }
    if ($support) {
      $arg = "";
      if ($support =~ /\{/) {
        $support =~ s/\{//;
        $support =~ s/\}//g;
        $support_flag = 0;
        if ($support =~ /PORT/) {
          $arg = $port;
          $support =~ s/PORT//;
        } 
        open (SUPPORT, "$support $arg $target|");
        while (<SUPPORT>) {
          if (eval($support_output) == 1) {
            $support_flag = 1;
            sleep 10;
            last;
          }
        }
       }
      } else {
        $support_flag = 1;
    }
    if ($support_flag == 1) {
       if (!($bogus eq "TRUE" && $output =~ " OK" && $sid ne "$bogus_sid")) { 
         ($severity,$service_output,$text, $cve) = &get_sid($sid);
         $service = $ARGV[0];
         $status  = "a";
         $trustee = "ANY\@ANY";
         $trusted = "ANY\@ANY";
         $text   .= " ($service)";
         &sara_print;
      }
   }
  }
}  
