示例#1
0
def parse_indicator(indicator: Dict[str, str]) -> Dict[str, Any]:
    """ Parsing indicator by indicators demisto convension.

    Args:
        indicator: Indicator as raw response.

    Returns:
        dict: Parsed indicator.
    """
    indicator_obj = {
        "value": indicator.get('summary'),
        "type": INDICATOR_MAPPING_NAMES.get(indicator.get('type', '')),
        "rawJSON": indicator,
        "score": calculate_dbot_score(indicator.get("threatAssessScore")),
        "fields": {
            "tags": argToList(demisto.getParam("feedTags")),
        },
    }

    tlp_color = demisto.getParam('tlp_color')
    if tlp_color:
        indicator_obj['fields'][
            'trafficlightprotocol'] = tlp_color  # type: ignore

    return indicator_obj
示例#2
0
def main():
    client = Client(
        demisto.getParam("api_access_id"),
        demisto.getParam("api_secret_key"),
        demisto.getParam("tc_api_path"),
    )
    command = demisto.command()
    demisto.info(f'Command being called is {command}')
    commands = {
        'test-module': module_test_command,
        f'{INTEGRATION_COMMAND_NAME}-get-indicators': get_indicators_command,
        f'{INTEGRATION_COMMAND_NAME}-get-owners': get_owners_command
    }
    try:
        if demisto.command() == 'fetch-indicators':
            indicators = fetch_indicators_command(client)
            for b in batch(indicators, batch_size=2000):
                demisto.createIndicators(b)
        else:
            readable_output, outputs, raw_response = commands[command](client)
            return_outputs(readable_output, outputs, raw_response)
    except Exception as e:
        return_error(
            f'Integration {INTEGRATION_NAME} Failed to execute {command} command. Error: {str(e)}'
        )
示例#3
0
def main():
    # Following methods raise exceptions so no need to check for return codes
    # But we do need to catch them
    global SERVER
    FROM = demisto.getParam('from')
    FQDN = demisto.params().get('fqdn')
    FQDN = (FQDN and FQDN.strip()) or None
    stderr_org = None
    try:
        if demisto.command() == 'test-module':
            stderr_org = swap_stderr(LOG)
            smtplib.SMTP.debuglevel = 1
        SERVER = SMTP(demisto.getParam('host'), int(demisto.params().get('port', 0)), local_hostname=FQDN)
        SERVER.ehlo()
        # TODO - support for non-valid certs
        if demisto.getParam('tls'):
            SERVER.starttls()
        user, password = get_user_pass()
        if user:
            SERVER.login(user, password)
    except Exception as e:
        # also reset at the bottom finally
        swap_stderr(stderr_org)  # type: ignore
        smtplib.SMTP.debuglevel = 0
        demisto.error('Failed test: {}\nStack trace: {}'.format(e, traceback.format_exc()))
        return_error_mail_sender(e)
        return  # so mypy knows that we don't continue after this
    # -- COMMANDS --
    try:
        if demisto.command() == 'test-module':
            msg = MIMEText('This is a test mail from Demisto\nRegards\nDBot')  # type: Message
            msg['Subject'] = 'Test mail from Demisto'
            msg['From'] = FROM
            msg['To'] = FROM
            SERVER.sendmail(FROM, [FROM], msg.as_string())
            SERVER.quit()
            demisto.results('ok')
        elif demisto.command() == 'send-mail':
            raw_message = demisto.getArg('raw_message')
            if raw_message:
                to = argToList(demisto.getArg('to'))
                cc = argToList(demisto.getArg('cc'))
                bcc = argToList(demisto.getArg('bcc'))
                str_msg = raw_message
            else:
                (str_msg, to, cc, bcc) = create_msg()

            SERVER.sendmail(FROM, to + cc + bcc, str_msg)  # type: ignore
            SERVER.quit()  # type: ignore
            demisto.results('Mail sent successfully')
        else:
            return_error_mail_sender('Command not recognized')
    except SMTPRecipientsRefused as e:
        error_msg = ''.join('{}\n'.format(val) for key, val in e.recipients.iteritems())
        return_error_mail_sender("Encountered error: {}".format(error_msg))
    except Exception as e:
        return_error_mail_sender(e)
    finally:
        swap_stderr(stderr_org)  # type: ignore
        smtplib.SMTP.debuglevel = 0
示例#4
0
def do_patch(token, suffix, body):
    insecure = demisto.getParam('insecure')
    server = demisto.getParam('server')
    url = fix_url(server) + suffix
    res = requests.patch(url, headers={'Authorization': 'Bearer ' + token,
                                       'Content-Type': 'application/json'}, data=json.dumps(body), verify=not insecure)
    parsed_response = parse_response(res)
    return parsed_response
示例#5
0
def generate_oauth1():
    oauth = OAuth1(
        client_key=demisto.getParam('consumerKey'),
        rsa_key=demisto.getParam('privateKey'),
        signature_method='RSA-SHA1',
        resource_owner_key=demisto.getParam('accessToken'),
    )
    return oauth
示例#6
0
def do_get(token, raw, suffix):
    insecure = demisto.getParam('insecure')
    server = demisto.getParam('server')
    url = fix_url(server) + suffix
    res = requests.get(url, headers={'Authorization': 'Bearer ' + token}, verify=not insecure)
    if (raw):
        return res
    else:
        return parse_response(res)
示例#7
0
def fetch_incidents():
    """
    Retrieve new incidents periodically based on pre-defined instance parameters
    """
    now = int(
        (datetime.utcnow() - datetime.utcfromtimestamp(0)).total_seconds() *
        1000)
    last_run_object = demisto.getLastRun()
    last_run = last_run_object and last_run_object['time']
    if not last_run:
        last_run = now - 24 * 60 * 60 * 1000
    payload = {
        'timeRange': {
            'type': 'absolute',
            'value': {
                'startTime': last_run,
                'endTime': now
            }
        },
        'filters': [{
            'name': 'alert.status',
            'operator': '=',
            'value': 'open'
        }]
    }
    if demisto.getParam('ruleName'):
        payload['filters'].append({
            'name': 'alertRule.name',
            'operator': '=',  # type: ignore
            'value': demisto.getParam('ruleName')
        })
    if demisto.getParam('policySeverity'):
        payload['filters'].append({
            'name': 'policy.severity',
            'operator': '=',  # type: ignore
            'value': demisto.getParam('policySeverity')
        })

    demisto.info(
        "Executing Prisma Cloud (RedLock) fetch_incidents with payload: {}".
        format(payload))
    response = req('POST', 'alert', payload, {'detailed': 'true'})
    incidents = []
    for alert in response:
        incidents.append({
            'name':
            alert.get('policy.name', 'No policy') + ' - ' + alert.get('id'),
            'occurred':
            convert_unix_to_demisto(alert.get('alertTime')),
            'severity':
            translate_severity(alert),
            'rawJSON':
            json.dumps(alert)
        })
    demisto.incidents(incidents)
    demisto.setLastRun({'time': now})
示例#8
0
def fetch_incidents():
    """
    Retrieve new incidents periodically based on pre-defined instance parameters
    """
    now = int(
        (datetime.utcnow() - datetime.utcfromtimestamp(0)).total_seconds() *
        1000)
    lastRunObject = demisto.getLastRun()
    lastRun = lastRunObject and lastRunObject['time']
    if not lastRun:
        lastRun = now - 24 * 60 * 60 * 1000
    payload = {
        'timeRange': {
            'type': 'absolute',
            'value': {
                'startTime': lastRun,
                'endTime': now
            }
        }
    }
    payload['filters'] = [{
        'name': 'alert.status',
        'operator': '=',
        'value': 'open'
    }]  # type: ignore
    if demisto.getParam('ruleName'):
        payload['filters'].append({
            'name': 'alertRule.name',
            'operator': '=',  # type: ignore
            'value': demisto.getParam('ruleName')
        })
    if demisto.getParam('policySeverity'):
        payload['filters'].append({
            'name': 'policy.severity',
            'operator': '=',  # type: ignore
            'value': demisto.getParam('policySeverity')
        })
    r = req('POST', 'alert', payload, {'detailed': 'true'})
    incidents = []
    for a in r:
        incidents.append({
            'name':
            a.get('policy.name', 'No policy') + ' - ' + a.get('id'),
            'occurred':
            convertUnixToDemisto(a.get('alertTime')),
            'severity':
            translate_severity(a),
            'rawJSON':
            json.dumps(a)
        })
    demisto.incidents(incidents)
    demisto.setLastRun({'time': now})
示例#9
0
def do_post(token, is_xml, suffix, body):
    insecure = demisto.getParam('insecure')
    server = demisto.getParam('server')
    url = fix_url(server) + suffix
    res = requests.post(url, headers={'Authorization': 'Bearer ' + token}, data=body, verify=not insecure)
    if is_xml:
        if res.content:
            parsed_response = xml2json(res.content)
        else:
            return_error('Unable to parse the following response: {}'.format(res))
    else:
        parsed_response = parse_response(res)
    return parsed_response
示例#10
0
def fetch_incidents():
    """
    Retrieve new incidents periodically based on pre-defined instance parameters
    """
    now = convert_date_to_unix(datetime.utcnow())
    last_run_object = demisto.getLastRun()
    if last_run_object and last_run_object.get('time'):
        last_run = last_run_object.get('time')
    else:
        last_run = now - 24 * 60 * 60 * 1000
    next_fetch = last_run
    q = '* AND timestamp:[%d TO *]' % last_run
    if demisto.getParam('fetchQuery'):
        q += ' AND ' + demisto.getParam('fetchQuery')
    else:
        q += ' AND workflow_status:(new OR inprogress)'
    query = QUERY.copy()
    query['q'] = q
    query['offset'] = 0
    query['limit'] = FETCH_LIMIT
    query['sort_by'] = 'timestamp:asc'
    resp_json = req('GET', 'search/alerts', query)
    incidents = []
    for a in resp_json['objects']:
        current_fetch = a.get('timestamp')
        if current_fetch:
            try:
                current_fetch = datetime.strptime(current_fetch,
                                                  "%Y-%m-%dT%H:%M:%S")
            except ValueError:
                current_fetch = datetime.strptime(current_fetch,
                                                  "%Y-%m-%dT%H:%M:%S.%f")
            current_fetch = convert_date_to_unix(current_fetch)
            if current_fetch > last_run:
                incidents.append({
                    'name':
                    a.get('name', 'No name') + ' - ' + a.get('id'),
                    'occurred':
                    a.get('timestamp') + 'Z',
                    'details':
                    a.get('description'),
                    'severity':
                    translate_severity(a.get('severity')),
                    'rawJSON':
                    json.dumps(a)
                })
            if current_fetch > next_fetch:
                next_fetch = current_fetch

    demisto.incidents(incidents)
    demisto.setLastRun({'time': next_fetch})
示例#11
0
def generate_md_context_create_issue(data, project_name=None, project_key=None):
    create_issue_obj = {"md": [], "context": {"Ticket": []}}
    if project_name:
        data["projectName"] = project_name

    if project_key:
        data["projectKey"] = project_key

    elif demisto.getParam('projectKey'):
        data["projectKey"] = demisto.getParam('projectKey')

    create_issue_obj['md'].append(data)  # type: ignore
    create_issue_obj['context']['Ticket'].append({"Id": demisto.get(data, 'id'), "Key": demisto.get(data, 'key')})  # type: ignore
    return create_issue_obj
示例#12
0
def generate_md_context_create_issue(data, project_name=None, project_key=None):
    create_issue_obj = {"md": [], "context": {"Ticket": []}}  # type: ignore
    if project_name:
        data["projectName"] = project_name

    if project_key:
        data["projectKey"] = project_key

    elif demisto.getParam('projectKey'):
        data["projectKey"] = demisto.getParam('projectKey')

    create_issue_obj['md'].append(data)  # type: ignore
    create_issue_obj['context']['Ticket'].append({"Id": demisto.get(data, 'id'), "Key": demisto.get(data, 'key')})  # type: ignore
    return create_issue_obj
示例#13
0
def main():
    try:
        handle_proxy()

        demisto_params = {
            "start_date":
            parse_date_range(demisto.getParam('date_range'))[0].isoformat(),
            "max_fetch":
            int(demisto.getParam('max_fetch')),
            "category_id":
            demisto.getParam("category_id"),
            "match_priority":
            demisto.getParam("match_priority"),
            "tags":
            demisto.getParam("tags"),
        }

        triage_instance = TriageInstance(
            host=demisto.getParam("host").rstrip("/")
            if demisto.getParam("host") else "",
            token=demisto.getParam("token"),
            user=demisto.getParam("user"),
            disable_tls_verification=demisto.params().get("insecure", False),
            demisto_params=demisto_params,
        )

        if demisto.command() == "test-module":
            test_function(triage_instance)

        if demisto.command() == "fetch-incidents":
            fetch_reports(triage_instance)

        elif demisto.command() == "cofense-search-reports":
            search_reports_command(triage_instance)

        elif demisto.command() == "cofense-get-attachment":
            get_attachment_command(triage_instance)

        elif demisto.command() == "cofense-get-reporter":
            get_reporter_command(triage_instance)

        elif demisto.command() == "cofense-get-report-by-id":
            get_report_by_id_command(triage_instance)

        elif demisto.command() == "cofense-get-report-png-by-id":
            get_report_png_by_id_command(triage_instance)

        elif demisto.command() == "cofense-get-threat-indicators":
            get_threat_indicators_command(triage_instance)

    except Exception as e:
        return_error(str(e))
        raise
示例#14
0
def fetch_incidents():
    """
    Fetch incidents for Demisto
    """
    now = int((datetime.utcnow() - datetime.utcfromtimestamp(0)).total_seconds() * 1000)
    lastRunObject = demisto.getLastRun()
    if not lastRunObject and lastRunObject.get('time'):
        fetch_delta, _ = parse_date_range(demisto.params().get('fetch_delta', DEFAULT_TIME_RANGE), to_timestamp=True)
    else:
        fetch_delta = lastRunObject.get('time')

    alert_type = demisto.getParam('type')
    min_severity_level = demisto.params().get('severity_level', 'All')
    if min_severity_level not in SEVERITY_LEVEL:
        raise Exception("Minimum Alert severity level to fetch incidents incidents from, allowed values are: ''All'',"
                        " ''Low'', ''Medium'',''High''(Setting to All will fetch all incidents)")

    alerts_HR, alerts_ctx = get_alerts_helper(handle_filters(fetch_delta))
    incidents = []
    for alert in alerts_ctx:
        if SEVERITY_LEVEL[min_severity_level] <= SEVERITY_LEVEL[alert.get('Severity', 'Low')]:
            if not alert_type or alert_type.lower() == alert.get('Type', '').lower():
                incidents.append({
                    'name': '{type} - {id}'.format(type=alert.get('Type', 'Type not found'), id=alert.get('ID')),
                    'occurred': alert.get('FoundDate'),
                    'severity': translate_severity(alert.get('Severity')),
                    'rawJSON': json.dumps(alert)
                })
    demisto.incidents(incidents)
    demisto.setLastRun({'time': now})
示例#15
0
def get_auth():
    is_basic = USERNAME and (PASSWORD or API_TOKEN)
    is_oauth1 = demisto.getParam('consumerKey') and demisto.getParam('accessToken') and demisto.getParam('privateKey')

    if is_basic:
        return generate_basic_oauth()

    elif is_oauth1:
        HEADERS.update({'X-Atlassian-Token': 'nocheck'})
        return generate_oauth1()

    return_error(
        'Please provide the required Authorization information:'
        '- Basic Authentication requires user name and password or API token'
        '- OAuth 1.0 requires ConsumerKey, AccessToken and PrivateKey'
    )
def main():
    """
        PARSE AND VALIDATE INTEGRATION PARAMS
    """
    # Execute command
    command = demisto.command()
    LOG(f'Command being called is {command}')
    commands: Dict[str, Callable] = {
        # Clusters
        "test-module":
        test_module_command,
        f"{INTEGRATION_COMMAND_NAME}-clusters-list":
        gcloud_clusters_list_command,
        f"{INTEGRATION_COMMAND_NAME}-clusters-describe":
        gcloud_clusters_describe_command,
        f"{INTEGRATION_COMMAND_NAME}-clusters-set-muster-auth":
        gcloud_clusters_set_master_auth,
        f"{INTEGRATION_COMMAND_NAME}-clusters-set-addons":
        gcloud_clusters_set_addons_command,
        f"{INTEGRATION_COMMAND_NAME}-clusters-set-legacy-auth":
        gcloud_clusters_set_legacy_auth_command,
        f"{INTEGRATION_COMMAND_NAME}-clusters-set-master-authorized-network":
        gcloud_clusters_set_master_authorized_network_command,
        f"{INTEGRATION_COMMAND_NAME}-clusters-set-k8s-stackdriver":
        gcloud_clusters_set_k8s_stackdriver_command,
        f"{INTEGRATION_COMMAND_NAME}-clusters-set-binary-auth":
        gcloud_clusters_set_binary_auth,
        f"{INTEGRATION_COMMAND_NAME}-clusters-set-intra-node-visibility":
        gcloud_clusters_set_intra_node_visibility,
        # Node pools
        f"{INTEGRATION_COMMAND_NAME}-node-pool-list":
        gcloud_node_pool_list_command,
        f"{INTEGRATION_COMMAND_NAME}-node-pool-describe":
        gcloud_node_pool_describe_command,
        f"{INTEGRATION_COMMAND_NAME}-node-pool-set-management":
        gcloud_set_node_pool_management,
        # Operation handling
        f"{INTEGRATION_COMMAND_NAME}-operations-list":
        gcloud_operations_list_command,
        f"{INTEGRATION_COMMAND_NAME}-operations-describe":
        gcloud_operations_describe_command,
        f"{INTEGRATION_COMMAND_NAME}-operations-cancel":
        gcloud_operations_cancel_command,
    }
    try:
        client: ClusterManagerClient = google_client_setup(
            json_configuration=demisto.getParam('credentials_json'))
        command_arguments = handle_default_configuration()
        readable_output, context_entry, raw_response = commands[command](
            client=client, **command_arguments)

        return_outputs(readable_output=readable_output,
                       outputs=context_entry,
                       raw_response=raw_response)
    except Exception as e:
        # Log exceptions
        return_error(
            f'Integration {INTEGRATION_NAME} Failed to execute {command} command.\n Error: {str(e)}'
        )
示例#17
0
def test_module():
    """
    Performs basic get request to get item samples
    """
    req_res = jira_req('GET', 'rest/api/latest/myself')
    run_query(demisto.getParam('query'), max_results=1)
    if req_res.ok:
        demisto.results('ok')
示例#18
0
def test_module():
    """
    Performs basic get request to get item samples
    """
    req_res = jira_req('GET', 'rest/api/latest/myself')
    run_query(demisto.getParam('query'), max_results=1)
    if req_res.ok:
        demisto.results('ok')
示例#19
0
def main():
    # Following methods raise exceptions so no need to check for return codes
    # But we do need to catch them
    global SERVER
    FROM = demisto.getParam('from')
    FQDN = demisto.params().get('fqdn')
    try:
        SERVER = SMTP(demisto.getParam('host'),
                      int(demisto.getParam('port')),
                      local_hostname=FQDN)
        SERVER.ehlo()
        # TODO - support for non-valid certs
        if demisto.getParam('tls'):
            SERVER.starttls()
        if demisto.getParam('credentials') and demisto.getParam(
                'credentials').get('identifier') and demisto.getParam(
                    'credentials').get('password'):  # noqa: E501
            SERVER.login(
                demisto.getParam('credentials')['identifier'],
                demisto.getParam('credentials')['password'])
    except Exception as e:
        if SERVER:
            SERVER.quit()
        return_error(e)

    # -- COMMANDS --
    try:
        if demisto.command() == 'test-module':
            msg = MIMEText('This is a test mail from Demisto\nRegards\nDBot'
                           )  # type: Message
            msg['Subject'] = 'Test mail from Demisto'
            msg['From'] = FROM
            msg['To'] = FROM
            SERVER.sendmail(FROM, [FROM], msg.as_string())  # type: ignore
            SERVER.quit()  # type: ignore
            demisto.results('ok')
        elif demisto.command() == 'send-mail':
            (str_msg, to, cc, bcc) = create_msg()
            SERVER.sendmail(FROM, to + cc + bcc, str_msg)  # type: ignore
            SERVER.quit()  # type: ignore
            demisto.results('Mail sent successfully')
        else:
            return_error_mail_sender('Command not recognized')
    except SMTPRecipientsRefused as e:
        error_msg = ''.join('{}\n'.format(val)
                            for key, val in e.recipients.iteritems())
        return_error_mail_sender("Encountered error: {}".format(error_msg))
    except Exception as e:
        return_error_mail_sender(str(e))
示例#20
0
def get_token():
    """
    Retrieve the token using the credentials
    """
    r = requests.post(URL + 'login',
                      headers=HEADERS,
                      verify=VERIFY,
                      json={
                          'customerName': demisto.getParam('customer') or '',
                          'username':
                          demisto.getParam('credentials')['identifier'],
                          'password':
                          demisto.getParam('credentials')['password']
                      })
    if r.status_code != requests.codes.ok:
        return_error('Error authenticating to RedLock service [%d] - %s' %
                     (r.status_code, r.text))
    TOKEN = r.json()['token']
    HEADERS['x-redlock-auth'] = TOKEN
示例#21
0
def test_module() -> None:
    try:
        supported_langs = list_languages()
        conf_langs = argToList(demisto.getParam('langs'))
        if conf_langs:
            for l in conf_langs:
                if l not in supported_langs:
                    demisto.results('Unsupported language configured: {}'.format(l))
        demisto.results('ok')
    except Exception as ex:
        demisto.results('Failed testing {}: {}'.format(TESSERACT_EXE, str(ex)))
示例#22
0
def main() -> None:
    # Commands definition
    command = demisto.command()
    commands: Dict[str, Callable] = {
        "test-module": test_module,
        "tidy-pyenv": tidy_pyenv_command,
        "tidy-goenv": tidy_goenv_command,
        "tidy-nodenv": tidy_nodenv_command,
        "tidy-homebrew": tidy_homebrew_command,
        "tidy-github-ssh-key": tidy_github_ssh_key_command,
        "tidy-git-clone": tidy_git_clone_command,
        "tidy-git-config": tidy_git_config_command,
        "tidy-zsh": tidy_zsh_command,
        "tidy-block-in-file": tidy_block_in_file_command,
        "tidy-exec": tidy_exec_command,
        "tidy-osx-command-line-tools": tidy_osx_command_line_tools_command,
        "tidy-python-env": tidy_python_env_command,
        "tidy-demisto-server": tidy_demisto_server_command,
        "tidy-demisto-web-client": tidy_demisto_web_client_command,
    }

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

    # Command execution
    try:
        demisto.debug(f'Command being called is {command}')
        demisto.results(commands[command](client, **demisto.args()))
    # Log exceptions and return errors
    except DemistoException as e:
        demisto.error(traceback.format_exc())
        return_error(
            f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}'
        )
def main():
    current_command = demisto.command()
    try:
        '''
        Before EVERY command the following tow lines are performed (do_auth and get_token_from_response)
        '''
        resp = do_auth(server=demisto.getParam('server'), crads=demisto.getParam(
            'authentication'), insecure=demisto.getParam('insecure'), domain=demisto.getParam('domain'))
        token = get_token_from_response(resp)
        if current_command == 'test-module':
            # This is the call made when pressing the integration test button.
            if token:
                demisto.results('ok')
        if current_command == 'sep-system-info':
            system_info_command(token)
        if current_command == 'sep-client-content':
            client_content_command(token)
        if current_command == 'sep-endpoints-info':
            endpoints_info_command(token)
        if current_command == 'sep-groups-info':
            groups_info_command(token)
        if current_command == 'sep-command-status':
            command_status(token)
        if current_command == 'sep-list-policies':
            list_policies_command(token)
        if current_command == 'sep-assign-policy':
            assign_policie_command(token)
        if current_command == 'sep-list-locations':
            list_locations_command(token)
        if current_command == 'sep-endpoint-quarantine':
            endpoint_quarantine_command(token)
        if current_command == 'sep-scan-endpoint':
            scan_endpoint_command(token)
        if current_command == 'sep-update-endpoint-content':
            update_endpoint_content_command(token)
        if current_command == 'sep-move-client-to-group':
            move_client_to_group_command(token)
        if current_command == 'sep-identify-old-clients':
            old_clients_command(token)
    except Exception as ex:
        return_error('Cannot perform the command: {}. Error: {}'.format(current_command, ex), ex)
示例#24
0
def test_module() -> None:
    try:
        supported_langs = list_languages()
        conf_langs = argToList(demisto.getParam('langs'))
        if conf_langs:
            for l in conf_langs:
                if l not in supported_langs:
                    demisto.results(
                        'Unsupported language configured: {}'.format(l))
        demisto.results('ok')
    except Exception as ex:
        demisto.results('Failed testing {}: {}'.format(TESSERACT_EXE, str(ex)))
示例#25
0
def get_mssp_sub_accounts():
    account_id = demisto.getParam('credentials')['identifier']
    accounts = req('GET', 'public/v1/mssp/customers', json_response=True)
    if not accounts:
        return_error("intsights-mssp-get-sub-accounts failed to return data.")

    # Fix accounts _id keys
    for account in accounts:
        account["ID"] = account["_id"]
        del account["_id"]

    if len(accounts) < 1:
        return_error('Current MSSP Account has no sub accounts.')

    account_ids = [i["ID"] for i in accounts]
    if mssp_account_id not in account_ids:
        demisto.log("[DEBUG] - MSSP sub accounts:" + str(accounts))
        return_error(
            'Entered sub account id ({}) is not part of this mssp account'.
            format(mssp_account_id))

    for i, account in enumerate(account_ids):
        # Call account
        HEADERS['Account-Id'] = account
        account_ua = req('GET',
                         'public/v1/account/used-assets',
                         json_response=True)

        if not account_ua:
            continue

        accounts[i].update(account_ua)

    demisto.results({
        'Type':
        entryTypes['note'],
        'EntryContext': {
            'IntSights.MsspAccount(val.ID === obj.ID)': accounts
        },
        'HumanReadable':
        tableToMarkdown(
            'IntSights MSSP accounts used assets ' + account_id,
            [a for a in accounts],
            ["ID", 'CompanyName', "Status", "AssetsLimit", "AssetsCount"]),
        'Contents':
        accounts,
        'ContentsFormat':
        formats['json']
    })

    # Restore the header
    HEADERS['Account-Id'] = mssp_account_id
示例#26
0
def fetch_indicators_command(client: Client) -> List[Dict[str, Any]]:
    """ Fetch indicators from ThreatConnect

    Args:
        client: ThreatConnect client.

    Returns:
        list: indicator to populate in demisto server.
    """
    raw_response = client.get_indicators(
        owners=argToList(demisto.getParam('owners')))

    return [parse_indicator(indicator) for indicator in raw_response]
示例#27
0
def get_token():
    """
    Retrieve the token using the credentials
    """
    response = requests.post(URL + 'login',
                             headers=HEADERS,
                             verify=VERIFY,
                             json={
                                 'customerName':
                                 demisto.getParam('customer') or '',
                                 'username':
                                 demisto.getParam('credentials')['identifier'],
                                 'password':
                                 demisto.getParam('credentials')['password']
                             })

    if response.status_code != requests.codes.ok:  # pylint: disable=no-member
        raise Exception('Error authenticating to RedLock service [%d] - %s' %
                        (response.status_code, response.text))
    try:
        response_json = response.json()
        TOKEN = response_json.get('token')
        if not TOKEN:
            demisto.debug(json.dumps(response_json))
            message = 'Could not retrieve token from server: {}'.format(
                response_json.get("message"))
            if response_json.get('message') == 'login_needs_customer_name':
                available_customer_names = [
                    name.get('customerName')
                    for name in response_json.get('customerNames')
                ]
                message = 'In order to login a customer name need to be configured. Available customer names: {}'.format(
                    {", ".join(available_customer_names)})
            raise Exception(message)
    except ValueError as exception:
        demisto.log(exception)
        raise Exception('Could not parse API response.')
    HEADERS['x-redlock-auth'] = TOKEN
示例#28
0
def client_content_command(token):
    time_zone = demisto.getParam('timeZone')
    client_content_json, client_version, last_update_date = get_client_content(token, time_zone)
    md = '## Client Content, last updated on {0}\n'.format(last_update_date)
    md += tableToMarkdown('Client Content Versions', client_version)
    demisto.results({
        'Type': entryTypes['note'],
        'ContentsFormat': formats['json'],
        'Contents': client_content_json,
        'HumanReadable': md,
        'EntryContext': {
            'SEPM.ClientContentVersions': client_version,
            'SEPM.LastUpdated': last_update_date
        }
    })
示例#29
0
def main():
    command = None

    try:
        handle_proxy()

        intezer_api_key = demisto.getParam('APIKey')
        intezer_base_url_param = demisto.getParam('AnalyzeBaseURL')
        use_ssl = not demisto.params().get('insecure', False)
        analyze_base_url = intezer_base_url_param or consts.BASE_URL

        intezer_api = IntezerApi(consts.API_VERSION, intezer_api_key,
                                 analyze_base_url, use_ssl)

        command_handlers: Dict[str, Callable[[IntezerApi, dict], Union[
            List[CommandResults], CommandResults, str]]] = {
                'test-module': check_is_available,
                'intezer-analyze-by-hash': analyze_by_hash_command,
                'intezer-analyze-by-file': analyze_by_uploaded_file_command,
                'intezer-get-latest-report': get_latest_result_command,
                'intezer-get-analysis-result':
                check_analysis_status_and_get_results_command,
                'intezer-get-sub-analyses': get_analysis_sub_analyses_command,
                'intezer-get-analysis-code-reuse':
                get_analysis_code_reuse_command,
                'intezer-get-analysis-metadata': get_analysis_metadata_command,
                'intezer-get-family-info': get_family_info_command
            }

        command = demisto.command()
        command_handler = command_handlers[command]
        command_results = command_handler(intezer_api, demisto.args())
        return_results(command_results)

    except Exception as e:
        return_error(f'Failed to execute {command} command. Error: {str(e)}')
示例#30
0
def build_triage_instance():
    demisto_params = {
        "start_date":
        parse_date_range(demisto.getParam("date_range"))[0].isoformat(),
        "max_fetch":
        int(demisto.getParam("max_fetch")),
        "category_id":
        demisto.getParam("category_id"),
        "match_priority":
        demisto.getParam("match_priority"),
        "tags":
        demisto.getParam("tags"),
        "mailbox_location":
        demisto.getParam("mailbox_location"),
    }

    return TriageInstance(
        host=demisto.getParam("host").rstrip("/")
        if demisto.getParam("host") else "",
        token=demisto.getParam("token"),
        user=demisto.getParam("user"),
        disable_tls_verification=demisto.params().get("insecure", False),
        demisto_params=demisto_params,
    )
示例#31
0
def extract_text_command() -> dict:
    langs = argToList(demisto.getArg('langs')) or argToList(demisto.getParam('langs'))
    demisto.debug("Using langs settings: {}".format(langs))
    entry_id = demisto.args()['entryid']
    file_path = demisto.getFilePath(entry_id)
    if not file_path:
        return_error("Couldn't find entry id: {}".format(entry_id))
    demisto.debug('Extracting text from file: {}'.format(file_path))
    res = extract_text(file_path['path'], langs)
    file_entry = {'EntryID': entry_id, 'Text': res}
    return {
        'Type': entryTypes['note'],
        'Contents': res,
        'ContentsFormat': formats['text'],
        'ReadableContentsFormat': formats['markdown'],
        'HumanReadable': "## Image OCR Extracted Text\n\n" + res,
        "EntryContext": {"File(val.EntryID == obj.EntryID)": file_entry},
    }
示例#32
0
def parse_indicator(indicator: Dict[str, str]) -> Dict[str, Any]:
    """ Parsing indicator by indicators demisto convension.

    Args:
        indicator: Indicator as raw response.

    Returns:
        dict: Parsed indicator.
    """
    return {
        "value": indicator.get('summary'),
        "type": INDICATOR_MAPPING_NAMES.get(indicator.get('type', '')),
        "rawJSON": indicator,
        "score": calculate_dbot_score(indicator.get("threatAssessScore")),
        "fields": {
            "tags": argToList(demisto.getParam("feedTags")),
        },
    }
示例#33
0
def get_indicators_command(client: Client) -> COMMAND_OUTPUT:
    """ Get indicator from ThreatConnect, Able to change limit and offset by command arguments.

    Args:
        client: ThreatConnect client.

    Returns:
        str: Human readable.
        dict: Operation entry context.
        dict: Operation raw response.
    """
    raw_response: Iterator[Any] = client.get_indicators(
        owners=argToList(
            demisto.getArg('owners') or demisto.getParam('owners')),
        limit=demisto.getArg('limit'),
        offset=demisto.getArg('offset'))
    readable_output: str = tableToMarkdown(
        name=f"{INTEGRATION_NAME} - Indicators",
        t=[parse_indicator(indicator) for indicator in raw_response])

    return readable_output, {}, list(raw_response)
示例#34
0
def extract_text_command() -> dict:
    langs = argToList(demisto.getArg('langs')) or argToList(
        demisto.getParam('langs'))
    demisto.debug("Using langs settings: {}".format(langs))
    entry_id = demisto.args()['entryid']
    file_path = demisto.getFilePath(entry_id)
    if not file_path:
        return_error("Couldn't find entry id: {}".format(entry_id))
    demisto.debug('Extracting text from file: {}'.format(file_path))
    res = extract_text(file_path['path'], langs)
    file_entry = {'EntryID': entry_id, 'Text': res}
    return {
        'Type': entryTypes['note'],
        'Contents': res,
        'ContentsFormat': formats['text'],
        'ReadableContentsFormat': formats['markdown'],
        'HumanReadable': "## Image OCR Extracted Text\n\n" + res,
        "EntryContext": {
            "File(val.EntryID == obj.EntryID)": file_entry
        },
    }
示例#35
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *

''' IMPORTS '''
import json
import requests
from base64 import b64encode

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

''' GLOBALS/PARAMS '''
BASE_URL = demisto.getParam('url').rstrip('/') + '/'
API_TOKEN = demisto.getParam('APItoken')
USERNAME = demisto.getParam('username')
PASSWORD = demisto.getParam('password')
IS_OAUTH = demisto.getParam('consumerKey') and demisto.getParam('accessToken') and demisto.getParam('privateKey')

# if not OAuth, check for valid parameters for basic auth, i.e. username & pass, or just APItoken
if not IS_OAUTH and not (USERNAME and (PASSWORD or API_TOKEN)):
    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 = {
示例#36
0
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *

'''IMPORTS'''
import requests
from datetime import datetime

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

''' GLOBAL VARS '''
BASE_URL = demisto.getParam('host').rstrip('/') + '/v1.0/'
TENANT = demisto.getParam('tenant')
TOKEN = demisto.getParam('token')
HEADERS = {"Authorization": TOKEN, "Accept": "application/json"}
USE_SSL = not demisto.params().get('unsecure', False)

''' CONSTANTS '''
DEMISTOBOT = "https://demistobot.demisto.com/msg-user-token"
PRODUCT = "MicrosoftGraphUser"
BLOCK_ACCOUNT_JSON = '{"accountEnabled": false}'
UNBLOCK_ACCOUNT_JSON = '{"accountEnabled": true}'
NO_OUTPUTS: dict = {}


def camel_case_to_readable(text):
    """
    'camelCase' -> 'Camel Case'
    """
    if text == 'id':
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',