#!/usr/bin/perl -w
# relay.pl C-class smtp relay scanner by konewka <konewka@localdomain.ru>
# use ./relay.pl 2> relay_servers to log only smtps with relaying.
# This is edu purpose only. enjoy
use Net::SMTP;

# Setup
my $mailfrom = "test\@yahoo.com";
my $mailto = "you\@google.pl";
my $timeout = 5;
my $print_relay_only = 0;
# Setup ends here. DO NOT CHANGE ANYTHING BELOW.

print "relay.pl by konewka <konewka\@localdomain.ru>\n";

if (!$ARGV[0] or $ARGV[0] !~ /^[^.]+\.[^.]+\.[^.]+$/) {
    print "- wrong syntax\n";
    print "usage: $0 <C-class subnet>\n";
    print "e.g. $0 192.168.11\n";
    exit 0;
}

my $subnet = $ARGV[0];
my $domain = "no domain yet";
my $serv_cnt = 0;
my $rel_cnt = 0;
my $nrel_cnt = 0;

print "- searching subnet $subnet for relays ..\n";
for ($d=0;$d<=255;$d++) {
    my $host = $subnet.".$d";
    if (!($sd = Net::SMTP->new($host, Timeout=>$timeout))) {
	next;
    }
    
    $serv_cnt++;
    # small trick to avoid from the same server display several times
    if ($domain ne $sd->domain()) {
	$domain = $sd->domain();
    }
    else {
	next;
    }
    if (!$sd->mail($mailfrom)) {
	print "+ $host [$domain] returned an error after mailfrom sent.\n";
    }
    if ($sd->to($mailto)) {
	print STDERR "+ $host [$domain] relays.\n";
	$rel_cnt++;
    }
    else {
	if (!$print_relay_only) {
	    print "+ $host [$domain] doesnt relay.\n";
	}
	$nrel_cnt++;
    }

    $sd->quit();
}

print "--- servers: $serv_cnt relays: $rel_cnt relayless: $nrel_cnt ---\n";
exit 0;
