Exemplo n.º 1
0
def login():
    query_path = 'www/core-service/rest/LoginService/login'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    params = {
        'login': demisto.get(demisto.params(), 'credentials.identifier'),
        'password': demisto.get(demisto.params(), 'credentials.password'),
        'alt': 'json'
    }
    res = send_request(query_path, headers=headers, params=params, is_login=True)
    if not res.ok:
        demisto.debug(res.text)
        return_error('Failed to login, check integration parameters.')

    try:
        res_json = res.json()
        if 'log.loginResponse' in res_json and 'log.return' in res_json.get('log.loginResponse'):
            auth_token = res_json.get('log.loginResponse').get('log.return')
            if demisto.command() not in ['test-module', 'fetch-incidents']:
                # this is done to bypass setting integration context outside of the cli
                demisto.setIntegrationContext({'auth_token': auth_token})
            return auth_token

        return_error('Failed to login. Have not received token after login')
    except ValueError:
        return_error('Failed to login. Please check integration parameters')
Exemplo n.º 2
0
def fetch():
    """
    Query viewer should be defined in ArcSight ESM. fetch incidents fetches the results of query viewer
    and converts them to Demisto incidents. We can query Cases or Events. If Cases are fetched then the
    query viewer query must return fields ID and Create Time. If Events are fetched then Event ID and Start Time.
    """
    events_query_viewer_id = demisto.params().get('viewerId')
    cases_query_viewer_id = demisto.params().get('casesQueryViewerId')
    type_of_incident = 'case' if events_query_viewer_id else 'event'
    last_run = json.loads(demisto.getLastRun().get('value', '{}'))
    already_fetched = last_run.get('already_fetched', [])

    fields, query_results = get_query_viewer_results(events_query_viewer_id or cases_query_viewer_id)
    # sort query_results by creation time
    query_results.sort(key=lambda k: int(k.get('Start Time') or k.get('Create Time')))

    incidents = []
    for result in query_results:
        # convert case or event to demisto incident
        r_id = result.get('ID') or result.get('Event ID')
        if r_id not in already_fetched:
            create_time_epoch = int(result.get('Start Time') or result.get('Create Time'))
            result['Create Time'] = parse_timestamp_to_datestring(create_time_epoch)
            incident_name = result.get('Name') or 'New {} from arcsight at {}'.format(type_of_incident, datetime.now())
            labels = [{'type': key.encode('utf-8'), 'value': value.encode('utf-8') if value else value} for key, value
                      in result.items()]
            incident = {
                'name': incident_name,
                'occurred': result['Create Time'],
                'labels': labels,
                'rawJSON': json.dumps(result)
            }

            incidents.append(incident)
            if len(incidents) >= FETCH_CHUNK_SIZE:
                break

            if len(already_fetched) > MAX_UNIQUE:
                already_fetched.pop(0)
            already_fetched.append(r_id)

    last_run = {
        'already_fetched': already_fetched,
    }
    demisto.setLastRun({'value': json.dumps(last_run)})
    decode_arcsight_output(incidents)

    if demisto.command() == 'as-fetch-incidents':
        contents = {
            'last_run': last_run,
            'last_run_updated': demisto.getLastRun(),
            'incidents': incidents,
            'already_fetched': already_fetched
        }
        return_outputs(readable_output='', outputs={}, raw_response=contents)
    else:
        demisto.incidents(incidents)
Exemplo n.º 3
0
def main():
    global ADMIN_EMAIL, PRIVATE_KEY_CONTENT, GAPPS_ID
    ADMIN_EMAIL = demisto.params()['adminEmail'].get('identifier', '')
    PRIVATE_KEY_CONTENT = demisto.params()['adminEmail'].get('password', '{}')
    GAPPS_ID = demisto.params().get('gappsID')
    ''' EXECUTION CODE '''
    COMMANDS = {
        'gmail-list-users': list_users_command,
        'gmail-get-user': get_user_command,
        'gmail-create-user': create_user_command,
        'gmail-delete-user': delete_user_command,
        'gmail-get-user-roles': get_user_role_command,
        'gmail-revoke-user-role': revoke_user_roles_command,
        'gmail-get-tokens-for-user': get_user_tokens_command,
        'gmail-search-all-mailboxes': search_all_mailboxes,
        'gmail-search': search_command,
        'gmail-get-mail': get_mail_command,
        'gmail-get-attachments': get_attachments_command,
        'gmail-move-mail': move_mail_command,
        'gmail-move-mail-to-mailbox': move_mail_to_mailbox_command,
        'gmail-delete-mail': delete_mail_command,
        'gmail-get-thread': get_thread_command,
        'gmail-add-filter': add_filter_command,
        'gmail-add-delete-filter': add_delete_filter_command,
        'gmail-list-filters': list_filters_command,
        'gmail-remove-filter': remove_filter_command,
    }
    command = demisto.command()
    LOG('GMAIL: command is %s' % (command, ))
    try:
        if command == 'test-module':
            list_users(ADMIN_EMAIL.split('@')[1])
            demisto.results('ok')
            sys.exit(0)

        if command == 'fetch-incidents':
            demisto.incidents(fetch_incidents())
            sys.exit(0)

        cmd_func = COMMANDS.get(command)
        if cmd_func is None:
            raise NotImplementedError(
                'Command "{}" is not implemented.'.format(command))
        else:
            demisto.results(cmd_func())
    except Exception as e:
        import traceback
        if command == 'fetch-incidents':
            LOG(traceback.format_exc(e))
            LOG.print_log()
            raise
        else:
            return_error('GMAIL: {}'.format(str(e)), traceback.format_exc(e))
Exemplo n.º 4
0
def http_post(url_suffix, data=None, files=None, parse_json=True):
    data = {} if data is None else data

    LOG('running request with url=%s\n\tdata=%s\n\tfiles=%s' % (BASE_URL + url_suffix,
        data, files, ))
    data.setdefault('apikey', demisto.params()['api_key'])

    res = requests.post(BASE_URL + url_suffix, verify=USE_SSL, data=data, files=files)

    if res.status_code == 403:
        raise Exception('API Key is incorrect')

    if res.status_code != 200:
        error_msg = res.json()['errors'][0]['message']
        if error_msg == nothing_to_analyze_message:
            return 'nothing_to_analyze'

        LOG('result is: %s' % (res.json(), ))
        error_msg = res.json()['errors'][0]['message']
        raise Exception('Your request failed with the following error: %s.\n%s' % (res.reason, error_msg, ))

    if parse_json:
        return res.json()
    else:
        return res.content
Exemplo n.º 5
0
def test_bad_host_no_ssl(mocker):
    mocker.patch.object(demisto, 'params',
                        return_value=BASE_TEST_PARAMS)
    return_error_mock = mocker.patch(RETURN_ERROR_TARGET)
    # validate our mock of params
    assert demisto.params().get('server_ip') == '127.0.0.1'
    main()
    assert return_error_mock.call_count == 1
    # call_args last call with a tuple of args list and kwargs
    err_msg = return_error_mock.call_args[0][0]
    assert len(err_msg) < 100
    assert 'Failed to access' in err_msg
Exemplo n.º 6
0
def test_module():
    path = 'table/' + TICKET_TYPE + '?sysparm_limit=1'
    res = send_request(path, 'GET')
    if 'result' not in res:
        return_error('ServiceNow error: ' + str(res))
    ticket = res['result']
    if demisto.params().get('isFetch'):
        if isinstance(ticket, list):
            ticket = ticket[0]
        if TIMESTAMP_FIELD not in ticket:
            raise ValueError("The timestamp field [{}]"
                             " does not exist in the ticket".format(TIMESTAMP_FIELD))
Exemplo n.º 7
0
def prepare_fetch_query(fetch_timestamp):
    query = FETCH_QUERY_DICT[demisto.params().get('fetch_query', 'Traps Threats')]
    if 'tms' in query:
        query += f" WHERE serverTime>'{fetch_timestamp}'"
        FETCH_SEVERITY = demisto.params().get('traps_severity')
        if not FETCH_SEVERITY:
            FETCH_SEVERITY = ['all']
        if 'all' not in FETCH_SEVERITY:
            query += ' AND ('
            for index, severity in enumerate(FETCH_SEVERITY):
                if index == (len(FETCH_SEVERITY) - 1):
                    query += f"messageData.trapsSeverity='{severity}'"
                else:
                    query += f"messageData.trapsSeverity='{severity}' OR "
            query += ')'
    if 'panw' in query:
        query += f' WHERE receive_time>{fetch_timestamp}'
        FETCH_SEVERITY = demisto.params().get('firewall_severity')
        if not FETCH_SEVERITY:
            FETCH_SEVERITY = ['all']
        FETCH_SUBTYPE = demisto.params().get('firewall_subtype')
        if not FETCH_SUBTYPE:
            FETCH_SUBTYPE = ['all']
        if 'all' not in FETCH_SUBTYPE:
            query += ' AND ('
            for index, subtype in enumerate(FETCH_SUBTYPE):
                if index == (len(FETCH_SUBTYPE) - 1):
                    query += f"subtype='{subtype}'"
                else:
                    query += f"subtype='{subtype}' OR "
            query += ')'
        if 'all' not in FETCH_SEVERITY:
            query += ' AND ('
            for index, severity in enumerate(FETCH_SEVERITY):
                if index == (len(FETCH_SEVERITY) - 1):
                    query += f"severity='{severity}'"
                else:
                    query += f"severity='{severity}' OR "
            query += ')'
    return query
Exemplo n.º 8
0
def test():
    """
    Login (already done in global).
    Test if fetch query viewers are valid.
    Run query viewer if fetch defined.
    """
    events_query_viewer_id = demisto.params().get('viewerId')
    cases_query_viewer_id = demisto.params().get('casesQueryViewerId')
    is_fetch = demisto.params().get('isFetch')

    if is_fetch and not events_query_viewer_id and not cases_query_viewer_id:
        return_error('If fetch is enabled, you must provide query viewer Resource ID for Cases or Events')

    if events_query_viewer_id:
        fields, results = get_query_viewer_results(events_query_viewer_id)
        if 'Event ID' not in fields or 'Start Time' not in fields:
            return_error('Query "{}" must contain "Start Time" and "Event ID" fields'.format(cases_query_viewer_id))

    if cases_query_viewer_id:
        fields, results = get_query_viewer_results(cases_query_viewer_id)
        if 'ID' not in fields or 'Create Time' not in fields:
            return_error('Query "{}" must contain "Create Time" and "ID" fields'.format(cases_query_viewer_id))
Exemplo n.º 9
0
def test_module():
    """
    Perform basic get request to get item samples
    """
    try:
        bigquery_client = start_and_return_bigquery_client(demisto.params()['google_service_creds'])
        query_job = bigquery_client.query(TEST_QUERY)
        query_results = query_job.result()
        results_rows_iterator = iter(query_results)
        next(results_rows_iterator)
        demisto.results("ok")
    except Exception as ex:
        return_error("Authentication error: credentials JSON provided is invalid.\n Exception recieved:"
                     "{}".format(ex))
Exemplo n.º 10
0
def main():
    global FETCH_QUERY
    FETCH_QUERY = demisto.params().get('fetch_query', 'Traps Threats')

    LOG('command is %s' % (demisto.command(),))
    try:
        if demisto.command() == 'test-module':
            if demisto.params().get('isFetch'):
                last_fetched_event_timestamp, _ = parse_date_range(FIRST_FETCH_TIMESTAMP)
            test_args = {
                "query": "SELECT * FROM panw.threat LIMIT 1",
                "startTime": 0,
                "endTime": 1609459200,
            }
            if query_loggings(test_args):
                demisto.results('ok')
            else:
                demisto.results('test failed')
        elif demisto.command() == 'cortex-query-logs':
            demisto.results(query_logs_command())
        elif demisto.command() == 'cortex-get-critical-threat-logs':
            demisto.results(get_critical_logs_command())
        elif demisto.command() == 'cortex-get-social-applications':
            demisto.results(get_social_applications_command())
        elif demisto.command() == 'cortex-search-by-file-hash':
            demisto.results(search_by_file_hash_command())
        elif demisto.command() == 'fetch-incidents':
            fetch_incidents()
    except Exception as e:
        error_message = str(e)
        if demisto.command() == 'fetch-incidents':
            LOG(error_message)
            LOG.print_log()
            raise
        else:
            return_error(error_message)
Exemplo n.º 11
0
def fetch_incidents():
    params = demisto.params()
    user_key = params.get('queryUserKey')
    user_key = user_key if user_key else ADMIN_EMAIL
    query = '' if params['query'] is None else params['query']
    last_run = demisto.getLastRun()
    last_fetch = last_run.get('time')

    # handle first time fetch
    if last_fetch is None:
        last_fetch = datetime.datetime.now() - datetime.timedelta(days=1)
    else:
        last_fetch = datetime.datetime.strptime(
            last_fetch, '%Y-%m-%dT%H:%M:%SZ')
    current_fetch = last_fetch

    credentials = get_credentials(
        ['https://www.googleapis.com/auth/gmail.readonly', ], user_key)
    service = discovery.build('gmail', 'v1', credentials=credentials)

    query += last_fetch.strftime(' after:%Y/%m/%d')
    LOG('GMAIL: fetch parameters:\nuser: %s\nquery=%s\nfetch time: %s' %
        (user_key, query, last_fetch, ))

    result = service.users().messages().list(
        userId=user_key, maxResults=100, q=query).execute()

    incidents = []
    # so far, so good
    LOG('GMAIL: possible new incidents are %s' % (result, ))
    for msg in result.get('messages', []):
        msg_result = service.users().messages().get(
            id=msg['id'], userId=user_key).execute()
        incident = mail_to_incident(msg_result, service, user_key)
        temp_date = datetime.datetime.strptime(
            incident['occurred'], '%Y-%m-%dT%H:%M:%SZ')

        # update last run
        if temp_date > last_fetch:
            last_fetch = temp_date + datetime.timedelta(seconds=1)

        # avoid duplication due to weak time query
        if temp_date > current_fetch:
            incidents.append(incident)
    demisto.info('extract {} incidents'.format(len(incidents)))
    demisto.setLastRun({'time': last_fetch.isoformat().split('.')[0] + 'Z'})
    return incidents
Exemplo n.º 12
0
def query_command():
    args = demisto.args()
    query_to_run = args['query']
    project_id = args.get('project_id', None)
    location = args.get('location', None)
    allow_large_results = args.get('allow_large_results', None)
    default_dataset = args.get('default_dataset', None)
    destination_table = args.get('destination_table', None)
    kms_key_name = args.get('kms_key_name', None)
    dry_run = args.get('dry_run', None)
    priority = args.get('priority', None)
    use_query_cache = args.get('use_query_cache', None)
    use_legacy_sql = args.get('use_legacy_sql', None)
    google_service_creds = demisto.params()['google_service_creds']
    job_id = args.get('job_id', None)
    write_disposition = args.get('write_disposition', None)
    query_results = query(query_to_run, project_id, location, allow_large_results, default_dataset,
                          destination_table, kms_key_name, dry_run, priority, use_query_cache, use_legacy_sql,
                          google_service_creds, job_id, write_disposition)

    context = {}
    rows_contexts = []
    human_readable = 'No results found.'
    if dry_run and str_to_bool(dry_run):
        human_readable = '### Dry run results: \n This query will process {0} ' \
                         'bytes'.format(query_results.total_bytes_processed)

    else:

        for row in query_results:
            row_context = {underscoreToCamelCase(k): convert_to_string_if_datetime(v) for k, v in row.items()}
            rows_contexts.append(row_context)

        if rows_contexts:

            context['BigQuery(val.Query && val.Query == obj.Query)'] = {
                'Query': args['query'],
                'Row': rows_contexts
            }
            title = 'BigQuery Query Results'
            human_readable = tableToMarkdown(title, rows_contexts, removeNull=True)

    return_outputs(
        readable_output=human_readable,
        outputs=context,
        raw_response=rows_contexts
    )
Exemplo n.º 13
0
def test_bad_ssl(mocker):
    params = BASE_TEST_PARAMS.copy()
    params['server_ip'] = '185.199.108.153'  # disable-secrets-detection
    params['secure_connection'] = 'SSL'
    params['port'] = 443
    mocker.patch.object(demisto, 'params',
                        return_value=params)
    return_error_mock = mocker.patch(RETURN_ERROR_TARGET)
    # validate our mock of params
    assert demisto.params().get('secure_connection') == 'SSL'
    main()
    assert return_error_mock.call_count == 1
    # call_args last call with a tuple of args list and kwargs
    err_msg = return_error_mock.call_args[0][0]
    assert len(err_msg) < 100
    assert 'Failed to access' in err_msg
    assert 'SSL error' in err_msg
Exemplo n.º 14
0
def update_parameters():
    """
    Check and see if the integration parameters changed and if so update global vars
    """
    params = demisto.params()
    incidents_per_minute = int(params.get('incidents_per_minute', '5'))
    max_num_of_incidents = int(params.get('max_num_of_incidents', '10'))
    frequency = int(params.get('frequency')) if params.get('frequency') else None
    global INCIDENTS_PER_MINUTE
    if INCIDENTS_PER_MINUTE != incidents_per_minute:
        INCIDENTS_PER_MINUTE = incidents_per_minute
    global MAX_NUM_OF_INCIDENTS
    if MAX_NUM_OF_INCIDENTS != max_num_of_incidents:
        MAX_NUM_OF_INCIDENTS = max_num_of_incidents
    global FREQUENCY
    if FREQUENCY != frequency:
        FREQUENCY = frequency
Exemplo n.º 15
0
def test_faulty_server(mocker):
    t = Thread(target=ssl_bad_socket_server)
    t.start()
    time.sleep(1)  # wait for socket server to startup
    params = BASE_TEST_PARAMS.copy()
    params['server_ip'] = '127.0.0.1'  # disable-secrets-detection
    params['secure_connection'] = 'SSL'
    params['unsecure'] = True
    params['port'] = 9636
    mocker.patch.object(demisto, 'params',
                        return_value=params)
    return_error_mock = mocker.patch(RETURN_ERROR_TARGET)
    # validate our mock of params
    assert demisto.params().get('secure_connection') == 'SSL'
    main()
    t.join(5)
    assert return_error_mock.call_count == 1
    # call_args last call with a tuple of args list and kwargs
    err_msg = return_error_mock.call_args[0][0]
    assert len(err_msg) < 100
    assert 'Failed to access' in err_msg
Exemplo n.º 16
0
''' IMPORTS '''
import requests
import base64
import os
import binascii

# Disable insecure warnings
requests.packages.urllib3.disable_warnings()

""" GLOBALS/PARAMS """
# Global annotation
CONTEXT = demisto.getIntegrationContext()
DEMISTOBOT = 'https://demistobot.demisto.com/msg-mail-token'
# Credentials
TOKEN = demisto.params().get('token')
TENANT_ID = demisto.params().get('tenant_id')
# Remove trailing slash to prevent wrong URL path to service
URL = demisto.params().get('url')
SERVER = URL[:-1] if (URL and URL.endswith('/')) else URL
# Should we use SSL
USE_SSL = not demisto.params().get('unsecure', False)
# Service base URL
BASE_URL = str(SERVER) + '/v1.0'

# Remove proxy if not set to true in params
if not demisto.params().get('proxy'):
    os.environ.pop('HTTP_PROXY', '')
    os.environ.pop('HTTPS_PROXY', '')
    os.environ.pop('http_proxy', '')
    os.environ.pop('https_proxy', '')
Exemplo n.º 17
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
import os
import subprocess
import sys
import base64

# pylint: disable=E1103

reload(sys)
sys.setdefaultencoding("utf-8")
proxy = demisto.get(demisto.params(), "proxy")

if proxy:
    http_proxy = os.environ["http_proxy"]
    https_proxy = os.environ["https_proxy"]

return_code = 0
error_message = ''


def rasterize_email_request(html, friendly_name):
    global return_code, error_message

    f = open('htmlBody.html', 'w')
    f.write('<html style="background:white";>' + html + '</html>')
    f.close()

    proxy_flag = ""
    if proxy:
Exemplo n.º 18
0
def format_results(client, uuid):
    # Scan Lists sometimes returns empty
    num_of_attempts = 0
    relationships = []
    response = urlscan_submit_request(client, uuid)
    scan_lists = response.get('lists')
    while scan_lists is None:
        try:
            num_of_attempts += 1
            demisto.debug('Attempting to get scan lists {} times'.format(num_of_attempts))
            response = urlscan_submit_request(client, uuid)
            scan_lists = response.get('lists')
        except Exception:
            if num_of_attempts == 5:
                break
            demisto.debug('Could not get scan lists, sleeping for 5 minutes before trying again')
            time.sleep(5)
    scan_data = response.get('data', {})
    scan_lists = response.get('lists', {})
    scan_tasks = response.get('task', {})
    scan_page = response.get('page', {})
    scan_stats = response.get('stats', {})
    scan_meta = response.get('meta', {})
    url_query = scan_tasks.get('url', {})
    scan_verdicts = response.get('verdicts', {})
    ec = makehash()
    dbot_score = makehash()
    human_readable = makehash()
    cont = makehash()
    file_context = makehash()
    url_cont = makehash()

    feed_related_indicators = []

    LIMIT = int(demisto.args().get('limit', 20))
    if 'certificates' in scan_lists:
        cert_md = []
        cert_ec = []
        certs = scan_lists['certificates']
        for x in certs[:LIMIT]:
            info, ec_info = cert_format(x)
            cert_md.append(info)
            cert_ec.append(ec_info)
        CERT_HEADERS = ['Subject Name', 'Issuer', 'Validity']
        cont['Certificates'] = cert_ec
    url_cont['Data'] = url_query
    if 'urls' in scan_lists:
        url_cont['Data'] = demisto.args().get('url')
        cont['URL'] = demisto.args().get('url')
        if isinstance(scan_lists.get('urls'), list):
            for url in scan_lists['urls']:
                feed_related_indicators.append({'value': url, 'type': 'URL'})
    # effective url of the submitted url
    human_readable['Effective URL'] = scan_page.get('url')
    cont['EffectiveURL'] = scan_page.get('url')
    if 'uuid' in scan_tasks:
        ec['URLScan']['UUID'] = scan_tasks['uuid']
    if 'ips' in scan_lists:
        ip_asn_MD = []
        ip_ec_info = makehash()
        ip_list = scan_lists['ips']
        asn_list = scan_lists['asns']

        ip_asn_dict = dict(zip(ip_list, asn_list))
        i = 1
        for k in ip_asn_dict:
            if i - 1 == LIMIT:
                break
            v = ip_asn_dict[k]
            ip_info = {
                'Count': i,
                'IP': k,
                'ASN': v
            }
            ip_ec_info[i]['IP'] = k
            ip_ec_info[i]['ASN'] = v
            ip_asn_MD.append(ip_info)
            i = i + 1
        cont['RelatedIPs'] = ip_ec_info
        if isinstance(scan_lists.get('ips'), list):
            for ip in scan_lists.get('ips'):
                feed_related_indicators.append({'value': ip, 'type': 'IP'})
        IP_HEADERS = ['Count', 'IP', 'ASN']
    # add redirected URLs
    if 'requests' in scan_data:
        redirected_urls = []
        for o in scan_data['requests']:
            if 'redirectResponse' in o['request']:
                if 'url' in o['request']['redirectResponse']:
                    url = o['request']['redirectResponse']['url']
                    redirected_urls.append(url)
        cont['RedirectedURLs'] = redirected_urls
    if 'countries' in scan_lists:
        countries = scan_lists['countries']
        human_readable['Associated Countries'] = countries
        cont['Country'] = countries
    if None not in scan_lists.get('hashes', []):
        hashes = scan_lists.get('hashes', [])
        cont['RelatedHash'] = hashes
        human_readable['Related Hashes'] = hashes
        for hashe in hashes:
            feed_related_indicators.append({'value': hashe, 'type': 'File'})
    if 'domains' in scan_lists:
        subdomains = scan_lists.get('domains', [])
        cont['Subdomains'] = subdomains
        human_readable['Subdomains'] = subdomains
        for domain in subdomains:
            feed_related_indicators.append({'value': domain, 'type': 'Domain'})
    if 'linkDomains' in scan_lists:
        link_domains = scan_lists.get('domains', [])
        for domain in link_domains:
            feed_related_indicators.append({'value': domain, 'type': 'Domain'})
    if 'asn' in scan_page:
        cont['ASN'] = scan_page['asn']
        url_cont['ASN'] = scan_page.get('asn')
    if 'asnname' in scan_page:
        url_cont['ASOwner'] = scan_page['asnname']
    if 'country' in scan_page:
        url_cont['Geo']['Country'] = scan_page['country']
    if 'domain' in scan_page:
        feed_related_indicators.append({'value': scan_page['domain'], 'type': 'Domain'})
    if 'ip' in scan_page:
        feed_related_indicators.append({'value': scan_page['ip'], 'type': 'IP'})
    if 'url' in scan_page:
        feed_related_indicators.append({'value': scan_page['url'], 'type': 'URL'})
    if 'overall' in scan_verdicts:
        human_readable['Malicious URLs Found'] = scan_stats['malicious']
        if scan_verdicts['overall'].get('malicious'):
            human_readable['Verdict'] = 'Malicious'
            url_cont['Data'] = demisto.args().get('url')
            cont['Data'] = demisto.args().get('url')
            dbot_score['Indicator'] = demisto.args().get('url')
            url_cont['Malicious']['Vendor'] = 'urlscan.io'
            cont['Malicious']['Vendor'] = 'urlscan.io'
            dbot_score['Vendor'] = 'urlscan.io'
            url_cont['Malicious']['Description'] = 'Match found in Urlscan.io database'
            cont['Malicious']['Description'] = 'Match found in Urlscan.io database'
            dbot_score['Score'] = 3
            dbot_score['Type'] = 'url'
        else:
            dbot_score['Vendor'] = 'urlscan.io'
            dbot_score['Indicator'] = demisto.args().get('url')
            dbot_score['Score'] = 0
            dbot_score['Type'] = 'url'
            human_readable['Verdict'] = 'Unknown'
        dbot_score['Reliability'] = client.reliability
    if 'urlscan' in scan_verdicts and 'tags' in scan_verdicts['urlscan']:
        url_cont['Tags'] = scan_verdicts['urlscan']['tags']
    processors_data = scan_meta['processors']
    if 'download' in processors_data and len(scan_meta['processors']['download']['data']) > 0:
        meta_data = processors_data['download']['data'][0]
        sha256 = meta_data['sha256']
        filename = meta_data['filename']
        filesize = meta_data['filesize']
        filetype = meta_data['mimeType']
        human_readable['File']['Hash'] = sha256
        cont['File']['Hash'] = sha256
        file_context['SHA256'] = sha256
        human_readable['File']['Name'] = filename
        cont['File']['FileName'] = filename
        file_context['Name'] = filename
        human_readable['File']['Size'] = filesize
        cont['File']['FileSize'] = filesize
        file_context['Size'] = filesize
        human_readable['File']['Type'] = filetype
        cont['File']['FileType'] = filetype
        file_context['Type'] = filetype
        file_context['Hostname'] = demisto.args().get('url')
    if feed_related_indicators:
        related_indicators = []
        for related_indicator in feed_related_indicators:
            related_indicators.append(Common.FeedRelatedIndicators(value=related_indicator['value'],
                                                                   indicator_type=related_indicator['type']))
        url_cont['FeedRelatedIndicators'] = related_indicators
    if demisto.params().get('create_relationships') is True:
        relationships = create_list_relationships({'page': scan_page}, url_query,
                                                  client.reliability)
    outputs = {
        'URLScan(val.URL && val.URL == obj.URL)': cont,
        outputPaths['file']: file_context
    }

    if 'screenshotURL' in scan_tasks:
        human_readable['Screenshot'] = scan_tasks['screenshotURL']
        screen_path = scan_tasks['screenshotURL']
        response_img = requests.request("GET", screen_path, verify=client.use_ssl)
        stored_img = fileResult('screenshot.png', response_img.content)

    dbot_score = Common.DBotScore(indicator=dbot_score.get('Indicator'), indicator_type=dbot_score.get('Type'),
                                  integration_name=BRAND, score=dbot_score.get('Score'),
                                  reliability=dbot_score.get('Reliability'))

    url = Common.URL(url=url_cont.get('Data'), dbot_score=dbot_score, relationships=relationships,
                     feed_related_indicators=url_cont.get('FeedRelatedIndicators'))

    command_result = CommandResults(
        readable_output=tableToMarkdown('{} - Scan Results'.format(url_query), human_readable),
        outputs=outputs,
        indicator=url,
        raw_response=response,
        relationships=relationships
    )

    demisto.results(command_result.to_context())

    if len(cert_md) > 0:
        demisto.results({
            'Type': entryTypes['note'],
            'ContentsFormat': formats['markdown'],
            'Contents': tableToMarkdown('Certificates', cert_md, CERT_HEADERS),
            'HumanReadable': tableToMarkdown('Certificates', cert_md, CERT_HEADERS)
        })
    if 'ips' in scan_lists:
        if isinstance(scan_lists.get('ips'), list):
            feed_related_indicators += scan_lists.get('ips')
        demisto.results({
            'Type': entryTypes['note'],
            'ContentsFormat': formats['markdown'],
            'Contents': tableToMarkdown('Related IPs and ASNs', ip_asn_MD, IP_HEADERS),
            'HumanReadable': tableToMarkdown('Related IPs and ASNs', ip_asn_MD, IP_HEADERS)
        })

    if 'screenshotURL' in scan_tasks:
        demisto.results({
            'Type': entryTypes['image'],
            'ContentsFormat': formats['text'],
            'File': stored_img['File'],
            'FileID': stored_img['FileID'],
            'Contents': ''
        })
Exemplo n.º 19
0
def main():
    base_url = demisto.params().get('base_url',
                                    'https://manage.office.com/api/v1.0/')
    verify_certificate = not demisto.params().get('insecure', False)

    first_fetch_delta = demisto.params().get('first_fetch_delta',
                                             '10 minutes').strip()
    first_fetch_datetime, _ = parse_date_range(first_fetch_delta)

    proxy = demisto.params().get('proxy', False)

    LOG(f'Command being called is {demisto.command()}')
    try:
        if demisto.command() == 'test-module':
            result = test_module()
            return_error(result)

        args = demisto.args()
        params = demisto.params()
        refresh_token = params.get('refresh_token', '')
        self_deployed = params.get('self_deployed', False)
        tenant_id = refresh_token if self_deployed else ''
        auth_id = params['auth_id']
        enc_key = params['enc_key']

        refresh_token = (
            demisto.getIntegrationContext().get('current_refresh_token')
            or refresh_token)

        client = Client(base_url=base_url,
                        tenant_id=tenant_id,
                        verify=verify_certificate,
                        proxy=proxy,
                        self_deployed=self_deployed,
                        refresh_token=refresh_token,
                        auth_and_token_url=auth_id,
                        enc_key=enc_key,
                        auth_code=params.get('auth_code', ''))

        access_token, token_data = client.get_access_token_data()
        client.access_token = access_token
        client.tenant_id = token_data['tid']

        if demisto.command() == 'fetch-incidents':
            next_run, incidents = fetch_incidents(
                client=client,
                last_run=demisto.getLastRun(),
                first_fetch_datetime=first_fetch_datetime)

            demisto.setLastRun(next_run)
            demisto.incidents(incidents)

        elif demisto.command() == 'ms-management-activity-start-subscription':
            start_or_stop_subscription_command(client, args, 'start')

        elif demisto.command() == 'ms-management-activity-stop-subscription':
            start_or_stop_subscription_command(client, args, 'stop')

        elif demisto.command() == 'ms-management-activity-list-subscriptions':
            list_subscriptions_command(client)

        elif demisto.command() == 'ms-management-activity-list-content':
            list_content_command(client, args)

    # Log exceptions
    except Exception as e:
        return_error(
            f'Failed to execute {demisto.command()} command. Error: {str(e)}')
Exemplo n.º 20
0
"""GLOBALS/PARAMS
Attributes:
    INTEGRATION_NAME:
        Name of the integration as shown in the integration UI, for example: Microsoft Graph User.

    INTEGRATION_COMMAND_NAME:
        Command names should be written in all lower-case letters,
        and each word separated with a hyphen, for example: msgraph-user.

    INTEGRATION_CONTEXT_NAME:
        Context output names should be written in camel case, for example: MSGraphUser.
"""
INTEGRATION_NAME = 'AlienVault OTX v2'
INTEGRATION_COMMAND_NAME = 'alienvault'
INTEGRATION_CONTEXT_NAME = 'AlienVaultOTX'
DEFAULT_THRESHOLD = int(demisto.params().get('default_threshold', 2))
TOKEN = demisto.params().get('api_token')


class Client(BaseClient):
    def test_module(self) -> Dict:
        """Performs basic GET request to check if the API is reachable and authentication is successful.

        Returns:
            Response json
        """
        return self.query(section='IPv4', argument='8.8.8.8')

    def query(self,
              section: str,
              argument: str = None,
Exemplo n.º 21
0
def fetch():
    """
    Query viewer should be defined in ArcSight ESM. fetch incidents fetches the results of query viewer
    and converts them to Demisto incidents. We can query Cases or Events. If Cases are fetched then the
    query viewer query must return fields ID and Create Time. If Events are fetched then Event ID and Start Time.
    """
    events_query_viewer_id = demisto.params().get('viewerId')
    cases_query_viewer_id = demisto.params().get('casesQueryViewerId')
    type_of_incident = 'case' if events_query_viewer_id else 'event'
    last_run = json.loads(demisto.getLastRun().get('value', '{}'))
    already_fetched = last_run.get('already_fetched', [])

    fields, query_results = get_query_viewer_results(events_query_viewer_id
                                                     or cases_query_viewer_id)
    # sort query_results by creation time
    query_results.sort(
        key=lambda k: int(k.get('Start Time') or k.get('Create Time')))

    incidents = []
    for result in query_results:
        # convert case or event to demisto incident
        r_id = result.get('ID') or result.get('Event ID')
        if r_id not in already_fetched:
            create_time_epoch = int(
                result.get('Start Time') or result.get('Create Time'))
            result['Create Time'] = parse_timestamp_to_datestring(
                create_time_epoch)
            incident_name = result.get(
                'Name') or 'New {} from arcsight at {}'.format(
                    type_of_incident, datetime.now())
            labels = [{
                'type': key.encode('utf-8'),
                'value': value.encode('utf-8') if value else value
            } for key, value in result.items()]
            incident = {
                'name': incident_name,
                'occurred': result['Create Time'],
                'labels': labels,
                'rawJSON': json.dumps(result)
            }

            incidents.append(incident)

            if len(already_fetched) > MAX_UNIQUE:
                already_fetched.pop(0)
            already_fetched.append(r_id)

            if len(incidents) >= FETCH_CHUNK_SIZE:
                break

    last_run = {
        'already_fetched': already_fetched,
    }
    demisto.setLastRun({'value': json.dumps(last_run)})
    decode_arcsight_output(incidents)

    if demisto.command() == 'as-fetch-incidents':
        contents = {
            'last_run': last_run,
            'last_run_updated': demisto.getLastRun(),
            'incidents': incidents,
            'already_fetched': already_fetched
        }
        return_outputs(readable_output='', outputs={}, raw_response=contents)
    else:
        demisto.incidents(incidents)
Exemplo n.º 22
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import requests
import os

# disable insecure warnings
requests.packages.urllib3.disable_warnings()

if not demisto.params().get('useProxy', False):
    del os.environ['HTTP_PROXY']
    del os.environ['HTTPS_PROXY']
    del os.environ['http_proxy']
    del os.environ['https_proxy']
''' GLOBAL VARS '''
SERVER_URL_V1 = 'https://www.cymon.io:443/api/nexus/v1'
SERVER_DASHBOARD_URL_V1 = 'https://www.cymon.io:443/api/dashboard/v1'
SERVER_URL_V2 = 'https://api.cymon.io/v2/ioc/search'

VERIFY_CERTIFICATES = False if demisto.params().get('unsecure') else True

DEFAULT_HEADERS = {"Content-Type": "application/json"}
''' HELPER FUNCTIONS '''


def cymon_says():
    return_error(
        'Cymon service discontinued. Please disable or delete the integration instance.'
    )
Exemplo n.º 23
0
def main():
    params = {k: v for k, v in demisto.params().items() if v is not None}
    params['feed_name_to_config'] = get_feed_config(
        params.get('services', ['AMAZON']),
        argToList(params.get('regions', [])))
    feed_main(params, 'AWS Feed', 'aws')
Exemplo n.º 24
0
def get_ip_report_command():
    """
    corresponds to 'vt-get-ip-report' command. Retrieves a report about an ip
    """

    args = demisto.args()
    ip = args['ip']
    threshold = int(
        args.get('threshold', None)
        or demisto.params().get('ipThreshold', None) or 10)
    full_response = FULL_RESPONSE or args.get('fullResponse', None) == 'true'
    if (full_response):
        max_len = 1000
    else:
        max_len = 50

    response = get_ip_report(ip)

    if (response.get('response_code') == -1):
        return "Invalid IP address "
    elif (response.get('response_code') == 0):
        return {
            'Type':
            entryTypes['note'],
            'Contents':
            response,
            'ContentsFormat':
            formats['json'],
            'EntryContext': {
                "DBotScore": {
                    'Indicator': ip,
                    'Type': 'ip',
                    'Vendor': 'VirusTotal - Private API',
                    'Score': 0
                }
            },
            'HumanReadable':
            "IP " + ip +
            "not in Virus Total's dataset. Virus Total returned the following response: "
            + json.dumps(response.get('verbose_msg'))
        }

    ec = {}  # type: dict
    md = '## VirusTotal IP report for: ' + ip + '\n'
    asn = str(response.get('asn', None)) if response.get('asn', None) else None
    if asn is not None:
        md += 'ASN: **' + asn + ' (' + str(response.get('as_owner',
                                                        '')) + ')**\n'
    md += 'Country: **' + response.get('country', '') + '**\n'

    resolutions = response.get('resolutions', None)

    if resolutions:
        resolutions = resolutions[:max_len]
        md += tableToMarkdown(
            "The following domains resolved to the given IP address:",
            resolutions)

    detected_urls = response.get('detected_urls', None)

    if detected_urls:
        detected_urls = detected_urls[:max_len]
        md += tableToMarkdown(
            "Latest URLs hosted in this IP address detected by at least one URL scanner or malicious URL dataset:",
            detected_urls)

    detected_downloaded_samples = response.get('detected_downloaded_samples',
                                               None)

    if detected_downloaded_samples:
        detected_downloaded_samples = detected_downloaded_samples[:max_len]
        md += tableToMarkdown(
            "Latest files that are detected by at least one antivirus solution and were downloaded by VirusTotal from"
            " the IP address provided", detected_downloaded_samples)

    undetected_downloaded_samples = response.get(
        'undetected_downloaded_samples', None)

    if undetected_downloaded_samples:
        undetected_downloaded_samples = undetected_downloaded_samples[:max_len]
        md += tableToMarkdown(
            "Latest files that are not detected by any antivirus solution and were downloaded by VirusTotal from the "
            "IP address provided", undetected_downloaded_samples)

    detected_communicating_samples = response.get(
        'detected_communicating_samples', None)

    if detected_communicating_samples:
        detected_communicating_samples = detected_communicating_samples[:
                                                                        max_len]
        md += tableToMarkdown(
            "Latest detected files that communicate with this IP address",
            detected_communicating_samples)

    undetected_communicating_samples = response.get(
        'undetected_communicating_samples', None)

    if undetected_communicating_samples:
        undetected_communicating_samples = undetected_communicating_samples[:
                                                                            max_len]
        md += tableToMarkdown(
            "Latest undetected files that communicate with this IP address",
            undetected_communicating_samples)

    detected_referrer_samples = response.get('detected_referrer_samples', None)

    if detected_referrer_samples:
        detected_referrer_samples = detected_referrer_samples[:max_len]
        md += tableToMarkdown(
            "Latest detected files that embed this IP address in their strings",
            detected_referrer_samples)

    undetected_referrer_samples = response.get('undetected_referrer_samples',
                                               None)

    if undetected_referrer_samples:
        undetected_referrer_samples = undetected_referrer_samples[:max_len]
        md += tableToMarkdown(
            "Latest undetected files that embed this IP address in their strings",
            undetected_referrer_samples)

    ec['DBotScore'] = []
    dbotScore = 0
    bad_downloads_amount = len(detected_communicating_samples
                               ) if detected_communicating_samples else 0
    detected_url_is_above_threshold = check_detected_urls_threshold(
        detected_urls,
        demisto.params().get('urlThreshold', None) or 10)
    if (bad_downloads_amount >= threshold or detected_url_is_above_threshold):
        ec.update({
            outputPaths['ip']: {
                'Address': ip,
                'ASN': asn,
                'Geo': {
                    'Country': response.get('country', '')
                },
                'Malicious': {
                    'Description':
                    'Recent malicious downloads: ' + str(bad_downloads_amount),
                    'Vendor':
                    'VirusTotal - Private API'
                }
            }
        })
        dbotScore = 3
    elif (bad_downloads_amount >= threshold / 2
          or len(detected_urls) >= threshold / 2):
        dbotScore = 2
    else:
        dbotScore = 1

    ec['DBotScore'] = {
        'Indicator': ip,
        'Type': 'ip',
        'Vendor': 'VirusTotal - Private API',
        'Score': dbotScore
    }
    if (dbotScore < 3):
        ec.update({
            outputPaths['ip']: {
                'Address': ip,
                'ASN': asn,
                'Geo': {
                    'Country': response.get('country', '')
                }
            }
        })

    ip_ec = {
        'Address': ip,
        'VirusTotal': {
            'DownloadedHashes': detected_downloaded_samples,
            'UnAVDetectedDownloadedHashes': undetected_downloaded_samples,
            "DetectedURLs": detected_urls,
            'CommunicatingHashes': detected_communicating_samples,
            'UnAVDetectedCommunicatingHashes':
            undetected_communicating_samples,
            'Resolutions': resolutions,
            'ReferrerHashes': detected_referrer_samples,
            'UnAVDetectedReferrerHashes': undetected_referrer_samples
        }
    }

    if (ec.get(outputPaths['ip'], False)):
        ec[outputPaths['ip']]['VirusTotal'] = {
            'DownloadedHashes': detected_downloaded_samples,
            'UnAVDetectedDownloadedHashes': undetected_downloaded_samples,
            "DetectedURLs": detected_urls,
            'CommunicatingHashes': detected_communicating_samples,
            'UnAVDetectedCommunicatingHashes':
            undetected_communicating_samples,
            'Resolutions': resolutions,
            'ReferrerHashes': detected_referrer_samples,
            'UnAVDetectedReferrerHashes': undetected_referrer_samples
        }
    else:
        ec[outputPaths['ip']].update(ip_ec)

    return {
        'Type': entryTypes['note'],
        'Contents': response,
        'ContentsFormat': formats['json'],
        'ReadableContentsFormat': formats['markdown'],
        'HumanReadable': md,
        'EntryContext': ec
    }
Exemplo n.º 25
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''

import json
import requests
import dateparser
from typing import Dict

# Disable insecure warnings
requests.packages.urllib3.disable_warnings()
''' GLOBALS/PARAMS '''

CLIENT_ID = demisto.params().get('client_id')
CLIENT_SECRET = demisto.params().get('client_secret')
# Remove trailing slash to prevent wrong URL path to service
SERVER = demisto.params().get('url', '').strip('/')

# Should we use SSL
USE_SSL = not demisto.params().get('insecure', False)
IS_FETCH = demisto.params().get('isFetch')
# How much time before the first fetch to retrieve incidents
FETCH_TIME = demisto.params().get('fetch_time', '3 days')
# Service base URL
BASE_URL = SERVER + '/api/2.0'
# Headers to be sent in requests
HEADERS = {'Content-Type': 'application/json', 'Accept': 'application/json'}
TIME_FORMAT = demisto.params().get('time_format', 'auto-discovery')
AUTH_TOKEN = ''
''' HELPER FUNCTIONS '''
Exemplo n.º 26
0
def get_domain_report_command():
    """
    corresponds to 'vt-get-domain-report' command. Retrieves a report about a domain
    """

    # variables
    args = demisto.args()
    domain = args['domain']
    threshold = int(
        args.get('threshold', None)
        or demisto.params().get('domainThreshold', None) or 10)
    full_response = FULL_RESPONSE or args.get('fullResponse', None) == 'true'
    if (full_response):
        max_len = 1000
    else:
        max_len = 50
    md = ''

    # VT Response
    response = get_domain_report(domain)
    if (response.get('response_code') == -1):
        return "Invalid domain"
    elif (response.get('response_code') == 0):
        return {
            'Type':
            entryTypes['note'],
            'Contents':
            response,
            'ContentsFormat':
            formats['json'],
            'EntryContext': {
                "DBotScore": {
                    'Indicator': domain,
                    'Type': 'domain',
                    'Vendor': 'VirusTotal - Private API',
                    'Score': 0
                }
            },
            'HumanReadable':
            "Domain " + domain +
            " not in Virus Total's dataset. Virus Total returned the following response: "
            + json.dumps(response.get('verbose_msg'))
        }

    communicating_hashes = response.get('detected_communicating_samples', None)
    communicating_malware_hashes = []
    if communicating_hashes:
        for d_hash in communicating_hashes:
            positives = d_hash.get('positives')
            if (positives >= threshold):
                communicating_malware_hashes.append(d_hash)

        communicating_malware_hashes = communicating_malware_hashes[:max_len]
        md += tableToMarkdown(
            "Latest detected files that communicated with " + domain,
            communicating_malware_hashes)

    downloaded_hashes = response.get('detected_downloaded_samples', None)
    downloaded_malware_hashes = []
    if downloaded_hashes:
        for d_hash in downloaded_hashes:
            positives = d_hash.get('positives')
            if (positives >= threshold):
                downloaded_malware_hashes.append(d_hash)
        downloaded_malware_hashes = downloaded_malware_hashes[:max_len]
        md += tableToMarkdown(
            "Latest detected files that were downloaded from " + domain,
            downloaded_malware_hashes)

    resolutions = response.get('resolutions', None)
    resolutions_list = []
    if resolutions:
        for res in resolutions:
            resolutions_list.append(res)
        resolutions_list = resolutions_list[:max_len]
        md += tableToMarkdown(
            domain + " has been resolved to the following IP addresses:",
            resolutions_list)

    whois = response.get('whois', None)
    if whois is not None:
        md += "## Whois analysis: \n"
        md += whois + '\n'

    subdomains = response.get('subdomains', None)
    if subdomains is not None:
        subdomains = list(set(subdomains))[:max_len]
        md += tableToMarkdown("Observed subdomains", [{
            'Domain': d
        } for d in subdomains])

    categories = response.get('categories', None)
    if categories is not None:
        categories = list(set(categories))[:max_len]

    domain_ec = {
        'DownloadedHashes': downloaded_malware_hashes,
        'CommunicatingHashes': communicating_malware_hashes,
        'Resolutions': resolutions_list,
        'Whois': whois,
        'Subdomains': subdomains,
        'Categories': categories
    }

    return {
        'Type': entryTypes['note'],
        'Contents': response,
        'ContentsFormat': formats['json'],
        'ReadableContentsFormat': formats['markdown'],
        'HumanReadable': md,
        'EntryContext': {
            outputPaths['domain']: {
                "Name": domain,
                "VirusTotal": domain_ec
            }
        }
    }
Exemplo n.º 27
0
from CommonServerUserPython import *
''' IMPORTS '''
import requests
import json
import time
import sys

# disable insecure warnings
requests.packages.urllib3.disable_warnings()

# Define utf8 as default encoding
reload(sys)
sys.setdefaultencoding('utf8')  # pylint: disable=E1101
''' GLOBAL VARS '''
SERVER_URL = 'https://www.virustotal.com/vtapi/v2/'
API_KEY = demisto.params().get('APIKey', '')

USE_SSL = False if demisto.params().get('insecure') else True
PREFERRED_VENDORS = demisto.params().get("preferredVendors", None)
PREFERRED_VENDORS_THRESHOLD = demisto.params().get("preferredVendorsThreshold",
                                                   None)

FULL_RESPONSE = demisto.params().get("fullResponseGlobal", False)

DEFAULT_HEADERS = {
    "Accept-Encoding": "gzip, deflate",
    "User-Agent":
    "gzip,  My Python requests library example client or username"
}
''' HELPER FUNCTIONS '''
Exemplo n.º 28
0
def get_entries_command():
    resource_id = demisto.args().get('resourceId')
    entry_filter = demisto.args().get('entryFilter')
    use_rest = demisto.params().get('use_rest', False)

    if use_rest:
        query_path = 'www/manager-service/rest/ActiveListService/getEntries'
        params = {'alt': 'json'}
        body = {
            "act.getEntries": {
                "act.authToken": AUTH_TOKEN,
                "act.resourceId": resource_id,
            }
        }  # type: Union[str, Dict[str, Dict[str, Any]]]
        res = send_request(query_path, json=body, params=params)
    else:
        query_path = 'www/manager-service/services/ActiveListService/'
        body = REQ_SOAP_BODY(function='getEntries',
                             auth_token=AUTH_TOKEN,
                             resource_id=resource_id,
                             entryList=None)
        res = send_request(query_path, body=body)

    if not res.ok:
        demisto.debug(res.text)
        return_error(
            "Failed to get entries:\nResource ID: {}\nStatus Code: {}\nRequest Body: {}\nResponse: {}"
            .format(resource_id, res.status_code, body, res.text))

    if use_rest:
        res_json = res.json()
        raw_entries = res_json.get('act.getEntriesResponse',
                                   {}).get('act.return', {})
    else:
        res_json = json.loads(xml2json((res.text).encode('utf-8')))
        raw_entries = demisto.get(res_json,
                                  'Envelope.Body.getEntriesResponse.return')

    # retrieve columns
    cols = demisto.get(raw_entries, 'columns')
    if cols:
        hr_columns = tableToMarkdown(
            name='', headers=['Columns'], t=cols,
            removeNull=True) if cols else 'Active list has no columns'
        contents = cols
        return_outputs(readable_output=hr_columns,
                       outputs={},
                       raw_response=contents)

    if 'entryList' in raw_entries:
        entry_list = raw_entries['entryList'] if isinstance(
            raw_entries['entryList'], list) else [raw_entries['entryList']]
        entry_list = [
            (d['entry'] if not isinstance(d['entry'], STRING_TYPES) else
             (d['entry'], )) for d in entry_list if 'entry' in d
        ]
        keys = raw_entries.get('columns')
        entries = [dict(zip(keys, values)) for values in entry_list]

        # if the user wants only entries that contain certain 'field:value' sets (filters)
        # e.g., "name:myName,eventId:0,:ValueInUnknownField"
        # if the key is empty, search in every key
        filtered_entries = filter_entries(entries, entry_filter)

        contents = decode_arcsight_output(filtered_entries)
        ActiveListContext = {
            'ResourceID': resource_id,
            'Entries': contents,
        }
        outputs = {
            'ArcSightESM.ActiveList.{id}'.format(id=resource_id):
            contents,
            'ArcSightESM.ActiveList(val.ResourceID===obj.ResourceID)':
            ActiveListContext
        }
        human_readable = tableToMarkdown(
            name='Active List entries: {}'.format(resource_id),
            t=filtered_entries,
            removeNull=True)
        return_outputs(readable_output=human_readable,
                       outputs=outputs,
                       raw_response=entries)

    else:
        demisto.results('Active List has no entries')
Exemplo n.º 29
0
def main():
    command = demisto.command()
    params = demisto.params()
    """
        PARSE AND VALIDATE INTEGRATION PARAMS
    """
    base_url = params.get('url')
    verify_certificate = not params.get('insecure', False)
    proxy = params.get('proxy', False)
    api_key = params.get('apikey', {})

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

    client = Client(base_url=base_url,
                    verify=verify_certificate,
                    proxy=proxy,
                    ok_codes=[200],
                    auth=requests.auth.HTTPBasicAuth(api_key, ''))

    try:
        '''EXECUTION CODE'''
        if command == 'bitsight-get-company-details':
            readable_output, context, res_json = get_company_details_command(
                client, demisto.args())
            results = CommandResults(readable_output=readable_output,
                                     outputs_prefix='BitSight.Company',
                                     outputs=context,
                                     outputs_key_field='guid',
                                     raw_response=res_json)
            return_results(results)
        elif command == 'bitsight-get-company-findings':
            readable_output, context, res_json = get_company_findings_command(
                client, demisto.args())
            results = CommandResults(readable_output=readable_output,
                                     outputs_prefix='BitSight.Finding',
                                     outputs=context,
                                     outputs_key_field='guid',
                                     raw_response=res_json)
            return_results(results)
        elif command == 'test-module':
            human_readable, outputs, raw_response = test_module(client)
            return_outputs(readable_output=human_readable,
                           outputs=outputs,
                           raw_response=raw_response)
        elif command == 'bitsight-get-companies-guid':
            readable_output, context, res_json = get_companies_guid_command(
                client)
            results = CommandResults(readable_output=readable_output,
                                     outputs_prefix='BitSight.GUID',
                                     outputs=context,
                                     outputs_key_field='temporary_id',
                                     raw_response=res_json)
            return_results(results)
        elif command == 'fetch-incidents':
            last_run = demisto.getLastRun()

            last_run_curr, events = fetch_incidents(client, last_run, params)

            if last_run != last_run_curr:
                demisto.setLastRun({'time': last_run_curr['time']})
                demisto.incidents(events)
            else:
                demisto.incidents([])

    # Log exceptions
    except Exception:
        return_error(
            f'Failed to execute {demisto.command()} command. Traceback: {traceback.format_exc()}'
        )
Exemplo n.º 30
0
def main() -> None:
    """main function, parses params and runs command functions

    :return:
    :rtype:
    """

    creds = demisto.params().get('credentials')
    base_url = demisto.params().get('url')
    adom = demisto.params().get('adom')
    verify_certificate = not demisto.params().get('insecure', False)
    proxy = demisto.params().get('proxy', False)

    demisto.debug(f'Command being called is {demisto.command()}')
    try:
        client = Client(url=base_url,
                        credentials=creds,
                        verify=verify_certificate,
                        proxy=proxy,
                        adom=adom)

        if demisto.command() == 'test-module':
            try:
                list_adom_devices_command(client, {})
            except DemistoException as e:
                if 'No permission for the resource' in str(e):
                    raise DemistoException(
                        "Unable to connect to the FortiManager Server - please check the "
                        "entered credentials and ADOM.")

                if 'Invalid url' in str(e):
                    raise DemistoException(
                        "Unable to connect to the default ADOM - please check the "
                        "entered credentials and ADOM.")

                else:
                    raise

            return_results("ok")

        elif demisto.command() == 'fortimanager-devices-list':
            return_results(list_adom_devices_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-device-groups-list':
            return_results(
                list_adom_devices_groups_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-address-list':
            return_results(
                list_firewall_addresses_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-address-create':
            return_results(create_address_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-address-update':
            return_results(update_address_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-address-delete':
            return_results(delete_address_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-address-group-list':
            return_results(list_address_groups_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-address-group-create':
            return_results(create_address_group_command(
                client, demisto.args()))

        elif demisto.command() == 'fortimanager-address-group-update':
            return_results(update_address_group_command(
                client, demisto.args()))

        elif demisto.command() == 'fortimanager-address-group-delete':
            return_results(delete_address_group_command(
                client, demisto.args()))

        elif demisto.command() == 'fortimanager-service-categories-list':
            return_results(
                list_service_categories_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-service-group-list':
            return_results(list_service_groups_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-service-group-create':
            return_results(create_service_group_command(
                client, demisto.args()))

        elif demisto.command() == 'fortimanager-service-group-update':
            return_results(update_service_group_command(
                client, demisto.args()))

        elif demisto.command() == 'fortimanager-service-group-delete':
            return_results(delete_service_group_command(
                client, demisto.args()))

        elif demisto.command() == 'fortimanager-custom-service-list':
            return_results(list_custom_service_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-custom-service-create':
            return_results(
                create_custom_service_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-custom-service-update':
            return_results(
                update_custom_service_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-custom-service-delete':
            return_results(
                delete_custom_service_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-firewall-policy-package-list':
            return_results(list_policy_packages_command(
                client, demisto.args()))

        elif demisto.command(
        ) == 'fortimanager-firewall-policy-package-create':
            return_results(
                create_policy_package_command(client, demisto.args()))

        elif demisto.command(
        ) == 'fortimanager-firewall-policy-package-update':
            return_results(
                update_policy_package_command(client, demisto.args()))

        elif demisto.command(
        ) == 'fortimanager-firewall-policy-package-delete':
            return_results(
                delete_policy_package_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-firewall-policy-list':
            return_results(list_policies_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-firewall-policy-create':
            return_results(create_policy_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-firewall-policy-update':
            return_results(update_policy_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-firewall-policy-delete':
            return_results(delete_policy_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-firewall-policy-move':
            return_results(move_policy_command(client, demisto.args()))

        elif demisto.command() == 'fortimanager-dynamic-interface-list':
            return_results(
                list_dynamic_interface_command(client, demisto.args()))

        elif demisto.command(
        ) == 'fortimanager-firewall-policy-package-install':
            return_results(
                install_policy_package_command(client, demisto.args()))

        elif demisto.command(
        ) == 'fortimanager-firewall-policy-package-install-status':
            return_results(
                install_policy_package_status_command(client, demisto.args()))

    # Log exceptions and return errors
    except Exception:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(
            f'Failed to execute {demisto.command()} command.\nError:\n{traceback.format_exc()}'
        )
Exemplo n.º 31
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import os
import requests
import json
from pancloud import LoggingService, Credentials
import base64
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

# disable insecure warnings
requests.packages.urllib3.disable_warnings()

''' GLOBAL VARS '''
AUTH_ID = demisto.params().get('auth_id')
# If there's a stored token in integration context, it's newer than current
TOKEN = demisto.getIntegrationContext().get('token')
if not TOKEN:
    TOKEN = demisto.params().get('token')

ENC_KEY = demisto.params().get('auth_key')

USE_SSL = not demisto.params().get('insecure', False)
TOKEN_RETRIEVAL_URL = 'https://demistobot.demisto.com/panw-token'
FETCH_QUERY = None

FIRST_FETCH_TIMESTAMP = demisto.params().get('first_fetch_timestamp', '').strip()
if not FIRST_FETCH_TIMESTAMP:
    FIRST_FETCH_TIMESTAMP = '24 hours'
Exemplo n.º 32
0
import demistomock as demisto  # noqa: F401
from CommonServerPython import *  # noqa: F401
import hashlib
from datetime import datetime
import uuid
import json
import requests
import re
import platform
import os.path
import copy

# disable insecure warnings
requests.packages.urllib3.disable_warnings()

if not demisto.params().get("proxy", True):
    del os.environ["HTTP_PROXY"]
    del os.environ["HTTPS_PROXY"]
    del os.environ["http_proxy"]
    del os.environ["https_proxy"]

# HELPER FUNCTIONS #


def load_host_url():
    ''' loads the host url from the configuration or strips the server url to get valid host url '''
    host = demisto.params()['ip_address']
    if host:
        # strip https://www. of the server address //disable-secrets-detection
        url = re.compile(r"https?://(www\.)?")
        host = url.sub('', demisto.params()['server']).strip().strip('/')
Exemplo n.º 33
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
import re
import requests
import json
import shutil

# disable insecure warnings
requests.packages.urllib3.disable_warnings()

if not demisto.params().get('proxy', False):
    del os.environ['HTTP_PROXY']
    del os.environ['HTTPS_PROXY']
    del os.environ['http_proxy']
    del os.environ['https_proxy']


def get_server_url():
    url = demisto.params()['url']
    url = re.sub('/[\/]+$/', '', url)
    url = re.sub('\/$', '', url)
    return url


''' GLOBAL VARIABLES '''

DEFAULTS = {
    'limit': 10,
    'offset': 0,
    'fetch_limit': 10,
Exemplo n.º 34
0
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
import mimetypes
import random
import string
from apiclient import discovery
from oauth2client.client import AccessTokenCredentials
import itertools as it
import urllib.parse
from typing import Tuple
import secrets
import hashlib
''' GLOBAL VARS '''
params = demisto.params()
EMAIL = params.get('email', '')
PROXY = params.get('proxy')
DISABLE_SSL = params.get('insecure', False)
FETCH_TIME = params.get('fetch_time', '1 days')
AUTH_CODE = params.get('code')

CLIENT_ID = params.get(
    'client_id'
) or "391797357217-pa6jda1554dbmlt3hbji2bivphl0j616.apps.googleusercontent.com"
TOKEN_URL = "https://www.googleapis.com/oauth2/v4/token"
TOKEN_FORM_HEADERS = {
    "Content-Type": "application/x-www-form-urlencoded",
    'Accept': 'application/json',
}
Exemplo n.º 35
0
def main() -> None:
    api_key = demisto.params().get('apikey')
    base_url = demisto.params().get('url')
    verify_certificate = not demisto.params().get('insecure', False)

    # How much time before the first fetch to retrieve incidents
    first_fetch_time = arg_to_timestamp(arg=demisto.params().get(
        'first_fetch', '3 days'),
                                        arg_name='First fetch time',
                                        required=True)
    proxy = demisto.params().get('proxy', False)
    demisto.debug(f'Command being called is {demisto.command()}')
    try:
        headers = {'Authorization': api_key}
        client = Client(base_url=base_url,
                        verify=verify_certificate,
                        headers=headers,
                        proxy=proxy)

        if demisto.command() == 'test-module':
            return_results(test_module(client, first_fetch_time))

        elif demisto.command() == 'fetch-incidents':
            query = demisto.params().get('query', None)
            max_results = arg_to_int(arg=demisto.params().get('max_fetch'),
                                     arg_name='max_fetch')
            if not max_results or max_results > MAX_INCIDENTS_TO_FETCH:
                max_results = MAX_INCIDENTS_TO_FETCH

            next_run, incidents = fetch_incidents(
                client=client,
                max_results=max_results,
                last_run=demisto.getLastRun(),
                first_fetch_time=first_fetch_time,
                query=query,
                mirror_direction=demisto.params().get('mirror_direction'),
                mirror_tag=demisto.params().get('mirror_tag'))
            demisto.setLastRun(next_run)
            demisto.incidents(incidents)

        elif demisto.command() == 'xsoar-search-incidents':
            return_results(search_incidents_command(client, demisto.args()))

        elif demisto.command() == 'xsoar-get-incident':
            return_results(get_incident_command(client, demisto.args()))

        elif demisto.command() == 'get-mapping-fields':
            return_results(get_mapping_fields_command(client))

        elif demisto.command() == 'get-remote-data':
            return_results(
                get_remote_data_command(client, demisto.args(),
                                        demisto.params()))

        elif demisto.command() == 'update-remote-system':
            return_results(
                update_remote_system_command(
                    client, demisto.args(),
                    demisto.params().get('mirror_tag')))

    # 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)}'
        )
Exemplo n.º 36
0
# std py packages

# 3-rd party py packages
import requests

# local py packages
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *

# Disable insecure warnings
requests.packages.urllib3.disable_warnings()

''' GLOBALS/PARAMS '''
# Parameters received from the user
PARAMS = demisto.params()

# TOKEN
TOKEN = PARAMS.get('token')

# Service base URL
BASE_URL = 'https://jsonwhois.com'

# Headers to be sent in requests
HEADERS = {
    'Accept': 'application/json',
    'Authorization': f'Token token={TOKEN}'
}

# Self signed certificate so no need to verify by default
USE_SSL = not PARAMS.get('insecure', False)
Exemplo n.º 37
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *

""" IMPORTS """
from datetime import datetime
import requests
import base64

# disable insecure warnings
requests.packages.urllib3.disable_warnings()

""" GLOBALS """
MAX_UNIQUE = int(demisto.params().get('max_unique', 2000))
FETCH_CHUNK_SIZE = int(demisto.params().get('fetch_chunk_size', 50))
BASE_URL = demisto.params().get('server').rstrip('/') + '/'
VERIFY_CERTIFICATE = not demisto.params().get('insecure', True)
HEADERS = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
}

REQ_SOAP_BODY = """<?xml version="1.0" encoding="UTF-8"?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:act="http://ws.v1.service.resource.manager.product.arcsight.com/activeListService/">
    <soapenv:Header />
        <soapenv:Body>
            <act:{function}>
                <act:authToken>{auth_token}</act:authToken>
                <act:resourceId>{resource_id}</act:resourceId>
                {entryList}
Exemplo n.º 38
0
def get_server_url():
    url = demisto.params()['url']
    url = re.sub('/[\/]+$/', '', url)
    url = re.sub('\/$', '', url)
    return url
Exemplo n.º 39
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
import boto3
from botocore.config import Config
from botocore.parsers import ResponseParserError
import urllib3.util
from datetime import datetime, date

# Disable insecure warnings
urllib3.disable_warnings()

AWS_DEFAULT_REGION = demisto.params()['defaultRegion']
AWS_ROLE_ARN = demisto.params()['roleArn']
AWS_ROLE_SESSION_NAME = demisto.params()['roleSessionName']
AWS_ROLE_SESSION_DURATION = demisto.params()['sessionDuration']
AWS_ROLE_POLICY = None
AWS_ACCESS_KEY_ID = demisto.params().get('access_key')
AWS_SECRET_ACCESS_KEY = demisto.params().get('secret_key')
VERIFY_CERTIFICATE = not demisto.params().get('insecure', True)
proxies = handle_proxy(proxy_param_name='proxy', checkbox_default_value=False)
config = Config(connect_timeout=1,
                retries=dict(max_attempts=5),
                proxies=proxies)
"""HELPER FUNCTIONS"""


def aws_session(service='cloudtrail',
                region=None,
                roleArn=None,
                roleSessionName=None,
Exemplo n.º 40
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
'''IMPORTS'''

import snowflake.connector
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from datetime import date, timedelta, datetime
from datetime import time as dttime
from decimal import Decimal

'''GLOBAL VARS'''

PARAMS = demisto.params()
CREDENTIALS = PARAMS.get('credentials')
USER = CREDENTIALS.get('identifier')
PASSWORD = CREDENTIALS.get('password')
CERTIFICATE = CREDENTIALS.get('credentials', {}).get('sshkey').encode()
CERT_PASSWORD = CREDENTIALS.get('credentials', {}).get('password')
CERT_PASSWORD = CERT_PASSWORD.encode() if CERT_PASSWORD else None
ACCOUNT = PARAMS.get('account')
AUTHENTICATOR = PARAMS.get('authenticator')
REGION = PARAMS.get('region')
WAREHOUSE = PARAMS.get('warehouse')
DATABASE = PARAMS.get('database')
SCHEMA = PARAMS.get('schema')
ROLE = PARAMS.get('role')
INSECURE = PARAMS.get('insecure', False)
# How much time before the first fetch to retrieve incidents
IS_FETCH = PARAMS.get('isFetch')
Exemplo n.º 41
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''

import json
import requests
import os
import os.path

# Disable insecure warnings
requests.packages.urllib3.disable_warnings()

# remove proxy if not set to true in params
if not demisto.params().get('proxy'):
    del os.environ['HTTP_PROXY']
    del os.environ['HTTPS_PROXY']
    del os.environ['http_proxy']
    del os.environ['https_proxy']

''' GLOBALS/PARAMS '''

USERNAME = demisto.params().get('credentials').get('identifier')
PASSWORD = demisto.params().get('credentials').get('password')
SERVER_URL = demisto.params().get('server')[:-1] if demisto.params().get('server').endswith('/') else \
    demisto.params().get('server')
FETCH_TIME = demisto.params().get('fetch_time', '3 days').strip()
FETCH_NOTIFICATIONS = demisto.params().get('fetch_notifications')
FETCH_BEHAVIORS = demisto.params().get('fetch_behviors')

# Should we use SSL
Exemplo n.º 42
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
'''IMPORTS'''

import requests
from datetime import datetime

'''GLOBAL VARS'''

PARAMS = demisto.params()
USE_SSL = not demisto.params().get('unsecure')
TENANT_ID = PARAMS.get('tenant_id')
TOKEN = PARAMS.get('token')
HOST = PARAMS.get('host', 'https://management.azure.com')
SERVER = HOST[:-1] if HOST.endswith('/') else HOST
API_VERSION = '2018-06-01'
HEADERS = {}
SUBSCRIPTION_ID = None
BASE_URL = None

# Image options to be used in the create_vm_command
IMAGES = {
    'ubuntu server 14.04 lts': {
        'publisher': 'Canonical',
        'offer': 'UbuntuServer',
        'sku': '14.04-LTS',
        'version': 'latest'
    },
    'ubuntu server 16.04 lts': {
        'publisher': 'Canonical',
Exemplo n.º 43
0
from requests.utils import quote
import time

""" POLLING FUNCTIONS"""
try:
    from Queue import Queue
except ImportError:
    from queue import Queue

# disable insecure warnings
requests.packages.urllib3.disable_warnings()


'''GLOBAL VARS'''
BASE_URL = 'https://urlscan.io/api/v1/'
APIKEY = demisto.params().get('apikey')
THRESHOLD = int(demisto.params().get('url_threshold', '1'))
INSECURE = demisto.params().get('insecure')
PROXY = demisto.params().get('proxy')
if not demisto.params().get('proxy', False):
    del os.environ['HTTP_PROXY']
    del os.environ['HTTPS_PROXY']
    del os.environ['http_proxy']
    del os.environ['https_proxy']


'''HELPER FUNCTIONS'''


def http_request(method, url_suffix, json=None, wait=0, retries=0):
    if method == 'GET':
Exemplo n.º 44
0
def main():
    global URL
    params = demisto.params()
    URL = params.get('api_endpoint')
    try:
        command = demisto.command()
        if command == 'test-module':
            auth_token = get_token()
            if 'error' not in auth_token:
                test_query = ("""
                    query IssuesTable(
                        $filterBy: IssueFilters
                        $first: Int
                        $after: String
                        $orderBy: IssueOrder
                    ) {
                        issues(
                        filterBy: $filterBy
                        first: $first
                        after: $after
                        orderBy: $orderBy
                        ) {
                        nodes {
                            ...IssueDetails
                        }
                        pageInfo {
                            hasNextPage
                            endCursor
                        }
                        totalCount
                        informationalSeverityCount
                        lowSeverityCount
                        mediumSeverityCount
                        highSeverityCount
                        criticalSeverityCount
                        uniqueEntityCount
                        }
                    }

                    fragment IssueDetails on Issue {
                        id
                        control {
                        id
                        name
                        query
                        }
                        createdAt
                        updatedAt
                        projects {
                        id
                        name
                        slug
                        businessUnit
                        riskProfile {
                            businessImpact
                        }
                        }
                        status
                        severity
                        entity {
                        id
                        name
                        type
                        }
                        entitySnapshot {
                        id
                        type
                        name
                        }
                        note
                        serviceTickets {
                        externalId
                        name
                        url
                        action {
                            id
                            type
                        }
                        }
                    }
                """)

                test_variables = {
                    'first': 1,
                    'filterBy': {
                        'status': [
                            'OPEN',
                            'IN_PROGRESS'
                        ]
                    },
                    'orderBy': {
                        'field': 'SEVERITY',
                        'direction': 'DESC'
                    }
                }

                test_response = checkAPIerrors(test_query, test_variables)

                if 'errors' not in test_response:
                    demisto.results('ok')
                else:
                    demisto.results(test_response)

        elif command == 'fetch-incidents':
            max_fetch = int(demisto.params().get('max_fetch'))
            fetch_issues(
                max_fetch=max_fetch
            )

        elif command == 'wiz-get-issues':
            demisto_args = demisto.args()
            issue_type = demisto_args.get('issue_type')
            resource_id = demisto_args.get('resource_id')
            severity = demisto_args.get('severity')
            issues = get_filtered_issues(
                issue_type=issue_type,
                resource_id=resource_id,
                severity=severity,
                limit=Wiz_API_LIMIT,
            )
            if isinstance(issues, str):
                #  this means the Issue is an error
                command_result = CommandResults(readable_output=issues, raw_response=issues)
            else:
                command_result = CommandResults(outputs_prefix="Wiz.Manager.Issues", outputs=issues,
                                                raw_response=issues)
            return_results(command_result)

        elif command == "wiz-get-resource":
            resource = get_resource(resource_id=demisto.args()['resource_id'])
            command_result = CommandResults(outputs_prefix="Wiz.Manager.Resource", outputs=resource, raw_response=resource)
            return_results(command_result)

        else:
            raise Exception('Unrecognized command: ' + command)
    except Exception as err:
        demisto.error(traceback.format_exc())
        return_error(str(err))
Exemplo n.º 45
0
def main():
    params = demisto.params()
    aws_default_region = params.get('defaultRegion')
    aws_role_arn = params.get('roleArn')
    aws_role_session_name = params.get('roleSessionName')
    aws_role_session_duration = params.get('sessionDuration')
    aws_role_policy = None
    aws_access_key_id = params.get('access_key')
    aws_secret_access_key = params.get('secret_key')
    aws_gd_severity = params.get('gs_severity', '')
    verify_certificate = not params.get('insecure', True)
    timeout = params.get('timeout') or 1
    retries = params.get('retries') or 5

    try:
        validate_params(aws_default_region, aws_role_arn,
                        aws_role_session_name, aws_access_key_id,
                        aws_secret_access_key)

        aws_client = AWSClient(aws_default_region, aws_role_arn,
                               aws_role_session_name,
                               aws_role_session_duration, aws_role_policy,
                               aws_access_key_id, aws_secret_access_key,
                               verify_certificate, timeout, retries)

        client = aws_client.aws_session(service=SERVICE)

        # The command demisto.command() holds the command sent from the user.
        if demisto.command() == 'test-module':
            # This is the call made when pressing the integration test button.
            result = test_function(client)

        if demisto.command() == 'aws-gd-create-detector':
            result = create_detector(client, demisto.args())

        if demisto.command() == 'aws-gd-delete-detector':
            result = delete_detector(client, demisto.args())

        if demisto.command() == 'aws-gd-get-detector':
            result = get_detector(client, demisto.args())

        if demisto.command() == 'aws-gd-update-detector':
            result = update_detector(client, demisto.args())

        if demisto.command() == 'aws-gd-create-ip-set':
            result = create_ip_set(client, demisto.args())

        if demisto.command() == 'aws-gd-delete-ip-set':
            result = delete_ip_set(client, demisto.args())

        if demisto.command() == 'aws-gd-list-detectors':
            result = list_detectors(client, demisto.args())

        if demisto.command() == 'aws-gd-update-ip-set':
            result = update_ip_set(client, demisto.args())

        if demisto.command() == 'aws-gd-get-ip-set':
            result = get_ip_set(client, demisto.args())

        if demisto.command() == 'aws-gd-list-ip-sets':
            result = list_ip_sets(client, demisto.args())

        if demisto.command() == 'aws-gd-create-threatintel-set':
            result = create_threat_intel_set(client, demisto.args())

        if demisto.command() == 'aws-gd-delete-threatintel-set':
            result = delete_threat_intel_set(client, demisto.args())

        if demisto.command() == 'aws-gd-get-threatintel-set':
            result = get_threat_intel_set(client, demisto.args())

        if demisto.command() == 'aws-gd-list-threatintel-sets':
            result = list_threat_intel_sets(client, demisto.args())

        if demisto.command() == 'aws-gd-update-threatintel-set':
            result = update_threat_intel_set(client, demisto.args())

        if demisto.command() == 'aws-gd-list-findings':
            result = list_findings(client, demisto.args())

        if demisto.command() == 'aws-gd-get-findings':
            result = get_findings(client, demisto.args())

        if demisto.command() == 'aws-gd-create-sample-findings':
            result = create_sample_findings(client, demisto.args())

        if demisto.command() == 'aws-gd-archive-findings':
            result = archive_findings(client, demisto.args())

        if demisto.command() == 'aws-gd-unarchive-findings':
            result = unarchive_findings(client, demisto.args())

        if demisto.command() == 'aws-gd-update-findings-feedback':
            result = update_findings_feedback(client, demisto.args())

        if demisto.command() == 'aws-gd-list-members':
            result = list_members(client, demisto.args())

        if demisto.command() == 'aws-gd-get-members':
            result = get_members(client, demisto.args())

        if demisto.command() == 'fetch-incidents':
            fetch_incidents(client, aws_gd_severity)
            sys.exit(0)

        demisto.results(result)
        sys.exit(0)

    except Exception as e:
        return_error(
            'Error has occurred in the AWS GuardDuty Integration: {error}\n {message}'
            .format(error=type(e), message=e.message))
Exemplo n.º 46
0
import demistomock as demisto
from CommonServerPython import *
import subprocess
import uuid

USERNAME = demisto.params()['credentials']['identifier'].replace("'", "''")
PASSWORD = demisto.params()['credentials']['password'].replace("'", "''")
EXCHANGE_FQDN = demisto.params()['exchangeFQDN'].replace("'", "''")
UNSECURE = demisto.params()['insecure']

STARTCS = '''
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$username,
[Parameter(Mandatory=$True)]
[string]$query,
[Parameter(Mandatory=$True)]
[string]$server,
[Parameter(Mandatory=$True)]
[bool]$unsecure
)
$WarningPreference = "silentlyContinue"
$password = Read-Host
$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$UserCredential = New-Object System.Management.Automation.PSCredential ($username, $secpasswd)
$searchName = [guid]::NewGuid().ToString() -replace '[-]'
$searchName = "DemistoSearch" + $searchName
if($unsecure){
    $url = "http://" + $server + "/PowerShell"
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $url `
Exemplo n.º 47
0
    return_error('Please provide Authorization information, Basic(userName & password / API-token) or OAuth1.0')
B64_AUTH = (b64encode((USERNAME + ":" + (API_TOKEN if API_TOKEN else PASSWORD)).encode('ascii'))).decode('ascii')
BASIC_AUTH = 'Basic ' + B64_AUTH
OAUTH = {
    "ConsumerKey": demisto.getParam('consumerKey'),
    "AccessToken": demisto.getParam('accessToken'),
    "PrivateKey": demisto.getParam('privateKey')
} if IS_OAUTH else ''

HEADERS = {
    'Content-Type': 'application/json',
}
if not IS_OAUTH:
    HEADERS['Authorization'] = BASIC_AUTH

USE_SSL = not demisto.params().get('insecure', False)


def jira_req(method, resource_url, body='', link=False):
    url = resource_url if link else (BASE_URL + resource_url)
    result = requests.request(
        method=method,
        url=url,
        data=body,
        headers=HEADERS,
        verify=USE_SSL,
        params=OAUTH,
    )
    if not result.ok:
        demisto.debug(result.text)
        try:
Exemplo n.º 48
0
def main():
    user_profile = None
    params = demisto.params()
    command = demisto.command()
    args = demisto.args()

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

    mapper_in = params.get('mapper_in')
    mapper_out = params.get('mapper_out')
    is_create_enabled = params.get("create_user_enabled")
    is_enable_enabled = demisto.params().get("enable_user_enabled")
    is_disable_enabled = params.get("disable_user_enabled")
    is_update_enabled = demisto.params().get("update_user_enabled")
    create_if_not_exists = demisto.params().get("create_if_not_exists")

    iam_command = IAMCommand(is_create_enabled,
                             is_enable_enabled,
                             is_disable_enabled,
                             is_update_enabled,
                             create_if_not_exists,
                             mapper_in,
                             mapper_out,
                             get_user_iam_attrs=['id', 'userName', 'emails'])

    base_url = 'https://api.slack.com/scim/v1/'
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': f'Bearer {access_token}'
    }

    client = Client(
        base_url=base_url,
        verify=verify_certificate,
        proxy=proxy,
        headers=headers,
        ok_codes=(200, 201),
    )

    group_client = GroupClient(
        base_url=base_url,
        verify=verify_certificate,
        proxy=proxy,
        headers=headers,
    )

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

    if command == 'iam-get-user':
        user_profile = iam_command.get_user(client, args)

    elif command == 'iam-create-user':
        user_profile = iam_command.create_user(client, args)

    elif command == 'iam-update-user':
        user_profile = iam_command.update_user(client, args)

    elif command == 'iam-disable-user':
        user_profile = iam_command.disable_user(client, args)

    if user_profile:
        # user_profile.return_outputs()
        return_results(user_profile)

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

        elif command == 'get-mapping-fields':
            return_results(get_mapping_fields(client))

    except Exception:
        # For any other integration command exception, return an error
        return_error(
            f'Failed to execute {command} command. Traceback: {traceback.format_exc()}'
        )

    if command == 'iam-get-group':
        return_results(get_group_command(group_client, args))

    elif command == 'iam-create-group':
        return_results(create_group_command(group_client, args))

    elif command == 'iam-update-group':
        return_results(update_group_command(group_client, args))

    elif command == 'iam-delete-group':
        return_results(delete_group_command(group_client, args))
Exemplo n.º 49
0
def load_certificate():
    """ Loads the certificate and passphrase from the configuration """
    cert = demisto.params()["certificate"]
    cert = base64.b64decode(cert)
    passphrase = demisto.params()["passphrase"] if "passphrase" in demisto.params() else ""
    return cert, passphrase
Exemplo n.º 50
0
def main():
    """
        PARSE AND VALIDATE INTEGRATION PARAMS
    """

    sg_api_key = demisto.params().get('apiKey')
    sg_from_email = demisto.params().get('fromEmail')
    sg_sender_name = demisto.params().get('fromEmailName')

    try:
        # Passing the API key
        sg = SendGridAPIClient(api_key=sg_api_key)

        command = demisto.command()
        args = demisto.args()

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

        elif demisto.command() == 'sg-send-email':
            result = send_mail(args, sg_from_email, sg_sender_name, sg)

        elif demisto.command() == 'sg-get-global-email-stats':
            result = get_global_email_stats(args, sg)

        elif demisto.command() == 'sg-get-category-stats':
            result = get_category_stats(args, sg)

        elif demisto.command() == 'sg-get-all-categories-stats':
            result = get_all_categories_stats(args, sg)

        elif demisto.command() == 'sg-list-categories':
            result = get_categories_list(args, sg)

        elif demisto.command() == 'sg-create-batch-id':
            result = create_batch_id(sg)

        elif demisto.command() == 'sg-scheduled-status-change':
            result = scheduled_send_status_change(args, sg)

        elif demisto.command() == 'sg-retrieve-all-scheduled-sends':
            result = retrieve_all_scheduled_sends(args, sg)

        elif demisto.command() == 'sg-retrieve-scheduled-send':
            result = retrieve_scheduled_send(args, sg)

        elif demisto.command() == 'sg-update-scheduled-send':
            result = update_scheduled_send(args, sg)

        elif demisto.command() == 'sg-delete-scheduled-send':
            result = delete_scheduled_send(args, sg)

        elif demisto.command() == 'sg-get-email-activity-list':
            result = get_email_activity_list(args, sg)

        elif demisto.command() == 'sg-get-all-lists':
            result = get_all_lists(args, sg)

        elif demisto.command() == 'sg-get-list-by-id':
            result = get_list_by_id(args, sg)

        elif demisto.command() == 'sg-create-list':
            result = create_list(args, sg)

        elif demisto.command() == 'sg-get-list-contact-count-by-id':
            result = get_list_contact_count_by_id(args, sg)

        elif demisto.command() == 'sg-update-list-name':
            result = update_list_name(args, sg)

        elif demisto.command() == 'sg-delete-list':
            result = delete_list(args, sg)

        demisto.results(result)

    # Log exceptions
    except Exception as e:
        if repr(e) == "KeyError('email')":
            return_error(
                f"Failed to execute {demisto.command()} command. Please provide a valid email."
            )
        else:
            return_error(
                f'Failed to execute {demisto.command()} command. Error: {str(e)}'
            )
Exemplo n.º 51
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *

''' IMPORTS '''
import requests

# disable insecure warnings
requests.packages.urllib3.disable_warnings()

# remove proxy if not set to true in params
if not demisto.params().get('proxy', False):
    del os.environ['HTTP_PROXY']
    del os.environ['HTTPS_PROXY']
    del os.environ['http_proxy']
    del os.environ['https_proxy']

''' GLOBALS'''

SERVER = demisto.params().get('server').rstrip('/') + '/api/v1/'
VERIFY_CERTIFICATE = not demisto.params().get('insecure', True)
FETCH_DELTA = demisto.params().get('fetchDelta', '24 hours').strip()
RELEVANT_DEVICE_ENTRIES = {
    'description': 'Description',
    'id': 'ID',
    'ip_address': 'Address',
    'last_seen': 'LastSeen',
    'live': 'Status',
    'location': 'Location',
    'name': 'Name',
    'updated_std': 'LastUpdated',
Exemplo n.º 52
0
def fetch_issues(max_fetch):
    """
    Fetch all Issues (OOB XSOAR Fetch)
    """

    if max_fetch > 500:
        max_fetch = 500

    last_run = demisto.getLastRun().get('time')
    if not last_run:  # first time fetch
        last_run = dateparser.parse(demisto.params().get('first_fetch', '7 days').strip())
        last_run = (last_run.isoformat()[:-3] + 'Z')

    query = ("""
        query IssuesTable(
            $filterBy: IssueFilters
            $first: Int
            $after: String
            $orderBy: IssueOrder
          ) {
            issues(
                filterBy: $filterBy
                first: $first
                after: $after
                orderBy: $orderBy
            ) {
                nodes {
                    ...IssueDetails
                }
                pageInfo {
                    hasNextPage
                    endCursor
                }
                totalCount
                informationalSeverityCount
                lowSeverityCount
                mediumSeverityCount
                highSeverityCount
                criticalSeverityCount
                uniqueEntityCount
            }
        }

        fragment IssueDetails on Issue {
            id
            control {
                id
                name
                query
                description
            }
            createdAt
            updatedAt
            projects {
                id
                name
                slug
                businessUnit
                riskProfile {
                    businessImpact
                }
            }
            status
            severity
            entity {
                id
                name
                type
            }
            entitySnapshot {
                id
                type
                nativeType
                name
                subscriptionId
                subscriptionExternalId
                subscriptionName
                resourceGroupId
                resourceGroupExternalId
                region
                cloudPlatform
                cloudProviderURL
                status
                tags
                providerId
                subscriptionTags
            }
            note
            dueAt
            serviceTicket {
                externalId
                name
                url
            }
            serviceTickets {
                externalId
                name
                url
                action {
                    id
                    type
                }
            }
        }
    """)
    variables = {
        "first": max_fetch,
        "filterBy": {
            "status": [
                "OPEN",
                "IN_PROGRESS"
            ],
            "createdAt": {
                "after":
                    last_run
            },
            "relatedEntity":
                {}
        },
        "orderBy": {
            "field":
                "SEVERITY",
            "direction":
                "DESC"
        }
    }

    response_json = checkAPIerrors(query, variables)

    issues = response_json['data']['issues']['nodes']
    while (response_json['data']['issues']['pageInfo']['hasNextPage']):

        variables['after'] = response_json['data']['issues']['pageInfo']['endCursor']
        response_json = checkAPIerrors(query, variables)
        if response_json['data']['issues']['nodes'] != []:
            issues += (response_json['data']['issues']['nodes'])

    incidents = list()
    for issue in issues:
        incident = build_incidents(issue=issue)
        incidents.append(incident)

    demisto.incidents(incidents)
    demisto.setLastRun(
        {'time': datetime.now().strftime(DEMISTO_OCCURRED_FORMAT)})
Exemplo n.º 53
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''

import requests
import urllib.parse

# Disable insecure warnings
requests.packages.urllib3.disable_warnings()
''' GLOBALS/PARAMS '''

# Remove trailing slash to prevent wrong URL path to service
API_URL = demisto.params()['api_url'].rstrip('/')

# Should we use SSL
USE_SSL = not demisto.params().get('insecure', False)

# Remove proxy if not set to true in params
if not demisto.params().get('proxy'):
    os.environ.pop('HTTP_PROXY', None)
    os.environ.pop('HTTPS_PROXY', None)
    os.environ.pop('http_proxy', None)
    os.environ.pop('https_proxy', None)

CLIENT_ID = demisto.params()['client_id']

CLIENT_SECRET = demisto.params()['client_secret']
''' HELPER FUNCTIONS '''

Exemplo n.º 54
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
""" IMPORTS """
from datetime import datetime
import requests
import base64

# disable insecure warnings
requests.packages.urllib3.disable_warnings()
""" GLOBALS """
MAX_UNIQUE = int(demisto.params().get('max_unique', 2000))
FETCH_CHUNK_SIZE = int(demisto.params().get('fetch_chunk_size', 50))
FETCH_CHUNK_SIZE = min(300,
                       FETCH_CHUNK_SIZE)  # fetch size should no exceed 300

BASE_URL = demisto.params().get('server').rstrip('/') + '/'
VERIFY_CERTIFICATE = not demisto.params().get('insecure', True)
HEADERS = {'Content-Type': 'application/json', 'Accept': 'application/json'}

REQ_SOAP_BODY = """<?xml version="1.0" encoding="UTF-8"?>
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:act="http://ws.v1.service.resource.manager.product.arcsight.com/activeListService/">
    <soapenv:Header />
        <soapenv:Body>
            <act:{function}>
                <act:authToken>{auth_token}</act:authToken>
                <act:resourceId>{resource_id}</act:resourceId>
                {entryList}
            </act:{function}>
        </soapenv:Body>
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *

''' IMPORTS '''
import json
import requests
import shutil

# Disable insecure warnings
requests.packages.urllib3.disable_warnings()

''' GLOBALS/PARAMS '''
URL = demisto.getParam('server')
TOKEN = demisto.getParam('token')
USE_SSL = not demisto.params().get('insecure', False)
DEFAULT_HEADERS = {'Content-Type': 'application/x-www-form-urlencoded'}
MULTIPART_HEADERS = {'Content-Type': "multipart/form-data; boundary=upload_boundry"}

URL_DICT = {
    'verdict': '/get/verdict',
    'verdicts': '/get/verdicts',
    'upload_file': '/submit/file',
    'upload_url': '/submit/link',
    'upload_file_url': '/submit/url',
    'report': '/get/report',
    'sample': '/get/sample'
}

ERROR_DICT = {
    '401': 'Unauthorized, API key invalid',
Exemplo n.º 56
0
def main():
    """
        PARSE AND VALIDATE INTEGRATION PARAMS
    """

    params = demisto.params()

    # get Acalvio API Server url
    base_url = params['url'].rstrip('/')

    # get Acalvio API Key
    apikey = params['apikey']

    # check if SSL is to be verified
    verify_certificate = not params.get('insecure', False)

    proxy = params.get('proxy', False)

    # set the headers
    headers = {
        'api_key': apikey,
        'content-type': 'application/json'
    }

    demisto.info(f'Command being called is \'{demisto.command()}\'')
    result = None

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

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

        elif demisto.command() == 'acalvio-is-deception-host':
            result = \
                do_deception_host_command(client, demisto.args())

        elif demisto.command() == 'acalvio-is-deception-file':
            result = \
                do_deception_file_command(client, demisto.args())

        elif demisto.command() == 'acalvio-is-deception-user':
            result = \
                do_deception_user_command(client, demisto.args())

        elif demisto.command() == 'acalvio-mute-deception-host':
            result = \
                do_mute_deception_host_command(client, demisto.args())

        elif demisto.command() == 'acalvio-unmute-deception-host':
            result = \
                do_unmute_deception_host_command(client, demisto.args())

        elif demisto.command() == 'acalvio-mute-deception-on-endpoint':
            result = \
                do_mute_deception_ep_command(client, demisto.args())

        elif demisto.command() == 'acalvio-unmute-deception-on-endpoint':
            result = \
                do_unmute_deception_ep_command(client, demisto.args())

        return_results(result)

    # Log exceptions
    except DemistoException as de:
        return_error(message=f'Failed to execute \'{demisto.command()}\' command. Error: {str(de)}')
Exemplo n.º 57
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
''' IMPORTS '''
import json
import shutil
import requests
# disable insecure warnings
requests.packages.urllib3.disable_warnings()


''' GLOBALS / PARAMS '''
IS_FETCH = demisto.params()['isFetch']
INCIDENT_TYPE = demisto.params()['incidentType']
SERVER_URL = demisto.params()['server_url']
CREDENTIALS = demisto.params()['credentials']
INSECURE = demisto.params()['unsecure']
PROXY = demisto.params()['proxy']
FETCH_TIME = demisto.params().get('fetch_time', '3 days')
SESSION_ID = None


''' HELPER FUNCTIONS '''


def http_request(method, url_suffix, params=None, data=None, files=None, is_json=True):
    # A wrapper for requests lib to send our requests and handle requests and responses better
    headers = {}
    if SESSION_ID is not None:
        headers['x-uid'] = SESSION_ID
        if files is None:
Exemplo n.º 58
0
import demistomock as demisto

from CommonServerPython import *
from CommonServerUserPython import *

import poplib
import base64
import quopri
from email.parser import Parser
from htmlentitydefs import name2codepoint
from HTMLParser import HTMLParser, HTMLParseError


''' GLOBALS/PARAMS '''
SERVER = demisto.params().get('server', '')
EMAIL = demisto.params().get('email', '')
PASSWORD = demisto.params().get('password', '')
PORT = int(demisto.params().get('port', '995'))
SSL = demisto.params().get('ssl')
FETCH_TIME = demisto.params().get('fetch_time', '7 days')

# pop3 server connection object.
pop3_server_conn = None  # type: ignore

TIME_REGEX = re.compile(r'^([\w,\d: ]*) (([+-]{1})(\d{2}):?(\d{2}))?[\s\w\(\)]*$')
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'


def connect_pop3_server():
    global pop3_server_conn
Exemplo n.º 59
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *

''' IMPORTS '''

import json
import requests
from distutils.util import strtobool

# Disable insecure warnings
requests.packages.urllib3.disable_warnings()

''' GLOBALS/PARAMS '''

USERNAME = demisto.params().get('credentials').get('identifier')
PASSWORD = demisto.params().get('credentials').get('password')
SERVER = (demisto.params()['url'][:-1]
          if (demisto.params()['url'] and demisto.params()['url'].endswith('/')) else demisto.params()['url'])
BASE_URL = SERVER + '/api/'
USE_SSL = not demisto.params().get('insecure', False)
HEADERS = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
}
URL_LIST_TYPE = 'URL_LIST'
IP_LIST_TYPE = 'IP_LIST'
CATEGORY_LIST_TYPE = 'CATEGORY_LIST'

''' HELPER FUNCTIONS '''
Exemplo n.º 60
0
def main():
    """
        PARSE AND VALIDATE INTEGRATION PARAMS
    """
    token = demisto.params().get('apikey')
    headers = {'Authorization': token}

    # get the service API url
    base_url = demisto.params().get('url') + '/api/'

    verify_certificate = not demisto.params().get('insecure', False)

    proxy = demisto.params().get('proxy', False)

    LOG(f'Command being called is {demisto.command()}')
    try:
        client = BaseClient(base_url=base_url,
                            headers=headers,
                            verify=verify_certificate,
                            proxy=proxy)

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

        # User Management commands
        elif demisto.command() == 'gophish-get-users':
            results_return('Users', client._http_request('GET', 'users/'))
        elif demisto.command() == 'gophish-get-user':
            results_return(
                'User',
                client._http_request('GET',
                                     'users/' + str(demisto.args().get('id'))))
        elif demisto.command() == 'gophish-create-user':
            payload = {
                'role': demisto.args().get('role'),
                'password': demisto.args().get('password'),
                'username': demisto.args().get('username')
            }
            results_return(
                'NewUser',
                client._http_request('POST', 'users/', json_data=payload))
        elif demisto.command() == 'gophish-modify-user':
            payload = {
                'role': demisto.args().get('role'),
                'password': demisto.args().get('password'),
                'username': demisto.args().get('username')
            }
            results_return(
                'ModifiedUser',
                client._http_request('PUT',
                                     'users/' + str(demisto.args().get('id')),
                                     json_data=payload))
        elif demisto.command() == 'gophish-delete-user':
            results_return(
                'DeletedUser',
                client._http_request('DELETE',
                                     'users/' + str(demisto.args().get('id'))))

        # Sending Profiles commands
        elif demisto.command() == 'gophish-get-all-sending-profiles':
            results_return('AllSendingProfiles',
                           client._http_request('GET', 'smtp/'))
        elif demisto.command() == 'gophish-get-sending-profile':
            results_return(
                'SendingProfile',
                client._http_request('GET',
                                     'smtp/' + str(demisto.args().get('id'))))
        elif demisto.command() == 'gophish-create-sending-profile':
            payload = {
                'name':
                demisto.args().get('name'),
                'interface_type':
                'SMTP',
                'from_address':
                demisto.args().get('from_address'),
                'host':
                demisto.args().get('host'),
                'username':
                demisto.args().get('username'),
                'password':
                demisto.args().get('password'),
                'ignore_cert_errors':
                bool(demisto.args().get('ignore_cert_errors'))
            }
            if demisto.args().get('headers'):
                profileheaders = process_profile_headers(
                    demisto.args().get('headers'))
                payload.update(profileheaders)
            results_return(
                'CreatedSendingProfile',
                client._http_request('POST', 'smtp/', json_data=payload))
        elif demisto.command() == 'gophish-delete-sending-profile':
            results_return(
                'DeletedSendingProfile',
                client._http_request('DELETE',
                                     'smtp/' + str(demisto.args().get('id'))))

        # Landing page commands
        elif demisto.command() == 'gophish-get-all-landing-pages':
            results_return('AllLandingPages',
                           client._http_request('GET', 'pages/'))
        elif demisto.command() == 'gophish-get-landing-page':
            results_return(
                'LandingPage',
                client._http_request('GET',
                                     'pages/' + str(demisto.args().get('id'))))
        elif demisto.command() == 'gophish-create-landing-page':
            payload = {
                'name':
                demisto.args().get('name'),
                'html':
                demisto.args().get('html'),
                'capture_credentials':
                bool(demisto.args().get('capture_credentials')),
                'capture_passwords':
                bool(demisto.args().get('capture_passwords')),
                'redirect_url':
                demisto.args().get('redirect_url')
            }
            results_return(
                'CreatedLandingPage',
                client._http_request('POST', 'pages/', json_data=payload))
        elif demisto.command() == 'gophish-delete-landing-page':
            results_return(
                'DeletedLandingPage',
                client._http_request('DELETE',
                                     'pages/' + str(demisto.args().get('id'))))
        elif demisto.command() == 'gophish-import-site-as-landing-page':
            payload = {
                'url': demisto.args().get('url'),
                'include_resources':
                bool(demisto.args().get('include_resources'))
            }
            results_return(
                'ImportedSite',
                client._http_request('POST', 'import/site', json_data=payload))

        # Templates commands
        elif demisto.command() == 'gophish-get-all-templates':
            results_return('AllTemplates',
                           client._http_request('GET', 'templates/'))
        elif demisto.command() == 'gophish-get-template':
            results_return(
                'Template',
                client._http_request(
                    'GET', 'templates/' + str(demisto.args().get('id'))))
        elif demisto.command() == 'gophish-delete-template':
            results_return(
                'DeletedTemplate',
                client._http_request(
                    'DELETE', 'templates/' + str(demisto.args().get('id'))))
        elif demisto.command() == 'gophish-import-template':
            payload = {
                'content': demisto.args().get('content'),
                'convert_links': bool(demisto.args().get('convert_links'))
            }
            results_return(
                'ImportedTemplate',
                client._http_request('POST', 'import/email',
                                     json_data=payload))
        elif demisto.command() == 'gophish-create-template':
            payload = {
                'name': demisto.args().get('name'),
                'subject': demisto.args().get('subject'),
                'text': demisto.args().get('text'),
                'html': demisto.args().get('html'),
                'attachments': []
            }  # attachments require more work
            results_return(
                'CreatedTemplate',
                client._http_request('POST', 'templates/', json_data=payload))

        # Campaign commands
        elif demisto.command() == 'gophish-get-all-campaigns':
            results_return('AllCampaigns',
                           client._http_request('GET', 'campaigns/'))
        elif demisto.command() == 'gophish-get-campaign-details':
            results_return(
                'CampaignDetails',
                client._http_request(
                    'GET', 'campaigns/' + str(demisto.args().get('id'))))
        elif demisto.command() == 'gophish-get-campaign-results':
            results_return(
                'CampaignResults',
                client._http_request(
                    'GET',
                    'campaigns/' + str(demisto.args().get('id')) + '/results'))
        elif demisto.command() == 'gophish-get-campaign-summary':
            results_return(
                'CampaignSummary',
                client._http_request(
                    'GET',
                    'campaigns/' + str(demisto.args().get('id')) + '/summary'))
        elif demisto.command() == 'gophish-delete-campaign':
            results_return(
                'DeletedCampaign',
                client._http_request(
                    'DELETE', 'campaigns/' + str(demisto.args().get('id'))))
        elif demisto.command() == 'gophish-complete-campaign':
            results_return(
                'CompletedCampaign',
                client._http_request(
                    'GET', 'campaigns/' + str(demisto.args().get('id')) +
                    '/complete'))
        elif demisto.command() == 'gophish-create-campaign':
            launch_date = dateparser.parse(demisto.args().get('launch_date'))
            assert launch_date is not None, f"could not parse {demisto.args().get('launch_date')}"
            payload = {
                'name': demisto.args().get('name'),
                'template': {
                    'name': demisto.args().get('template')
                },
                'url': demisto.args().get('url'),
                'page': {
                    'name': demisto.args().get('page')
                },
                'smtp': {
                    'name': demisto.args().get('smtp')
                },
                'launch_date': launch_date.strftime('%Y-%m-%dT%H:%M:%S+00:00'),
                'groups': generate_groups(demisto.args().get('groups'))
            }
            if demisto.args().get('send_by_date'):
                send_by_date = dateparser.parse(
                    demisto.args().get('send_by_date'))
                assert send_by_date is not None
                payload.update({
                    'send_by_date':
                    send_by_date.strftime('%Y-%m-%dT%H:%M:%S+00:00')
                })
            results_return(
                'CreatedCampaign',
                client._http_request('POST', 'campaigns/', json_data=payload))

        # User Groups related commands
        elif demisto.command() == 'gophish-get-all-groups':
            results_return('AllGroups', client._http_request('GET', 'groups/'))
        elif demisto.command() == 'gophish-get-group':
            results_return(
                'Group',
                client._http_request('GET', 'groups/' +
                                     str(demisto.args().get('id'))))
        elif demisto.command() == 'gophish-get-all-groups-summary':
            results_return('AllGroupsSummary',
                           client._http_request('GET', 'groups/summary'))
        elif demisto.command() == 'gophish-get-group-summary':
            results_return(
                'GroupSummary',
                client._http_request(
                    'GET',
                    'groups/' + str(demisto.args().get('id')) + '/summary'))
        elif demisto.command() == 'gophish-create-group':
            payload = {
                'name': demisto.args().get('name'),
                'targets': formtargets(demisto.args().get('targets'))
            }
            results_return(
                'CreatedGroup',
                client._http_request('POST', 'groups/', json_data=payload))
        elif demisto.command() == 'gophish-delete-group':
            results_return(
                'DeletedGroup',
                client._http_request('DELETE', 'groups/' +
                                     str(demisto.args().get('id'))))

    # Log exceptions
    except Exception as e:
        return_error(
            f'Failed to execute {demisto.command()} command. Error: {str(e)}')