cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
17936
Views
24
Helpful
19
Comments
Anand Kanani
Cisco Employee
Cisco Employee

I am pleased to share a script that I have created to emulate the Time-Based Access Lists (ACL) functionality on Cisco Firepower Threat Defense (FTD) using the APIs available in Cisco Firepower Management Center (FMC). This can be used until the feature is available natively into the later versions of FTD/FMC.

 

This script - called as tba.py is a Python Script. It is available for download as an attachment from the bottom of this page.

 

How does it work:

  1. The user creates a text file containing the list of Policy Name, Rule ID and enable/disable timestamps.
  2. This script runs every 1 minute as a cronjob / scheduled task. It reads the file created by the user, checks if a rule is supposed to be enabled or disabled. If yes, then it makes the change on FMC by making the API calls. Then it pushes the Policy Changes onto the affected NGFW devices by triggering a Policy Deployment for those devices.
  3. Additionally, the script reports all its Activities and Errors to an Audit Log file. There are various error handling and reporting functions built in the script. The script can also send out an email notification after making any Policy updates.

 

What are the Dependencies / Requirements:

  1. Run this script on any separate host that has reachability to FMC via HTTPS for Management. Currently, it has been tested on Linux (however any OS should be fine as long as it has Python & the required Python modules installed).
  2. This script has been tested on Python 3.6, however it should work fine on any recent version of Python 3 or Python 2
  3. It requires Python 'requests' module. This can be installed by executing the command "python -m pip install requests" on the CLI of the host where you will be running this script after installing Python.
  4. Create a new user on FMC specifically for executing this script. This user must have the Read-Write Privilege to Modify the required the Access Policies to enable/disable a particular rule, and this user must have the Privilege to Deploy the Policies on the NGFW devices. In case if you want to do manual deployment of the policy updates done by this script, then you will not need the Deploy Privilege for this user.

 

Which FMC / FTD softwares versions are supported:

This script is created and tested on FMC version 6.2.2.x. The script makes API calls to the FMC only. So anything above FMC 6.2.2 and above should be fine.

The script does not talk to FTD device, hence its version does not matter.

 

What are the Inputs required:

The script will require the user to update the following variables inside the script BEFORE executing it for the first time.

fmc_hostname = "x.x.x.x"                     # REQUIRED - Provide the IP or Hostname of FMC.
fmc_username = "xxxx"                        # REQUIRED - Create a new user on FMC specifically for executing this script. DO NOT keep it same as your regular FMC user account.
fmc_password = "xxxx"                        # REQUIRED -
domain_in_fmc = "Global"                     # REQUIRED - FMC Management Domain. Leave it as it is, if you do not know what this is.
smtp_server = 'smtp.mydomain.com:25'         # OPTIONAL - provide this if you want email notifications about policy changes done by this script. Make it blank otherwise
sender = 'no-reply@mydomain.com'             # OPTIONAL - provide this if you want email notifications about policy changes done by this script. Make it blank otherwise
receivers = ['securityadmin@mydomain.com']   # OPTIONAL - note the [] brackets in this one. do not delete them
deploy_policy_changes_automatically = 1      # REQUIRED - 1 = automatic / 0 = manual, policy deployment to devices

 

The script will further require the user create a file named - tba-db.txt This file will contain the list of Policy Name, Rule ID and enable/disable timestamps for the Rules which the user wants to enable/disable at a particular pre-defined time. If you run the script without creating this file, then the script will create a sample file for you with simple documentation inside it around how to proceed further.

 

Here is how the tba-db.txt file would look like in production:

ADD YOUR TIME BASED ACL DETAILS HERE IN THE BELOW SYNTAX:
<ENABLE Date in YYYY-MM-DD HH:MM> #### <DISABLE Date in YYYY-MM-DD HH:MM> #### "<Policy Name>" #### <Rule ID>

FOR EXAMPLE:
2018-03-25 00:00 #### 2018-04-24 23:59 #### "PFW Policy" #### 55
2018-03-25 00:00 #### 2018-04-24 23:59 #### "PFW Policy" #### 88
2018-03-30 00:00 #### 2018-04-31 23:59 #### "PFW Policy" #### 100

NOTE: IT IS ASSUMED THAT YOU HAVE ALREADY CREATED THE POLICIES AND RULES IN FMC BEFORE ADDING THEM HERE.

-----------

THE RULE NAME, POLICY UUID AND RULE UUID WILL BE AUTO-POPULATED WHEN YOU EXECUTE THE TBA.PY SCRIPT. THEN THE SAME FILE WILL LOOK LIKE:
<ENABLE Date in YYYY-MM-DD HH:MM> #### <DISABLE Date in YYYY-MM-DD HH:MM> #### "<Policy Name>" #### <Rule ID> #### "<Rule Name - auto-populated>" #### <Policy UUID - auto-populated> #### <Rule UUID - auto-populated>

FOR EXAMPLE:
2018-03-25 00:00 #### 2018-04-24 23:59 #### "PFW Policy" #### 55 #### "Debug Rule - Ref CHG10861" #### 0050568E-5C8B-0ed3-0000-146028897141 #### 0050568E-5C8B-0ed3-0000-000268437508

-----------

FOR ADDING ANY NEW RULE, JUST FOLLOW THE SIMPLE SYNTAX GIVEN IN THE BEGINNING.
FOR REMOVING ANY NEW RULE, JUST DELETE THE WHOLE RULE LINE.
FOR MAKING ANY EDITS TO AN EXISTING RULE, SIMPLY UPDATE THE START TIME / END TIME. DO NOT CHANGE ANYTHING ELSE.
ADD YOUR CONTENT BELOW THIS HASHED LINE ONLY

###########################################################################################

2018-04-01 00:00 #### 2018-04-10 23:59 #### "DMZ FW Policy" #### 100
2018-04-01 00:00 #### 2018-04-10 23:59 #### "DMZ FW Policy" #### 101
2018-04-01 00:00 #### 2018-04-10 23:59 #### "DMZ FW Policy" #### 102
2018-04-02 00:00 #### 2018-04-11 23:59 #### "Data Center FW Policy" #### 200
2018-04-03 09:00 #### 2018-04-12 17:59 #### "Data Center FW Policy" #### 201
2018-04-03 09:00 #### 2018-04-12 17:59 #### "Data Center FW Policy" #### 202

 

When you run the script, it pulls up the UUIDs of the above Access Policies and Rules. All the updates in FMC are done using these UUIDs. UUID is an automatically generated unique identifier of any entity like Access Policy, Access Rule, Network Object and more inside the FMC.

Using UUIDs ensure that a different Rule is not accidentally enabled or disabled by this script in case if the Rule ID changes anytime due to any Rule Addition / Deletion done by the user directly in FMC.

 

Where can I track the activities of this script:

The script documents all its Activities and Errors, if any, in a log file named - tba-audit.log file. This log file can be found in the same directory where the script is saved. Keep the script and the rules file in the same directory.

 

How to use this script:

  1. Install the pre-requisites as mentioned in the above section.
  2. Save the Script (tba.py) and the Rules File (tba-db.txt) in the directory of your choice.
  3. Modify the script and add the variables FMC hostname, username, password, etc as mentioned in the above section
  4. Update the Rules File and add the details in the syntax as mentioned in the above section
  5. Execute the script once manually to test that it is working fine
  6. Add the script as a CronJob in case of Linux / Mac or Scheduled Task in case of Windows. The script should be invoked EVERY 1 MINUTE. All the activities of the script can be viewed in the tba-audit.log file. The user may receive email notifications if email details are configured in the script.
  7. The Rules File (tba-db.txt) can be updated at any point of time. Any entries due to syntax error or due to the deletion of the Rule from FMC will be automatically commented out in the Rules File and reported in the Log file.

 

How to add a CronJob for this script:

The CronJob for this script can be added just like you do for any other script or task. No special privileges are required for this. Even a non-admin user can add a CronJob.

 

Here is an article for reference - How do I set up a Cron job? - Ask Ubuntu

 

Here is the line that he would need to add for this script:

* * * * * /usr/bin/python3 /absolute_full_path/tba.py > /dev/null

 

Where can I get Support / Can I make any changes to this script:

This script is available for use to everyone in 'AS-IS' basis WITHOUT any form of support on the script itself. The user is free to make any modifications to the script code as required. It is strongly advised to test the script in a lab environment before using it in production. Also it is strongly advised to take periodic configuration backups before making any changes on the FMC through external medium like API calls. That will make it easier to restore in case if any undesired change happens.

 

I would like to explicitly call out and thank plakatos and neipatel for their useful inputs and for their attempts to create the initial versions of this. Also I would like to thank @hevyapan for providing an update with support added to deploy the same on Firewalls configured as High Availability (HA) pairs.

 

Hope the script is useful.

 

PS: 14/Dec/2018 - Updated the script with support added to deploy the same on Firewalls configured as High Availability (HA) pairs.

19 Comments
matteodapozzo
Level 5
Level 5

Thank you Anand! I will try it.

Awesome work.

Matteo

adeka
Cisco Employee
Cisco Employee

Thanks Anand, this would help me and all sales community immensely till this feature becomes natively available with FTD. Appreciate your contribution!

Nautilian
Level 1
Level 1

Thank you very much for this.

I have tried to deploy this on 6.2.3 and keep getting the following error:

[2018-05-07 14:12:12] - INFO - Rule Status Modification Scheduled. So updating this Rule

[2018-05-07 14:12:12] - ERROR - ERROR occurred in PUT -->{"error":{"category":"OTHER","messages":[{"description":"Unprocessable Entity"}],"severity":"ERROR"}}

[2018-05-07 14:12:12] - INFO - ~~~~~~~~~~~~~~~~~~~~

I am assuming there is something wrong in this section of the code but for the life of me cannot figure it out:

def modifyRuleStatus(self, policy_id, rule_id, rule_data, rule_status):

  """Updates a rule status - either enable or disable."""

  path = "/api/fmc_config/v1/domain/" + self.uuid + "/policy/accesspolicies/" + policy_id + "/accessrules/" + rule_id

  server = "https://"+self.host

  url = server + path

  rule_data.pop('metadata', None)

  rule_data.pop('links', None)

  rule_data.pop('commentHistoryList', None)

  if rule_status == 'disable':

  rule_data['enabled']=False

  else:

  rule_status = 'enable'

  rule_data['enabled']=True

  r = None

  try:

  self._req_counter_check()

  r = requests.put(url, data=json.dumps(rule_data),headers=self.headers, verify=False)

  status_code = r.status_code

  resp = r.text

  json_response = json.loads(resp)

  if status_code == 200:

  if json_response['id'] == rule_id:

  logger.info("Rule Update in FMC Completed Successfully for the Rule ID - " + rule_id + " in the Policy ID - " + policy_id)

  return ("Rule Update in FMC Completed Successfully")

  else:

  logger.error("ERROR occurred in PUT -->" + resp)

  return ("ERROR: occurred in PUT -->" + resp)

  elif status_code == 404:

  logger.error("Cannot find the Given Domain ID or Policy ID or Rule ID. Hence no operation performed.")

  return ("ERROR: Cannot find the Given Domain ID or Policy ID or Rule ID. Hence no operation performed.")

  else:

  logger.error("ERROR occurred in PUT -->" + resp)

  return ("ERROR occurred in PUT -->" + resp)

  except Exception as err:

  logger.error("ERROR in connection", exc_info=True)

  return ("ERROR in connection" + str(err))

  finally:

  if r:

  r.close()

If you could help me out this would rock!

Kind Regards,

esekizin
Cisco Employee
Cisco Employee

Hi, I am using 6.2.3.1 patched version, anyone have tested yet ?  When I try to execute it gives me to the messages as below, the point is my FMC rule status does not change.

~~~~~~~~~~~~~~~~~~~~

PROCESSING THE LINE -

2018-05-09 04:10 #### 2018-05-09 04:30 #### "Base_access_control" #### 1

NEED TO CONNECT TO FMC, SO ESTABLISHING CONNECTION

GETTING THE LIST ALL THE ACCESS POLICIES FROM FMC

Fetching all rules for this policy - 000C293B-3863-0ed3-0000-008589934615

Found the Rule UUID and Name: 000C293B-3863-0ed3-0000-000268436498  TEST_API

~~~~~~~~~~~~~~~~~~~~

No Policy Update scheduled to at this time

As I understood script good works and fine the rule name, but I am pretty sure I use automatic deploy feature, and the time that I choose is in future. default my rule status is disable, in tba-db.txt already set the future time, after couple minutes I choose the disable time.

For example if the current time is 4:15 I configure my policy as below.

2018-05-09 04:22 #### 2018-05-25 04:30 #### "Base_access_control" #### 1

What could be the problem, thank you for your support.

Anand Kanani
Cisco Employee
Cisco Employee

Hi Eser, the script is working fine in your case, there is no problem.

In your example, you are running it at 4:15 and you have configured the ACL to be enabled / disabled at 4:22 / 4:30 respectively; so at 4:15 the script is not supposed to make any changes to the policy. Hence you see "No Policy Update scheduled to at this time" message.

You are supposed to run this script as a cron job / scheduled task; to be executed every minute. Its documented in the README section.

Also note that the script pulls the UUID of the policies and the rules, in case if it does not find them. This usually happens when you execute it for the first time.

Anand Kanani
Cisco Employee
Cisco Employee

The error message is not giving any details. This is all it says - {"error":{"category":"OTHER","messages":[{"description":"Unprocessable Entity"}],"severity":"ERROR"}}

This needs some debugging. Not seen this before.

Try running it again.

esekizin
Cisco Employee
Cisco Employee

Hi Anand, Eleftherios is right, the script gives the error message, If you haven't tested before I will be appreciate If you can debug and help us.

Regards,

esekizin
Cisco Employee
Cisco Employee

In my audit logs the latest message shows as : API, PUT https://10.12.12.12/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/policy/accesspolicies/000C293B-3863-0ed3-0000-008589934615/accessrules/000C293B-3863-0ed3-0000-000268436498 Unprocessable Entity (422) - The server understands the content type of the request entity and the syntax of the request entity is correct but was unable to process the contained instructions

tkiel
Level 1
Level 1

great job, unfortunately not working when running HA in version 6.2.3.1.

but with hardcoding the device-list to deploy, it works.

excellent script

Hi,

I have the following rule on FMC.

7   ACL-BDR-HOST insize-zone dmz-zone 10.1.1.1 20.1.1.1 any any allow

And we edit file “tba-db.txt” as the following.

2018-06-21 12:35 #### 2018-06-21 12:40 #### "ACL-BDR-HOST" #### 7

When we run the script “tba.py” manually, we see the following error.

~~~~~~~~~~~~~~~~~~~~

PROCESSING THE LINE -

2018-06-21 12:35 #### 2018-06-21 12:40 #### "ACL-BDR-HOST" #### 7

NEED TO CONNECT TO FMC, SO ESTABLISHING CONNECTION

GETTING THE LIST ALL THE ACCESS POLICIES FROM FMC

ERROR: Cannot find the access policy for the given line. Commenting it out from the given rules file and Moving to the next line

~~~~~~~~~~~~~~~~~~~~

could you please help to advise how to fix this issue?

Regards,

Thanks, Anand for shared, worked very well for me. 

 

itsupport
Level 1
Level 1

I was able to get this running in 6.2.3.X, however not in an HA environment. Can anyone advise on modifications for HA ?

Anand Kanani
Cisco Employee
Cisco Employee

Hi kann.vannath@ababank.com

The error message clearly states the issue. It is not able to find the policy/rule - "ACL-BDR-HOST" #### 7 so it commented this line.

Either the policy name or rule or both does not exist / mistyped. Correct that, uncomment the line and run the script again.

Thanks!

Anand

itsupport
Level 1
Level 1

This is the error received in an HA scenario:

[2018-11-19 17:22:14] - INFO - DEPLOYING THE UPDATED POLICIES TO THE ASSOCIATED DEVICES:-
[2018-11-19 17:22:22] - INFO - Received details about all deployable devices
[2018-11-19 17:22:32] - ERROR - ERROR occurred in POST -->{"error":{"category":"FRAMEWORK","messages":[{"description":"The device list in Request does not match the deployable devices"}],"severity":"ERROR"}}
[2018-11-19 17:22:32] - INFO - Successfully sent email

I did see tkiel's comment above about hard coding the device-list to deploy, however it is unclear based on the comment where those changes were made. 

Anand Kanani
Cisco Employee
Cisco Employee

Updated the script with support added to deploy the same on Firewalls configured as High Availability (HA) pairs.

Getting Started

Find answers to your questions by entering keywords or phrases in the Search bar above. New here? Use these resources to familiarize yourself with the community: