#!/usr/bin/perl
#
#  file "pfctl_delete"
#  OpenBSD firewall-delete script, called by "doormand". 
#  This removes a "pass in quick" rule from the firewall.
#
#  Called with five arguments:
#
# $1 : name of the interface (e.g. ne0) (unused for rule-flush)
# $2 : source IP; i.e. dotted-decimal address of the 'knock' client
# $3 : source port; when this script is called for the first time
#      to delete a broad firewall rule, this argument will be set
#      to a single "0" (0x30) character.  This means that the source
#      port was not known, and a broad rule allowing any source
#      port was set.
# $4 : destination IP; that is, the IP address of the interface 
#      in argument 1.
# $5 : The port number of the requested service (e.g. 22 for ssh, etc.)
#
#

use strict ;

my ($if, $saddr, $sport, $daddr, $dport) ;
my ($name) ; 
my (@a, $int_saddr) ;
my ($ret) ;
my $pfctl = "/sbin/pfctl" ;

($if, $saddr, $sport, $daddr, $dport) = @ARGV ;

if ($sport == 0) {
    @a = split /\./, $saddr ;
    $int_saddr = ($a[0]<<24) + ($a[1]<<16) + ($a[2]<<8) + $a[3] ;
    $name = sprintf ("%8.8x-%4.4x", $int_saddr, $dport) ;
} else {
    $name = sprintf ("%4.4x-%4.4x", $sport, $dport) ;
}

open PIPE, "2>&1 pfctl -Fr -a doorman:$name |" ;

$ret = <PIPE> ;
chomp $ret ;

if ($ret =~ /^rules cleared$/) {
    print "0\n" ;
} else {
    print "-1 3 $ret\n" ;
}

