#!/usr/bin/perl
##############################################
#                                            #
# RelayCheck v1.0                            #
# Written By: Epicurus (epicurus@wilter.com) #
#                                            #
# Purpose: To scan a list of SMTP servers to #
# find servers that will relay e-mail. There #
# are many reasons why one might need such a #
# list of SMTP servers.                      #
#                                            #
# Usage:                                     #
# Create a list of hosts which you want to   #
# scan. One host per line. Then run this     #
# script.                                    #
#                                            #
##############################################
use Socket;

print "RelayCheck v1.0\n";
print "Written By: Epicurus (epicurus\@wilter.com)\n\n";

print "Host List: ";
chomp($host_list=<STDIN>);

print "HELO Domain: ";
chomp($helo_domain=<STDIN>);

print "Attempt From: ";
chomp($from=<STDIN>);

print "Attempt To: ";
chomp($to=<STDIN>);

print "Log Session?(y/n)";
$yn=<STDIN>;

if($yn =~ /y/i)
{ 
	$log = 1; 
	$logfile="relay.log";

	print "Log File [$logfile]: ";
	$file=<STDIN>;
	chop($file) if $file =~ /\n$/;

	if($file ne "") 
	{
		$logfile=$file;
	}
	open(LOG,">>$logfile") || die("Unable to write to $logfile!");
	print LOG "RelayCheck Scan:\n\n";
}

##############################################

$helo_string = "HELO $helo_domain\r\n";
$mail_from = "MAIL FROM: <$from>\r\n";
$rcpt_to = "RCPT TO: <$to>\r\n";
$port = 25;

$found=0;
$i=0;
open(HOSTS,"$host_list") || die $!;
while(<HOSTS>)
{
	chop($_) if $_ =~ /\n$/;
	$remote=$_;
	$print_remote = $remote;
	$print_remote .= "." while(length($print_remote) < 38);
	$print_remote .= ": ";
        print "$print_remote";
	print LOG "$print_remote" if($log==1);
	&send_mail;
	$i++;
}
close(HOSTS);

print "\nFinished Scanning. $found out of $i hosts will relay.\n\n";
print LOG "\nFinished Scanning. $found out of $i hosts will relay.\n\n" if($log==1);
close(LOG);


sub send_mail
{
	if ($port =~ /\D/) { $port = getservbyname($port, 'tcp'); }
	die("No port specified.") unless $port;
        $iaddr = inet_aton($remote) || die("Failed to find host: $remote");
        $paddr = sockaddr_in($port, $iaddr);
	$proto = getprotobyname('tcp');
        socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die("Failed to open socket: $!");
	connect(SOCK, $paddr) || die("Unable to connect: $!");

	$smtp=<SOCK>;
        if($smtp =~ /^220 /)
	{
		send(SOCK,$helo_string,0);
	}

	$smtp=<SOCK>;
	if($smtp =~ /^250 /)
	{
		send(SOCK,$mail_from,0);
	}

	$smtp=<SOCK>;
	if($smtp =~ /^250 /)
	{
		send(SOCK,$rcpt_to,0);
	}
	
	$smtp=<SOCK>;
	if($smtp =~ /^250 /)
	{
		$found++;
                print "relaying allowed\n";
		print LOG "relaying allowed\n" if($log==1);
	}
	else
	{
                print "no relaying\n";
		print LOG "no relaying\n" if($log==1);
	}

	send(SOCK,"QUIT\r\n",0);
        close(SOCK);
}
