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
Upload a YARA File

Upload a YARA File

This task encodes and uploads a YARA file to the Apex Central server.

  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 YARA file.

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 YARA File

This task encodes the YARA 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 apt_equation_cryptotable.yara.

  2. Encode the file to Base64.
    file_name='apt_equation_cryptotable.yara'
    # Encoding the YARA file to base 64.
    print('Encoding the YARA file to base 64.')
    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 YARA file" API, see https://automation.trendmicro.com/apex-central/api#operation/YARAResource_POSTFile.

    # Upload the YARA file to the Apex Central server.
    print('Upload the YARA file to the Apex Central server.')
    productAgentAPIPath = '/WebApp/IOCBackend/YARAResource/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('Not successful, please handle your error')
    print(r.status_code)
    print(json.dumps(r.json(), indent=4))
    file_hashID = r.json()["Data"]["UploadedResultInfoList"][0]["FileHashID"]
    print('file hashID:',file_hashID)
  5. Verify that the file was uploaded.

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

    200
    {
        "Data": {
            "UploadedResultInfoList": [
                {
                    "FileName": "apt_equation_cryptotable.yara",
                    "FileHashID": "1ba83c52fc2edd0fb67db398e089d8c1cd35b3aa",
                    "UploadedStatus": 1
                }
            ],
            "UploadedResultMessageList": [
                {
                    "MessageType": 1,
                    "Message": "Uploaded 1 YARA file(s) successfully."
                }
            ]
        },
        "Meta": {
            "Result": 1,
            "ErrorCode": 0,
            "ErrorMsg": ""
        },
        "PermissionCtrl": {
            "permission": "255",
            "elements": null
        },
        "FeatureCtrl": {
            "mode": "0"
        },
        "SystemCtrl": {
            "TmcmSoDist_Role": "none"
        }
    }file hashID: 1ba83c52fc2edd0fb67db398e089d8c1cd35b3aa
  6. Print the value of file_hashID.
    print('file hashID:',file_hashID)
  7. Retrieve the list of YARA files that are stored on the Apex Central server.

    For more information about the "List uploaded YARA files" API, see https://automation.trendmicro.com/apex-central/api#operation/YARAResource_FilingCabinet.

    Note:

    The query string includes the name of the uploaded YARA file.

    # (Optional) Check the result in the YARA file list.
    print('(Optional) Check the result in the YARA file list.')
    productAgentAPIPath = '/WebApp/IOCBackend/YARAResource/FilingCabinet'
    canonicalRequestHeaders = ''
     
    useRequestBody = ''
     
    payload =  {
        "FileHashIDList":[file_hashID],
        "FuzzyMatchString":file_name
      }
    param = json.dumps(payload)
    useQueryString="?param="+urllib.parse.quote(param)
    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'}
    #Choose by call type.
    r = requests.get(use_url_base + productAgentAPIPath + useQueryString, headers=headers, verify=False)
     
    print(r.status_code)
    print(json.dumps(r.json(), indent=4))
  8. Verify that the FilingCabinet value in the response is not a null array [].

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

    200
    {
        "Data": {
            "FilingCabinet": [
                {
                    "FileHashID": "1ba83c52fc2edd0fb67db398e089d8c1cd35b3aa",
                    "FileName": "apt_equation_cryptotable.yara",
                    "FileAddedDatetime": "11/18/2019 14:59:43",
                    "UploadedFrom": 1,
                    "UploadedBy": "test",
                    "ExtractingStatus": 999
                }
            ],
            "TotalIOCCount": 1
        },
        "Meta": {
            "Result": 1,
            "ErrorCode": 0,
            "ErrorMsg": ""
        },
        "PermissionCtrl": {
            "permission": "255",
            "elements": null
        },
        "FeatureCtrl": {
            "mode": "0"
        },
        "SystemCtrl": {
            "TmcmSoDist_Role": "none"
        }
    }