Ejemplo n.º 1
0
def get_access_token():
    integration_context = demisto.getIntegrationContext()
    access_token = integration_context.get('access_token')
    stored = integration_context.get('stored')
    if access_token and stored:
        if epoch_seconds() - stored < 60 * 60 - 30:
            return access_token
    headers = {
        'Authorization': AUTH_ID,
        'Accept': 'application/json'
    }

    dbot_response = requests.get(
        TOKEN_RETRIEVAL_URL,
        headers=headers,
        params={'token': get_encrypted(TOKEN, ENC_KEY)},
        verify=USE_SSL
    )
    if dbot_response.status_code not in {200, 201}:
        msg = 'Error in authentication. Try checking the credentials you entered.'
        try:
            demisto.info('Authentication failure from server: {} {} {}'.format(
                dbot_response.status_code, dbot_response.reason, dbot_response.text))
            err_response = dbot_response.json()
            server_msg = err_response.get('message')
            if server_msg:
                msg += ' Server message: {}'.format(server_msg)
        except Exception as ex:
            demisto.error('Failed parsing error response: [{}]. Exception: {}'.format(err_response.content, ex))
        raise Exception(msg)
    try:
        parsed_response = dbot_response.json()
    except ValueError:
        raise Exception(
            'There was a problem in retrieving an updated access token.\n'
            'The response from the Demistobot server did not contain the expected content.'
        )
    access_token = parsed_response.get('access_token')
    api_url = parsed_response.get('url')
    token = parsed_response.get('token')

    demisto.setIntegrationContext({
        'access_token': access_token,
        'stored': epoch_seconds(),
        'api_url': api_url,
        'token': token
    })
    return access_token
Ejemplo n.º 2
0
def main() -> None:
    params = demisto.params()
    command = demisto.command()
    args = demisto.args()

    demisto.debug(f'Command being called is {command}')
    try:
        client = AzureNSGClient(
            app_id=params.get('app_id', ''),
            subscription_id=params.get('subscription_id', ''),
            resource_group_name=params.get('resource_group_name', ''),
            verify=not params.get('insecure', False),
            proxy=params.get('proxy', False),
        )
        commands = {
            'azure-nsg-security-groups-list': list_groups_command,
            'azure-nsg-security-rules-list': list_rules_command,
            'azure-nsg-security-rule-delete': delete_rule_command,
            'azure-nsg-security-rule-create': create_rule_command,
            'azure-nsg-security-rule-update': update_rule_command,
            'azure-nsg-security-rule-get': get_rule_command,
            'azure-nsg-auth-start': start_auth,
            'azure-nsg-auth-complete': complete_auth,
            'azure-nsg-auth-reset': reset_auth,
        }
        if command == 'test-module':
            return_error("Please run `!azure-nsg-auth-start` and `!azure-nsg-auth-complete` to log in."
                         " For more details press the (?) button.")

        if command == 'azure-nsg-auth-test':
            return_results(test_connection(client, params))
        else:
            return_results(commands[command](client, **args))

    # Log exceptions and return errors
    except Exception as e:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}')
Ejemplo n.º 3
0
def fetch_samples(client, mapper_in, report_url, workday_date_format):
    """
    This function returns a list of (at most) five sample events (used for classification and mapping only).

    Args:
        client: Workday client
        mapper_in: Incoming mapper's name
        report_url: The report full URL
        workday_date_format: Date format in Workday

    Returns:
        events: Incidents/events that will be used as samples for classification and mapping.
    """
    events = []
    num_of_samples = 5
    try:
        report_entries = client.get_full_report(report_url)
        num_of_samples = min(num_of_samples, len(report_entries))
        report_entries = report_entries[:num_of_samples]

        for entry in report_entries:
            workday_user = demisto.mapObject(entry, mapper_in,
                                             DEFAULT_INCIDENT_TYPE)
            workday_user = convert_incident_fields_to_cli_names(workday_user)
            reformat_date_fields(workday_user, workday_date_format)

            entry['UserProfile'] = workday_user
            event = {
                "name": workday_user.get(EMAIL_ADDRESS_FIELD),
                "rawJSON": json.dumps(entry),
                "details": 'This is a sample event.'
            }
            events.append(event)
    except Exception as e:
        demisto.error('Failed to fetch events. Reason: ' + str(e))
        raise e

    return events
Ejemplo n.º 4
0
def main() -> None:
    """main function, parses params and runs command functions

    :return:
    :rtype:
    """

    # SSH Key integration requires ssh_agent to be running in the background
    ssh_agent_setup.setup()

    # Common Inputs
    command = demisto.command()
    args = demisto.args()
    int_params = demisto.params()

    try:

        if command == 'test-module':
            # This is the call made when pressing the integration Test button.
            return_results('This integration does not support testing from this screen. \
                           Please refer to the documentation for details on how to perform \
                           configuration tests.')
        elif command == 'acme-account':
            return_results(generic_ansible('ACME', 'acme_account', args, int_params, host_type))
        elif command == 'acme-account-info':
            return_results(generic_ansible('ACME', 'acme_account_info', args, int_params, host_type))
        elif command == 'acme-certificate':
            return_results(generic_ansible('ACME', 'acme_certificate', args, int_params, host_type))
        elif command == 'acme-certificate-revoke':
            return_results(generic_ansible('ACME', 'acme_certificate_revoke', args, int_params, host_type))
        elif command == 'acme-challenge-cert-helper':
            return_results(generic_ansible('ACME', 'acme_challenge_cert_helper', args, int_params, host_type))
        elif command == 'acme-inspect':
            return_results(generic_ansible('ACME', 'acme_inspect', args, int_params, host_type))
    # Log exceptions and return errors
    except Exception as e:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(f'Failed to execute {command} command.\nError:\n{str(e)}')
Ejemplo n.º 5
0
    def execute_query(self, query: str, bind_vars: Any) -> Tuple[List, List]:
        """
        Execute query at DB2 Database via connection

        Args:
            query(str): db2 query string
            bind_vars(Any): in case there are names and values - a bind_vars dict,
                            in case there are only values - list

        Returns:
            Tuple[results(List), headers(List)]
        """
        results = list()
        headers = list()
        status = False

        stmt = self._prepare_statement(query, bind_vars)

        try:
            demisto.info("Executing ...")
            status = ibm_db.execute(stmt)
            demisto.info("Done !!!")
        except Exception:
            demisto.error(clear(ibm_db.stmt_error()))
            demisto.error(clear(ibm_db.stmt_errormsg()))
            raise DemistoException(clear(ibm_db.stmt_errormsg()))

        demisto.info("Collecting results")
        if status:
            row = ibm_db.fetch_assoc(stmt)
            while row:
                results.append(row)
                row = ibm_db.fetch_assoc(stmt)

        if results:
            headers = [*results[0]]

        return results, headers
Ejemplo n.º 6
0
def main():
    get_roles_response: List = demisto.executeCommand('getRoles', {})
    if is_error(get_roles_response):
        demisto.error(
            f'Failed to get roles: {str(get_error(get_roles_response))}')
    else:
        hours_per_user: Dict[str, int] = {}
        get_users_response: List = demisto.executeCommand('getUsers', {})
        if is_error(get_users_response):
            demisto.error(
                f'Failed to get users: {str(get_error(get_users_response))}')
        else:
            users = get_users_response[0]['Contents']
            roles = get_roles_response[0]['Contents']
            for role in roles:
                role_on_call_hours = 0
                shifts = role.get('shifts') or []
                for shift in shifts:
                    role_on_call_hours += count_hours_in_shift(shift)
                role_users = map(
                    lambda role_user: role_user.get('name', ''),
                    filter(
                        lambda u: role.get('name') in reduce(
                            operator.add,
                            u.get('roles', {}).values()), users))
                for username in role_users:
                    if username in hours_per_user:
                        hours_per_user[username] += role_on_call_hours
                    else:
                        hours_per_user[username] = role_on_call_hours

        line_widget = LineWidget()
        for user, number_of_hours in hours_per_user.items():
            line_widget.add_category(name=user,
                                     number=number_of_hours,
                                     group=user)

        return_results(line_widget)
Ejemplo n.º 7
0
    def get_iocs(self, method, iocurl, params):
        """
        Fetch the IOC's for the given parameters
        :param method: Requests method to be used
        :param iocurl: API URL Suffix to be used
        :param params: parameters to be used as part of request
        :return:indicator details as JSON
        """
        ioc_data = {}
        resp = {}
        token = params.get('token', '')
        payload = {
            'token': '{}'.format(token),
            'from': arg_to_number(params.get('from', '0')),
            'limit': arg_to_number(params.get('limit', '50')),
            'start_date': '{}'.format(params.get('start_date')),
            'end_date': '{}'.format(params.get('end_date')),
            'type': '{}'.format(params.get('type')),
            'keyword': '{}'.format(params.get('keyword'))
        }
        files: List[Any] = []
        headers = {
            "Cookie": "XSRF-TOKEN={}".format(token)
        }
        url = urljoin(self._base_url, iocurl)

        response = requests.request('{}'.format(str(method).upper()), url, headers=headers, data=payload, files=files)

        try:
            resp = response.json()
            if resp.get('count'):
                ioc_data = resp
            else:
                demisto.error("Error trying to Fetch IOC's {}".format(resp))
        except Exception as e:
            raise Exception("Error: [{}] for response [{}]".format(e, resp))

        return ioc_data
Ejemplo n.º 8
0
def main() -> None:
    params = demisto.params()
    command = demisto.command()
    demisto.debug(f'Command being called is {command}')
    try:
        verify_certificate = not params.get('insecure', False)
        proxy = params.get('proxy', False)

        client = Client(base_url=BASE_URL,
                        verify=verify_certificate,
                        proxy=proxy)

        if command == 'test-module':
            result = test_module(client)
            return_results(result)

        elif command == 'dbot-truth-bomb':
            return_results(dbot_fact(client, demisto.args()))

    # Log exceptions and return errors
    except Exception as e:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(f'Failed to execute {command} command.\nError:\n{str(e)}')
Ejemplo n.º 9
0
def main():
    try:
        handle_proxy()

        active_command = demisto.command()

        if active_command == 'test-module':
            test_module()
            demisto.results('ok')

        elif active_command == 'fetch-incidents':
            fetch_incidents_command()

        elif active_command == 'ip':
            ip_command()

        elif active_command == 'domain':
            domain_command()

    # Log exceptions
    except Exception as e:
        demisto.error(str(e) + "\n\nTrace:\n" + traceback.format_exc())
        return_error(str(e))
Ejemplo n.º 10
0
def fetch_certificates(params, token):
    """
    Fetches all certificates that match the provided params.

    :param params: Search parameters
    :param token: Expanse Refresh token
    :return: List of certificate objects
    """
    certificates = []
    results = http_request('GET', 'assets/certificates', params, token=token)
    try:
        if len(results.get('data', [])) > 0:
            certificates += results.get('data', [])
            next_page = results.get('pagination', {}).get('next', None)
            while next_page is not None:
                params['pageToken'] = get_page_token(next_page)
                results = http_request('GET', 'assets/certificates', params, token=token)
                certificates += results['data']
                next_page = results.get('pagination', {}).get('next', None)
        return certificates
    except Exception as err:
        demisto.error("Error fetching certificates: {}".format(err))
        return []
Ejemplo n.º 11
0
def remove_key(keys_to_traverse: List[str], data: Dict[str,
                                                       Any]) -> Dict[str, Any]:
    try:
        key = keys_to_traverse[0]

        # If we've reached the last key in the list to traverse we can just drop it.
        if len(keys_to_traverse) == 1:
            del data[key]
            return data

        # Lists and dicts require us to move on with traversal.
        if isinstance(data[key], dict):
            data[key] = remove_key(keys_to_traverse[1:], data[key])
        elif isinstance(data[key], list):
            for i in range(len(data[key])):
                data[key][i] = remove_key(keys_to_traverse[1:], data[key][i])
        else:
            del data[key]

    except Exception:
        demisto.error(f"Key '{key}' not found in Automox response.")

    return data
Ejemplo n.º 12
0
def main() -> None:
    command = demisto.command()
    demisto.debug(
        f'Bitcoin Abuse: Command being called is {demisto.command()}')

    try:

        if command == 'test-module':
            fetch_indicators(demisto.params(), test_module=True)

        elif command == 'fetch-indicators':
            fetch_indicators(demisto.params(), test_module=False)

        elif command == 'bitcoinabuse-report-address':
            return_results(
                report_address_command(demisto.params(), demisto.args()))

    # Log exceptions and return errors
    except Exception as e:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(
            f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}'
        )
Ejemplo n.º 13
0
def main() -> None:

    command = demisto.command()
    demisto.debug(f"Command being called is {command}")
    try:
        handle_proxy()
        client = Client()

        if command == "test-module":
            # This is the call made when pressing the integration Test button.
            return_results(test_module(client))

        elif command == "jarm-fingerprint":
            return_results(jarm_fingerprint_command(client, demisto.args()))
        else:
            raise NotImplementedError(f'Command {command} is not implemented.')

    # Log exceptions and return errors
    except Exception as e:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(
            f"Failed to execute {demisto.command()} command.\nError:\n{str(e)}"
        )
Ejemplo n.º 14
0
def main() -> None:
    """main function, parses params and runs command functions

    :return:
    :rtype:
    """

    # SSH Key integration requires ssh_agent to be running in the background
    ssh_agent_setup.setup()

    try:

        if demisto.command() == 'test-module':
            # This is the call made when pressing the integration Test button.
            return_results('ok')
        elif demisto.command() == 'dns-nsupdate':
            return_results(generic_ansible('dns', 'nsupdate', demisto.args()))
    # Log exceptions and return errors
    except Exception as e:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(
            f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}'
        )
Ejemplo n.º 15
0
def upload_file(filename, content, attachments_list):
    """
    Uploads file to War room.

    :type filename: ``str``
    :param filename: file name to upload

    :type content: ``str``
    :param content: Content of file to upload

    :type attachments_list: ``list``
    :param attachments_list: List of uploaded file data to War Room
    """
    file_result = fileResult(filename, content)

    if is_error(file_result):
        demisto.error(file_result['Contents'])
        raise Exception(file_result['Contents'])

    attachments_list.append({
        'path': file_result['FileID'],
        'name': file_result['File']
    })
Ejemplo n.º 16
0
def fetch_ips(params, token):
    """
    Returns all ip results matching search params.

    :param params: Search parameters
    :param token: Expanse Refresh token
    :return: List of ip objects
    """
    ips = []
    results = http_request('GET', 'assets/ips', params, token=token)
    try:
        if len(results.get('data', [])) > 0:
            ips += results.get('data', [])
            next_page = results.get('pagination', {}).get('next', None)
            while next_page is not None:
                params['pageToken'] = get_page_token(next_page)
                results = http_request('GET', 'assets/ips', params, token=token)
                ips += results['data']
                next_page = results.get('pagination', {}).get('next', None)
        return ips
    except Exception as err:
        demisto.error("Error fetching ips: {}".format(err))
        return []
Ejemplo n.º 17
0
def get_cache_path():
    path = tempfile.gettempdir() + "/zeepcache"
    try:
        os.makedirs(path)
    except OSError:
        if os.path.isdir(path):
            pass
        else:
            raise
    db_path = os.path.join(path, "cache.db")
    try:
        if not os.path.isfile(db_path):
            static_init_db = os.getenv('ZEEP_STATIC_CACHE_DB',
                                       '/zeep/static/cache.db')
            if os.path.isfile(static_init_db):
                demisto.debug(
                    f'copying static init db: {static_init_db} to: {db_path}')
                shutil.copyfile(static_init_db, db_path)
    except Exception as ex:
        # non fatal
        demisto.error(
            f'Failed copying static init db to: {db_path}. Error: {ex}')
    return db_path
Ejemplo n.º 18
0
def main() -> None:
    params = demisto.params()
    args = demisto.args()
    base_url = "https://api.macvendors.com"
    verify_cert = not params.get('insecure', False)
    proxy = params.get('proxy', False)
    command = demisto.command()
    demisto.debug(f'Command being called is {command}')
    try:
        client = BaseClient(
            base_url=base_url,
            verify=verify_cert,
            proxy=proxy,
        )
        if command == "test-module":
            test_module(client)
        elif command == "macvendors-lookup-mac":
            lookup_mac_command(client, args)

    # Log exceptions and return errors
    except Exception as e:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(f'Failed to execute {command} command.\nError: {str(e)}')
Ejemplo n.º 19
0
def main() -> None:

    params = demisto.params()

    client_args = {
        'client_id': params.get('credentials').get('identifier'),
        'client_secret': params.get('credentials').get('password')
    }

    remote = params.get('remote', QWATCH_REMOTE)

    proxy = params.get('proxy', False)
    verify_ssl = not params.get('insecure', False)

    command = demisto.command()

    demisto.debug(f'Command being called is {command}')

    try:

        client = Client(remote, verify_ssl, proxy, **client_args)

        args = demisto.args()

        if command == 'test-module':
            demisto.results(test_module(client))

        elif command == 'fetch-incidents':
            demisto.incidents(fetch_incidents(client, params))

        elif command == 'qintel-qwatch-exposures':
            return_results(search_exposures(client, args, params))

    # Log exceptions
    except Exception as e:
        demisto.error(traceback.format_exc())
        return_error(f'Failed to execute {command} command.\nError:\n{str(e)}')
Ejemplo n.º 20
0
def mail_to_incident(msg, service, user_key):
    parsed_msg, headers = get_email_context(msg, user_key)

    file_names = []
    command_args = {
        'messageId': parsed_msg['ID'],
        'userId': user_key,
    }

    for attachment in parsed_msg['Attachments']:
        command_args['id'] = attachment['ID']
        result = service.users().messages().attachments().get(
            **command_args).execute()
        file_data = base64.urlsafe_b64decode(result['data'].encode('ascii'))

        # save the attachment
        file_result = fileResult(attachment['Name'], file_data)

        # check for error
        if file_result['Type'] == entryTypes['error']:
            demisto.error(file_result['Contents'])
            raise Exception(file_result['Contents'])

        file_names.append({
            'path': file_result['FileID'],
            'name': attachment['Name'],
        })

    return {
        'type': 'Gmail',
        'name': parsed_msg['Subject'],
        'details': parsed_msg['Body'],
        'labels': create_incident_labels(parsed_msg, headers),
        'occurred': parse_time(parsed_msg['Date']),
        'attachment': file_names,
        'rawJSON': json.dumps(parsed_msg),
    }
Ejemplo n.º 21
0
def handle_exception(user_profile, e, action):
    """ Handles failed responses from Okta API by setting the User Profile object with the results.

    Args:
        user_profile (IAMUserProfile): The User Profile object.
        e (Exception): The exception error. If DemistoException, holds the response json.
        action (IAMActions): An enum represents the current action (get, update, create, etc).
    """
    if e.__class__ is DemistoException and hasattr(
            e, 'res') and e.res is not None:
        try:
            resp = e.res.json()
            error_code = resp.get('errorCode')
            error_message = get_error_details(resp)
        except ValueError:
            error_code = e.res.status_code
            error_message = str(e)
    else:
        error_code = ''
        error_message = str(e)

    if error_code == USER_IS_DISABLED_ERROR:
        error_message = USER_IS_DISABLED_MSG

    if error_code in ERROR_CODES_TO_SKIP:
        user_profile.set_result(action=action,
                                skip=True,
                                skip_reason=error_message)
    else:
        should_return_error = error_code in ERROR_CODES_TO_RETURN_ERROR
        user_profile.set_result(action=action,
                                success=False,
                                return_error=should_return_error,
                                error_code=error_code,
                                error_message=error_message)

    demisto.error(traceback.format_exc())
Ejemplo n.º 22
0
def main() -> None:
    """main function, parses params and runs command functions

    :return:
    :rtype:
    """

    api_key = demisto.params().get("api_key")
    proxy = demisto.params().get("proxy", False)

    demisto.debug(f"Command being called is {demisto.command()}")
    try:
        client = Client(
            api_key=api_key,
            proxy=handle_proxy("proxy", proxy).get("https", ""),
            use_cache=False,
            integration_name="xsoar-community-integration-v1.0.2",
            offering="community",
        )

        if demisto.command() == "test-module":
            # This is the call made when pressing the integration Test button.
            result: Any = test_module(client)
            return_results(result)

        elif demisto.command() == "ip":
            result = ip_reputation_command(client, demisto.args())
            return_results(result)

    # Log exceptions and return errors
    except RequestFailure:
        raise DemistoException(EXCEPTION_MESSAGES["UNAUTHENTICATED"])

    except Exception as err:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(EXCEPTION_MESSAGES["COMMAND_FAIL"].format(
            demisto.command(), str(err)))
Ejemplo n.º 23
0
def main():
    params: Dict = demisto.params()
    base_url: str = params.get('base_url', '')
    client_id: str = params.get('client_id', '')
    client_secret: str = params.get('client_secret', '')
    event_type = ','.join(params.get('event_type', []))
    verify_ssl = not params.get('insecure', False)
    proxy = params.get('proxy', False)
    offset = params.get('offset', '0')
    try:
        offset = int(offset)
    except ValueError:
        offset = 0
    incident_type = params.get('incidentType', '')
    store_samples = params.get('store_samples', False)
    first_fetch_time, _ = parse_date_range(params.get('first_fetch', '1 hour'))

    stream = EventStream(base_url=base_url, app_id='Demisto', verify_ssl=verify_ssl, proxy=proxy)

    LOG(f'Command being called is {demisto.command()}')
    try:
        if demisto.command() == 'test-module':
            run(test_module(base_url, client_id, client_secret, verify_ssl, proxy))
        elif demisto.command() == 'long-running-execution':
            run(long_running_loop(
                base_url, client_id, client_secret, stream, offset, event_type, verify_ssl, proxy, incident_type,
                first_fetch_time, store_samples
            ))
        elif demisto.command() == 'fetch-incidents':
            fetch_samples()
        elif demisto.command() == 'crowdstrike-falcon-streaming-get-sample-events':
            get_sample_events(store_samples)
    except Exception as e:
        error_msg = f'Error in CrowdStrike Falcon Streaming v2: {str(e)}'
        demisto.error(error_msg)
        demisto.updateModuleHealth(error_msg)
        return_error(error_msg)
Ejemplo n.º 24
0
def login():
    if USE_APPROLE_AUTH_METHOD:
        path = 'auth/approle/login'
        body = {
            'role_id': USERNAME,
            'secret_id': PASSWORD,
        }
    else:
        path = 'auth/userpass/login/' + USERNAME  # type: ignore
        body = {'password': PASSWORD}

    url = '{}/{}'.format(SERVER_URL, path)
    res = requests.request('POST',
                           url,
                           headers=get_headers(),
                           data=json.dumps(body),
                           verify=VERIFY_SSL)
    if (res.status_code < 200 or res.status_code >= 300
        ) and res.status_code not in DEFAULT_STATUS_CODES:
        try:
            error_body = res.json()
            if 'errors' in error_body and isinstance(error_body['errors'],
                                                     list):
                error_body = ';'.join(error_body['errors']) if len(
                    error_body['errors']) > 0 else 'None'
        except Exception as ex:
            demisto.error("Error in login (parsing error msg): {}".format(ex))
            error_body = res.content
        return_error('Login failed. Status code: {}, details: {}'.format(
            str(res.status_code), error_body))

    auth_res = res.json()
    if not auth_res or 'auth' not in auth_res or 'client_token' not in auth_res[
            'auth']:
        return_error('Could not authenticate user')

    return auth_res['auth']['client_token']
Ejemplo n.º 25
0
def main() -> None:
    """main function, parses params and runs command functions

    """
    params = demisto.params()
    args = demisto.args()
    command = demisto.command()

    base_url = params.get('base_url')
    verify = not params.get('insecure', False)
    proxy = params.get('proxy', False)

    try:
        client = Client(base_url=base_url, verify=verify, proxy=proxy)

        if command == 'test-module':
            return_results(test_module_command(client))
        elif command == 'postmark-spamcheck':
            entry_id = args.get('entryid')
            file_path = demisto.getFilePath(entry_id).get('path')
            result = spamcheck_command(client=client,
                                       file_path=file_path,
                                       args=args)
            result['entryid'] = entry_id
            command_results = CommandResults(
                readable_output=tableToMarkdown('Postmark - Spamcheck',
                                                result,
                                                metadata='Spamcheck completed',
                                                removeNull=True),
                outputs_prefix='Postmark.Spamcheck',
                outputs_key_field='entryid',
                outputs=result)
            return_results(command_results)
    except Exception as e:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(
            f'Failed to execute {demisto.command()} command. Error: {str(e)}')
Ejemplo n.º 26
0
def validate_input(args, is_iocs=False):
    """
    Check if the input params for the command are valid. Return an error if any
    :param args: dictionary of input params
    :param is_iocs: check if the params are for iocs command
    """
    try:
        # we assume all the params to be non-empty, as cortex ensures it
        if int(args.get('from')) < 0:
            raise ValueError(f"Parameter having negative value, from: {arg_to_number(args.get('from'))}'")
        limit = int(args.get('limit', '1'))

        if is_iocs:
            date_format = "%Y-%m-%d"
            _start_date = datetime.strptime(args.get('start_date'), date_format)
            _end_date = datetime.strptime(args.get('end_date'), date_format)
            if limit <= 0 or limit > 1000:
                raise ValueError(
                    f"Limit should a positive number upto 1000, limit: {limit}")
        else:
            date_format = "%Y/%m/%d"
            _start_date = datetime.strptime(args.get('start_date'), date_format)
            _end_date = datetime.strptime(args.get('end_date'), date_format)
            if limit <= 0 or limit > LIMIT_EVENT_ITEMS:
                raise ValueError(f"Limit should a positive number upto 50, limit: {limit}")

        if _start_date > datetime.today():
            raise ValueError(f"Start date must be a date before or equal to {datetime.today().strftime(date_format)}")
        if _end_date > datetime.today():
            raise ValueError(f"End date must be a date before or equal to {datetime.today().strftime(date_format)}")
        if _start_date > _end_date:
            raise ValueError(f"Start date {args.get('start_date')} cannot be after end date {args.get('end_date')}")

        return None
    except Exception as e:
        demisto.error("Exception with validating inputs [{}]".format(e))
        raise e
Ejemplo n.º 27
0
def main() -> None:
    # Commands definition
    command = demisto.command()
    commands: Dict[str, Callable] = {
        "test-module": test_module,
        "tidy-pyenv": tidy_pyenv_command,
        "tidy-goenv": tidy_goenv_command,
        "tidy-nodenv": tidy_nodenv_command,
        "tidy-homebrew": tidy_homebrew_command,
        "tidy-github-ssh-key": tidy_github_ssh_key_command,
        "tidy-git-clone": tidy_git_clone_command,
        "tidy-git-config": tidy_git_config_command,
        "tidy-zsh": tidy_zsh_command,
        "tidy-block-in-file": tidy_block_in_file_command,
        "tidy-exec": tidy_exec_command,
        "tidy-osx-command-line-tools": tidy_osx_command_line_tools_command,
        "tidy-python-env": tidy_python_env_command,
        "tidy-demisto-server": tidy_demisto_server_command,
        "tidy-demisto-web-client": tidy_demisto_web_client_command,
    }

    # Tidy client configuration
    hostname = demisto.getArg("hostname") or demisto.getParam("hostname")
    user = demisto.getArg("user") or demisto.getParam("user")
    password = demisto.getArg("password") or demisto.getParam("password")
    client = TidyClient(hostname=hostname, user=user, password=password)

    # Command execution
    try:
        demisto.debug(f'Command being called is {command}')
        demisto.results(commands[command](client, **demisto.args()))
    # Log exceptions and return errors
    except DemistoException as e:
        demisto.error(traceback.format_exc())
        return_error(
            f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}'
        )
Ejemplo n.º 28
0
def main() -> None:

    base_url = demisto.params().get('base_url')
    access_id = demisto.params().get('access_id')
    secret_key = demisto.params().get('secret_key')
    verify = not demisto.params().get('insecure', False)
    proxies = handle_proxy(proxy_param_name="proxy")

    demisto.debug(f'Command being called is {demisto.command()}')
    try:

        client = Client(
            base_url=base_url,
            access_id=access_id,
            secret_key=secret_key,
            verify=verify,
            proxies=proxies,
        )

        if demisto.command() == 'test-module':
            test_module(client)
        elif demisto.command() == 'ip':
            return_results(ip_details_command(client, demisto.args()))
        elif demisto.command() == 'domain':
            return_results(domain_details_command(client, demisto.args()))
        elif demisto.command() == 'url':
            return_results(url_details_command(client, demisto.args()))
        elif demisto.command() == 'file':
            return_results(file_details_command(client, demisto.args()))
        elif demisto.command() == 'create_intel':
            return_results(create_intel_command(client, demisto.args()))

    except Exception as e:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(
            f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}'
        )
Ejemplo n.º 29
0
    def get_alerts(self, method, eventurl, params):
        """
        Fetch the Events for the given parameters
        :param method: Requests method to be used
        :param eventurl: API URL Suffix to be used
        :param params: parameters to be used as part of request
        :return: alert details as list
        """

        events_data = None
        payload = json.dumps({
            'from': params.get('from'),
            'limit': params.get('limit', '50'),
            'start_date': params.get('start_date'),
            'end_date': params.get('end_date'),
            'order_by': params.get('order_by'),
            'priority': params.get('priority', '')
        })
        headers = {
            'X-API-KEY': '{}'.format(params.get('token')),
            'Content-Type': 'application/json'
        }

        url = urljoin(self._base_url, eventurl)
        response = requests.request('{}'.format(str(method).upper()), url, headers=headers, data=payload)

        try:
            resp = response.json()
            if (resp.get('success') or False):
                events_data = resp.get('data', {}).get('results')
            else:
                raise Exception(resp)
        except Exception as e:
            demisto.error("Exception with Fetch Events [{}]".format(e))
            raise e

        return events_data
Ejemplo n.º 30
0
    def error_parser(error: requests.Response) -> str:
        """

        Args:
            error (requests.Response): response with error

        Returns:
            str: string of error

        """
        try:
            response = error.json()
            demisto.error(str(response))
            inner_error = response.get('error', {})
            if isinstance(inner_error, dict):
                err_str = f"{inner_error.get('code')}: {inner_error.get('message')}"
            else:
                err_str = inner_error
            if err_str:
                return err_str
            # If no error message
            raise ValueError
        except ValueError:
            return error.text
Ejemplo n.º 31
0
def mail_to_incident(msg, service, user_key):
    parsed_msg, headers = get_email_context(msg, user_key)

    file_names = []
    command_args = {
        'messageId': parsed_msg['ID'],
        'userId': user_key,
    }

    for attachment in parsed_msg['Attachments']:
        command_args['id'] = attachment['ID']
        result = service.users().messages().attachments().get(**command_args).execute()
        file_data = base64.urlsafe_b64decode(result['data'].encode('ascii'))

        # save the attachment
        file_result = fileResult(attachment['Name'], file_data)

        # check for error
        if file_result['Type'] == entryTypes['error']:
            demisto.error(file_result['Contents'])
            raise Exception(file_result['Contents'])

        file_names.append({
            'path': file_result['FileID'],
            'name': attachment['Name'],
        })

    return {
        'type': 'Gmail',
        'name': parsed_msg['Subject'],
        'details': parsed_msg['Body'],
        'labels': create_incident_labels(parsed_msg, headers),
        'occurred': parse_time(parsed_msg['Date']),
        'attachment': file_names,
        'rawJSON': json.dumps(parsed_msg),
    }
Ejemplo n.º 32
0
def test_nginx_server(port: int, params: Dict):
    nginx_process = start_nginx_server(port, params)
    # let nginx startup
    sleep(0.5)
    try:
        protocol = 'https' if params.get('key') else 'http'
        res = requests.get(f'{protocol}://localhost:{port}/nginx-test',
                           verify=False,
                           proxies={
                               "http": "",
                               "https": ""
                           })  # nosec guardrails-disable-line
        res.raise_for_status()
        welcome = 'Welcome to nginx'
        if welcome not in res.text:
            raise ValueError(
                f'Unexpected response from nginx-text (does not contain "{welcome}"): {res.text}'
            )
    finally:
        try:
            nginx_process.terminate()
            nginx_process.wait(1.0)
        except Exception as ex:
            demisto.error(f'failed stoping test nginx process: {ex}')