#!/usr/bin/perl5.8.4
# 
# mssql.sara attempts authentication vi user sa eith blanm password.
#            It also tests for patch in reolution service of mssql
#
# usage: mssql.sara  [-v] host
# 
# Author:  Advanced Research Corporation  21 May 2004
# 
#

require 'config/paths.pl';
require 'config/sara.cf';
require 'perl/misc.pl';
require 'perl/get_host.pl';
require 'perllib/getopts.pl';
$sid_file = "rules/sid.def";
#
Getopts("v");
if (!$ARGV[0]) {
      die "Usage: mssql.sara  [-v] target";
}
#
#  Try blank sa password vulnerability
#
$sqlanlz = $SQLANLZ;
$target  = $ARGV[0];
$ip = &get_host_addr($target);
$host    = $ip;
#
if (-e $sqlanlz)
{
$printed=0;
$sid = "SQL-001";
  open (MSSQL,"$sqlanlz -i $ip 2>/dev/null|");
  while (<MSSQL>) {
    if (/SQLServer PenTest/) {
      ($severity,$service_output,$text,$cve) = &get_sid($sid);
      $status = "a";
      $service = "ms-sql-s";
      $trustee = "ANY\@ANY";
      $trusted = "ANY\@ANY";
      &sara_print();
    }
  }
  close (MSSQL);
}
#
#  Test for MSSQL 2000 patch
#
 use Socket;
 use Sys::Hostname;

 my ( $count, $hisiaddr, $hispaddr, $histime,
      $iaddr, $paddr, $port, $proto,
      $rin, $rout, $rtime, $sbuffer);
 $sid = "SQL-002";
 $sbuffer = ("\x02");
 $iaddr = gethostbyname(hostname());
 $proto = getprotobyname('udp');
 $port = 1434;
 $paddr = sockaddr_in(0, $iaddr); # 0 means let kernel pick

 socket(SOCKET, PF_INET, SOCK_DGRAM, $proto)   || die "socket: $!";
 bind(SOCKET, $paddr)			       || die "bind: $!";

 $| = 1;
 $hisiaddr = inet_aton($host)    || die "unknown host";
 $hispaddr = sockaddr_in($port, $hisiaddr);
 defined(send(SOCKET, $sbuffer, 0, $hispaddr))    || die "send $host: $!";
 $rin = '';
 vec($rin, fileno(SOCKET), 1) = 1;

 $packet_count = 0;
 while (select($rout = $rin, undef, undef, 3.0)) {
     $packet_count++;
     $rtime = '';
     ($hispaddr = recv(SOCKET, $rbuffer, 255, 0))	  || die "recv: $!";
     if ($packet_count == 1) {
      ($d1,$d2,$d3,$d4,$d5,$d6,$d7,$version) = split(/\;/,$rbuffer);
      print "ServerName: $d2\n$d3: $d4\n$d5: $d6\n$d7: $version\n" if $opt_v; 
      $version =~ s/\.//g;
        $sbuffer = "\x0A";
        defined(send(SOCKET, $sbuffer, 0, $hispaddr)) || die "send $host: $!";
        if ($version >= 800195) {
          $packet_count = 0;
          last;
        }
        next;
     }
     if ($packet_count >= 2) {
       ($severity,$service_output,$text,$cve) = &get_sid($sid);
#       $target	= "$host";
       $service = "ms-sql-m";
       $status	= "a";
       $trustee = "ANY\@ANY";
       $trusted = "ANY\@ANY";
       &sara_print;
     }
     last;
 }
 close (SOCKET);

