def _add_incident(self, event, *args, **kwargs):
        """Function to add an incident to another org."""

        # get information about the incident, such as its ID
        incident = event.message["incident"]
        inc_id = incident["id"]

        LOG.info("Connecting to alternate org...")
        resilient_client = resilient.SimpleClient(self.to_org_name,
                                                  self.to_org_address,
                                                  verify=self.to_org_verify_tls)

        LOG.info("Authenticating with alternate org...")
        resilient_client.connect(self.to_org_username,
                                 self.to_org_password)

        LOG.info("Creating new incident data...")
        # NOTE: The other organization is likely to have different schema from the originating org
        # (custom fields, and different valid values for 'select' fields).  Ensure that all required
        # fields are set in the new incident, and that copied values are mapped appropriately.
        new_incident = {'name': 'New Incident Copied From Other Org',
                        'description': 'Incident created from incident '+str(inc_id),
                        'discovered_date': incident['discovered_date']}

        LOG.info("Posting new incident to alternate org...")
        new_incident = resilient_client.post('/incidents', new_incident)

        LOG.info("Finished incident posting! New incident ID is %s", new_incident["id"])

        return "Incident Created"
Exemplo n.º 2
0
    def test_org_error(self, co3_args):
        """No org entered"""
        url = "https://{0}:{1}".format(co3_args.host, co3_args.port or 443)
        client = resilient.SimpleClient(org_name=co3_args.org,
                                        base_url=url,
                                        verify=False,
                                        proxies=co3_args.proxy)
        # Mismatch.
        try:
            client._extract_org_id({"orgs": [{"name": "Fake Org"}]})
            assert False
        except Exception as e:
            assert True

        # not enabled
        try:
            client._extract_org_id(
                {"orgs": [{
                    "name": client.org_name,
                    "enabled": False
                }]})
            assert False
        except Exception as e:
            assert True

        # Erase org_name input
        client.org_name = None
        try:
            client._extract_org_id({"orgs": [{"name": "Fake Org"}]})
            assert False
        except Exception as e:
            assert True
Exemplo n.º 3
0
 def test_connect_no_verify(self, co3_args):
     """ Successful connection with no Cert Verification """
     url = "https://{0}:{1}".format(co3_args.host, co3_args.port or 443)
     client = resilient.SimpleClient(org_name=co3_args.org,
                                     base_url=url,
                                     verify=False)
     assert client
     userinfo = client.connect(co3_args.email, co3_args.password)
     assert userinfo
Exemplo n.º 4
0
 def _connect(self, co3_args):
     uri = "https://{0}:{1}".format(co3_args.host, co3_args.port or 443)
     client = resilient.SimpleClient(org_name=co3_args.org,
                                     base_url=uri,
                                     verify=False)
     assert client
     user_info = client.connect(co3_args.email, co3_args.password)
     assert user_info
     return client
Exemplo n.º 5
0
 def test_extract_org_id_failure(self, co3_args, resp):
     """Extract org id given org name"""
     url = "https://{0}:{1}".format(co3_args.host, co3_args.port or 443)
     client = resilient.SimpleClient(org_name=co3_args.org,
                                     base_url=url,
                                     verify=False,
                                     proxies=co3_args.proxy)
     try:
         client._extract_org_id({"orgs": resp})
         assert False
     except Exception as e:
         assert True
Exemplo n.º 6
0
    def connect(self, opt_parser):
        res_opt = opt_parser.opts.get(RESILIENT_SECTION)
        host = res_opt.get("host", None)
        port = res_opt.get("port", 443)
        email = res_opt.get("email", None)
        password = res_opt.get("password", None)
        org = res_opt.get("org", None)
        api_key_id = res_opt.get("api_key_id", None)
        api_key_secret = res_opt.get("api_key_secret", None)

        if host and org and ((email and password) or (api_key_id and api_key_secret)):
            url = "https://{}:{}".format(host, port)
            verify = True
            try:
                cafile = opt_parser.getopt(RESILIENT_SECTION, "cafile")
                if cafile in ['false', 'False']:
                    #
                    #   This is a security related feature. The user has to explicitly enter false or False to
                    #   turn it off. We don't accept anything else.
                    #
                    self.log.debug("HTTPS certificate validation has been turned off.")

                    requests.packages.urllib3.disable_warnings()
                    verify = False
                elif os.path.isfile(cafile):
                    #
                    #   User specified a cafile for trusted certificate
                    #
                    verify = cafile
            except:
                verify = True

            args = {"base_url": url,
                    "verify": verify,
                    "org_name": org}

            self.res_client = resilient.SimpleClient(**args)
            if email is not None and password is not None:
                session = self.res_client.connect(email, password)

                if session is not None:
                    user_name = session.get("user_displayname", "Not found")
                    print("User display name is : {}".format(user_name))

                print("Done")
            else:
                self.res_client.set_api_key(api_key_id=api_key_id,
                                            api_key_secret=api_key_secret)
Exemplo n.º 7
0
    def client_connection(self):
        config = configparser.ConfigParser()
        section = "resilient"

        config.read("config.cfg")
        host = config.get(section, 'host')
        port = config.get(section, 'port')
        email = config.get(section, 'email')
        password = config.get(section, 'password')
        org = config.get(section, 'org')
        url = "https://{0}:{1}".format(host, port or 443)
        client = resilient.SimpleClient(org_name=org,
                                        base_url=url,
                                        verify=False)

        userinfo = client.connect(email, password)
        assert userinfo
        print("working")
        return client
Exemplo n.º 8
0
 def test_api_key(self, co3_args):
     """
     Test using api key to get org
     :return:
     """
     print(str(co3_args))
     url = "https://{0}:{1}".format(co3_args.host, co3_args.port or 443)
     client = resilient.SimpleClient(org_name=co3_args.org,
                                     base_url=url,
                                     verify=False,
                                     proxies=co3_args.proxy)
     if (co3_args.api_key_id is not None and co3_args.api_key_secret is not None):
         try:
             # Erase org_id
             client.org_id = None
             ret = client.set_api_key(co3_args.api_key_id, co3_args.api_key_secret)
             assert client.org_id
         except Exception as e:
             assert False
Exemplo n.º 9
0
    def connect(self):
        print("----------------")
        print("Ready to connect")
        print("----------------")
        print("Read config information from app.confg ...")
        arg_parser = resilient.ArgumentParser(
            resilient.get_config_file()).parse_args(args=self.other_args)
        host = arg_parser.host
        email = arg_parser.email
        password = arg_parser.password
        org = arg_parser.org
        api_key_id = arg_parser.api_key_id
        api_key_secret = arg_parser.api_key_secret

        cafile = arg_parser.cafile

        verify = True
        if cafile is not None and cafile == "false":
            verify = False
        url = "https://{}:443".format(host)
        print("Connecting to {} using user:{}, and org:{}".format(
            url, email, org))
        print("Validate cert: {}".format(verify))

        args = {"base_url": url, "verify": verify, "org_name": org}

        self.res_client = resilient.SimpleClient(**args)

        if email is not None and password is not None:
            session = self.res_client.connect(email, password)

            if session is not None:
                user_name = session.get("user_displayname", "Not found")
                print("User display name is : {}".format(user_name))

            print("Done")
        else:
            self.res_client.set_api_key(api_key_id=api_key_id,
                                        api_key_secret=api_key_secret)
Exemplo n.º 10
0
    def __init__(self, request):
        # TODO: replace/supplement with the 'resilient.circuits.customize' entry-point
        # TODO: Add support for phases, tasks, incident types.
        # TODO: Add support for optional action and custom fields (currently all set as required)

        host = os.environ.get("TEST_RESILIENT_APPLIANCE",
                              request.config.option.resilient_host)
        url = "https://%s:443" % host
        org = os.environ.get("TEST_RESILIENT_ORG",
                             request.config.option.resilient_org)
        user = os.environ.get("TEST_RESILIENT_USER",
                              request.config.option.resilient_email)
        password = os.environ.get("TEST_RESILIENT_PASSWORD",
                                  request.config.option.resilient_password)
        assert all((host, org, user, password))

        # Connect to Resilient
        self.client = resilient.SimpleClient(org_name=org,
                                             base_url=url,
                                             verify=False)
        session = self.client.connect(user, password)

        # Retrieve constants from appliance
        constants = self._get_constants()["actions_framework"]
        # Invert the dictionaries so they are {"name": id,...}
        action_object_types = {
            value: int(key)
            for key, value in constants["action_object_types"].items()
        }
        action_types = {
            value: int(key)
            for key, value in constants["action_types"].items()
        }
        destination_types = {
            value: int(key)
            for key, value in constants["destination_types"].items()
        }

        # Delete all existing configuration items
        self._clear_org()

        # Create all required configuration items for this class of tests
        action_fields = getattr(request.cls, "action_fields", None)
        if action_fields:
            for field_name, info in action_fields.items():
                success = self._create_action_field(field_name, info[0],
                                                    info[1], info[2])
                assert success
        custom_fields = getattr(request.cls, "custom_fields", None)
        if custom_fields:
            for field_name, info in custom_fields.items():
                success = self._create_custom_field(field_name, info[0],
                                                    info[1], info[2])
                assert success
        destinations = getattr(request.cls, "destinations", None)
        if destinations:
            for queue_name in destinations:
                success = self._create_destination(queue_name,
                                                   destination_types["Queue"])
                assert success

        destinations = self.client.get("/message_destinations")["entities"]
        destinations = {
            dest["programmatic_name"]: int(dest["id"])
            for dest in destinations
        }
        manual_actions = getattr(request.cls, "manual_actions", None)
        if manual_actions:
            for action_name, info in manual_actions.items():
                success = self._create_manual_action(
                    action_name, destinations[info[0]],
                    action_object_types[info[1]], action_types["Manual"],
                    info[2])
                assert success
        automatic_actions = getattr(request.cls, "automatic_actions", None)
        if automatic_actions:
            for action_name, info in automatic_actions.items():
                success = self._create_automatic_action(
                    action_name, destinations[info[0]],
                    action_object_types[info[1]], action_types["Automatic"],
                    info[2])
                assert success

        data_tables = getattr(request.cls, "data_tables", None)
        print("create data tables: %s" % data_tables)
        if data_tables:
            for table_name, columns in data_tables.items():
                success = self._create_data_table(table_name, columns)
                assert success
Exemplo n.º 11
0
def download_incidents_csv(opt_parser, csv_file):
    """
    Download incidents and convert json into CSV. Save the result to the csv_file.

    :param opt_parser:  Options/configurations and command line parameters
    :param csv_file:    CSV file to save samples/incidents to
    :return:            Number of incidents saved to the CSV file
    """
    res_opt = opt_parser.opts.get(RESILIENT_SECTION)
    host = res_opt.get("host", None)
    email = res_opt.get("email", None)
    password = res_opt.get("password", None)
    org = res_opt.get("org", None)

    num_inc = 0
    if host and org and email and password:
        url = "https://{}:443".format(host)
        verify = True
        try:
            cafile = opt_parser.getopt(RESILIENT_SECTION, "cafile")
            if cafile == "false" or cafile == "False":
                #
                #   This is a security related feature. The user has to explicitly enter false or False to
                #   turn it off. We don't accept anything else.
                #
                LOG.debug("HTTPS certificate validation has been turned off.")

                requests.packages.urllib3.disable_warnings()
                verify = False
            elif os.path.isfile(cafile):
                #
                #   User specified a cafile for trusted certificate
                #
                verify = cafile
        except:
            verify = True

        args = {"base_url": url, "verify": verify, "org_name": org}

        resilient_client = resilient.SimpleClient(**args)
        session = resilient_client.connect(email, password)
        max_count = None
        if opt_parser.getopt(MACHINE_LEARNING_SECTION, "max_count"):
            max_count = int(
                opt_parser.getopt(MACHINE_LEARNING_SECTION, "max_count"))

        time_start = opt_parser.getopt(MACHINE_LEARNING_SECTION, "time_start")
        time_end = opt_parser.getopt(MACHINE_LEARNING_SECTION, "time_end")
        res_filter = IncidentTimeFilter(time_start=time_start,
                                        time_end=time_end,
                                        in_log=LOG)

        # get_incidents is going to download all the incidents using this resilient_client
        # The optional max_count controls how many samples to process. The conversion from
        # json to CSV will stop once reaches this limit.
        num_inc = resilient_utils.get_incidents(res_client=resilient_client,
                                                filename=csv_file,
                                                filter=res_filter,
                                                max_count=max_count,
                                                in_log=LOG)

    LOG.info("Saved {} samples into {}".format(num_inc, csv_file))

    return num_inc
Exemplo n.º 12
0
    def test_throw_simple_http_exception(self, co3_args):
        with pytest.raises(resilient.SimpleHTTPException) as exception_info:
            client = resilient.SimpleClient("Not A real Org")
            user_info = client.connect("*****@*****.**", "test")

            assert exception_info