#!/usr/bin/perl

require 'config/paths.pl';
require 'perl/misc.pl';

print "BEGIN\n";
if ($#ARGV < 0) {
   die "Usage: $0 port target\n";
}

$target = "$ARGV[1]";
$port ="$ARGV[0]";
if($ARGV[0] =~ /\:/) {
   $port =~ s/\:TCP//;
} elsif ($ARGV[0] =~ /X-(\d+)/) {
   $port = 6000 + $1;
} 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");
}

$flag = "OK";

# check whether authentication is enabled
# (if not, not vulnerable)
$gopher_test = "halidate /\n";
$args = "-bs \"$gopher_test\" $target $port";
die "Can't open $TCP_SCAN: $!\n" unless open(SCAN, "$TCP_SCAN $args|");

while(<SCAN>) {
    if (/<FORM/) {
	$flag = "MAYBE";
    }
}
close(SCAN);

if ($flag eq "MAYBE") {

    # check version of HTTP server

    $gopher_test = "GET / HTTP/1.0\n\n";
    $args = "-bs \"$gopher_test\" $target $port";
    die "Can't open $TCP_SCAN: $!\n" unless open(SCAN, "$TCP_SCAN $args|");

    $flag = "OK";
    while(<SCAN>) {
	if (/Server: GopherWEB\/(\d+)\.(\d+)\.?(\d*)/) {
	    # assume it will be fixed in 2.1.5
	    if (($1 > 2) || ($1==2 && $2 > 1) || ($1==2 && $2==1 && $3 > 4)) {
		$flag = "OK";
	    } else {
		$flag = "BAD";
	    }
	}
    }
}

if ($flag eq "BAD") {
    $service = $ARGV[0];
    $status = "a";
    $trustee = "ANY\@ANY";
    $service_output = "gopher vulnerabilities";
    $trusted = "ANY\@ANY";
    $text = "Possible buffer overflow in gopher";
    $severity = "zcio";
    &saint_print();
}
