Exemplo n.º 1
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 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
Exemplo n.º 3
0
# for Tenant examples
account_name = "Test_tenant"
tenant_id = 6
new_policy = api.Policy()
new_policy.name = "Test Policy"
new_policy.description = "Inherits from Base Policy"
new_policy.auto_requires_update = "on"
new_policy.parent_id = 1

# For Settings examples
settings_policy_id = 1
firewall_fail_open_mode = True

# For Computer Overrides examples
override_computer_id = 2
expand = api.Expand()
expand.add(expand.intrusion_prevention)

# For Scheduled Tasks examples
custom_interval = 2
start_time = 30000
day = 14
scheduled_task_id = 5

# For Role examples
role_name = "Auditor"

# For Automate Deployment examples
host_name = "testhostname"
max_sessions = 10
max_sessions_exceeded_action = "Block new sessions"
Exemplo n.º 4
0
    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"

# Create a search filter with maximum returned items
    def __init__(self):
        self.api_config = deepsecurity.Configuration()
        self.api_version = ''

        self.API_CONFIG_PATH = "config/api_config.yml"
        self.MAX_RETRY_ERROR_MSG = "ERROR: Failed to establish connection - Make sure the hostname is correct"
        self.MAX_ITEMS_PER_PAGE = 1000 #Up To 5000

        expand_options = deepsecurity.Expand()
        expand_options.add(
            # deepsecurity.Expand.anti_malware,
            # deepsecurity.Expand.application_control,
            # deepsecurity.Expand.firewall,
            # deepsecurity.Expand.web_reputation,
            # deepsecurity.Expand.log_inspection,
            # deepsecurity.Expand.integrity_monitoring,
            # deepsecurity.Expand.intrusion_prevention,
            # deepsecurity.Expand.computer_settings,
            # deepsecurity.Expand.computer_status,
            # deepsecurity.Expand.ec2_virtual_machine_summary,
            # deepsecurity.Expand.azure_arm_virtual_machine_summary,
            # deepsecurity.Expand.azure_vm_virtual_machine_summary,
            # deepsecurity.Expand.gcp_virtual_machine_summary
            deepsecurity.Expand.all
        )
        self.COMPUTER_EXPAND = expand_options.list()


        search_criteria = deepsecurity.SearchCriteria()
        search_criteria.id_value = 0
        search_criteria.id_test = "greater-than"
        self.SEARCH_FILTER = deepsecurity.SearchFilter(max_items=self.MAX_ITEMS_PER_PAGE, search_criteria=search_criteria)

        #Turns off warnings unless specified
        if not sys.warnoptions:
    	       warnings.simplefilter("ignore")


        file_config = dict()

        try:
            with open(self.API_CONFIG_PATH, "r", encoding = 'utf-8') as cfg_fd:
                file_config = yaml.safe_load(cfg_fd.read())

            if file_config is None:
                file_config = dict()


        
            self.api_config.host = file_config["host"]
            self.api_config.api_key['api-secret-key'] = file_config["api-secret-key"]
            self.api_version = file_config["api-version"]

            if not "https://" in self.api_config.host:
                self.api_config.host = "https://"+self.api_config.host
        except Exception as e:
            print(Fore.LIGHTRED_EX + "Error while loading the config/api_config.yml file, resetting it...")
            try:
                os.makedirs("config")
            except Exception as e:
                pass

        try:
            if "host" not in file_config or file_config["host"] == "https://<Your DSM Hostname or IP>:<DSM Port>/api" or \
                "api-secret-key" not in file_config or file_config["api-secret-key"] == "" or "api-version" not in file_config:
                print(Fore.LIGHTRED_EX+"CONFIG FILE NOT SET!")
                print("{}Insert the DSM host (link) following this example {}[{}https://{}<Your DSM Hostname or IP>{}:{}<DSM Port if on-premise>{}/api{}]".
                format(Fore.LIGHTCYAN_EX, Fore.LIGHTWHITE_EX,Fore.LIGHTBLUE_EX, Fore.LIGHTGREEN_EX,Fore.LIGHTWHITE_EX,Fore.LIGHTRED_EX,Fore.LIGHTMAGENTA_EX,Fore.LIGHTWHITE_EX))
                self.api_config.host = input("Inset the DSM Host: ").rstrip().lstrip()
                file_config["host"] = self.api_config.host
                if self.api_config.host == "":
                    raise TypeError("Empty Host Configuration is NOT VALID")

                print(Fore.LIGHTCYAN_EX + "Insert the secret key for the API (Check the documentation if lost)")
                self.api_config.api_key['api-secret-key'] = input("Inset the Api Secret key: ").rstrip().lstrip()
                file_config["api-secret-key"] = self.api_config.api_key['api-secret-key']
                if self.api_config.api_key['api-secret-key'] == "":
                    raise TypeError("Empty key Configuration is NOT VALID")

                self.api_version = "v1"
                file_config["api-version"] = self.api_version

                print(Fore.LIGHTGREEN_EX + "Saving to config/api_config.yml (you can modify the info here)")
                try:
                    with open(self.API_CONFIG_PATH, "w+") as config:
                        yaml.dump(file_config,config, default_flow_style=False)
                except Exception as e:
                    print("Could not save configs to file, you will have to type them again later")
        
        except Exception as e:
            raise IOError("Corrupted api_config, please re download the file: " + str(e))

        
        if self.api_config.host is None or self.api_config.api_key is None or self.api_version is None:
            raise TypeError( ("API Configuration values on {} are NOT VALID".format(self.API_CONFIG_PATH)))
Exemplo n.º 6
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)