First Steps Toward Deep Security Automation

The Deep Security API enables you to automate operational tasks, thereby increasing the productivity of your value stream and improving the security services that you support:

  • Configure policies and common objects
  • Provide security services for new computers
  • Discover vulnerabilities and patch them
  • Perform routine maintenance tasks

If you want to learn about the features and abilities of Deep Security, go to the Deep Security Help Center.

The API and SDK – DevOps tools for automation

The Deep Security API is a RESTful API that you use to make HTTP requests to interact with Deep Security Manager. The SDK includes client libraries that help you to use the API in the following languages:

The API Reference provides information about each resource that you interact with:

  • Descriptions of operations that you can perform on each resource (GET, POST, etc)
  • Request paths, headers, and payloads
  • Examples of requests and response messages

Guides, such as this one, provide an introduction to the API with examples and explanations of how to automate typical Deep Security operational tasks.

Set up your development environment

The environment where you develop your software requires the following items:

  • Network access to a running Deep Security Manager, either one that you installed or one provisioned by Deep Security as a Service.
  • An SDK client library, if you choose to use one. Go to the Python SDK page, the JavaScript SDK page, or the Java SDK page to download the client library and learn how to add it to your development environment.
  • The runtime environment for the programming language of your client library.

Tip: To start exploring the API right away, instead of using the client library you can use an HTTP client such as Postman, Paw, or curl.

Authenticate with Deep Security Manager

Deep Security Manager uses API keys for authenticating HTTP requests. Each request that you make requires an api-secret-key header that contains a secret key, as in the following example request:

GET /api/policies HTTP/1.1
Host: localhost:4119
api-secret-key: 2:vJC6lckDygB6FYURIvR0WK2ZTAhIY8rb0Amy9UMn4mo=
api-version: v1

When using a client library, you obtain an instance of ApiClient  and configure it to use your secret key. The configuration is global, so that all calls to the API thereafter are authenticated using the secret key. The GET and POST examples below show how to create and configure ApiClient.

The manager uses the secret to authenticate your request. Each API key is associated with a role that determines the actions that you can perform.

Create an API key

Create an API key to use for authenticating your requests with Deep Security Manager. When you create an API key, you provide a name, the role to associate with the key, and optionally an expiry date. For more information, see Create and Manage API Keys.

Note: You require administrator privileges to create an API key.

Upon creation of an API key, you are provided a unique secret key that is associated with the API key. You include this secret key in the HTTP request for authenticating. You must store the secret key when it is provided because at no other time are you able to obtain it. If you lose the secret you must create a new API key or create a new secret for the key.

The Creating a Trend Micro Deep Security API Key video steps you through the process.
  1. In Deep Security Manager, click Administration > User Management > System API Keys.
  2. Click New and enter the property values for the key.
  3. Click Next.
    The secret is presented. This is the only time that you can obtain the secret.
  4. Copy the secret and securely store it.
  5. Click Close.

API versions

The API is versioned. Each request that you make must include the version to use in the api-version header. The first version is v1.

Although new versions are rarely released, you must ensure that the API version you are using is compatible with the Deep Security Manager with which you are interacting. However, Deep Security Manager is backward-compatible with all versions of the API. For example, if your code uses the v1 API and you upgrade the manager, your code behavior does not change. However, you should always use the latest available version of the API.

Perform a GET request: list policies

To start exploring the API, go to the List Policies operation in the Policies section of the API reference. Notice that List Policies is a GET request on the policies endpoint:

get /policies

Use an HTTP client

To send the request right away use Postman, Paw, or curl. Use the following information to create the request:

  • URL: https://<Manager host name>:<port>/api/policies, for example https://localhost:4119/api/policies
  • First header:
    • Key: api-secret-key
    • Value: <your key secret>
  • Second header:
    • Key: api-version
    • Value: v1

Example curl command:

curl -X GET https://localhost:4119/api/policies -H 'api-secret-key: 5:W+lC8YHIaYHeQuDbJZLkqwM5b8xjxla2pHtBNoiifF8=' -H 'api-version: v1'

Tip: If your Deep Security Manager is using a self-signed certificate to establish a secure connection, in the Postman settings, turn off SSL certificate verification. For Paw, in the Network preferences clear Validate SSL Certificates. For curl, include the --insecure option.

Use a client library

The following example code creates an ApiClient object that configures authentication with Deep Security Manager. A PoliciesApi object is then created and used to list all policies.

Python
Use the following steps to run the example.

  1. Create a file named first_steps_get_example.py and copy the following example code to the file.
    import deepsecurity as api
    from deepsecurity.rest import ApiException as api_exception
    
    
    def get_policies_list(api, configuration, api_version, api_exception):
        """ Gets a list of policies on the Deep Security Manager
    
        :return: A PoliciesApi object that contains a list of policies.
        """
    
        try:
            # Create a PoliciesApi object
            policies_api = api.PoliciesApi(api.ApiClient(configuration))
    
            # List policies using version v1 of the API
            policies_list = policies_api.list_policies(api_version)
    
            # View the list of policies
            return policies_list
    
        except api_exception as e:
            return "Exception: " + str(e)
    
    if __name__ == '__main__':
        # Add Deep Security Manager host information to the api client configuration
        configuration = api.Configuration()
        configuration.host = 'https://192.168.17.149:4119/api'
    
        # Authentication
        configuration.api_key['api-secret-key'] = '2:l069trAePqPRxZUfBqyw442z1DWm9s4u0F/g9bewnFE='
    
        # Version
        api_version = 'v1'
        print(get_policies_list(api, configuration, api_version, api_exception))
  2. Locate the following code and change the URL and secret key according to your environment:
    • configuration.host = 'https://192.168.17.149:4119/api'
    • configuration.api_key['api-secret-key'] = '2:l069trAePqPRxZUfBqyw442z1DWm9s4u0F/g9bewnFE='
  3. Open a Command Prompt (Windows) or terminal (Linux) and enter the following command:
    python first_steps_get_example.py
JavaScript
Use the following steps to run the example.

  1. Create a file named FirstStepsGetExample.js and copy the following example code to the file.
    exports.getPolicies = function(hostNameAndPort, apiSecretKey) {
      return new Promise((resolve, reject) => {
        // Deep Security module
        const api = require("@trendmicro/deepsecurity");
    
        // Create the client
        const defaultClient = api.ApiClient.instance;
        defaultClient.basePath = "https://" + hostNameAndPort + "/api";
        const defaultAuthentication = defaultClient.authentications["DefaultAuthentication"];
        defaultAuthentication.apiKey = apiSecretKey;
    
        // Allow connection that is 'secured' with self-signed certificate - for development only
        process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    
        // Create a PoliciesApi object
        const policiesApi = new api.PoliciesApi();
    
        // List policies. Use version v1 of the API
        policiesApi.listPolicies("v1")
          .then(policies => {
            resolve(policies);
          })
          .catch(error => {
            reject(error);
          });
      });
    };
  2. Create another file named App.js and copy the following code to the file:
    const path = require("path");
    
    const FirstStepsGetExample = require(path.resolve(__dirname, "./FirstStepsGetExample.js"));
    
    FirstStepsGetExample.getPolicies("localhost:4119", "3:zNi5ag8xPGpfEMElV0GxAIpTs5Ji8BQoCtXaTAgKkVM=")
      .then( policies => {
        console.log(policies);
      })
      .catch(error => {
        console.log(error);
    });
  3. In the App.js file, change the URL and secret key parameters of the call to FirstStepsGetExample.getPolicies according to your environment.
  4. Open a Command Prompt (Windows) or terminal (Linux) and enter the following command:
    node App.js
Java
Use the following steps to compile and run the class

  1. Create a file named FirstStepsGetExample.java and copy the following example code to the file.
    package com.trendmicro.deepsecurity.docs;
    
    import com.trendmicro.deepsecurity.ApiClient;
    import com.trendmicro.deepsecurity.ApiException;
    import com.trendmicro.deepsecurity.Configuration;
    import com.trendmicro.deepsecurity.api.PoliciesApi;
    import com.trendmicro.deepsecurity.auth.ApiKeyAuth;
    import com.trendmicro.deepsecurity.model.Policies;
    import com.trendmicro.deepsecurity.model.Policy;
    
    public class FirstStepsGetExample {
      /*
       * Retrieves all policies and prints the names.
       */
      public static void main(String[] args){
        //Create the client
        ApiClient dsmClient = Configuration.getDefaultApiClient();
        dsmClient.setBasePath("https://192.168.60.128:4119/api");
        ApiKeyAuth DefaultAuthentication = (ApiKeyAuth) dsmClient.getAuthentication("DefaultAuthentication");
        DefaultAuthentication.setApiKey("3:/tiKl3+6ritnk4tQXipq5ufIls5nCFqoGoUcWl+imTU=");  
        
        //Create a PoliciesApi object
        PoliciesApi policiesApi = new PoliciesApi();
        try {
          //List policies. Use version v1 of the API.
          Policies policies = policiesApi.listPolicies(false, "v1");  
          for (Policy policy : policies.getPolicies()){
            System.out.println(policy.getName());
          }
        } catch (ApiException e) {
          e.printStackTrace();
        }
      }
    }
  2. Locate the following code and change the URL and secret key according to your environment:
    • dsmClient.setBasePath("https://192.168.60.128:4119/api");
    • DefaultAuthentication.setApiKey("3:/tiKl3+6ritnk4tQXipq5ufIls5nCFqoGoUcWl+imTU=");
  3. To compile the Java class, open a Command Prompt (Windows) or terminal and enter the following command:
    javac -d . -cp <path to java client library> FirstStepsGetExample.java
  4. To execute the class, enter the following command:
    • Windows:
      java -cp ".;<path to java client library>" com.trendmicro.ds.docs.api_examples.FirstStepsGetExample
    • Linux:
      java -cp ".:<path to java client library>" com.trendmicro.ds.docs.api_examples.FirstStepsGetExample

Perform a POST request: search firewall rules

Perform a POST request to search for firewall rules. In the API reference, the Search Firewall Rules operation (Firewall Rules section) for the firewallrules endoint is a POST request to the path firewallrules/search.

post /firewallrules/search

The API reference also shows a series of parameters that you use in the request body. For Search Firewall Rules, each parameter is a search criterium. In this example we search for the ID of 3.

Use an HTTP client to post

Use the following information to create the request in Postman or Paw:

  • Request type: POST
  • URL: https://<Deep Security Manager hostname>:<port>/api/firewallrules/search, for example https://localhost:4119/api/firewallrules/search
  • First header:
    • Key: api-secret-key
    • Value: your key secret
  • Second header:
    • Key: api-version
    • Value: v1
  • Third header:
    • Key: Content-Type
    • Value: application/json

Also, add the following raw code to the body:

{
  "searchCriteria": [{
    "idTest":"equal",
    "idValue":3
  }]
}

Example curl command:

curl -X POST https://localhost:4119/api/firewallrules/search \
-H 'Cache-Control: no-cache' \
-H 'api-secret-key: 3:zNi5ag8xPGpfEMElV0GxAIpTs5Ji8BQoCtXaTAgKkVM=' \
-H 'api-version: v1' \
-H 'content-type: application/json' \
-d '{
  "searchCriteria": [{
    "idTest":"equal",
    "idValue":3
  }]
}'

Use a client library to post

The following example creates a SearchFilter object that defines search criteria. The SearchFilter object is then used as a parameter of the searchFirewallRules method of aModuleFirewallApi object.

Python
Use the following steps to run the example.

    1. Create a file named first_steps_post_example.py and copy the following example code to the file.
      import deepsecurity as api
      from deepsecurity.rest import ApiException as api_exception
      
      def search_firewall_rules(api, configuration, api_version, api_exception):
          """ Searches the firewall rules for any rule that contains DHCP in the rule name.
      
          :param api: The Deep Security API modules.
          :param configuration: Configuration object to pass to the api client.
          :param api_version: The version of the API to use.
          :param api_exception: The Deep Security API exception module.
          :return: A list containing all firewall rules that match the search criteria.
          """
      
          # Define the search criteria
          search_criteria = api.SearchCriteria()
          search_criteria.field_name = "name"
          search_criteria.string_value = "%DHCP%"
          search_criteria.string_test = "equal"
          search_criteria.string_wildcards = True
      
          # Create search filter to find the rule
          search_filter = api.SearchFilter(None,[search_criteria])
      
          # Create a FirewallRulesApi object
          firewall_rules_api = api.FirewallRulesApi(api.ApiClient(configuration))
      
          try:
              # Perform the search
              firewall_rules = firewall_rules_api.search_firewall_rules(api_version, search_filter=search_filter)
              firewall_rules_list = []
              for rule in firewall_rules.firewall_rules:
                  firewall_rules_list.append(rule)
              return firewall_rules
      
          except api_exception as e:
              return "Exception: " + str(e)
      
      if __name__ == '__main__':
          # Add Deep Security Manager host information to the api client configuration
          configuration = api.Configuration()
          configuration.host = 'https://192.168.17.149:4119/api'
      
          # Authentication
          configuration.api_key['api-secret-key'] = '2:l069trAePqPRxZUfBqyw442z1DWm9s4u0F/g9bewnFE='
      
          # Version
          api_version = 'v1'
          print(search_firewall_rules(api, configuration, api_version, api_exception))
    2. Locate the following code and change the URL and secret key according to your environment:
      • configuration.host = 'https://192.168.17.149:4119/api'
      • configuration.api_key['api-secret-key'] = '2:l069trAePqPRxZUfBqyw442z1DWm9s4u0F/g9bewnFE='
    3. Open a Command Prompt (Windows) or terminal (Linux) and enter the following command:
      python first_steps_post_example.py
JavaScript

Use the following steps to run the example.

  1. Create a file named FirstStepsPostExample.js and copy the following example code to the file.
    exports.searchFirewallRules = function(hostNameAndPort, apiSecretKey) {
      return new Promise((resolve, reject) => {
        
      // Deep Security module
      const api = require("@trendmicro/deepsecurity");
    
      // Create the client
      const defaultClient = api.ApiClient.instance;
      defaultClient.basePath = "https://" + hostNameAndPort + "/api";
      const defaultAuthentication = defaultClient.authentications["DefaultAuthentication"];
      defaultAuthentication.apiKey = apiSecretKey;
    
      // Allow connection that is 'secured' with self-signed certificate - for development only
      process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    
      // Define the search criteria
      const searchCriteria = new api.SearchCriteria();
      searchCriteria.fieldName = "name";
      searchCriteria.stringValue = "%DHCP%";
      searchCriteria.stringTest = api.SearchCriteria.StringTestEnum.equal;
      searchCriteria.stringWildcards = true;
    
      // Create a search filter to find the rule
      const searchFilter = new api.SearchFilter();
      searchFilter.searchCriteria = [searchCriteria];
      
      // Add the search filter to a search options object
      const searchOptions = {
        searchFilter: searchFilter,
        overrides: false
      }
    
      // Create a FirewallRulesApi object
      const fwRulesApi = new api.FirewallRulesApi();
    
      // Perform the search and handle the returned promise
      fwRulesApi.searchFirewallRules("v1", searchOptions)
        .then(data => { 
          resolve(data.firewallRules);
        })
        .catch(error => {
          reject(error);
        });
      });
    };
  2. Create another file named App.js and copy the following code to the file:
    const path = require("path");
    const FirstStepsPostExample = require(path.resolve(__dirname, "./FirstStepsPostExample.js"));
    
    FirstStepsPostExample.searchFirewallRules("localhost:4119", "3:zNi5ag8xPGpfEMElV0GxAIpTs5Ji8BQoCtXaTAgKkVM=")
      .then( firewallRules => {
        for (let i in firewallRules) {
            console.log(`${firewallRules[i].ID} ${firewallRules[i].name}`);
          }
      })
      .catch(error => {
        console.log(error);
      });
  3. In the App.js file, change the URL and secret key parameters of the call to FirstStepsPostExample.searchFirewallRules according to your environment.
  4. Open a Command Prompt (Windows) or terminal (Linux) and enter the following command:
    node App.js
Java
Use the following steps to compile and run the class

  1. Create a file named FirstStepsPostExample.java and copy the following example code to the file.
    package com.trendmicro.deepsecurity.docs;
    
    import com.trendmicro.deepsecurity.ApiClient;
    import com.trendmicro.deepsecurity.ApiException;
    import com.trendmicro.deepsecurity.Configuration;
    import com.trendmicro.deepsecurity.api.FirewallRulesApi;
    import com.trendmicro.deepsecurity.auth.ApiKeyAuth;
    import com.trendmicro.deepsecurity.model.FirewallRule;
    import com.trendmicro.deepsecurity.model.FirewallRules;
    import com.trendmicro.deepsecurity.model.SearchCriteria;
    import com.trendmicro.deepsecurity.model.SearchFilter;
    
    public class FirstStepsPostExample {
      /*
       * Searches for firewall rules that contain 'DHCP' in the name.
       */
      public static void main(String[] args){
        //Create the client
        ApiClient dsmClient = Configuration.getDefaultApiClient();
        dsmClient.setBasePath("https://192.168.60.128:4119/api");
        ApiKeyAuth DefaultAuthentication = (ApiKeyAuth) dsmClient.getAuthentication("DefaultAuthentication");
        DefaultAuthentication.setApiKey("3:fkZjcAuvj9ZWhdXgVvFl4Q3DymDZTKHOE3EDDqYPwdg=");  
    
        //Create the search criteria
        SearchCriteria searchCriteria = new SearchCriteria();
        searchCriteria.setFieldName("name");
        searchCriteria.setStringValue("%DHCP%");
        searchCriteria.setStringTest(SearchCriteria.StringTestEnum.EQUAL);
        searchCriteria.setStringWildcards(true);
        //Create the search filter
        SearchFilter searchFilter = new SearchFilter();
        searchFilter.addSearchCriteriaItem(searchCriteria);
    
        //Use FirewallRulesApi to search
        FirewallRulesApi fwRulesApi = new FirewallRulesApi();
        try {
          FirewallRules fwrules = fwRulesApi.searchFirewallRules(searchFilter, "v1");
          for (FirewallRule fwrule : fwrules.getFirewallRules()){
            System.out.println(fwrule.getName());
          }
        } catch (ApiException e) {
          e.printStackTrace();
        }
      }
    }
  2. Locate the following code and change the URL and API key secret according to your environment:
    • dsmClient.setBasePath("https://192.168.60.128:4119/api");
    • DefaultAuthentication.setApiKey("3:/tiKl3+6ritnk4tQXipq5ufIls5nCFqoGoUcWl+imTU=");
  3. To compile the Java class, open a Command Prompt (Windows) or terminal and enter the following command:
    javac -d . -cp <path to java client library> FirstStepsPostExample.java
  4. To execute the class, enter the following command:
    • Windows:
      java -cp ".;<path to java client library>" com.trendmicro.ds.docs.api_examples.FirstStepsPostExample
    • Windows:
      java -cp ".;&lt:path to java client library>" com.trendmicro.ds.docs.api_examples.FirstStepsPostExample

Run the code examples in the guides

The code examples in other Automation Center guides are structured differently than those in the First Steps guide. The following section describes how to create a framework for running the code examples for the SDK in each language.

Create a framework for running the code examples in the guides

Python

To run the code examples, create a framework for the Python client library that uses a main script to import the client library and configure authentication with the Deep Security Manager. Save the code examples in a separate file. The main script imports  this file as a module, runs the functions of the file to make API calls to the Deep Security Manager and prints the returned output.

The below example shows how to run the code examples from the Configure Policy, Computer, and System Settings guide:

  1. Create a file named settings_examples.py and save the code examples from the Configure Policy, Computer, and System Settings guide into it.
  2. Create a file named properties.json and save the following JSON code into it, replacing the values for “url”  and “secretkey” with the URL and API key for your DSM:
    {
        "url": "https://192.168.17.143:4119/api",
        "secretkey": "2:HNVgA9U0Gf1F/+GtKB58ITFJkoCVxysoz/vTi5NmLPk="
    }

    Note: The Deep Security Manager URL and API key are sensitive data. By storing them outside of your script, you can prevent them from entering any shared spaces or repositories your scripts belong to.

  3. Create a file named main.py and save the following code into it:
    import deepsecurity as api
    from deepsecurity.rest import ApiException as api_exception
    
    # Get the DSM URL and API key from the properties.json file
    import json
    
    with open('properties.json') as raw_properties:
        properties = json.load(raw_properties)
    
    secret_key = properties['secretkey']
    url =  properties['url']
    
    # Add the DSM information to the API client configuration
    configuration = api.Configuration() # Create a Configuration object
    configuration.host = url  # Set the URL of the DSM
    configuration.api_key['api-secret-key'] = secret_key  # Set the secret key for the DSM
    
    # Add the API version to a global variable
    api_version = 'v1'
    
    # Import the file with the code examples from the Create and Configure Policies guide
    import settings_examples
    
    # Add any additional global variables that will be shared across your functions
    # Variables for Settings examples
    settings_policy_id = 9
    
    def main():
        ''' Run the examples from the Create and Configure Policies guide
    
        Each function call passes the api client configuration information
        and any required variables and prints their output.
        '''
    
        # Settings examples
        print(
            "Displaying results from settings_examples.get_network_engine_mode:\n" +
            str(settings_examples.get_network_engine_mode(
                api, configuration, api_version, api_exception, settings_policy_id))
        )
    
        print(
            "Displaying results from settings_examples.set_network_engine_mode:\n" +
            str(settings_examples.set_network_engine_mode_to_inline(
                api, configuration, api_version, api_exception, settings_policy_id))
        )
    
    if __name__ == '__main__':
        main()
    
  4. Open a command line interface and type python main.py. The main.py script will run the settings_examples.py functions and print the returned output to the console.
JavaScript

To run the code examples, create a framework for the JavaScript client library that uses a main script to import the client library and configure authentication with the Deep Security Manager. Save the code examples in a separate file. The main script imports this file as a module, runs the functions of the file to make API calls to the Deep Security Manager and prints the returned output.

The below example shows how to run the code examples from the Configure Policy, Computer, and System Settings guide:

    1. Create a new folder for your nodeJS project.
    2. Create a symbolic link from your nodeJS project to the @trendmicro/deepsecurity package (see the Link your project to the SDK package section on the JavaScript SDK page).
    3. Create a sub folder named ‘lib’.
    4. In the ‘lib’ folder, Create a file named SettingsExamples.js and save the code examples from the Configure Policy, Computer, and System Settings into it.
    5. Go back to the parent folder of ‘lib’.
    6. Create a file named properties.json and save the following JSON code into it, replacing the values for “url” and “secretkey” with the URL and API key for your DSM:
      {
          "url": "https://192.168.17.143:4119/api",
          "secretkey": "2:HNVgA9U0Gf1F/+GtKB58ITFJkoCVxysoz/vTi5NmLPk="
      }

      Note: The Deep Security Manager URL and API key are sensitive data. By storing them outside of your script, you can prevent them from entering any shared spaces or repositories your scripts belong to.

    7. Create a file named App.js and save the following code into it:
      // Import the client library
      const api = require("@trendmicro/deepsecurity");
      const path = require("path");
      const fs = require('fs');
      
      // Get the DSM URL and API key from the properties.json file
      let rawProperties = fs.readFileSync("properties.json");
      let properties = JSON.parse(rawProperties);
      
      // Assign the API key to a variable
      const secretkey = properties.secretkey;
      
      // Create the client and configure the Deep Security Manager address
      const defaultClient = api.ApiClient.instance;
      defaultClient.basePath = properties.url;
      
      // Configure the client to use the API key
      const DefaultAuthentication = defaultClient.authentications['DefaultAuthentication'];
      DefaultAuthentication.apiKey = secretkey;
      
      // Import the SettingsExample module
      const SettingsExamples = require(path.resolve(__dirname, "lib/SettingsExamples.js"));
      
      // Assign value used by the settings examples to variables
      const settingsPolicyID = 9
      
      // Run functions
      SettingsExamples.getNetworkEngineMode(api, settingsPolicyID, "v1")
      .then(data => {
         console.log("Network engine mode is " + data);
      })
      .then( () => {
      return SettingsExamples.setNetworkEngineModeToInline(api, settingsPolicyID, "v1")
      .then(data => {
          console.log("Network engine mode has been set to " + data);
          })
      })
      .catch(error => {
        console.log(error);
      });
      
    8. Open a command line interface and type node App.js. The App.js script will run the SettingsExamples.js functions and print the returned output to the console.
Java
  • To run the code examples, create a framework for the Java client library that uses a main class to import the client library and configure authentication with the Deep Security Manager. Save the code examples in a separate file. The main class imports this file as a class and runs the methods of the file to make API calls to the Deep Security Manager.
  • You should use a Java IDE. If you don’t already have an IDE installed, we suggest that you use Eclipse. You can find instructions for configuring the client library in the Java SDK guide.
  • The below example shows how to run some of the code examples from the Create and Configure Policies guide:
    • Note: This example uses the package name of com.trendmicro.deepsecurity.docs. If you use a different package name you will need to modify the examples accordingly.

      1. Open the Deep Security project in Eclipse.
      2. Right-click the com.trendmicro.deepsecurity.docs package and click New > Folder. Name the folder ‘Resources’ and click Finish.
      3. Right-click the parent package (for example, com.trendmicro.deepsecurity.docs) and click New > Class, type ‘PolicyExample’ for the name, and click Finish.
      4. In the PolicyExample.java file, below the package declaration, add the following imports:
        import java.lang.reflect.Method;
        import com.trendmicro.deepsecurity.ApiException;
        import com.trendmicro.deepsecurity.model.Computer;
        import com.trendmicro.deepsecurity.model.LogInspectionRule;
        import com.trendmicro.deepsecurity.model.Policies;
        import com.trendmicro.deepsecurity.model.Policy;
        import com.trendmicro.deepsecurity.model.SearchCriteria;
        import com.trendmicro.deepsecurity.model.SearchFilter;
        import com.trendmicro.deepsecurity.api.ComputersApi;
        import com.trendmicro.deepsecurity.api.PoliciesApi;
        import com.trendmicro.deepsecurity.api.PolicyLogInspectionRuleDetailsApi;
      5. Inside the class block, add the following code examples from the Create and Configure Policies guide, then save the file:
        • Create a policy below Base Policy
        • Search for a policy and add it to a computer
        • Selectively reset overrides of a rule
      6. Right-click the ‘Resources’ package and click New > File, name it ‘example.properties’, and click Finish.
      7. Add the following text to the file, and replace the values for “secretkey” and “url” with the URL and API key for your DSM:
        secretkey=2:7jj01PcE9JiHgaXc0Mmo8oMURAgwtkBXV+zn/XcF+iE=
        url=https://192.168.17.143:4119

        Note: The Deep Security Manager URL and API key are sensitive data. By storing them outside of your script, you can prevent them from entering any shared spaces or repositories your scripts belong to.

      8. Right-click the parent package (for example, com.trendmicro.deepsecurity.docs) and click New > Class, type ‘Main’ for the class name, and click Finish.
      9. Overwrite the template code with the following:
        package com.trendmicro.deepsecurity.docs;
        
        import java.io.IOException;
        import java.io.InputStream;
        import java.util.Properties;
        import java.util.concurrent.ThreadLocalRandom;
        
        import com.trendmicro.deepsecurity.ApiClient;
        import com.trendmicro.deepsecurity.Configuration;
        import com.trendmicro.deepsecurity.auth.ApiKeyAuth;
        
        import com.trendmicro.deepsecurity.docs.PolicyExample;
        import com.trendmicro.deepsecurity.model.Policy;
        
        /*
         * A simple framework for running code examples from the Deep Security Automation Center guides.
         */
        public class Main {
        	
        	//Values to use for example method arguments. Edit according to your environment.
        	private static String policyName = "Test Policy " + ThreadLocalRandom.current().nextInt(1, 1000);  //Random suffix avoids collisions
        	private static Integer computerID = new Integer(1);
        	private static Integer policyID = new Integer(8);
        	private static Integer liRuleID = new Integer(20);
        
        	public static void main(String[] args) {
        
        		//Retrieve the DSM url and secret key from the properties file
        		Properties prop = new Properties();
        		ClassLoader loader = Thread.currentThread().getContextClassLoader();           
        		InputStream stream = loader.getResourceAsStream("com/trendmicro/deepsecurity/docs/Resources/example.properties");
        		try {
        			prop.load(stream);
        		} catch (IOException e) {
        			System.out.println(e.getMessage());
        			e.printStackTrace();
        		}
        
        		//Configure ApiClient
        		ApiClient dsmClient = Configuration.getDefaultApiClient();
        		dsmClient.setBasePath(prop.getProperty("url") + "/api");
        		ApiKeyAuth DefaultAuthentication = (ApiKeyAuth) dsmClient.getAuthentication("DefaultAuthentication");
        		DefaultAuthentication.setApiKey(prop.getProperty("secretkey"));
        
        		//Run the policy examples
        		runPolicyExamples();
        	}
        
        	/*
        	 * Runs the examples in the com.trendmicro.deepsecurity.docs.PolicyExample class.
        	 * The policy name, computer ID, and Log Inspection rule ID values are stored
        	 * in global variables.
        	 */
        	private static void runPolicyExamples() {
        		PolicyExample policyExample = new PolicyExample();
        		Policy testPolicy = policyExample.createPolicy(policyName);
        		policyExample.assignLinuxServerPolicy(computerID);
        		policyExample.selectiveResetForLogInspectionRuleOnPolicy(policyID, liRuleID);
        	}
        
        }
      10. To run the code examples, click Run > Run As > Java Application.

    You should also know…

    There are a few things that you should be aware of while using the API and the client libraries.

    Express a null value

    To express a null value using the API, use 0 (zero). For example, when you use 0 as the policyID for a computer it is interpreted as null, and that the computer has no assigned policy.

    Note that this applies when using the API directly. The client libraries support the use of null values.

    Valid values for boolean properties

    When you use the API, you must use either true or false for the values of boolean properties. Any other value returns an error.

    If you do not provide a value (i.e. null), false is the default value.

    Updates include only changed values

    When you use an operation to modify a resource, you provide only the properties that you need to change. For example, to change the name of a policy, you provide a policy object with a name property, and all other properties are null or not specified. This pattern is typical for REST API’s.

    When using programming languages such as Python or Java, you might be accustomed to obtaining an object that represents the resource, changing a property, and then returning the object in the update call. However, when using the Deep Security client libraries you create an object, set only the values that you want to change, and then use that object in the update call.

    Python
    policy = api.Policy()
    policy.name = policy_name
    policy_api = api.PoliciesApi()
    policy_api.modifyPolicy(policyID, policy, false, "v1")
    
    JavaScript
    let policy = new api.Policy();
    policy.name = policyName;
    const policiesApi = new api.PoliciesApi();
    policiesApi.modifyPolicy(policyID, policy, apiVersion, { overrides:false } )
      .then (returnedPolicy => {
        console.log("Policy successfully updated.");
      })
      .catch (error => {
        console.log(error);
      });
    Java
    Policy policy = new Policy();
    policy.setName(policyName);
    PoliciesApi policiesApi = new PoliciesApi();
    policiesApi.modifyPolicy(policyID, policy, false, "v1");
    

    The overrides parameter

    Many API operations define an overrides parameter that controls whether the response includes only overrides that are configured on the targeted resource (overrides = true), or includes both overrides and property values that the resource inherits (overrides = false).

    For example, the Describe a Policy operation of the policies endpoint returns a policy object for a specific policy on Deep Security Manager. This endpoint defines an overrides parameter that determines which property values are returned for the targeted policy:

    • overrides = false: The returned policy object includes the property values that are inherited from the parent policy, as well as the property values that the policy overrides.
    • overrides = true: The returned policy object includes only the properties that the policy overrides.

    For operations that create or modify a resource, the overrides parameter applies to the created or modified object that the response contains. For example, you use the Create a Policy operation to create a policy that has the Base Policy as the parent, and turns on the Application Control module:

    • overrides = false: The response includes a policy object that has all of the property values of the Base Policy policy, as well as the Application Control status value of on.
    • overrides = true: The response includes a policy object that includes only the Application Control status value of on.

    For operations that search or list resources, the overrides parameter determines which resources are returned, as well as which property values are included. For example, the List Intrusion Prevention Rules operation of the policies endpoint defines an overrides parameter:

    • overrides = false: The returned list includes all Intrusion Prevention rules that are assigned to the targeted policy and the parent policy. All rule properties are included.
    • overrides = true: The returned list includes only the rules that have properties that are overridden in the targeted policy. Furthermore, the rules only include the properties that are overridden.

    For an example of seeing overrides, see Example: Get the overrides for a computer.

    Next steps

    Explore the API Reference or continue with another guide, which are listed on the left.