コネクタ ロジックを構築する
メールコネクタ統合を作成する
メールコネクタ統合を作成する手順は次のとおりです。
- [Automation > IDE] ウィンドウで、 [Add] をクリックして新しい IDE アイテムを追加します。SOAR のみのプラットフォームを使用している場合は、[レスポンス] > [IDE] に移動します。
- [Integration] を選択し、統合に「
Email Connector」という名前を付けます。 - [作成] をクリックします。統合がデフォルトのアイコンとともにサイドバーに表示されます。
[more_vert カスタム統合を構成] をクリックし、次の設定を定義します。
- 説明
- アイコン
- Python の依存関係
- 統合パラメータ
[保存] をクリックします。
メールコネクタを作成する
メールコネクタを作成する手順は次のとおりです。
- [Automation > IDE] ウィンドウで、 [Add] をクリックして新しい IDE アイテムを追加します。SOAR のみのプラットフォームを使用している場合は、[レスポンス] > [IDE] に移動します。
- [Connector] を選択し、コネクタに「
My Email Connector」という名前を付けます。 - リストで、[Email Connector] 統合を選択して、コネクタを統合に関連付けます。
- [作成] をクリックします。
コネクタ パラメータを設定する
コネクタを作成したら、コネクタのパラメータを設定します。
次の表に従ってコネクタ パラメータを構成します。
パラメータ 説明 タイプ Username必須。インターネット メッセージ アクセス プロトコル(IMAP)のユーザー名。コネクタが Google SecOps プラットフォームにメールを pull するメールアドレス。デフォルト値は email@gmail.comです。stringPassword必須。コネクタが Google SecOps プラットフォームにメールを pull するために使用するメールアドレスの IMAP パスワード。 passwordIMAP Port必須。IMAP がリモート サーバーからメールにアクセスするために使用するネットワーク ポート(デフォルト値は 993など)。intIMAP Server Address必須。IMAP アカウントの受信メールサーバー(デフォルト値は imap.gmail.comなど)。stringFolder to check for emails(省略可)指定したフォルダ(デフォルト値は Inboxなど)からのみメールを pull します。inbox次のフィールドの詳細を入力します。
プロダクト フィールド名(
device_product): アラートのプロダクト名に割り当てる未加工フィールドの値を決定します。コードでは、このフィールドはMail(PRODUCT)として定義されています。event["device_product"] = PRODUCT # The PRODUCT constant is "Mail"イベント フィールド名(
event_name): イベントタイプ フィールドに割り当てる未加工フィールドの値を決定します。コードでは、このフィールドはSuspicious emailとして定義されています。event["event_name"] = "Suspicious email"
メールコネクタを編集する
メールコネクタのコードとパラメータを編集する手順は次のとおりです。
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)コネクタのコードをコピーしたら、必要なモジュールのインポートと
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 インタープリタはコードを順番に実行し、スクリプトで定義された各関数を呼び出します。
コネクタ パラメータを抽出します。
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" )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 )メール情報が収集されていることを確認し、各メール メッセージを反復処理します。
# 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)find_url_in_email_message_body(siemplify, email_messages_data_list)関数を使用して、メール メッセージ本文の URL を検索します。URL が見つかった場合は、ハンドブック内の他の統合を使用して、その URL が悪意のあるものかどうかを確認できます。found_urls_in_email_body = find_url_in_email_message_body( siemplify, email_messages_data_list )各メール メッセージの一意の 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", "")アラートを 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 )作成したアラートを検証し、
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")ユーザーの受信トレイに未読メールがない場合のシナリオを処理します。
else: siemplify.LOGGER.info( f"The inbox for user {username} has no unread emails" )alertsリストをシステムに返して、各アラートがケースキューにケースとして表示されるようにします。# Return all the created alerts to the Cases module siemplify.return_package(alerts)コネクタに構成された間隔で
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 モジュールを使用してメールサーバーに接続し、メール メッセージの詳細を取得して、未読のメール メッセージを含むリストを返します。
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 = []imaplibモジュールを使用してメールサーバーに接続します。# Log in to email using the imaplib module mail = imaplib.IMAP4_SSL(imap_host, imap_port) mail.login(username, password)未読メッセージを確認するメールフォルダを特定します。この例では、メールは 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)すべての未読メッセージ(
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 関数は、各メール メッセージ コンポーネントを対応するイベント フィールドに関連付けることで、イベントを作成します。
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}" )イベント フィールドの辞書を作成します。必須フィールドは、
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
各アラートには 1 つ以上のイベントが含まれます。この例では、アラートに 1 つのメール メッセージに対応する 1 つのイベントが含まれています。イベントを作成したら、イベント情報を含むアラートを作成します。
アラートを作成し、アラート情報フィールドを初期化する
create_alert 関数はアラートを作成します。各アラートには 1 つ以上のイベントが含まれます。この例では、各アラートに 1 つのメール メッセージを表す 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()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イベントを検証して
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 をスキャンします。
各メール メッセージで、書式なしテキスト コンテンツを含むメッセージ本文の部分を見つけます。
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": continueemail_message_body = part.get_payload()を使用してメール本文のペイロードを読み込み、URLS_REGEX正規表現を使用して URL を検索します。URLS_REGEX = r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"メールの本文から一致する 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 のプロフェッショナルから回答を得ることができます。