Configure TCP filtering (Perl)

This code can be found in Chapter 3 of Windows Server 2003 Security Cookbook

Purchase XP Cookbook or Networking Recipes for only $25 plus shipping! While supplies last.

Find out how to download all of the Perl code from this site.

# This code enables IP Filtering for all adapters and configures
# filtering for all IP-enabled adapters.
# ------ SCRIPT CONFIGURATION ------

use Win32::OLE qw(in);

$strComputer = '.';
$arrTCPPorts = [0];
# Allow all TCP ports
$arrUDPPorts = [0];
# Allow all UDP ports
$arrProtos = [80, 25];
# Allow only HTTP and SMTP
# ------ END CONFIGURATION ---------
$objWMI = Win32::OLE->GetObject('winmgmts:\\\\' . $strComputer . '\\root\\cimv2');
$objAdapterConfig = $objWMI->Get('Win32_NetworkAdapterConfiguration');
$intRC = $objAdapterConfig->EnableIPFilterSec(1);
if ($intRC == 0) {
    print "IP Filtering for all adapters enabled\n";
}
elsif ($intRC == 1) {
    print "IP Filtering enabled for all adapters, but you must reboot for the changes to take effect\n";
}
else {
    print 'There was an error enabling IP Filtering for all ' . 'adapters: ' . $intRC, "\n";
}

$colNAConfigs = $objWMI->ExecQuery('select * ' . ' from Win32_NetworkAdapterConfiguration ' . ' where IPEnabled = True');
foreach my $objNAConfig (in $colNAConfigs) {
    $intRC = $objNAConfig->EnableIPSec($arrTCPPorts, $arrUDPPorts, $arrProtos);
    if ($intRC == 0) {
        print 'IP Filtering configured for \'' . $objNAConfig->Description . '\'', "\n";
    }
    elsif ($intRC == 1) {
        print 'IP Filtering configured for \'' . $objNAConfig->Description . '\', but you must reboot for the changes to take effect', "\n";
    }
    else {
        print 'There was an error configuring IP Filtering for \'' . $objNAConfig->Description . '\': ' . $intRC, "\n";
    }
}

This code has been viewed 780 times.

New from the creators of TechTasks.com: StatSheet.com