Connector-Logik erstellen
E‑Mail-Connector-Integration erstellen
So erstellen Sie eine E-Mail-Connector-Integration:
- Klicke im Fenster Automatisierung > IDE auf Hinzufügen, um ein neues IDE-Element hinzuzufügen. Wenn Sie eine reine SOAR-Plattform verwenden, rufen Sie Antwort > IDE auf.
- Wählen Sie Integration aus und nennen Sie die Integration
Email Connector. - Klicken Sie auf Erstellen. Die Integration wird in der Seitenleiste mit einem Standardsymbol angezeigt.
Klicken Sie auf more_vert Benutzerdefinierte Integration konfigurieren und legen Sie die folgenden Einstellungen fest:
- Beschreibung
- Symbol
- Python-Abhängigkeiten
- Integrationsparameter
Klicken Sie auf Speichern.
E‑Mail-Connector erstellen
So erstellen Sie einen E‑Mail-Connector:
- Klicke im Fenster Automatisierung > IDE auf Hinzufügen, um ein neues IDE-Element hinzuzufügen. Wenn Sie eine reine SOAR-Plattform verwenden, rufen Sie Antwort > IDE auf.
- Wählen Sie Connector aus und nennen Sie den Connector
My Email Connector. - Wählen Sie in der Liste die Integration Email Connector aus, um den Connector mit der Integration zu verknüpfen.
- Klicken Sie auf Erstellen.
Connector-Parameter festlegen
Legen Sie nach dem Erstellen des Connectors die Connector-Parameter fest:
Konfigurieren Sie die Connector-Parameter gemäß der folgenden Tabelle:
Parameter Beschreibung Typ UsernameErforderlich. IMAP-Nutzername (Internet Message Access Protocol). Die E‑Mail-Adresse, von der der Connector E‑Mails in die Google SecOps-Plattform abruft. Der Standardwert ist email@gmail.com.stringPasswordErforderlich. IMAP-Passwort für die E‑Mail-Adresse, die der Connector verwendet, um E‑Mails in die Google SecOps-Plattform zu übertragen. passwordIMAP PortErforderlich. Der Netzwerkport, der von IMAP für den Zugriff auf E‑Mails von einem Remote-Server verwendet wird (z. B. 993als Standardwert).intIMAP Server AddressErforderlich. Der Eingangsserver für ein IMAP-Konto (z. B. imap.gmail.comals Standardwert).stringFolder to check for emailsOptional: Ruft nur E‑Mails aus dem angegebenen Ordner ab (z. B. Inboxals Standardwert).inboxGeben Sie die folgenden Felddetails ein:
Produktfeldname (
device_product): Bestimmt den Rohfeldwert, der dem Produktnamen der Benachrichtigung zugewiesen werden soll. Im Code ist dieses Feld alsMail(PRODUCT) definiert:event["device_product"] = PRODUCT # The PRODUCT constant is "Mail"Ereignisfeldname (
event_name): Bestimmt den Rohfeldwert, der dem Ereignistypfeld zugewiesen werden soll. Im Code wird dieses Feld alsSuspicious emaildefiniert:event["event_name"] = "Suspicious email"
E‑Mail-Connector bearbeiten
So bearbeiten Sie den Code und die Parameter für den E-Mail-Connector:
Kopieren Sie den folgenden Code, der für My Email Connector erstellt wurde, und fügen Sie ihn in die IDE ein:
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)Nachdem Sie den Code des Connectors kopiert haben, prüfen Sie die erforderlichen Modulimporte und die Funktion
main. Jede vonmainaufgerufene Funktion wird in den folgenden Abschnitten ausführlich beschrieben.
Relevante Importe
Ein Python-Modul enthält eine Reihe von Funktionen, Klassen oder Variablen, die definiert und implementiert sind. Importieren Sie die folgenden Module in das Skript, um die Connector-Funktionen zu implementieren:
# 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
Hauptfunktion
Die Funktion main ist der Einstiegspunkt des Scripts. Der Python-Interpreter führt den Code sequenziell aus und ruft jede im Skript definierte Funktion auf:
Extrahieren Sie die Connector-Parameter. Verwenden Sie die Funktion
siemplify.extract_connector_param, um die einzelnen konfigurierten Parameter für den Connector (username,password,imap_host,imap_portundfolder_to_check) zu extrahieren:# 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" )Verwenden Sie die Funktion
get_email_messages_data(imap_host, imap_port, username, password, folder_to_check), um alle Informationen aus den ungelesenen E‑Mails zu erfassen:# Get the digested email message data email_messages_data_list = get_email_messages_data( imap_host, imap_port, username, password, folder_to_check )Prüfen Sie, ob die E‑Mail-Informationen erfasst wurden, und gehen Sie jede E‑Mail-Nachricht durch:
# 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 timeExtrahieren Sie das Nachrichtendatum (
datetime_email_message = message["Date"]) und konvertieren Sie es mithilfe der Google SecOps-Dienstfunktionen in die Unix-Epoche:string_to_datetime = convert_string_to_datetime(datetime_email_message) datetime_in_unix_time = convert_datetime_to_unix_time(string_to_datetime)Mit der Funktion
find_url_in_email_message_body(siemplify, email_messages_data_list)können Sie im Text von E‑Mail-Nachrichten nach URLs suchen. Wenn eine URL gefunden wird, können Sie andere Integrationen in Ihrem Playbook verwenden, um zu prüfen, ob sie schädlich ist:found_urls_in_email_body = find_url_in_email_message_body( siemplify, email_messages_data_list )Extrahieren Sie die eindeutige ID jeder E‑Mail-Nachricht und weisen Sie sie der Variablen
alert_idzu:# 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", "")Nachdem Sie alle erforderlichen Details extrahiert haben, um die Benachrichtigung in die Google SecOps-Plattform aufzunehmen, erstellen Sie das Ereignis und die Benachrichtigung:
# 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 )Validieren Sie die erstellte Benachrichtigung und fügen Sie sie der Liste
alertshinzu:# 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")Behandeln Sie das Szenario, in dem der Posteingang des Nutzers keine ungelesenen E‑Mails enthält:
else: siemplify.LOGGER.info( f"The inbox for user {username} has no unread emails" )Geben Sie die Liste
alertsan das System zurück, damit jede Benachrichtigung als Fall in der Fallwarteschlange angezeigt wird:# Return all the created alerts to the Cases module siemplify.return_package(alerts)Führen Sie die Funktion
mainin dem für den Connector konfigurierten Intervall aus: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)
Ungelesene E‑Mail-Nachricht abrufen
Die Funktion get_email_messages_data stellt über die Module imaplib und email eine Verbindung zum E‑Mail-Server her, ruft die Details der E‑Mail-Nachrichten ab und gibt eine Liste mit den ungelesenen E‑Mail-Nachrichten zurück:
Definieren Sie die Funktion
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 = []Stellen Sie mit dem Modul
imaplibeine Verbindung zum E‑Mail-Server her:# Log in to email using the imaplib module mail = imaplib.IMAP4_SSL(imap_host, imap_port) mail.login(username, password)E-Mail-Ordner bestimmen, in dem nach ungelesenen Nachrichten gesucht werden soll. In diesem Beispiel werden E‑Mails aus dem Ordner Posteingang (
DEFAULT_FOLDER_TO_CHECK_INBOX = "inbox") extrahiert:# 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)Sammle alle ungelesenen Nachrichten (
DEFAULT_MESSAGES_TO_READ_UNSEEN = "UNSEEN") und wandle die Daten in eine Liste um:# 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
Ereignis erstellen
Die Funktion create_event erstellt ein Ereignis, indem jede Komponente der E‑Mail-Nachricht mit den entsprechenden Ereignisfeldern verknüpft wird:
Definieren Sie die Funktion
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}" )Erstellen Sie ein Wörterbuch für die Ereignisfelder. Die Pflichtfelder sind
event["StartTime"],event["EndTime"],event["event_name"]undevent["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
Jede Benachrichtigung enthält ein oder mehrere Ereignisse. In diesem Beispiel enthält eine Benachrichtigung ein einzelnes Ereignis, das einer E‑Mail-Nachricht entspricht. Nachdem Sie das Ereignis erstellt haben, erstellen Sie die Benachrichtigung, die die Ereignisinformationen enthält.
Benachrichtigung erstellen und die Felder für Benachrichtigungsinformationen initialisieren
Die Funktion create_alert erstellt die Benachrichtigung. Jede Benachrichtigung enthält ein oder mehrere Ereignisse. In diesem Beispiel enthält jede Benachrichtigung ein Ereignis, das eine einzelne E‑Mail-Nachricht darstellt:
Definieren Sie die Funktion
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()Initialisieren Sie die
alert_info-Felder:# 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 = PRODUCTValidieren Sie das Ereignis und hängen Sie es an
alert_info.eventsan: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
URLs im E‑Mail-Text finden
Die Funktion find_url_in_email_message_body sucht im E‑Mail-Text nach URLs:
Suchen Sie in jeder E‑Mail-Nachricht den Teil des Nachrichtentexts mit Nur-Text-Inhalt:
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": continueLaden Sie die Nutzlast des Nachrichtentexts mit
email_message_body = part.get_payload()und suchen Sie mit dem regulären AusdruckURLS_REGEXnach URLs:URLS_REGEX = r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"Extrahieren Sie die übereinstimmenden URLs aus dem E‑Mail-Text und geben Sie die Liste zurück:
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
Nachdem Sie den Connector-Code überprüft haben, können Sie den Connector so konfigurieren, dass Fälle aus einem ausgewählten Gmail-Posteingang in die Plattform aufgenommen werden.
Benötigen Sie weitere Hilfe? Antworten von Community-Mitgliedern und Google SecOps-Experten erhalten