#!/usr/bin/perl
#
# external_acl helper for Squid to verify NT Domain group
# membership of a computername using his IP address
#
# Author:
#   Razvan Grigore <esteticu@gmail.com>
#
# Version history:
#   2008-12-05 Razvan Grigore <esteticu@gmail.com>
#               Initial release

# Disable output buffering
$|=1;

#
# Find out IP's hostname
#
sub getname {
        local($ip) = @_;
        $SIG{ALRM} = sub { die(); };
        eval {
                $hostname = "";
                alarm 1;
                $hostname = `/usr/bin/nmblookup -A $ip | awk '\$2 == "<20>" { print \$1 ; exit }'`;
                alarm 0;
        };
        chop $hostname;
        return $hostname;
}


#
# Check if computername belongs to a group
#
sub check {
        local($computername, $group) = @_;
        $cn = `/usr/bin/ldapsearch -LLL -h __ldap server__ -D '__ldap user__' -w '__ldap password__' -x -b "OU=your,DC=internal,DC=domain,DC=com" "(&(objectclass=computer)(sAMAccountName=$computername\$)(memberof=CN=$group,OU=Administrative Groups,OU=your,OU=Groups,DC=internal,DC=domain,DC=com))" cn |grep "cn:"`;
        return 'ERR' if $cn eq "";
        return 'OK';
}

#
# Main loop
#
while (<STDIN>) {
        chop;
        ($ip, $group) = split(/\s+/);

        $computername = &getname($ip);

        if ($computername eq "") {
                print "ERR\n";
        }
        else {
                $ans = &check($computername, $group);
                print "$ans\n";
        }
}
