def main(): try: if demisto.command() == 'test-module': test_module() elif demisto.command() == 'image-ocr-list-languages': demisto.results(list_languages_command()) elif demisto.command() == 'image-ocr-extract-text': demisto.results(extract_text_command()) else: return_error('Unknown command: {}'.format(demisto.command())) except subprocess.CalledProcessError as cpe: return_error("Failed {} execution. Return status: {}.\nError:\n{}".format(cpe.cmd, cpe.returncode, cpe.stderr)) except Exception as ex: return_error("Failed with error: {}\n\nTrace:\n{}".format(str(ex), traceback.format_exc()))
def main(): LOG('command is %s' % (demisto.command(), )) try: if demisto.command() == 'test-module': 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)
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')
def main(): """ COMMANDS MANAGER / SWITCH PANEL """ command = demisto.command() LOG(f'Command being called is {command}') try: if command == 'test-module': # This is the call made when pressing the integration test button. test_module() demisto.results('ok') elif command in ('msgraph-mail-list-emails', 'msgraph-mail-search-email'): list_mails_command() elif command == 'msgraph-mail-get-email': get_message_command() elif command == 'msgraph-mail-delete-email': delete_mail_command() elif command == 'msgraph-mail-list-attachments': list_attachments_command() elif command == 'msgraph-mail-get-attachment': get_attachment_command() # Log exceptions except Exception as e: LOG(e) LOG.print_log() raise
def add_comment_command(issue_id, comment, visibility=''): url = f'rest/api/latest/issue/{issue_id}/comment' comment = { "body": comment } if visibility: comment["visibility"] = { "type": "role", "value": visibility } result = jira_req('POST', url, json.dumps(comment)) data = result.json() md_list = [] if not isinstance(data, list): data = [data] for element in data: md_obj = { 'id': demisto.get(element, 'id'), 'key': demisto.get(element, 'updateAuthor.key'), 'comment': demisto.get(element, 'body'), 'ticket_link': demisto.get(element, 'self') } md_list.append(md_obj) human_readable = tableToMarkdown(demisto.command(), md_list, "") contents = data return_outputs(readable_output=human_readable, outputs={}, raw_response=contents)
def add_link_command(issue_id, title, url, summary=None, global_id=None, relationship=None): req_url = f'rest/api/latest/issue/{issue_id}/remotelink' link = { "object": { "url": url, "title": title } } if summary: link['summary'] = summary if global_id: link['globalId'] = global_id if relationship: link['relationship'] = relationship result = jira_req('POST', req_url, json.dumps(link)) data = result.json() md_list = [] if not isinstance(data, list): data = [data] for element in data: md_obj = { 'id': demisto.get(element, 'id'), 'key': demisto.get(element, 'updateAuthor.key'), 'comment': demisto.get(element, 'body'), 'ticket_link': demisto.get(element, 'self') } md_list.append(md_obj) human_readable = tableToMarkdown(demisto.command(), md_list, "", removeNull=True) contents = data return_outputs(readable_output=human_readable, outputs={}, raw_response=contents)
def issue_query_command(query, start_at='', max_results=None, headers=''): j_res = run_query(query, start_at, max_results) issues = demisto.get(j_res, 'issues') md_and_context = generate_md_context_get_issue(issues) human_readable = tableToMarkdown(demisto.command(), md_and_context['md'], argToList(headers)) contents = j_res outputs = {'Ticket(val.Id == obj.Id)': md_and_context['context']} return_outputs(readable_output=human_readable, outputs=outputs, raw_response=contents)
def load_extended_keys(): global EXTENDED_KEYS if demisto.command() == 'fetch-incidents': last_run = demisto.getLastRun() EXTENDED_KEYS = last_run.get('extended_keys', {}) else: integration_context = demisto.getIntegrationContext() EXTENDED_KEYS = integration_context.get('extended_keys', {}) if not EXTENDED_KEYS: session = login() url = REST_ADDRESS + '/eventAttributeType/all' response = session.get(url, verify=VERIFY_SSL, auth=AUTH) EXTENDED_KEYS = dict((attr['attributeId'], attr['displayName']) for attr in response.json()) if demisto.command() != 'fetch-incidents': demisto.setIntegrationContext({'extended_keys': EXTENDED_KEYS})
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)
def create_issue_command(): url = 'rest/api/latest/issue' issue = get_issue_fields(issue_creating=True, **demisto.args()) result = jira_req('POST', url, json.dumps(issue)) j_res = result.json() md_and_context = generate_md_context_create_issue(j_res, project_key=demisto.getArg('projectKey'), project_name=demisto.getArg('issueTypeName')) human_readable = tableToMarkdown(demisto.command(), md_and_context['md'], "") contents = j_res outputs = md_and_context['context'] return_outputs(readable_output=human_readable, outputs=outputs, raw_response=contents)
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))
def main(): LOG('command is %s' % (demisto.command(),)) try: # Remove proxy if not set to true in params handle_proxy() if demisto.command() == 'test-module': test_module() elif demisto.command() == 'wildfire-upload': wildfire_upload_file_command() elif demisto.command() in ['wildfire-upload-file-remote', 'wildfire-upload-file-url']: wildfire_upload_file_url_command() elif demisto.command() == 'wildfire-upload-url': wildfire_upload_url_command() elif demisto.command() == 'wildfire-report': wildfire_get_report_command() elif demisto.command() == 'file': wildfire_file_command() elif demisto.command() == 'wildfire-get-sample': wildfire_get_sample_command() elif demisto.command() == 'wildfire-get-verdict': wildfire_get_verdict_command() elif demisto.command() == 'wildfire-get-verdicts': wildfire_get_verdicts_command() except Exception as ex: return_error(str(ex)) finally: LOG.print_log()
def main(): """Main Execution block""" try: cmd_name = demisto.command() LOG('Command being called is {}'.format(cmd_name)) if cmd_name in COMMANDS.keys(): COMMANDS[cmd_name]() except Exception as e: # return_error(str(e)) raise e
def create_ticket_context(data, ticket_type): context = { 'ID': data.get('sys_id'), 'Summary': data.get('short_description'), 'Number': data.get('number'), 'CreatedOn': data.get('sys_created_on'), 'Active': data.get('active'), 'AdditionalComments': data.get('comments'), 'CloseCode': data.get('close_code'), 'OpenedAt': data.get('opened_at') } # These fields refer to records in the database, the value is their system ID. if 'closed_by' in data: context['ResolvedBy'] = data['closed_by']['value'] if 'value' in data['closed_by'] else '' if 'opened_by' in data: context['OpenedBy'] = data['opened_by']['value'] if 'value' in data['opened_by'] else '' context['Creator'] = data['opened_by']['value'] if 'value' in data['opened_by'] else '' if 'assigned_to' in data: context['Assignee'] = data['assigned_to']['value'] if 'value' in data['assigned_to'] else '' # Try to map fields if 'priority' in data: # Backward compatibility if demisto.command() in DEPRECATED_COMMANDS: context['Priority'] = data['priority'] else: context['Priority'] = TICKET_PRIORITY.get(data['priority'], data['priority']) if 'state' in data: mapped_state = data['state'] # Backward compatibility if demisto.command() not in DEPRECATED_COMMANDS: if ticket_type in TICKET_STATES: mapped_state = TICKET_STATES[ticket_type].get(data['state'], mapped_state) context['State'] = mapped_state return createContext(context, removeNull=True)
def main(): try: handle_proxy() command = demisto.command() LOG('Command being called is {}'.format(command)) login() if command == 'test-module': test_integration() elif command == 'fetch-incidents': fetch_incidents() elif command == 'fidelis-get-alert': get_alert_command() elif command == 'fidelis-delete-alert': delete_alert_command() elif command == 'fidelis-get-malware-data': get_malware_data_command() elif command == 'fidelis-get-alert-pcap': get_alert_pcap_command() elif command == 'fidelis-get-alert-report': get_alert_report_command() elif command == 'fidelis-sandbox-upload': sandbox_upload_command() elif command == 'fidelis-list-alerts': list_alerts_command() elif command == 'fidelis-upload-pcap': upload_pcap_command() elif command == 'fidelis-run-pcap': run_pcap_command() elif command == 'fidelis-list-pcap-components': list_pcap_components_command() except Exception as e: return_error('error has occurred: {}'.format(str(e))) finally: logout()
def get_issue(issue_id, headers=None, expand_links=False, is_update=False, get_attachments=False): result = jira_req('GET', 'rest/api/latest/issue/' + issue_id) j_res = result.json() if expand_links == "true": expand_urls(j_res) attachments = demisto.get(j_res, 'fields.attachment') # list of all attachments if get_attachments == 'true' and attachments: attachments_zip = jira_req(method='GET', resource_url=f'secure/attachmentzip/{issue_id}.zip').content demisto.results(fileResult(filename=f'{j_res.get("id")}_attachments.zip', data=attachments_zip)) md_and_context = generate_md_context_get_issue(j_res) human_readable = tableToMarkdown(demisto.command(), md_and_context['md'], argToList(headers)) if is_update: human_readable += f'Issue #{issue_id} was updated successfully' contents = j_res outputs = {'Ticket(val.Id == obj.Id)': md_and_context['context']} return_outputs(readable_output=human_readable, outputs=outputs, raw_response=contents)
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)
incidents, max_results = [], 50 if id_offset: query = f'{query} AND id >= {id_offset}' if fetch_by_created: query = f'{query} AND created>-1m' res = run_query(query, '', max_results) for ticket in res.get('issues'): id_offset = max(id_offset, ticket.get("id")) incidents.append(create_incident_from_ticket(ticket)) demisto.setLastRun({"idOffset": id_offset}) demisto.incidents(incidents) ''' COMMANDS MANAGER / SWITCH PANEL ''' demisto.debug('Command being called is %s' % (demisto.command())) try: # Remove proxy if not set to true in params handle_proxy() if demisto.command() == 'test-module': # This is the call made when pressing the integration test button. test_module() elif demisto.command() == 'fetch-incidents': # Set and define the fetch incidents command to run after activated via integration settings. fetch_incidents(**snakify(demisto.params())) elif demisto.command() == 'jira-get-issue': get_issue(**snakify(demisto.args()))
def main(): """ PARSE AND VALIDATE INTEGRATION PARAMS """ params = demisto.params() LOG(f'Command being called is {demisto.command()}') try: client = Client(self_deployed=params.get('self_deployed', False), auth_and_token_url=params.get('auth_id', ''), refresh_token=params.get('refresh_token', ''), enc_key=params.get('enc_key', ''), redirect_uri=params.get('redirect_uri', ''), auth_code=params.get('auth_code', ''), subscription_id=params.get('subscriptionID', ''), resource_group_name=params.get('resourceGroupName', ''), workspace_name=params.get('workspaceName', ''), verify=not params.get('insecure', False), proxy=params.get('proxy', False)) commands = { 'azure-sentinel-get-incident-by-id': get_incident_by_id_command, 'azure-sentinel-list-incidents': list_incidents_command, 'azure-sentinel-update-incident': update_incident_command, 'azure-sentinel-delete-incident': delete_incident_command, 'azure-sentinel-list-incident-comments': list_incident_comments_command, 'azure-sentinel-incident-add-comment': incident_add_comment_command, 'azure-sentinel-list-incident-relations': list_incident_relations_command, 'azure-sentinel-get-entity-by-id': get_entity_by_id_command, 'azure-sentinel-list-entity-relations': list_entity_relations_command } if demisto.command() == 'test-module': # cannot use test module due to the lack of ability to set refresh token to integration context raise Exception("Please use !azure-sentinel-test instead") elif demisto.command() == 'azure-sentinel-test': test_connection(client, params) elif demisto.command() == 'fetch-incidents': # How much time before the first fetch to retrieve incidents first_fetch_time = params.get('fetch_time', '3 days').strip() min_severity = severity_to_level( params.get('min_severity', 'Informational')) # Set and define the fetch incidents command to run after activated via integration settings. next_run, incidents = fetch_incidents( client=client, last_run=demisto.getLastRun(), first_fetch_time=first_fetch_time, min_severity=min_severity) demisto.setLastRun(next_run) demisto.incidents(incidents) elif demisto.command() in commands: return_outputs(*commands[demisto.command()]( client, demisto.args())) # type: ignore except Exception as e: return_error( f'Failed to execute {demisto.command()} command. Error: {str(e)}')
'URL': url_array, 'IP': ip_array, 'Domain': dom_array }) demisto.results({ 'Type': entryTypes['note'], 'ContentsFormat': formats['markdown'], 'Contents': r, 'HumanReadable': tableToMarkdown('URLScan.io query results for {}'.format(raw_query), hr_md, HUMAN_READBALE_HEADERS, removeNull=True), 'EntryContext': ec }) """COMMAND FUNCTIONS""" try: if demisto.command() == 'test-module': search_type = 'ip' query = '8.8.8.8' urlscan_search(search_type, query) demisto.results('ok') if demisto.command() in {'urlscan-submit', 'url'}: urlscan_submit_command() if demisto.command() == 'urlscan-search': urlscan_search_command() except Exception as e: LOG(e) LOG.print_log(False) return_error(e.message)
hash_type_key = HASH_TYPE_KEYS.get(hash_type) if not hash_type_key: return create_error_entry('file argument must be sha1(40 charecters) or sha256(64 charecters) or md5(32 charecters)') hash_param = {} hash_param[hash_type_key] = hash try: tie_client.set_file_reputation(trust_level_key, hash_param, filename, comment) return 'Successfully set file repuation' except Exception as ex: return create_error_entry(str(ex)) args = demisto.args() if demisto.command() == 'test-module': test() demisto.results('ok') sys.exit(0) elif demisto.command() == 'file': results = file(args.get('file')) demisto.results(results) sys.exit(0) elif demisto.command() == 'tie-file-references': results = file_references(args.get('file')) demisto.results(results) sys.exit(0) elif demisto.command() == 'tie-set-file-reputation': results = set_file_reputation( args.get('file'), args.get('trust_level'),
res_json = res.json() if 'qvs.findAllIdsResponse' in res_json and 'qvs.return' in res_json.get('qvs.findAllIdsResponse'): query_viewers = res_json.get('qvs.findAllIdsResponse').get('qvs.return') contents = decode_arcsight_output(query_viewers) outputs = {'ArcSightESM.AllQueryViewers': contents} human_readable = tableToMarkdown(name='', t=query_viewers, headers='Query Viewers', removeNull=True) return_outputs(readable_output=human_readable, outputs=outputs, raw_response=contents) else: demisto.results('No Query Viewers were found') AUTH_TOKEN = demisto.getIntegrationContext().get('auth_token') or login() try: if demisto.command() == 'test-module': test() demisto.results('ok') elif demisto.command() == 'as-fetch-incidents' or demisto.command() == 'fetch-incidents': fetch() elif demisto.command() == 'as-get-matrix-data' or demisto.command() == 'as-get-query-viewer-results': get_query_viewer_results_command() elif demisto.command() == 'as-get-all-cases': get_all_cases_command() elif demisto.command() == 'as-get-case': get_case_command()
demisto.results( fileResult(file_sha256, extract_zipped_buffer(res.content))) else: raise Exception # Handle like an exception except Exception: demisto.results({ 'Type': entryTypes['error'], 'ContentsFormat': formats['text'], 'Contents': str(res.content) }) ''' COMMANDS MANAGER / SWITCH PANEL ''' LOG('Command being called is %s' % (demisto.command())) try: if demisto.command() == 'test-module': # This is the call made when pressing the integration test button. test_module() demisto.results('ok') elif demisto.command() == 'url': url_command() elif demisto.command() == 'domain': domain_command() elif demisto.command() == 'file': file_command() elif demisto.command() == 'urlhaus-download-sample': urlhaus_download_sample_command()
context = {'URL': url, 'httpTransaction': url_list} ec = { 'URLScan(val.URL && val.URL == obj.URL)': context, } human_readable = tableToMarkdown('{} - http transaction list'.format(url), url_list, ['URLs'], metadata=metadata) return_outputs(human_readable, ec, response) """COMMAND FUNCTIONS""" try: handle_proxy() if demisto.command() == 'test-module': search_type = 'ip' query = '8.8.8.8' urlscan_search(search_type, query) demisto.results('ok') if demisto.command() in {'urlscan-submit', 'url'}: urlscan_submit_command() if demisto.command() == 'urlscan-search': urlscan_search_command() if demisto.command() == 'urlscan-submit-url-command': demisto.results(urlscan_submit_url()) if demisto.command() == 'urlscan-get-http-transaction-list': format_http_transaction_list() if demisto.command() == 'urlscan-get-result-page': demisto.results(get_result_page()) if demisto.command() == 'urlscan-poll-uri':
def main() -> None: params = demisto.params() command = demisto.command() args = demisto.args() demisto.debug(f'Command being called is {command}') try: client = AADClient(app_id=params.get('app_id', ''), subscription_id=params.get('subscription_id', ''), verify=not params.get('insecure', False), proxy=params.get('proxy', False), azure_ad_endpoint=params.get( 'azure_ad_endpoint', 'https://login.microsoftonline.com')) # auth commands if command == 'test-module': return_results( 'The test module is not functional, run the azure-ad-auth-start command instead.' ) elif command == 'azure-ad-auth-start': return_results(start_auth(client)) elif command == 'azure-ad-auth-complete': return_results(complete_auth(client)) elif command == 'azure-ad-auth-test': return_results(test_connection(client)) elif command == 'azure-ad-auth-reset': return_results(reset_auth()) # actual commands elif command == 'azure-ad-identity-protection-risks-list': return_results( azure_ad_identity_protection_risk_detection_list_command( client, **args)) elif command == 'azure-ad-identity-protection-risky-user-list': return_results( azure_ad_identity_protection_risky_users_list_command( client, **args)) elif command == 'azure-ad-identity-protection-risky-user-history-list': return_results( azure_ad_identity_protection_risky_users_history_list_command( client, **args)) elif command == 'azure-ad-identity-protection-risky-user-confirm-compromised': return_results( azure_ad_identity_protection_risky_users_confirm_compromised_command( client, **args)) elif command == 'azure-ad-identity-protection-risky-user-dismiss': return_results( azure_ad_identity_protection_risky_users_dismiss_command( client, **args)) elif command == 'fetch-incidents': incidents, last_run = fetch_incidents(client, params) demisto.incidents(incidents) demisto.setLastRun(last_run) else: raise NotImplementedError( f'Command "{command}" is not implemented.') except Exception as e: return_error( "\n".join( (f'Failed to execute command "{demisto.command()}".', f'Error:{str(e)}', f'Traceback: {traceback.format_exc()}')), e)
def main(): ''' INSTANCE CONFIGURATION ''' SERVER_IP = demisto.params().get('server_ip') USERNAME = demisto.params().get('credentials')['identifier'] PASSWORD = demisto.params().get('credentials')['password'] DEFAULT_BASE_DN = demisto.params().get('base_dn') SECURE_CONNECTION = demisto.params().get('secure_connection') DEFAULT_PAGE_SIZE = int(demisto.params().get('page_size')) NTLM_AUTH = demisto.params().get('ntlm') UNSECURE = demisto.params().get('unsecure', False) PORT = demisto.params().get('port') if PORT: # port was configured, cast to int PORT = int(PORT) last_log_detail_level = None try: try: set_library_log_hide_sensitive_data(True) if is_debug_mode(): demisto.info( 'debug-mode: setting library log detail to EXTENDED') last_log_detail_level = get_library_log_detail_level() set_library_log_detail_level(EXTENDED) server = initialize_server(SERVER_IP, PORT, SECURE_CONNECTION, UNSECURE) except Exception as e: return_error(str(e)) return global conn if NTLM_AUTH: # intialize connection to LDAP server with NTLM authentication # user example: domain\user domain_user = SERVER_IP + '\\' + USERNAME if '\\' not in USERNAME else USERNAME conn = Connection(server, user=domain_user, password=PASSWORD, authentication=NTLM) else: # here username should be the user dn conn = Connection(server, user=USERNAME, password=PASSWORD) # bind operation is the “authenticate” operation. try: # open socket and bind to server if not conn.bind(): message = "Failed to bind to server. Please validate the credentials configured correctly.\n{}".format( json.dumps(conn.result)) return_error(message) return except Exception as e: exc_msg = str(e) demisto.info("Failed bind to: {}:{}. {}: {}".format( SERVER_IP, PORT, type(e), exc_msg + "\nTrace:\n{}".format(traceback.format_exc()))) message = "Failed to access LDAP server. Please validate the server host and port are configured correctly" if 'ssl wrapping error' in exc_msg: message = "Failed to access LDAP server. SSL error." if not UNSECURE: message += ' Try using: "Trust any certificate" option.' return_error(message) return demisto.info('Established connection with AD LDAP server') if not base_dn_verified(DEFAULT_BASE_DN): message = "Failed to verify the base DN configured for the instance.\n" \ "Last connection result: {}\n" \ "Last error from LDAP server: {}".format(json.dumps(conn.result), json.dumps(conn.last_error)) return_error(message) return demisto.info('Verfied base DN "{}"'.format(DEFAULT_BASE_DN)) ''' COMMAND EXECUTION ''' if demisto.command() == 'test-module': if conn.user == '': # Empty response means you have no authentication status on the server, so you are an anonymous user. raise Exception("Failed to authenticate user") demisto.results('ok') if demisto.command() == 'ad-search': free_search(DEFAULT_BASE_DN, DEFAULT_PAGE_SIZE) if demisto.command() == 'ad-expire-password': expire_user_password(DEFAULT_BASE_DN) if demisto.command() == 'ad-set-new-password': set_user_password(DEFAULT_BASE_DN) if demisto.command() == 'ad-unlock-account': unlock_account(DEFAULT_BASE_DN) if demisto.command() == 'ad-disable-account': disable_user(DEFAULT_BASE_DN) if demisto.command() == 'ad-enable-account': enable_user(DEFAULT_BASE_DN) if demisto.command() == 'ad-remove-from-group': remove_member_from_group(DEFAULT_BASE_DN) if demisto.command() == 'ad-add-to-group': add_member_to_group(DEFAULT_BASE_DN) if demisto.command() == 'ad-create-user': create_user() if demisto.command() == 'ad-delete-user': delete_user() if demisto.command() == 'ad-update-user': update_user(DEFAULT_BASE_DN) if demisto.command() == 'ad-modify-computer-ou': modify_computer_ou(DEFAULT_BASE_DN) if demisto.command() == 'ad-create-contact': create_contact() if demisto.command() == 'ad-update-contact': update_contact() if demisto.command() == 'ad-get-user': search_users(DEFAULT_BASE_DN, DEFAULT_PAGE_SIZE) if demisto.command() == 'ad-get-computer': search_computers(DEFAULT_BASE_DN, DEFAULT_PAGE_SIZE) if demisto.command() == 'ad-get-group-members': search_group_members(DEFAULT_BASE_DN, DEFAULT_PAGE_SIZE) except Exception as e: message = str(e) if conn: message += "\nLast connection result: {}\nLast error from LDAP server: {}".format( json.dumps(conn.result), conn.last_error) return_error(message) return finally: # disconnect and close the connection if conn: conn.unbind() if last_log_detail_level: set_library_log_detail_level(last_log_detail_level)
def main() -> None: """Main method used to run actions.""" try: demisto_params = demisto.params() demisto_args = demisto.args() base_url = demisto_params.get('server', '').rstrip('/') verify_ssl = not demisto_params.get('unsecure', False) proxy = demisto_params.get('proxy', False) headers = { 'X-RFToken': demisto_params['token'], 'X-RF-User-Agent': 'Cortex_XSOAR/2.0 Cortex_XSOAR_' f'{demisto.demistoVersion()["version"]}' } client = Client(base_url=base_url, verify=verify_ssl, headers=headers, proxy=proxy) command = demisto.command() if command == 'test-module': try: client.entity_lookup(['8.8.8.8'], 'ip') return_results('ok') except Exception as err: try: error = json.loads(str(err).split('\n')[1]) if 'error' in error: message = error.get("error", {})["message"] return_results(f'Failed due to: {message}') except Exception as err2: return_results('Unknown error. Please verify that the API' ' URL and Token are correctly configured.') elif command in ['url', 'ip', 'domain', 'file', 'cve']: entities = argToList(demisto_args.get(command)) return_results(lookup_command(client, entities, command)) elif command == 'recordedfuture-threat-assessment': context = demisto_args.get('context') entities = { 'ip': argToList(demisto_args.get('ip')), 'domain': argToList(demisto_args.get('domain')), 'hash': argToList(demisto_args.get('file')), 'url': argToList(demisto_args.get('url')), 'vulnerability': argToList(demisto_args.get('cve')) } return_results(triage_command(client, entities, context)) elif command == 'recordedfuture-alert-rules': rule_name = demisto_args.get('rule_name', '') limit = demisto_args.get('limit', 10) return_results(get_alert_rules_command(client, rule_name, limit)) elif command == 'recordedfuture-alerts': params = { x: demisto_args.get(x) for x in demisto_args if not x == 'detailed' } if params.get('rule_id', None): params['alertRule'] = params.pop('rule_id') if params.get('offset', None): params['from'] = params.pop('offset') if params.get('triggered_time', None): date, _ = parse_date_range(params.pop('triggered_time'), date_format='%Y-%m-%d %H:%M:%S') params['triggered'] = '[{},)'.format(date) return_results(get_alerts_command(client, params)) elif command == 'recordedfuture-intelligence': return_results( enrich_command( client, demisto_args.get('entity'), demisto_args.get('entity_type'), demisto_args.get('fetch_related_entities') == 'yes', demisto_args.get('fetch_riskyCIDRips') == 'yes')) except Exception as e: return_error(f'Failed to execute {demisto.command()} command. ' f'Error: {str(e)}')
demisto.results('Performed action successfully') def test(): if MineMeldClient.get_all_nodes(): demisto.results('ok') # code starts here MineMeldClient = APIClient(url=SERVER_URL, username=USERNAME, password=PASSWORD, capath=None) if demisto.command() == 'test-module': test() elif demisto.command() == 'minemeld-add-to-miner' or demisto.command( ) == 'minemeld-remove-from-miner': update_miner() elif demisto.command() == 'minemeld-retrieve-miner': retrieve_miner_indicators() elif demisto.command() == 'minemeld-get-indicator-from-miner': get_indicator_from_miner() elif demisto.command() == 'minemeld-get-all-miners-names': get_all_miner_names() elif demisto.command() == 'domain': domain() elif demisto.command() == 'url': url() elif demisto.command() == 'file':
generic_context = createContext( { 'MD5': file if fmt == 'md5' else None, 'SHA1': file if fmt == 'sha1' else None, 'SHA256': file if fmt == 'sha256' else None }, removeNull=True) make_indicator_reputation_request(indicator_type='file', value=file, generic_context=generic_context) ''' EXECUTION CODE ''' command = demisto.command() LOG('command is {0}'.format(demisto.command())) try: handle_proxy() if command == 'test-module': test_module() elif command == 'threatq-advanced-search': advance_search_command() elif command == 'threatq-search-by-name': search_by_name_command() elif command == 'threatq-search-by-id': search_by_id_command() elif command == 'threatq-create-indicator': create_indicator_command() elif command == 'threatq-create-event': create_event_command()
'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown("AbuseIPDB report categories", categories, removeNull=True), 'EntryContext': { 'AbuseIPDB.Categories(val && val == obj)': createContext(categories, removeNull=True), } } return entry try: if demisto.command() == 'test-module': # Tests connectivity and credentails on login test_module() elif demisto.command() == 'ip': demisto.results(check_ip_command(**demisto.args())) elif demisto.command() == 'abuseipdb-check-cidr-block': demisto.results(check_block_command(**demisto.args())) elif demisto.command() == 'abuseipdb-report-ip': demisto.results(report_ip_command(**demisto.args())) elif demisto.command() == 'abuseipdb-get-blacklist': demisto.results(get_blacklist_command(**demisto.args())) elif demisto.command() == 'abuseipdb-get-categories': demisto.results( get_categories_command(**demisto.args())) # type:ignore except Exception as e:
incidents = [] current_fetch = last_fetch for alert in alerts: current_fetch = 1000 * (int(demisto.get(alert, 'description.created'))) current_fetch = timestamp_to_datestring(current_fetch, '%Y-%m-%d-%H:%M:%S') incident = create_incident(alert) incidents.append(incident) demisto.incidents(incidents) demisto.setLastRun({'time': current_fetch}) # Execution Code try: if demisto.command() == 'test-module': test_module() elif demisto.command() == 'canarytools-list-tokens': list_tokens_command() elif demisto.command() == 'canarytools-get-token': get_token_command() elif demisto.command() == 'canarytools-list-canaries': list_canaries_command() elif demisto.command() == 'canarytools-check-whitelist': check_whitelist_command() elif demisto.command() == 'canarytools-whitelist-ip': whitelist_ip_command() elif demisto.command() == 'canarytools-edit-alert-status': alert_status_command() elif demisto.command() == 'fetch-incidents': fetch_incidents_command()
'DELETE', f'/shodan/alert/{alert_id}/trigger/{trigger}/ignore/{service}') if not res.get('success', False): return_error( f'Failed removing service "{service}" for trigger {trigger} in alert {alert_id} from the whitelist' ) demisto.results( f'Removed service "{service}" for trigger {trigger} in alert {alert_id} from the whitelist' ) ''' COMMANDS MANAGER / SWITCH PANEL ''' if demisto.command() == 'test-module': # This is the call made when pressing the integration test button. test_module() demisto.results('ok') elif demisto.command() == 'search': search_command() elif demisto.command() == 'ip': ip_command() elif demisto.command() == 'shodan-search-count': shodan_search_count_command() elif demisto.command() == 'shodan-scan-ip': shodan_scan_ip_command() elif demisto.command() == 'shodan-scan-internet': shodan_scan_internet_command() elif demisto.command() == 'shodan-scan-status': shodan_scan_status_command()
def main() -> None: try: arguments = demisto.args() api_key = demisto.params().get('apikey') base_url = urljoin(demisto.params()['url'], '/api/') verify_certificate = not demisto.params().get('insecure', False) first_fetch_time = arg_to_timestamp( arg=demisto.params().get('first_fetch', '1 days'), arg_name='First fetch time', required=True ) assert isinstance(first_fetch_time, int) proxy = demisto.params().get('proxy', False) page = arguments.get('page', "1") page_count_no = arguments.get('max', "25") demisto.debug(f'Command being called is {demisto.command()}') params = {'page': page, 'max': page_count_no} headers = { 'Authorization': f'Bearer {api_key}' } client = Client( base_url=base_url, verify=verify_certificate, headers=headers, proxy=proxy) if demisto.command() == 'test-module': result = test_module_command(client) return_results(result) elif demisto.command() == 'fetch-incidents': # Set and define the fetch incidents command to run after activated via integration settings. fetch_incident_command = demisto.params().get('fetch_incident_command') max_results = arg_to_int( arg=demisto.params().get('max_fetch'), arg_name='max_fetch', required=False ) 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(), # getLastRun() gets the last run dict first_fetch_time=first_fetch_time, command_type=fetch_incident_command ) demisto.setLastRun(next_run) demisto.incidents(incidents) elif demisto.command() == 'gra-fetch-users': fetch_records(client, '/users', 'Gra.Users', 'employeeId', params) elif demisto.command() == 'gra-fetch-accounts': fetch_records(client, '/accounts', 'Gra.Accounts', 'id', params) elif demisto.command() == 'gra-fetch-active-resource-accounts': resource_name = arguments.get('resource_name', 'Windows Security') active_resource_url = '/resources/' + resource_name + '/accounts' fetch_records(client, active_resource_url, 'Gra.Active.Resource.Accounts', 'id', params) elif demisto.command() == 'gra-fetch-user-accounts': employee_id = arguments.get('employee_id') user_account_url = '/users/' + employee_id + '/accounts' fetch_records(client, user_account_url, 'Gra.User.Accounts', 'id', params) elif demisto.command() == 'gra-fetch-resource-highrisk-accounts': res_name = arguments.get('Resource_name', 'Windows Security') high_risk_account_resource_url = '/resources/' + res_name + '/accounts/highrisk' fetch_records(client, high_risk_account_resource_url, 'Gra.Resource.Highrisk.Accounts', 'id', params) elif demisto.command() == 'gra-fetch-hpa': fetch_records(client, '/accounts/highprivileged', 'Gra.Hpa', 'id', params) elif demisto.command() == 'gra-fetch-resource-hpa': resource_name = arguments.get('Resource_name', 'Windows Security') resource_hpa = '/resources/' + resource_name + '/accounts/highprivileged' fetch_records(client, resource_hpa, 'Gra.Resource.Hpa', 'id', params) elif demisto.command() == 'gra-fetch-orphan-accounts': fetch_records(client, '/accounts/orphan', 'Gra.Orphan.Accounts', 'id', params) elif demisto.command() == 'gra-fetch-resource-orphan-accounts': resource_name = arguments.get('resource_name', 'Windows Security') resource_orphan = '/resources/' + resource_name + '/accounts/orphan' fetch_records(client, resource_orphan, 'Gra.Resource.Orphan.Accounts', 'id', params) elif demisto.command() == 'gra-user-activities': employee_id = arguments.get('employee_id') user_activities_url = '/user/' + employee_id + '/activity' fetch_records(client, user_activities_url, 'Gra.User.Activity', 'employee_id', params) elif demisto.command() == 'gra-fetch-users-details': employee_id = arguments.get('employee_id') fetch_records(client, '/users/' + employee_id, 'Gra.User', 'employeeId', params) elif demisto.command() == 'gra-highRisk-users': fetch_records(client, '/users/highrisk', 'Gra.Highrisk.Users', 'employeeId', params) elif demisto.command() == 'gra-cases': status = arguments.get('status') cases_url = '/cases/' + status fetch_records(client, cases_url, 'Gra.Cases', 'caseId', params) elif demisto.command() == 'gra-user-anomalies': employee_id = arguments.get('employee_id') anomaly_url = '/users/' + employee_id + '/anomalies/' fetch_records(client, anomaly_url, 'Gra.User.Anomalies', 'anomaly_name', params) elif demisto.command() == 'gra-case-action': action = arguments.get('action') caseId = arguments.get('caseId') subOption = arguments.get('subOption') caseComment = arguments.get('caseComment') riskAcceptDate = arguments.get('riskAcceptDate') cases_url = '/cases/' + action if action == 'riskManageCase': post_url = {"caseId": int(caseId), "subOption": subOption, "caseComment": caseComment, "riskAcceptDate": riskAcceptDate} else: post_url = {"caseId": int(caseId), "subOption": subOption, "caseComment": caseComment} post_url_json = json.dumps(post_url) fetch_post_records(client, cases_url, 'Gra.Case.Action', 'caseId', params, post_url_json) elif demisto.command() == 'gra-case-action-anomaly': action = arguments.get('action') caseId = arguments.get('caseId') anomalyNames = arguments.get('anomalyNames') subOption = arguments.get('subOption') caseComment = arguments.get('caseComment') riskAcceptDate = arguments.get('riskAcceptDate') cases_url = '/cases/' + action if action == 'riskAcceptCaseAnomaly': post_url = {"caseId": int(caseId), "anomalyNames": anomalyNames, "subOption": subOption, "caseComment": caseComment, "riskAcceptDate": riskAcceptDate} else: post_url = {"caseId": int(caseId), "anomalyNames": anomalyNames, "subOption": subOption, "caseComment": caseComment} post_url_json = json.dumps(post_url) fetch_post_records(client, cases_url, 'Gra.Cases.Action.Anomaly', 'caseId', params, post_url_json) elif demisto.command() == 'gra-investigate-anomaly-summary': fromDate = arguments.get('fromDate') toDate = arguments.get('toDate') modelName = arguments.get('modelName') if fromDate is not None and toDate is not None: investigateAnomaly_url = '/investigateAnomaly/anomalySummary/' + modelName + '?fromDate=' + fromDate \ + ' 00:00:00&toDate=' + toDate + ' 23:59:59' else: investigateAnomaly_url = '/investigateAnomaly/anomalySummary/' + modelName fetch_records(client, investigateAnomaly_url, 'Gra.Investigate.Anomaly.Summary', 'modelId', params) # 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)}')
def main() -> None: """ main function, parses params and runs command functions """ params = demisto.params() # Authentication api_key = params.get("apikey") # get the service API url base_url = urljoin(params["url"], "/api/1.5/") verify_certificate = not params.get("insecure", False) proxy = params.get("proxy", False) comment_tag = params.get("comment_tag") escalate_tag = params.get("escalate_tag") input_tag = params.get("input_tag") get_attachments = params.get("get_attachments", False) close_incident = params.get("close_incident", False) reopen_incident = params.get("reopen_incident", False) reopen_group = params.get("reopen_group", "Default") demisto.debug(f"Command being called is {demisto.command()}") try: client = Client( base_url=base_url, verify_certificate=verify_certificate, api_key=api_key, proxy=proxy, comment_tag=comment_tag, escalate_tag=escalate_tag, input_tag=input_tag, get_attachments=get_attachments, close_incident=close_incident, reopen_incident=reopen_incident, reopen_group=reopen_group, ) if demisto.command() == "test-module": # This is the call made when pressing the integration Test button. result = test_module(client) return_results(result) elif demisto.command() == "fetch-incidents": max_fetch = params.get("max_fetch", 100) last_run = demisto.getLastRun() first_fetch_timestamp = params.get("first_fetch_timestamp", "7 days").strip() mirror_direction = MIRROR_DIRECTION.get( demisto.params().get("mirror_direction", "None"), None) integration_instance = demisto.integrationInstance() incidents, new_last_run = fetch_incidents( client=client, last_run=last_run, max_fetch=max_fetch, first_fetch_time=first_fetch_timestamp, mirror_direction=mirror_direction, integration_instance=integration_instance, ) demisto.setLastRun(new_last_run) demisto.incidents(incidents) elif demisto.command() == "get-mapping-fields": result = get_mapping_fields() return_results(result) elif demisto.command() == "get-remote-data": investigation = demisto.investigation() result = get_remote_data(client, investigation, demisto.args()) return_results(result) elif demisto.command() == "get-modified-remote-data": result = get_modified_remote_data(client, demisto.args()) return_results(result) elif demisto.command() == "update-remote-system": investigation = demisto.investigation() result = update_remote_system(client, investigation, demisto.args()) return_results(result) elif demisto.command() == "ztap-get-alert-entries": result = ztap_get_alert_entries(client, demisto.args()) return_results(result) # 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)}" )
users_readable, users_outputs = parse_outputs(users_data) human_readable = tableToMarkdown(name='All Graph Users', t=users_readable, removeNull=True) outputs = {'MSGraphUser(val.ID == obj.ID)': users_outputs} return_outputs(readable_output=human_readable, outputs=outputs, raw_response=users_data) def list_users(properties): users = http_request('GET', 'users', params={'$select': properties}).get('value') return users try: handle_proxy() # COMMANDS if demisto.command() == 'test-module': test_function() elif demisto.command() == 'msgraph-user-terminate-session': terminate_user_session_command() elif demisto.command() == 'msgraph-user-unblock': unblock_user_command() elif demisto.command() == 'msgraph-user-update': update_user_command() elif demisto.command() == 'msgraph-user-delete': delete_user_command() elif demisto.command() == 'msgraph-user-create':
def main(): try: handle_proxy() command = demisto.command() LOG('Command being called is {}'.format(command)) login() if command == 'test-module': test_integration() elif command == 'fetch-incidents': fetch_incidents() elif command == 'fidelis-get-alert': get_alert_command() elif command == 'fidelis-delete-alert': delete_alert_command() elif command == 'fidelis-get-malware-data': get_malware_data_command() elif command == 'fidelis-get-alert-pcap': get_alert_pcap_command() elif command == 'fidelis-get-alert-report': get_alert_report_command() elif command == 'fidelis-sandbox-upload': sandbox_upload_command() elif command == 'fidelis-list-alerts': list_alerts_command() elif command == 'fidelis-upload-pcap': upload_pcap_command() elif command == 'fidelis-run-pcap': run_pcap_command() elif command == 'fidelis-list-pcap-components': list_pcap_components_command() elif command == 'fidelis-get-alert-by-uuid': get_alert_by_uuid() elif command == 'fidelis-list-metadata': list_metadata() elif command == 'fidelis-list-alerts-by-ip': list_alerts_by_ip() elif command == 'fidelis-download-malware-file': download_malware_file() elif command == 'fidelis-download-pcap-file': download_pcap_file() elif command == 'fidelis-get-alert-session-data': get_alert_sessiondata_command() elif command == 'fidelis-get-alert-execution-forensics': get_alert_ef_command() elif command == 'fidelis-get-alert-forensic-text': get_alert_forensictext_command() elif command == 'fidelis-get-alert-decoding-path': get_alert_dpath_command() elif command == 'fidelis-update-alert-status': update_alertstatus_command() elif command == 'fidelis-alert-execution-forensics-submission': alert_ef_submission_command() elif command == 'fidelis-add-alert-comment': add_alert_comment_command() elif command == 'fidelis-assign-user-to-alert': manage_alert_assignuser_command() elif command == 'fidelis-close-alert': manage_alert_closealert_command() elif command == 'fidelis-manage-alert-label': manage_alert_label_command() except Exception as e: return_error('error has occurred: {}'.format(str(e))) finally: logout()
params = demisto.params() server = params["server"].rstrip('/') prefix = server + "/awakeapi/v1" verify = not params.get('unsecure', False) credentials = params["credentials"] identifier = credentials["identifier"] password = credentials["password"] suspicious_threshold = params["suspicious_threshold"] malicious_threshold = params["malicious_threshold"] authTokenRequest = {"loginUsername": identifier, "loginPassword": password} authTokenResponse = requests.post(prefix + "/authtoken", json=authTokenRequest, verify=verify) authToken = authTokenResponse.json()["token"]["value"] headers = {"Authentication": ("access " + authToken)} command = demisto.command() args = demisto.args() request = {} ''' HELPERS ''' # Convenient utility to marshal command arguments into the request body def slurp(fields): for field in fields: if field in args: request[field] = args[field] # Render a subset of the fields of the Contents as a markdown table
cursor.execute(db_operation) demisto.results('Operation executed successfully.') '''COMMAND SWITCHBOARD''' commands = { 'test-module': test_module, 'fetch-incidents': fetch_incidents, 'snowflake-query': snowflake_query_command, 'snowflake-update': snowflake_update_command } '''EXECUTION''' try: handle_proxy() if demisto.command() in commands.keys(): commands[demisto.command()]() except snowflake.connector.errors.Error as e: return_error(error_message_from_snowflake_error(e)) except Exception as e: if IS_FETCH: raise e else: if isinstance(e, snowflake.connector.errors.Error): return_error(error_message_from_snowflake_error(e)) else: return_error(str(e))
def rasterize_email_command(): html = demisto.args()['htmlBody'] friendly_name = 'email.png' if demisto.get(demisto.args(), 'type') == 'pdf': friendly_name = 'email.pdf' rasterize_email_request(html, friendly_name) if return_code == 0: file = file_result_existing_file(friendly_name) file['Type'] = entryTypes['image'] demisto.results(file) else: demisto.results({'ContentsFormat': 'text', 'Type': entryTypes['error'], 'Contents': 'PhantomJS returned - ' + error_message}) if demisto.command() == 'test-module': rasterize_email_request('test text', 'email.png') if return_code == 0: demisto.results('ok') else: demisto.results(error_message) elif demisto.command() == 'rasterize-image': rasterize_image() elif demisto.command() == 'rasterize-email': rasterize_email_command() elif demisto.command() == 'rasterize': rasterize() else:
def main() -> None: """main function, parses params and runs command functions Args: None Returns: None """ params = demisto.params() # Credentials api_key = params.get('username').get("password") username = params.get('username').get("identifier") # SecurityScorecard API URL base_url = params.get('base_url', "https://api.securityscorecard.io/") # Default configuration verify_certificate = not params.get('insecure', False) proxy = params.get('proxy', False) # Fetch configuration max_fetch = params.get("max_fetch") incident_fetch_interval = params.get("incidentFetchInterval") args: Dict[str, str] = demisto.args() demisto.debug(f'Command being called is {demisto.command()}') try: headers: Dict = {"Authorization": f"Token {api_key}"} client = SecurityScorecardClient(base_url=base_url, verify=verify_certificate, headers=headers, proxy=proxy, api_key=api_key, username=username, max_fetch=max_fetch) if demisto.command() == 'test-module': return_results( test_module(client=client, incident_fetch_interval=incident_fetch_interval)) elif demisto.command() == "fetch-incidents": fetch_alerts(client=client) elif demisto.command() == 'securityscorecard-portfolios-list': return_results(portfolios_list_command(client=client, args=args)) elif demisto.command() == 'securityscorecard-portfolio-list-companies': return_results( portfolio_list_companies_command(client=client, args=args)) elif demisto.command() == 'securityscorecard-company-score-get': return_results(company_score_get_command(client=client, args=args)) elif demisto.command() == 'securityscorecard-company-factor-score-get': return_results( company_factor_score_get_command(client=client, args=args)) elif demisto.command( ) == 'securityscorecard-company-history-score-get': return_results( company_history_score_get_command(client=client, args=args)) elif demisto.command( ) == 'securityscorecard-company-history-factor-score-get': return_results( company_history_factor_score_get_command(client=client, args=args)) elif demisto.command( ) == 'securityscorecard-alert-grade-change-create': return_results( alert_grade_change_create_command(client=client, args=args)) elif demisto.command( ) == 'securityscorecard-alert-score-threshold-create': return_results( alert_score_threshold_create_command(client=client, args=args)) elif demisto.command() == 'securityscorecard-alert-delete': return_results(alert_delete_command(client=client, args=args)) elif demisto.command() == 'securityscorecard-alerts-list': return_results(alerts_list_command(client=client, args=args)) elif demisto.command() == 'securityscorecard-company-services-get': return_results( company_services_get_command(client=client, args=args)) # Log exceptions and return errors except Exception as e: demisto.error(traceback.format_exc()) # print the traceback return_error( f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}' )
def main() -> None: try: params = demisto.params() base_url = urljoin(params['url'], '/api') if not params.get('credentials') or not (api_token := params.get( 'credentials', {}).get('password')): raise DemistoException( 'Missing API Key. Fill in a valid key in the integration configuration.' ) verify_certificate = not params.get('insecure', False) proxy = params.get('proxy', False) command = demisto.command() args = demisto.args() if demisto.args() else {} demisto.debug(f'Command being called is {command}') client = Client(base_url=base_url, use_ssl=verify_certificate, use_proxy=proxy, apitoken=api_token) commands: Dict[str, Callable] = { 'cb-edr-processes-search': processes_search_command, 'cb-edr-process-get': process_get_command, 'cb-edr-process-segments-get': process_segments_get_command, 'cb-edr-process-events-list': process_events_list_command, 'cb-edr-binary-search': binary_search_command, 'cb-edr-binary-download': binary_download_command, 'cb-edr-binary-summary': binary_summary_command, 'cb-edr-alert-search': alert_search_command, 'cb-edr-alert-update': alert_update_command, 'cb-edr-binary-bans-list': binary_bans_list_command, 'cb-edr-binary-ban': binary_ban_command, 'cb-edr-watchlists-list': get_watchlist_list_command, 'cb-edr-watchlist-create': watchlist_create_command, 'cb-edr-watchlist-update': watchlist_update_command, 'cb-edr-watchlist-delete': watchlist_delete_command, 'cb-edr-sensors-list': sensors_list_command, 'cb-edr-quarantine-device': quarantine_device_command, 'cb-edr-unquarantine-device': unquarantine_device_command, 'cb-edr-sensor-installer-download': sensor_installer_download_command, 'endpoint': endpoint_command } if command == 'test-module': result = test_module(client, params) return_results(result) elif command == 'fetch-incidents': next_run, incidents = fetch_incidents( client=client, max_results=params.get('max_fetch'), last_run=demisto.getLastRun(), first_fetch_time=params.get('first_fetch', '3 days'), status=params.get('alert_status', None), feedname=params.get('alert_feed_name', None), query=params.get('alert_query', None)) demisto.setLastRun(next_run) demisto.incidents(incidents) elif command in commands: return_results(commands[command](client, **args)) else: raise NotImplementedError( f'command {command} was not implemented in this integration.')
def main(): params: Dict = demisto.params() server: str = params.get('server', '').rstrip('/') credentials: Dict = params.get('credentials', {}) username: str = credentials.get('identifier', '') password: str = credentials.get('password', '') fetch_time: str = params.get('fetch_time', '3 days').strip() try: fetch_limit: int = int(params.get('fetch_limit', '10')) except ValueError: raise DemistoException('Value for fetch_limit must be an integer.') saved_report_id: str = demisto.params().get('saved_report_id', '') last_run: dict = demisto.getLastRun() args: dict = demisto.args() verify_ssl = not params.get('insecure', False) wsdl: str = f'{server}/ProtectManager/services/v2011/incidents?wsdl' session: Session = Session() session.auth = SymantecAuth(username, password, server) session.verify = verify_ssl cache: SqliteCache = SqliteCache(timeout=None) transport: Transport = Transport(session=session, cache=cache) client: Client = Client(wsdl=wsdl, transport=transport) command = demisto.command() demisto.info(f'Command being called is {command}') commands = { 'test-module': test_module, 'fetch-incidents': fetch_incidents, 'symantec-dlp-get-incident-details': get_incident_details_command, 'symantec-dlp-list-incidents': list_incidents_command, 'symantec-dlp-update-incident': update_incident_command, 'symantec-dlp-incident-binaries': incident_binaries_command, 'symantec-dlp-list-custom-attributes': list_custom_attributes_command, 'symantec-dlp-list-incident-status': list_incident_status_command, 'symantec-dlp-incident-violations': incident_violations_command } try: handle_proxy() if command == 'fetch-incidents': fetch_incidents(client, fetch_time, fetch_limit, last_run, saved_report_id) # type: ignore[operator] elif command == 'test-module': test_module(client, saved_report_id) # type: ignore[arg-type] elif command == 'symantec-dlp-list-incidents': human_readable, context, raw_response =\ commands[command](client, args, saved_report_id) # type: ignore[operator] return_outputs(human_readable, context, raw_response) elif command == 'symantec-dlp-list-incident-status' or command == 'symantec-dlp-list-custom-attributes': human_readable, context, raw_response = commands[command]( client) # type: ignore[operator] return_outputs(human_readable, context, raw_response) elif command == 'symantec-dlp-incident-binaries': human_readable, context, file_entries, raw_response =\ commands[command](client, args) # type: ignore[operator] return_outputs(human_readable, context, raw_response) for file_entry in file_entries: demisto.results(file_entry) elif command in commands: human_readable, context, raw_response = commands[command]( client, args) # type: ignore[operator] return_outputs(human_readable, context, raw_response) # Log exceptions except Exception as e: err_msg = f'Error in Symantec DLP integration: {str(e)}' if demisto.command() == 'fetch-incidents': LOG(err_msg) LOG.print_log() raise else: return_error(err_msg, error=e)
""" 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)) ''' COMMANDS MANAGER / SWITCH PANEL ''' LOG('Command being called is %s' % (demisto.command())) try: if demisto.command() == 'test-module': test_module() elif demisto.command() == 'bigquery-query': query_command() except Exception as e: LOG(str(e)) LOG.print_log() raise
''' EXECUTION CODE ''' COMMANDS = { 'test-module': test_integration, 'fetch-incidents': fetch_incidents, 'redcanary-list-detections': list_detections_command, 'redcanary-list-endpoints': list_endpoints_command, 'redcanary-get-endpoint': get_endpoint_command, 'redcanary-get-endpoint-detections': get_endpoint_detections_command, 'redcanary-get-detection': get_detection_command, 'redcanary-acknowledge-detection': acknowledge_detection_command, 'redcanary-update-remediation-state': remediate_detection_command, 'redcanary-execute-playbook': execute_playbook_command, } try: handle_proxy() LOG('command is %s' % (demisto.command(), )) command_func = COMMANDS.get(demisto.command()) if command_func is not None: if demisto.command() == 'fetch-incidents': demisto.incidents(command_func()) else: demisto.results(command_func()) except Exception as e: LOG(e.message) if demisto.command() != 'test-module': LOG.print_log() return_error('error has occurred: {}'.format(e.message, ))
}) '''COMMAND SWITCHBOARD''' commands = { 'azure-vm-list-instances': list_vms_command, 'azure-vm-get-instance-details': get_vm_command, 'azure-vm-start-instance': start_vm_command, 'azure-vm-poweroff-instance': poweroff_vm_command, 'azure-vm-create-instance': create_vm_command, 'azure-vm-delete-instance': delete_vm_command, 'azure-list-resource-groups': list_resource_groups_command } '''EXECUTION''' try: # Initial setup SUBSCRIPTION_ID = set_subscription_id() BASE_URL = SERVER + '/subscriptions/' + SUBSCRIPTION_ID + '/resourceGroups/' if demisto.command() == 'test-module': test_module() elif demisto.command() in commands.keys(): commands[demisto.command()]() except Exception as e: screened_error_message = screen_errors(e.message, TENANT_ID) return_error(screened_error_message)
def main(): params = demisto.params() username = params.get('credentials').get('identifier') password = params.get('credentials').get('password') domain = params.get('domain') # Remove trailing slash to prevent wrong URL path to service server = params['url'].strip('/') # Service base URL base_url = server + '/api/v2/' # Should we use SSL use_ssl = not params.get('insecure', False) api_token = params.get('api_token') # Remove proxy if not set to true in params handle_proxy() command = demisto.command() client = Client(base_url, username, password, domain, api_token=api_token, verify=use_ssl) demisto.info(f'Command being called is {command}') commands = { 'test-module': test_module, 'tn-get-system-status': get_system_status, 'tn-get-package': get_package, 'tn-create-package': create_package, 'tn-list-packages': get_packages, 'tn-get-sensor': get_sensor, 'tn-list-sensors': get_sensors, 'tn-ask-question': ask_question, 'tn-get-question-metadata': get_question_metadata, 'tn-get-question-result': get_question_result, 'tn-create-saved-question': create_saved_question, 'tn-get-saved-question-metadata': get_saved_question_metadata, 'tn-get-saved-question-result': get_saved_question_result, 'tn-list-saved-questions': get_saved_questions, 'tn-create-action': create_action, 'tn-create-action-by-host': create_action_by_host, 'tn-get-action': get_action, 'tn-list-actions': get_actions, 'tn-create-saved-action': create_saved_action, 'tn-get-saved-action': get_saved_action, 'tn-list-saved-actions': get_saved_actions, 'tn-list-saved-actions-pending-approval': get_saved_actions_pending, 'tn-create-filter-based-group': create_filter_based_group, 'tn-create-manual-group': create_manual_group, 'tn-get-group': get_group, 'tn-list-groups': get_groups, 'tn-delete-group': delete_group } try: if command in commands: human_readable, outputs, raw_response = commands[command]( client, demisto.args()) return_outputs(readable_output=human_readable, outputs=outputs, raw_response=raw_response) # Log exceptions except Exception as e: err_msg = f'Error in Tanium v2 Integration [{e}]' return_error(err_msg, error=e)
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) args = demisto.args() params = demisto.params() LOG(f'Command being called is {demisto.command()}') try: if demisto.command() == 'test-module': result = test_module() return_error(result) refresh_token = params.get('refresh_token', '') self_deployed = params.get('self_deployed', False) redirect_uri = params.get('redirect_uri', '') tenant_id = refresh_token if self_deployed else '' auth_id = params['auth_id'] enc_key = params.get('enc_key') certificate_thumbprint = params.get('certificate_thumbprint') private_key = params.get('private_key') if not self_deployed and not enc_key: raise DemistoException('Key must be provided. For further information see https://xsoar.pan.dev/docs' '/reference/articles/microsoft-integrations---authentication') elif not enc_key and not (certificate_thumbprint and private_key): raise DemistoException('Key or Certificate Thumbprint and Private Key must be provided.') refresh_token = get_integration_context().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, timeout=calculate_timeout_value(params=params, args=args), enc_key=enc_key, auth_code=params.get('auth_code', ''), redirect_uri=redirect_uri, certificate_thumbprint=certificate_thumbprint, private_key=private_key ) 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)}')
def main() -> None: """main function, parses params and runs command functions :return: :rtype: """ # SSH Key integration requires ssh_agent to be running in the background ssh_agent_setup.setup() # Common Inputs command = demisto.command() args = demisto.args() int_params = demisto.params() creds_mapping = {"identifier": "username", "password": "******"} try: if command == 'test-module': # This is the call made when pressing the integration Test button. result = generic_ansible('VMware', 'vmware_about_info', args, int_params, host_type, creds_mapping) if result: return_results('ok') else: return_results(result) elif command == 'vmware-about-info': return_results( generic_ansible('VMware', 'vmware_about_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-category': return_results( generic_ansible('VMware', 'vmware_category', args, int_params, host_type, creds_mapping)) elif command == 'vmware-category-info': return_results( generic_ansible('VMware', 'vmware_category_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-cfg-backup': return_results( generic_ansible('VMware', 'vmware_cfg_backup', args, int_params, host_type, creds_mapping)) elif command == 'vmware-cluster': return_results( generic_ansible('VMware', 'vmware_cluster', args, int_params, host_type, creds_mapping)) elif command == 'vmware-cluster-drs': return_results( generic_ansible('VMware', 'vmware_cluster_drs', args, int_params, host_type, creds_mapping)) elif command == 'vmware-cluster-ha': return_results( generic_ansible('VMware', 'vmware_cluster_ha', args, int_params, host_type, creds_mapping)) elif command == 'vmware-cluster-info': return_results( generic_ansible('VMware', 'vmware_cluster_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-cluster-vsan': return_results( generic_ansible('VMware', 'vmware_cluster_vsan', args, int_params, host_type, creds_mapping)) elif command == 'vmware-content-deploy-template': return_results( generic_ansible('VMware', 'vmware_content_deploy_template', args, int_params, host_type, creds_mapping)) elif command == 'vmware-content-library-info': return_results( generic_ansible('VMware', 'vmware_content_library_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-content-library-manager': return_results( generic_ansible('VMware', 'vmware_content_library_manager', args, int_params, host_type, creds_mapping)) elif command == 'vmware-datacenter': return_results( generic_ansible('VMware', 'vmware_datacenter', args, int_params, host_type, creds_mapping)) elif command == 'vmware-datastore-cluster': return_results( generic_ansible('VMware', 'vmware_datastore_cluster', args, int_params, host_type, creds_mapping)) elif command == 'vmware-datastore-info': return_results( generic_ansible('VMware', 'vmware_datastore_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-datastore-maintenancemode': return_results( generic_ansible('VMware', 'vmware_datastore_maintenancemode', args, int_params, host_type, creds_mapping)) elif command == 'vmware-dns-config': return_results( generic_ansible('VMware', 'vmware_dns_config', args, int_params, host_type, creds_mapping)) elif command == 'vmware-drs-group': return_results( generic_ansible('VMware', 'vmware_drs_group', args, int_params, host_type, creds_mapping)) elif command == 'vmware-drs-group-info': return_results( generic_ansible('VMware', 'vmware_drs_group_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-drs-rule-info': return_results( generic_ansible('VMware', 'vmware_drs_rule_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-dvs-host': return_results( generic_ansible('VMware', 'vmware_dvs_host', args, int_params, host_type, creds_mapping)) elif command == 'vmware-dvs-portgroup': return_results( generic_ansible('VMware', 'vmware_dvs_portgroup', args, int_params, host_type, creds_mapping)) elif command == 'vmware-dvs-portgroup-find': return_results( generic_ansible('VMware', 'vmware_dvs_portgroup_find', args, int_params, host_type, creds_mapping)) elif command == 'vmware-dvs-portgroup-info': return_results( generic_ansible('VMware', 'vmware_dvs_portgroup_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-dvswitch': return_results( generic_ansible('VMware', 'vmware_dvswitch', args, int_params, host_type, creds_mapping)) elif command == 'vmware-dvswitch-lacp': return_results( generic_ansible('VMware', 'vmware_dvswitch_lacp', args, int_params, host_type, creds_mapping)) elif command == 'vmware-dvswitch-nioc': return_results( generic_ansible('VMware', 'vmware_dvswitch_nioc', args, int_params, host_type, creds_mapping)) elif command == 'vmware-dvswitch-pvlans': return_results( generic_ansible('VMware', 'vmware_dvswitch_pvlans', args, int_params, host_type, creds_mapping)) elif command == 'vmware-dvswitch-uplink-pg': return_results( generic_ansible('VMware', 'vmware_dvswitch_uplink_pg', args, int_params, host_type, creds_mapping)) elif command == 'vmware-evc-mode': return_results( generic_ansible('VMware', 'vmware_evc_mode', args, int_params, host_type, creds_mapping)) elif command == 'vmware-folder-info': return_results( generic_ansible('VMware', 'vmware_folder_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest': return_results( generic_ansible('VMware', 'vmware_guest', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-boot-info': return_results( generic_ansible('VMware', 'vmware_guest_boot_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-boot-manager': return_results( generic_ansible('VMware', 'vmware_guest_boot_manager', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-custom-attribute-defs': return_results( generic_ansible('VMware', 'vmware_guest_custom_attribute_defs', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-custom-attributes': return_results( generic_ansible('VMware', 'vmware_guest_custom_attributes', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-customization-info': return_results( generic_ansible('VMware', 'vmware_guest_customization_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-disk': return_results( generic_ansible('VMware', 'vmware_guest_disk', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-disk-info': return_results( generic_ansible('VMware', 'vmware_guest_disk_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-find': return_results( generic_ansible('VMware', 'vmware_guest_find', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-info': return_results( generic_ansible('VMware', 'vmware_guest_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-move': return_results( generic_ansible('VMware', 'vmware_guest_move', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-network': return_results( generic_ansible('VMware', 'vmware_guest_network', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-powerstate': return_results( generic_ansible('VMware', 'vmware_guest_powerstate', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-screenshot': return_results( generic_ansible('VMware', 'vmware_guest_screenshot', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-sendkey': return_results( generic_ansible('VMware', 'vmware_guest_sendkey', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-snapshot': return_results( generic_ansible('VMware', 'vmware_guest_snapshot', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-snapshot-info': return_results( generic_ansible('VMware', 'vmware_guest_snapshot_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-tools-upgrade': return_results( generic_ansible('VMware', 'vmware_guest_tools_upgrade', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-tools-wait': return_results( generic_ansible('VMware', 'vmware_guest_tools_wait', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-video': return_results( generic_ansible('VMware', 'vmware_guest_video', args, int_params, host_type, creds_mapping)) elif command == 'vmware-guest-vnc': return_results( generic_ansible('VMware', 'vmware_guest_vnc', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host': return_results( generic_ansible('VMware', 'vmware_host', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-acceptance': return_results( generic_ansible('VMware', 'vmware_host_acceptance', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-active-directory': return_results( generic_ansible('VMware', 'vmware_host_active_directory', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-capability-info': return_results( generic_ansible('VMware', 'vmware_host_capability_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-config-info': return_results( generic_ansible('VMware', 'vmware_host_config_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-config-manager': return_results( generic_ansible('VMware', 'vmware_host_config_manager', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-datastore': return_results( generic_ansible('VMware', 'vmware_host_datastore', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-dns-info': return_results( generic_ansible('VMware', 'vmware_host_dns_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-facts': return_results( generic_ansible('VMware', 'vmware_host_facts', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-feature-info': return_results( generic_ansible('VMware', 'vmware_host_feature_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-firewall-info': return_results( generic_ansible('VMware', 'vmware_host_firewall_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-firewall-manager': return_results( generic_ansible('VMware', 'vmware_host_firewall_manager', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-hyperthreading': return_results( generic_ansible('VMware', 'vmware_host_hyperthreading', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-ipv6': return_results( generic_ansible('VMware', 'vmware_host_ipv6', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-kernel-manager': return_results( generic_ansible('VMware', 'vmware_host_kernel_manager', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-lockdown': return_results( generic_ansible('VMware', 'vmware_host_lockdown', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-ntp': return_results( generic_ansible('VMware', 'vmware_host_ntp', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-ntp-info': return_results( generic_ansible('VMware', 'vmware_host_ntp_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-package-info': return_results( generic_ansible('VMware', 'vmware_host_package_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-powermgmt-policy': return_results( generic_ansible('VMware', 'vmware_host_powermgmt_policy', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-powerstate': return_results( generic_ansible('VMware', 'vmware_host_powerstate', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-scanhba': return_results( generic_ansible('VMware', 'vmware_host_scanhba', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-service-info': return_results( generic_ansible('VMware', 'vmware_host_service_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-service-manager': return_results( generic_ansible('VMware', 'vmware_host_service_manager', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-snmp': return_results( generic_ansible('VMware', 'vmware_host_snmp', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-ssl-info': return_results( generic_ansible('VMware', 'vmware_host_ssl_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-vmhba-info': return_results( generic_ansible('VMware', 'vmware_host_vmhba_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-host-vmnic-info': return_results( generic_ansible('VMware', 'vmware_host_vmnic_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-local-role-info': return_results( generic_ansible('VMware', 'vmware_local_role_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-local-role-manager': return_results( generic_ansible('VMware', 'vmware_local_role_manager', args, int_params, host_type, creds_mapping)) elif command == 'vmware-local-user-info': return_results( generic_ansible('VMware', 'vmware_local_user_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-local-user-manager': return_results( generic_ansible('VMware', 'vmware_local_user_manager', args, int_params, host_type, creds_mapping)) elif command == 'vmware-maintenancemode': return_results( generic_ansible('VMware', 'vmware_maintenancemode', args, int_params, host_type, creds_mapping)) elif command == 'vmware-migrate-vmk': return_results( generic_ansible('VMware', 'vmware_migrate_vmk', args, int_params, host_type, creds_mapping)) elif command == 'vmware-object-role-permission': return_results( generic_ansible('VMware', 'vmware_object_role_permission', args, int_params, host_type, creds_mapping)) elif command == 'vmware-portgroup': return_results( generic_ansible('VMware', 'vmware_portgroup', args, int_params, host_type, creds_mapping)) elif command == 'vmware-portgroup-info': return_results( generic_ansible('VMware', 'vmware_portgroup_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-resource-pool': return_results( generic_ansible('VMware', 'vmware_resource_pool', args, int_params, host_type, creds_mapping)) elif command == 'vmware-resource-pool-info': return_results( generic_ansible('VMware', 'vmware_resource_pool_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-tag': return_results( generic_ansible('VMware', 'vmware_tag', args, int_params, host_type, creds_mapping)) elif command == 'vmware-tag-info': return_results( generic_ansible('VMware', 'vmware_tag_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-tag-manager': return_results( generic_ansible('VMware', 'vmware_tag_manager', args, int_params, host_type, creds_mapping)) elif command == 'vmware-target-canonical-info': return_results( generic_ansible('VMware', 'vmware_target_canonical_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vcenter-settings': return_results( generic_ansible('VMware', 'vmware_vcenter_settings', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vcenter-statistics': return_results( generic_ansible('VMware', 'vmware_vcenter_statistics', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vm-host-drs-rule': return_results( generic_ansible('VMware', 'vmware_vm_host_drs_rule', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vm-info': return_results( generic_ansible('VMware', 'vmware_vm_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vm-shell': return_results( generic_ansible('VMware', 'vmware_vm_shell', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vm-storage-policy-info': return_results( generic_ansible('VMware', 'vmware_vm_storage_policy_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vm-vm-drs-rule': return_results( generic_ansible('VMware', 'vmware_vm_vm_drs_rule', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vm-vss-dvs-migrate': return_results( generic_ansible('VMware', 'vmware_vm_vss_dvs_migrate', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vmkernel': return_results( generic_ansible('VMware', 'vmware_vmkernel', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vmkernel-info': return_results( generic_ansible('VMware', 'vmware_vmkernel_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vmkernel-ip-config': return_results( generic_ansible('VMware', 'vmware_vmkernel_ip_config', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vmotion': return_results( generic_ansible('VMware', 'vmware_vmotion', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vsan-cluster': return_results( generic_ansible('VMware', 'vmware_vsan_cluster', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vspan-session': return_results( generic_ansible('VMware', 'vmware_vspan_session', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vswitch': return_results( generic_ansible('VMware', 'vmware_vswitch', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vswitch-info': return_results( generic_ansible('VMware', 'vmware_vswitch_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vsphere-file': return_results( generic_ansible('VMware', 'vsphere_file', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vcenter-extension': return_results( generic_ansible('VMware', 'vcenter_extension', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vcenter-extension-info': return_results( generic_ansible('VMware', 'vcenter_extension_info', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vcenter-folder': return_results( generic_ansible('VMware', 'vcenter_folder', args, int_params, host_type, creds_mapping)) elif command == 'vmware-vcenter-license': return_results( generic_ansible('VMware', 'vcenter_license', args, int_params, host_type, creds_mapping)) # Log exceptions and return errors except Exception as e: demisto.error(traceback.format_exc()) # print the traceback return_error(f'Failed to execute {command} command.\nError:\n{str(e)}')
def issue_upload_command(issue_id, upload): j_res = upload_file(upload, issue_id) md = generate_md_upload_issue(j_res, issue_id) human_readable = tableToMarkdown(demisto.command(), md, "") contents = j_res return_outputs(readable_output=human_readable, outputs={}, raw_response=contents)
else: raise else: service = client.connect( host=demisto.params()['host'], port=demisto.params()['port'], username=demisto.params()['authentication']['identifier'], password=demisto.params()['authentication']['password'], verify=VERIFY_CERTIFICATE) if service is None: demisto.error("Could not connect to SplunkPy") sys.exit(0) # The command demisto.command() holds the command sent from the user. if demisto.command() == 'test-module': # for app in service.apps: # print app.name if len(service.jobs) >= 0: demisto.results('ok') sys.exit(0) if demisto.command() == 'splunk-search': t = datetime.utcnow() - timedelta(days=7) time_str = t.strftime(SPLUNK_TIME_FORMAT) kwargs_oneshot = {"earliest_time": time_str} # type: Dict[str,Any] if demisto.get(demisto.args(), 'earliest_time'): kwargs_oneshot['earliest_time'] = demisto.args()['earliest_time'] if demisto.get(demisto.args(), 'latest_time'): kwargs_oneshot['latest_time'] = demisto.args()['latest_time'] if demisto.get(demisto.args(), 'event_limit'): kwargs_oneshot['count'] = int(demisto.args()['event_limit'])
# Create some basic demisto-related tags to attach to file details on initial upload data = { 'tag_list': entry_id + ',' + str(date.today()) + ',' + 'demisto' + ',' + incident_name } upload = http_post('project/default/malware/upload/', None, data=data, files=files) return upload ''' COMMANDS MANAGER / SWITCH PANEL ''' LOG('Command being called is %s' % (demisto.command())) try: if demisto.command() == 'test-module': # This is the call made when pressing the integration test button. test_module() elif demisto.command() == 'file': # Collect SHA56 hash from demisto details hash_value = demisto.args().get('file') hash_type = get_hash_type(hash_value) # Check if hash is SHA256 - Viper API only supports SHA256 if hash_type.lower() != 'sha256': error = True else: error = False
context = createContext(results, keyTransform=string_to_context_key) demisto.results({ 'Type': entryTypes['note'], 'ContentsFormat': formats['text'], 'Contents': results, 'EntryContext': { 'AutoFocus.TopTagsResults(val.PublicTagName == obj.PublicTagName)': context }, 'HumanReadable': md }) ''' COMMANDS MANAGER / SWITCH PANEL ''' LOG('Command being called is %s' % (demisto.command())) try: # Remove proxy if not set to true in params handle_proxy() active_command = demisto.command() if active_command == 'test-module': # This is the call made when pressing the integration test button. test_module() demisto.results('ok') elif active_command == 'autofocus-search-samples': search_samples_command() elif active_command == 'autofocus-search-sessions': search_sessions_command() elif active_command == 'autofocus-samples-search-results': samples_search_results_command()
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)) LOG('Executing command ' + demisto.command()) raise_exception = False try: if demisto.command() == 'test-module': test_module() demisto.results('ok') elif demisto.command() == 'fetch-incidents': raise_exception = True fetch_incidents() elif demisto.command() == 'servicenow-get' or \ demisto.command() == 'servicenow-incident-update' or demisto.command() == 'servicenow-get-ticket': demisto.results(get_ticket_command()) elif demisto.command() == 'servicenow-update' or \ demisto.command() == 'servicenow-incident-update' or demisto.command() == 'servicenow-update-ticket': demisto.results(update_ticket_command()) elif demisto.command() == 'servicenow-create' or \
'Bigfix.QueryResults': output } }) try: # do requets to /api/help # should be good indicator for test connectivity def test(): fullurl = BASE_URL + '/api/help' res = requests.get(fullurl, auth=(USERNAME, PASSWORD), verify=VERIFY_CERTIFICATE) res.raise_for_status() if demisto.command() == 'test-module': # do requets to /api/help # should be good indicator for test connectivity test() demisto.results('ok') elif demisto.command() == 'bigfix-get-sites': get_sites_command() elif demisto.command() == 'bigfix-get-site': get_site_command() elif demisto.command() == 'bigfix-get-endpoints': get_endpoints_command() elif demisto.command() == 'bigfix-get-endpoint':
def main(): """main function, parses params and runs command functions :return: :rtype: """ handle_proxy() params = demisto.params() username = params.get('username') apikey = params.get('apikey') base_url = params.get('url').rstrip('/') proxy = params.get('proxy', False) verify_certificate = not params.get('insecure', False) first_fetch_param = params.get('first_fetch') if params.get( 'first_fetch') else '1 day' first_fetch_dt = dateparser.parse(first_fetch_param, settings={'TIMEZONE': 'UTC'}) if first_fetch_param and not first_fetch_dt: return_error( f"First fetch input '{first_fetch_param}' is invalid. Valid format eg.:1 day" ) first_fetch = first_fetch_dt.timestamp() max_fetch = params.get('max_fetch') max_fetch = int( params.get('max_fetch')) if (max_fetch and max_fetch.isdigit()) else 50 max_fetch = max(min(200, max_fetch), 1) headers = {'Content-Type': 'application/json'} demisto.debug(f"Command being called is {demisto.command()}") try: client = Client(base_url=base_url, verify=verify_certificate, headers=headers, proxy=proxy, username=username, apikey=apikey) args = demisto.args() if demisto.command() == 'test-module': return_results(test_module(client, params.get('max_fetch'))) elif demisto.command() == 'lp-get-incidents': return_results(get_incidents_command(client, args)) elif demisto.command() == 'lp-get-incident-data': return_results(get_incident_data_command(client, args)) elif demisto.command() == 'lp-get-incident-states': return_results(get_incident_states_command(client, args)) elif demisto.command() == 'lp-add-incident-comment': return_results(add_incident_comment_command(client, args)) elif demisto.command() == 'lp-assign-incidents': return_results(assign_incidents_command(client, args)) elif demisto.command() == 'lp-resolve-incidents': return_results(resolve_incidents_command(client, args)) elif demisto.command() == 'lp-close-incidents': return_results(close_incidents_command(client, args)) elif demisto.command() == 'lp-reopen-incidents': return_results(reopen_incidents_command(client, args)) elif demisto.command() == 'lp-get-users': return_results(get_users_command(client)) elif demisto.command() == 'fetch-incidents': demisto.incidents(fetch_incidents(client, first_fetch, max_fetch)) except Exception as err: demisto.error(traceback.format_exc()) # print the traceback return_error( f"Failed to execute {demisto.command()} command. Error: {str(err)}" )
credentials.append({ 'user': account_name, 'password': password, 'name': system_name }) if identifier: credentials = list( filter(lambda c: c.get('name', '') == identifier, credentials)) demisto.credentials(credentials) ''' COMMANDS MANAGER / SWITCH PANEL ''' LOG('Command being called is %s' % (demisto.command())) try: handle_proxy() signin() if demisto.command() == 'test-module': # This is the call made when pressing the integration test button. get_managed_accounts_request() demisto.results('ok') elif demisto.command() == 'beyondtrust-get-managed-accounts': get_managed_accounts() elif demisto.command() == 'beyondtrust-get-managed-systems': get_managed_systems() elif demisto.command() == 'beyondtrust-create-release-request': create_release() elif demisto.command() == 'beyondtrust-get-credentials':
'rawJSON': json.dumps(item), } latest = max(latest, incident_date) incidents.append(incident) if latest != last_fetch: last_fetch = (latest + timedelta(seconds=1)).strftime('%Y-%m-%dT%H:%M:%S') demisto.setLastRun({'time': last_fetch}) demisto.incidents(incidents) ''' COMMANDS MANAGER / SWITCH PANEL ''' try: handle_proxy() command = demisto.command() LOG('Command being called is {}'.format(command)) login() if command == 'test-module': test_integration() elif command == 'fetch-incidents': fetch_incidents() elif command == 'fidelis-get-alert': get_alert_command() elif command == 'fidelis-delete-alert': delete_alert_command() elif command == 'fidelis-get-malware-data': get_malware_data_command()
def main(): """ PARSE AND VALIDATE INTEGRATION PARAMS """ key = demisto.params().get("credentials").get("identifier") token = demisto.params().get('credentials').get("password") # get the service API url base_url = urljoin(demisto.params()['url'], '/1') verify_certificate = not demisto.params().get('insecure', False) proxy = demisto.params().get('proxy', False) LOG(f'Command being called is {demisto.command()}') try: client = Client(key, token, base_url=base_url, verify=verify_certificate, proxy=proxy) if demisto.command() == 'test-module': return_results(test_module(client)) elif demisto.command() == 'fetch-incidents': board_id = get_board_id() # If the list is specified, we only fetch incidents belonging to that list (by ID) list_id = demisto.params().get("list_id") # Set and define the fetch incidents command to run after activated via integration settings. next_run, incidents = fetch_incidents( client=client, last_run=demisto.getLastRun(), board_id=board_id, list_id_filter=list_id) demisto.setLastRun(next_run) demisto.incidents(incidents) elif demisto.command() == 'trello-list-boards': return_results(list_boards(client)) elif demisto.command() == 'trello-list-lists': board_id = get_board_id() return_results(list_lists(client, board_id)) elif demisto.command() == 'trello-list-labels': board_id = get_board_id() return_results(list_labels(client, board_id)) elif demisto.command() == 'trello-create-label': board_id = get_board_id() return_results(create_label(client, board_id, demisto.args())) elif demisto.command() == 'trello-list-actions': board_id = get_board_id() filter_str = demisto.args().get("filter", None) since = demisto.args().get("since", None) before = demisto.args().get("before", None) return_results( list_actions(client, board_id, filter_str, since, before)) elif demisto.command() == 'trello-create-card': list_id = demisto.args().get("list_id") return_results(create_card(client, list_id, demisto.args())) elif demisto.command() == 'trello-list-cards': list_id = demisto.args().get("list_id") return_results(list_cards(client, list_id)) elif demisto.command() == 'trello-update-card': card_id = demisto.args().get("card_id") return_results(update_card(client, card_id, demisto.args())) elif demisto.command() == 'trello-add-comment': card_id = demisto.args().get("card_id") return_results(add_comment(client, card_id, demisto.args())) elif demisto.command() == 'trello-delete-card': card_id = demisto.args().get("card_id") return_results(delete_card(client, card_id)) elif demisto.command() == 'trello-get-mapping-fields': demisto.results(get_mapping_fields()) elif demisto.command() == 'trello-get-remote-data': demisto.results(get_remote_data(client, demisto.args())) # Log exceptions except Exception as e: return_error( f'Failed to execute {demisto.command()} command. Error: {str(e)}')
def list_tenants_request(): """ Get devices from Symantec MC :return: List of Symantec MC tenants """ path = 'tenants' params: dict = {} response = http_request('GET', path, params) return response ''' COMMANDS ''' LOG('Command being called is ' + demisto.command()) handle_proxy() COMMAND_DICTIONARY = { 'test-module': test_module, 'symantec-mc-list-devices': list_devices_command, 'symantec-mc-get-device': get_device_command, 'symantec-mc-get-device-health': get_device_health_command, 'symantec-mc-get-device-license': get_device_license_command, 'symantec-mc-get-device-status': get_device_status_command, 'symantec-mc-list-policies': list_policies_command, 'symantec-mc-get-policy': get_policy_command, 'symantec-mc-create-policy': create_policy_command, 'symantec-mc-update-policy': update_policy_command, 'symantec-mc-delete-policy': delete_policy_command, 'symantec-mc-add-policy-content': add_policy_content_command,
def main() -> None: """Main method used to run actions.""" try: demisto_params = demisto.params() demisto_args = demisto.args() base_url = demisto_params.get("server_url", "").rstrip("/") verify_ssl = not demisto_params.get("unsecure", False) proxy = demisto_params.get("proxy", False) # Clean the input from the user and split string domains = (demisto_params.get("domains", "").rstrip(";").replace(" ", "").split(";")) # If user has not set password properties we will get empty string but client require empty list password_properties = demisto_params.get("password_properties") or [] try: limit_identities = int( demisto_params.get("limit_identities", LIMIT_IDENTITIES)) # We can't do that on UI, so set the limit here. if limit_identities > LIMIT_IDENTITIES: limit_identities = LIMIT_IDENTITIES except ValueError: limit_identities = LIMIT_IDENTITIES headers = { "X-RFToken": demisto_params["token"], "X-RF-User-Agent": f"xsoar-identity/{__version__} rfclient (Cortex_XSOAR_" f'{demisto.demistoVersion()["version"]})', } client = Client( base_url=base_url, verify=verify_ssl, headers=headers, proxy=proxy, ) command = demisto.command() actions = Actions(client) if command == "test-module": try: client.whoami() return_results("ok") except Exception as err: message = str(err) try: error = json.loads(str(err).split("\n")[1]) if "fail" in error.get("result", {}).get("status", ""): message = error.get("result", {})["message"] except Exception: message = ( "Unknown error. Please verify that the API" f" URL and Token are correctly configured. RAW Error: {err}" ) raise DemistoException(f"Failed due to - {message}") elif command == "recordedfuture-identity-search": return_results( actions.identity_search_command( domains, demisto_args.get("latest-downloaded", ""), demisto_args.get("domain-type"), password_properties, limit_identities, )) elif command == "recordedfuture-identity-lookup": return_results( actions.identity_lookup_command( demisto_args.get("identities"), demisto_args.get("first-downloaded", ""), password_properties, domains, )) except Exception as e: return_error(f"Failed to execute {demisto.command()} command. " f"Error: {str(e)}")