### Install Python Libraries Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/client-samples/Deployments/NetworkTunnels/README.md Install necessary Python libraries using pip. Ensure you have Python 3.x.x installed. ```shell pip install -r requirements.txt ``` -------------------------------- ### Start Docker ELK Stack Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Reports/S3-ELK-Example/README.md Run this command from the root folder of your extracted example stack to start the ELK services in detached mode. Use 'docker-compose up' without '-d' to keep the logs visible in your terminal. ```bash docker-compose up -d ``` -------------------------------- ### Install Cloudlock Libraries (Windows) Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cloudlock/Sample Scripts/README.md Install the required Python libraries (requests, configparser, python-dateutil) for the sample script on Windows using pip. Ensure you are using the correct Python executable path. ```batch c:\python27\scripts\Pip.exe install requests c:\python27\scripts\Pip.exe install configparser c:\python27\scripts\Pip.exe install python-dateutil ``` -------------------------------- ### Example Log File Name Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Deployments/NetworkTunnel/create-tunnel/README.md An example of a generated log file name, following the specified format. ```ini tunnel_log_2022_05_09_12_43.csv ``` -------------------------------- ### Install OAuth Python Libraries Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/Auth/client-samples/python/README.md Installs the necessary Python packages for OAuth 2.0 client credentials flow. ```shell pip install oauthlib pip install requests_oauthlib ``` -------------------------------- ### Extract Example Stack Archive Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Reports/S3-ELK-Example/README.md This command is used to extract the example ELK stack archive. Navigate to the directory where you want to set up the stack before running this command. ```bash tar -xzvf example_stack.tar.gz ``` -------------------------------- ### Start ELK Stack Docker Containers Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Reports/Reporting-and-Investigate-APIs-ELK/README.md Execute this command to start the ELK stack services using Docker Compose. Ensure you have Docker installed and configured. ```shell sudo -E docker-compose up ``` -------------------------------- ### Migration Script Usage Example Source: https://context7.com/ciscodevnet/cloud-security/llms.txt Demonstrates how to use the API class and functions to export application lists from a source organization and import them into a target organization. Requires environment variables for API keys and secrets. ```python # Usage example token_url = 'https://api.sse.cisco.com/auth/v2/token' source_api = API(token_url, os.environ['SOURCE_API_KEY'], os.environ['SOURCE_API_SECRET']) target_api = API(token_url, os.environ['TARGET_API_KEY'], os.environ['TARGET_API_SECRET']) # Export from source get_application_lists(source_api, "application_lists.json") # Import to target create_application_list(target_api, "application_lists.json") ``` -------------------------------- ### Sample Output from Go Client Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/golang/README.md Example output from the Go client application, showing response status, time, request string, and response body. The first request may have a higher response time due to token acquisition. ```text Code: 200: RspTime: 746(ms): https://api.umbrella.com/reports/v2/summary?from=-5days&to=now {"meta":{},"data":{"applications":0,"domains":0,"requestsblocked":0,"filetypes":0,"requests":0,"policycategories":0,"requestsallowed":0,"categories":0,"identitytypes":0,"applicationsblocked":0,"files":0,"identities":0,"policyrequests":0,"applicationsallowed":0}} Code: 200: RspTime: 286(ms): https://api.umbrella.com/reports/v2/summary?from=-5days&to=now {"meta":{},"data":{"applications":0,"domains":0,"requestsblocked":0,"filetypes":0,"requests":0,"policycategories":0,"requestsallowed":0,"categories":0,"identitytypes":0,"applicationsblocked":0,"files":0,"identities":0,"policyrequests":0,"applicationsallowed":0}} Code: 200: RspTime: 204(ms): https://api.umbrella.com/reports/v2/summary?from=-5days&to=now {"meta":{},"data":{"applications":0,"domains":0,"requestsblocked":0,"filetypes":0,"requests":0,"policycategories":0,"requestsallowed":0,"categories":0,"identitytypes":0,"applicationsblocked":0,"files":0,"identities":0,"policyrequests":0,"applicationsallowed":0}} ``` -------------------------------- ### Install Guzzle and OAuth2 Subscriber with Composer Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/php/README.md Installs the necessary PHP libraries, Guzzle and kamermans/guzzle-oauth2-subscriber, using Composer. This command should be run in the project directory. ```shell php composer.phar install ``` -------------------------------- ### Sample API Response Output Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/Auth/client-samples/python/README.md Example output from the Secure Access API, showing the obtained access token and subsequent data responses. ```json Token: {'token_type': 'bearer', 'access_token': 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjIwMTktMDEtMDEiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE2Mjk5Mzc3MTUsImlhdCI6MTYyOTkzNDExNSwiaXNzIjoidW1icmVsbGEtYXV0aHovYXV0aHN2YyIsIm5iZiI6MTYyOTkzNDExNSwic3ViIjoib3JnLzU3MjE4NzgvdXNlci8xMTgxODU2NCIsInNjb3BlIjoicm9sZTpyb290LWFkbWluIiwiYXV0aHpfZG9uZSI6ZmFsc2V9.mh3OoJV4Wzjv04SSkiDi6rR65Zrd9aigV0K5ciPvF5a2aiy0tKdlLpT_ty0NBxh5ojyt9iO5588Ntu5GzzWvDbGgtdrkus1pMNU92IUioN4cF2Y4yCLooshFfDjiwccuJd8afmD1o6miZ4Tzqg906ZGq5KEwfclzA9lPwmkalpGkQDCYFRCtQWXWIKVHPNhgpZjf1lAgUwDngSvwJHC_KRb1MICHgiM_SolhwIz66ISkdIm_aRKeTK5EAWW0RCBEQx0E2kY1AHVyahrKDZMPV-tQEPxAEaiMhQKqHtJUbITTYt7LQzQZ6aOrOaS-Stip6_lLgcGIPXOUmGFEjg1Vvg', 'expires_in': 3600, 'expires_at': 1629937714.8636105} {'meta': {}, 'data': {'applications': 0, 'domains': 0, 'requestsblocked': 0, 'filetypes': 0, 'requests': 0, 'policycategories': 0, 'requestsallowed': 0, 'categories': 0, 'identitytypes': 0, 'applicationsblocked': 0, 'files': 0, 'identities': 0, 'policyrequests': 0, 'applicationsallowed': 0}} {'meta': {}, 'data': {'applications': 0, 'domains': 0, 'requestsblocked': 0, 'filetypes': 0, 'requests': 0, 'policycategories': 0, 'requestsallowed': 0, 'categories': 0, 'identitytypes': 0, 'applicationsblocked': 0, 'files': 0, 'identities': 0, 'policyrequests': 0, 'applicationsallowed': 0}} ``` -------------------------------- ### Cloudlock API - cURL Example Source: https://context7.com/ciscodevnet/cloud-security/llms.txt This section provides a basic cURL command for testing Cloudlock API connectivity and retrieving incidents. It demonstrates how to authenticate and make a GET request to the incidents endpoint. ```APIDOC ## Cloudlock API - cURL Example ### Description This example shows how to use `curl` to interact with the Cloudlock API, specifically for retrieving incident data. It includes authentication headers and the endpoint for fetching incidents. ### Method GET ### Endpoint `https://api.cloudlock.com/api/v2/incidents` ### Parameters #### Query Parameters - **count_total** (boolean) - Optional. Set to `false` to exclude total count. - **limit** (integer) - Optional. Maximum number of incidents to return. - **order** (string) - Optional. Field to order the results by (e.g., `created_at`). ### Request Example (cURL) ```bash curl -k -H "Authorization: Bearer YourAPITokenHere" \ 'https://api.cloudlock.com/api/v2/incidents?limit=10&order=created_at' ``` ### Response Example (Success - 200 OK) ```json { "items": [ { "id": "12345", "incident_status": "new", "severity": "WARNING", "created_at": "2024-01-15T10:30:00Z", "entity": { "name": "document.pdf", "owner_email": "user@company.com" }, "policy": { "name": "PCI-DSS Detection" } } ] } ``` ``` -------------------------------- ### Handle Missing Module Error Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/Policies/application-lists/application-lists-migrate/README.md This error indicates that a required Python library, such as 'requests', has not been installed. Install the necessary libraries using `pip install -r requirements.txt`. ```python ModuleNotFoundError: No module named 'requests' ``` -------------------------------- ### Import Go Libraries for OAuth2.0 Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/golang/README.md Imports the required Go libraries for handling OAuth 2.0 client credentials flow. Ensure you have these packages installed. ```go import ( "net/http" "golang.org/x/net/context" "golang.org/x/oauth2/clientcredentials" ) ``` -------------------------------- ### Duplicate Network Tunnel Name Error Example Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Deployments/NetworkTunnel/create-tunnel/README.md This example shows the error message and log output when attempting to create a tunnel with a name that already exists. ```shell Error creating tunnel04test, see log for details [createTunnel()] response = {"error":"Tunnel Name must be unique."} [write_tunnel_attributes()] line = tunnel04test,Meraki MX,,ABCDEF9876543210fedcba,,,Tunnel Name must be unique., ``` -------------------------------- ### Example NSDs Recheck Script Output Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/SOCTools/NSD_Recheck/README.md This is an example of the output you can expect when running the nsd_recheck.py script. It shows the process of checking domains, removing blocked ones, and identifying expired NSDs. ```command line Starting Newly Seen Domains Re-Check Script. Enter your destination list ID for NSD recheck: 3174032 Destination list ID: 3174032 Checking 91 Domains Removing 0 domains that are blocked. Removing 30 expired NSDs. Result : {"code": 200, "text": "OK"} Domains remaining for next run : 61 Done. ``` -------------------------------- ### Run Tunnel Monitor Script Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/client-samples/Deployments/NetworkTunnels/README.md Execute the Python script to start monitoring the network tunnel states. Ensure all prerequisites and environment variables are set. ```shell python3 tunnel_monitor_sse.py ``` -------------------------------- ### Initialize OAuth2RestTemplate with Client Credentials Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/java/README.md Configure and initialize an OAuth2RestTemplate using client credentials (API key and secret) for authentication. This setup automatically handles token lifecycle management, including creation, reuse, and refresh. ```java . . . // Create the OAuth2 client credential resource details. ClientCredentialsResourceDetails clientCredConfig = new ClientCredentialsResourceDetails(); clientCredConfig.setClientId(); clientCredConfig.setClientSecret(); clientCredConfig.setAccessTokenUri(https://api.umbrella.com/auth/v2/token); // Create an OAuth2 REST template with OAuth 2.0 client credentials access-token-provider OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(clientCredConfig, new DefaultOAuth2ClientContext()); restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); restTemplate.setAccessTokenProvider(new ClientCredentialsAccessTokenProvider()); . . . ``` -------------------------------- ### Get Access Token using Python Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/Auth/client-samples/python/README.md Retrieves an access token by making a POST request to the token URL using client credentials. Handles potential exceptions during the request. ```python def getAccessToken(self): try: payload={} rsp = requests.post(self.token_url, data=payload, auth=(self.client_id, self.client_secret)) rsp.raise_for_status() except Exception as e: print(e) return None else: return rsp.json()['access_token'] ``` -------------------------------- ### Troubleshooting API Response Example Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Deployments/NetworkTunnel/monitor-tunnel/README.md Illustrates a common troubleshooting scenario where the Umbrella Network Tunnels API returns a 404 status, indicating that tunnel states were not found for the organization. This output also shows the subsequent error logging and email alert generation. ```shell Checking Tunnel Status at 2022-05-09 11:33:33.979461 ============================================================ GET /tunnelsState Response: Status = 404, Message Content = {"error":"Tunnels states not found for organization"} ERROR: Response Status is not 200/OK Update Tunnel States Result: {"update status": "Script fail", "reason": "ERROR: API Request fail, status = 404"} Error detected Email alert enabled, send email alert. Try connection to mail server. Error connecting to email server please run connect() first. Tunnel Status Check completed. Wait 120 seconds before next status check. ``` -------------------------------- ### Create HTTP Request to Umbrella Reporting API Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/golang/README.md Uses the initialized HTTP client to make a GET request to the Umbrella Reporting API. The client automatically includes the Bearer token for authentication. ```go res, err := httpClient.Get("https://api.umbrella.com/reports/v2/summary?from=-5days&to=now") if err != nil { fmt.Printf("Error calling API, %s\n", err.Error()) return } ``` -------------------------------- ### Navigate and Unzip Sample Data Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Reports/Reporting-and-Investigate-APIs-ELK/README.md Change directory into the downloaded sample and unzip the provided archive. ```shell cd Reporting\ and\ Investigate\ APIs\ in\ ELK/ unzip Reporting_Investigate_ELK.zip cd Reporting_Investigate_ELK ``` -------------------------------- ### Download Sample ELK Configuration Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Reports/Reporting-and-Investigate-APIs-ELK/README.md Use this command to export the sample ELK stack configuration files from GitHub. ```shell svn export https://github.com/CiscoDevNet/cloud-security/trunk/Umbrella/Samples/Reports/Reporting-and-Investigate-APIs-ELK ``` -------------------------------- ### Fetch Go Packages Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/golang/README.md Fetches the necessary Go packages for the client application using go mod init and go mod tidy. ```shell go mod init go mod tidy ``` -------------------------------- ### Sample Output from oauthlib Client Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/python/README.md Sample output demonstrating the token acquisition, reuse, and refresh process, along with API response data. ```text Token: {'token_type': 'bearer', 'access_token': 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjIwMTktMDEtMDEiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE2Mjk5Mzc3MTUsImlhdCI6MTYyOTkzNDExNSwiaXNzIjoidW1icmVsbGEtYXV0aHovYXV0aHN2YyIsIm5iZiI6MTYyOTkzNDExNSwic3ViIjoib3JnLzU3MjE4NzgvdXNlci8xMTgxODU2NCIsInNjb3BlIjoicm9sZTpyb290LWFkbWluIiwiYXV0aHpfZG9uZSI6ZmFsc2V9.mh3OoJV4Wzjv04SSkiDi6rR65Zrd9aigV0K5ciPvF5a2aiy0tKdlLpT_ty0NBxh5ojyt9iO5588Ntu5GzzWvDbGgtdrkus1pMNU92IUioN4cF2Y4yCLooshFfDjiwccuJd8afmD1o6miZ4Tzqg906ZGq5KEwfclzA9lPwmkalpGkQDCYFRCtQWXWIKVHPNhgpZjf1lAgUwDngSvwJHC_KRb1MICHgiM_SolhwIz66ISkdIm_aRKeTK5EAWW0RCBEQx0E2kY1AHVyahrKDZMPV-tQEPxAEaiMhQKqHtJUbITTYt7LQzQZ6aOrOaS-Stip6_lLgcGIPXOUmGFEjg1Vvg' , 'expires_in': 3600, 'expires_at': 1629937714.8636105} {'meta': {}, 'data': {'applications': 0, 'domains': 0, 'requestsblocked': 0, 'filetypes': 0, 'requests': 0, 'policycategories': 0, 'requestsallowed': 0, 'categories': 0, 'identitytypes': 0, 'applicationsblocked': 0, 'files': 0, 'identities': 0, 'policyrequests': 0, 'applicationsallowed': 0}} {'meta': {}, 'data': {'applications': 0, 'domains': 0, 'requestsblocked': 0, 'filetypes': 0, 'requests': 0, 'policycategories': 0, 'requestsallowed': 0, 'categories': 0, 'identitytypes': 0, 'applicationsblocked': 0, 'files': 0, 'identities': 0, 'policyrequests': 0, 'applicationsallowed': 0}} ``` -------------------------------- ### Run the Go Client Application Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/golang/README.md Executes the Go client application. Ensure environment variables are set and packages are fetched before running. ```shell go run main.go ``` -------------------------------- ### Sample Output of `oauthlib` Client Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/Auth/client-samples/python/README.md Displays sample output from the `oauthlib` client, showing token acquisition, reuse, and refresh. ```json Token: {'token_type': 'bearer', 'access_token': 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjIwMTktMDEtMDEiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE2Mjk5Mzc3MTUsImlhdCI6MTYyOTkzNDExNSwiaXNzIjoidW1icmVsbGEtYXV0aHovYXV0aHN2YyIsIm5iZiI6MTYyOTkzNDExNSwic3ViIjoib3JnLzU3MjE4NzgvdXNlci8xMTgxODU2NCIsInNjb3BlIjoicm9sZTpyb290LWFkbWluIiwiYXV0aHpfZG9uZSI6ZmFsc2V9.mh3OoJV4Wzjv04SSkiDi6rR65Zrd9aigV0K5ciPvF5a2aiy0tKdlLpT_ty0NBxh5ojyt9iO5588Ntu5GzzWvDbGgtdrkus1pMNU92IUioN4cF2Y4yCLooshFfDjiwccuJd8afmD1o6miZ4Tzqg906ZGq5KEwfclzA9lPwmkalpGkQDCYFRCtQWXWIKVHPNhgpZjf1lAgUwDngSvwJHC_KRb1MICHgiM_SolhwIz66ISkdIm_aRKeTK5EAWW0RCBEQx0E2kY1AHVyahrKDZMPV-tQEPxAEaiMhQKqHtJUbITTYt7LQzQZ6aOrOaS-Stip6_lLgcGIPXOUmGFEjg1Vvg' 'expires_in': 3600, 'expires_at': 1629937714.8636105} {'meta': {}, 'data': {'applications': 0, 'domains': 0, 'requestsblocked': 0, 'filetypes': 0, 'requests': 0, 'policycategories': 0, 'requestsallowed': 0, 'categories': 0, 'identitytypes': 0, 'applicationsblocked': 0, 'files': 0, 'identities': 0, 'policyrequests': 0, 'applicationsallowed': 0}} {'meta': {}, 'data': {'applications': 0, 'domains': 0, 'requestsblocked': 0, 'filetypes': 0, 'requests': 0, 'policycategories': 0, 'requestsallowed': 0, 'categories': 0, 'identitytypes': 0, 'applicationsblocked': 0, 'files': 0, 'identities': 0, 'policyrequests': 0, 'applicationsallowed': 0}} ``` -------------------------------- ### Cloudlock API - Incident Management (Python Client) Source: https://context7.com/ciscodevnet/cloud-security/llms.txt This section details the Python client for the Cloudlock Enterprise API, enabling retrieval and management of DLP incidents. It includes methods for getting incidents, getting a specific incident by ID, and updating an incident's status or severity. ```APIDOC ## Cloudlock API - Incident Management (Python Client) ### Description This Python client allows you to interact with the Cloudlock Enterprise API to manage Data Loss Prevention (DLP) incidents. It supports retrieving lists of incidents, fetching details of a specific incident, and updating incident properties like status and severity. ### Methods #### `get_incidents(**payload)` Retrieves a list of incidents with optional filtering parameters. - **Parameters**: - `payload` (dict) - Optional. Key-value pairs for filtering incidents (e.g., `limit`, `order`). - **Returns**: - `list` - A list of incident dictionaries. #### `get_incident(incident_id, **payload)` Retrieves a specific incident by its unique identifier. - **Parameters**: - `incident_id` (str) - The unique ID of the incident to retrieve. - `payload` (dict) - Optional. Additional parameters for the request. - **Returns**: - `dict` - The incident details. #### `update_incident(incident_id, status=None, severity=None, customer_key=None)` Updates an existing incident's status, severity, or customer key. - **Parameters**: - `incident_id` (str) - The unique ID of the incident to update. - `status` (str) - Optional. The new status for the incident (e.g., 'resolved', 'acknowledged'). - `severity` (str) - Optional. The new severity for the incident (e.g., 'INFO', 'WARNING', 'CRITICAL'). - `customer_key` (str) - Optional. The customer key to associate with the incident. ### Request Example (Python) ```python import requests from requests.packages.urllib3.util import Retry class CLAPIClient(object): """CloudLock API Client""" BASE_URL = 'https://api.cloudlock.com/api/v2' def __init__(self, token, base_url=BASE_URL): self.token = token self.base_url = base_url self.session = requests.session() retries = Retry(total=100, status_forcelist=(429, 500, 502, 504), backoff_factor=0.1) self.session.mount(self.base_url, requests.adapters.HTTPAdapter(max_retries=retries)) self.session.headers.update({ 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(self.token) }) def _request(self, relative_url, params=None, data=None, method='GET', verify_ssl=False): relative_url = '/'.join((self.base_url, relative_url)) response = self.session.request(method, relative_url, params=params, data=data, verify=verify_ssl) response.raise_for_status() return response.json() def get_incidents(self, **payload): """Get incidents with optional filters""" return self._request('incidents?count_total=false', params=payload)['items'] def get_incident(self, incident_id, **payload): """Get a specific incident by ID""" r = self._request('incidents/%s' % incident_id, params=payload) return r['results'][0] def update_incident(self, incident_id, status=None, severity=None, customer_key=None): """Update an incident's status, severity, or customer key""" import json data = {'incident_status': status, 'severity': severity, 'customer_key': customer_key} data = {k: v for k, v in data.items() if v is not None} self._request('incidents/{}'.format(incident_id), data=json.dumps(data), method='PUT') # Usage example token = "your_cloudlock_api_token" cl_client = CLAPIClient(token) # Get recent incidents incidents = cl_client.get_incidents(limit=100, order='created_at') for incident in incidents: print(f"Incident ID: {incident['id']}") print(f" Status: {incident['incident_status']}") print(f" Severity: {incident['severity']}") print(f" Entity: {incident.get('entity', {}).get('name', 'N/A')}") print(f" Policy: {incident.get('policy', {}).get('name', 'N/A')}") print() # Update an incident cl_client.update_incident("incident_123", status="resolved", severity="INFO") ``` ### Response Example (Success - GET Incidents) ```json { "items": [ { "id": "12345", "incident_status": "new", "severity": "WARNING", "created_at": "2024-01-15T10:30:00Z", "entity": { "name": "document.pdf", "owner_email": "user@company.com" }, "policy": { "name": "PCI-DSS Detection" } } ] } ``` ``` -------------------------------- ### Initialize OAuth2.0 HTTP Client in Go Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/golang/README.md Initializes an HTTP client using OAuth 2.0 client credentials. This client automatically manages token lifecycle, including creation, reuse, and refresh. Set API_KEY and API_SECRET as environment variables. ```go config := &clientcredentials.Config{ TokenURL: "https://api.umbrella.com/auth/v2/token", ClientID: "", ClientSecret: "", } httpClient := config.Client(context.Background()) if httpClient == nil { fmt.Printf("Error creating Oauth2 http client for %s ", config.TokenURL) return } ``` -------------------------------- ### Get Help for Cloudlock Incident Pull Script Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cloudlock/Sample Scripts/README.md Display the help message for the 'pull_incidents.py' script to understand available options and arguments for fetching incidents. ```bash python /home/ubuntu/pull_incidents.py --help ``` -------------------------------- ### Initialize Python Secure Access API Class Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/Auth/client-samples/python/README.md Initializes the Secure Access API client with token URL, client ID, and client secret. ```python class secureAccessAPI(): def __init__(self, token_url, client_id, client_secret): self.token_url = token_url self.client_id = client_id self.client_secret = client_secret ``` -------------------------------- ### Make Authenticated API Request Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/java/README.md Use the initialized OAuth2RestTemplate to make a GET request to the Umbrella Reporting API. The Bearer token is automatically acquired and included in the request headers. ```java . . . final String requestUrl = "https://api.umbrella.com/reports/v2/summary?from=-5days&to=now" final String response = restTemplate.getForObject(requestUrl, String.class); . . . ``` -------------------------------- ### Sample credentials.json Configuration Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Deployments/NetworkTunnel/create-tunnel/README.md Configure your Cisco Umbrella API credentials and settings in the credentials.json file. Ensure all fields are updated with your specific data. ```json { "key": "", "secret": "", "org_id": "", "log_file": "tunnel_log", "tunnel_data": "tunnel_data.csv", "debug": true } ``` -------------------------------- ### Call Secure Access API with Authentication Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/Auth/client-samples/python/README.md Makes a GET request to the Secure Access Reporting API, automatically refreshing the token if expired. Includes error handling and prints the JSON response. ```python @refreshToken def callSecureAccessApi(api, path): try: api_headers = {} api_headers['Authorization'] = 'Bearer ' + api.access_token r = requests.get('https://api.sse.cisco.com/reports/v2/' + path, headers=api_headers) r.raise_for_status() except Exception as e: print("Report API call failed for {}: {}", path, e) else: print(json.dumps(r.json(), indent=4)) ``` -------------------------------- ### Initialize HTTP Client with Credentials Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/Auth/client-samples/python/README.md Initializes an HTTP client object using client credentials, organization ID, and token URL for OAuth 2.0. ```python auth = HTTPBasicAuth(client_id, client_secret) client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url=url, auth=auth) ``` -------------------------------- ### Call Umbrella Reporting API Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/python/README.md Makes a GET request to the Umbrella Reporting API, automatically refreshing the token if necessary using the `@refreshToken` decorator. Prints the JSON response or an error message. ```python @refreshToken def callUmbrellaApi(api, path): try: api_headers = {} api_headers['Authorization'] = 'Bearer ' + api.access_token r = requests.get('https://api.umbrella.com/reports/v2/' + path, headers=api_headers) r.raise_for_status() except Exception as e: print("Report API call failed for {}: {}", path, e) else: print(json.dumps(r.json(), indent=4)) ``` -------------------------------- ### Run Application Lists Migration Script Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/Policies/application-lists/application-lists-migrate/README.md Execute the Python script to migrate application lists. Ensure all environment variables are correctly set before running. ```shell python3 application_lists_migrate.py ``` -------------------------------- ### Make Authenticated Request to Umbrella Reporting API Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/php/README.md Initializes the Guzzle HTTP client with the configured OAuth2 middleware and makes a GET request to the Umbrella Reporting v2 API summary endpoint. ```php // This is the normal Guzzle client that you use in your application $client = new GuzzleHttp\Client([ 'handler' => $stack, 'auth' => 'oauth', ]); $response = $client->get("https://api.umbrella.com/reports/v2/summary?from=-5days&to=now"); echo "Status: ".$response->getStatusCode()."\n"; ``` -------------------------------- ### Create Application Lists Source: https://context7.com/ciscodevnet/cloud-security/llms.txt Creates application lists in a target Cisco Secure Access organization from an exported JSON file. The JSON file should contain a list of application list objects. ```python def create_application_list(api, application_lists_file): """Create application lists in target organization from exported JSON""" with open(application_lists_file, 'r') as file: data = json.load(file) for app_list in data: payload = { 'applicationListName': app_list.get('applicationListName'), 'isDefault': app_list.get('isDefault'), 'applicationIds': app_list.get('applicationIds'), 'applicationCategoryIds': app_list.get('applicationCategoryIds') } response = api.Query('policies', 'applicationLists', 'post', payload) if response.status_code == 200: print(f"Created: {app_list.get('applicationListName')}") ``` -------------------------------- ### Create Python Virtual Environment Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/Policies/application-lists/application-lists-migrate/README.md Create a Python virtual environment to isolate project dependencies. Activate it using the appropriate command for your operating system. ```shell python3 -m venv myenv ``` ```shell myenv\Scripts\activate ``` ```shell source myenv/bin/activate ``` -------------------------------- ### Build Java Application with Maven Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/java/README.md Build the Java application as a single JAR file with all dependencies using the Maven assembly plugin. ```shell mvn assembly:assembly -DdescriptorId=jar-with-dependencies ``` -------------------------------- ### Cisco Secure Access API Client Source: https://context7.com/ciscodevnet/cloud-security/llms.txt Provides a reusable client for Cisco Secure Access APIs with support for GET, POST, and DELETE operations, including automatic token refresh. Requires API credentials and token URL for initialization. ```python import requests from oauthlib.oauth2 import BackendApplicationClient from oauthlib.oauth2 import TokenExpiredError from requests_oauthlib import OAuth2Session from requests.auth import HTTPBasicAuth class SSEAPI: def __init__(self, url, ident, secret): self.url = url self.ident = ident self.secret = secret self.token = None def GetToken(self): auth = HTTPBasicAuth(self.ident, self.secret) client = BackendApplicationClient(client_id=self.ident) oauth = OAuth2Session(client=client) self.token = oauth.fetch_token(token_url=self.url, auth=auth) return self.token def ReqGet(self, end_point): success = False resp = None if self.token == None: self.GetToken() while not success: try: bearer_token = "Bearer " + self.token['access_token'] api_headers = { "Authorization": bearer_token, "Content-Type": "application/json" } resp = requests.get('https://api.sse.cisco.com/{}'.format(end_point), headers=api_headers) resp.raise_for_status() success = True except TokenExpiredError: token = self.GetToken() except Exception as e: raise(e) return resp def ReqPost(self, end_point, data): if self.token == None: self.GetToken() bearer_token = "Bearer " + self.token['access_token'] api_headers = { 'Authorization': bearer_token } resp = requests.post('https://api.sse.cisco.com/{}'.format(end_point), json=data, headers=api_headers) resp.raise_for_status() return resp def ReqDelete(self, end_point, data): if self.token == None: self.GetToken() bearer_token = "Bearer " + self.token['access_token'] api_headers = { 'Authorization': bearer_token } resp = requests.delete('https://api.sse.cisco.com/{}'.format(end_point), json=data, headers=api_headers) resp.raise_for_status() return resp ``` ```python # Usage example - Monitor Network Tunnels import os client_id = os.environ.get('API_KEY') client_secret = os.environ.get('API_SECRET') token_url = 'https://api.sse.cisco.com/auth/v2/token' sse_api = SSEAPI(token_url, client_id, client_secret) tunnel_endpoints = 'deployments/v2/networktunnelgroups' tunnelComponents = sse_api.ReqGet(tunnel_endpoints).json() for tunnel in tunnelComponents["data"]: if tunnel["status"] == "disconnected" or tunnel["status"] == "warning": print(f"Alert: {tunnel['name']} - {tunnel['deviceType']} - {tunnel['status']}") ``` -------------------------------- ### Edit Environment Configuration File Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Reports/Reporting-and-Investigate-APIs-ELK/README.md Use 'vim' to edit the '.env' file and update the placeholders with your specific Umbrella and Investigate API credentials and settings. ```shell vim .env ``` -------------------------------- ### Run the Main Script Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Deployments/NetworkTunnel/create-tunnel/README.md Execute the main Python script to create network tunnels. Ensure your tunnel attributes are correctly set in tunnel_data.csv. ```shell python3 main.py ``` -------------------------------- ### Schedule Cloudlock Incidents Script with Crontab Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cloudlock/Sample Scripts/README.md Schedule the Python script to run automatically using crontab. This example runs the script every 2 minutes, directing output to '/tmp/sim.log'. Ensure the script path and output directory are correctly set. ```shell SHELL=/bin/bash */2 * * * * root python /home/ubuntu/cl_sample_incidents.py -c flat_file -u https://YourAPIServersAddress/api/v2 -t -p /tmp >> /tmp/sim.log 2>&1 ``` -------------------------------- ### Run the Application Lists Copy Script Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/Policies/application-lists/application-lists-copy/README.md Execute the Python script to copy application lists. Ensure environment variables like OUTPUT_DIR, API_KEY, and API_SECRET are set. ```shell python3 application_lists_copy.py ``` -------------------------------- ### Set Environment Variables Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/client-samples/Deployments/NetworkTunnels/README.md Configure the required environment variables before running the script. These include API keys, password, and email. ```shell export API_KEY=VALUE ``` ```shell export API_SECRET=VALUE ``` ```shell export PASSWD=VALUE ``` ```shell export EMAIL=VALUE ``` -------------------------------- ### Run AD Connector Monitor on Windows Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Deployments/VirtualAppliances/README.MD Executes the AD Connector Monitor script using Python on a Windows operating system. Ensure all environment variables and prerequisites are met. ```python python ADConnectorMonitor.py ``` -------------------------------- ### Run `oauthlib` Python Client Source: https://github.com/ciscodevnet/cloud-security/blob/master/Cisco Secure Access/Samples/Auth/client-samples/python/README.md Executes the `oauthlib` Python client application to interact with the Secure Access Reporting API. ```shell python3 oauthlib_api_sample_client.py ``` -------------------------------- ### Initialize Umbrella API Client Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/python/README.md Initializes the Umbrella API client with token URL, client ID, and client secret. This class is the foundation for all API interactions. ```python class UmbrellaAPI(): def __init__(self, token_url, client_id, client_secret): self.token_url = token_url self.client_id = client_id self.client_secret = client_secret ``` -------------------------------- ### Run AD Connector Monitor on Mac Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Deployments/VirtualAppliances/README.MD Executes the AD Connector Monitor script using Python 3 on a macOS system. Ensure all environment variables and prerequisites are met. ```python python3 ADConnectorMonitor.py ``` -------------------------------- ### Initialize and Use Cloudlock API Client in Python Source: https://context7.com/ciscodevnet/cloud-security/llms.txt This Python class provides methods to interact with the Cloudlock API for managing DLP incidents. It includes error handling with retries and SSL verification options. Use this client to fetch, retrieve, and update incident details. ```python import requests from requests.packages.urllib3.util import Retry class CLAPIClient(object): """CloudLock API Client""" BASE_URL = 'https://api.cloudlock.com/api/v2' def __init__(self, token, base_url=BASE_URL): self.token = token self.base_url = base_url self.session = requests.session() retries = Retry(total=100, status_forcelist=(429, 500, 502, 504), backoff_factor=0.1) self.session.mount(self.base_url, requests.adapters.HTTPAdapter(max_retries=retries)) self.session.headers.update({ 'Content-Type': 'application/json', 'Authorization': 'Bearer {}'.format(self.token) }) def _request(self, relative_url, params=None, data=None, method='GET', verify_ssl=False): relative_url = '/'.join((self.base_url, relative_url)) response = self.session.request(method, relative_url, params=params, data=data, verify=verify_ssl) response.raise_for_status() return response.json() def get_incidents(self, **payload): """Get incidents with optional filters""" return self._request('incidents?count_total=false', params=payload)['items'] def get_incident(self, incident_id, **payload): """Get a specific incident by ID""" r = self._request('incidents/%s' % incident_id, params=payload) return r['results'][0] def update_incident(self, incident_id, status=None, severity=None, customer_key=None): """Update an incident's status, severity, or customer key""" import json data = {'incident_status': status, 'severity': severity, 'customer_key': customer_key} data = {k: v for k, v in data.items() if v is not None} self._request('incidents/{}'.format(incident_id), data=json.dumps(data), method='PUT') ``` ```python # Usage example token = "your_cloudlock_api_token" cl_client = CLAPIClient(token) # Get recent incidents incidents = cl_client.get_incidents(limit=100, order='created_at') for incident in incidents: print(f"Incident ID: {incident['id']}") print(f" Status: {incident['incident_status']}") print(f" Severity: {incident['severity']}") print(f" Entity: {incident.get('entity', {}).get('name', 'N/A')}") print(f" Policy: {incident.get('policy', {}).get('name', 'N/A')}") print() # Update an incident cl_client.update_incident("incident_123", status="resolved", severity="INFO") ``` -------------------------------- ### Initialize Guzzle HTTP Client with OAuth2 Middleware Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/php/README.md Initializes a Guzzle HTTP client and configures OAuth2.0 middleware for requesting access tokens using client credentials and refresh tokens. ```php // Authorization client - this is used to request OAuth access tokens $reauth_client = new GuzzleHttp\Client([ // URL for access_token request 'base_uri' => 'http://some_host/access_token_request_url', ]); $reauth_config = [ "client_id" => $client_id, "client_secret" => $client_secret, //"scope" => "your scope(s)", // optional ]; $grant_type = new ClientCredentials($reauth_client, $reauth_config); // This grant type is used to get a new Access Token and Refresh Token when // only a valid Refresh Token is available $refresh_grant_type = new RefreshToken($reauth_client, $reauth_config); // Tell the middleware to use the two grant types $oauth = new OAuth2Middleware($grant_type, $refresh_grant_type); $stack = HandlerStack::create(); $stack->push($oauth); ``` -------------------------------- ### Sample Output of Java Spring Security Client Source: https://github.com/ciscodevnet/cloud-security/blob/master/Umbrella/Samples/Auth/client-samples/java/README.md The client logs request details including response time, request string, and response body. The first request may have a higher response time as it acquires the access token. ```java call#1: RspTime: 980(ms): https://api.umbrella.com/reports/v2/summary?from=-5days&to=now {"meta":{},"data":{"applications":0,"domains":0,"requestsblocked":0,"filetypes":0,"requests":0,"policycategories":0,"requestsallowed":0,"categories":0,"identitytypes":0,"applicationsblocked":0,"files":0,"identities":0,"policyrequests":0,"applicationsallowed":0}} call#2: RspTime: 333(ms): https://api.umbrella.com/reports/v2/summary?from=-5days&to=now {"meta":{},"data":{"applications":0,"domains":0,"requestsblocked":0,"filetypes":0,"requests":0,"policycategories":0,"requestsallowed":0,"categories":0,"identitytypes":0,"applicationsblocked":0,"files":0,"identities":0,"policyrequests":0,"applicationsallowed":0}} call#3: RspTime: 392(ms): https://api.umbrella.com/reports/v2/summary?from=-5days&to=now {"meta":{},"data":{"applications":0,"domains":0,"requestsblocked":0,"filetypes":0,"requests":0,"policycategories":0,"requestsallowed":0,"categories":0,"identitytypes":0,"applicationsblocked":0,"files":0,"identities":0,"policyrequests":0,"applicationsallowed":0}} ``` -------------------------------- ### Export Application Lists Source: https://context7.com/ciscodevnet/cloud-security/llms.txt Retrieves all application lists and their details from a Cisco Secure Access organization and saves them to a JSON file. Ensure the API object is properly initialized. ```python def get_application_lists(api, output_file): """Get all application lists and their details from an organization""" response = api.Query('policies', 'applicationLists', 'get') if response.status_code == 200: data = response.json() application_details = [] for app_list in data.get('results', []): if app_list['applicationListId']: details_response = api.Query('policies', f"applicationLists/{app_list['applicationListId']}", 'get') if details_response.status_code == 200: application_details.append(details_response.json()) with open(output_file, 'w') as f: json.dump(application_details, f, indent=4) print(f"Application details written to {output_file}") return application_details ```