Common Server Python
Common functions that will be appended to the code of each integration/script before being executed.
AutoFocusKeyRetriever#
AutoFocus API Key management class
Arguments:
api_keystr: Auto Focus API key coming from the integration parametersoverride_default_credentialsbool: Whether to override the default credentials and use the Cortex XSOAR given AutoFocus API Key
BarColumnPieWidget#
Bar/Column/Pie Widget representation
Arguments:
categorieslist: a list of categories to display(Better use the add_category function to populate the data.
add_category#
Add a category to widget.
Arguments:
namestr: the name of the category to add.numberint: the number value of the category.
to_display#
CommandResults#
CommandResults class - use to return results to warroom
Arguments:
outputs_prefixstr: should be identical to the prefix in the yml contextPath in yml file. for example: CortexXDR.Incidentoutputs_key_fieldstr or list[str]: primary key field in the main object. If the command returns Incidents, and of the properties of Incident is incident_id, then outputs_key_field='incident_id'. If object has multiple unique keys, then list of strings is supported outputs_key_field=['id1', 'id2']outputslist or dict: the data to be returned and will be set to contextindicatorslist: DEPRECATED: use 'indicator' instead.indicatorCommon.Indicator: single indicator like Common.IP, Common.URL, Common.File, etc.readable_outputstr: (Optional) markdown string that will be presented in the warroom, should be human readable - (HumanReadable) - if not set, readable output will be generatedraw_responsedict | list: must be dictionary, if not provided then will be equal to outputs. usually must be the original raw response from the 3rd party service (originally Contents)indicators_timelineIndicatorsTimeline: must be an IndicatorsTimeline. used by the server to populate an indicator's timeline.ignore_auto_extractbool: must be a boolean, default value is False. Used to prevent AutoExtract on output.relationshipslist of EntityRelationship: List of relationships of the indicator.mark_as_notebool: must be a boolean, default value is False. Used to mark entry as note.tagslist: must be a list, default value is None. Used to tag war room entries.entry_typeint code of EntryType: type of return value, see EntryTypescheduled_commandScheduledCommand: manages the way the command should be polled.extended_payloaddict: (Optional) A dictionary representing the contents of ExtendedPayload for synchronization.execution_metricsExecutionMetrics: contains metric data about a command's executionreplace_existingbool: Replace the context value at outputs_prefix if it exists. Works only if outputs_prefix is a path to a nested value i.e., contains a period. For example, the "next token" result should always be overwritten. This response can be returned as follows:
Examples:
to_context#
CommandRunner#
Class for executing multiple commands and save the results of each command.
Command#
Data class with the data required to execute a command.
Arguments:
commands__: The commands list or a single commandargs_lststr + List[str]: The args list or a single argsbrandList[Dict] + Dict: The brand to useinstancestr: The instance to use
_is_valid#
Error handling of the given arguments
Arguments:
commands__: list of commandsargs_lst__: list of args
Result#
Class for the result of the command.
Arguments:
command__: command that was run. :type commandstrargs__: args that was run.branddict: The brand that was used.instancestr: The instance that was used.resultstr: The result of the command.
execute_commands#
Runs the demisto.executeCommand() and gets all the results, including the errors, returned from the command.
Arguments:
commandCommand: The commands to run. (required)extract_contentsbool: Whether to extract Contents part of the results. Default is True.
Returns:
Tuple[List[ResultWrapper], List[ResultWrapper]]- A tuple of two lists: the command results list and command errors list.
run_commands_with_summary#
Given a list of commands, return a list of results (to pass to return_results).
In addition, it will create a CommandResult of the summary of the commands, which is a readable_output.
Arguments:
commands__: A list of commands.
get_results_summary#
Get a Human Readable result for all the results of the commands.
Arguments:
results__: list of returned resultserrors__: list of returned errors
ConfKey#
YML configuration key fields.
This is an empty class, used for code autocompletion when using demisto-sdk generate_yml_from_python command syntax. For more information, visit the command's README.md.
Returns:
ConfKey- The ConfKey object
DBotScoreReliability#
Enum: Source reliability levels Values are case sensitive
A_PLUS_PLUS
A_PLUS
A
B
C
D
E
F
is_valid_type#
get_dbot_score_reliability_from_str#
DBotScoreType#
Enum: contains all the indicator types DBotScoreType.IP DBotScoreType.FILE DBotScoreType.DOMAIN DBotScoreType.URL DBotScoreType.CVE DBotScoreType.ACCOUNT DBotScoreType.CRYPTOCURRENCY DBotScoreType.EMAIL DBotScoreType.ATTACKPATTERN DBotScoreType.CUSTOM
IP
FILE
DOMAIN
URL
CVE
ACCOUNT
CIDR
DOMAINGLOB
CERTIFICATE
CRYPTOCURRENCY
EMAIL
ATTACKPATTERN
CUSTOM
is_valid_type#
DebugLogger#
Wrapper to initiate logging at logging.DEBUG level.
Is used when debug-mode=True.
__del__#
log_start_debug#
Utility function to log start of debug mode logging
DemistoHandler#
Handler to route logging messages to an IntegrationLogger or demisto.debug if not supplied
emit#
EntityRelationship#
XSOAR entity relationship.
Arguments:
namestr: Relationship name.relationship_typestr: Relationship type. (e.g. IndicatorToIndicator...).entity_astr: A value, A aka source of the relationship.entity_a_familystr: Entity family of A, A aka source of the relationship. (e.g. Indicator...)entity_a_typestr: Entity A type, A aka source of the relationship. (e.g. IP/URL/...).entity_bstr: B value, B aka destination of the relationship.entity_b_familystr: Entity family of B, B aka destination of the relationship. (e.g. Indicator...)entity_b_typestr: Entity B type, B aka destination of the relationship. (e.g. IP/URL/...).source_reliabilitystr: Source reliability.fieldsdict: Custom fields. (Optional)brandstr: Source brand name. (Optional)
RelationshipsTypes#
Relationships Types objects.
RELATIONSHIP_TYPES#
is_valid_type#
RelationshipsFamily#
Relationships Family object list.
INDICATOR#
is_valid_type#
Relationships#
Enum: Relations names and their reverse
APPLIED
ATTACHMENT_OF
ATTACHES
ATTRIBUTE_OF
ATTRIBUTED_BY
ATTRIBUTED_TO
AUTHORED_BY
BEACONS_TO
BUNDLED_IN
BUNDLES
COMMUNICATED_WITH
COMMUNICATED_BY
COMMUNICATES_WITH
COMPROMISES
CONTAINS
CONTROLS
CREATED_BY
CREATES
DELIVERED_BY
DELIVERS
DETECTS
DETECTED_BY
DOWNLOADS
DOWNLOADS_FROM
DROPPED_BY
DROPS
DUPLICATE_OF
EMBEDDED_IN
EMBEDS
EXECUTED
EXECUTED_BY
EXFILTRATES_TO
EXPLOITS
HAS
HOSTED_ON
HOSTS
IMPERSONATES
INDICATED_BY
INDICATOR_OF
INJECTED_FROM
INJECTS_INTO
INVESTIGATES
IS_ALSO
LOCATED_AT
MITIGATED_BY
MITIGATES
ORIGINATED_FROM
OWNED_BY
OWNS
PART_OF
RELATED_TO
REMEDIATES
RESOLVED_BY
RESOLVED_FROM
RESOLVES_TO
SEEN_ON
SENT
SENT_BY
SENT_FROM
SENT_TO
SIMILAR_TO
SUB_DOMAIN_OF
SUB_TECHNIQUE_OF
PARENT_TECHNIQUE_OF
SUPRA_DOMAIN_OF
TARGETED_BY
TARGETS
TYPES
UPLOADED_TO
USED_BY
USED_ON
USES
VARIANT_OF
RELATIONSHIPS_NAMES
is_valid#
Arguments:
_typestr: the data to be returned and will be set to context
Returns:
bool- Is the given type supported
get_reverse#
Arguments:
namestr: Relationship name
Returns:
str- Returns the reversed relationship name
to_entry#
Convert object to XSOAR entry
Returns:
dict- XSOAR entry representation.
to_indicator#
Convert object to XSOAR entry
Returns:
dict- XSOAR entry representation.
to_context#
Convert object to XSOAR context
Returns:
dict- XSOAR context representation.
EntryFormat#
Enum: contains all the entry formats (e.g. HTML, TABLE, JSON, etc.)
HTML
TABLE
JSON
TEXT
DBOT_RESPONSE
MARKDOWN
is_valid_type#
EntryType#
Enum: contains all the entry types (e.g. NOTE, ERROR, WARNING, FILE, etc.)
NOTE
DOWNLOAD_AGENT
FILE
ERROR
PINNED
USER_MANAGEMENT
IMAGE
PLAYGROUND_ERROR
ENTRY_INFO_FILE
VIDEO_FILE
WARNING
STATIC_VIDEO_FILE
MAP_ENTRY_TYPE
DEBUG_MODE_FILE
WIDGET
EXECUTION_METRICS
ErrorTypes#
Enum: contains all the available error types
SUCCESS
QUOTA_ERROR
GENERAL_ERROR
AUTH_ERROR
SERVICE_ERROR
CONNECTION_ERROR
PROXY_ERROR
SSL_ERROR
TIMEOUT_ERROR
RETRY_ERROR
ExecutionMetrics#
ExecutionMetrics is used to collect and format metric data to be reported to the XSOAR server.
is_supported#
success#
success#
quota_error#
quota_error#
general_error#
general_error#
auth_error#
auth_error#
service_error#
service_error#
connection_error#
connection_error#
proxy_error#
proxy_error#
ssl_error#
ssl_error#
timeout_error#
timeout_error#
retry_error#
retry_error#
get_metric_list#
update_metrics#
ExecutionTimeout#
Context manager to limit the execution time of a code block.
Initializes the ExecutionTimeout context manager.
Arguments:
seconds__: The maximum execution time in seconds.
_timeout_handler#
Signal handler that raises a SignalTimeoutError.
Arguments:
signum__: The number of the signal received.frameint: The current stack frame.
__enter__#
Enters the context manager by setting up the signal handler for SIGALRM and starting the timer.
__exit__#
Exits the context manager by canceling the SIGALARM and
suppressing the SignalTimeoutError.
Arguments:
exc_type__: The type of the exception that occurred, if any.exc_val__: The instance of the exception that occurred, if any.exc_tb__: A traceback object showing where the exception occurred, if any.
Returns:
bool- True if theSignalTimeoutErrorwas raised and suppressed, False otherwise.
limit_time#
Decorator method to limit the execution time of a function.
Arguments:
seconds__: The maximum execution time in seconds.default_return_valueint or float: The value to return if the function times out.
Returns:
any- Any
FeedIndicatorType#
Type of Indicator (Reputations), used in TIM integrations
Account#
CVE#
Domain#
DomainGlob#
Email#
File#
FQDN#
Host#
IP#
CIDR#
IPv6#
IPv6CIDR#
Registry#
SSDeep#
URL#
AS#
MUTEX#
Malware#
Identity#
Location#
Software#
X509#
is_valid_type#
list_all_supported_indicators#
ip_to_indicator_type#
Returns the indicator type of the input IP.
Arguments:
ipstr: IP address to get it's indicator type.
Returns:
str- : Indicator type from FeedIndicatorType, or None if invalid IP address.
indicator_type_by_server_version#
Returns the indicator type of the input by the server version. If the server version is 6.2 and greater, remove the STIX prefix of the type
Arguments:
indicator_typestr: Type of an indicator.
Returns:
str- : Indicator type .
FileAttachmentType#
Enum: contains the file attachment types, Used to add metadata to the description of the attachment whether the file content is expected to be inline or attached as a file
Returns:
str- : The file attachment typeATTACHED
FormatADTimestamp#
Formats an Active Directory timestamp into human readable time representation
Arguments:
tsint: The timestamp to be formatted (required)
Returns:
str- A string represeting the time
FormatIso8601#
Convert a time expressed in seconds to ISO 8601 time format string
Arguments:
tint: Time expressed in seconds (required)
Returns:
str- An ISO 8601 time format string
GetDemistoVersion#
Callable class to replace get_demisto_version function
__call__#
Returns the Demisto version and build number.
Returns:
dict- Demisto version object if Demisto class has attribute demistoVersion, else raises AttributeError
GetMappingFieldsResponse#
Handler for the mapping fields object.
Arguments:
scheme_types_mappinglist: List of all the mappings in the remote system.
add_scheme_type#
Add another incident type mapping.
Arguments:
scheme_type_mappingdict: mapping of a singular field.
extract_mapping#
Extracts the mapping into XSOAR mapping screen.
Returns:
dict- the mapping object for the current field.
GetModifiedRemoteDataArgs#
get-modified-remote-data args parser
Arguments:
argsdict: arguments for the command.
GetModifiedRemoteDataResponse#
get-modified-remote-data response parser
Arguments:
modified_incident_idslist: The incidents that were modified since the last check.
to_entry#
Extracts the response
Returns:
list- List of incidents to run the get-remote-data command on.
GetRemoteDataArgs#
get-remote-data args parser
Arguments:
argsdict: arguments for the command.
GetRemoteDataResponse#
get-remote-data response parser
Arguments:
mirrored_objectdict: The object you are mirroring, in most cases the incident.entrieslist: The entries you want to add to the war room.
extract_for_local#
Extracts the response into the mirrored incident.
Returns:
list- List of details regarding the mirrored incident.
ISOEncoder#
A custom JSONEncoder that converts datetime objects to ISO 8601 strings.
Returns:
ISOEncoder- The ISOEncoder object
default#
IncidentSeverity#
Enum: contains all the incident severity types
UNKNOWN
INFO
LOW
MEDIUM
HIGH
CRITICAL
IncidentStatus#
Enum: contains all the incidents status types (e.g. pending, active, done, archive)
PENDING
ACTIVE
DONE
ARCHIVE
IndicatorsSearcher#
Used in order to search indicators by the paging or serachAfter param
Arguments:
pageint: the number of page from which we start search indicators from.filter_fieldsOptional[str]: comma separated fields to filter (e.g. "value,type")from_dateOptional[str]: the start date to search from.queryOptional[str]: indicator search queryto_dateOptional[str]: the end date to search until to.valuestr: the indicator value to search.limitOptional[int]: the current upper limit of the search (can be updated after init)sortList[Dict]: An array of sort params ordered by importance. Item structure: {"field": string, "asc": boolean}
SEARCH_AFTER_TITLE#
__iter__#
next#
__next__#
page#
total#
limit#
limit#
is_search_done#
Return True if one of these conditions is met (else False):
- self.limit is set, and it's updated to be less or equal to zero - return True
- for search_after if self.total was populated by a previous search, but no self._search_after_param
- for page if self.total was populated by a previous search, but page is too large
search_indicators_by_version#
There are 2 cases depends on the sever version:
- Search indicators using paging, raise the page number in each call.
- Search indicators using searchAfter param, update the _search_after_param in each call.
Arguments:
from_dateOptional[str]: the start date to search from.queryOptional[str]: indicator search querysizeint: limit the number of returned results.to_dateOptional[str]: the end date to search until to.valuestr: the indicator value to search.
Returns:
dict- object contains the search results
IndicatorsTimeline#
IndicatorsTimeline class - use to return Indicator Timeline object to be used in CommandResults
Arguments:
indicatorslist: expects a list of indicators.categorystr: indicator category.messagestr: indicator message.
InputArgument#
YML input argument for a command.
This is an empty class, used for code autocompletion when using demisto-sdk generate_yml_from_python command syntax. For more information, visit the command's README.md.
Returns:
InputArgument- The InputArgument object
IntegrationLogger#
a logger for python integrations:
use LOG(<message>) to add a record to the logger (message can be any object with str)
use LOG.print_log(verbose=True/False) to display all records in War-Room (if verbose) and server log.
use add_replace_strs to add sensitive strings that should be replaced before going to the log.
Arguments:
messagestr: The message to be logged
_iter_sensistive_dict_obj#
encode#
__call__#
add_replace_strs#
Add strings which will be replaced when logging. Meant for avoiding passwords and so forth in the log.
set_buffering#
set whether the logger buffers messages or writes staight to the demisto log
Arguments:
state__: True/False
print_log#
build_curl#
Parses the HTTP client "send" log messages and generates cURL queries out of them.
Arguments:
textstr: The HTTP client log message.
write#
print_override#
JsonTransformer#
A class to transform a json to
Arguments:
flattenbool: Should we flatten the json usingflattenCell(for BC)keysSet[str]: Set of keys to keepis_nestedbool: If look for nestedfuncCallable: A function to parse the json
Constructor for JsonTransformer
Arguments:
flattenbool: Should we flatten the json usingflattenCell(for BC)keysIterable[str]: an iterable of relevant keys list from the json. Notice we save it as a set in the classis_nestedbool: Whether to search in nested keys or notfuncCallable: A function to parse the json
json_to_str#
json_to_path_generator#
Arguments:
json_inputlist or dict: The json input to transformpathList[str + int]: The path of the key, value pair inside the json
:rtype Tuple[List[str + int], str, str]
LineWidget#
Line Widget representation
Arguments:
categoriesAny: a list of categories to display(Better use the add_category function to populate the data.
add_category#
Add a category to widget.
Arguments:
namestr: the name of the category to add.numberint: the number value of the category.groupstr: the name of the relevant group.
to_display#
MirrorObject#
A container class for storing ticket metadata used in mirroring integrations.
This class is intended to be populated by commands like !jira-create-issue
and placed directly into the root context under MirrorObject.
A container class for storing ticket metadata used in mirroring integrations.
This class is intended to be populated by commands like !jira-create-issue
and placed directly into the root context under MirrorObject.
Attributes:
object_url (Optional[str]): Direct URL to the created ticket for preview/use.
object_id (Optional[str]): Unique identifier of the created ticket.
to_context#
Converts the instance to a dictionary.
Returns:
dict- Dictionary representation of the MirrorObject instance.
NormalizeRegistryPath#
Normalizes a registry path string
Arguments:
strRegistryPathstr: The registry path (required)
Returns:
str- The normalized string
NumberWidget#
Number Widget representation
Arguments:
numberint: The number for the widget to display.
to_display#
OutputArgument#
YML output argument.
This is an empty class, used for code autocompletion when using demisto-sdk generate_yml_from_python command syntax. For more information, visit the command's README.md.
Returns:
OutputArgument- The OutputArgument object
ParameterTypes#
YML ConfKey key_type type.
This is an empty class, used for code autocompletion when using demisto-sdk generate_yml_from_python command syntax. For more information, visit the command's README.md.
Returns:
ParameterTypes- The ParameterTypes enum
STRING#
NUMBER#
ENCRYPTED#
BOOLEAN#
AUTH#
DOWNLOAD_LINK#
TEXT_AREA#
INCIDENT_TYPE#
TEXT_AREA_ENCRYPTED#
SINGLE_SELECT#
MULTI_SELECT#
PollResult#
The response object for polling functions. This object contains information about whether to run again, and what the CommandResults are in case of success, or failure.
Returns:
PollResult- PollResult
Constructor for PollResult
Arguments:
responseAny: The response of the command in the event of success, or in case of failure but Polling is falsecontinue_to_pollUnion[bool, Callable]: An iterable of relevant keys list from the json. Notice we save it as a set in the classargs_for_next_runDict: The arguments to use in the next iteration. Will use the input args in case of Nonepartial_resultCommandResults: CommandResults to return, even though we will poll again
PrettifyCompactedTimestamp#
Formats a compacted timestamp string into human readable time representation
Arguments:
xstr: The timestamp to be formatted (required)
Returns:
str- A string represeting the time
QuickActionPreview#
A container class for storing quick action data previews.
This class is intended to be populated by commands like !get-remote-data-preview
and placed directly into the root context under QuickActionPreview.
A container class for storing quick action data previews.
This class is intended to be populated by commands like !get-remote-data-preview
and placed directly into the root context under QuickActionPreview.
Attributes:
id (Optional[str]): The ID of the ticket.
title (Optional[str]): The title or summary of the ticket or action.
description (Optional[str]): A brief description or details about the action.
status (Optional[str]): Current status (e.g., Open, In Progress, Closed).
assignee (Optional[str]): The user or entity assigned to the action.
creation_date (Optional[str]): The date and time when the item was created.
severity (Optional[str]): Indicates the priority or severity level.
to_context#
Converts the instance to a dictionary.
Returns:
dict- Dictionary representation of the QuickActionPreview instance.
ScheduledCommand#
ScheduledCommand configuration class Holds the scheduled command configuration for the command result - managing the way the command should be polled.
Arguments:
commandstr: The command that'll run after next_run_in_seconds has passed.next_run_in_secondsint: How long to wait before executing the command.argsOptional[Dict[str, Any]]: Arguments to use when executing the command.timeout_in_secondsOptional[int]: Number of seconds until the polling sequence will timeout.items_remainingOptional[int]: Number of items that are remaining to be polled.
VERSION_MISMATCH_ERROR#
raise_error_if_not_supported#
supports_polling#
Check if the integration supports polling (if server version is greater than 6.2.0). Returns: Boolean
to_results#
Returns the result dictionary of the polling command
SchemeTypeMapping#
Scheme type mappings builder.
Arguments:
type_namestr: The name of the remote incident type.fieldsdict: The dict of fields to their description.
add_field#
Adds a field to the incident type mapping.
Arguments:
namestr: The name of the field.descriptionstr: The description for that field.a
extract_mapping#
Extracts the mapping into XSOAR mapping screen.
Returns:
dict- the mapping object for the current field.
SignalTimeoutError#
Custom exception raised when the execution timeout is reached.
SmartGetDict#
A dict that when called with get(key, default) will return the default passed value, even if there is a value of "None" in the place of the key. Example with built-in dict:
Example with SmartGetDict:
TableOrListWidget#
Table/List Widget representation
Arguments:
dataAny: a list of data to display(Better use the add_category function to populate the data.
add_row#
Add a row to the widget.
Arguments:
dataAny: the data to add to the list/table.
to_display#
TextWidget#
Text Widget representation
Arguments:
textstr: The text for the widget to display
to_display#
Text Widget representation
Arguments:
textstr: The text for the widget to display
ThreatIntel#
XSOAR Threat Intel Objects
ObjectsNames#
Enum: Threat Intel Objects names.
CAMPAIGN
ATTACK_PATTERN
REPORT
MALWARE
COURSE_OF_ACTION
INTRUSION_SET
TOOL
THREAT_ACTOR
INFRASTRUCTURE
TACTIC
ObjectsScore#
Enum: Threat Intel Objects Score.
CAMPAIGN
ATTACK_PATTERN
REPORT
MALWARE
COURSE_OF_ACTION
INTRUSION_SET
TOOL
THREAT_ACTOR
INFRASTRUCTURE
TACTIC
KillChainPhases#
Enum: Kill Chain Phases names.
BUILD_CAPABILITIES
PRIVILEGE_ESCALATION
ADVERSARY_OPSEC
CREDENTIAL_ACCESS
EXFILTRATION
LATERAL_MOVEMENT
DEFENSE_EVASION
PERSISTENCE
COLLECTION
IMPACT
INITIAL_ACCESS
DISCOVERY
EXECUTION
INSTALLATION
DELIVERY
WEAPONIZATION
ACT_ON_OBJECTIVES
COMMAND_AND_CONTROL
TrendWidget#
Trend Widget representation
Arguments:
current_numberint: The Current number in the trend.previous_numberint: The previous number in the trend.
to_display#
UpdateRemoteSystemArgs#
update-remote-system args parser
Arguments:
argsdict: arguments for the command of the command.
YMLMetadataCollector#
The YMLMetadataCollector class provides decorators for integration functions which contain details relevant to yml generation.
This is an empty class, used for code autocompletion when using demisto-sdk generate_yml_from_python command syntax. For more information, visit the command's README.md.
Returns:
YMLMetadataCollector- The YMLMetadataCollector object
command#
add_http_prefix_if_missing#
This function adds http:// prefix to the proxy address in case it is missing.
Arguments:
addressstring: Proxy address.
Returns:
string- proxy address after the 'http://' prefix was added, if needed.
add_sensitive_log_strs#
Adds the received string to both LOG and DebugLogger. The logger will mask the string each time he encounters it.
Arguments:
sensitive_strstr: The string to be replaced.
appendContext#
Append data to the investigation context. Usable by scripts not integrations, since it uses setContext
Arguments:
keystr: The context path (required)dataany: Data to be added to the context (required)dedupbool: True if de-duplication is required. Default is False.
append_metrics#
Returns a 'CommandResults' list appended with metrics.
Arguments:
execution_metricsExecutionMetrics: Metrics object to be added to CommandResults list(optional).resultslist: 'CommandResults' list to append metrics to (required).
Returns:
list- results appended with the metrics if the server version is supported.
argToBoolean#
Boolean-ish arguments that are passed through demisto.args() could be type bool or type string. This command removes the guesswork and returns a value of type bool, regardless of the input value's type. It will also return True for 'yes' and False for 'no'.
Arguments:
value__: the value to evaluate
Returns:
bool- a boolean representation of 'value'
argToList#
Converts a string representation of args to a python list
Arguments:
argstr or list: Args to be converted (required)separatorstr: A string separator to separate the strings, the default is a comma.transformcallable: A function transformer to transfer the returned list arguments.
Returns:
list- A python list of args
arg_to_bool_or_none#
Converts a value to a boolean or None.
Arguments:
valueAny: The value to convert to boolean or None.
arg_to_datetime#
Converts an XSOAR argument to a datetime
This function is used to quickly validate an argument provided to XSOAR
via demisto.args() into an datetime. It will throw a ValueError if the input is invalid.
If the input is None, it will throw a ValueError if required is True,
or None if required is ``False.
Arguments:
argAny: argument to convertarg_namestr: argument nameis_utcbool: if True then date converted as utc timezone, otherwise will convert with local timezone.requiredbool: throws exception ifTrueand argument provided is Nonesettingsdict: If provided, passed to dateparser.parse function.
returns an datetime if conversion works
returns None if arg is None and required is set to False
otherwise throws an Exception
Returns:
Optional[datetime]-
arg_to_number#
Converts an XSOAR argument to a Python int
This function is used to quickly validate an argument provided to XSOAR
via demisto.args() into an int type. It will throw a ValueError
if the input is invalid. If the input is None, it will throw a ValueError
if required is True, or None if required is ``False.
Arguments:
argAny: argument to convertarg_namestr: argument namerequiredbool: throws exception ifTrueand argument provided is None
returns an int if arg can be converted
returns None if arg is None and required is set to False
otherwise throws an Exception
Returns:
Optional[int]-
assign_params#
Creates a dictionary from given kwargs without empty values. empty values are: None, '', [], {}, ()
Examples:
Arguments:
keys_to_ignoretuple or list: Keys to ignore if existsvalues_to_ignoretuple or list: Values to ignore if existskwargskwargs: kwargs to filter
Returns:
dict- dict without empty values
auto_detect_indicator_type#
Infer the type of the indicator.
Arguments:
indicator_valuestr: The indicator whose type we want to check. (required)
Returns:
str- The type of the indicator.
aws_table_to_markdown#
Converts a raw response from AWS into a markdown formatted table. This function checks to see if there is only one nested dict in the top level of the dictionary and will use the nested data.
Arguments:
response__: Raw response from AWStable_headerdict: The header string to use for the table.
Returns:
str- Markdown formatted table as a string.
b64_decode#
Decode a str in a base 64 format to a picture. Replaces the use of base64.b64decode function which doesn't add padding to the supplied str.
Arguments:
b64_str__: string to decode
Returns:
bytes- decoded binary
b64_encode#
Base64 encode a string. Wrapper function around base64.b64encode which will accept a string In py3 will encode the string to binary using utf-8 encoding and return a string result decoded using utf-8
Arguments:
text__: string to encode
Returns:
str- encoded string
batch#
Gets an iterable and yields slices of it.
Arguments:
iterablelist: list or other iterable object.batch_sizeint: the size of batches to fetch
Returns:
list-
build_dbot_entry#
Build a dbot entry. if score is 3 adds malicious
Examples:
Arguments:
indicatorstr: indicator field. if using file hashes, can be dictindicator_typestr: type of indicator ('url, 'domain', 'ip', 'cve', 'email', 'md5', 'sha1', 'sha256', 'crc32', 'sha512', 'ctph')vendorstr: Integration IDscoreint: DBot score (0-3)descriptionstr or None: description (will be added to malicious if dbot_score is 3). can be Nonebuild_maliciousbool: if True, will add a malicious entry
Returns:
dict- dbot entry
build_malicious_dbot_entry#
Build Malicious dbot entry
Examples:
Arguments:
indicatorstr: Value (e.g. 8.8.8.8)indicator_typestr: e.g. 'IP'vendorstr: Integration IDdescriptionstr: Why it's malicious
Returns:
dict- A malicious DBot entry
calculate_new_offset#
This calculates the new offset based on the response
Arguments:
old_offsetint: The offset from the previous runnum_incidentsint: The number of incidents returned by the API.total_incidentsint: The total number of incidents returned by the API.
Returns:
int- The new offset for the next run.
camel_case_to_underscore#
Converts a camelCase string to snake_case
Arguments:
sstr: The string to convert (e.g. helloWorld) (required)
Returns:
str- The converted string (e.g. hello_world)
camelize#
Convert all keys of a dictionary (or list of dictionaries) to CamelCase (with capital first letter)
Arguments:
srcdict or list: The dictionary (or list of dictionaries) to convert the keys for. (required)delimstr: The delimiter between two words in the key (e.g. delim=' ' for "Start Date"). Default ' '.upper_camelbool: When True then transforms dictionary keys to camel case with the first letter capitalised (for example: demisto_content to DemistoContent), otherwise the first letter will not be capitalised (for example: demisto_content to demistoContent).
Returns:
dict or list- The dictionary (or list of dictionaries) with the keys in CamelCase.
camelize_string#
Transform snake_case to CamelCase
Arguments:
src_strstr: snake_case string to convert.delimstr: indicator category.upper_camelbool: When True then transforms string to camel case with the first letter capitalised (for example: demisto_content to DemistoContent), otherwise the first letter will not be capitalised (for example: demisto_content to demistoContent).
Returns:
str- A CammelCase string.
censor_request_logs#
Censors the request logs generated from the urllib library directly by replacing sensitive information such as tokens and cookies with a mask. In most cases, the sensitive value is the first word after the keyword, but in some cases, it is the second one.
Arguments:
request_log__: The request log to censor
Returns:
str- The censored request log
comma_separated_mapping_to_dict#
Transforming a textual comma-separated mapping into a dictionary object.
Arguments:
raw_textstr: Comma-separated mapping e.g ('key1=value1', 'key2=value2', ...)
Returns:
dict-
content_profiler#
A decorator for profiling the execution time and performance of a function.
This decorator is useful for identifying performance bottlenecks and understanding the time complexity of your code. It collects and displays detailed profiling information, including the total execution time, the number of calls, and the average time per call. When to use it:
- When you need to debug and optimize the performance of your functions or methods.
- When you want to identify slow or inefficient parts of your code.
- During the development and testing phases to ensure that your code meets performance requirements.
To use, decorate the function that calls the function you want to profile with @content_profiler. Example: I want to profile the function_to_profile() function:
Analyze the Profiling Data with SnakeViz: Download the <automation_name>.prof from the war room and run: pip install snakeviz; snakveiz <automation_name>.prof
Tested with Python 3.10
Arguments:
funcfunction: The function to be profiled.
Returns:
any- The profiled function.
convert_dict_values_bytes_to_str#
Converts byte dict values to str
Arguments:
input_dictdict: dict to converts its values.
Returns:
dict- dict contains str instead of bytes.
createContext#
Receives a dict with flattened key values, and converts them into nested dicts
Arguments:
datadict or list: The data to be added to the context (required)idstr: The ID of the context entrykeyTransformfunction: A formatting function for the markdown table headersremoveNullbool: True if empty columns should be removed, false otherwise
Returns:
list- The converted context list
createContextSingle#
Receives a dict with flattened key values, and converts them into nested dicts
Arguments:
objdict or list: The data to be added to the context (required)idstr: The ID of the context entrykeyTransformfunction: A formatting function for the markdown table headersremoveNullbool: True if empty columns should be removed, false otherwise
Returns:
list- The converted context list
create_clickable_url#
Make the given url clickable when in markdown format by concatenating itself, with the proper brackets
Arguments:
urlUnion[List[str], str]: the url of interest or a list of urlstextUnion[List[str], str, None]: the text of the url or a list of texts of urls.
Returns:
Union[List[str], str]- Markdown format for clickable url
create_indicator_result_with_dbotscore_unknown#
Used for cases where the api response to an indicator is not found, returns CommandResults with readable_output generic in this case, and indicator with DBotScore unknown
Arguments:
indicatorstr: The value of the indicatorindicator_typeDBotScoreType: use DBotScoreType class [Unsupport in types CVE and ATTACKPATTERN]reliabilityDBotScoreReliability: use DBotScoreReliability classcontext_prefixstr: Use only in case that the indicator is CustomIndicatoraddress_typestr: Use only in case that the indicator is Cryptocurrencyrelationshipslist of EntityRelationship: List of relationships of the indicator.
Returns:
CommandResults-
create_updated_last_run_object#
Calculates the next fetch time and limit depending the incidents result and creates an updated LastRun object with the new time and limit.
Arguments:
last_rundict: The LastRun objectincidentslist: List of the incidents resultfetch_limitint: The fetch limitlook_backint: The time to look back in fetch in minutesstart_fetch_timestr: The time the fetch started to fetch fromend_fetch_timestr: The end time in which the fetch incidents endedcreated_time_fieldstr: The incident created time fielddate_formatstr: The date formatincrease_last_run_timebool: Whether to increase the last run time with one millisecondnew_offsetint | None: The new offset to set in the last run
Returns:
Dict- The new LastRun object
date_to_timestamp#
Parses date_str_or_dt in the given format (default: %Y-%m-%dT%H:%M:%S) to milliseconds Examples: ('2018-11-06T08:56:41', '2018-11-06T08:56:41', etc.)
Arguments:
date_str_or_dtstr or datetime.datetime: The date to be parsed. (required)date_formatstr: The date format of the date string (will be ignored if date_str_or_dt is of type datetime.datetime). (optional)
Returns:
int- The parsed timestamp.
datetime_to_string#
Converts a datetime object into a string. When used with json.dumps() for the default parameter,
e.g. json.dumps(response, default=datetime_to_string) datetime_to_string allows entire JSON objects
to be safely added to context without causing any datetime marshalling errors.
Arguments:
datetime_obj__: Datetime object.
Returns:
str- String representation of a datetime object.
detect_file_indicator_type#
Detect the type of the file indicator.
Arguments:
indicator_valuestr: The indicator whose type we want to check. (required)
Returns:
str- The type of the indicator.
dict_safe_get#
Recursive safe get query (for nested dicts and lists), If keys found return value otherwise return None or default value. Example:
Examples:
Arguments:
dict_objectdict: dictionary to query.keyslist: keys for recursive get.default_return_valueobject: Value to return when no key available.return_typetype: Excepted return type.raise_return_typebool: Whether to raise an error when the value didn't match the expected return type.
Returns:
object-
doubleBackslashes#
Double any backslashes in the given string if it contains two backslashes.
Arguments:
ststr: The string to be modified (required).
Returns:
str- A modified string with doubled backslashes.
elem2json#
Convert an ElementTree or Element into a JSON string.
elem_to_internal#
Convert an Element into an internal dictionary (not JSON!).
encode_string_results#
Encode string as utf-8, if any unicode character exists.
Arguments:
text__: string to encode
Returns:
str- encoded string
ensure_proxy_has_http_prefix#
The function checks if proxy environment vars are missing http/https prefixes, and adds http if so.
execute_command#
Runs the demisto.executeCommand() function and checks for errors.
Arguments:
commandstr: The command to run. (required)argsdict: The command arguments. (required)extract_contentsbool: Whether to return only the Contents part of the results. Default is True.fail_on_errorbool: Whether to fail the command when receiving an error from the command. Default is True.
Returns:
- `` - The command results.
- When
fail_on_erroris True -listordictorstr. - When
fail_on_erroris False -boolandstr.
Note:
For backward compatibility, only when fail_on_error is set to False, two values will be returned.
fileResult#
Creates a file from the given data
Arguments:
filenamestr: The name of the file to be created (required)datastr or bytes: The file data (required)file_typestr: one of the entryTypes file or entryInfoFile (optional)
Returns:
dict- A Demisto war room entry
file_result_existing_file#
Rename an existing file
Arguments:
filenamestr: The name of the file to be modified (required)saveFilenamestr: The new file name
Returns:
dict- A Demisto war room entry
filter_incidents_by_duplicates_and_limit#
Removes duplicate incidents from response and returns the incidents till limit. The function should be called after getting the get-incidents API response, and by passing the id_field it will filter out the incidents that were already fetched by checking the incident IDs that are saved from the previous fetch in the last run object
Arguments:
incidents_reslist: The incidents from the API responselast_rundict: The LastRun objectfetch_limitint: The incidents limit to returnid_fieldstr: The incident id field
Returns:
list- List of incidents after filtering duplicates when len(incidents) <= limit
flattenCell#
Flattens a markdown table cell content into a single string
Arguments:
datastr or list: The cell content (required)is_prettybool: Should cell content be pretified (default is True)
Returns:
str- A sting representation of the cell content
flattenRow#
Flatten each element in the given rowDict
Arguments:
rowDictdict: The dict to be flattened (required)
Returns:
dict- A flattened dict
flattenTable#
Flatten each row in the given tableDict
Arguments:
tableDictdict: The table to be flattened (required)
Returns:
dict- A flattened table
formatAllArgs#
makes a nice string representation of all the arguments
Arguments:
argslist: function arguments (required)kwdsdict: function keyword arguments (required)
Returns:
string- string representation of all the arguments
formatCell#
Convert a given object to md while decending multiple levels
Arguments:
datastr or list or dict: The cell content (required)is_prettybool: Should cell content be prettified (default is True)json_transformJsonTransformer: The Json transform object to transform the data
Returns:
str- The formatted cell content as a string
formatEpochDate#
Convert a time expressed in seconds since the epoch to a string representing local time
Arguments:
tint: Time represented in seconds (required)
Returns:
str- A string representing local time
generic_http_request#
A wrapper for the BaseClient._http_request() method, that allows performing HTTP requests without initiating a BaseClient object. Note: Avoid using this method if unnecessary. It is more recommended to use the BaseClient class.
Args:
method (str): HTTP request method (e.g., GET, POST, PUT, DELETE).
server_url (str): Base URL of the server.
timeout (int, optional): Timeout in seconds for the request (defaults to 10).
verify (bool, optional): Whether to verify SSL certificates (defaults to True).
proxy (bool or str, optional): Use a proxy server. Can be a boolean (defaults to False)
or a proxy URL string.
client_headers (dict, optional): Additional headers to be included in all requests
made by the client (overrides headers argument).
headers (dict, optional): Additional headers for this specific request.
url_suffix (str, optional): Path suffix to be appended to the server URL.
data (object, optional): Data to be sent in the request body (e.g., dictionary for POST requests).
ok_codes (list of int, optional): A list of HTTP status codes that are considered successful responses
(defaults to [200]).
auth (tuple, optional): Authentication credentials (username, password) for the request.
error_handler (callable, optional): Function to handle request errors.
files (dict, optional): Dictionary of files to be uploaded (for multipart/form-data requests).
params (dict, optional): URL parameters to be included in the request.
retries (int, optional): Number of times to retry the request on failure (defaults to 0).
retries (int, optional): Number of times to retry the request on failure (defaults to 0).
status_list_to_retry (int, optional): A set of integer HTTP status codes that we should force a retry on.
A retry is initiated if the request method is in ['GET', 'POST', 'PUT']
and the response status code is in status_list_to_retry.
resp_type (iterable, optional): Determines which data format to return from the HTTP request. The default
is 'json'.
json_data (dict, optional): The dictionary to send in a 'POST' request.
backoff_factor (float, optional): A backoff factor to apply between attempts after the second try
(most errors are resolved immediately by a second try without a
delay). urllib3 will sleep for::
{backoff factor} * (2 ** ({number of total retries} - 1))
seconds. If the backoff_factor is 0.1, then :func:.sleep will sleep
for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer
than :attr:Retry.BACKOFF_MAX.
By default, backoff_factor set to 5
raise_on_redirect (bool, optional): Whether, if the number of redirects is exhausted, to raise a MaxRetryError, or to return a response with a response code in the 3xx range.
raise_on_status (bool,optional): Similar meaning to raise_on_redirect:
whether we should raise an exception, or return a response,
if status falls in status_forcelist range and retries have
been exhausted.
empty_valid_codes (list, optional): A list of all valid status codes of empty responses (usually only 204, but can vary)
return_empty_response (bool, optional): Whether to return an empty response body if the response code is in empty_valid_codes
params_parser (callable, optional): How to quote the params. By default, spaces are replaced with + and / to %2F.
see here for more info: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode
Note! supported only in python3.
with_metrics (bool, optional): Whether or not to calculate execution metrics from the response
Returns:
Returns:
dict or str or bytes or xml.etree.ElementTree.Element or requests.Response- Depends on the resp_type parameter
Raises: exceptions.RequestException: If an error occurs during the request.
get_current_time#
Gets the current time in a given timezone, as time awared datetime.
Arguments:
time_zoneint: The time zone offset in hours.
Returns:
datetime- The current time.
get_demisto_version_as_str#
Get the Demisto Server version as a string <version>-<build>. If unknown will return: 'Unknown'.
Meant to be use in places where we want to display the version. If you want to perform logic based upon vesrion
use: is_demisto_version_ge.
Returns:
dict- Demisto version as string
get_engine_base_url#
Gets the xsoar engine id and returns it's base url. For example: for engine_id = '4ccccccc-5aaa-4000-b666-dummy_id', base url = '11.180.111.111:1443'.
Arguments:
engine_idstr: The xsoar engine id.
Returns:
str- The base URL of the engine.
get_error#
execute_command_result must contain error entry - check the result first with is_error function if there is no error entry in the result then it will raise an Exception
Arguments:
execute_command_resultdict or list: result of demisto.executeCommand()
Returns:
string- Error message extracted from the demisto.executeCommand() result
get_feed_last_run#
This function gets the feed's last run: using demisto.getLastRun().
Returns:
dict-
get_fetch_run_time_range#
Calculates the time range for fetch depending the look_back argument and the previous fetch start time given from the last_run object.
Arguments:
last_rundict: The LastRun objectfirst_fetchstr: The first time to fetch, used in the first fetch of an instancelook_backint: The time to look back in fetch in minutestimezoneint: The time zone offset in hoursdate_formatstr: The date format
Returns:
Tuple- The time range (start_time, end_time) of the creation date for the incidents to fetch in the current run.
get_found_incident_ids#
Gets the found incident ids from the last run object and adds the new fetched incident IDs.
Arguments:
last_rundict: The LastRun objectincidentslist: List of incidents to addlook_backint: The look back time in minutesid_fieldstr: The incident id field
Returns:
dict- The new incident ids.
get_hash_type#
Checks the type of the given hash. Returns 'md5', 'sha1', 'sha256' or 'Unknown'.
Arguments:
hash_filestr: The hash to be checked (required)
Returns:
str- The hash type
get_integration_context#
Gets the integration context.
Arguments:
syncbool: Whether to get the integration context directly from the DB.with_versionbool: Whether to return the version.
Returns:
dict-
get_integration_context_with_version#
Get the latest integration context with version, if available.
Arguments:
syncbool: Whether to get the context directly from the DB.
Returns:
tuple-
get_integration_instance_name#
Getting calling integration instance name
Returns:
str- Calling integration instance name
get_integration_name#
Getting calling integration's name
Returns:
str- Calling integration's name
get_last_mirror_run#
This function gets the last run of the mirror, from XSOAR version 6.6.0, using demisto.getLastMirrorRun().
Before XSOAR version 6.6.0, the given data is not returned and an exception will be raised.
Returns:
dict- we did not set anything yet).
get_latest_incident_created_time#
Gets the latest incident created time
Arguments:
incidentslist: List of incidentscreated_time_fieldstr: The incident created time fielddate_formatstr: The date formatincrease_last_run_timebool: Whether to increase the last run time with one millisecond
Returns:
str- The latest incident time
get_message_classes_dump#
A function that returns the printable message about classes dump
Arguments:
classes_as_listlist: The classes to print to the log
Returns:
str- Message to print.
get_message_global_vars#
A function that returns the printable message about global variables
Returns:
str- Message to print.
get_message_local_vars#
A function that returns the printable message about local variables
Returns:
str- Message to print.
get_message_memory_dump#
Listener function to dump the memory to log info
Arguments:
_sigint: The signal number_frameAny: The current stack frame
Returns:
str- Message to print.
get_message_modules_sizes#
A function that returns the printable message about the loaded modules by size
Returns:
str- Message to print.
get_message_threads_dump#
Listener function to dump the threads to log info
Arguments:
_sigint: The signal number_frameAny: The current stack frame
Returns:
str- Message to print.
get_pack_version#
Get the pack version. The version can be retrieved only for the pack that contains the running script or integration.
Returns:
str- The pack version in which the integration/script is part of, in case not found returns empty string.
get_schedule_metadata#
Get the entry schedule metadata if available
Arguments:
contextdict: Context in which the command was executed.
Returns:
dict- Dict with metadata of scheduled entry
get_script_name#
Getting calling script name
Returns:
str- Calling script name
get_server_config#
Retrieves XSOAR server configuration.
Returns:
dict-
get_size_of_object#
A function that recursively iterate to sum size of object & members.
Arguments:
input_objectAny: The object to calculate its memory footprint
Returns:
int- Size of input_object in bytes, or -1 if cannot determine the size.
get_tenant_account_name#
Gets the tenant name from the server url.
Returns:
str- The account name.
get_x_content_info_headers#
Get X-Content-* headers to send in outgoing requests to use when performing requests to external services such as oproxy.
Returns:
dict- headers dict
handle_proxy#
Handle logic for routing traffic through the system proxy. Should usually be called at the beginning of the integration, depending on proxy checkbox state.
Additionally will unset env variables REQUESTS_CA_BUNDLE and CURL_CA_BUNDLE if handle_insecure is speficied (default). This is needed as when these variables are set and a requests.Session object is used, requests will ignore the Sesssion.verify setting. See: https://github.com/psf/requests/blob/master/requests/sessions.py#L703
Arguments:
proxy_param_namestring: name of the "use system proxy" integration parametercheckbox_default_valuebool: Default value of the proxy param checkboxhandle_insecurebool: Whether to check the insecure param and unset env variablesinsecure_param_namestring: Name of insecure param. If None will search insecure and unsecure
Returns:
dict- proxies dict for the 'proxies' parameter of 'requests' functions
handle_proxy_for_long_running#
Handle logic for long running integration routing traffic through the system proxy. Should usually be called at the beginning of the integration, depending on proxy checkbox state. Long running integrations on hosted tenants XSOAR8 and XSIAM has a dedicated env. var.: CRTX_HTTP_PROXY. Fallback call to handle_proxy in cases long running integration on engine or XSOAR6
Arguments:
proxy_param_namestring: name of the "use system proxy" integration parametercheckbox_default_valuebool: Default value of the proxy param checkboxhandle_insecurebool: Whether to check the insecure param and unset env variablesinsecure_param_namestring: Name of insecure param. If None will search insecure and unsecure
Returns:
Tuple[dict, boolean]- proxies dict for the 'proxies' parameter of 'requests' functions and use_ssl boolean
has_passed_time_threshold#
Checks if the time difference between the current time and the timestamp is greater than the threshold.
Arguments:
timestamp_strstr: The timestamp to compare the current time to.seconds_thresholdint: The threshold in seconds.
Returns:
bool- True if the time difference is greater than the threshold, otherwise False.
hash_djb2#
Hash string with djb2 hash function
Arguments:
sstr: The input string to hashseedint: The seed for the hash function (default is 5381)
Returns:
int- The hashed value
indicators_value_to_clickable#
Function to get the indicator url link for indicators
Arguments:
indicatorsdict + List[dict]: An indicator or a list of indicators
Returns:
dict-
internal_to_elem#
Convert an internal dictionary (not JSON!) into an Element. Whatever Element implementation we could import will be used by default; if you want to use something else, pass the Element class as the factory parameter.
isCommandAvailable#
Check the list of available modules to see whether a command is currently available to be run.
Arguments:
cmdstr: The command to check (required)
Returns:
bool- True if command is available, False otherwise
is_debug_mode#
Return if this script/command was passed debug-mode=true option
Returns:
bool- true if debug-mode is enabled
is_demisto_version_ge#
Utility function to check if current running integration is at a server greater or equal to the passed version
Arguments:
versionstr: Version to checkbuild_numberstr: Build number to check
Returns:
bool- True if running within a Server version greater or equal than the passed version
is_error#
Check if the given execute_command_result has an error entry
Arguments:
execute_command_resultdict or list: Demisto entry (required) or result of demisto.executeCommand()
Returns:
bool- True if the execute_command_result has an error entry, false otherwise
is_filename_valid#
Checking if the file name contains invalid characters.
Arguments:
filename__: The file name
Returns:
bool- True if valid otherwise False.
is_integration_command_execution#
This function determines whether the current execution a script execution or a integration command execution.
Returns:
bool- Is the current execution a script execution or a integration command execution.
is_integration_instance_running_on_engine#
Determines whether the current integration instance runs on an xsoar engine. If yes - returns the engine id.
Returns:
str- The engine id iff the instance is running on an xsaor engine.
is_ip_address_internal#
Checks if an IP address is an internal (RFC 1918) IP, Available from python3.
Returns:
bool- True if the given IP address is an internal.
is_ip_valid#
Checks if the given string represents a valid IP address. By default, will only return 'True' for IPv4 addresses.
Arguments:
sstr: The string to be checked (required)accept_v6_ipsbool: A boolean determining whether the function should accept IPv6 addresses
Returns:
bool- True if the given string represents a valid IP address, False otherwise
is_ipv6_valid#
Checks if the given string represents a valid IPv6 address.
Arguments:
addressstr: The string to check.
Returns:
bool- True if the given string represents a valid IPv6 address.
is_mac_address#
Test for valid mac address
Arguments:
macstr: MAC address in the form of AA:BB:CC:00:11:22
Returns:
bool- True/False
is_platform#
Determines whether or not the platform is platform.
Returns:
bool- True iff the platform is unified_platform.
is_scheduled_command_retry#
Determines if the current command is a polling retry command. This is useful if some actions should not be performed when a command is polling for a response such as submitting data for processing.
Returns:
Bool- True if the command is part of a polling retry, otherwise false
is_time_sensitive#
Checks if the command reputation (auto-enrichment) is called as auto-extract=inline. This function checks if the 'isTimeSensitive' attribute exists in the 'demisto' object and if it's set to True.
Returns:
bool- bool
is_using_engine#
Determines whether or not the platform is using engine. NOTE:
- This method works only for system integrations (not custom).
- On xsoar 8, this method works only for integrations that runs on the xsoar pod - not on the engine-0 (mainly long running integrations) such as: EDL, Cortex Core - IOC, Cortex Core - IR, ExportIndicators, Generic Webhook, PingCastle, Publish List, Simple API Proxy, Syslog v2, TAXII Server, TAXII2 Server, Web File Repository, Workday_IAM_Event_Generator, XSOAR-Web-Server, Microsoft Teams, AWS-SNS-Listener.
Returns:
bool- True iff the platform is using engine.
is_versioned_context_available#
Determines whether versioned integration context is available according to the server version.
Returns:
bool-
is_xsiam#
Determines whether or not the platform is XSIAM.
Returns:
bool- True iff the platform is XSIAM.
is_xsiam_or_xsoar_saas#
Determines whether or not the platform is XSIAM or XSOAR SAAS.
Returns:
bool- True iff the platform is XSIAM or XSOAR SAAS.
is_xsoar#
Determines whether or not the platform is XSOAR.
Returns:
bool- True iff the platform is XSOAR.
is_xsoar_hosted#
Determines whether or not the platform is XSOAR hosted.
Returns:
bool- True iff the platform is XSOAR hosted.
is_xsoar_on_prem#
Determines whether or not the platform is a XSOAR on-prem.
Returns:
bool- True iff the platform is XSOAR on-prem.
is_xsoar_saas#
Determines whether or not the platform is XSOAR SAAS.
Returns:
bool- True iff the platform is XSOAR SAAS.
json2elem#
Convert a JSON string into an Element. Whatever Element implementation we could import will be used by default; if you want to use something else, pass the Element class as the factory parameter.
json2xml#
Convert a JSON string into an XML string. Whatever Element implementation we could import will be used by default; if you want to use something else, pass the Element class as the factory parameter.
logger#
decorator function to log the function call using LOG
Arguments:
funcfunction: function to call (required)
Returns:
any- returns the func return value.
merge_lists#
Replace values in a list with those in an updated list. Example:
Examples:
Arguments:
original_listlist: The original list.updated_listlist: The updated list.keystr: The key to replace elements by.
Returns:
list-
parse_date_range#
THIS FUNCTTION IS DEPRECATED - USE dateparser.parse instead
Parses date_range string to a tuple date strings (start, end). Input must be in format 'number date_range_unit') Examples: (2 hours, 4 minutes, 6 month, 1 day, etc.)
Arguments:
date_rangestr: The date range to be parsed (required)date_formatstr: Date format to convert the date_range to. (optional)to_timestampbool: If set to True, then will return time stamp rather than a datetime.datetime. (optional)timezoneint: timezone should be passed in hours (e.g if +0300 then pass 3, if -0200 then pass -2).utcbool: If set to True, utc time will be used, otherwise local time.
Returns:
(datetime.datetime, datetime.datetime) or (int, int) or (str, str)- The parsed date range.
parse_date_string#
Parses the date_string function to the corresponding datetime object. Note: If possible (e.g. running Python 3), it is suggested to use dateutil.parser.parse or dateparser.parse functions instead.
Examples:
Arguments:
date_stringstr: The date string to parse. (required)date_formatstr: The date format of the date string. If the date format is known, it should be provided. (optional)
Returns:
(datetime.datetime, datetime.datetime)- The parsed datetime.
parse_json_string#
Parse a JSON string into a Python dictionary.
Arguments:
json_stringstr: The JSON string to be parsed.
Returns:
dict-
pascalToSpace#
Converts pascal strings to human readable (e.g. "ThreatScore" -> "Threat Score", "thisIsIPAddressName" -> "This Is IP Address Name"). Could be used as headerTransform
Arguments:
sstr: The string to be converted (required)
Returns:
str- The converted string
polling_function#
To use on a function that should rerun itself Commands that use this decorator must have a Polling argument, polling: true in yaml, and a hidden hide_polling_output argument. Commands that use this decorator should return a PollResult. Will raise an DemistoException if the server version doesn't support Scheduled Commands (< 6.2.0)
Arguments:
namestr: The name of the commandintervalint: How many seconds until the next run. Recommended range: 30-60 seconds.timeoutint: How longpoll_messagestr: The message to display in the war room while pollingrequires_polling_argbool: Whether a polling argument should be expected as one of the demisto args
Returns:
Function- Decorator for polling functions
positiveFile#
Checks if the given entry from a file reputation query is positive (known bad) (deprecated)
Arguments:
entrydict: File entry (required)
Returns:
bool- True if bad, false otherwise
positiveIp#
Checks if the given entry from a file reputation query is positive (known bad) (deprecated)
Arguments:
entrydict: IP entry (required)
Returns:
bool- True if bad, false otherwise
positiveUrl#
Checks if the given entry from a URL reputation query is positive (known bad) (deprecated)
Arguments:
entrydict: URL entry (required)
Returns:
bool- True if bad, false otherwise
register_signal_handler_profiling_dump#
Function that registers the threads and memory dump signal listener
Arguments:
profiling_dump_rows_limitint: The max number of profiling related rows to print to the logprofiling_dump_rows_limitint: The max number of profiling related rows to print to the log
remove_duplicates_from_list_arg#
Removes duplicates from a list after calling argToList. For example: args: {'ids': "1,2,1"}, field='ids' The return output will be ["1", "2"]
Arguments:
argsdict: Args to be converted (required)fieldstr: Field in args to be converted into list without duplicates (required)
Returns:
list- A python list of args without duplicates
remove_empty_elements#
Recursively remove empty lists, empty dicts, or None elements from a dictionary.
Arguments:
d__: Input dictionary.
Returns:
dict- Dictionary with all empty lists, and empty dictionaries removed.
remove_nulls_from_dictionary#
Remove Null values from a dictionary. (updating the given dictionary)
Arguments:
datadict: The data to be added to the context (required)
remove_old_incidents_ids#
Removes old incident ids from the last run object to avoid overloading.
Arguments:
found_incidents_idsdict: Dict of incidents idscurrent_timeint: The current epoch time to compare with the existing IDs added timelook_backint: The look back time in minutes
Returns:
dict- The new incidents ids
replace_in_keys#
Replace a substring in all of the keys of a dictionary (or list of dictionaries)
Arguments:
srcdict or list: The dictionary (or list of dictionaries) with keys that need replacement. (required)existingstr: substring to replace.newstr: new substring that will replace the existing substring.
Returns:
dict or list- The dictionary (or list of dictionaries) with keys after substring replacement.
replace_spaces_in_credential#
This function is used in case of credential from type: 9 is in the wrong format of one line with spaces instead of multiple lines.
Arguments:
credentialstr or None: the credential to replace spaces in.
otherwise the credential will be returned as is.
response_to_context#
Recursively creates a data dictionary where all key starts with capital letters. If a key include underscores, removes underscores, capitalize every word. Example: "one_two" to "OneTwo
Arguments:
reponse_objAny: The response object to update. :user_predefiend_keys: An optional argument, a dict with predefined keys where the key is the key in the response and value is the key we want to turn the key into.
Returns:
Any- A response with all keys (if there're any) starts with a capital letter.
retry#
retries to execute a function until an exception isn't raised anymore.
Arguments:
timesint: The number of times to trigger the retry mechanism.delayint: The time in seconds to sleep between each timeexceptionsException: The exceptions that should be caught when executing the function (Union[tuple[type[Exception], ...], type[Exception]])
Returns:
Any- Any
return_error#
Returns error entry with given message and exits the script
Arguments:
messagestr: The message to return to the entry (required)errorstr or Exception: The raw error message to log (optional)outputsdict or None: the outputs that will be returned to playbook/investigation context (optional)
Returns:
dict- Error entry object
return_outputs#
DEPRECATED: use return_results() instead
This function wraps the demisto.results(), makes the usage of returning results to the user more intuitively.
Arguments:
readable_outputstr | int: markdown string that will be presented in the warroom, should be human readable - (HumanReadable)outputsdict: the outputs that will be returned to playbook/investigation context (originally EntryContext)raw_responsedict | list | str: must be dictionary, if not provided then will be equal to outputs. usually must be the original raw response from the 3rd party service (originally Contents)timelinedict | list: expects a list, if a dict is passed it will be put into a list. used by server to populate an indicator's timeline. if the 'Category' field is not present in the timeline dict(s), it will automatically be be added to the dict(s) with its value set to 'Integration Update'.ignore_auto_extractbool: expects a bool value. if true then the warroom entry readable_output will not be auto enriched.
return_results#
This function wraps the demisto.results(), supports.
Arguments:
resultsCommandResults or PollResult or str or dict or BaseWidget or list or GetMappingFieldsResponse or GetModifiedRemoteDataResponse or GetRemoteDataResponse: A result object to return as a War-Room entry.
return_warning#
Returns a warning entry with the specified message, and exits the script.
Arguments:
messagestr: The message to return in the entry (required).exitbool: Determines if the program will terminate after the command is executed. Default is False.warningstr: The warning message (raw) to log (optional).outputsdict or None: The outputs that will be returned to playbook/investigation context (optional).ignore_auto_extractbool: Determines if the War Room entry will be auto-enriched. Default is false.
Returns:
dict- Warning entry object
safe_load_json#
Safely loads a JSON object from an argument. Allows the argument to accept either a JSON in string form, or an entry ID corresponding to a JSON file.
Arguments:
json_object__: Entry ID or JSON string.
Returns:
dict- Dictionary object from a parsed JSON file or string.
safe_sleep#
Sleeps for the given duration, but raises an error if it would exceed the TTL.
Arguments:
duration_secondsfloat: The desired sleep duration in seconds.
safe_strptime#
Parses a date string to a datetime object, handling cases where the microsecond component is missing.
Arguments:
date_strstr: The date string to parse (required)datetime_formatstr: The format of the date string (required)strptimeCallable: The function to use for parsing the date string (optional)
Returns:
datetime.datetime- The parsed datetime object
scoreToReputation#
Converts score (in number format) to human readable reputation format
Arguments:
scoreint: The score to be formatted (required)
Returns:
str- The formatted score
sectionsToMarkdown#
Converts a list of Demisto JSON tables to markdown string of tables
Arguments:
rootdict or list: The JSON table - List of dictionaries with the same keys or a single dictionary (required)
Returns:
str- A string representation of the markdown table
send_data_to_xsiam#
Send the supported fetched data types into the XDR data-collector private api.
Arguments:
dataUnion[str, list]: The data to send to XSIAM server. Should be of the following:
- List of strings or dicts where each string or dict represents an event or asset.
- String containing raw events separated by a new line.
vendorstr: The vendor corresponding to the integration that originated the data.productstr: The product corresponding to the integration that originated the data.data_formatstr: Should only be filled in case the 'events' parameter contains a string of raw events in the format of 'leef' or 'cef'. In other cases the data_format will be set automatically.url_keystr: The param dict key where the integration url is located at. the default is 'url'.num_of_attemptsint: The num of attempts to do in case there is an api limit (429 error codes)chunk_sizeint: Advanced - The maximal size of each chunk size we send to API. Limit of 9 MB will be inforced.data_typestr: Type of data to send to Xsiam, events or assets.should_update_health_modulebool: whether to trigger the health module showing how many events were sent to xsiam This can be useful when using send_data_to_xsiam in batches for the same fetch.add_proxy_to_requestbool: whether to add proxy to the send evnets request.snapshot_idstr: the snapshot id.items_countstr: the asset snapshot items count.multiple_threadsbool: whether to use multiple threads to send the events to xsiam or not. Note that when set to True, the updateModuleHealth should be done from the itnegration itself.
In case of running with multiple threads, the list of futures will hold the number of events sent and can be accessed by: for future in concurrent.futures.as_completed(futures): data_size += future.result()
send_events_to_xsiam#
Send the fetched events into the XDR data-collector private api.
Arguments:
eventsUnion[str, list]: The events to send to XSIAM server. Should be of the following:
- List of strings or dicts where each string or dict represents an event.
- String containing raw events separated by a new line.
vendorstr: The vendor corresponding to the integration that originated the events.productstr: The product corresponding to the integration that originated the events.data_formatstr: Should only be filled in case the 'events' parameter contains a string of raw events in the format of 'leef' or 'cef'. In other cases the data_format will be set automatically.url_keystr: The param dict key where the integration url is located at. the default is 'url'.num_of_attemptsint: The num of attempts to do in case there is an api limit (429 error codes)chunk_sizeint: Advanced - The maximal size of each chunk size we send to API. Limit of 9 MB will be inforced.should_update_health_modulebool: whether to trigger the health module showing how many events were sent to xsiamadd_proxy_to_requestbool: whether to add proxy to the send evnets request.multiple_threadsbool: whether to use multiple threads to send the events to xsiam or not.
In case of running with multiple threads, the list of futures will hold the number of events sent and can be accessed by: for future in concurrent.futures.as_completed(futures): data_size += future.result()
set_feed_last_run#
This function sets the feed's last run: using demisto.setLastRun().
Arguments:
last_run_indicatorsdict: Indicators to save in "lastRun" object.
set_integration_context#
Sets the integration context.
Arguments:
contextdict: The context to set.syncbool: Whether to save the context directly to the DB.versionAny: The version of the context to set.
Returns:
dict-
set_last_mirror_run#
This function sets the last run of the mirror, from XSOAR version 6.6.0, by using demisto.setLastMirrorRun().
Before XSOAR version 6.6.0, we don't set the given data and an exception will be raised.
Arguments:
last_mirror_rundict: Data to save in the "LastMirrorRun" object.
set_to_integration_context_with_retries#
Update the integration context with a dictionary of keys and values with multiple attempts. The function supports merging the context keys using the provided object_keys parameter. If the version is too old by the time the context is set, another attempt will be made until the limit after a random sleep.
Arguments:
contextdict: A dictionary of keys and values to set.object_keysdict: A dictionary to map between context keys and their unique ID for merging them.syncbool: Whether to save the context directly to the DB.max_retry_timesint: The maximum number of attempts to try.
shortCrowdStrike#
Display CrowdStrike Intel results in Markdown (deprecated)
Arguments:
entrydict: CrowdStrike result entry (required)
Returns:
dict- A Demisto entry containing the shortened CrowdStrike info
shortDomain#
Formats a domain reputation entry into a short table (deprecated)
Arguments:
entrydict: Domain result entry (required)
Returns:
dict- A Demisto entry containing the shortened domain info
shortFile#
Formats a file reputation entry into a short table (deprecated)
Arguments:
entrydict: File result entry (required)
Returns:
dict- A Demisto entry containing the shortened file info
shortIp#
Formats an ip reputation entry into a short table (deprecated)
Arguments:
entrydict: IP result entry (required)
Returns:
dict- A Demisto entry containing the shortened IP info
shortUrl#
Formats a URL reputation entry into a short table (deprecated)
Arguments:
entrydict: URL result entry (required)
Returns:
dict- A Demisto entry containing the shortened URL info
shorten_string_for_printing#
Function that removes the middle of a long str, for printint or logging. If needed, it will replace the middle with '...',
Examples:
Arguments:
source_stringstr: A long str that needs shortening.max_lengthint: Maximum length of the returned str, should be higher than 0. Default is 64.
Returns:
str- : A string no longer than max_length.
signal_handler_profiling_dump#
Listener function to dump the threads and memory to log info
Arguments:
_sigint: The signal number_frameAny: The current stack frame
skip_cert_verification#
The function deletes the self signed certificate env vars in order to http requests to skip certificate validation.
skip_proxy#
The function deletes the proxy environment vars in order to http requests to skip routing through proxy
snakify#
Convert all keys of a dictionary to snake_case (underscored separated)
Arguments:
srcdict: The dictionary to convert the keys for. (required)
Returns:
dict- The dictionary (or list of dictionaries) with the keys in CamelCase.
split_data_to_chunks#
Splits a string of data into chunks of an approximately specified size. The actual size can be lower.
Arguments:
datalist or a string: A list of data or a string delimited with \n to split to chunks.target_chunk_sizeint: The maximum size of each chunk. The maximal size allowed is 9MB.
Returns:
collections.Iterable[list]- An iterable of lists where each list contains events with approx size of chunk size.
stringEscape#
Escape newline chars in the given string.
Arguments:
ststr: The string to be modified (required).
Returns:
str- A modified string.
stringEscapeMD#
Escape any chars that might break a markdown string
Arguments:
ststr: The string to be modified (required)minimal_escapingbool: Whether replace all special characters or table format only (optional)escape_multilinebool: Whether convert line-ending characters (optional)
Returns:
str- A modified string
stringUnEscape#
Unescape newline chars in the given string.
Arguments:
ststr: The string to be modified (required).
Returns:
str- A modified string.
string_to_context_key#
Checks if string, removes underscores, capitalize every word. Example: "one_two" to "OneTwo"
Arguments:
stringstr: The string to be converted (required)
Returns:
str- The converted string
string_to_table_header#
Checks if string, change underscores to spaces, capitalize every word. Example: "one_two" to "One Two"
Arguments:
stringstr: The string to be converted (required)
Returns:
str- The converted string
support_multithreading#
Adds lock on the calls to the Cortex XSOAR server from the Demisto object to support integration which use multithreading.
tableToMarkdown#
Converts a demisto table in JSON form to a Markdown table
Arguments:
namestr: The name of the table (required)tdict or list: The JSON table - List of dictionaries with the same keys or a single dictionary (required)headerslist or string: A list of headers to be presented in the output table (by order). If string will be passed then table will have single header. Default will include all available headers.headerTransformfunction: A function that formats the original data headers (optional)removeNullbool: Remove empty columns from the table. Default is Falsemetadatastr: Metadata about the table contentsurl_keyslist: a list of keys in the given JSON table that should be turned in to clickabledate_fieldslist: A list of date fields to format the value to human-readable output.json_transform_mappingDict[str, JsonTransformer]: A mapping between a header key to corresponding JsonTransformeris_auto_json_transformbool: Boolean to try to auto transform complex jsonsort_headersbool: Sorts the table based on its headers only if the headers parameter is not specified
Returns:
str- A string representation of the markdown table
timestamp_to_datestring#
Parses timestamp (milliseconds) to a date string in the provided date format (by default: ISO 8601 format) Examples: (1541494441222, 1541495441000, etc.)
Arguments:
timestampint or str: The timestamp to be parsed (required)date_formatstr: The date format the timestamp should be parsed to. (optional)is_utcbool: Should the string representation of the timestamp use UTC time or the local machine time
Returns:
str- The parsed timestamp in the date_format
underscoreToCamelCase#
Convert an underscore separated string to camel case
Arguments:
sstr: The string to convert (e.g. hello_world) (required)upper_camelbool: When True then transforms dictionarykeys to camel case with the first letter capitalised (for example: demisto_content to DemistoContent), otherwise the first letter will not be capitalised (for example: demisto_content to demistoContent).
Returns:
str- The converted string (e.g. HelloWorld)
update_integration_context#
Update the integration context with a given dictionary after merging it with the latest integration context.
Arguments:
contextdict: The keys and values to update in the integration context.object_keysdict: A dictionary to map between context keys and their unique ID for merging them with the latest context.syncbool: Whether to use the context directly from the DB.
Returns:
tuple-
update_last_run_object#
Updates the LastRun object with the next fetch time and limit and with the new fetched incident IDs.
Arguments:
last_rundict: The LastRun objectincidentslist: List of the incidents resultfetch_limitint: The fetch limitstart_fetch_timestr: The time the fetch started to fetch fromend_fetch_timestr: The end time in which the fetch incidents endedlook_backint: The time to look back in fetch in minutescreated_time_fieldstr: The incident created time fieldid_fieldstr: The incident id fielddate_formatstr: The date formatincrease_last_run_timebool: Whether to increase the last run time with one millisecondnew_offsetint | None: The new offset to set in the last run
Returns:
Dict- The updated LastRun object
url_to_clickable_markdown#
Turn the given urls fields in to clickable url, used for the markdown table.
Arguments:
data[Union[str, List[Any], Dict[str, Any]]]: a dictionary or a list containing data with some values that are urlsurl_keysList[str]: the keys of the url's wished to turn clickable
Returns:
[Union[str, List[Any], Dict[str, Any]]]- markdown format for clickable url
urljoin#
Will join url and its suffix
Example: "https://google.com/", "/" => "https://google.com/" "https://google.com", "/" => "https://google.com/" "https://google.com", "api" => "https://google.com/api" "https://google.com", "/api" => "https://google.com/api" "https://google.com/", "api" => "https://google.com/api" "https://google.com/", "/api" => "https://google.com/api"
Arguments:
urlstring: URL string (required)suffixstring: the second part of the url
Returns:
string- Full joined url
vtCountPositives#
Counts the number of detected URLs in the entry
Arguments:
entrydict: Demisto entry (required)
Returns:
int- The number of detected URLs
xml2json#
Convert an XML string into a JSON string.
Arguments:
xmlstringstr: The string to be converted (required)
Returns:
dict or list- The converted JSON
xsiam_api_call_with_retries#
Send the fetched events or assests into the XDR data-collector private api.
Arguments:
clientBaseClient: base client containing the XSIAM url.xsiam_urlstr: The URL of XSIAM to send the api request.zipped_databytes: encoded eventsheadersdict: headers for the requesterror_msgstr: The error message prefix in case of an error.num_of_attemptsint: The num of attempts to do in case there is an api limit (429 error codes).events_error_handlercallable: error handler functiondata_typestr: events or assets
Returns:
requests.Response or DemistoException- Response object or DemistoException