Welcome to Trend Micro
This website uses cookies for website functionality, traffic analytics, personalization, social media functionality and advertising. Our Cookie Notice provides more information and explains how to amend your cookie settings.
Learn more
Add Objects from an OpenIOC File to the User-Defined Suspicious Objects List

Add Objects from an OpenIOC File to the User-Defined Suspicious Objects List

This task uploads an OpenIOC file and then adds objects from the file to the User-Defined Suspicious Objects (UDSO) list.

  1. Obtain an application ID and API key.
  2. Define the libraries and functions necessary to create JSON Web Tokens for authorization.
  3. Encode and upload the OpenIOC file.
  4. Add objects from the OpenIOC file to the UDSO list.

Obtain an Application ID and API Key

This task retrieves the application ID and API key for an external application that consumes Apex Central Automation APIs.

  1. Go to Administration > Settings > Automation API Access Settings.

    The Automation API Access Settings screen appears.

  2. Click Add.

    The Application Access Settings section appears and displays the following information:

    • Application ID: Used by Apex Central to identify the external application

    • API key: Used by the external application to sign requests sent to Apex Central

    • API type: Indicates the API functions that the external application can access

  3. Select Enable application integration using Apex Central Automation APIs.
  4. Configure the following settings.
    • Application name: Specify an easily identifiable name for the application.

    • Communication time-out: Select the maximum number of seconds allowed for a request to reach Apex Central after the application generates the request.

  5. Click Save.

    The Automation API Access Settings screen appears and displays the newly added application in the table.

  6. In Python, assign values to following parameters.

    Parameter

    Value

    use_application_id

    Your application ID

    use_api_key

    Your API key

    use_url_base

    Your server URL

    use_application_id = YOUR_APPLICATION_ID
    use_api_key = YOUR_API_KEY
    use_url_base = YOUR_SERVER_URL

Define the Libraries and Functions Required for JSON Web Token Creation

This task defines the necessary libraries and functions for creating the JSON web token (JWT).

  1. Define the necessary libraries.
    import base64
    import jwt
    import hashlib
    import time
    import json
  2. Define the function that creates the checksum.
    def create_checksum(http_method, raw_url, headers, request_body):
        string_to_hash = http_method.upper() + '|' + raw_url.lower() + '|' + headers + '|' + request_body
        base64_string = base64.b64encode(hashlib.sha256(str.encode(string_to_hash)).digest()).decode('utf-8')
        return base64_string
  3. Define the function that creates the JWT.
    def create_jwt_token(appication_id, api_key, http_method, raw_url, headers, request_body,
                         iat=time.time(), algorithm='HS256', version='V1'):
        checksum = create_checksum(http_method, raw_url, headers, request_body)
        payload = {'appid': appication_id,
                   'iat': iat,
                   'version': version,
                   'checksum': checksum}
        token = jwt.encode(payload, api_key, algorithm=algorithm).decode('utf-8')
        return token

Encode and Upload the OpenIOC File

This task encodes the OpenIOC file to Base64 and uploads the file to the Apex Central server.

  1. Assign a value to file_name.
    file_name = <YOUR_FILE_PATH>

    In this use case, the assigned file name is BKDR_KULUOZ.SM04.ioc.

  2. Encode the file to Base64.
    file_name='BKDR_KULUOZ.SM04.ioc'
    # Encoding the OpenIOC file to base64.
    print('Encoding the OpenIOC file to base64.')
    with open(file_name, "rb") as f:
        file_string_base64 = base64.b64encode(f.read())
  3. Upload the file to the Apex Central server and assign the response value to r.

    For more information about the "Upload OpenIOC file" API, see https://automation.trendmicro.com/apex-central/api#operation/OpenIOCResource_POSTFile.

    print('Uploading the OpenIOC file to the Apex Central server.')
    productAgentAPIPath = '/WebApp/IOCBackend/OpenIOCResource/File'
    canonicalRequestHeaders = ''
    useQueryString = ''
    
    payload = {
      "param":
      [
        {
          "FileName": file_name,
          "FileContentBase64":file_string_base64.decode()
        }
      ]
    }
    useRequestBody = json.dumps(payload) 
      
    jwt_token = create_jwt_token(use_application_id, use_api_key, 'POST',
                                  productAgentAPIPath + useQueryString,
                                  canonicalRequestHeaders, useRequestBody, iat=time.time())
     
    headers = {'Authorization': 'Bearer ' + jwt_token , 'Content-Type': 'application/json;charset=utf-8'}
    r = requests.post(use_url_base + productAgentAPIPath + useQueryString, headers=headers, data=useRequestBody, verify=False)
  4. Perform error handling and print the API response.
    if r.status_code !=200 and r.status_code!=201:
      print(r.status_code)
      #insert error handling code
    
    print(json.dumps(r.json(), indent=4))
  5. Verify that the file was uploaded.

    If your request was successful, the response will be similar to the following:

    200
    {
      "Data":
      {
        "UploadedResultInfoList":
        [
          {
            "FileName": "BKDR_KULUOZ.SM04.ioc",
            "FileHashID": "73d95a30c812d9cff0eaf37a686fdfef8f9ca531",
            "UploadedStatus": 1
          }
        ],
        "UploadedResultMessageList":
        [
          {
              "MessageType": 1,
              "Message": "Uploaded 1 OpenIOC file(s) successfully."
          }
        ]
      },
      "FeatureCtrl":
      {
        "mode": "0"
      },
      "Meta":
      {
        "Result": 1,
        "ErrorCode": 0,
        "ErrorMsg": "Success"
      },
      "PermissionCtrl":
      {
        "permission": "255",
        "elements": "null"
      }
    }
  6. Print the value of file_hashID.
    file_hashID = r.json()["Data"]["UploadedResultInfoList"][0]["FileHashID"]
    print('file_hashID:',file_hashID)

Add Objects to the User-Defined Suspicious Objects List

This task extracts objects from the OpenIOC file and adds the objects to the User-Defined Suspicious Objects (UDSO) list.

  1. Extract objects from the file, add the objects to the UDSO list, and assign the response value to r.

    For more information about the "Extract OpenIOC objects to list" API, see https://automation.trendmicro.com/apex-central/api#operation/UserDefinedSOResource_OpenIOCExtraction.

    print('Extracting the objects from the OpenIOC file and adding the objects to the User-Defined Suspicious Objects list.')
     
    productAgentAPIPath = '/WebApp/SuspiciousObjectsBackend/UserDefinedSOResource/OpenIOCExtraction'
    canonicalRequestHeaders = ''
    useQueryString = ''
    payload = {
      "param":
        {
          "FileHashIDList": [file_hashID],
          "ScanType":{
             "File":2,
             "IP":2,
             "URL":2,
             "Domain":2
          }
        }
    }
     
    useRequestBody = json.dumps(payload) 
     
    jwt_token = create_jwt_token(use_application_id, use_api_key, 'PUT',
                                  productAgentAPIPath + useQueryString,
                                  canonicalRequestHeaders, useRequestBody, iat=time.time())
     
    headers = {'Authorization': 'Bearer ' + jwt_token, 'Content-Type': "application/json"}
     
    r = requests.put(use_url_base + productAgentAPIPath + useQueryString, headers=headers, data=useRequestBody, verify=False)

    You must assign values to the following parameters:

    Parameter

    Description

    Value

    FileHashIDList

    Hash value of the uploaded file

    file_hashID value from the response to the previous API call

    ScanType

    Action to be performed on objects added to the UDSO list

    One of the following:

    • 1: Log

    • 2: Block

    • 3: Quarantine

    Note:

    In this use case, the value assigned to all objects is 2.

  2. Perform error handling and print the API response.
    if r.status_code !=200 and r.status_code!=201:
      print(r.status_code)
      #insert error handling code
    
    print(json.dumps(r.json(), indent=4))
  3. Verify that the objects were extracted from the file.

    If your request was successful, the response will be similar to the following:

    {
        "Data": [
            {
                "FileHashID": "73d95a30c812d9cff0eaf37a686fdfef8f9ca531",
                "ExtractingStatus": 1,
                "ExtractionErrorMessage": ""
            }
        ],
        "Meta": {
            "Result": 1,
            "ErrorCode": 0,
            "ErrorMsg": ""
        },
        "PermissionCtrl": {
            "permission": "255",
            "elements": null
        },
        "FeatureCtrl": {
            "mode": "0"
        },
        "SystemCtrl": {
            "TmcmSoDist_Role": "none"
        }
    }
    Note:

    If the ExtractingStatus value is 1, the objects were successfully extracted.

  4. Retrieve the UDSO list, and assign the response value to r.

    For more information about the "List UDSO entries" API, see https://automation.trendmicro.com/apex-central/api#operation/SuspiciousObjects_QueryUserDefinedSO.

    print('Retrieving the objects in the User-Defined Suspicious Objects list.')
    productAgentAPIPath = '/WebApp/api/SuspiciousObjects/UserDefinedSO/'
    canonicalRequestHeaders = ''
     
    useRequestBody = ''
     
    useQueryString=""
    jwt_token = create_jwt_token(use_application_id, use_api_key, 'GET',
                                  productAgentAPIPath + useQueryString,
                                  canonicalRequestHeaders, useRequestBody, iat=time.time())
     
    headers = {'Authorization': 'Bearer ' + jwt_token , 'Content-Type': 'application/json;charset=utf-8'}
    r = requests.get(use_url_base + productAgentAPIPath + useQueryString, headers=headers, verify=False)
  5. Perform error handling and print the API response.
    if r.status_code !=200 and r.status_code!=201:
      print(r.status_code)
      #insert error handling code
    
    print(json.dumps(r.json(), indent=4))
  6. Verify that the objects were added to the UDSO list.
    200
    {
        "Data": [
            {
                "type": "ip",
                "content": "168.95.1.1",
                "notes": "Suspicious IP address",
                "scan_action": "log",
                "expiration_utc_date": "2020-06-01T16:00:00"
            },
            {
                "type": "file",
                "content": "601F1889667EFAEBB33B8C12572835DA3F027F78",
                "notes": "Small file for test",
                "scan_action": "log",
                "expiration_utc_date": null
            },
            ...
            {
                "type": "ip",
                "content": "5.175.166.35",
                "notes": "",
                "scan_action": "block",
                "expiration_utc_date": null
            }
        ],
        "Meta": {
            "Result": 1,
            "ErrorCode": 0,
            "ErrorMsg": ""
        },
        "PermissionCtrl": {
            "permission": "255",
            "elements": null
        },
        "FeatureCtrl": {
            "mode": "0"
        },
        "SystemCtrl": {
            "TmcmSoDist_Role": "none"
        }
    }