#!/usr/bin/perl
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#
#  ************************************************** !!! WARNING !!! ***********************************************************
#  *                                            FOR SECURITY TESTiNG ONLY!                                                      *
#  ******************************************************************************************************************************
#  * By using this code you agree that I makes no warranties or representations, express or implied, about the                  *
#  * accuracy, timeliness or completeness of this, including without limitations the implied warranties of                      *
#  * merchantability and fitness for a particular purpose.                                                                      *
#  * I makes NO Warranty of non-infringement. This code may contain technical inaccuracies or typographical errors.             *
#  * This code can never be copyrighted or owned by any commercial company, under no circumstances what so ever.                *
#  * but can be use for as long the developer, are giving explicit approval of the usage, and the user understand               *
#  * and approve of all the parts written in this notice.                                                                       *
#  * This program may NOT be used by any Danish company, unless explicit written permission from the developer .                *
#  * Neither myself nor any of my Affiliates shall be liable for any direct, incidental, consequential, indirect                *
#  * or punitive damages arising out of access to, inability to access, or any use of the content of this code,                 *
#  * including without limitation any PC, other equipment or other property, even if I am Expressly advised of                  *
#  * the possibility of such damages. I DO NOT encourage criminal activities. If you use this code or commit                    *
#  * criminal acts with it, then you are solely responsible for your own actions and by use, downloading,transferring,          *
#  * and/or reading anything from this code you are considered to have accepted the terms and conditions and have read          *
#  * this disclaimer. Once again this code is for penetration testing purposes only.                                            *
#  ******************************************************************************************************************************
#
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#
#  Author/Developer:  Dennis Rand - CIRT.DK
#  Website:           http://www.cirt.dk
#  Copyright:         (c)2007 by Dennis Rand
#  Remember:          This program may NOT be used by any Danish company, unless explicit written permission.
#                     This would be violation of the law on intellectual property rights
#  Special thanks to: Andrew Christensen.
#                     Gary C Morse - Razorpoint Security Technologies inc.
#
#
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#
#  Description:
#   This program is used to test SMTP servers for Relaying problems
#   that could lead to an spammer using your mailserver to send SPAM.
#   Try to bypass relay protection in as many ways as possible.
#   Remember that both the Customer Email and the Tester Email has to 
#   be valid due to the testcases, that try to get by the security on the server.
#   Current total testcases that are to be run: 608, where 19 of them are unique
#
#   Features / Bugs should be reported to Dennis Rand for fix or creation
#   All ideas are higly welcome to make this as complete as possible.
#   And remember this may never be used to earn money, so KEEP IT FREE.
#
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#
# Building plugins:
#   PLUGINNAME=Short description of the plugin, and what is does
#   DESCRIPTION= This is an description <CR><CN> that are put into <CR><CN> the email <CR><CN>
#   SUBJECT=Mostely the same as Plugin name
#   MAILFROM=insert either eg. <LOCALMAIL> this will be translated into eg. <der@somewhere.dk>
#   RCPTTO=<REMOTEMAIL> 
#
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#
# Commands to use in plugins:
#   LOCALMAIL    =  This will be translated into the Customers email address
#   REMOTEMAIL   =  This will be translated into the Testers email address
#   DOMAIN       =  This will be translated into the Domain name set in the configuration file
#   INITTESTER   =  This will be translated into "any" if testers email is any@cirt.dk
#   DOMAINTESTER =  This will be translated into "cirt.dk" if testers email is any@cirt.dk
#   INITCOMPANY  =  This will be translated into "qwerty" if customers email is qwerty@qwe.dk
#   <CR>         =  This will be translated into an Return
#   <CN>         =  This will be translated into an Newline
#
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#
#  Requirements:
#    perl 5.8.0 it will proberly work with others but are written and tested on this perl version
#    Getopt::Long
#    IO::Socket
#    Time::HiRes
#
#    Also tested on ActivePerl v5.8.6 built for MSWin32-x86
#
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#
#  TO-DO:
#   . Make more plugins
#   . Make support for testing AUTH 
#   . Make more features, ideas needed
#
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#
#  Version:
#   Version 1.0
#      This is the first functional version, that are currently in beta release, and are in need to be tested.
#
#   Version 1.1 - Still needs more test and plugins
#      Added more functions into the plugin language located in the sub -> Read_plugin_file.
#      Fixed an bug in the HTML report where < and > is now translated into &lt; and &gt; now RCPT TO and MAIL FROM are shown.
#      Added more information into the report so that it is possible to see what the message contains.
#      Added/Removed plugin name as being listed and put it as an link to the description.
#      Passed 20 plugins maybe some of them are the same, need cleanup and new plugin testcases.
#      Added date, and X-Mailer into the email proberly need more parameters.
#
#   Version 1.2
#      Added function to test for MAIL,SEND,SOML,SAML FROM
#      Added more information into html report and the mail send
#      Added possibility to delay between tests to ensure 
#      Added success and faliure attempts into the report
#      Made minor modifications to output on screen during the scan
#
#   Version 1.3
#      Made emails look like comming from Ximian Evolution 1.4.6 (1.4.6-2)
#      Made a progressbar that runs while the scan is in progress.
#      Fixed an error in the showing of scan time frame (When did it start and when did it end)
#
#   Version 1.4
#     Cleaned up some of the code.
#     Checks for updates at www.cirt.dk
#     The mails now appear to come from an Outlook client instead of the Ximian Evolution
#     Set Sensitivity to Private, to possible avoid it from being read by a mail sweeper, one could hope
#     Set Importance to High
#     Set a Read receipt for this message on to it.
#     Rewritten the main connection code.
#     Added catch of CTRL + C, so program terminates in a nice way.
#     Rewritten alot of the report stuff, so it is possible to see what was sent and recieved.
#
#   Version 1.5
#     Instead of only being able to delay for seconds, now possible to delay for microseconds
#        * 1 second =  1000000 microseconds (Time::HiRes)
#     Made the "GUI" a bit more nice :)
#     Made it possible to do no check for updates at CIRT.DK 
#     Added the possibility that the program will not terminate if SMTP server responds slow
#     Added some checks for service on host and port both connection and Service checks
#     Changed statusbar to watching sucessfully and faliured attempts, during runtime
#     Added a counter to show how many testcases to be run.
#     Added possibility to change the X-Mailer, and MIME Version.
#     Added the testcases to be run with different settings shown below.
#        * X-Priority, X-MSMail-Priority, Importance, Sensitivity
# 
#   Version 1.6
#     Made some minor changes to the report for supporting other then IE, also Firefox and possible more.
#     Made it possible to do only "-unique" scan or all.
#
#   Version 1.7
#     Updated RelayScanner and Plugins it has many spelling and grammatical mistakes(Gary C Morse - Razorpoint Security Technologies inc.)
# 
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
use IO::Socket;
use Getopt::Long;
use Time::HiRes qw(usleep);
 
$version           = "Version 1.7";                 # Version 
$copyright         = "(c)2007 by Dennis Rand";      # Copyright information
$iconbase          = "http://www.cirt.dk";
$plug              = "/tools/relayscanner/plugins/";
$plugindir         = "plugins/";                    # Plugin directory
$port              = "25";                          # Default SMTP server port
$timestamp         = localtime;
$count, $helo_ok   = 0;
@list              = ("MAIL","SEND","SOML","SAML"); # Commands to use in <LIST> FROM
@hlo               = ("HELO","EHLO");
@x_priority        = ("1 (Highest)", "3 (Normal)", "5 (Low)");
@x_msmail_pri      = ("High", "Normal", "Low");
@importance        = ("High", "Normal", "Low");
@sensitivity       = ("Private", "Personal", "Normal", "Confidential");
$xmailer           = "Microsoft Outlook, Build 10.0.6626";
$mime_ver          = "1.0";
$delay             = 2000000;                       # Default amount of seconds between each testcase
$wait              = 200000;                        # Default amount of time between HELO and rest (0.2 second)
$success           = 0;
$faliure           = 0;
$timeout           = 10;                            # Maximum timeout of the connection
$noresponse        = ": The server answers very slow or is dead ==> Retry number: ";
$tcnr              = 0;


GetOptions( 
   "load=s"    => \$load_file,
   "delay=i"   => \$delay,
   "timeout=i" => \$timeout,
   "nocheck"   => \$nocheck,
   "noupdate"  => \$noupdate,
   "xmailer=s" => \$xmailer,
   "mimever=s" => \$mime_ver,
   "unique"    => \$unique,
   "help|?"    => sub 
   { 
      print "\n\n\n\n\n";
      print "\t\t\t **************************************** \r\n";
      print "\t\t\t **************************************** \r\n";
      print "\t\t\t **   CIRT.DK SMTP Relay Scanner    ** \r\n";
      print "\t\t\t **            $version             ** \r\n";
      print "\t\t\t **************************************** \r\n";
      print "\t\t\t ********$copyright********** \r\n";
      print "\t\t\t **************************************** \r\n";
      print "\n\t     ooOOooOOooOOooOOooOOooOOooOOooOOOOooOOooOOooOOooOOooOOooOOooOOoo\n\n";
      print "\t\t Parameters\n";
      print "\t\t    -load    < Config filename > \n";
      print "\t\t    -delay   < Microseconds between testcases > Default:  $delay = ", ($delay / 1000000), " sec.\n";
      print "\t\t    -timeout < Timeout connection to SMTP > \tDefault: $timeout seconds\n";
      print "\r\n";
      print "\t\t Advanced properties\n";
      print "\t\t    -xmailer < Mail program sending from >\tDefault: $xmailer\r\n";
      print "\t\t    -mimever < MIME Version>\t\t\tDefault: $mime_ver\r\n";
      print "\t\t    -unique  (Only checks unique testcases)\r\n";
      print "\r\n";
      print "\t\t    -nocheck (Does not check for a 220, when connection are made)\n";
      print "\t\t    -noupdate\t (Donīt check for updates)\r\n";
      print "\n\t     ooOOooOOooOOooOOooOOooOOooOOooOOOOooOOooOOooOOooOOooOOooOOooOOoo\n";
      print "\t       Usage eg.: $0 -l <filename> -delay 2000000\n";
      print "\n\t     ooOOooOOooOOooOOooOOooOOooOOooOOOOooOOooOOooOOooOOooOOooOOooOOoo";
      print "\n\t     Configuration file eg.:\n";
      print "\n\t     CustomerEmailServer=mail.anyone.com";
      print "\n\t     CustomerEmail=admin\@anyone.com";
      print "\n\t     CustomerDomain=anyone.com";
      print "\n\t     TesterEmail=relayscanner\@cirt.dk";
      print "\n\t     Port=25";
      print "\n\t     ooOOooOOooOOooOOooOOooOOooOOooOOOOooOOooOOooOOooOOooOOooOOooOOoo\n\n";
      exit;
   }
);

#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
# Check for updates at www.cirt.dk
sub ChkUpdatesCon
{
   $| = 1;
   $updates = IO::Socket::INET->new(
   Proto    => "tcp",
   PeerAddr => "www.cirt.dk", 
   PeerPort => "80", 
   Reuse    => 1,
   Timeout  => 10,) || print "\t - NO ROUTE TO WWW.CIRT.DK\r\n";
}  

sub ChkUpdates
{
   print " [X] Checking for updates";
   if(!$noupdate)
   {
      ChkUpdatesCon();
      $response = undef;
      print $updates "GET /tools/relayscanner/rs_update.txt HTTP/1.0\r\nHost: www.cirt.dk\r\nUser-Agent: Mozilla/4.0 (RelayScanner Update Check)\r\n\r\n";
      while(<$updates>)
         {
            if(!defined($response)){$response = $_;}
            $result .= $_;
         }
      if ($result =~ m/200 OK/mgsi)
      {   
         if($result !~ m/$version/mgsi) 
         {
            ($result) = $result =~ m/Update_Info:\s+(.*)/;
            $result   =~ s/<CN>/\r\n\t/g;
            print "\t - FOUND\r\noo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00\r\nINFORMATION:\r\nCIRT.DK SMTP Relay scanner has been updated, get the latest version at www.cirt.dk\r\nUpdate includes following features: $result\r\nThe scan will continue in 5 seconds\r\noo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00\r\n"; 
            close(updates); 
            $rap_updates = 1;
            sleep(5);
         }
         else
         {
            print "\t - NO UPDATES\r\n";
         }
      } 
   }
   else 
   {
      print "\t - NO CHECK\r\n";
   }
} 
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
# Catch Interupt - CTRL + C

sub catchInterrupt {
  $SIG{INT} = sub {exit;};
  print "\r\n [X] CIRT.DK SMTP RelayScanner has been terminated by CTRL + C\n\n";
  exit;
};

$SIG{INT} = \&catchInterrupt;

# verify that interrupt handler was installed properly

unless(defined($SIG{INT})){print "Unable to install signal handler, contact $copyright";}
unless($SIG{INT} == \&catchInterrupt){print "There was an unexpected error installing the signal handler, contact $copyright";}
  
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
# Counts the number of Testcases to run
sub count_tc
{
 if($unique) 
 {
    @x_priority = ("1 (Highest)");
    @x_msmail_pri = ("High");
    @importance = ("High");
    @sensitivity = ("Personal");
 }
 foreach $list_count (@list) # Loop all the plugins through the commands MAIL, SEND, SOML and SAML FROM
   {
      foreach $hlo_count (@hlo)
      {
         foreach $x_priority_count (@x_priority)
         {
            foreach $x_msmail_pri_count (@x_msmail_pri)
            {
               foreach $importance_count (@importance)
               {
                  foreach $sensitivity_count (@sensitivity)
                  {
                     opendir(D, "$plugindir") || die "Cannot open Plugins Directory.\r\n";
                     @plnames = readdir(D);
                     foreach $plugin_fil (@plnames) 
                     {
                        if($plugin_fil eq '..' or $plugin_fil eq '.'){next;} 
                        $tcnr++;
                     }
                  }
               }
            }
         }
      }
   }
   print " [X] Total testcases to run\t - ", ($tcnr),"\r\n";
   print " [X] Delay between tests\t - ", ($delay / 1000000)," seconds\r\n";
   print " [X] Relay scan started\t\t - $timestamp\r\n\r\n";
}
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO

sub splash_screen 
{
   print "\n\n\n";
   print "\t **************************************** \r\n";
   print "\t **************************************** \r\n";
   print "\t ***   CIRT.DK SMTP Relay Scanner     *** \r\n";
   print "\t ***           $version            *** \r\n";
   print "\t **************************************** \r\n";
   print "\t ******* $copyright ********* \r\n";
   print "\t **************************************** \r\n";
   print "\t **************************************** \r\n\r\n\r\n";

}

#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
# Loads the scannings file with Customer data into program

sub Load_scanner 
{
   print " [X] Loading scanner";
   if (-f $load_file) 
   {
     open (FILE, $load_file);
     while (<FILE>) 
     {
        chomp; 
        $target         = $' if (/^CustomerEmailServer=/);
        $customer_email = $' if (/^CustomerEmail=/);
        $domain         = $' if (/^CustomerDomain=/);
        $tester_email   = $' if (/^TesterEmail=/);
        $port           = $' if (/^Port=/); 
     }
  } 
  else 
  {
     print "\t\t - FAILED\r\n";
     print "\tThe configuration file '$load_file' could not be found\n\tTry RelayScanner.pl -help or -? for more information.\n\n\n";
     exit;
  }
  close(FILE);
  print "\t\t - DONE\r\n";
  &slog;
}

#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
# Checks if connection to host and port possible
sub ChkServerCon
{
   $| = 1;
   $Chk     = IO::Socket::INET->new(
   Proto    => "tcp",
   PeerAddr => $target, 
   PeerPort => $port, 
   Reuse    => 1,
   Timeout  => 10,) || exit { print "\t - FAILED\r\n\tNo service on $target port $port scanning stopped\r\n\r\n"}
}  

sub ChkServerExist
{
   print " [X] Checking for service";
   ChkServerCon();
   print "\t - DONE\r\n";
   if(!$nocheck)
   {
      print " [X] Checking for SMTP service";
      unless (<$Chk> =~ "220") {print "\t - FAILED\r\n\tThe service behind port: $port does not seem to be an SMTP Server.\r\n\tUse -nocheck if this is an SMTP server\r\n\r\n"; exit }
      print "\t - DONE\r\n";
   }   
   close($Chk);
}

sub hexencode 
{
   $unencoded = $_[0];
   $encoded = "";
   foreach my $char (split(//,$unencoded))
   {
      $encoded .= sprintf("%02x",ord($char));
   }
   return $encoded;
}
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
# Read the plugin file

sub read_plugin_file
{
   unless ($copyright =~ "Dennis Rand") {print "\n Syntax error near \"\$copyright\" Execution aborted due to compilation errors.\n";exit;}
   open (PLUGIN, "$plugindir$plugin_file");
   while (<PLUGIN>) 
   {
      chomp; 
      $plugin_name = $' if (/^PLUGINNAME=/);  # Name of Plugin
      $subject     = $' if (/^SUBJECT=/);     # Description of the plugin
      $description = $' if (/^DESCRIPTION=/); # Message to be put in body of the email
      $mailfrom    = $' if (/^MAILFROM=/);    # The mail from
      $rcptto      = $' if (/^RCPTTO=/);      # Description of the plugin
      $helo        = $' if (/^HELO=/);        # HELO mostely used RelayChecker@DOMAINTESTER
   }

   # Translate the plugin files using self made plugin language
   ($front_company,$back_company)   = split(/\@/,$customer_email);# Split up Customer email
   ($front_tester,$back_tester)     = split(/\@/,$tester_email);  # Split up Tester email

   $mailfrom     =~ s/LOCALMAIL/$customer_email/g;   # Replaces LOCALMAIL with Customers email in MAIL FROM
   $rcptto       =~ s/LOCALMAIL/$customer_email/g;   # Replaces LOCALMAIL with Customers email in RCPT TO
   $description  =~ s/LOCALMAIL/$customer_email/g;   # Replaces LOCALMAIL with Customers email in BODY
   $helo         =~ s/LOCALMAIL/$customer_email/g;   # Replaces LOCALMAIL with Customers email in HELO
 
   $mailfrom     =~ s/REMOTEMAIL/$tester_email/g;    # Replaces REMOTEMAIL with Testers email in MAIL FROM
   $rcptto       =~ s/REMOTEMAIL/$tester_email/g;    # Replaces REMOTEMAIL with Testers email in RCPT TO
   $description  =~ s/REMOTEMAIL/$tester_email/g;    # Replaces REMOTEMAIL with Testers email in BODY
   $helo         =~ s/REMOTEMAIL/$tester_email/g;    # Replaces REMOTEMAIL with Testers email in HELO 

   $mailfrom     =~ s/INITTESTER/$front_tester/g;    # Replaces INITTESTER with the testers email address before the @ in MAIL FROM
   $rcptto       =~ s/INITTESTER/$front_tester/g;    # Replaces INITTESTER with the testers email address before the @ in RCPT TO
   $description  =~ s/INITTESTER/$front_tester/g;    # Replaces INITTESTER with the testers email address before the @ in BODY 
   $helo         =~ s/INITTESTER/$front_tester/g;    # Replaces INITTESTER with the testers email address before the @ in HELO  

   $mailfrom     =~ s/INITCOMPANY/$front_company/g;  # Replaces INITCOMPANY with the companys email address before the @ in MAIL FROM
   $rcptto       =~ s/INITCOMPANY/$front_company/g;  # Replaces INITCOMPANY with the companys email address before the @ in RCPT TO
   $description  =~ s/INITCOMPANY/$front_company/g;  # Replaces INITCOMPANY with the companys email address before the @ in BODY
   $helo         =~ s/INITCOMPANY/$front_company/g;  # Replaces INITCOMPANY with the companys email address before the @ in HELO

   $mailfrom     =~ s/DOMAINTESTER/$back_tester/g;   # Replaces TESTERDOMAIN with the testers email domain in MAIL FROM
   $rcptto       =~ s/DOMAINTESTER/$back_tester/g;   # Replaces TESTERDOMAIN with the testers email domain in RCPT TO
   $helo         =~ s/DOMAINTESTER/$back_tester/g;   # Replaces TESTERDOMAIN with the testers email domain in HELO
   $description  =~ s/DOMAINTESTER/$back_tester/g;   # Replaces TESTERDOMAIN with the testers email domain in BODY
 
   $mailfrom     =~ s/DOMAIN/$domain/g;              # Replaces DOMAIN with the companys Mail domain name in MAIL FROM
   $rcptto       =~ s/DOMAIN/$domain/g;              # Replaces DOMAIN with the companys Mail domain name in RCPT TO
   $helo         =~ s/DOMAIN/$domain/g;              # Replaces DOMAIN with the companys Mail domain name in HELO
   $description  =~ s/DOMAIN/$domain/g;              # Replaces DOMAIN with the companys Mail domain name in BODY

   $description  =~ s/<CR>/\r/g;                     # Replaces <CR> with Character Return
   $description  =~ s/<CN>/\n/g;                     # Replaces <CN> with Character Newline

   close(PLUGIN);
   &Relay_engine; # Now lets send the plugin through the engine 

   #Progressbar
   print "\r [X] Relay Checking in progress: => ",$success,"/",$faliure;
}

#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
# Connection Strings

sub Con 
{ 
   $| = 1;
   $remote = IO::Socket::INET->new(
   Proto => "tcp",
   PeerAddr => $target, 
   PeerPort => $port, 
   Reuse => 1,
   Timeout => $timeout,)
} 

#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
# Relay Mailing Engine

sub Relay_engine 
{
   $set = 1;
   usleep($delay); # Set 5 seconds delay between tests
   $count++;
   $result = "";
   Con();
   while(!defined $remote)
   {
      Con();
      if(!defined $remote)
      {
         $whattime = localtime;
         print STDERR "\r [X] $whattime$noresponse" . $failed++ ;
         sleep 5;
         $firsttimeout = 1;
      }
   }
   
   if($firsttimeout)
   {
      print "\r\n";
      $failed = 1;
   }
   $firsttimeout = 0;
   print $remote "";
   usleep($wait); 
   print $remote "$hlo [$helo]\r\n";
   print $remote "$list FROM: $mailfrom\r\n";
   print $remote "RCPT TO: $rcptto\r\n";
   print $remote "DATA\r\n";

   $mailfrom =~ s/<//g;  
   $rcptto   =~ s/<//g;  
   $mailfrom =~ s/>//g;  
   $rcptto   =~ s/>//g;  

   print $remote "From: \"CIRT.DK SMTP Relay Scanner\" <$mailfrom>\r\n";
   print $remote "To: $rcptto\r\n";
   print $remote "Subject: $subject (Test Case: $count)\r\n";
   print $remote "Date: $timestamp\r\n";
   print $remote "Message-ID: <000501c5314325d6ef600901a8c0$count\@$domain>\r\n";
   print $remote "MIME-Version: $mime_ver\r\n";
   print $remote "Content-Type: text/plain\r\n";
   print $remote "Content-Transfer-Encoding: 7bit\r\n";
   print $remote "X-Priority: $x_priority\r\n";
   print $remote "x-MSMail-Priority: $x_msmail_pri\r\n";
   print $remote "X-Mailer: $xmailer\r\n";
   print $remote "Importance: $importance\r\n";
   print $remote "X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2180\r\n";
   print $remote "Sensitivity: $sensitivity\r\n";
   print $remote "Disposition-Notification-To: \"CIRT.DK Relay Scanner\" <$tester_email>\r\n";
   print $remote "\r\nTestcase: $count\r\n$description\r\n\r\n";
   print $remote "Mail creation:\r\n";
   print $remote "$list FROM: $mailfrom\r\n";
   print $remote "RCPT TO: $rcptto\r\n\r\n";
   print $remote "-----------------------------------\r\n";
   print $remote "CIRT.DK Relay Scanner $version\r\n";
   print $remote "$copyright - CIRT.DK\r\n";
   print $remote "http://www.cirt.dk\r\n";
   print $remote "-----------------------------------\r\n";
   print $remote "\r\n.\r\n";
   print $remote "QUIT\r\n";
   print $remote "EXIT\r\n";
   while(<$remote>)
   {
      $result .= $_;
      if ( $result =~ m/(250.*Message accepted)/mgsi || m/(250.*queued)/mgsi)
      {
         $set = 0;
      }
      elsif ( $result =~ m/(501.*connection rejected from box remote address)/mgsi)
      {
         $set = 1;
  close($remote);
      }
      else
      {
      }
   }
   if($set){$faliure++;} else {$success++;}
   &wlog;
   close($remote);
}

#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
# Read all plugins in the plugins libary, and put it through all the combinations of testcases

sub run_plugins 
{
   if($unique) 
   {
      @x_priority = ("1 (Highest)");
      @x_msmail_pri = ("High");
      @importance = ("High");
      @sensitivity = ("Personal");
   }
   
   foreach $list (@list) # Loop all the plugins through the commands MAIL, SEND, SOML and SAML FROM
   {
      foreach $hlo (@hlo) # Loop all the plugins through the commands HELO and EHLO
      {
        foreach $x_priority (@x_priority)
        {
           foreach $x_msmail_pri (@x_msmail_pri)
           {
              foreach $importance (@importance)
              {
                 foreach $sensitivity (@sensitivity)
                 {      
                     opendir(D, "$plugindir") || die "Cannot open Plugins Directory.\r\n";
                     @names = readdir(D);
                     foreach $plugin_file (@names) 
                     {
                        if($plugin_file eq '..' or $plugin_file eq '.'){next;} 
                        &read_plugin_file;
                     }
                 } 
              } 
           } 
        }
     }
  }
}

#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
# Writes the beginning of the log

sub slog
{
   $log = "SMTP_Relay_Scanner_".$domain.".html";
   open(FH, ">", $log);
   print FH "<HTML>\n<HEAD>\n<TITLE>$domain - SMTP Relay Scanner $version</TITLE>\n\n";
   print FH "<SCRIPT LANGUAGE=JavaScript>\n";
   print FH "function ExpandIt(objMenu,objImage)\n";
   print FH "{\n";
   print FH "   if (objMenu.style.display == \"none\")\n";
   print FH "   {\n";
   print FH "      objMenu.style.display = \"\";\n";
   print FH "      objImage.src = \"http://www.cirt.dk/icons/folder.open.gif\";\n";
   print FH "   }\n";
   print FH "   else\n";
   print FH "   {\n";
   print FH "      objMenu.style.display = \"none\";\n";
   print FH "      objImage.src = \"http://www.cirt.dk/icons/folder.gif\";\n";
   print FH "   }\n";
   print FH "}\n";
   print FH "</SCRIPT>\n\n";
   print FH " <style type=\"text/css\">\n";
   print FH "<!--\n";
   print FH "   .inp  { font-family: monospace; background-color: Black; color: Black;}\n";
   print FH "   a.nav { text-decoration:none}\n";
   print FH "   a.nav:hover {color: Black}\n";
   print FH "//-->\n";
   print FH "</style>\n\n";
   print FH "</HEAD>\n";
   print FH "<!-- \r\n";
   print FH "     Remember if you are a Danish company, \r\n";
   print FH "     and does not have explicit written permission,\r\n";
   print FH "     you are in violation of the law on\r\n"; 
   print FH "     intellectual property rights\r\n -->\r\n\r\n";
   print FH "</HEAD>\n";
   print FH "<BODY BGCOLOR=white>\n";
   print FH "<TABLE WIDTH=90% BGCOLOR=white CELLSPACING=0 CELLPADDING=2 BORDER=0>\n<TR>\n<TD>\n<CENTER>\n<FONT FACE=Tahoma COLOR=black SIZE=+2><B>SMTP Relay Scanner $version</B></FONT>\n</LEFT>\n</TD>\n</TABLE>\r\n";
   print FH "<TABLE WIDTH=90% BGCOLOR=white CELLSPACING=0 CELLPADDING=2 BORDER=0>\n<TR>\n<TD>\n<CENTER>\n<FONT FACE=Tahoma COLOR=black SIZE=1><B>$copyright - CIRT.DK</B></FONT>\n</LEFT>\n</TD>\n</TABLE>\r\n";
   print FH "<TABLE WIDTH=90% BGCOLOR=white CELLSPACING=0 CELLPADDING=2 BORDER=0>\n<TR>\n<TD>\n<CENTER>\n<FONT FACE=Tahoma COLOR=black SIZE=1><B><A HREF=\"http://www.cirt.dk\">http://www.cirt.dk</A></B></FONT>\n</LEFT>\n</TD>\n</TABLE>\n<BR>\r\n";
   print FH "<TABLE WIDTH=90% BGCOLOR=black CELLSPACING=0 CELLPADDING=2 BORDER=0>\n<TR>\n<TD>\n<CENTER>\n<FONT FACE=Tahoma COLOR=white SIZE=+1><B>SMTP Relay Audit Report for $target</B>\n</FONT>\n</LEFT>\n</TD>\n</TABLE>\n<BR>\r\n";
   print FH "<TABLE WIDTH=90% BGCOLOR=white CELLSPACING=0 CELLPADDING=0 BORDER=0><TR ALIGN=left><COLOR=black SIZE=2>\r\n";

   print FH "\r\n";
   print FH "  <TR>\r\n";
   print FH "    <TD>\r\n";
   print FH "       <B>Target SMTP server:</B>\r\n";
   print FH "    </TD>\r\n";
   print FH "    <TD><LEFT>\r\n";
   print FH " <B>$target</B>\r\n";

   print FH "\r\n";
   print FH "  <TR>\r\n";
   print FH "    <TD>\r\n";
   print FH "       <B>Port number:</B>\r\n";
   print FH "    </TD>\r\n";
   print FH "    <TD><LEFT>\r\n";
   print FH "       <B>$port</B>\r\n";
   print FH "    </LEFT></TD>\r\n";
   print FH "  </TR>\r\n";
   print FH "\r\n";

   print FH "  <TR>\r\n";
   print FH "    <TD>\r\n";
   print FH "       <B>Domain name:</B>\r\n";
   print FH "    </TD>\r\n";
   print FH "    <TD><LEFT>\r\n";
   print FH "       <B>$domain</B>\r\n";
   print FH "    </LEFT></TD>\r\n";
   print FH "  </TR>\r\n";
   print FH "\r\n";

   print FH "  <TR>\r\n";
   print FH "    <TD>\r\n";
   print FH "       <B>Customer email:</B>\r\n";
   print FH "    </TD>\r\n";
   print FH "    <TD><LEFT>\r\n";
   print FH "       <B>$customer_email</B>\r\n";
   print FH "    </LEFT></TD>\r\n";
   print FH "  </TR>\r\n";
   print FH "\r\n";

   print FH "  <TR>\r\n";
   print FH "    <TD>\r\n";
   print FH "       <B>Tester email:</B>\r\n";
   print FH "    </TD>\r\n";
   print FH "    <TD><LEFT>\r\n";
   print FH "       <B>$tester_email</B>\r\n";
   print FH "    </LEFT></TD>\r\n";
   print FH "  </TR>\r\n";
   print FH "\r\n";

   print FH "  <TR>\r\n";
   print FH "    <TD>\r\n";
   print FH "       <B>Scan Started:</B>\r\n";
   print FH "    </TD>\r\n";
   print FH "    <TD><LEFT>\r\n";
   print FH "       <B>$timestamp</B>\r\n";
   print FH "    </LEFT></TD>\r\n";
   print FH "  </TR>\r\n";
   
   print FH "</TABLE>\r\n";
   print FH "<BR><TABLE WIDTH=90% BGCOLOR=black CELLSPACING=0 CELLPADDING=2 BORDER=0><TR><TD><CENTER><FONT FACE=Tahoma COLOR=white SIZE=+1><B>Audit Results</B></FONT></LEFT></TD></TABLE>\r\n";
   print FH "\r\n";
   print FH "<TABLE WIDTH=90% BGCOLOR=white CELLSPACING=0 CELLPADDING=0 BORDER=0><TR ALIGN=left><BR>\r\n";
   print FH "<FONT SIZE=\"2\" COLOR=Black> Description: Sent/Received Data - HELO/MAIL FROM/X-Priority/x-MSMail-Priority/Importance/Sensitivity</FONT><BR>\r\n";
   print FH "<CENTER>\n";
   print FH "--------------------------------------------------------------------------------------------------------\n";
   print FH "</CENTER><BR>\n";
   close(FH);
}

#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
# Writing log informaiton to report

sub wlog
{
   $b64name  =  hexencode("$plugin_file$count");
   $rcptto   =~ s/</&lt;/g;
   $rcptto   =~ s/>/&gt;/g;
   $mailfrom =~ s/</&lt;/g;
   $mailfrom =~ s/>/&gt;/g;
   $helo     =~ s/</&lt;/g;
   $helo     =~ s/>/&gt;/g;
   $0        =~ s/RelayScanner.pl//g;
   open(FH, ">>", $log);
   print FH "\r\n";
   print FH "  <TR>\r\n";
   print FH "     <TD>\r\n";
   if($set)
   {
      print FH "         <B><A HREF=\"$iconbase$plug$plugin_file.html\">TC: $count - $plugin_name<FONT COLOR=\"#FF0000\"> (Failed)</FONT></A></B><BR>\n";
   } 
   else
   {  
      print FH "         <B><A HREF=\"$iconbase$plug$plugin_file.html\">TC: $count - $plugin_name<FONT COLOR=\"#00FF00\"> (Success)</FONT></A></B><BR>\n";
   }
   print FH "          <DIV onClick=\"ExpandIt(menuCompany0$b64name,imgCompany0$b64name);\" CLASS=\"H2\">\n";
   print FH "          <IMG SRC=\"$iconbase/icons/folder.gif\" WIDTH=\"9\" HEIGHT=\"9\" ID=\"imgCompany0$b64name\">\n";
   print FH "          <FONT SIZE=\"2\" COLOR=Black style={cursor:hand;}><B>Sent/Received Data - $hlo/$list/$x_priority/$x_msmail_pri/$importance/$sensitivity</B><BR></FONT></DIV>\n";
   print FH "          <SPAN ID=\"menuCompany0$b64name\" STYLE=\"display: none\"><FONT SIZE=1>\n";
   print FH "          <B><LI>Data sent to Server:</B><BR>\n";
   print FH "               <I>$hlo [$helo]</I><BR>\n";
   print FH "               <I>$list FROM: $mailfrom</I><BR>\n";
   print FH "               RCPT TO: $rcptto<BR>\n";
   print FH "               DATA<BR>\n";
   print FH "               From: \"CIRT.DK SMTP Relay Scanner\" &lt;$mailfrom&gt<BR>\n";
   print FH "               To: $rcptto<BR>\n";
   print FH "               Subject: $subject (Test Case: $count)<BR>\n";
   print FH "               Date: $timestamp<BR>\n";
   print FH "               Message-ID: &lt;000501c5314325d6ef600901a8c0",$count,"\@",$domain,"&gt;<BR>\n";
   print FH "               MIME-Version: ",$mime_ver,"<BR>\n";
   print FH "               Content-Type: text/plain<BR>\n";
   print FH "               Content-Transfer-Encoding: 7bit<BR>\n";
   print FH "               <I>X-Priority: ",$x_priority,"</I><BR>\n";
   print FH "               <I>x-MSMail-Priority: ",$x_msmail_pri,"</I><BR>\n";
   print FH "               <I>X-Mailer: ",$xmailer,"</I><BR>\n";
   print FH "               <I>Importance: ",$importance,"</I><BR>\n";
   print FH "               X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2180<BR>\n";
   print FH "               <I>Sensitivity: ",$sensitivity,"</I><BR>\n";
   print FH "               Disposition-Notification-To: \"CIRT.DK Relay Scanner\" &lt;",$tester_email,"&gt<BR>\n";
   print FH "               <BR>\nTestcase: ",$count,"<BR>\n",$description,"<BR>\n<BR>\n";
   print FH "               Mail creation:<BR>\n";
   print FH "               $list FROM: $mailfrom<BR>\n";
   print FH "               RCPT TO: $rcptto<BR>\n";
   print FH "          <BR>\n.<BR>\n";
   print FH "          QUIT<BR>\n";
   print FH "          <CENTER>\n";
   print FH "               ------------------------------------------------------------------------------------------------------------------------------------------------\n";
   print FH "          </CENTER><BR>\n";

   print FH "          <B><LI>Response from Server:</B><BR>\n";
   my @lines = split(/\n/,$result);
   foreach $line (@lines)
   {
      if ( $line =~ m/(250.*Message accepted)/mgsi || m/(250.*queued)/mgsi)
      {
         print FH "         <B>$line</B><BR>\n";
      }
      else
      {
         print FH "            $line<BR>\n";
      }
   }
   print FH "          </font></SPAN><DIV onClick=\"ExpandIt(menuCompany0$b64name,imgCompany0$b64name);\" class=\"H2\"></font></SPAN></font>\n";

   print FH "     </TD>\r\n";
   print FH "     <TD><LEFT>\r\n";
   print FH "         <B></B>\r\n";
   print FH "     </LEFT></TD>\r\n";
   print FH "  </TR>\r\n";


   print FH "  <TR>\r\n";
   print FH "     <TD>\r\n";
   print FH "        <HR>\r\n";
   print FH "     </TD>\r\n";
   print FH "     <TD><LEFT>\r\n";
   print FH "        <HR>\r\n";
   print FH "     </TD\r\n";
   print FH "  </TR>\r\n";
   close (FH);
}

#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
# Write ending to log file

sub end_log
{
   $timestamp1 = localtime;
   open(FH, ">>", $log);
   
   print FH "\r\n";
   print FH "  </TABLE>\r\n";
   print FH " \r\n\r\n";
   print FH "<BR><TABLE WIDTH=90% BGCOLOR=black CELLSPACING=0 CELLPADDING=2 BORDER=0><TR><TD><CENTER><FONT FACE=Tahoma COLOR=white SIZE=+1><B>Report Summary</B></FONT></LEFT></TD></TABLE><BR>\r\n";
   print FH "<TABLE WIDTH=90% BGCOLOR=white CELLSPACING=0 CELLPADDING=0 BORDER=0><TR ALIGN=left>\r\n";
   print FH "  <TR>\r\n";
   print FH "     <TD>\r\n";
   print FH "         <B>The Scan completed:</B>\r\n";
   print FH "     </TD>\r\n";
   print FH "     <TD><LEFT>\r\n";
   print FH "         <B>$timestamp1<B>\r\n";
   print FH "     </LEFT></TD>\r\n";
   print FH "  </TR>\r\n";
   print FH "\r\n";

   print FH "  <TR>\r\n";
   print FH "     <TD>\r\n";
   print FH "         <B>Possible Success attempts:</B>\r\n";
   print FH "     </TD>\r\n";
   print FH "     <TD><LEFT>\r\n";
   print FH "         <B>$success<B>\r\n";
   print FH "     </LEFT></TD>\r\n";
   print FH "  </TR>\r\n";
   print FH "\r\n";

   print FH "  <TR>\r\n";
   print FH "     <TD>\r\n";
   print FH "         <B>Possible Failed attempts</B>\r\n";
   print FH "     </TD>\r\n";
   print FH "     <TD><LEFT>\r\n";
   print FH "         <B>$faliure<B>\r\n";
   print FH "     </LEFT></TD>\r\n";
   print FH "  </TR>\r\n";

   print FH "  <TR>\r\n";
   print FH "     <TD>\r\n";
   print FH "         <B>Total number of Relay checks performed:</B>\r\n";
   print FH "     </TD>\r\n";
   print FH "     <TD><LEFT>\r\n";
   print FH "         <B>$count<B>\r\n";
   print FH "     </LEFT></TD>\r\n";
   print FH "  </TR>\r\n";
   print FH "\r\n";

   print FH "</TABLE>\r\n";
   print FH "\r\n";
   print FH " <BR><TABLE WIDTH=90% BGCOLOR=black CELLSPACING=0 CELLPADDING=2 BORDER=0><TR><TD><CENTER><FONT FACE=Tahoma COLOR=white SIZE=1><B>$copyright - CIRT.DK</B></FONT></LEFT></TD></TABLE><BR><BR>\r\n";
   print FH " </BODY>\r\n";
   print FH "<!-- Remember if you are a Danish company, \r\n";
   print FH "     and does not have explicit written permission,\r\n";
   print FH "     you are in violation of the law on\r\n"; 
   print FH "     intellectual property rights\r\n -->\r\n\r\n";
   print FH "</HTML>\r\n";
   close (FH);

   $timestamp1 = localtime;
   print "\r\n\r\n [X] Scanning Finished\t\t - $timestamp1";
   print "\r\n\r\n ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOoo\r\n";
   printf STDERR "\r\n  Successfully attempts:%3s $success";
   printf STDERR "\r\n  Failed attempts:%8s $faliure";
   printf STDERR "\r\n  Total attempts:%9s $count";
   print "\r\n\r\n ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOoo\n\n\n";

}

#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO
#ooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOOooOO

#Shows splash screen
&splash_screen;
# Check for Updates of the SMTP Releay Scanner
&ChkUpdates;
# Loading the Scanner
&Load_scanner;
# Lets check if there is a service and if the service is SMTP
&ChkServerExist;
# Counts testcases to run
&count_tc;
# Load in all the plugins and run them through the Relay engine
&run_plugins;
# Writes summery to logfile and writes summery to screen
&end_log;

