建構連接器邏輯

支援的服務:

本文說明如何在整合式開發環境 (IDE) 中建立整合,然後連結連接器,藉此建構新的連接器。

建立電子郵件連接器整合

如要建立電子郵件連接器整合,請按照下列步驟操作:

  1. 在「自動化動作」>「IDE」視窗中,按一下 「新增」圖示,新增 IDE 項目。如果使用的是 SOAR 專用平台,請依序前往「Response」>「IDE」。
  2. 選取「整合」,並將整合命名為 Email Connector。
  3. 點選「建立」。整合項目會顯示在側欄中,並附有預設圖示。
  4. 按一下「more_vert」more_vert設定自訂整合,然後定義下列設定:

    • 說明
    • 圖示
    • Python 依附元件
    • 整合參數
  5. 按一下「儲存」。

建立電子郵件連接器

如要建立電子郵件連接器,請按照下列步驟操作:

  1. 在「自動化動作」>「IDE」視窗中,按一下 「新增」圖示,新增 IDE 項目。如果使用的是 SOAR 專用平台,請依序前往「Response」>「IDE」。
  2. 選取「連接器」,並將連接器命名為 My Email Connector。
  3. 在清單中選取「Email Connector」整合項目,將連接器與整合項目建立關聯。
  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) 函式,在電子郵件訊息內文中搜尋網址。如果找到網址,您可以使用應對手冊中的其他整合項目,檢查該網址是否為惡意網址:

    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 專業人員尋求解答。