#!/usr/bin/perl5.8.4
#
# The script connects to MySQL and gets version number
# It also attempts to connect to server wuth mysql user connecting to mysql db
#
use IO::Socket;
require 'perl/misc.pl';
my $dum0  = 0;
my $ver   = 0;
my $sid   = 0;
my $cve   = 0;
my $debug = 0;
#$SIG{ALRM} = sub {$dum0 = $dum0};
usage() unless (@ARGV >= 0);

my $host = @ARGV[0];
if (!$host)
{
  usage();
}
alarm  5;
my $port = 3306;

# create the socket
my $socket = IO::Socket::INET->new(proto=>'tcp', PeerAddr=>$host, PeerPort=>$port);
$socket or die "Cannot build socket\n";
# receive greeting
my $reply;
recv($socket, $reply, 1024, 0);
if (length($reply) < 7 || $reply =~ /is not allowed to connect/)
{
 exit(1);
}
($ver, $dum0) = split(/-/, $reply);
($dum0, $ver) = split(/\n/, $ver);
print "VERSION $ver" if $debug;
print "Received greeting:\n" if $debug;
HexDump($reply) if $debug;
print "\n" if $debug;
if ($ver =~ /3.22.2[6-9]/) {
   $sid = "MYSQL-001";
} elsif ($ver =~ /3.23.[2-9]$/ || $ver =~ /3.23.10/ || $ver =~ /3.23.2[0-9]/ || $ver =~ /3.23.3[0-8]/) {
   $sid = "MYSQL-002";
} elsif ($ver =~ /3.23.39/ || $ver =~ /3.23.4[0-9]/ || $ver =~ /3.23.5[0-4]/) {
   $sid = "MYSQL-003";
}elsif ($ver =~ /4.1.[012]/ || $ver =~ /5.0.0/) {
   $sid = "MYSQL-004";
}
if ($sid) {
      ($severity,$service_output,$text,$cve) = &get_sid($sid);
       $target = $host;
       $service = "mysql";
       $status  = "a";
       $trustee = "ANY\@ANY";
       $trusted = "ANY\@ANY";
       &sara_print();
}
sub usage
{
    # print usage information
    print "\nUsage: mysql.sara <target>\n\n";
    exit(1);
}


###
# do a hexdump of a string (assuming it's binary)
###
sub HexDump
{
 my $buffer = $_[0];

 # unpack it into chars
 my @up = unpack("C*", $buffer);
 my $pos=0;

 # calculate matrix sizes
 my $rows = int(@up/16);
 my $leftover = int(@up%16);

 for( my $row=0; $row < $rows ; $row++, $pos+=16)
 {
  printf("%08X\t", $pos);
  my @values = @up[$pos .. $pos+15];
  my @line;
  foreach my $val (@values)
  {
   push(@line, sprintf("%02X", $val));
  }
  print join(' ', @line), "\n";
 }
 # print last line
 printf("%08X\t", $pos);
 my @values = @up[$pos .. $pos+$leftover-1];
 my @line;
 foreach my $val (@values)
 {
  push(@line, sprintf("%02X", $val));
 }
 print join(' ', @line), "\n";
}

#
#  Check for open mysql password

open(MYSQL,"perl/contrib/mysql.pl -h $host -u mysql -p '' -S mysql|");
while (<MYSQL>) {
  if (/Welcome/) {
    $sid = "MYSQL-005";
    ($severity,$service_output,$text,$cve) = &get_sid($sid);
    $target = $host;
    $service = "mysql";
    $status  = "a";
    $trustee = "ANY\@ANY";
    $trusted = "ANY\@ANY";
    &sara_print();
  }
}
close(MYSQL);

