构建连接器逻辑

支持的国家/地区:

本文档介绍了如何在集成开发环境 (IDE) 中构建新连接器,方法是先创建集成,然后将连接器关联到该集成。

创建电子邮件连接器集成

如需创建电子邮件连接器集成,请按照以下步骤操作:

  1. 在自动化 > IDE 窗口中,点击 添加以添加新的 IDE 项。如果您使用的是仅限 SOAR 的平台,请前往响应 > IDE。
  2. 选择集成,并将集成命名为 Email Connector。
  3. 点击创建。该集成会显示在边栏中,并带有默认图标。
  4. 点击 more_vert 配置自定义集成,然后指定以下设置:

    • 说明
    • Icon
    • Python 依赖项
    • 集成参数
  5. 点击保存。

创建电子邮件连接器

如需创建电子邮件连接器,请按以下步骤操作:

  1. 在自动化 > IDE 窗口中,点击 添加以添加新的 IDE 项。如果您使用的是仅限 SOAR 的平台,请前往响应 > IDE。
  2. 选择连接器,并将连接器命名为 My Email Connector。
  3. 在列表中,选择电子邮件连接器集成,将连接器与集成相关联。
  4. 点击创建。

设置连接器参数

创建连接器后,设置连接器参数:

  1. 根据下表配置连接器参数:

    参数 说明 类型
    Username 必需。互联网邮件访问协议 (IMAP) 用户名。连接器从中将电子邮件拉取到 Google SecOps 平台的邮箱。默认值为 email@gmail.com。 string
    Password 必需。连接器用于将邮件拉取到 Google SecOps 平台中的邮箱的 IMAP 密码。 password
    IMAP Port 必需。IMAP 用于从远程服务器访问电子邮件的网络端口(例如,默认值为 993)。 int
    IMAP Server Address 必需。IMAP 账号的接收邮件服务器(例如,默认值为 imap.gmail.com)。 string
    Folder to check for emails 可选。仅从指定文件夹(例如,默认值为 Inbox)中提取电子邮件。 inbox
  2. 输入以下字段详细信息:

    • 商品字段名称 (device_product):确定要分配给提醒商品名称的原始字段值。在代码中,此字段定义为 Mail (PRODUCT):

      event["device_product"] = PRODUCT  # The PRODUCT constant is "Mail"
      
    • 事件字段名称 (event_name):确定要分配给事件类型字段的原始字段值。在代码中,此字段定义为 Suspicious email:

      event["event_name"] = "Suspicious email"
      

修改电子邮件连接器

如需修改电子邮件连接器的代码和参数,请按以下步骤操作:

  1. 复制为 My Email Connector 创建的以下代码,并将其粘贴到 IDE 中:

    from SiemplifyConnectors import SiemplifyConnectorExecution
    from SiemplifyConnectorsDataModel import AlertInfo
    from SiemplifyUtils import (
        output_handler,
        convert_datetime_to_unix_time,
        convert_string_to_datetime,
    )
    import email
    import imaplib
    import re
    import sys
    
    # CONSTANTS
    CONNECTOR_NAME = "Mail"
    VENDOR = "Mail"
    PRODUCT = "Mail"
    DEFAULT_PRIORITY = 60  # Default is Medium
    RULE_GENERATOR_EXAMPLE = "Mail"
    DEFAULT_FOLDER_TO_CHECK_INBOX = "inbox"
    DEFAULT_MESSAGES_TO_READ_UNSEEN = "UNSEEN"
    URLS_REGEX = r"(?i)\b(?:http(?:s)?:\/\/)?(?:www\.)?[a-zA-Z0-9:%_\+~#=][a-zA-Z0-9:%\._\+~#=]{1,255}\.[a-z]{2,6}\b(?:[-a-zA-Z0-9@:%_\+.~#?&//=]*)"
    
    def create_alert(
        siemplify, alert_id, email_message_data, datetime_in_unix_time, created_event
    ):
        """Returns an alert which is one event that contains one unread email message."""
        siemplify.LOGGER.info(f"Started processing Alert {alert_id}")
    
        alert_info = AlertInfo()
    
        # Initializes alert_info
        # Each alert needs a unique ID; otherwise, it won't create a case with the same alert ID.
        alert_info.display_id = f"{alert_id}"
        # By default, ticket_id = display_id. If the external alert ID differs from display_id,
        # you can save the original external alert ID in the "ticket_id" field.
        alert_info.ticket_id = f"{alert_id}"
        alert_info.name = email_message_data["Subject"]
        # The name of the SIEM rule that causes the creation of the alert.
        alert_info.rule_generator = RULE_GENERATOR_EXAMPLE
        # Time should be saved in UnixTime using SiemplifyUtils.convert_datetime_to_unix_time
        # or SiemplifyUtils.convert_string_to_datetime.
        alert_info.start_time = datetime_in_unix_time
        alert_info.end_time = datetime_in_unix_time
        # Priority values: Informative = -1, Low = 40, Medium = 60, High = 80, Critical = 100.
        alert_info.priority = 60
        # Fetched from the original alert. If built manually, state the source vendor (for example, Microsoft, McAfee).
        alert_info.device_vendor = VENDOR
        # Fetched from the original alert. If built manually, state the source product (for example, ActiveDirectory, AntiVirus).
        alert_info.device_product = PRODUCT
    
        siemplify.LOGGER.info(f"Events creating started for alert {alert_id}")
        try:
            if created_event is not None:
                alert_info.events.append(created_event)
                siemplify.LOGGER.info(f"Added Event {alert_id} to Alert {alert_id}")
        # Raise an exception if failed to process the event
        except Exception as e:
            siemplify.LOGGER.error(f"Failed to process event {alert_id}")
            siemplify.LOGGER.exception(e)
        return alert_info
    
    def create_event(
        siemplify,
        alert_id,
        email_message_data,
        all_found_url_in_emails_body_list,
        datetime_in_unix_time,
    ):
        """Returns the digested data of a single unread email."""
        siemplify.LOGGER.info(
            f"--- Started processing Event: alert_id: {alert_id} | event_id: {alert_id}"
        )
        event = {}
        # Time should be saved in UnixTime using SiemplifyUtils.convert_datetime_to_unix_time
        # or SiemplifyUtils.convert_string_to_datetime.
        event["StartTime"] = datetime_in_unix_time
        event["EndTime"] = datetime_in_unix_time
        event["event_name"] = "Suspicious email"
        # "device_product" is the field name that describes the product the event originated from.
        event["device_product"] = PRODUCT
        event["Subject"] = email_message_data["Subject"]
        event["SourceUserName"] = email_message_data["From"]
        event["DestinationUserName"] = email_message_data["To"]
        event["found_url"] = ",".join(all_found_url_in_emails_body_list)
        siemplify.LOGGER.info(
            f"---Finished processing Event: alert_id: {alert_id} | event_id: {alert_id}"
        )
        return event
    
    def find_url_in_email_message_body(siemplify, email_messages_data_list):
        """Search for a URL in the email body."""
        all_found_url_in_emails_body_list = []
        for message in email_messages_data_list:
            for part in message.walk():
                if part.get_content_maintype() == "text\\plain":
                    continue
                email_message_body = part.get_payload()
                all_found_urls = re.findall(URLS_REGEX, str(email_message_body))
                for url in all_found_urls:
                    if url not in all_found_url_in_emails_body_list:
                        all_found_url_in_emails_body_list.append(url)
        return all_found_url_in_emails_body_list
    
    def get_email_messages_data(
        imap_host, imap_port, username, password, folder_to_check
    ):
        """Returns all unread email messages."""
        email_messages_data_list = []
    
        # Log in to email using the imaplib module
        mail = imaplib.IMAP4_SSL(imap_host, imap_port)
        mail.login(username, password)
    
        # Determine the default email folder to pull emails from ("inbox")
        if folder_to_check is None:
            folder_to_check = DEFAULT_FOLDER_TO_CHECK_INBOX
    
        # Select the email folder to pull the data from
        mail.select(folder_to_check)
    
        # Store the email message data
        result, data = mail.search(None, DEFAULT_MESSAGES_TO_READ_UNSEEN)
    
        # If several emails are collected in the cycle, split each
        # email message into a separate item in chosen_mailbox_items_list
        if len(data) > 0:
            chosen_mailbox_items_list = data[0].split()
            # Iterate through each email message and append to email_messages_data_list
            for item in chosen_mailbox_items_list:
                typ, email_data = mail.fetch(item, "(RFC 822)")
                # Decode from binary string to string
                raw_email = email_data[0][1].decode("utf-8")
                # Convert the email data into an email object
                email_message = email.message_from_string(raw_email)
                # Append the email message data to email_messages_data_list
                email_messages_data_list.append(email_message)
        return email_messages_data_list
    
    @output_handler
    def main(is_test_run):
        # The main output of each connector run that contains the alerts data
        alerts = []
        # Siemplify main SDK wrapper
        siemplify = SiemplifyConnectorExecution()
        siemplify.script_name = CONNECTOR_NAME
    
        # In case of running a test
        if is_test_run:
            siemplify.LOGGER.info(
                'This is an "IDE Play Button"\\"Run Connector once" test run'
            )
    
        # Extract the connector's parameters
        username = siemplify.extract_connector_param(param_name="Username")
        password = siemplify.extract_connector_param(param_name="Password")
        imap_host = siemplify.extract_connector_param(
            param_name="IMAP Server Address"
        )
        imap_port = siemplify.extract_connector_param(param_name="IMAP Port")
        folder_to_check = siemplify.extract_connector_param(
            param_name="Folder to check for emails"
        )
    
        # Get the digested email message data
        email_messages_data_list = get_email_messages_data(
            imap_host, imap_port, username, password, folder_to_check
        )
        # If email_messages_data_list is not empty
        if len(email_messages_data_list) > 0:
            for message in email_messages_data_list:
                # Convert the email message datetime from string to Unix time using SiemplifyUtils functions
                datetime_email_message = message["Date"]
                string_to_datetime = convert_string_to_datetime(
                    datetime_email_message
                )
                datetime_in_unix_time = convert_datetime_to_unix_time(
                    string_to_datetime
                )
                found_urls_in_email_body = find_url_in_email_message_body(
                    siemplify, email_messages_data_list
                )
                # Get the unique ID of each email message and remove the suffix "@mail.gmail.com"
                # from the Message-ID. Each alert ID can be ingested into the system only once.
                alert_id = message["Message-ID"].replace("@mail.gmail.com", "")
                # Create the event by calling the create_event() function
                created_event = create_event(
                    siemplify,
                    alert_id,
                    message,
                    found_urls_in_email_body,
                    datetime_in_unix_time,
                )
                # Create the alert by calling the create_alert() function
                created_alert = create_alert(
                    siemplify,
                    alert_id,
                    message,
                    datetime_in_unix_time,
                    created_event,
                )
                # Check that created_alert is not None
                if created_alert is not None:
                    alerts.append(created_alert)
                    siemplify.LOGGER.info(
                        f"Added Alert {alert_id} to package results"
                    )
        # If the inbox for the user has no unread emails
        else:
            siemplify.LOGGER.info(
                f"The inbox for user {username} has no unread emails"
            )
        # Return all the created alerts to the Cases module
        siemplify.return_package(alerts)
    
    if __name__ == "__main__":
        # Connectors run in iterations. The interval is configurable from the Connectors UI.
        is_test_run = not (len(sys.argv) < 2 or sys.argv[1] == "True")
        main(is_test_run)
    
  2. 复制连接器的代码后,请查看所需的模块导入和 main 函数。以下各部分详细介绍了从 main 调用的每个函数。

相关导入

Python 模块包含一组已定义和实现的函数、类或变量。 如需实现连接器函数,请将以下模块导入脚本:

# Responsible for executing the connector
from SiemplifyConnectors import SiemplifyConnectorExecution

# Data model that contains the AlertInfo class
from SiemplifyConnectorsDataModel import AlertInfo

# Utility functions for output handling and time conversion
from SiemplifyUtils import (
    output_handler,
    convert_datetime_to_unix_time,
    convert_string_to_datetime,
)
import email
import imaplib
import re
import sys

主函数

main 函数是脚本的入口点。Python 解释器会按顺序运行代码,并调用脚本中定义的每个函数:

  1. 提取连接器参数。使用 siemplify.extract_connector_param 函数提取连接器的每个已配置参数(username、password、imap_host、imap_port 和 folder_to_check):

    # Extract the connector's parameters
    username = siemplify.extract_connector_param(param_name="Username")
    password = siemplify.extract_connector_param(param_name="Password")
    imap_host = siemplify.extract_connector_param(param_name="IMAP Server Address")
    imap_port = siemplify.extract_connector_param(param_name="IMAP Port")
    folder_to_check = siemplify.extract_connector_param(
        param_name="Folder to check for emails"
    )
    
  2. 使用 get_email_messages_data(imap_host, imap_port, username, password, folder_to_check) 函数从这些未读邮件中收集所有信息:

    # Get the digested email message data
    email_messages_data_list = get_email_messages_data(
        imap_host, imap_port, username, password, folder_to_check
    )
    
  3. 确认已收集电子邮件信息,并遍历每封电子邮件:

    # If email_messages_data_list is not empty
    if len(email_messages_data_list) > 0:
        for message in email_messages_data_list:
            # Convert the email message datetime from string to Unix time
    

    提取邮件日期 (datetime_email_message = message["Date"]),并使用 Google SecOps 实用函数将其转换为 Unix 纪元时间:

    string_to_datetime = convert_string_to_datetime(datetime_email_message)
    datetime_in_unix_time = convert_datetime_to_unix_time(string_to_datetime)
    
  4. 使用 find_url_in_email_message_body(siemplify, email_messages_data_list) 函数在电子邮件正文中搜索网址。如果找到网址,您可以使用 playbook 中的其他集成来检查该网址是否为恶意网址:

    found_urls_in_email_body = find_url_in_email_message_body(
        siemplify, email_messages_data_list
    )
    
  5. 提取每封电子邮件的唯一 ID,并将其分配给 alert_id 变量:

    # Get the unique ID of each email message and remove the suffix "@mail.gmail.com"
    # from the Message-ID. Each alert ID can be ingested into the system only once.
    alert_id = message["Message-ID"].replace("@mail.gmail.com", "")
    
  6. 提取将提醒注入 Google SecOps 平台所需的所有详细信息后,创建事件和提醒:

    # Create the event by calling the create_event() function
    created_event = create_event(
        siemplify,
        alert_id,
        message,
        found_urls_in_email_body,
        datetime_in_unix_time,
    )
    # Create the alert by calling the create_alert() function
    created_alert = create_alert(
        siemplify, alert_id, message, datetime_in_unix_time, created_event
    )
    
  7. 验证创建的提醒并将其添加到 alerts 列表中:

    # Check that created_alert is not None
    if created_alert is not None:
        alerts.append(created_alert)
        siemplify.LOGGER.info(f"Added Alert {alert_id} to package results")
    
  8. 处理用户收件箱中没有未读电子邮件的情况:

    else:
        siemplify.LOGGER.info(
            f"The inbox for user {username} has no unread emails"
        )
    
  9. 将 alerts 列表返回给系统,以便每个提醒在案例队列中显示为一个案例:

    # Return all the created alerts to the Cases module
    siemplify.return_package(alerts)
    
  10. 按照为连接器配置的时间间隔运行 main 函数:

    if __name__ == "__main__":
        # Connectors run in iterations. The interval is configurable from the Connectors UI.
        is_test_run = not (len(sys.argv) < 2 or sys.argv[1] == "True")
        main(is_test_run)
    

获取未读邮件

get_email_messages_data 函数使用 imaplib 和 email 模块连接到电子邮件服务器,检索电子邮件详细信息,并返回包含未读电子邮件的列表:

  1. 定义 get_email_messages_data(imap_host, imap_port, username, password, folder_to_check) 函数:

    def get_email_messages_data(
        imap_host, imap_port, username, password, folder_to_check
    ):
        """Returns all unread email messages."""
        email_messages_data_list = []
    
  2. 使用 imaplib 模块连接到电子邮件服务器:

    # Log in to email using the imaplib module
    mail = imaplib.IMAP4_SSL(imap_host, imap_port)
    mail.login(username, password)
    
  3. 确定要检查未读邮件的电子邮件文件夹。在此示例中,系统会从收件箱文件夹 (DEFAULT_FOLDER_TO_CHECK_INBOX = "inbox") 中提取电子邮件:

    # Determine the default email folder to pull emails from ("inbox")
    if folder_to_check is None:
        folder_to_check = DEFAULT_FOLDER_TO_CHECK_INBOX
    
    # Select the email folder to pull the data from
    mail.select(folder_to_check)
    
  4. 收集所有未读消息 (DEFAULT_MESSAGES_TO_READ_UNSEEN = "UNSEEN") 并将数据转换为列表:

    # Store the email message data
    result, data = mail.search(None, DEFAULT_MESSAGES_TO_READ_UNSEEN)
    
    # If several emails are collected in the cycle, split each
    # email message into a separate item in chosen_mailbox_items_list
    if len(data) > 0:
        chosen_mailbox_items_list = data[0].split()
        # Iterate through each email message and append to email_messages_data_list
        for item in chosen_mailbox_items_list:
            typ, email_data = mail.fetch(item, "(RFC 822)")
            # Decode from binary string to string
            raw_email = email_data[0][1].decode("utf-8")
            # Convert the email data into an email object
            email_message = email.message_from_string(raw_email)
            # Append the email message data to email_messages_data_list
            email_messages_data_list.append(email_message)
    return email_messages_data_list
    

创建事件

create_event 函数通过将每个电子邮件消息组件与相应的事件字段相关联来创建事件:

  1. 定义 create_event(siemplify, alert_id, email_message_data, all_found_url_in_emails_body_list, datetime_in_unix_time) 函数:

    def create_event(
        siemplify,
        alert_id,
        email_message_data,
        all_found_url_in_emails_body_list,
        datetime_in_unix_time,
    ):
        """Returns the digested data of a single unread email."""
        siemplify.LOGGER.info(
            f"--- Started processing Event: alert_id: {alert_id} | event_id: {alert_id}"
        )
    
  2. 为事件字段创建字典。必填字段包括 event["StartTime"]、event["EndTime"]、event["event_name"] 和 event["device_product"]:

    event = {}
    # Time should be saved in UnixTime using SiemplifyUtils.convert_datetime_to_unix_time
    # or SiemplifyUtils.convert_string_to_datetime.
    event["StartTime"] = datetime_in_unix_time
    event["EndTime"] = datetime_in_unix_time
    event["event_name"] = "Suspicious email"
    # "device_product" is the field name that describes the product the event originated from.
    event["device_product"] = PRODUCT
    event["Subject"] = email_message_data["Subject"]
    event["SourceUserName"] = email_message_data["From"]
    event["DestinationUserName"] = email_message_data["To"]
    event["found_url"] = ",".join(all_found_url_in_emails_body_list)
    siemplify.LOGGER.info(
        f"---Finished processing Event: alert_id: {alert_id} | event_id: {alert_id}"
    )
    return event
    

每个提醒都包含一个或多个事件。在此示例中,一条提醒包含一个与一封电子邮件对应的事件。创建事件后,创建包含事件信息的提醒。

创建提醒并初始化提醒信息字段

create_alert 函数会创建提醒。每个提醒都包含一个或多个事件;在本例中,每个提醒都包含一个代表单封电子邮件的事件:

  1. 定义 create_alert 函数:

    def create_alert(
        siemplify, alert_id, email_message_data, datetime_in_unix_time, created_event
    ):
        """Returns an alert which is one event that contains one unread email message."""
        siemplify.LOGGER.info(f"-------------- Started processing Alert {alert_id}")
        alert_info = AlertInfo()
    
  2. 初始化 alert_info 字段:

    # Initialize the alert_info fields
    alert_info.display_id = f"{alert_id}"
    alert_info.ticket_id = f"{alert_id}"
    alert_info.name = email_message_data["Subject"]
    alert_info.rule_generator = RULE_GENERATOR_EXAMPLE
    alert_info.start_time = datetime_in_unix_time
    alert_info.end_time = datetime_in_unix_time
    alert_info.device_vendor = VENDOR
    alert_info.device_product = PRODUCT
    
  3. 验证事件并将其附加到 alert_info.events:

    siemplify.LOGGER.info(f"Events creating started for alert {alert_id}")
    try:
        if created_event is not None:
            alert_info.events.append(created_event)
            siemplify.LOGGER.info(f"Added Event {alert_id} to Alert {alert_id}")
    # Raise an exception if failed to process the event
    except Exception as e:
        siemplify.LOGGER.error(f"Failed to process event {alert_id}")
        siemplify.LOGGER.exception(e)
    return alert_info
    

在邮件正文中查找网址

find_url_in_email_message_body 函数会扫描邮件正文中的网址:

  1. 对于每封电子邮件,找到邮件正文中包含纯文本内容的部分:

    def find_url_in_email_message_body(siemplify, email_messages_data_list):
        """Search for a URL in the email body."""
        all_found_url_in_emails_body_list = []
        for message in email_messages_data_list:
            for part in message.walk():
                if part.get_content_maintype() == "text\\plain":
                    continue
    
  2. 使用 email_message_body = part.get_payload() 加载邮件正文载荷,并使用 URLS_REGEX 正则表达式搜索网址:

    URLS_REGEX = r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
    
  3. 从邮件正文中提取匹配的网址并返回列表:

    email_message_body = part.get_payload()
    all_found_urls = re.findall(URLS_REGEX, str(email_message_body))
    for url in all_found_urls:
        if url not in all_found_url_in_emails_body_list:
            all_found_url_in_emails_body_list.append(url)
    siemplify.LOGGER.info(f"The URL found: {all_found_url_in_emails_body_list}")
    return all_found_url_in_emails_body_list
    

查看连接器代码后,您可以配置连接器,以将所选 Gmail 收件箱中的案例注入到平台中。

需要更多帮助?获得社区成员和 Google SecOps 专业人士的解答。