def syslog_send_notification(manager: SyslogManager, min_severity: int):
    """
    Send a message to syslog
    :param manager: Syslog manager
    :param min_severity: Minimum severity of incidents to send messages about
    """
    message = demisto.args().get('message', '')
    entry = demisto.args().get('entry')
    ignore_add_url = demisto.args().get('ignoreAddURL', False)
    log_level = demisto.args().get('log_level', 'INFO')
    severity = demisto.args().get('severity')  # From server
    message_type = demisto.args().get('messageType', '')  # From server

    if severity:
        try:
            severity = int(severity)
        except Exception:
            severity = None

    if message_type == INCIDENT_OPENED and (severity is not None
                                            and severity < min_severity):
        return

    if not message:
        message = ''

    message = message.replace('\n', ' ').replace('\r', ' ').replace('`', '')
    investigation = demisto.investigation()
    if investigation:
        investigation_id = investigation.get('id')
        if entry:
            message = f'{entry}, {message}'
        message = f'{investigation_id}, {message}'

    if ignore_add_url and isinstance(ignore_add_url, str):
        ignore_add_url = bool(strtobool(ignore_add_url))
    if not ignore_add_url:
        investigation = demisto.investigation()
        server_links = demisto.demistoUrls()
        if investigation:
            if investigation.get('type') != PLAYGROUND_INVESTIGATION_TYPE:
                link = server_links.get('warRoom')
                if link:
                    if entry:
                        link += '/' + entry
                    message += f' {link}'
            else:
                link = server_links.get('server', '')
                if link:
                    message += f' {link}#/home'

    if not message:
        raise ValueError('No message received')

    send_log(manager, message, log_level)

    demisto.results('Message sent to Syslog successfully.')
Beispiel #2
0
def write_log_json():
    """ Gather Args, form json document, write document to MondoDB """
    investigation = demisto.investigation()
    investigation_id = investigation.get('id')
    investigation_user = investigation.get('user')
    timestamp = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S+00:00")
    id_ = demisto.args().get('id', investigation_id)
    playbook = demisto.args().get('playbook')
    action = demisto.args().get('action')
    user = demisto.args().get('user', investigation_user)
    message = demisto.args().get('message')
    logjson = {
        'timestamp': timestamp,
        'id': id_,
        'playbook': playbook,
        'action': action,
        'user': user,
        'message': message
    }
    # Add json to the document collection in MondoDB
    result = COLLECTION.insert_one(logjson)
    entry_id = result.inserted_id

    context = {
        'EntryID': str(entry_id),
        'Timestamp': timestamp,
        'ID': id_,
        'Playbook': playbook,
        'Action': action,
        'User': user,
        'Message': message
    }
    ec = {'MongoDB.Entry(val.EntryID === obj.EntryID)': context}
    return 'MongoDB Log - 1 document/record added', ec, {}
Beispiel #3
0
def close_channel():
    """
    Archives a mirrored slack channel by its incident ID.
    """
    investigation = demisto.investigation()
    if investigation.get('type') == PLAYGROUND_INVESTIGATION_TYPE:
        return_error('Can not perform this action in playground.')

    integration_context = demisto.getIntegrationContext()
    if not integration_context or not integration_context.get('mirrors', []):
        return_error('No mirrors found for this incident.')

    mirrors = json.loads(integration_context['mirrors'])
    mirror = list(
        filter(lambda m: investigation.get('id') == m['investigation_id'],
               mirrors))
    if not mirror:
        return_error('Could not find the mirrored Slack conversation.')

    mirror = mirrors.pop(mirrors.index(mirror[0]))
    conversation_id = mirror['channel_id']

    CHANNEL_CLIENT.conversations_archive(channel=conversation_id)

    # Check for other mirrors on the archived channel
    channel_mirrors = list(
        filter(lambda m: conversation_id == m['channel_id'], mirrors))
    for mirror in channel_mirrors:
        mirrors.remove(mirror)

    set_to_latest_integration_context('mirrors', mirrors)

    demisto.results('Channel successfully archived.')
def send_ms_teams_message(entitlement, task, user_id, message):
    investigation_id: str = demisto.investigation()['id']

    adaptive_card: dict = {
        'contentType': 'application/vnd.microsoft.card.adaptive',
        'content': {
            '$schema':
            'http://adaptivecards.io/schemas/adaptive-card.json',
            'version':
            '1.0',
            'type':
            'AdaptiveCard',
            'msteams': {
                'width': 'Full'
            },
            'body': [{
                'type': 'TextBlock',
                'text': message,
                'wrap': True
            }],
            'actions': [{
                'type': 'Action.Submit',
                'title': 'Yes',
                'data': {
                    'response': 'Yes',
                    'entitlement': entitlement,
                    'investigation_id': investigation_id,
                    'task_id': task
                }
            }, {
                'type': 'Action.Submit',
                'title': 'No',
                'data': {
                    'response': 'No',
                    'entitlement': entitlement,
                    'investigation_id': investigation_id,
                    'task_id': task
                }
            }]
        }
    }

    command_arguments: dict = {
        'adaptive_card': json.dumps(adaptive_card),
        'using-brand': 'Microsoft Teams'
    }

    if user_id:
        command_arguments['team_member'] = user_id
        demisto.results(
            demisto.executeCommand('send-notification', command_arguments))
    else:
        raise Exception('A user must be provided.')
Beispiel #5
0
def find_mirror_by_investigation() -> dict:
    mirror: dict = {}
    investigation = demisto.investigation()
    if investigation:
        integration_context = demisto.getIntegrationContext()
        if integration_context.get('mirrors'):
            mirrors = json.loads(integration_context['mirrors'])
            investigation_filter = list(
                filter(
                    lambda m: investigation.get('id') == m['investigation_id'],
                    mirrors))
            if investigation_filter:
                mirror = investigation_filter[0]

    return mirror
Beispiel #6
0
def main():
    args = demisto.args()
    entry_id = args.get('entry_id', '')
    file_path = demisto.getFilePath(entry_id).get('path')

    wpa_password = args.get('wpa_password', '')
    rsa_decrypt_key_entry_id = args.get('rsa_decrypt_key_entry_id', '')
    rsa_key_file_path = None
    if rsa_decrypt_key_entry_id:
        rsa_key_file_path = demisto.getFilePath(rsa_decrypt_key_entry_id).get(
            'path')
    conversation_number_to_display = int(args.get('convs_to_display', '15'))
    extracted_protocols = argToList(args.get('protocol_output', ''))
    if 'All' in extracted_protocols:
        extracted_protocols = ALL_SUPPORTED_PROTOCOLS
    is_flows = True
    is_reg_extract = args.get('extract_strings', 'False') == 'True'
    pcap_filter = args.get('pcap_filter', '')
    homemade_regex = args.get('custom_regex', '')  # 'Layer (.+):'
    pcap_filter_new_file_path = ''
    pcap_filter_new_file_name = args.get('filtered_file_name', '')
    unique_ips = args.get('extract_ips', 'False') == 'True'

    if pcap_filter_new_file_name:
        temp = demisto.uniqueFile()
        pcap_filter_new_file_path = demisto.investigation()['id'] + '_' + temp

    try:
        pcap = PCAP(is_reg_extract, extracted_protocols, homemade_regex,
                    unique_ips, entry_id)
        pcap.mine(file_path, wpa_password, rsa_key_file_path, is_flows,
                  is_reg_extract, pcap_filter, pcap_filter_new_file_path)
        hr, ec, raw = pcap.get_outputs(conversation_number_to_display,
                                       is_flows, is_reg_extract)
        return_outputs(hr, ec, raw)

    except Exception as e:
        return_error(f'Unexpected error: {str(e)}',
                     error=traceback.format_exc())

    if pcap_filter_new_file_name:
        demisto.results({
            'Contents': '',
            'ContentsFormat': formats['text'],
            'Type': 3,
            'File': pcap_filter_new_file_name,
            'FileID': temp
        })
Beispiel #7
0
def main():
    script_arguments: dict = demisto.args()

    team_member: str = script_arguments.get('team_member', '')
    channel: str = script_arguments.get('channel', '')

    if not (team_member or channel):
        raise ValueError('Either team member or channel must be provided.')

    if team_member and channel:
        raise ValueError('Either team member or channel should be provided, not both.')

    persistent: bool = script_arguments.get('persistent', '') == 'true'
    response: list = demisto.executeCommand('addEntitlement', {'persistent': persistent})
    if isError(response[0]):
        demisto.results(response)
        return

    entitlement: str = response[0]['Contents']
    investigation_id: str = demisto.investigation()['id']
    task_id: str = script_arguments.get('task_id', '')
    message_text: str = script_arguments.get('message', '')

    first_option: str = script_arguments.get('option1', '')
    second_option: str = script_arguments.get('option2', '')
    options: list = [first_option, second_option]
    additional_options: list = argToList(script_arguments.get('additional_options'))
    options.extend(additional_options)

    message: dict = {
        'message_text': message_text,
        'options': options,
        'entitlement': entitlement,
        'investigation_id': investigation_id,
        'task_id': task_id
    }

    command_arguments: dict = {
        'message': json.dumps(message),
        'using-brand': 'Microsoft Teams'
    }

    if channel:
        command_arguments['channel'] = channel
    elif team_member:
        command_arguments['team_member'] = team_member

    demisto.results(demisto.executeCommand('send-notification', command_arguments))
def mirror_investigation():
    """
    Update the integration context with a new or existing mirror.
    """
    mirror_type = demisto.args().get('type', 'all')

    investigation = demisto.investigation()

    if investigation.get('type') == PLAYGROUND_INVESTIGATION_TYPE:
        return_error('Can not perform this action in the playground.')

    investigation_id = investigation.get('id')

    demisto.mirrorInvestigation(investigation_id, f'{mirror_type}:FromDemisto',
                                False)

    demisto.results('Investigation mirrored to Syslog successfully.')
Beispiel #9
0
def send_message(destinations: list, entry: str, ignore_add_url: bool,
                 integration_context: dict, message: str, thread_id: str):
    """
    Sends a message to Slack.
    :param destinations: The destinations to send to.
    :param entry: A WarRoom entry to send.
    :param ignore_add_url: Do not add a Demisto URL to the message.
    :param integration_context: Current integration context.
    :param message: The message to send.
    :param thread_id: The Slack thread ID to send the message to.
    :return: The Slack send response.
    """
    if not message:
        message = '\n'
    if ignore_add_url and isinstance(ignore_add_url, str):
        ignore_add_url = bool(strtobool(ignore_add_url))
    if not ignore_add_url:
        investigation = demisto.investigation()
        server_links = demisto.demistoUrls()
        if investigation:
            if investigation.get('type') != PLAYGROUND_INVESTIGATION_TYPE:
                link = server_links.get('warRoom')
                if link:
                    if entry:
                        link += '/' + entry
                    message += '\n{} {}'.format('View it on:', link)
            else:
                link = server_links.get('server', '')
                if link:
                    message += '\n{} {}'.format('View it on:', link + '#/home')
    try:
        response = send_message_to_destinations(destinations, message,
                                                thread_id)
    except SlackApiError as e:
        if str(e).find('not_in_channel') == -1 and str(e).find(
                'channel_not_found') == -1:
            raise
        bot_id = integration_context.get('bot_id')
        if not bot_id:
            bot_id = get_bot_id()
        for dest in destinations:
            invite_users_to_conversation(dest, [bot_id])
        response = send_message_to_destinations(destinations, message,
                                                thread_id)
    return response
Beispiel #10
0
def save_file(file_name, file_content) -> str:
    """
    save attachment to the war room and return the file internal path.

    Args:
      file_name (str): The name of the file to be created.
      file_content (str/bytes): the file data.

    Returns:
      str: the file internal path

    """
    created_file = fileResult(file_name, file_content)
    file_id = created_file.get('FileID')
    attachment_internal_path = demisto.investigation().get('id') + '_' + file_id
    demisto.results(created_file)

    return attachment_internal_path
Beispiel #11
0
def main():
    res = demisto.executeCommand(
        'addEntitlement', {
            'persistent': demisto.get(demisto.args(), 'persistent'),
            'replyEntriesTag': demisto.get(demisto.args(), 'replyEntriesTag')
        })
    if isError(res[0]):
        demisto.results(res)
        sys.exit(0)
    entitlement = demisto.get(res[0], 'Contents')
    option1 = demisto.get(demisto.args(), 'option1')
    if not option1:
        option1 = 'yes'
    option2 = demisto.get(demisto.args(), 'option2')
    if not option2:
        option2 = 'no'
    entitlementString = entitlement + '@' + demisto.investigation()['id']
    if demisto.get(demisto.args(), 'task'):
        entitlementString += '|' + demisto.get(demisto.args(), 'task')
    message = '%s - Please reply to this thread with `%s` or `%s`' % (
        demisto.args()['message'], option1, option2)

    to = demisto.get(demisto.args(), 'user')
    channel = demisto.get(demisto.args(), 'channel')

    args = {
        'message':
        json.dumps({
            'message': message,
            'entitlement': entitlementString
        }),
        'ignoreAddURL':
        'true'
    }

    if to:
        args['to'] = to
    elif channel:
        args['channel'] = channel
    else:
        return_error('Either a user or a channel must be provided.')

    demisto.results(demisto.executeCommand('send-notification', args))
Beispiel #12
0
def main():
    entry_id = demisto.args()["entry_id"]
    out_format = demisto.args().get('format', 'pdf')
    all_files = demisto.args().get('all_files', 'no') == 'yes'
    # URLS
    try:
        result = demisto.getFilePath(entry_id)
        if not result:
            return_error("Couldn't find entry id: {}".format(entry_id))
        demisto.debug('going to convert: {}'.format(result))
        file_path = result['path']
        file_path_name_only = os.path.splitext(os.path.basename(file_path))[0]
        file_name = result.get('name')
        if file_name:  # remove the extension
            file_name = os.path.splitext(file_name)[0]
        with tempfile.TemporaryDirectory() as outdir:
            files = convert_file(file_path, out_format, all_files, outdir)
            if not files:
                return_error(
                    'No file result returned for convert format: {}'.format(
                        out_format))
                return
            for f in files:
                temp = demisto.uniqueFile()
                shutil.copy(f, demisto.investigation()['id'] + '_' + temp)
                name = os.path.basename(f)
                if file_name:
                    name = name.replace(file_path_name_only, file_name)
                demisto.results({
                    'Contents': '',
                    'ContentsFormat': formats['text'],
                    'Type': entryTypes['file'],
                    'File': name,
                    'FileID': temp
                })
    except subprocess.CalledProcessError as e:
        return_error("Failed converting file. Output: {}. Error: {}".format(
            e.output, e))
    except Exception as e:
        return_error(
            "Failed converting file. General exception: {}.\n\nTrace:\n{}".
            format(e, traceback.format_exc()))
Beispiel #13
0
def viper_upload(path, name, entry_id):
    """
    Performs upload of file to Viper database.
    """
    # Get absolute filepath for upload
    new_path = os.path.abspath(path)
    files = {'file': (name, open(new_path, 'rb'))}
    incident_name = demisto.get(demisto.investigation(), 'name')

    # Create some basic demisto-related tags to attach to file details on initial upload
    data = {
        'tag_list':
        entry_id + ',' + str(date.today()) + ',' + 'demisto' + ',' +
        incident_name
    }
    upload = http_post('project/default/malware/upload/',
                       None,
                       data=data,
                       files=files)
    return upload
Beispiel #14
0
def blacklist_to_entry(data, saveToContext):
    if not isinstance(data, list):
        data = [data]

    ips = [d.get("ipAddress") for d in data]
    context = {"Blacklist": ips}
    temp = demisto.uniqueFile()
    with open(demisto.investigation()['id'] + '_' + temp, 'wb') as f:
        wr = csv.writer(f, quoting=csv.QUOTE_ALL)
        for ip in ips:
            wr.writerow([ip])
    entry = {
        'HumanReadable': '',
        'Contents': ips,
        'ContentsFormat': formats['json'],
        'Type': entryTypes['file'],
        'File': "Blacklist.csv",
        'FileID': temp,
        'EntryContext': {'AbuseIPDB': createContext(context if saveToContext else None, removeNull=True)}
    }
    return entry
Beispiel #15
0
def mirror_investigation():
    """
    Updates the integration context with a new or existing mirror.
    """
    mirror_type = demisto.args().get('type', 'all')
    auto_close = demisto.args().get('autoclose', 'true')
    mirror_direction = demisto.args().get('direction', 'both')
    mirror_to = demisto.args().get('mirrorTo', 'group')
    channel_name = demisto.args().get('channelName', '')
    channel_topic = demisto.args().get('channelTopic', '')

    investigation = demisto.investigation()

    if investigation.get('type') == PLAYGROUND_INVESTIGATION_TYPE:
        return_error('Can not perform this action in playground.')

    integration_context = demisto.getIntegrationContext()

    if not integration_context or not integration_context.get('mirrors', []):
        mirrors: list = []
    else:
        mirrors = json.loads(integration_context['mirrors'])
    if not integration_context or not integration_context.get(
            'conversations', []):
        conversations: list = []
    else:
        conversations = json.loads(integration_context['conversations'])

    investigation_id = investigation.get('id')
    slack_users = []
    for user in investigation.get('users'):
        slack_user = get_user_by_name(user, integration_context)
        if not slack_user:
            demisto.results({
                'Type':
                11,  # Warning
                'Contents':
                'User {} not found in Slack'.format(user),
                'ContentsFormat':
                formats['text']
            })
        else:
            slack_users.append(slack_user)

    users_to_invite = list(map(lambda u: u.get('id'), slack_users))
    current_mirror = list(
        filter(lambda m: m['investigation_id'] == investigation_id, mirrors))
    channel_filter: list = []
    if channel_name:
        channel_filter = list(
            filter(lambda m: m['channel_name'] == channel_name, mirrors))

    if not current_mirror:
        channel_name = channel_name or 'incident-{}'.format(investigation_id)

        if not channel_filter:
            if mirror_to == 'channel':
                conversation = CHANNEL_CLIENT.channels_create(
                    name=channel_name).get('channel', {})
            else:
                conversation = CHANNEL_CLIENT.groups_create(
                    name=channel_name).get('group', {})

            conversation_name = conversation.get('name')
            conversation_id = conversation.get('id')
            conversations.append(conversation)
        else:
            mirrored_channel = channel_filter[0]
            conversation_id = mirrored_channel['channel_id']
            conversation_name = mirrored_channel['channel_name']

        mirror = {
            'channel_id': conversation_id,
            'channel_name': conversation_name,
            'investigation_id': investigation.get('id'),
            'mirror_type': mirror_type,
            'mirror_direction': mirror_direction,
            'mirror_to': mirror_to,
            'auto_close': bool(strtobool(auto_close)),
            'mirrored': False
        }
    else:
        mirror = mirrors.pop(mirrors.index(current_mirror[0]))
        conversation_id = mirror['channel_id']
        if mirror_type:
            mirror['mirror_type'] = mirror_type
        if auto_close:
            mirror['auto_close'] = bool(strtobool(auto_close))
        if mirror_direction:
            mirror['mirror_direction'] = mirror_direction
        if mirror_to and mirror['mirror_to'] != mirror_to:
            return_error('Cannot change the Slack channel type from Demisto.')
        if channel_name:
            return_error('Cannot change the Slack channel name from Demisto.')
        if channel_topic:
            return_error('Cannot change the Slack channel topic from Demisto.')
        conversation_name = mirror['channel_name']
        mirror['mirrored'] = False

    set_topic = False
    if channel_topic:
        set_topic = True
    else:
        mirror_name = 'incident-{}'.format(investigation_id)
        channel_filter = list(
            filter(lambda m: m['channel_name'] == conversation_name, mirrors))
        if 'channel_topic' in mirror:
            channel_topic = mirror['channel_topic']
        elif channel_filter:
            channel_mirror = channel_filter[0]
            channel_topic = channel_mirror['channel_topic']
        else:
            channel_topic = ''
        mirrored_investigations_ids = list(
            map(lambda m: 'incident-{}'.format(m['investigation_id']),
                channel_filter))
        if not channel_topic or channel_topic.find('incident-') != -1:
            new_topic = ', '.join(mirrored_investigations_ids + [mirror_name])
            if channel_topic != new_topic:
                channel_topic = new_topic
                set_topic = True

    if set_topic:
        CHANNEL_CLIENT.conversations_setTopic(channel=conversation_id,
                                              topic=channel_topic)
    mirror['channel_topic'] = channel_topic

    if mirror_type != 'none':
        if integration_context.get('bot_id'):
            bot_id = integration_context['bot_id']
        else:
            bot_id = get_bot_id()
        users_to_invite += [bot_id]
        invite_users_to_conversation(conversation_id, users_to_invite)

        integration_context['bot_id'] = bot_id

    mirrors.append(mirror)

    set_to_latest_integration_context('mirrors', mirrors)
    set_to_latest_integration_context('conversations', conversations)

    demisto.results('Investigation mirrored successfully, channel: {}'.format(
        conversation_name))
Beispiel #16
0
managerName = demisto.get(res[0]['Contents'][0], 'displayname')
if not managerDN:
    demisto.results('Unable to get manager email from DN - ' + managerDN)
    sys.exit(0)
allowReply = demisto.get(demisto.args(), 'allowReply')
if allowReply:
    res = demisto.executeCommand('addEntitlement', {'persistent': demisto.get(demisto.args(), 'persistent'),
                                                    'replyEntriesTag': demisto.get(demisto.args(), 'replyEntriesTag')})
    if isError(res[0]):
        demisto.results(res)
        sys.exit(0)
    entitlement = demisto.get(res[0], 'Contents')
    if not entitlement:
        demisto.results('Unable to get entitlement')
        sys.exit(0)
    subject = demisto.gets(demisto.incidents()[0], 'name') + ' - #' + demisto.investigation()['id'] + ' ' + entitlement
else:
    subject = demisto.gets(demisto.incidents()[0], 'name') + ' - #' + demisto.investigation()['id']

body = demisto.get(demisto.args(), 'body')
if not body:
    body = """\
        Hi $managerName,
        We've received the following request below from $empName. Please reply to this email with either "approve" or "deny".
        Cheers,
        Your friendly security team"""
actualBody = Template(body)
empRequest = demisto.get(demisto.args(), 'request')
if not empRequest:
    empRequest = demisto.incidents()[0]['details']
demisto.results(demisto.executeCommand('send-mail', {'to': managerEmail, 'subject': subject, 'body': textwrap.dedent(
if allowReply:
    res = demisto.executeCommand(
        'addEntitlement', {
            'persistent': demisto.get(demisto.args(), 'persistent'),
            'replyEntriesTag': demisto.get(demisto.args(), 'replyEntriesTag')
        })
    if isError(res[0]):
        demisto.results(res)
        sys.exit(0)
    entitlement = demisto.get(res[0], 'Contents')
    if not entitlement:
        demisto.results('Unable to get entitlement')
        sys.exit(0)
    subject = demisto.gets(
        demisto.incidents()[0],
        'name') + ' - #' + demisto.investigation()['id'] + ' ' + entitlement
else:
    subject = demisto.gets(demisto.incidents()[0],
                           'name') + ' - #' + demisto.investigation()['id']

body = demisto.get(demisto.args(), 'body')
if not body:
    body = """\
        Hi $managerName,
        We've received the following request below from $empName. Please reply to this email with either "approve" or "deny".
        Cheers,
        Your friendly security team"""
actualBody = Template(body)
empRequest = demisto.get(demisto.args(), 'request')
if not empRequest:
    empRequest = demisto.incidents()[0]['details']
Beispiel #18
0
def main():
    res = demisto.executeCommand(
        'addEntitlement', {
            'persistent': demisto.get(demisto.args(), 'persistent'),
            'replyEntriesTag': demisto.get(demisto.args(), 'replyEntriesTag')
        })
    if isError(res[0]):
        demisto.results(res)
        sys.exit(0)
    entitlement = demisto.get(res[0], 'Contents')
    option1 = demisto.get(demisto.args(), 'option1')
    option2 = demisto.get(demisto.args(), 'option2')
    extra_options = argToList(demisto.args().get('additionalOptions', ''))
    reply = demisto.get(demisto.args(), 'reply')
    response_type = demisto.get(demisto.args(), 'responseType')
    lifetime = demisto.get(demisto.args(), 'lifetime')
    slack_instance = demisto.get(demisto.args(), 'slackInstance')
    slack_version = demisto.args().get('slackVersion', 'SlackV3')
    try:
        parsed_date = dateparser.parse('in ' + lifetime,
                                       settings={'TIMEZONE': 'UTC'})
        assert parsed_date is not None, f'could not parse in {lifetime}'
        expiry = datetime.strftime(parsed_date, DATE_FORMAT)
    except Exception:
        parsed_date = dateparser.parse('in 1 day',
                                       settings={'TIMEZONE': 'UTC'})
        assert parsed_date is not None
        expiry = datetime.strftime(parsed_date, DATE_FORMAT)
    default_response = demisto.get(demisto.args(), 'defaultResponse')

    entitlement_string = entitlement + '@' + demisto.investigation()['id']
    if demisto.get(demisto.args(), 'task'):
        entitlement_string += '|' + demisto.get(demisto.args(), 'task')

    args = {'ignoreAddURL': 'true', 'using-brand': slack_version}
    if slack_instance:
        args.update({'using': slack_instance})
    user_options = [option1, option2]
    options = []
    if extra_options:
        user_options += extra_options
    if response_type == 'thread':
        for option in user_options:
            options.append(option.split('#')[0])
        string_options = ' or '.join(
            list(map(lambda o: '`{}`'.format(o), options)))
        message = '{} - Please reply to this thread with {}.'.format(
            demisto.args()['message'], string_options)
        args['message'] = json.dumps({
            'message': message,
            'entitlement': entitlement_string,
            'reply': reply,
            'expiry': expiry,
            'default_response': default_response
        })
    else:
        for option in user_options:
            option = option.split('#')
            button = {'text': option[0]}
            if len(option) > 1:
                style = STYLES_DICT.get(option[1])
                if style:
                    button['style'] = style
            options.append(button)
        blocks = json.dumps(
            create_blocks(demisto.args()['message'], entitlement_string,
                          options, reply))
        args['blocks'] = json.dumps({
            'blocks': blocks,
            'entitlement': entitlement_string,
            'reply': reply,
            'expiry': expiry,
            'default_response': default_response
        })
        args['message'] = demisto.args()['message']

    to = demisto.get(demisto.args(), 'user')
    channel = demisto.get(demisto.args(), 'channel')
    channel_id = demisto.get(demisto.args(), 'channel_id')

    if to:
        args['to'] = to
    elif channel_id:
        args['channel_id'] = channel_id
    elif channel:
        args['channel'] = channel
    else:
        return_error('Either a user or a channel must be provided.')

    try:
        demisto.results(demisto.executeCommand('send-notification', args))
    except ValueError as e:
        if 'Unsupported Command' in str(e):
            return_error(
                'The command is unsupported by this script. If you have SlackV2 enabled, '
                'please use SlackAsk instead.')
        else:
            return_error(
                'An error has occurred while executing the send-notification command',
                error=e)
def main() -> None:
    """
    main function, parses params and runs command functions
    """

    params = demisto.params()

    # Authentication
    api_key = params.get("apikey")

    # get the service API url
    base_url = urljoin(params["url"], "/api/1.5/")

    verify_certificate = not params.get("insecure", False)
    proxy = params.get("proxy", False)
    comment_tag = params.get("comment_tag")
    escalate_tag = params.get("escalate_tag")
    input_tag = params.get("input_tag")
    get_attachments = params.get("get_attachments", False)
    close_incident = params.get("close_incident", False)
    reopen_incident = params.get("reopen_incident", False)
    reopen_group = params.get("reopen_group", "Default")

    demisto.debug(f"Command being called is {demisto.command()}")
    try:

        client = Client(
            base_url=base_url,
            verify_certificate=verify_certificate,
            api_key=api_key,
            proxy=proxy,
            comment_tag=comment_tag,
            escalate_tag=escalate_tag,
            input_tag=input_tag,
            get_attachments=get_attachments,
            close_incident=close_incident,
            reopen_incident=reopen_incident,
            reopen_group=reopen_group,
        )

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

        elif demisto.command() == "fetch-incidents":
            max_fetch = params.get("max_fetch", 100)
            last_run = demisto.getLastRun()
            first_fetch_timestamp = params.get("first_fetch_timestamp",
                                               "7 days").strip()
            mirror_direction = MIRROR_DIRECTION.get(
                demisto.params().get("mirror_direction", "None"), None)
            integration_instance = demisto.integrationInstance()
            incidents, new_last_run = fetch_incidents(
                client=client,
                last_run=last_run,
                max_fetch=max_fetch,
                first_fetch_time=first_fetch_timestamp,
                mirror_direction=mirror_direction,
                integration_instance=integration_instance,
            )
            demisto.setLastRun(new_last_run)
            demisto.incidents(incidents)

        elif demisto.command() == "get-mapping-fields":
            result = get_mapping_fields()
            return_results(result)

        elif demisto.command() == "get-remote-data":
            investigation = demisto.investigation()
            result = get_remote_data(client, investigation, demisto.args())
            return_results(result)

        elif demisto.command() == "get-modified-remote-data":
            result = get_modified_remote_data(client, demisto.args())
            return_results(result)

        elif demisto.command() == "update-remote-system":
            investigation = demisto.investigation()
            result = update_remote_system(client, investigation,
                                          demisto.args())
            return_results(result)

        elif demisto.command() == "ztap-get-alert-entries":
            result = ztap_get_alert_entries(client, demisto.args())
            return_results(result)

    # Log exceptions and return errors
    except Exception as e:
        demisto.error(traceback.format_exc())  # print the traceback
        return_error(
            f"Failed to execute {demisto.command()} command.\nError:\n{str(e)}"
        )
Beispiel #20
0
def main():
    res = demisto.executeCommand(
        'addEntitlement', {
            'persistent': demisto.get(demisto.args(), 'persistent'),
            'replyEntriesTag': demisto.get(demisto.args(), 'replyEntriesTag')
        })
    if isError(res[0]):
        demisto.results(res)
        sys.exit(0)
    entitlement = demisto.get(res[0], 'Contents')
    option1 = demisto.get(demisto.args(), 'option1')
    option2 = demisto.get(demisto.args(), 'option2')
    extra_options = argToList(demisto.args().get('additionalOptions', ''))
    reply = demisto.get(demisto.args(), 'reply')
    response_type = demisto.get(demisto.args(), 'responseType')
    lifetime = demisto.get(demisto.args(), 'lifetime')
    try:
        expiry = datetime.strftime(
            dateparser.parse('in ' + lifetime, settings={'TIMEZONE': 'UTC'}),
            DATE_FORMAT)
    except Exception:
        expiry = datetime.strftime(
            dateparser.parse('in 1 day', settings={'TIMEZONE': 'UTC'}),
            DATE_FORMAT)
    default_response = demisto.get(demisto.args(), 'defaultResponse')

    entitlement_string = entitlement + '@' + demisto.investigation()['id']
    if demisto.get(demisto.args(), 'task'):
        entitlement_string += '|' + demisto.get(demisto.args(), 'task')

    args = {'ignoreAddURL': 'true'}
    user_options = [option1, option2]
    options = []
    if extra_options:
        user_options += extra_options
    if response_type == 'thread':
        for option in user_options:
            options.append(option.split('#')[0])
        string_options = ' or '.join(
            list(map(lambda o: '`{}`'.format(o), options)))
        message = '{} - Please reply to this thread with {}.'.format(
            demisto.args()['message'], string_options)
        args['message'] = json.dumps({
            'message': message,
            'entitlement': entitlement_string,
            'reply': reply,
            'expiry': expiry,
            'default_response': default_response
        })
    else:
        for option in user_options:
            option = option.split('#')
            button = {'text': option[0]}
            if len(option) > 1:
                style = STYLES_DICT.get(option[1])
                if style:
                    button['style'] = style
            options.append(button)
        blocks = json.dumps(
            create_blocks(demisto.args()['message'], entitlement_string,
                          options, reply))
        args['blocks'] = json.dumps({
            'blocks': blocks,
            'entitlement': entitlement_string,
            'reply': reply,
            'expiry': expiry,
            'default_response': default_response
        })
        args['message'] = demisto.args()['message']

    to = demisto.get(demisto.args(), 'user')
    channel = demisto.get(demisto.args(), 'channel')

    if to:
        args['to'] = to
    elif channel:
        args['channel'] = channel
    else:
        return_error('Either a user or a channel must be provided.')

    demisto.results(demisto.executeCommand('send-notification', args))
def get_investigation_id():
    investigation = demisto.investigation()
    investigation_id = investigation.get('id')

    return investigation_id
Beispiel #22
0
    })

if isError(res[0]):
    demisto.results(res)
    sys.exit(0)
entitlement = demisto.get(res[0], 'Contents')

option1 = demisto.get(demisto.args(), 'option1')

if not option1:
    option1 = 'yes'
option2 = demisto.get(demisto.args(), 'option2')

if not option2:
    option2 = 'no'
entitlementString = entitlement + '@' + demisto.investigation()['id']

if demisto.get(demisto.args(), 'task'):
    entitlementString += '|' + demisto.get(demisto.args(), 'task')
message = '%s - Please reply `%s %s` or `%s %s`' % (demisto.args()['message'],
                                                    option1, entitlementString,
                                                    option2, entitlementString)

demisto.results(
    demisto.executeCommand(
        'send-notification', {
            'to': demisto.get(demisto.args(), 'user'),
            'message': message,
            'ignoreAddURL': 'true',
            'using-brand': 'mattermost'
        }))