#!/bin/perl
#
# mssql.saint
# Copyright (C) 2002  SAINT Corporation
# by Sam Kline, SAINT, 5/02
#
# Reference:
# mssql_brute_force.nasl by H D Moore

require 'perl/misc.pl';
require 'perllib/netbios.pl';

print "BEGIN\n";

$usage = "$0 [-v] <target>";
$verbose = 0;

die $usage if $#ARGV < 0;
if ($ARGV[0] eq "-v") {
    $verbose = 1;
    shift;
}
$target = $ARGV[0];

$service = "mssql";
$status = "a";

$login = "sa";
$password = "";
$maxlen = 30;

&open_socket($target, tcp, 1433);

$send = &list2str(2,0,2,0,0,0,2,(0)x32);
$send .= $login . &list2str((0)x($maxlen-length($login)));
$send .= chr(length($login));
$send .= $password . &list2str((0)x($maxlen-length($password)));
$send .= chr(length($password));
$send .= &list2str((48)x6,97,48,(0)x17,32,24,129,184,44,8,3);
$send .= &list2str(1,6,10,9,1,1,(0)x9);
$send .= "squelda 1.0";
$send .= &list2str((0)x19,11,(0)x32);
$send .= chr(length($password));
$send .= $password . &list2str((0)x($maxlen-length($password)));
$send .= &list2str((0)x224,4,2,0,0);
$send .= "MSDBLIB";
$send .= &list2str(0,0,0,7,6,0,0,0,0,13,17,(0)x24);
syswrite(SOCK, $send, length($send));

$send = &list2str(2,1,0,71,0,0,2,(0)x8,1);
$send .= &list2str((0)x45,48,48,48,0,0,0,3,0,0,0);
syswrite(SOCK, $send, length($send));

sysread(SOCK,$recv,4);
$recv_len = ord(substr($recv,3,1));
sysread(SOCK,$recv,$recv_len-4);

if ($verbose) {
  for ($i=0; $i<length($recv); $i+=8) {
    for ($j=0; $j<8 && $i+$j<length($recv); $j++) {
      $k = substr($recv,$i+$j,1);
      if (ord($k)<32 || ord($k)>126) {
	print ".";
      } else {
	print $k;
      }
    }
    print "  ";
    for ($j=0; $j<8 && $i+$j<length($recv); $j++) {
      $k = substr($recv,$i+$j,1);
      print ord($k) . "-";
    }
    print "\n";
  }
}

&close_socket;

if ($recv =~ /Microsoft SQL Server/) {
  $severity = "rs";
  $trusted = "ANY\@ANY";
  $trustee = "ANY\@ANY";
  $service_output = "MS SQL Server default password";
  $text = "SQL Server account $login has no password";
  &saint_print;
}

sub list2str {

my(@input) = @_;
my($str) = "";

foreach $byte (@input) {
    $str .= chr($byte);  
}

return($str);
}
