7 months, 1 week

Network Security Using The Firepower APIs




 

 

Network Security protects your network and data from breaches, intrusions and other threats, which involves access control, virus and antivirus software, application security, network analytics, types of network-related security (endpoint, web, wireless), firewalls, VPN encryption and more.
In computing, a firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules. A firewall typically establishes a barrier between a trusted network and an untrusted network, such as the Internet.
We are going to focus on the automation abilities of Cisco's Firepower Management Center (FMC) by using its Representational State Transfer (REST) 
application programming interface (API). Using automation together with FMC allows us to constantly check our enacted access policies or automatically update them.
Follow these steps to authenticate against the FMC REST API: 
1. Import the required requests library as well as the json and sys modules from the standard library:
import requests
import json
import sys
from requests.auth import HTTPBasicAuth
2. Next, specify the base URL as well as our login information:
base_url = "https://fmcrestapisandbox.cisco.com"
username = "<Insert username here>"
password = "<Insert password>"
3. Next, we create our authentication function:
def get_authenticated_session(user, password, base_url):
4. Within this authentication function, specify the authentication URL and authentication details:
 auth_url = f"{base_url}/api/fmc_platform/v1/auth/generatetoken"
 auth = HTTPBasicAuth(user, password)
5. Send a POST request with an empty body to the auth URL. Depending on your 
FMC installation, you'll have a self-signed certificate. If that is the case, set the 
verify property of the POST request to False. This will prevent requests from 
verifying the Secure Sockets Layer (SSL) certificate:
 resp = requests.post(auth_url, auth=auth, verify=False)
6. Next, we create a new session object and, if the request to the authentication URL 
was successful, set the authentication header of our session based on the token 
returned from the request to the authentication URL:
 s = requests.Session()
 if resp.ok:
 s.headers.update({
 'X-auth-access-token': resp.headers.get('Xauth-access-token')
 }) 
7. Next, we disable SSL verification for our session, print out a message that our authentication was successful, and parse the domains. 
 s.verify = False
 print("Authenticated successfully!")
 domains = json.loads(resp.headers.get('DOMAINS'))
8. To finish off, we return the session as well as our list of domains:
   return s, domains
else:
  print(f"Failed to authenticate. Response code:{resp.status_code}")
  sys.exit(-1)
9. With our authentication function finished, we can use it to retrieve an authenticated session as well as a list of domains:
sess, domains = get_authenticated_session(username, password, base_url)
10. And then, for each of our domains, we can print out the name and the identifier (ID):
for d in domains:
 print(f"{d['name']}: {d['uuid']}")

FMC uses an X-auth-access-token header key instead of the more common Authorization key.

Retrieving access policies
Follow these steps to retrieve your access policies from the FMC REST API:
1. Import the required requests library as well as the json and sys modules from the standard library:
import requests
import json
import sys
from requests.auth import HTTPBasicAuth
2. Specify the required variables such as your username, password, and domain ID:
base_url = "https://fmcrestapisandbox.cisco.com"
username = "<Insert username here>"
password = "<Insert password here>"
domain = "<Insert domain id here>"
3. Define an authentication function and use this function to obtain an authenticated session based on your username and password combination.
def get_authenticated_session(user, password, base_url):
  auth_url = f"{base_url}/api/fmc_platform/v1/auth/generatetoken"
  auth = HTTPBasicAuth(user, password)
  resp = requests.post(auth_url, auth=auth, verify=False)
  s = requests.Session()
  if resp.ok:
     s.headers.update({
    'X-auth-access-token': resp.headers.get('Xauth-access-token')
  })
     s.verify = False
     print("Authenticated succesfully!")
     domains = json.loads(resp.headers.get('DOMAINS'))
     return s, domains
  else:
     print(f"Failed to authenticate. Response code: {resp.status_code}")
     sys.exit(-1)
     sess, domains = get_authenticated_session(username,password, base_url)
4. Define a URL that we want to request our policies from, as well as an empty list of items.
 url = f"{base_url}/api/fmc_config/v1/domain/{domain}/policy/accesspolicies"
 items = []
 resp = sess.get(url)
5. If the request was successful:
if resp.ok:
   data = resp.json()
   for i in data['items']:
      items.append(i)
6. Next, we need to take care of all the additional pages.
next_links = []
 if "next" in data['paging']:
     if isinstance(data['paging']['next'], list):
         next_links = data['paging']['next']
     else:
         next_links.append(data['paging']['next'])
7. With the list of remaining pages retrieved, we can then iterate over this list and send a GET request for each of these links:
 for link in next_links:
    print(f"Requesting url '{link}'")
    r = sess.get(link)
8. If this request was successful, we add all the access policies contained within the items list. 
if r.ok:
   for i in r.json()['items']:
      items.append(i)
else:
   print(f"Failed to request url '{link}'.Status code: {r.status_code}")
9. Finally, we need to handle the case that our initial request failed.
else:
    print(f"Failed to request url '{url}'. Status code: {resp.status_code}")
for i in items:
    print(f"{i['name']}: {i['id']}")

Changing access policies
Follow these steps to change one of your access policies using the FMC REST API: 
1. Import the required requests library as well as the json and sys modules from 
the standard library:
import requests
import json
import sys
from requests.auth import HTTPBasicAuth
2. Specify the required variables such as your username, password, domain ID, and the 
ID of the policy you want to change:
base_url = "https://fmcrestapisandbox.cisco.com"
username = "<Insert username here>"
password = "<Insert password here>"
domain = "<Insert domain id here>"
policy_id = "<Insert your policy id here>"
3. Define an authentication function and use this function to obtain an authenticated session based on your username and password combination.
def get_authenticated_session(user, password, base_url):
  auth_url = f"{base_url}/api/fmc_platform/v1/auth/generatetoken"
  auth = HTTPBasicAuth(user, password)
  resp = requests.post(auth_url, auth=auth, verify=False)
  s = requests.Session()
  if resp.ok:
     s.headers.update({
    'X-auth-access-token': resp.headers.get('Xauth-access-token')
    })
     s.verify = False
     print("Authenticated succesfully!")
     domains = json.loads(resp.headers.get('DOMAINS'))
     return s, domains
  else:
     print(f"Failed to authenticate. Response code: {resp.status_code}")
     sys.exit(-1)
     sess, domains = get_authenticated_session(username, password, base_url)
4. Specify the URL of the policy we want to change and request the initial data:
 url = f"{base_url}/api/fmc_config/v1/domain/{domain}/
 policy/accesspolicies/{policy_id}"
 resp = sess.get(url)
5. If the request was successful.
if resp.ok:
 data = resp.json()
6. Next, delete some of the API-specific keys in your data. This step is required so that we can update the resource using the information obtained from the GET request without running into API errors.
7. With the list of remaining pages retrieved, we can then iterate over this list and send a GET request for each of these links:
if 'urls' in data.keys():
  del data['urls']
if 'metadata' in data.keys():
  del data['metadata']
 
if 'links' in data.keys():
  del data['links']
8. We can then change the property we want to change—in this case, our policy 
name—and post the data back to the API:
 data['name'] = 'Test-API'
 res = sess.put(url, json=data)
 print(res.status_code)
 print(res.json())


 


Responses(0)







Related