How to Retrieve Software Bill of Materials (SBOM) Using the Uptycs API: A Step-by-Step Guide

How to Retrieve Software Bill of Materials (SBOM) Using the Uptycs API: A Step-by-Step Guide

To get SBOM(Software Bill of Material) information for your resource through Uptycs API, follow below step

Obtain Access Keys:
      •  Login to the Uptycs console
      •  Go to Account Settings
      •  Create an API Key
      •  Download the API Key in JSON format. For example, if your username is UserX, the file might be
          named UserX_apikey.json

Calling API:
      •  Method: POST
      •  URL : https://{domain}.uptycs.io/public/api/v2/customers/{customerId}/sbom
Payload
Payload
{
      "name":   "HOST_SBOM",
      "resourceId":   "ec27ba82-1ebd-22e8-df47-5af2b795a044",
      "resourceName":   "abc_xyz-123",
      "format":   "CycloneDX"
}

Values for parameters in the payload:
  1. name : Allowed values are HOST_SBOM or IMAGE_SBOM
  2. resourceId: UUID of the resource for which you want to retrieve SBOM details.
  3. resourceName: Name of the resource for which you want to obtain SBOM details. This parameter is optional if you have already provided the resourceId.
  4. format: Allowed format values are spdx or CycloneDX


Notes
Run the below python script to call Uptycs API and retrieve SBOM details of any resource .
     try:
        import requests
        import time
        import jwt
        import datetime as dt
        import json
    except Exception as err:
        print('ERROR :', err)
        exit(-1)
       

    # get file name
    def getFileName():
        file_name = input("\nEnter the File name of access keys (User_apikey.json)\n")
        return file_name


    def getCredentials(file_name):
        # open credentials file
        try:
            with open(file_name, 'r') as file:
                content = file.read()
                return json.loads(content)
        except FileNotFoundError:
            print(f"⛔ The file '{file_name}' could not be found.")
            exit(-1)
        except Exception as e:
            print(f"⛔ An error occurred while trying to open the file: {e}")
            exit(-1)
        return {}

    # API headers
    def api_headers(credentials):
        seconds_to_expiry = 3600
        exp = time.time() + seconds_to_expiry
        expiry = dt.datetime.fromtimestamp(exp).strftime('%Y-%m-%d %H:%M')
        domain = credentials['domain']
        customerId = credentials['customerId']
        key = credentials['key']
        secret = credentials['secret']
        token = jwt.encode({'iss':key, 'exp':exp}, secret, algorithm='HS256')
        auth = f'Bearer {token}'
        creds = {'domain':domain,'customerId':customerId}
        creds['Expiration'] = expiry
        creds['Authorization'] = auth
        return creds

    # API POST Call
    def POSTCall(url, creds, payload):
        response = requests.post(url, headers=creds, data=payload)

        data = response.json()
        status_code = response.status_code

        return data, status_code


    # check if API call is failed
    def check_api_call_status(response, status_code):
        if status_code not in [200, 201, 202, 204]:
            print(f'API call failed with status code {status_code}\n\n {response}\n\n')
            exit(-1)

    # save data to json file
    def save_to(fileName, data):
        try:
            with open(f'{fileName}.json', 'w') as f:
                f.write(json.dumps(data))
            print(f"\nOutput stored to {fileName}.json\n")    
        except Exception as err:
            print(f'\nFailed to store data to {fileName}.json\n{err}')


    def main():
        file_name = getFileName()
        credentials = getCredentials(file_name)
        domain = credentials['domain']
        customerId = credentials['customerId']
        print (f'\n✅ Credentials read for domain {domain}\n')
        creds = api_headers(credentials)
       
        resourceId = input("\nEnter the Correct Resource Id of the Asset\n")
        resourceType = "HOST_SBOM" if input("\nEnter the resource type: HOST_SBOM (1) | IMAGE_SBOM (2)\n") == "1" else "IMAGE_SBOM"
        formatType = "CycloneDX" if input("\nEnter the format spdx (1) | CycloneDX (2)\n") == "2" else "SPDX"

        # Format the URL
        url = f'https://{domain}.uptycs.io/public/api/v2/customers/{customerId}/sbom'

        # payload
        payload = {
            "name": resourceType, # Host(HOST_SBOM) or Image(IMAGE_SBOM)
            "resourceId": resourceId, # Uptycs AssetId or UUID
            "resourceName": "ASDWNAADSP001.corp.root.nasd.com", # this is optional. Use this if you know hostname instead of asset id
            "format": formatType # output format spdx (or) CycloneDX
        }
        print("\n\nQuery Posted for execution....\n")
        response, status_code = POSTCall(url, creds, payload)
        check_api_call_status(response, status_code)
        print(f"Query is {response['status']} \n")

        # call the API until it finishes
        while response['status'] != 'FINISHED':
            response, status_code = POSTCall(url, creds, payload)
            check_api_call_status(response, status_code)
            print(f"Query is {response['status']}\n")
            time.sleep(1)
       
        outputFileName = input('Enter the outfile Name to store api response without file extension\n')

        save_to(outputFileName, response)
       
    if __name__ == "__main__":
        main()



Idea
Execution Demo:



This guide provides a structured approach to utilizing the Uptycs /sbom API endpoint to generate and retrieve SBOM data of your software for further analysis. Adjust parameters and inputs as per your specific requirements and configurations in Uptycs.

If you need any help, please feel free to contact support@uptycs.com


    • Related Articles

    • API calling via Swagger

      Go To the "Account Settings". Click the "CREATE" button to generate API keys, which will be downloaded in JSON format. The downloaded JSON will contain information such as customerId, API key, API Secret, Domain, DomainSuffix, and other relevant ...
    • Provisioning roles using API

      Overview Starting with Uptycs portal release 46025, Uptycs provides entity level granular user permissions through roles. This document outlines the process to create roles using API - with examples. Procedure -- Create a new role $ urestapi -k ...
    • Generate JWT Token using PowerShell CMDLETS

      With just PowerShell Cmdlets, you can generate a Bearer Auth Token using the following steps. # please install JWT module in PowerShell Install-Module JWT # cmdlet to generate JWT Token New-Jwt -Header '{"alg": "HS256", "typ": "JWT"}' -PayloadJson ...
    • Delete assets offline since a particular date using the API

      This script / procedure outlines the process to delete assets which have been offline before a particular date. Prerequisite tools iusql urestapi Procedure Download api key from Uptycs UI Download attached script, delete_offline_assets_since.sh     ...
    • Uptycs Alert Triggers API Call

      This python module can be run to trigger Uptycs API calls from Uptycs alerts.  Example: An alert is configured to fire when asset location is not in USA (possible GDPR issue). This python can then be run to automatically make an API call to disable ...