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

 

Nick Kelly

Cybersecurity Engineer, Cisco

Nick has over 20 years of experience in Security Operations and Security Sales. He is an avid student of cybersecurity and regularly engages with the Infosec community at events like BSides, RVASec, Derbycon and more. The son of an FBI forensics director, Nick holds a B.S. in Criminal Justice and is one of Cisco’s Fire Jumper Elite members. When he’s not working, he writes cyberpunk and punches aliens on his Playstation.

 

Virgilio “BONG” dela Cruz Jr.

CCDP, CCNA V, CCNP, Cisco IPS Express Security for AM/EE
Field Solutions Architect, Tech Data

Virgilio “Bong” has sixteen years of professional experience in IT industry from academe, technical and customer support, pre-sales, post sales, project management, training and enablement. He has worked in Cisco Technical Assistance Center (TAC) as a member of the WAN and LAN Switching team. Bong now works for Tech Data as the Field Solutions Architect with a focus on Cisco Security and holds a few Cisco certifications including Fire Jumper Elite.

 

John Cavanaugh

CCIE #1066, CCDE #20070002, CCAr
Chief Technology Officer, Practice Lead Security Services, NetCraftsmen

John is our CTO and the practice lead for a talented team of consultants focused on designing and delivering scalable and secure infrastructure solutions to customers across multiple industry verticals and technologies. Previously he has held several positions including Executive Director/Chief Architect for Global Network Services at JPMorgan Chase. In that capacity, he led a team managing network architecture and services.  Prior to his role at JPMorgan Chase, John was a Distinguished Engineer at Cisco working across a number of verticals including Higher Education, Finance, Retail, Government, and Health Care.

He is an expert in working with groups to identify business needs, and align technology strategies to enable business strategies, building in agility and scalability to allow for future changes. John is experienced in the architecture and design of highly available, secure, network infrastructure and data centers, and has worked on projects worldwide. He has worked in both the business and regulatory environments for the design and deployment of complex IT infrastructures.