Build connector logic
Create an email connector integration
To create an email connector integration, follow these steps:
- In the Automation > IDE window, click Add to add a new IDE item. If you are on a SOAR-only platform, go to Response > IDE.
- Select Integration and name the integration
Email Connector. - Click Create. The integration appears in the sidebar with a default icon.
Click more_vert Configure Custom Integration and define the following settings:
- Description
- Icon
- Python Dependencies
- Integration Parameters
Click Save.
Create an email connector
To create an email connector, follow these steps:
- In the Automation > IDE window, click Add to add a new IDE item. If you are on a SOAR-only platform, go to Response > IDE.
- Select Connector and name the connector
My Email Connector. - In the list, select the Email Connector integration to associate the connector with the integration.
- Click Create.
Set the connector parameters
After you create the connector, set the connector parameters:
Configure the connector parameters according to the following table:
Parameter Description Type UsernameRequired. Internet Message Access Protocol (IMAP) username. The email address from which the connector pulls emails into the Google SecOps platform. The default value is email@gmail.com.stringPasswordRequired. IMAP password for the email address that the connector uses to pull emails into the Google SecOps platform. passwordIMAP PortRequired. The network port used by IMAP to access emails from a remote server (for example, 993as the default value).intIMAP Server AddressRequired. The incoming mail server for an IMAP account (for example, imap.gmail.comas the default value).stringFolder to check for emailsOptional. Pulls emails only from the specified folder (for example, Inboxas the default value).inboxEnter the following field details:
Product Field Name (
device_product): Determines the raw field value to assign to the alert's product name. In the code, this field is defined asMail(PRODUCT):event["device_product"] = PRODUCT # The PRODUCT constant is "Mail"Event Field Name (
event_name): Determines the raw field value to assign to the event type field. In the code, this field is defined asSuspicious email:event["event_name"] = "Suspicious email"
Edit the email connector
To edit the code and parameters for the email connector, follow these steps:
Copy the following code created for My Email Connector and paste it into the 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)After copying the connector's code, review the required module imports and the
mainfunction. Each function called frommainis described in detail in the following sections.
Relevant imports
A Python module has a set of functions, classes, or variables defined and implemented. To implement the connector functions, import the following modules into the script:
# 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 function
The main function is the script's entry point. The Python interpreter runs the code sequentially and calls each function defined in the script:
Extract the connector parameters. Use the
siemplify.extract_connector_paramfunction to extract each configured parameter for the connector (username,password,imap_host,imap_port, andfolder_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" )Use the
get_email_messages_data(imap_host, imap_port, username, password, folder_to_check)function to collect all information from the unread emails:# Get the digested email message data email_messages_data_list = get_email_messages_data( imap_host, imap_port, username, password, folder_to_check )Confirm that the email information is collected and iterate through each email message:
# 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 timeExtract the message date (
datetime_email_message = message["Date"]) and convert it to Unix epoch time using Google SecOps utility functions:string_to_datetime = convert_string_to_datetime(datetime_email_message) datetime_in_unix_time = convert_datetime_to_unix_time(string_to_datetime)Search for URLs in the email message body using the
find_url_in_email_message_body(siemplify, email_messages_data_list)function. If a URL is found, you can use other integrations in your playbook to check whether it is malicious:found_urls_in_email_body = find_url_in_email_message_body( siemplify, email_messages_data_list )Extract the unique ID of each email message and assign it to the
alert_idvariable:# 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", "")After you extract all the necessary details to ingest the alert into the Google SecOps platform, create the event and the alert:
# 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 )Validate the created alert and add it to the
alertslist:# 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")Handle the scenario where the user's inbox has no unread emails:
else: siemplify.LOGGER.info( f"The inbox for user {username} has no unread emails" )Return the
alertslist to the system so that each alert is presented as a case in the case queue:# Return all the created alerts to the Cases module siemplify.return_package(alerts)Run the
mainfunction at the interval configured for the connector: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 the unread email message
The get_email_messages_data function connects to the email server using the imaplib and email modules, retrieves the email message details, and returns a list containing the unread email messages:
Define the
get_email_messages_data(imap_host, imap_port, username, password, folder_to_check)function:def get_email_messages_data( imap_host, imap_port, username, password, folder_to_check ): """Returns all unread email messages.""" email_messages_data_list = []Connect to the email server using the
imaplibmodule:# Log in to email using the imaplib module mail = imaplib.IMAP4_SSL(imap_host, imap_port) mail.login(username, password)Determine the email folder to check for unread messages. In this example, emails are extracted from the Inbox folder (
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)Collect all unread messages (
DEFAULT_MESSAGES_TO_READ_UNSEEN = "UNSEEN") and convert the data into a list:# 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 the event
The create_event function creates an event by associating each email message component with the corresponding event fields:
Define the
create_event(siemplify, alert_id, email_message_data, all_found_url_in_emails_body_list, datetime_in_unix_time)function: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}" )Create a dictionary for the event fields. The mandatory fields are
event["StartTime"],event["EndTime"],event["event_name"], andevent["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
Each alert contains one or more events. In this example, an alert contains a single event corresponding to one email message. After creating the event, create the alert that contains the event information.
Create the alert and initialize the alert information fields
The create_alert function creates the alert. Each alert contains one or more events; in this example, each alert contains one event representing a single email message:
Define the
create_alertfunction: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()Initialize the
alert_infofields:# 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 = PRODUCTValidate the event and append it to
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 URLs in the email body
The find_url_in_email_message_body function scans the email body for URLs:
For each email message, locate the part of the message body with plain text content:
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": continueLoad the message body payload with
email_message_body = part.get_payload()and search for URLs using theURLS_REGEXregular expression:URLS_REGEX = r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"Extract the matching URLs from the email body and return the list:
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
After reviewing the connector code, you can configure the connector to ingest cases into the platform from a selected Gmail inbox.
Need more help? Get answers from Community members and Google SecOps professionals.