Assign Rules with Recommendation Scans

Recommendation scans identify Intrusion Prevention, Integrity Monitoring, and Log Inspection rules that should be assigned or removed for a computer or policy. The API provides access to the results of recommendation scans for each of these protection modules at the computer and policy levels via the following classes:

  • ComputerIntrusionPreventionAssignmentsRecommendationsApi
  • ComputerIntegrityMonitoringAssignmentsRecommendationsApi
  • ComputerLogInspectionAssignmentsRecommendationsApi
  • PolicyIntrusionPreventionAssignmentsRecommendationsApi
  • PolicyIntegrityMonitoringAssignmentsRecommendationsApi
  • PolicyLogInspectionAssignmentsRecommendationsApi

The methods and functions of these classes return objects that include the latest recommendations and scan information. The following JSON represents the data structure of the returned objects:

{
    "assignedRuleIDs": [],
    "recommendationScanStatus": "valid",
    "lastRecommendationScanDate": "1562702362438",
    "recommendedToAssignRuleIDs": [],
    "recommendedToUnassignRuleIDs": []
}

To run a recommendation scan using the API, you use scheduled tasks. See the Maintain Protection Using Scheduled Tasks guide.

For more information about recommendation scans, see Manage and run recommendation scans in the Deep Security Help Center.

Find when recommendation scans last ran

Obtain the date of the last recommendation scan when you want to make sure your computers have been recently scanned. For example, a computer is not scanned if it is offline when the recommendation scan is scheduled to run. You can run a script that discovers, for each computer in your environment, when a scan last ran. Depending on the results, you can run a recommendation scan as needed.

Use the following general steps to get the date of the last recommendation scan for one or more computers:

  1. Create a ComputersApi object to obtain the ID of the computers to check.
  2. Create a ComputerIntrusionPreventionAssignmentsRecommendationsApi object and use it to list the Intrusion Prevention rule assignments and recommendations.
  3. Obtain the date of the last scan from the returned IntrusionPreventionAssignments object.
When a recommendation scan runs, it determines recommendations for the Intrusion Prevention, Integrity Monitoring, and Log Inspection security modules. Therefore, the methods and functions of the ComputerIntrusionPreventionAssignmentsRecommendationsApiComputerIntegrityMonitoringAssignmentsRecommendationsApi, and ComputerLogInspectionAssignmentsRecommendationsApi return the same value for the date and status of the last scan.

For example, obtain a list of all computers in your environment (you only need the ID so set the expand parameter to none to return the minimal information):

Python
expand = api.Expand(api.Expand.none)
computers_api = api.ComputersApi(api.ApiClient(configuration))
computers = computers_api.list_computers(api_version, expand=expand.list(), overrides=False)
JavaScript
const getListOfComputers = () => {
  const computersApi = new api.ComputersApi();= api.Expand.OptionsEnum;
  const expand = new api.Expand.Expand(Options.none);
  const opts = {
    expand: expand.list(),
    overrides: false,
  };
  return computersApi.listComputers(apiVersion, opts);
};
Java
// Include minimal information in the returned Computer objects
Expand expand = new Expand(Expand.OptionsEnum.NONE);= new ComputersApi();
Computers computers = computersApi.listComputers(expand.list(), Boolean.FALSE, apiVersion);

For each computer, obtain the applied rules and recommendation scan results:

Python
computer_ips_assignments_recommendations_api = (
    api.ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi(api.ApiClient(configuration)))
intrusion_prevention_assignments = (
    computer_ips_assignments_recommendations_api.list_intrusion_prevention_rule_ids_on_computer(
        computer.id,
        api_version,
        overrides=False)
JavaScript
const computerIntrusionPreventionRuleAssignmentsRecommendationsApi = new api.ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi();
const opts = {
  overrides: false
};
computerIntrusionPreventionRuleAssignmentsRecommendationsApi.listIntrusionPreventionRuleIDsOnComputer(computerObj.ID, apiVersion, opts);
Java
ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi ipRulesRecApi = new ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi();
Boolean overrides = Boolean.FALSE;
IntrusionPreventionAssignments ipAssignments = ipRulesRecApi.listIntrusionPreventionRuleIDsOnComputer(computer.getID(), overrides, apiVersion);

Finally, extract the date of the last scan. Note that when no recommendation scan has run, the property is None (Python), undefined (JavaScript), or null (Java):

Python
reco_scan_info = list()
if intrusion_prevention_assignments.last_recommendation_scan_date is not None:
    d = datetime.datetime.utcfromtimestamp(intrusion_prevention_assignments.last_recommendation_scan_date/1000)
    reco_scan_info.append(d.strftime('%Y-%m-%d %H:%M:%S'))
else:
    reco_scan_info.append("No scan on record")
JavaScript
let scanInfo = [];
if (intrusionPreventionAssignments.lastRecommendationScanDate !== undefined) {
  scanInfo.push(new Date(intrusionPreventionAssignments.lastRecommendationScanDate).toString());
} else {
  scanInfo.push("No scan on record");
}
Java
List<String> recoScanInfo = new ArrayList<>();
if (ipAssignments.getLastRecommendationScanDate() != null) {
	Long lastScanSinceEpoch = ipAssignments.getLastRecommendationScanDate();
	scanInfo.push(new Date(intrusionPreventionAssignments.lastRecommendationScanDate).toString());
} else {
	recoScanInfo.add("No scan on record");
}

Also see the List Intrusion Prevention Rule IDs operation in the API Reference.

Example: Get the date of the last recommendation scan for all computers

The following example retrieves a list of all computers and determines the date and status of the last recommendation scan. The information, along with the computer hostnames, are returned in comma separated value (CSV) format that can be opened as a spreadsheet.

Python

View source

# Include minimal information in the returned Computer objects
expand = api.Expand(api.Expand.none)
try:
    # Get the list of computers and iterate over it
    computers_api = api.ComputersApi(api.ApiClient(configuration))
    computers = computers_api.list_computers(api_version, expand=expand.list(), overrides=False)
    computer_ips_assignments_recommendations_api = (
        api.ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi(api.ApiClient(configuration)))
    for computer in computers.computers:
        # Get the recommendation scan information
        intrusion_prevention_assignments = (
            computer_ips_assignments_recommendations_api.list_intrusion_prevention_rule_ids_on_computer(
                computer.id,
                api_version,
                overrides=False))
        reco_scan_info = list()
        # Computer name
        reco_scan_info.append(computer.host_name)
        # Scan date
        if intrusion_prevention_assignments.last_recommendation_scan_date is not None:
            d = datetime.datetime.utcfromtimestamp(intrusion_prevention_assignments.last_recommendation_scan_date/1000)
            reco_scan_info.append(d.strftime('%Y-%m-%d %H:%M:%S'))
        else:
            reco_scan_info.append("No scan on record")
        # Scan status
        reco_scan_info.append(intrusion_prevention_assignments.recommendation_scan_status)
        # Add to the CSV string
        csv += format_for_csv(reco_scan_info)
    return csv
JavaScript

View source

// Obtains a list of all computers
const getListOfComputers = () => {
  const computersApi = new api.ComputersApi();= api.Expand.OptionsEnum;
  const expand = new api.Expand.Expand(Options.none);
  const opts = {
    expand: expand.list(),
    overrides: false,
  };
  return computersApi.listComputers(apiVersion, opts);
};= computerObj => {
  return new Promise((resolve, reject) => {= new api.ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi();
    const opts = {
      overrides: false,
    };
    computerIntrusionPreventionRuleAssignmentsRecommendationsApi
      .listIntrusionPreventionRuleIDsOnComputer(computerObj.ID, apiVersion, opts)
      .then(intrusionPreventionAssignments => {
        let scanInfo = [];scanInfo.push(computerObj.hostName);(intrusionPreventionAssignments.lastRecommendationScanDate !== undefined) {
          scanInfo.push(new Date(intrusionPreventionAssignments.lastRecommendationScanDate));
        } else {
          scanInfo.push('No scan on record');
        }scanInfo.push(intrusionPreventionAssignments.recommendationScanStatus);
        resolve(scanInfo);
      })
      .catch(error => {
        reject(error);
      });
  });
};comma-separated values string
const date = new Date(Date.now());
let csv = date.getUTCDate() + '-' + date.getUTCMonth() + '-' + date.getUTCFullYear() + '\r\n';
csv += 'Host Name, Last Scan Date, Scan Status\r\n';
let scanInfoPromises = [];// Get all computers and extract the recommendation scan information
return getListOfComputers()
  .then(computers => {
    for (const computer of computers.computers) {
      scanInfoPromises.push(getRcommendationScanInfo(computer));
    }Promise.all(scanInfoPromises);
  })
  .then(allComputersScanInfo => {allComputersScanInfo.forEach(computerScanInfo => {
      csv += formatForCSV(computerScanInfo);
    });
    resolve(csv);
  })
  .catch(error => {
    reject(error);
  });
Java

View source

// Add the current date to the report
StringBuilder csv = new StringBuilder(LocalDateTime.now().toString() + "\r\n");comma-separated values
csv.append("Host Name, Last Scan Date, Scan Status\r\n");= new Expand(Expand.OptionsEnum.NONE);= new ComputersApi();
Computers computers = computersApi.listComputers(expand.list(), Boolean.FALSE, apiVersion);
for (Computer computer : computers.getComputers()) {
	List<String> recoScanInfo = new ArrayList<>();recoScanInfo.add(computer.getHostName());= new ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi();
	Boolean overrides = Boolean.FALSE;
	IntrusionPreventionAssignments ipAssignments = ipRulesRecApi.listIntrusionPreventionRuleIDsOnComputer(computer.getID(), overrides, apiVersion);(ipAssignments.getLastRecommendationScanDate() != null) {
		Long lastScanSinceEpoch = ipAssignments.getLastRecommendationScanDate();
		LocalDateTime lastScanUTC = LocalDateTime.ofInstant(Instant.ofEpochMilli(lastScanSinceEpoch.longValue()), ZoneOffset.UTC);
		recoScanInfo.add(lastScanUTC.toString());
	} else {
		recoScanInfo.add("No scan on record");
	}recoScanInfo.add(ipAssignments.getRecommendationScanStatus().getValue());csv.append(formatForCSV(recoScanInfo));
}
return csv.toString();

Apply recommendations

The API provides access to the recommendation scan results that have been made for a computer for the integrity monitoring, intrusion prevention, and log inspection modules. Use a ComputerIntrusionPreventionAssignmentsRecommendationsApi object to obtain an IntrusionPreventionAssignments object for a computer. The IntrusionPreventionAssignments object contains and provides access to the recommendations for that computer:

  • Recommended Intrusion Prevention rules to assign and unassign
  • Scan status
  • When the last scan occurred

After you obtain the rule recommendations, you can apply them to computer policies, as illustrated in the Add intrusion prevention rules to computers’ policies example.

When there has been no recommendation scan performed on a computer, ComputerIntrusionPreventionAssignmentsRecommendationsApi returns null for rule IDs and the last scan occurrence.

Similar classes are provided for the integrity monitoring and log inspection modules:

  • ComputerIntegrityMonitoringAssignmentsRecommendationsApi and IntegrityMonitoringAssignments
  • ComputerLogInspectionAssignmentsRecommendationsApi and LogInspectionAssignments

The following example obtains the recommendations for Intrusion Prevention for a computer.

Python

View source

ip_recommendations_api = api.ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi(api.ApiClient(configuration))
ip_assignments = None
try:
    ip_assignments = ip_recommendations_api.list_intrusion_prevention_rule_ids_on_computer(computer_id, api_version, overrides=False)
    return ip_assignments.recommended_to_assign_rule_ids
except api_exception as e:
    return "Exception: " + str(e)
JavaScript

View source

// Obtains the results of the recommendation scan
const getRecommendations = () => {
  const ipRecosApi = new api.ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi();
  return ipRecosApi.listIntrusionPreventionRuleIDsOnComputer(computerID, apiVersion, { overrides: false });
};
getRecommendations()
  .then(ipAssignments => {resolve(ipAssignments.assignedRuleIDs);
  })
  .catch(error => {
    reject(error);
  });
Java

View source

ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi ipRecosApi = new ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi();
IntrusionPreventionAssignments ipAssignments = null;
ipAssignments = ipRecosApi.listIntrusionPreventionRuleIDsOnComputer(computerID, Boolean.FALSE, apiVersion);
Also see the List Intrusion Prevention Rule IDs operation in the API Reference. For information about authenticating API calls, see Authenticate with Deep Security Manager.