def request_computers(self):
        """Returns a list with all computers in the DS environment"""

        computers_list = []
        api_instance = deepsecurity.ComputersApi(deepsecurity.ApiClient(self.api_config))
        try:
            while True:
                paged_response = api_instance.search_computers(self.api_version,
                    expand=self.COMPUTER_EXPAND, overrides=False, search_filter=self.SEARCH_FILTER)
                computers_list+=paged_response.computers
                last_id = computers_list[-1].id
                self.SEARCH_FILTER.search_criteria.id_value = last_id

                if len(paged_response.computers) != self.SEARCH_FILTER.max_items:
                    break

        except deepsecurity.rest.ApiException as e:
            self.handle_api_exception(e,"COMPUTERS")
        except urllib3.exceptions.MaxRetryError as e:
            raise Exception(self.MAX_RETRY_ERROR_MSG)
        except urllib3.exceptions.LocationParseError:
            raise TypeError( ("API Configuration values on {} are NOT VALID".format(self.API_CONFIG_PATH)))
        except Exception as e:
            raise Exception("Generic connection error!" + str(e) + "Generic connection error!")
        
        self.SEARCH_FILTER.search_criteria.id_value = 0 #Reset the Search Criteria
        return computers_list
コード例 #2
0
def get_affected_instance_in_deep_security(instance_id):
    """
    Find and return the specified instance in Deep Security

    Returns a deepsecurity.computers.Computer object or None
    """
    result = None

    # if not DSM: return result
    DSM_computer = client.ComputersApi(client.ApiClient(configuration))

    try:
        # NEED TO CHANGE THIS CODE TO SEARCH SPECIFIC INSTANCE ID
        search_filter = deepsecurity.SearchFilter()
        overrides = True

        response = DSM_computer.search_computers('v1', search_filter=search_filter, overrides=overrides)

        for computer in response.computers:
            if computer.ec2_virtual_machine_summary.instance_id == instance_id:
                attr = vars(computer)
                print(attr['_id'])
                print(type(attr['_id']))
                return attr['_id']

    except api_exception as ex:
        print("Could not find the instance in Deep Security. Threw exception: {}".format(ex))
コード例 #3
0
def tune_app_control(api, configuration, api_version, api_exception):

    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)

    # Search computer in deep security dashboard
    search_criteria = api.SearchCriteria()
    search_criteria.field_name = "displayName"
    search_criteria.string_value = '%' + search_name + '%'
    search_criteria.string_test = "equal"
    search_criteria.string_wildcards = True

    # Create search filter to find computer
    search_filter = api.SearchFilter(None, [search_criteria])

    # Create a ComputerApi object
    computer_api = api.ComputersApi(api.ApiClient(configuration))

    try:
        # Perform the search
        computer_details = computer_api.search_computers(api_version, search_filter=search_filter)
        ec2_instance_id = []
        ds_ids = []
        for ec2_details in computer_details.computers:
            ec2_instance_id.append(ec2_details.ec2_virtual_machine_summary.instance_id)
            ds_ids.append(ec2_details.id)

        # Set the Reconnaissance Scan value
        setting_value = api.SettingValue()
        setting_value.value = "true"

        # Add the SettingValue to a ComputerSettings object
        computer_settings = api.ComputerSettings()
        computer_settings.firewall_setting_reconnaissance_enabled = setting_value

        app_controll_settings = api.ApplicationControlComputerExtension()
        app_controll_settings.state = app_control_status

        # Add the ComputerSettings object to a Computer object
        computer = api.Computer()
        computer.computer_settings = computer_settings
        computer.application_control = app_controll_settings

        for ds_id in ds_ids:
            computer_api.modify_computer(ds_id, computer, api_version, overrides=True)

        return ec2_instance_id

    except api_exception as e:
        return "Exception: " + str(e)
コード例 #4
0
def lambda_handler(event, context):
    global DSM
    global configuration
    configuration = client.Configuration()
    # DSM_policy = client.PoliciesApi(client.ApiClient(configuration))
    # DSM_client = client.ComputersApi(client.ApiClient(configuration))

    ds_api_key = '2:CC8BLAbBl8VH5sfPFjygafiV7heQc9fkHhDWkNjsxRk='

    ds_hostname = 'app.deepsecurity.trendmicro.com'
    ds_port = '443'

    # ds_ignore_ssl_validation = None
    # if 'dsIgnoreSslValidation' in os.environ: ds_ignore_ssl_validation = os.environ['dsIgnoreSslValidation']

    try:
        # DSM connection string
        configuration.host = 'https://' + ds_hostname + ':' + ds_port + '/api'
        configuration.verify_ssl = False
        # Authentication
        configuration.api_key['api-secret-key'] = ds_api_key
        api_version = 'v1'

        print("Signed into Deep Security")
    except api_exception as ex:
        print(
            "Could not successfully sign into Deep Security. Threw exception: {}"
            .format(ex))

    # From here we have to fetch data
    DSM_computer = client.ComputersApi(client.ApiClient(configuration))

    try:
        # NEED TO CHANGE THIS CODE TO SEARCH SPECIFIC INSTANCE ID
        search_filter = deepsecurity.SearchFilter()
        overrides = False

        response = DSM_computer.search_computers('v1',
                                                 search_filter=search_filter,
                                                 overrides=overrides)

        for computer in response.computers:
            if computer.ec2_virtual_machine_summary.instance_id == 'i-0ab687235eddfb3ad':
                attr = vars(computer)
                instance_in_ds = attr['_id']
                api_instance = deepsecurity.ScheduledTasksApi(
                    deepsecurity.ApiClient(configuration))
                scheduled_task = deepsecurity.ScheduledTask(
                ).scan_for_recommendations_task_parameters
                res = api_instance.create_scheduled_task(
                    scheduled_task, api_version)

        print("Found the instance in Deep Security as computer {}".format(
            len(response.computers)))
    except api_exception as ex:
        print(
            "Could not find the instance in Deep Security. Threw exception: {}"
            .format(ex))
コード例 #5
0
 def request_computers(self):
     """Returns a list with all computers in the DS environment"""
     api_instance = deepsecurity.ComputersApi(
         deepsecurity.ApiClient(self.api_config))
     try:
         api_response = api_instance.list_computers(self.version,
                                                    overrides=False)
     except ApiException as e:
         raise
     return api_response.computers
コード例 #6
0
def DeepSec_Api():
    print ('Connecting to Deep Security Platform ...###Calling Deep Security API###')
    if not sys.warnoptions:
        warnings.simplefilter("ignore")
    configuration=deepsecurity.Configuration()
    configuration.host="https://app.deepsecurity.trendmicro.com:443/api"
    #print ('deeptoken', deeptoken)
    dee=deeptoken
    print ('Fetching endpoint information using Access Key :', dee)
    configuration.api_key['api-secret-key']=dee

    api_instance=deepsecurity.ComputersApi(deepsecurity.ApiClient(configuration))
    api_version='v1'
    expand_options=deepsecurity.Expand()
    expand_options.add(expand_options.none)
    expand=expand_options.list()
    overrides=False

    try:
        api_response=api_instance.list_computers(api_version,expand=expand,overrides=overrides)
        #pprint(api_response)
    except ApiException as e:
        print("Exception: %s",e)
    #sqlmain()
    try:
        conn = sqlmain()
        c = conn.cursor()
        print ('Downloading Report from Deep Security Platform ...###Calling Deep Security API###')
        for item in tqdm(api_response.computers):
            sql = f' INSERT INTO DeepSecurity(host_name, agent_version, computer_status, last_agent_communication, anti_malware, last_ip_used) ' \
                  f'VALUES(?, ?, ?, ?, ?, ?) '
            cur = conn.cursor()

            # Prepare data to insert
            list_array = []
            host_name = item.host_name if item.host_name else 'None';
            agent_version = item.agent_version if item.agent_version else 'None';
            computer_status = item.computer_status if item.computer_status else 'None';
            last_agent_communication = str(item.last_agent_communication) if item.last_agent_communication else 'None';
            anti_malware = item.anti_malware if item.anti_malware else 'None';
            last_ip_used = item.last_ip_used if item.last_ip_used else 'None';
            list_array.extend((host_name, agent_version, computer_status, last_agent_communication, anti_malware, last_ip_used))

            # execute insert query
            c.execute(sql, list_array)
            conn.commit()
            inserted_id = cur.lastrowid
            #print(inserted_id)
    except Error as e:
        print(e)
    finally:
        if conn:
            conn.close()
 def request_computer_per_id(self, comp_id):
     """Returns a unique computer in the DS environment"""
     api_instance = deepsecurity.ComputersApi(deepsecurity.ApiClient(self.api_config))
     try:
         api_response = api_instance.describe_computer(comp_id, self.api_version, 
         expand=self.COMPUTER_EXPAND, overrides=False)
     except deepsecurity.rest.ApiException as e:
         self.handle_api_exception(e,"COMPUTERS")
     except urllib3.exceptions.MaxRetryError as e:
         raise Exception(self.MAX_RETRY_ERROR_MSG)
     except urllib3.exceptions.LocationParseError:
         raise TypeError( ("API Configuration values on {} are NOT VALID".format(self.API_CONFIG_PATH)))
     return api_response
コード例 #8
0
def GetAllComputers(configuration):

    expand = Expand(Expand.ec2_virtual_machine_summary)
    expndList = expand.list()
    # Set search criteria
    search_criteria = api.SearchCriteria()
    search_criteria.id_value = 0
    search_criteria.id_test = "greater-than"

    # Create a search filter with maximum returned items
    page_size = 50
    search_filter = api.SearchFilter()
    search_filter.max_items = page_size
    search_filter.search_criteria = [search_criteria]

    # Perform the search and do work on the results
    computers_api = api.ComputersApi(api.ApiClient(configuration))
    paged_computers = []
    while True:
        try:
            t0 = time.time()
            computers = computers_api.search_computers(
                api_version, search_filter=search_filter, expand=expndList)
            t1 = time.time()
            num_found = len(computers.computers)
            current_paged_computers = []

            if num_found == 0:
                print("No computers found.")
                break

            for computer in computers.computers:
                current_paged_computers.append(computer)

            paged_computers.append(current_paged_computers)

            # Get the ID of the last computer in the page and return it with the number of computers on the page
            last_id = computers.computers[-1].id
            search_criteria.id_value = last_id
            print("Last ID: " + str(last_id),
                  "Computers found: " + str(num_found))
            print("Return rate: {0} hosts/sec".format(num_found / (t1 - t0)))

            if num_found != page_size:
                print("Num_found {0} - Page size is {1}".format(
                    num_found, page_size))

        except api_exception as e:
            print("Exception: {0}".format(str(e)))

    return paged_computers
def getcomputerinfo(host_id, policy_id, configuration, api_version, overrides):
    try:
        computer_instance = deepsecurity.ComputersApi(
            deepsecurity.ApiClient(configuration))
        computers = computer_instance.list_computers(api_version,
                                                     overrides=overrides)
        for computer in computers.computers:
            if (computer.policy_id == policy_id):
                if (computer.id == host_id):
                    print(computer)
    except ApiException as e:
        print(
            "An exception occurred when calling ComputersApi.list_computers: %s\n"
            % e)
コード例 #10
0
    def get_computer_id(self, hostname):
        print(f'Searching for "{hostname}" IDs...')

        search_field = 'hostName'
        search_computers_api = api.ComputersApi(
            self.api_client).search_computers
        computer = self._find_exact_match(search_field, hostname,
                                          search_computers_api)

        if not computer.computers:
            sys.exit('Error: Could not find hostname')

        computer_id = computer.computers[0].id

        print(f'"{hostname}" - Computer ID: {computer_id}')

        return computer_id
コード例 #11
0
    def get_computers(self):
        expand = api.Expand(api.Expand.intrusion_prevention)

        try:
            computers_api = api.ComputersApi(self.api_client)
            computer_list = computers_api.list_computers(self.api_version,
                                                         expand=expand.list(),
                                                         overrides=False)

        except ApiException as e:
            return 'Exception: ' + str(e)

        computers = dict()

        for computer in computer_list.computers:
            computers[computer.host_name] = computer

        return computers
def getacstatus(host_id, policy_id, configuration, api_version, overrides):
    try:
        computer_instance = deepsecurity.ComputersApi(
            deepsecurity.ApiClient(configuration))
        computers = computer_instance.list_computers(api_version,
                                                     overrides=overrides)
        for computer in computers.computers:
            if (computer.policy_id == policy_id):
                if (computer.id == host_id):
                    if (computer.tasks is not None):
                        print("Current status: " +
                              computer.tasks.agent_tasks[0])
                        return (computer.tasks.agent_tasks[0])
                    else:
                        return (None)
    except ApiException as e:
        print(
            "An exception occurred when calling ComputersApi.list_computers: %s\n"
            % e)
コード例 #13
0
    def change_computer_name(self, current_name, new_name):
        computer_id = self.get_computer_id(current_name)

        computers_api = api.ComputersApi(self.api_client)
        computer = api.Computer()
        computer.host_name = new_name

        try:
            computers_api.modify_computer(computer_id,
                                          computer,
                                          self.api_version,
                                          overrides=False)
            print(
                f'Successfully changed computer name from "{current_name}" to "{new_name}"'
            )

        except ApiException as e:
            print(str(e))
            sys.exit(1)
コード例 #14
0
def sign_in_to_deep_security():
    """
    Sign in to Deep Security
    """
    global DSM
    global configuration

    configuration = client.Configuration()
    DSM_policy = client.PoliciesApi(client.ApiClient(configuration))
    DSM_client = client.ComputersApi(client.ApiClient(configuration))

    if 'apiKey' not in os.environ:
        print("apiKey is REQUIRED environment variables for this AWS Lambda function")
        return None
    ds_api_key = os.environ['apiKey']

    ds_hostname = None
    if 'dsHostname' in os.environ: ds_hostname = os.environ['dsHostname']
    ds_port = None
    if 'dsPort' in os.environ: ds_port = os.environ['dsPort']

    # ds_ignore_ssl_validation = None
    # if 'dsIgnoreSslValidation' in os.environ: ds_ignore_ssl_validation = os.environ['dsIgnoreSslValidation']

    try:
        # DSM connection string
        configuration.host = 'https://' + ds_hostname + ':' + ds_port + '/api'
        configuration.verify_ssl = False
        # Authentication
        configuration.api_key['api-secret-key'] = ds_api_key
        api_version = 'v1'

        policies_list = DSM_policy.list_policies(api_version)
        computer_list = DSM_client.list_computers(api_version)

        print("Signed into Deep Security")
    except api_exception as ex:
        print("Could not successfully sign into Deep Security. Threw exception: {}".format(ex))
コード例 #15
0
def get_anti_malware_status_for_computers(api, configuration, api_version,
                                          api_exception):
    """Obtains agent and appliance status for the Anti-Malware module of all computers.
    Returns the status information of all computers that have the Anti-Malware module turned off,
    or where the status of the module is not active as comma-separated values.
    :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 string that can be saved as a CSV file.
    """
    # Add column titles to comma-separated values string
    csv = "Host Name,Module State,Agent or Appliance,Status,Status Message\r\n"
    # Include Anti-Malware information in the returned Computer objects
    expand = api.Expand(api.Expand.anti_malware)
    try:
        computers_api = api.ComputersApi(api.ApiClient(configuration))
        computers = computers_api.list_computers(api_version,
                                                 expand=expand.list(),
                                                 overrides=False)
        print('1')
        # Get the list of computers and iterate over it
        for computer in computers.computers:
            # Module information to add to the CSV string
            module_info = []
            # Check that the computer has a an agent or appliance status
            if computer.anti_malware.module_status:
                agent_status = computer.anti_malware.module_status.agent_status
                appliance_status = computer.anti_malware.module_status.appliance_status
            else:
                agent_status = None
                appliance_status = None
            # Agents that are not active for the module
            if agent_status and agent_status != "inactive":
                # Host name
                module_info.append(computer.host_name)
                # Module state
                module_info.append(computer.anti_malware.state)
                # Agent status and status message
                module_info.append("Agent")
                module_info.append(agent_status)
                module_info.append(
                    computer.anti_malware.module_status.agent_status_message)
                # Add the module info to the CSV string
                csv_line = ""
                for num, item in enumerate(module_info):
                    csv_line += item
                    if num != (len(module_info) - 1):
                        csv_line += ","
                    else:
                        csv_line += "\r\n"
                csv += csv_line
            # Appliances that are not active for the module
            if appliance_status and appliance_status != "inactive":
                # Host name
                module_info.append(computer.host_name)
                # Module state
                module_info.append(computer.anti_malware.state)
                # Appliance status and status message
                module_info.append("Appliance")
                module_info.append(appliance_status)
                module_info.append(computer.anti_malware.module_status.
                                   appliance_status_message)
                # Add the module info to the CSV string
                csv_line = ""
                for num, item in enumerate(module_info):
                    csv_line += item
                    if num != (len(module_info) - 1):
                        csv_line += ","
                    else:
                        csv_line += "\r\n"
                csv += csv_line
        return csv
    except api_exception as e:
        return "Exception: " + str(e)
コード例 #16
0
    def _GetGroupComputers(self, configuration, groupID):

        # Set search group criteria
        search_group_criteria = api.SearchCriteria()
        search_group_criteria.field_name = "groupID"
        if groupID:
            search_group_criteria.numeric_value = groupID
            search_group_criteria.numeric_test = "equal"
        else:
            search_group_criteria.null_test = True

        # Set search criteria
        search_criteria = api.SearchCriteria()
        search_criteria.id_value = 0
        search_criteria.id_test = "greater-than"

        # Create a search filter with maximum returned items
        page_size = 250
        search_filter = api.SearchFilter()
        search_filter.max_items = page_size
        search_filter.search_criteria = [
            search_criteria, search_group_criteria
        ]

        # Perform the search and do work on the results
        computers_api = api.ComputersApi(api.ApiClient(configuration))
        paged_computers = []
        while True:
            try:
                expand = Expand(Expand.ec2_virtual_machine_summary)
                t0 = time.time()
                computers = computers_api.search_computers(
                    api_version,
                    search_filter=search_filter,
                    expand=expand.list())
                t1 = time.time()
                num_found = len(computers.computers)
                current_paged_computers = []

                if num_found == 0:
                    #This gets noise with so many threads
                    #print("No computers found.")
                    break

                for computer in computers.computers:
                    current_paged_computers.append(computer)

                paged_computers.append(current_paged_computers)

                # Get the ID of the last computer in the page and return it with the number of computers on the page
                last_id = computers.computers[-1].id
                search_criteria.id_value = last_id
                print("Last ID: " + str(last_id),
                      "Computers found: " + str(num_found))
                print("Return rate: {0} hosts/sec".format(num_found /
                                                          (t1 - t0)))
                if num_found != page_size:
                    print("Num_found {0} - Page size is {1}".format(
                        num_found, page_size))

            except api_exception as e:
                print("Exception: {0}".format(str(e)))

        return paged_computers
コード例 #17
0
with open(property_file) as raw_properties:
    properties = json.load(raw_properties)

secret_key = properties['secretkey']
url = properties['url']
api_version = 'v1'

# Add DSM host information to the API client configuration
configuration = api.Configuration()
configuration.host = url
configuration.api_key['api-secret-key'] = secret_key

# Initialization
# Set Any Required Values
api_instance = api.ComputersApi(api.ApiClient(configuration))
# Add AV and IPS information
expand_options = api.Expand()
expand_options.add(api.Expand.computer_status)
expand_options.add(api.Expand.security_updates)
expand_options.add(api.Expand.intrusion_prevention)
expand_options.add(api.Expand.anti_malware)
expand_options.add(api.Expand.interfaces)
expand_options.add(api.Expand.azure_arm_virtual_machine_summary)
expand = expand_options.list()
overrides = False

# Set search criteria
search_criteria = api.SearchCriteria()
search_criteria.id_value = 0
search_criteria.id_test = "greater-than"
def gethostid(policy_id, configuration, api_version, overrides):
    try:
        # Get the hosts that are using the selected policy
        hosts_using_policy = []
        computer_instance = deepsecurity.ComputersApi(
            deepsecurity.ApiClient(configuration))
        computers = computer_instance.list_computers(api_version,
                                                     overrides=overrides)
        for computer in computers.computers:
            computer_info = []
            if (computer.policy_id == policy_id):
                host_string = computer.display_name + "(" + computer.host_name + ")"
                hosts_using_policy.append(host_string)

        # If not hosts are using the selected policy, exit
        if hosts_using_policy is None:
            print(
                "There are no hosts with the selected policy assigned.  Please assign the policy to the host under test and re-run the script"
            )
            exit()

        # Otherwise prompt the user to confirm
        if (len(hosts_using_policy) == 1):
            y_or_n_selected = False

            while (y_or_n_selected == False):
                print("The host under test is: " + hosts_using_policy[0])
                print("Is this correct (y/n)?")
                host_correct = input()
                if (host_correct.isalpha() and len(host_correct) == 1):
                    if ("y" in host_correct.lower()):
                        print("Using host: " + hosts_using_policy[0])
                        y_or_n_selected = True
                    else:
                        print(
                            "Please assign the policy you selected to the host under test or select the policy assigned to the host under test and try again"
                        )
                        exit()
                else:
                    print("Invalid entry, please try again")

        # If there is more than one host using the policy
        # Prompt the user to provide the system under test
        if (len(hosts_using_policy) > 1):
            count = 1
            for host in hosts_using_policy:
                print(str(count) + " = " + host)
                count += 1
            print(
                "Enter the number for the host you will be running these tests on?"
            )
            selected_host = input()
            if (not selected_host.isdigit()) or (int(selected_host) >
                                                 (len(hosts_using_policy) + 1)
                                                 or selected_host == 0):
                print("Invalid option, please try again")
                selected_host = 0
            selected_host = int(selected_host) - 1
            print("You have selected to use: " +
                  hosts_using_policy[selected_host] +
                  " as the host under test")
            host_to_select = hosts_using_policy[selected_host]
        else:
            print("This policy is assigned to: " + hosts_using_policy[0] +
                  " so this host is selected as the host under test")
            host_to_select = hosts_using_policy[0]

        # Get the host id
        for computer in computers.computers:
            if (computer.host_name in host_to_select):
                return (computer.id)

    except ApiException as e:
        print(
            "An exception occurred when calling ComputersApi.list_computers: %s\n"
            % e)
コード例 #19
0
configuration.api_key['api-secret-key'] = '2:PZGmBIe8rcKSF6fK2HeMkoyh5ZrC/fQeeyJyUjcpzyk='

# Initialization
# Set Any Required Values
api_instance = deepsecurity.PoliciesApi(deepsecurity.ApiClient(configuration))
api_version = 'v1'

search_criteria = deepsecurity.SearchCriteria()
search_criteria.field_name = "name"
search_criteria.string_test = "equal"
search_criteria.string_value = "%Linux Server%"

# Create a search filter
search_filter = deepsecurity.SearchFilter(None, [search_criteria])
policies_api = deepsecurity.PoliciesApi(deepsecurity.ApiClient(configuration))
computers_api = deepsecurity.ComputersApi(deepsecurity.ApiClient(configuration))
computer = deepsecurity.Computer()

try:
    # Perform the search
    policy_search_results = policies_api.search_policies(api_version, search_filter=search_filter)

    # Assign the policy to the computer
    computer.policy_id = REPLACE_WITH_THE_POLICY_ID_TO_ASSIGN

    computers_api.modify_computer(REPLACE_WITH_THE_COMPUTER_ID_TO_MODIFY, computer, api_version)

except ApiException as e:
    pprint( "Exception: " + str(e))

コード例 #20
0
# Initialization

#DSAAS SOAP API Setup
client = zeep.Client(wsdl=url + '/webservice/Manager?WSDL',
                     transport=transport_with_basic_auth)

# client.wsdl.dump()

if tenant != "":
    sessionId = client.service.authenticateTenant(tenant, username, password)
else:
    sessionId = client.service.authenticate(username, password)

# Set Any Required Values
api_instance1 = deepsecurity.ComputersApi(
    deepsecurity.ApiClient(configuration))
api_instance2 = deepsecurity.AntiMalwareConfigurationsApi(
    deepsecurity.ApiClient(configuration))
api_version = 'v1'
overrides = False

dateNow = datetime.datetime.now() - datetime.timedelta(days=15)


def json_default(value):
    if isinstance(value, datetime.datetime):
        return dict(year=value.year,
                    month=value.month,
                    day=value.day,
                    hour=value.hour,
                    minute=value.minute,