커넥터 로직 빌드
이메일 커넥터 통합 만들기
이메일 커넥터 통합을 만들려면 다음 단계를 따르세요.
- 자동화 > IDE 창에서 추가를 클릭하여 새 IDE 항목을 추가합니다. SOAR 전용 플랫폼을 사용하는 경우 응답 > IDE로 이동합니다.
- 통합을 선택하고 통합 이름을
Email Connector로 지정합니다. - 만들기를 클릭합니다. 통합이 기본 아이콘과 함께 사이드바에 표시됩니다.
more_vert 커스텀 통합 구성을 클릭하고 다음 설정을 정의합니다.
- 설명
- 아이콘
- Python 종속 항목
- 통합 매개변수
저장을 클릭합니다.
이메일 커넥터 만들기
이메일 커넥터를 만들려면 다음 단계를 따르세요.
- 자동화 > IDE 창에서 추가를 클릭하여 새 IDE 항목을 추가합니다. SOAR 전용 플랫폼을 사용하는 경우 응답 > IDE로 이동합니다.
- 커넥터를 선택하고 커넥터 이름을
My Email Connector로 지정합니다. - 목록에서 이메일 커넥터 통합을 선택하여 커넥터를 통합과 연결합니다.
- 만들기를 클릭합니다.
커넥터 파라미터 설정
커넥터를 만든 후 커넥터 파라미터를 설정합니다.
다음 표에 따라 커넥터 매개변수를 구성합니다.
매개변수 설명 유형 Username필수. 인터넷 메시지 액세스 프로토콜(IMAP) 사용자 이름입니다. 커넥터가 이메일을 Google SecOps 플랫폼으로 가져오는 이메일 주소입니다. 기본값은 email@gmail.com입니다.stringPassword필수. 커넥터가 이메일을 Google SecOps 플랫폼으로 가져오는 데 사용하는 이메일 주소의 IMAP 비밀번호입니다. passwordIMAP Port필수. IMAP에서 원격 서버의 이메일에 액세스하는 데 사용하는 네트워크 포트입니다(예: 기본값 993).intIMAP Server Address필수. IMAP 계정의 수신 메일 서버입니다(예: 기본값으로 imap.gmail.com).stringFolder to check for emails선택사항. 지정된 폴더에서만 이메일을 가져옵니다(예: 기본값으로 Inbox).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 유틸리티 함수를 사용하여 유닉스 시간으로 변환합니다.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이 발견되면 플레이북의 다른 통합을 사용하여 악성인지 확인할 수 있습니다.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)읽지 않은 메일을 확인할 이메일 폴더를 결정합니다. 이 예시에서는 받은편지함 폴더(
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
각 알림에는 하나 이상의 이벤트가 포함됩니다. 이 예시에서 알림에는 이메일 메시지 하나에 해당하는 단일 이벤트가 포함됩니다. 이벤트를 만든 후 이벤트 정보가 포함된 알림을 만듭니다.
알림을 만들고 알림 정보 필드 초기화
create_alert 함수는 알림을 만듭니다. 각 알림에는 하나 이상의 이벤트가 포함됩니다. 이 예시에서 각 알림에는 단일 이메일 메시지를 나타내는 하나의 이벤트가 포함됩니다.
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 전문가에게 문의하여 답변을 받으세요.