יצירת לוגיקה של מחבר

נתמכים ב:

במאמר הזה מוסבר איך ליצור מחבר חדש בסביבת הפיתוח המשולבת (IDE) על ידי יצירת שילוב ואז קישור של מחבר אליו.

יצירת שילוב של מחבר אימייל

כדי ליצור שילוב של מחבר אימייל, פועלים לפי השלבים הבאים:

  1. בחלון Automation > IDE, לוחצים על Add כדי להוסיף פריט IDE חדש. אם אתם משתמשים בפלטפורמה של SOAR בלבד, עוברים אל Response > IDE.
  2. בוחרים באפשרות Integration (שילוב) ונותנים לשילוב את השם Email Connector.
  3. לוחצים על יצירה. השילוב מופיע בסרגל הצד עם סמל ברירת מחדל.
  4. לוחצים על more_vert הגדרת שילוב בהתאמה אישית ומגדירים את ההגדרות הבאות:

    • תיאור
    • סמל
    • יחסי תלות ב-Python
    • פרמטרים של שילוב
  5. לוחצים על Save.

יצירת מחבר אימייל

כדי ליצור מחבר לאימייל:

  1. בחלון Automation > IDE, לוחצים על Add כדי להוסיף פריט IDE חדש. אם אתם משתמשים בפלטפורמה של SOAR בלבד, עוברים אל Response > IDE.
  2. בוחרים באפשרות מחבר ונותנים למחבר את השם My Email Connector.
  3. ברשימה, בוחרים את השילוב Email Connector כדי לשייך את המחבר לשילוב.
  4. לוחצים על יצירה.

הגדרת הפרמטרים של המחבר

אחרי שיוצרים את המחבר, מגדירים את הפרמטרים שלו:

  1. מגדירים את הפרמטרים של המחבר לפי הטבלה הבאה:

    פרמטר תיאור סוג
    Username חובה. שם המשתמש ב-IMAP ‏(Internet Message Access Protocol). כתובת האימייל שממנה המחבר מושך אימיילים לפלטפורמת Google SecOps. ערך ברירת המחדל הוא email@gmail.com. string
    Password חובה. סיסמת IMAP לכתובת האימייל שבה המחבר משתמש כדי למשוך אימיילים לפלטפורמת Google SecOps. 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"]) וממירים אותו לראשית זמן יוניקס (Unix epoch) באמצעות פונקציות בסיסיות של Google SecOps:

    string_to_datetime = convert_string_to_datetime(datetime_email_message)
    datetime_in_unix_time = convert_datetime_to_unix_time(string_to_datetime)
    
  4. מחפשים כתובות URL בגוף ההודעה של הודעת האימייל באמצעות הפונקציה find_url_in_email_message_body(siemplify, email_messages_data_list). אם נמצאה כתובת URL, אפשר להשתמש בשילובים אחרים בפלייבוק כדי לבדוק אם היא זדונית:

    found_urls_in_email_body = find_url_in_email_message_body(
        siemplify, email_messages_data_list
    )
    
  5. מחלצים את המזהה הייחודי של כל הודעת אימייל ומקצים אותו למשתנה 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. בוחרים את תיקיית האימייל שבה רוצים לבדוק אם יש הודעות שלא נקראו. בדוגמה הזו, האימיילים נשלפים מהתיקייה Inbox (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
    

חיפוש כתובות URL בתוכן האימייל

הפונקציה find_url_in_email_message_body סורקת את תוכן האימייל כדי למצוא כתובות URL:

  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. טוענים את המטען הייעודי (payload) של גוף ההודעה באמצעות email_message_body = part.get_payload() ומחפשים כתובות URL באמצעות הביטוי הרגולרי URLS_REGEX:

    URLS_REGEX = r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
    
  3. חלץ את כתובות ה-URL התואמות מתוכן האימייל והחזר את הרשימה:

    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.