Cisco NAC Subnet Filter API Example

NetCraftsmen®

The Cisco NAC subnet filter is used to allow computers to bypass authentication and optionally perform posture assessment.  The optional posture assessment is based on the role that is assigned to the subnet filter.  These subnets can be added through the NAC Manager Web GUI or through the NAC API.

The NAC API provides a way of performing NAC functions through a script.  A subnet filter script could be useful when adding or removing a large number of subnets.  Cisco provides details on the API functionality, but does not provide a lot of examples for configuring scripts, so I thought I’d throw out a Perl script I wrote as an example.

The Perl script I wrote provides a means of adding or removing subnets.  The usage screen is shown below.  

#######################################################################
Usage:  perl subnet.pl [remove | add [deny, allow, role name]] file
Example:  perl subnet.pl add allow subnetlist.txt
Example:  perl subnet.pl add "employee" subnetlist.txt
Example:  perl subnet.pl remove subnetlist.txt
  - File must contain one Subnet per line in subnet,CIDR netmask,description format
  - Make user there is a carriage return after the last line
  - Example of a line:  172.16.1.0,24,Allowed Subnets
#######################################################################

An example of adding a subnet is shown below.

perl subnet.pl add allow subnetlist.txt
Enter the NAC Manager IP: 10.1.1.233
Enter the NAC Manager User ID: admin
Enter the NAC Manager password: password
#################################################################
Log files have been created with the information below.
Note:  If the file existed in the current directory, it was deleted
        success.log = Successful additions
        failure.log = Failed additions
        info.log = Informative messages
#################################################################

The full Perl script is shown below.

#! /usr/bin/perl -w
############################################################
#
# Modified 8/1/2010
#
# This Perl script changes the Subnet filter list of existing
# filter list entries to the "deny" access type.  Because the NAC API
# only support add and remove, we have to remove the subnet 
# and then add it back in with "deny" as the access type
#
# The script takes two or three parameters.  The first parameter is whether 
# to add or remove the subnets.  The second parameter is the role to use, if
# "add" was chosen as the first parameter.  The third parameter is the file 
# that contains a CSV file with the subnets, the CIDR subnet mask, and 
# description per line. 
#
# There are three log files that are created.  Success.log
# contains the subnet of all subnets that were
# successfully changed in the NAC subnet filter list.  
# Failure.log contains the subnets of all subnets 
# that failed to be added.  Info.log contains information 
# about the success and failure of each subnet.  The files
# are overwritten on each script execution, so the files should be
# saved to a different directory if they need to be kept
#
############################################################
# Define variables
$successlog = "success.log";
$failurelog = "failure.log";
$infolog = "info.log";
# Use HTTP Module
use HTTP::Request::Common qw(POST GET);
use HTTP::Headers;
use LWP::UserAgent;
use MIME::Base64;
sub usage()
{
  print "nn#######################################################################n";
  print "Usage:  perl subnet.pl [remove | add [deny, allow, role name]] <filename>n";
  print "Example:  perl subnet.pl add allow subnetlist.txtn";
  print "Example:  perl subnet.pl add "employee" subnetlist.txtn";
  print "Example:  perl subnet.pl remove subnetlist.txtnn";
  print "  - File must contain one Subnet per line in <subnet>,<CIDR mask>,description formatn";
  print "  - Make user there is a carriage return after the last linen";
  print "  - Example of a line:  172.16.1.0,24,Allowed Subnetsn"; 
  print "#######################################################################n";
}
# Exit if an incorrect number of arguments are used
if ($#ARGV < 1 or $#ARGV > 2) {
  usage();
  exit 1;
}
$action = $ARGV[0];
if ($action =~ /add/)
  {
  if ($#ARGV != 2) 
    {
    usage();
    exit 1;
    }
  $type = $ARGV[1];
  $file = $ARGV[2];
  }  
elsif ($action =~ /remove/)
  {
  if ($#ARGV != 1)
    {
    usage();
    exit 1;
    }
  $type = "";
  $file = $ARGV[1];
  }
else
  {
  usage();
  exit 1;
  }
# Open file for reading
open(FILE, "<$file") || die "nnCan't open file $file for readingn";
# Open LogFile
open SLOG, "> $successlog";
open FLOG, "> $failurelog";
open ILOG, "> $infolog";
# Gathering information about access to the NAC Manager
print "Enter the NAC Manager IP: ";
$camip = <STDIN>;
chomp($camip);
print "Enter the NAC Manager User ID: ";
$camuser = <STDIN>;
chomp($camuser);
print "Enter the NAC Manager password: ";
$campassword = <STDIN>;
chomp($campassword);
# Setup the request parameters
$ua = LWP::UserAgent->new();
$ua->agent("CCAAgent/v4.1.3 CleanAccessManager API");
$encoded = encode_base64("$camuser/:$campassword");
$url = "https://$camip/admin/cisco_api.jsp";
# Reading each line of the file
while (<FILE>)
  {
  ($line) = $_;
  chomp($line);
  ($subnet,$mask,$description) = split(/,/,$line,3);
  #Error checking for valid Subnet
  if ($subnet !~ /dd?d?.dd?d?.dd?d?.dd?d?/)
    {
    print ILOG "Invalid Subnet $linen";    
    print FLOG "$linen";
    next;
    }
  # Creating API request
  if ($action =~ /remove/)
    {
    # Creating requests
    $req = POST $url,
    'Authorization' => "Basic ".$encoded,
    Content => [
      op => "removesubnet",
      admin => "$camuser",
      passwd => "$campassword",
      subnet => "$subnet",
      mask => "$mask"
    ];
    }
  if ($action =~ /add/)
    {
    if ($type =~ /allow/ || $type =~ /deny/)
      {
      $req = POST $url,
      'Authorization' => "Basic ".$encoded,
      Content => [
        op => "addsubnet",
        admin => "$camuser",
        passwd => "$campassword",
        subnet => "$subnet",
        mask => "$mask",
        type => "$type",
        desc => "$description"
      ];
      }
    else
      {
      $req = POST $url,
      'Authorization' => "Basic ".$encoded,
      Content => [
        op => "addsubnet",
        admin => "$camuser",
        passwd => "$campassword",
        subnet => "$subnet",
        mask => "$mask",
        type => "userole",
        role => "$type",
        desc => "$description"
      ];
      }
    }
  # Executing API request
  $res = $ua->request($req);
  $err = $res->status_line;
  # Put the results into $results
  $results = $res->content;
  #############
  # Reporting
  #############
  print ILOG "Result for $line	";
  print ILOG "Webserver response=$err	";
  print ILOG "API response=$results";
  # CAM is reporting bad HTTP request
  if ($err !~ "200 OK") 
    {
    print FLOG "$linen";
    next;
    }
  
  # CAM response from API Request
  if ($results =~ /error=0/)
    {
    print SLOG "$linen";
    }
  else 
    {
    print FLOG "$linen";
    }
  }
  # Close logfile
  close SLOG;
  close FLOG;
  close ILOG;
  print "n#################################################################n";
  print "Log files have been created with the information below.n";
  print "Note:  If the file existed in the current directory, it was deletedn";
  print "	success.log = Successful additionsn";
  print "	failure.log = Failed additionsn";
  print "	info.log = Informative messagesn";
  print "#################################################################n";
  
  exit 0;

Leave a Reply