#!/usr/bin/perl
#
# bin/relay.saint
#
# based on checks from mail-abuse.org
#
$running_under_saint = 1;
require 'config/paths.pl';
require 'perl/misc.pl';
require 'perl/get_host.pl';
require 'perl/getfqdn.pl';
require 'perl/hostname.pl';

die "Usage: relay.saint <target>\n" if $#ARGV < 0;
print "BEGIN\n";

$verbose = 0;
if ($ARGV[0] =~ /-v/) {
  $verbose = 1;
  shift @ARGV;
}
$target = $ARGV[0];
$status = "a";
$service = "smtp";
$port = "25";

@relay_checks = (
	"MAIL FROM: <saint\@mail-abuse.org>\r\nRCPT TO: <saint\@mail-abuse.org>\r\n",
	"MAIL FROM: <saint>\r\nRCPT TO: <saint\@mail-abuse.org>\r\n",
	"MAIL FROM: <>\r\nRCPT TO: <saint\@mail-abuse.org>\r\n",
	"MAIL FROM: <saint\@$target>\r\nRCPT TO: <saint\@mail-abuse.org>\r\n",
	"MAIL FROM: <saint\@$target>\r\nRCPT TO: <saint%mail-abuse.org\@$target>\r\n",
	"MAIL FROM: <saint\@$target>\r\nRCPT TO: <\"saint\@mail-abuse.org\">\r\n",
	"MAIL FROM: <saint\@$target>\r\nRCPT TO: <\"saint%mail-abuse.org\">\r\n",
	"MAIL FROM: <saint\@$target>\r\nRCPT TO: <saint\@mail-abuse.org\@$target>\r\n",
	"MAIL FROM: <saint\@$target>\r\nRCPT TO: <\"saint\@mail-abuse.org\"\@$target>\r\n",
	"MAIL FROM: <saint\@$target>\r\nRCPT TO: <saint\@mail-abuse.org\@$target>\r\n",
	"MAIL FROM: <saint\@$target>\r\nRCPT TO: <\@$target:saint\@mail-abuse.org>\r\n",
	"MAIL FROM: <saint\@>\r\nRCPT TO: <relaytest\@mail-abuse.org\@>\r\n",
	"MAIL FROM: <saint\@$target>\r\nRCPT TO: <mail-abuse.org!saint>\r\n",
	"MAIL FROM: <saint\@$target>\r\nRCPT TO: <mail-abuse.org!saint\@$target>\r\n"
);

# if we're scanning our own host, it will false alarm
exit 0 if $target eq &getfqdn(&hostname());

$ok = "yes";
for $check (@relay_checks) {

    $args = "-bs \"HELO saint\r\n" . $check . "QUIT\r\n\"";

    print "$args\n" if $verbose;
    open(RELAY, "$TCP_SCAN $args $target $port |") || die "Can't open $TCPSCAN: $!\n";
    while (<RELAY>) {
	print if $verbose;

	# If we get 250 OK for HELO, MAIL FROM, and RCPT TO,
	# then the server probably allows relaying
	if (/\D250\D.*\D250\D.*\D250\D/) {
	    # Microsoft mail servers false alarm on this check
	    $ok = "no";
	    $ok = "M" if /Microsoft/;
	}
    }
    close RELAY;
    last if $ok ne "yes";
}

if ($ok eq "no") {
    $severity = "zcio";
    $trustee = "ANY\@$target";
    $trusted = "ANY\@$target";
    $service_output = "SMTP mail relay";
    $text = "SMTP may be a mail relay";
    &saint_print();
}
 
