#!/usr/bin/perl5.8.4

# bin/telnet.sara
#
# Check for vulnerabilities in the telnet daemon
# by Bob Todd, 3/2002
# Updated to handle false positives for JD printers
# Derived for SPtelnet.c from Secure Point

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

$usage="Usage: $0 [-v] [-x] port target";

&Getopts("vx") || die $usage;
die $usage if ($#ARGV < 1);
$target = $ARGV[1];
$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) {
     $firewall_flag=$ENV{SARA_FW};
     $level_flag=$ENV{SARA_LEVEL};
}
$opt_x = 1 if $level_flag == 3;
# Check for buffer overflow in telnet

# Send AYT (Are You There) command to be sure it is real telnetd
$args = "\\377\\366";
$AYT_OK = 0;

open(TCPSCAN, "$TCP_SCAN -bs \"$args\" $target $port |")
	|| die "$0: cannot run $TCP_SCAN";
while(<TCPSCAN>) {
    print if $opt_v;
    $AYT_OK = 1 if (/\[.*yes.*\]/i);
}
close TCPSCAN;
  
if ($AYT_OK == 1) {
    $service = $port;
    $trusted = "ANY\@ANY";
    $trustee = "ANY\@ANY";
    $status = "a";

    if ($opt_x) {
# Send buffer overflow 
	$args = "\\377\\366" x 512;
	$AYT_OK = 0;

	open(TCPSCAN, "$TCP_SCAN -bs \"$args\" $target $port|");
	while(<TCPSCAN>) {
	    print if $opt_v;
            ($dum,$dum,$dum,$banner) = split(/\:/);
	    $AYT_OK = 1 if ($banner =~ /[a-zA-Z0-9]/);
	}
	close TCPSCAN;

	# Lack of [yes] means that telnetd daemon probably died
        # Update for JD printers; any response is OK
	# overflow succeeded
	if (!$AYT_OK) {
            ($severity,$service_output,$text, $cve) = &get_sid($sid);
            $status  = "a";
            $sid = 'TEL-002';
            $text =~ s/\;/$port/;
	    &sara_print;
	}
    }
}
