def main(): fields_mapping = {} for xdr_field in XDR_INCIDENT_FIELDS: if xdr_field in demisto.args() and demisto.args().get( xdr_field) is not None: custom_field_in_demisto = demisto.args().get(xdr_field) fields_mapping[xdr_field] = custom_field_in_demisto playbook_to_run = demisto.args().get('playbook_to_run') incident_id = demisto.args().get('incident_id') first_run = demisto.args().get('first') == 'true' interval = int(demisto.args().get('interval')) xdr_incident_from_previous_run = demisto.args().get( 'xdr_incident_from_previous_run') xdr_alerts_field = demisto.args().get('xdr_alerts') xdr_file_artifacts_field = demisto.args().get('xdr_file_artifacts') xdr_network_artifacts_field = demisto.args().get('xdr_network_artifacts') verbose = demisto.args().get('verbose') == 'true' xdr_incident_markdown_field = demisto.args().get( 'xdr_incident_markdown_field') # deprecated if xdr_incident_markdown_field: # deprecated field raise ValueError( 'Deprecated xdr_incident_markdown_field argument, instead use xdr_alerts, xdr_file_artifacts, ' 'xdr_network_artifacts. For more information follow Demisto documentation.' ) previous_scheduled_task_id = demisto.get(demisto.context(), 'XDRSyncScriptTaskID') if first_run and previous_scheduled_task_id: if verbose: demisto.debug( 'Stopping previous scheduled task with ID: {}'.format( previous_scheduled_task_id)) demisto.executeCommand('StopScheduledTask', {'taskID': previous_scheduled_task_id}) demisto.setContext('XDRSyncScriptTaskID', '') xdr_incident_sync(incident_id, fields_mapping, playbook_to_run, xdr_incident_from_previous_run, first_run, interval, xdr_alerts_field, xdr_file_artifacts_field, xdr_network_artifacts_field, verbose)
def main(): entry_ids = demisto.get(demisto.args(), 'entryid') if entry_ids: if isinstance(entry_ids, STRING_TYPES): # playbook inputs may be in the form: [\"23@2\",\"24@2\"] if passed as a string and not array entry_ids = entry_ids.strip().replace(r'\"', '"') entry_ids = argToList(entry_ids) entries = [] # type: List[str] for ent_id in entry_ids: res = demisto.executeCommand('getEntry', {'id': ent_id}) entries.extend(res) else: entries = demisto.executeCommand('getEntries', {}) for e in entries: id = is_entry_email(e) if id: # we use setContext so server can detect the additional context path used beyond the condition values demisto.setContext('reportedemailentryid', id) demisto.results('yes') return demisto.results('no')
def main(args: Dict): data = args.get('data') raw_regex = args.get('regex', '') group = int(args.get('group', '0')) context_key = args.get('contextKey', '') flags, multiple_matches = parse_regex_flags(args.get('flags', 'gim')) regex = re.compile(raw_regex, flags=flags) # in case group is out of range, fallback to all matching string if group > regex.groups: group = 0 results = [] if multiple_matches: regex_result = regex.search(data) while regex_result: results.append(regex_result.group(group)) regex_result = regex.search(data, regex_result.span()[1]) else: regex_result = regex.search(data) if regex_result: results = regex_result.group(group) results = results[0] if len(results) == 1 else results if results: human_readable = json.dumps(results) else: human_readable = 'Regex does not match.' context = {} if context_key: context = {context_key: results} # clearing the context field in order to override it instead of appending it. demisto.setContext('MatchRegex.results', results) return CommandResults(readable_output=human_readable, outputs=context, raw_response=results, )
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 import json JSON_CONTEXT_KEY = "JsonObject" json_str = demisto.args()['input'] demisto.debug(json_str) obj = json.loads(json_str) if "_source" in obj: new_obj = obj["_source"] obj = new_obj objStr = json.dumps(obj) demisto.setContext(JSON_CONTEXT_KEY, objStr) demisto.results(objStr)
def main(args): fields_mapping = {} for xdr_field in XDR_INCIDENT_FIELDS: if xdr_field in args and args.get(xdr_field) is not None: custom_field_in_demisto = args.get(xdr_field) fields_mapping[xdr_field] = custom_field_in_demisto incident_id = args.get('incident_id') first_run = args.get('first') == 'true' interval = int(args.get('interval')) xdr_incident_from_previous_run = args.get('xdr_incident_from_previous_run') xdr_alerts_field = args.get('xdr_alerts') xdr_file_artifacts_field = args.get('xdr_file_artifacts') xdr_network_artifacts_field = args.get('xdr_network_artifacts') verbose = args.get('verbose') == 'true' # get current running incident incident_in_demisto = demisto.incidents()[0] if not incident_in_demisto: raise ValueError("Error - demisto.incidents()[0] expected to return current incident " "from context but returned None") xdr_incident_markdown_field = args.get('xdr_incident_markdown_field') # deprecated if xdr_incident_markdown_field: # deprecated field return_error('Deprecated xdr_incident_markdown_field argument, instead use xdr_alerts, xdr_file_artifacts, ' 'xdr_network_artifacts. For more information follow Demisto documentation.', None) latest_incident_in_xdr = None previous_scheduled_task_id = demisto.get(demisto.context(), 'XDRSyncScriptTaskID') if first_run and previous_scheduled_task_id: # it means someone rerun the playbook, so we stop the previous scheduled task and set the task ID to be empty. if verbose: demisto.debug('Stopping previous scheduled task with ID: {}'.format(previous_scheduled_task_id)) demisto.executeCommand('StopScheduledTask', {'taskID': previous_scheduled_task_id}) demisto.setContext('XDRSyncScriptTaskID', '') try: latest_incident_in_xdr = xdr_incident_sync(incident_id, fields_mapping, xdr_incident_from_previous_run, first_run, xdr_alerts_field, xdr_file_artifacts_field, xdr_network_artifacts_field, incident_in_demisto, verbose) except Exception as ex: return_error(str(ex), ex) finally: # even if error occurred keep trigger sync if latest_incident_in_xdr is None: args = args_to_str(args, xdr_incident_from_previous_run) else: args = args_to_str(args, latest_incident_in_xdr) res = demisto.executeCommand("ScheduleCommand", { 'command': '''!XDRSyncScript {}'''.format(args), 'cron': '*/{} * * * *'.format(interval), 'times': 1 }) if is_error(res): # return the error entries to warroom demisto.results(res) return scheduled_task_id = res[0]["Contents"].get("id") demisto.setContext("XDRSyncScriptTaskID", scheduled_task_id) if verbose: demisto.results("XDRSyncScriptTaskID: {}".format(scheduled_task_id))
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 brandName = "Demisto REST API" instanceName = demisto.args().get('instanceName') allInstances = demisto.getModules() brandInstances = [ instanceName for instanceName in allInstances if allInstances[instanceName]['brand'].lower() == brandName.lower() and demisto.get(allInstances[instanceName], 'state') and allInstances[instanceName]['state'] == 'active' ] if brandInstances and instanceName in brandInstances: instance = allInstances.get(instanceName) instance['name'] = instanceName demisto.setContext('DemsistoAPIInstances', instance) demisto.results('yes') else: demisto.results('no')
break elif (context_since is not None) and (log_until is None): log_until = re.findall( '(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})', line) if not log_until: continue newestDate = log_until[0] newestDate = findNewestDate(log_until[0], context_log_until) break else: oldestDate = context_since newestDate = context_log_until break demisto.setContext("LogServer.since", str(oldestDate)) demisto.setContext("LogServer.logUntil", str(newestDate)) demisto.setContext("LogServer.restartCount", restartcount) demisto.executeCommand( "setIncident", { "healthcheckrestartcount": restartcount, "healthchecklogsince": str(oldestDate), "healthcheckloguntil": str(newestDate) }) if suggestions: for entry in suggestions: res.append({ "category": "Log Analysis", "severity": "High", "description": entry[0],
def xdr_incident_sync(incident_id, fields_mapping, playbook_name_to_run, xdr_incident_from_previous_run, first_run, interval, xdr_alerts_field, xdr_file_artifacts_field, xdr_network_artifacts_field, verbose=True): latest_incident_in_xdr_result, latest_incident_in_xdr, latest_incident_in_xdr_markdown = \ get_latest_incident_from_xdr(incident_id) if first_run: xdr_incident_from_previous_run = latest_incident_in_xdr else: if xdr_incident_from_previous_run: xdr_incident_from_previous_run = json.loads( xdr_incident_from_previous_run) else: raise ValueError( "xdr_incident_from_previous_run expected to contain incident JSON, but passed None" ) # get the incident from demisto incident_in_demisto = demisto.incidents()[0] if not incident_in_demisto: return_error( "Error - demisto.incidents()[0] expected to return current incident " "from context but returned None") return incident_in_demisto_was_modified, xdr_update_args = compare_incident_in_demisto_vs_xdr_context( incident_in_demisto, xdr_incident_from_previous_run, incident_id, fields_mapping) if incident_in_demisto_was_modified: # update xdr and finish the script demisto.debug( "the incident in demisto was modified, updating the incident in xdr accordingly. " ) demisto.debug("xdr_update_args: {}".format( json.dumps(xdr_update_args, indent=4))) res = demisto.executeCommand("xdr-update-incident", xdr_update_args) if is_error(res): raise ValueError(get_error(res)) latest_incident_in_xdr_result, latest_incident_in_xdr, latest_incident_in_xdr_markdown = \ get_latest_incident_from_xdr(incident_id) xdr_incident = latest_incident_in_xdr_result[0]['Contents'] update_incident = dict() update_incident[xdr_alerts_field] = replace_in_keys( xdr_incident.get('alerts').get('data', []), '_', '') update_incident[xdr_file_artifacts_field] = replace_in_keys( xdr_incident.get('file_artifacts').get('data', []), '_', '') update_incident[xdr_network_artifacts_field] = replace_in_keys( xdr_incident.get('network_artifacts').get('data', []), '_', '') res = demisto.executeCommand("setIncident", update_incident) if is_error(res): raise ValueError(get_error(res)) # update the context with latest incident from xdr demisto.results(latest_incident_in_xdr_result) args = args_to_str(demisto.args(), latest_incident_in_xdr) res = demisto.executeCommand( "ScheduleCommand", { 'command': '''!XDRSyncScript {}'''.format(args), 'cron': '*/{} * * * *'.format(interval), 'times': 1 }) if is_error(res): raise Exception(get_error(res)) scheduled_task_id = res[0]["Contents"].get("id") demisto.setContext("XDRSyncScriptTaskID", scheduled_task_id) if verbose: demisto.results( "XDRSyncScriptTaskID: {}".format(scheduled_task_id)) return_outputs( "Incident in Demisto was modified, updating incident in XDR accordingly.\n\n{}" .format(xdr_update_args), None) return incident_in_xdr_was_modified, demisto_update_args = compare_incident_in_xdr_vs_previous_xdr_in_context( latest_incident_in_xdr, xdr_incident_from_previous_run, fields_mapping) if incident_in_xdr_was_modified: demisto.debug( "the incident in xdr was modified, updating the incident in demisto" ) demisto.debug("demisto_update_args: {}".format( json.dumps(demisto_update_args, indent=4))) xdr_incident = latest_incident_in_xdr_result[0]['Contents'] update_incident = dict() update_incident[xdr_alerts_field] = replace_in_keys( xdr_incident.get('alerts').get('data', []), '_', '') update_incident[xdr_file_artifacts_field] = replace_in_keys( xdr_incident.get('file_artifacts').get('data', []), '_', '') update_incident[xdr_network_artifacts_field] = replace_in_keys( xdr_incident.get('network_artifacts').get('data', []), '_', '') res = demisto.executeCommand("setIncident", update_incident) if is_error(res): raise ValueError(get_error(res)) demisto.results(latest_incident_in_xdr_result) if verbose: return_outputs( "Incident in XDR was modified, updating incident in Demisto accordingly.\n\n{}" .format(demisto_update_args), None) # rerun the playbook demisto.executeCommand("setPlaybook", {"name": playbook_name_to_run}) return if first_run: demisto.results(latest_incident_in_xdr_result) # set the incident markdown field # update_incident_markdown_field = dict() # update_incident_markdown_field[xdr_incident_markdown_field] = latest_incident_in_xdr_markdown xdr_incident = latest_incident_in_xdr_result[0]['Contents'] update_incident = dict() update_incident[xdr_alerts_field] = replace_in_keys( xdr_incident.get('alerts').get('data', []), '_', '') update_incident[xdr_file_artifacts_field] = replace_in_keys( xdr_incident.get('file_artifacts').get('data', []), '_', '') update_incident[xdr_network_artifacts_field] = replace_in_keys( xdr_incident.get('network_artifacts').get('data', []), '_', '') demisto.results(update_incident) res = demisto.executeCommand("setIncident", update_incident) if is_error(res): raise ValueError(get_error(res)) args = args_to_str(demisto.args(), latest_incident_in_xdr) res = demisto.executeCommand( "ScheduleCommand", { 'command': '''!XDRSyncScript {}'''.format(args), 'cron': '*/{} * * * *'.format(interval), 'times': 1 }) scheduled_task_id = res[0]["Contents"].get("id") demisto.setContext("XDRSyncScriptTaskID", scheduled_task_id) if verbose: demisto.results("XDRSyncScriptTaskID: {}".format(scheduled_task_id)) return_outputs("Nothing to sync.", None)
def main(): res = [] tbl = [] devices = demisto.get(demisto.args(), 'devices') devicesBackupStarted = [] devicesBackupError = [] if not devices: res.append({ "Type": entryTypes["error"], "ContentsFormat": formats["text"], "Contents": "Received empty device list!" }) else: devices = ','.join(devices) if isinstance(devices, list) else devices sshArgs = {"using": devices, "cmd": BASH_ADD} resSSH = demisto.executeCommand("ssh", sshArgs) try: for entry in resSSH: if isError(entry) and not demisto.get(entry, 'Contents.command'): res += resSSH break else: device = entry['ModuleName'] if demisto.get(entry, 'Contents.success'): output = demisto.get(entry, 'Contents.output') backFileLoc = output.find("Backup file location") result = 'Answer returned' devicesBackupStarted.append({ 'DeviceName': device, 'System': demisto.get(entry, 'Contents.system'), 'Status': ("Done" if output.find("local backup succeeded.") > -1 else "Pending"), 'Path': (output[backFileLoc, :] if backFileLoc > -1 else None) }) else: devicesBackupError.append(device) output = "Output:\n" + str(demisto.get(entry, 'Contents.output')) + \ "Error:\n" + str(demisto.get(entry, 'Contents.error')) result = 'Failed to query' tbl.append({ 'DeviceName': device, 'System': demisto.get(entry, 'Contents.system'), 'Query result': result, 'Output': output }) except Exception as ex: res.append({ "Type": entryTypes["error"], "ContentsFormat": formats["text"], "Contents": "Error occurred while parsing output from command. " "Exception info:\n" + str(ex) + "\n\nInvalid output:\n" + str(resSSH) }) demisto.setContext('CheckpointBackup', devicesBackupStarted) res.append({ "Type": entryTypes["note"], "ContentsFormat": formats["table"], "Contents": tbl }) demisto.results(res)