Scripting and Automation Best Practices with Prisma Cloud CSPM JWT

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
Announcements
L4 Transporter
No ratings

By Bishvesh Pachauli, Cloud Security Engineer

and Paul Burega, Cloud Security Engineer

 

Introduction 

 

When we talk to our customers, we see a trend that more enterprise customers are onboarding their cloud accounts to Prisma Cloud for better security, visibility, and compliance. 

 

Many teams are relying on automation to streamline their Security Operations Center. Automation allows customers to scale their operations as their cloud presence grows and allows the data from Prisma Cloud to be integrated with a customer’s existing workflow to manage Cloud security.  This API is also used by Cortex XSOAR playbooks for alert remediation and alert report generation.

 

This automation extracts information from Prisma Cloud via the public Rest APIs, documented in the Prisma™ Cloud API Reference.

 

As part of security best practices, Prisma Cloud utilizes a Jason Web Token (JWT), an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.  The JWT is used to manage the security and authentication of the user or access key for the script access to the Prisma Cloud API.

 

This article talks about best practices for the use of the JWT token for use in scripts and applications accessing the Prisma Cloud API. 

 

Script Security Best Practices

 

Your scripts and applications utilizing the Prisma Cloud API should always follow the following security best practices.

  1. No hard-coded client credentials.  Access keyId/Secret Access keys are confidential and need to be protected. Your script should not include hard-coded client credentials.
  2. JWT tokens can be reused for the life of the token. Upon expiration (HTTPS 401: Unauthorized error), the calling party will be required to be authorized for a new token.  There is also a refresh token endpoint for cases where the token has not yet expired.
  3. Just like sharing passwords between users is a bad security practice, sharing access keys between scripts is a bad security practice. Access keys should have regular expiry dates and regenerate just as your company’s password change policy requires.
  4. Practice “grant least privilege” when assigning roles to access keys.
  5. Always check and act on API return codes. This will ensure that no matter what happens with Prisma Cloud, your script will not fail unexpectedly. 

 

API Flows

 

Below are three flow diagrams that illustrate several ways in which APIs can be called in general, not specific to Prisma Cloud.  

 

Approach 1: This is the least favored approach as the token does not expire, and is susceptible to attack and impersonation as there is no lifespan to the token. 

RPrasadi_0-1663777178296.png

Figure 1: Flow diagrams with token that does not expire_Palo-Alto-Networks

 

Approach 2: An significant improvement over 1) is to have the JWT token time out. 

RPrasadi_1-1663777178295.png

Figure 2: Flow diagrams with JWT token timeout_Palo-Alto-Networks

 

Approach 3: The best approach is where the token is refreshed just before it expires. Currently, the Prisma Cloud SaaS JWT expires every 10 minutes. This is the mechanism used by the Prisma Cloud UI, and is best for 24/7 applications.

RPrasadi_2-1663777178357.png

Figure 3: Flow diagrams with token is refreshed_Palo-Alto-Networks

 

Best practices for implementing

 

  1. Always check and handle API return codes appropriately: RPrasadi_3-1663777178293.png

    Figure 4: API return codes_Palo-Alto-Networks


    While calling Prisma Cloud APIs, please check for the API return codes after each API call. This is a security best practice.


If the return code is:
a) 401: Your token has expired, typically the JWT is > 10 minutes old.  Please generate a new token.

  1. b) 429: Too many requests in the past second. Perform exponential backoff and call the API again.
    c) 500, 502, 503, 504: Server error. Perform exponential backoff and call the API again.
    Please remember that all API retries must use exponential backoff, which means delay should be in the order of 1 sec, 2 sec, 4 sec, 8 sec, up to a max of 32 seconds..

  1. For continuously running applications, ensure JWT is refreshed in approximately 9 minutes and 50 seconds by a dedicated thread. For simple automation scripts/Cron Jobs, wait until you receive a 401 return code and refresh the token again.




An ideal API workflow automation framework should look like this:

RPrasadi_4-1663777178355.png

Figure 5: API workflow automation framework_Palo-Alto-Networks

Python Best Practices

 

Palo Alto Networks provides a GitHub library: Prisma Cloud Python Integration - PCPI which contains our Python3 toolkit for Prisma Cloud APIs.

 

This library provides all the session management for best practices of the Prisma Cloud CSPM JWT. This library is easy to use in your existing python scripts and applications:

$ pip3 install pcpi

 

No need to rewrite your python code, just change your Prisma Cloud API calls to use the interface provided by the library.  The library will manage your JWT session and keep the token refreshed, as well as apply the necessary retries and exponential backoff based on the return codes provided. 

 

The session loader is a module that has functions for loading Prisma Cloud credentials from a file, environment variables, or from the user into your program. This ensures you get your script up and running as quickly as possible.

 

from pcpi import session_loader

 

#Defaults to a file named 'tenant_credentials.yml'

session_manager_default = session_loader.load_from_file()

 

#File must be a yaml (.yml) file. If a file that does not exist is specified, the script will build one.

session_manager = session_loader.load_from_file(file_path='~/secrets/my_secrets.yml')

 

cspm_session = session_manager.create_cspm_session()

cwp_session = session_manager.create_cwp_session()

 

response = cspm_session.request('GET', '/cloud')

 

print(response.json())



Additional example information is available from the GitHub repository. 



Bash Best Practices

 

The following code snippet will use curl to access the Prisma Cloud APIs and log any information generated. 

 

function error {

   (

    echo "$(date "+%m%d%Y %T") : Start logging"

    cat tmp_token.json 1>&2

    echo "$(date "+%m%d%Y %T") : Done logging"

    ) >& $LOGFILE

    exit 1 # terminate and indicate error

}

 

curl --location --request POST -i 'https://api2.prismacloud.io/login' \

--header 'accept: application/json; charset=UTF-8' \

--header 'content-type: application/json' \

--data-raw '{

    "username": "<access key id>",

    "password": "<access key secret>"

}' >> tmp_token.json

 

time_now=`date +%s`

        echo "$time_now - $time_initial"

        time_diff=$((time_now - time_initial))

        echo $time_diff

        if [ $time_diff -gt $threshold ]

        then

           # Refresh token

           extend_token=`curl --location --request GET 'https://api2.prismacloud.io/auth_token/extend' \

                              --header 'accept: application/json; charset=UTF-8' \

                              --header 'content-type: application/json' \

                              --header 'x-redlock-auth: '"$token"'' | jq '.token' | sed 's/^.\(.*\).$/\1/'`

           if [[ $status -ne 200 ]]

           then

              error

            fi

            # Replace token with extend_token

            token=$extend_token

            # Assign now_time to initial_time

            time_initial=$time_now

        fi

 

Conclusion

 

Best practices for automation that involves APIs should combine Token security & validity and handling of API return codes. This not only enhances the usability of the automation framework from the user experience but also increases automation reliability, up-time and performance.  Minimizing the time refreshing the JWT maximizes the time your user code is executing and results in the shortest time to script completion with your desired results.

 

About the Authors

 

Bishvesh Pachauli and Paul Burega are cloud security engineers specializing in Cloud Security Posture Management. 

Paul and Bishvesh utilize collaborative approach to break down complex problems into solutions for global enterprise customers and leverage their multi-industry knowledge to inspire success. 

Rate this article:
(2)
Comments
L1 Bithead

Thank you for publishing these automation best practices! 

  • 8544 Views
  • 1 comments
  • 5 Likes
Register or Sign-in
Labels
Article Dashboard
Version history
Last Updated:
‎10-28-2024 12:49 PM
Updated by: