Ejemplo n.º 1
0
 def __init__(self, api_key):
     self.configuration = deepsecurity.Configuration()
     self.configuration.host = f'https://{os.environ["ApiEndpoint"]}/api'
     self.configuration.api_key['api-secret-key'] = api_key
     self.connectorClient = deepsecurity.AWSConnectorsApi(
         deepsecurity.ApiClient(self.configuration))
     self.apiVersion = 'v1'
Ejemplo n.º 2
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))
Ejemplo n.º 3
0
 def __init__(self):
     ds_api_key = os.environ['DS_KEY']
     self.api_version = os.environ.get('DS_API_VERSION', 'v1')
     dsm_address = os.environ.get(
         'DS_API_ADDRESS', 'https://app.deepsecurity.trendmicro.com/api')
     config = api.Configuration()
     config.host = dsm_address
     config.api_key['api-secret-key'] = ds_api_key
     self.api_client = api.ApiClient(config)
Ejemplo n.º 4
0
 def __init__(self, host, api_key, version):
     self.host = host
     self.api_key = api_key
     self.version = version
     try:
         self.api_config = deepsecurity.Configuration()
         self.api_config.host = host
         self.api_config.api_key['api-secret-key'] = api_key
     except:
         raise TypeError("Invalid types: host - {} api_key - {}".format(
             type(host), type(api_key)))
Ejemplo n.º 5
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 __init__(self, dsm_address):

        try:
            ds_api_key = os.environ['DS_KEY']
            self.api_version = os.environ.get('DS_API_VERSION', 'v1')

        except KeyError:
            sys.exit(
                '"DS_KEY" environment variables are not set. Please set them and try again.'
            )

        config = api.Configuration()
        config.host = dsm_address
        config.api_key['api-secret-key'] = ds_api_key

        self.api_client = api.ApiClient(config)
    def __init__(self):
        try:
            print('Obtaining DS API key')
            ds_api_key = os.environ['DS_KEY']
            self.api_version = os.environ.get('DS_API_VERSION', 'v1')
            print(f'Set API version to {self.api_version}')

        except KeyError:
            sys.exit(
                '"DS_KEY" environment variables are not set. Please set them and try again.'
            )

        dsm_address = os.environ.get(
            'DS_API_ADDRESS', 'https://app.deepsecurity.trendmicro.com/api')
        print(f'Obtained DS API address: {dsm_address}')

        print('Initiating DS connection')
        config = api.Configuration()
        config.host = dsm_address
        config.api_key['api-secret-key'] = ds_api_key

        self.api_client = api.ApiClient(config)
Ejemplo n.º 8
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))
Ejemplo n.º 9
0
if not sys.warnoptions:
    warnings.simplefilter("ignore")

# Get the DSM URL and API key from a JSON file
property_file = os.path.dirname(
    os.path.abspath(__file__)) + '/../properties.json'

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.PoliciesApi(api.ApiClient(configuration))

# Add column titles to comma-separated values string
csv = "Policy ID;Name;Description;Antimalware;Antimalware manual scan configuration id;Antimalware real time scan configuration;Antimalware Scheduled scan configuration;Application control;firewall;integrity monitoring;interface types;intrusion prevention;recommendation scan mode;log_inspection;web reputation\n"

overrides = False

try:
    policies = api_instance.list_policies(api_version, overrides=overrides)
Ejemplo n.º 10
0
#MY FIRST EXAMPLE FOR SEARCHING IPS RULES IN COMPUTERS
#MY FIRST EXAMPLE FOR SEARCHING IPS RULES IN COMPUTERS
from __future__ import print_function
import sys, warnings
import deepsecurity
from deepsecurity.rest import ApiException
from pprint import pprint

# Setup
if not sys.warnoptions:
    warnings.simplefilter("ignore")
configuration = deepsecurity.Configuration()
configuration.host = 'https://192.168.75.210:4119/api'

# Authentication
configuration.api_key[
    'api-secret-key'] = '2:PZGmBIe8rcKSF6fK2HeMkoyh5ZrC/fQeeyJyUjcpzyk='

# Initialization
# Set Any Required Values
api_instance = deepsecurity.ComputerIntrusionPreventionRuleAssignmentsRecommendationsApi(
    deepsecurity.ApiClient(configuration))
computer_id = 1
api_version = 'v1'
overrides = False

try:
    api_response = api_instance.list_intrusion_prevention_rule_ids_on_computer(
        computer_id, api_version, overrides=overrides)
    pprint(api_response)
except ApiException as e:
def main():
    # Setup and connect to Cloud One Workload Security or Deep Security
    api_version = 'v1'
    overrides = False
    if not sys.warnoptions:
        warnings.simplefilter("ignore")
    configuration = deepsecurity.Configuration()
    configuration.host = 'https://cloudone.trendmicro.com:443/api'
    configuration.api_key['api-secret-key'] = '<Your API Key>'

    print("Welcome to the test suite for Cloud One Workload Security")
    print(
        "This script works by running a set of tests and assigns rules at the policy level if necessary"
    )
    # Get the Operating System information
    operating_system = getoperatingsystem()
    print("")
    print("The policies in your Cloud One account are:")

    # List the policies and get the policy_id
    policy_id = getpolicyid(configuration, api_version, overrides)

    # Check the hosts that the policy is applied to so we can know what host
    # the tests are being run on
    host_id = gethostid(policy_id, configuration, api_version, overrides)
    print("")
    time.sleep(2)

    # Set the variables for the tests to run
    ips_rule_to_apply = "Restrict Download Of EICAR Test File Over HTTP"
    if ("redhat" in operating_system or "ubuntu" in operating_system):
        im_rule_to_apply = "Unix - Open Port Monitor"
        li_rule_to_apply = "Unix - Syslog"
    if ("windows" in operating_system):
        im_rule_to_apply = "Microsoft Windows - 'Hosts' file modified"
        li_rule_to_apply = "Microsoft Windows Events"

    # Check with the user what test the user wants to run
    user_input = 0
    while (user_input == 0):
        print("The available tests are: ")
        print("1 = Anti-Malware")
        print("2 = Intrusion Prevention")
        print("3 = Integrity Monitoring")
        print("4 = Web Reputation")
        print("5 = Log Inspection")
        print(
            "6 = Application Control (Note: This test takes about 3 minutes to run)"
        )
        print("7 = Docker Anti-Malware (only works on Ubuntu and Redhat)")
        print("8 = All Tests")
        print("Which test would you like to perform: ")
        user_input = input()
        if (not user_input.isdigit()) or (int(user_input) > 8):
            print("Invalid option, please try again")
            user_input = 0

    # Run the anti-malware test
    if (int(user_input) == 1):
        antimalwaretest(operating_system)
        exit()

    # Run the intrusion prevention test
    if (int(user_input) == 2):
        ipstest(ips_rule_to_apply, policy_id, configuration, api_version,
                overrides, operating_system)
        exit()

    # Run the Integrity Monitoring test
    if (int(user_input) == 3):
        integritymonitoringtest(host_id, im_rule_to_apply, policy_id,
                                configuration, api_version, overrides,
                                operating_system)
        exit()

    # Run the Web Reputation test
    if (int(user_input) == 4):
        webreputationtest(policy_id, configuration, api_version, overrides,
                          operating_system)
        exit()

    # Run the Log Inspection test
    if (int(user_input) == 5):
        loginspectiontest(li_rule_to_apply, policy_id, configuration,
                          api_version, overrides, operating_system)
        exit()

    # Run the Application Control test
    if (int(user_input) == 6):
        applicationcontroltest(host_id, policy_id, configuration, api_version,
                               overrides, operating_system)
        exit()

    # Run the Docker antimalware test
    if (int(user_input) == 7):
        dockeramtest(host_id, policy_id, configuration, api_version, overrides,
                     operating_system)
        exit()

    # Run all tests
    if (int(user_input) == 8):
        print("Running all tests")
        antimalwaretest(operating_system)
        ipstest(ips_rule_to_apply, policy_id, configuration, api_version,
                overrides, operating_system)
        integritymonitoringtest(host_id, im_rule_to_apply, policy_id,
                                configuration, api_version, overrides,
                                operating_system)
        webreputationtest(policy_id, configuration, api_version, overrides,
                          operating_system)
        loginspectiontest(li_rule_to_apply, policy_id, configuration,
                          api_version, overrides, operating_system)
        applicationcontroltest(host_id, policy_id, configuration, api_version,
                               overrides, operating_system)
        if ("ubuntu" in operating_system or "redhat" in operating_system):
            dockeramtest(host_id, policy_id, configuration, api_version,
                         overrides, operating_system)
        exit()
Ejemplo n.º 12
0
 def __init__(self, url, api_key, verify_ssl, api_version):
     self.configuration = ds.Configuration()
     self.configuration.host = url
     self.configuration.api_key['api-secret-key'] = api_key
     self.configuration.verify_ssl = verify_ssl
     self.api_version = api_version
    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)))