#!/usr/bin/perl

use strict;
use Sys::Syslog qw(:DEFAULT setlogsock);
use Socket;

#
# Usage: relaycheck.pl [-v]
#
# Demo delegated Postfix SMTPD policy server. This server implements
# relay address checking with vrfy commands. State is kept in a memory
# through associative arrays. Logging is sent to syslogd.
#
# How it works: each time a Postfix SMTP server process is started
# it connects to the policy service socket, and Postfix runs one
# instance of this PERL script.  By default, a Postfix SMTP server
# process terminates after 100 seconds of idle time, or after serving
# 100 clients. Thus, the cost of starting this PERL script is smoothed
# out over time.
#
# To run this from /etc/postfix/master.cf:
#
#    relaycheck  unix  -       n       n       -       -       spawn
#      user=nobody argv=/usr/bin/perl /usr/libexec/postfix/relaycheck.pl
#
# To use this from Postfix SMTPD, use in /etc/postfix/main.cf:
#
#    smtpd_recipient_restrictions =
#	...
#	reject_unauth_destination
#	check_policy_service unix:private/policy
#	...
#
# NOTE: specify check_policy_service AFTER reject_unauth_destination
# or else your system can become an open relay.
#
# To test this script by hand, execute:
#
#    % perl relaycheck.pl
#
# Each query is a bunch of attributes. Order does not matter, and
# the demo script uses only a few of all the attributes shown below:
#
#    request=smtpd_access_policy
#    protocol_state=RCPT
#    protocol_name=SMTP
#    helo_name=some.domain.tld
#    queue_id=8045F2AB23
#    sender=foo@bar.tld
#    recipient=bar@foo.tld
#    client_address=1.2.3.4
#    client_name=another.domain.tld
#    instance=123.456.7
#    sasl_method=plain
#    sasl_username=you
#    sasl_sender=
#    size=12345
#    [empty line]
#
# The policy server script will answer in the same style, with an
# attribute list followed by a empty line:
#
#    action=dunno
#    [empty line]
#

our $check_validity_time=60;
our %relaytable=('relaydomain.example.org' => 'targetserver.example.org',
		 'faszom.org' => '10.0.0.1',
		 'teleline.hu' => '62.77.210.129');

#
# Syslogging options for verbose mode and for fatal errors.
# NOTE: comment out the $syslog_socktype line if syslogging does not
# work on your system.
#
our $syslog_socktype = 'unix'; # inet, unix, stream, console
our $syslog_facility="mail";
our $syslog_options="pid";
our $syslog_priority="info";
our $verbose;
our $option;
our %attr;
our %cached_address;
our %cache_timestamp;

#
# VRFY an addres at the target server.
#

sub vrfy_recipient {
    my $addr = shift ;
    my ($lp, $domain, $rep);
    ($lp, $domain) = split( /\@/ , $addr , 2 ) ;

    socket(MYSOCK, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
    connect(MYSOCK, sockaddr_in(25,inet_aton($relaytable{$domain})));
    select((select(MYSOCK), $| = 1)[0]);
    $rep=<MYSOCK>;
    print MYSOCK "VRFY $addr\n";
    $rep=<MYSOCK>;
    return scalar($rep=~m/^2\d\d /);
    close(MYSOCK);
}

#
# Recipient checking. First we try our cache, than connect to target
# and VRFY the recipient.
#

sub check_recipient {
    my $addr = shift;
    if ( defined($cached_address{$addr}) ) {
        if (time() - $cache_timestamp{$addr} > $check_validity_time ) {
            undef $cached_address{$addr};
            undef $cache_timestamp{$addr};
        } else {
            return $cached_address{$addr};
        }
    }
    $cached_address{$addr}=vrfy_recipient($addr);
    $cache_timestamp{$addr}=time();
    return $cached_address{$addr};
}

#
# Demo SMTPD access policy routine. The result is an action just like
# it would be specified on the right-hand side of a Postfix access
# table.  Request attributes are available via the %attr hash.
#
sub smtpd_access_policy {
    my($lp, $domain);

    ($lp, $domain) = split( /\@/ , lc $attr{'recipient'} , 2 ) ;

    # The result can be any action that is allowed in a Postfix access(5) map.
    #
    # To label mail, return ``PREPEND'' headername: headertext
    #
    # In case of success, return ``DUNNO'' instead of ``OK'' so that the
    # check_policy_service restriction can be followed by other restrictions.
    #
    # In case of failure, specify ``DEFER_IF_PERMIT optional text...''
    # so that mail can still be blocked by other access restrictions.
    #
    if ( ! grep ( /^$domain$/ , keys(%relaytable) ) ) {
	return "dunno";
    } elsif ( check_recipient($attr{'recipient'}) ) {
	return "dunno";
    } else {
	return "reject Recipient address rejected, unkown address";
    }
}

#
# Log an error and abort.
#
sub fatal_exit {
    my($first) = shift(@_);
    syslog "err", "fatal: $first", @_;
    exit 1;
}

#
# This process runs as a daemon, so it can't log to a terminal. Use
# syslog so that people can actually see our messages.
#
setlogsock $syslog_socktype;
openlog $0, $syslog_options, $syslog_facility;

#
# We don't need getopt() for now.
#
while ($option = shift(@ARGV)) {
    if ($option eq "-v") {
	$verbose = 1;
    } else {
	syslog $syslog_priority, "Invalid option: %s. Usage: %s [-v]",
		$option, $0;
	exit 1;
    }
}

#
# Unbuffer standard output.
#
select((select(STDOUT), $| = 1)[0]);

#
# Receive a bunch of attributes, evaluate the policy, send the result.
#
while (<STDIN>) {
    my $action;
    if (/([^=]+)=(.*)\n/) {
	$attr{substr($1, 0, 512)} = substr($2, 0, 512);
    } elsif ($_ eq "\n") {
	if ($verbose) {
	    for (keys %attr) {
		syslog $syslog_priority, "Attribute: %s=%s", $_, $attr{$_};
	    }
	}
	fatal_exit "unrecognized request type: '%s'", $attr{request}
	    unless $attr{"request"} eq "smtpd_access_policy";
	$action = smtpd_access_policy();
	syslog $syslog_priority, "Action: %s", $action if $verbose;
	print STDOUT "action=$action\n\n";
	%attr = ();
    } else {
	chop;
	syslog $syslog_priority, "warning: ignoring garbage: %.100s", $_;
    }
}
