#!/usr/bin/perl5.8.4

# bin/rdesktop.sara
#
# Last Mod 10 Nov 04, 12:00:00 by Bob Todd
#
require 'config/paths.pl';
require 'config/sara.cf';
require 'perl/misc.pl';
require 'perllib/getopts.pl';

$service  = "ms-wbt";
$port = "3389";
&Getopts("d:");

if (!$opt_d) {
   die "Usage: bin/rdesktop.sara -d <sara-data>\n";
}

$target = $ARGV[0];
#------------------------------------------------------------------------
@PWD      = "";
$CMD      = "";
$HOST_FILE = "results/$opt_d/all-hosts";
$FACT_FILE = "results/$opt_d/facts";
$FACT_TMP  = "results/$opt_d/facts.tmp";
$USR_FILE = "rules/auth-data/users";
$PWD_FILE = "rules/auth-data/smbpasswords";
if ((! -e $HOST_FILE) || (! -e $FACT_FILE)) {
  die "Database, $opt_d, does not exist or is corrupted\n";
}
#
# Need to check sara-data and get user records; else USR_FILE
# Need to check if X is available
# Need to provide message that this is post SARA
# arg = ./rdesktop -u rtodd -p 'Key_Larg1'  -g 640x480 -C -X 156.40.59.229
if (-e $RDESKTOP) {
  open (RDESKTOP, "$RDP -X localhost 2>&1|");
  while (<RDESKTOP>) {
    chomp;
     if (/open display/) {
       die "rdesktop cannot find an X server, aborting ...\n";
     }
  }
  close (RDESKTOP);    
  $cnt = 0;
  open(PWD, "$PWD_FILE");
  while(<PWD>) {
    chomp;
    next if /^#/;
    $pwd[$cnt++] = $_;
  }
  close(PWD);  
  $cnt = 0;
  open(TMP,">$FACT_TMP");
  open(FACTS, "$FACT_FILE");
  while (<FACTS>) {
    chomp;
    print TMP "$_\n" if (!/\|ms-wbt\|a\|uw/);
    ($target,$id, $dum, $dum, $dum, $dum, $output, $user) = split(/\|/);
    if ($id eq "users") {
      print "$target \> $output\n";
      open(WBT, "$FACT_FILE");
      while(<WBT>) {
        chomp;
        ($_target, $_id) = split(/\|/);
        if(($target eq $_target) && ($_id eq "ms-wbt")) {
          print "ms-wbt found for $target\n";
          (@users) = split(/\,/,$user);
          for (@users) {
            $_user = $_;
            @password = @pwd;
            for (@password) {
              $_pwd = $_;
              $_pwd =~ s/\%USER/$_user/;
              print "$target - $_user - $_pwd\n";
              $arg = " $_user \"$_pwd\" $target";
              open(RDP, "$RDP $arg $target|");
              while(<RDP>) {  
print;
                if(/Login successful/) {
                  $sid = "RDP-001";
                  ($severity,$service_output,$text,$cve) = &get_sid($sid);
                  $status  = "a";
                  $trustee="ANY\@ANY";
                  $trusted="ANY\@ANY";
                  $text = " $text $_user";
                  $fact_rec[$cnt++] = "$target|$service|a|$severity|$trustee|$trusted|$service_output|$text";
                }
              }
              close(RDP);
            }
          }
          last;
          close(WBT);
        } 
      }
    }
  }
} 
close(FACTS);
#
#  If more than one record of same value; trash them all
@_fact_rec = @fact_rec;
for (@fact_rec) {
   print TMP "$_\n";
}
close(TMP);
rename "$FACT_TMP","$FACT_FILE";

exit;
