Compila la lógica del conector

Compatible con lo siguiente:

En este documento, se explica cómo compilar un conector nuevo en el entorno de desarrollo integrado (IDE) creando una integración y, luego, vinculando un conector a ella.

Crea una integración de conector de correo electrónico

Para crear una integración de conector de correo electrónico, sigue estos pasos:

  1. En la ventana Automatización > IDE, haz clic en Agregar para agregar un nuevo elemento de IDE. Si estás en una plataforma solo de SOAR, ve a Respuesta > IDE.
  2. Selecciona Integración y asígnale el nombre Email Connector.
  3. Haz clic en Crear. La integración aparecerá en la barra lateral con un ícono predeterminado.
  4. Haz clic en more_vert Configurar integración personalizada y define los siguientes parámetros de configuración:

    • Descripción
    • Ícono
    • Dependencias de Python
    • Parámetros de integración
  5. Haz clic en Guardar.

Crea un conector de correo electrónico

Para crear un conector de correo electrónico, sigue estos pasos:

  1. En la ventana Automatización > IDE, haz clic en Agregar para agregar un nuevo elemento de IDE. Si estás en una plataforma solo de SOAR, ve a Respuesta > IDE.
  2. Selecciona Conector y asígnale el nombre My Email Connector.
  3. En la lista, selecciona la integración Email Connector para asociar el conector con la integración.
  4. Haz clic en Crear.

Establece los parámetros del conector

Después de crear el conector, establece sus parámetros:

  1. Configura los parámetros del conector según la siguiente tabla:

    Parámetro Descripción Tipo
    Username Obligatorio. Es el nombre de usuario del Protocolo de acceso a mensajes de Internet (IMAP). Es la dirección de correo electrónico desde la que el conector extrae los correos electrónicos a la plataforma de Google SecOps. El valor predeterminado es email@gmail.com. string
    Password Obligatorio. Es la contraseña de IMAP para la dirección de correo electrónico que usa el conector para extraer correos electrónicos a la plataforma de Google SecOps. password
    IMAP Port Obligatorio. Es el puerto de red que usa IMAP para acceder a los correos electrónicos desde un servidor remoto (por ejemplo, 993 como valor predeterminado). int
    IMAP Server Address Obligatorio. El servidor de correo entrante para una cuenta de IMAP (por ejemplo, imap.gmail.com como el valor predeterminado). string
    Folder to check for emails Opcional. Extrae correos electrónicos solo de la carpeta especificada (por ejemplo, Inbox como valor predeterminado). inbox
  2. Ingresa los siguientes detalles del campo:

    • Nombre del campo del producto (device_product): Determina el valor del campo sin procesar que se asignará al nombre del producto de la alerta. En el código, este campo se define como Mail (PRODUCT):

      event["device_product"] = PRODUCT  # The PRODUCT constant is "Mail"
      
    • Nombre del campo del evento (event_name): Determina el valor del campo sin procesar que se asignará al campo del tipo de evento. En el código, este campo se define como Suspicious email:

      event["event_name"] = "Suspicious email"
      

Edita el conector de correo electrónico

Para editar el código y los parámetros del conector de correo electrónico, sigue estos pasos:

  1. Copia el siguiente código creado para My Email Connector y pégalo en el 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. Después de copiar el código del conector, revisa las importaciones de módulos requeridas y la función main. Cada llamada a función desde main se describe en detalle en las siguientes secciones.

Importaciones relevantes

Un módulo de Python tiene un conjunto de funciones, clases o variables definidas y, además, implementadas. Para implementar las funciones del conector, importa los siguientes módulos a la secuencia de comandos:

# 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

Función principal

La función main es el punto de entrada de la secuencia de comandos. El intérprete de Python ejecuta el código de forma secuencial y llama a cada función definida en la secuencia de comandos:

  1. Extrae los parámetros del conector. Usa la función siemplify.extract_connector_param para extraer cada parámetro configurado para el conector (username, password, imap_host, imap_port y 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. Usa la función get_email_messages_data(imap_host, imap_port, username, password, folder_to_check) para recopilar toda la información de los correos electrónicos no leídos:

    # Get the digested email message data
    email_messages_data_list = get_email_messages_data(
        imap_host, imap_port, username, password, folder_to_check
    )
    
  3. Confirma que se recopile la información del correo electrónico y, luego, itera cada mensaje de correo electrónico:

    # 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
    

    Extrae la fecha del mensaje (datetime_email_message = message["Date"]) y conviértela en tiempo Unix con las funciones de utilidad de 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. Busca URLs en el cuerpo del mensaje de correo electrónico con la función find_url_in_email_message_body(siemplify, email_messages_data_list). Si se encuentra una URL, puedes usar otras integraciones en tu guía para verificar si es maliciosa:

    found_urls_in_email_body = find_url_in_email_message_body(
        siemplify, email_messages_data_list
    )
    
  5. Extrae el ID único de cada mensaje de correo electrónico y asígnalo a la variable 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. Después de extraer todos los detalles necesarios para transferir la alerta a la plataforma de Google SecOps, crea el evento y la alerta:

    # 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. Valida la alerta creada y agrégala a la lista de 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. Controla la situación en la que la bandeja Recibidos del usuario no tiene correos electrónicos no leídos:

    else:
        siemplify.LOGGER.info(
            f"The inbox for user {username} has no unread emails"
        )
    
  9. Devuelve la lista alerts al sistema para que cada alerta se presente como un caso en la cola de casos:

    # Return all the created alerts to the Cases module
    siemplify.return_package(alerts)
    
  10. Ejecuta la función main en el intervalo configurado para el conector:

    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)
    

Obtén el mensaje de correo electrónico no leído

La función get_email_messages_data se conecta al servidor de correo electrónico con los módulos imaplib y email, recupera los detalles de los mensajes de correo electrónico y devuelve una lista que contiene los mensajes de correo electrónico no leídos:

  1. Define la función 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. Conéctate al servidor de correo electrónico con el módulo imaplib:

    # Log in to email using the imaplib module
    mail = imaplib.IMAP4_SSL(imap_host, imap_port)
    mail.login(username, password)
    
  3. Determinar la carpeta de correo electrónico en la que se deben buscar mensajes no leídos En este ejemplo, los correos electrónicos se extraen de la carpeta Recibidos (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. Recopila todos los mensajes no leídos (DEFAULT_MESSAGES_TO_READ_UNSEEN = "UNSEEN") y convierte los datos en una lista:

    # 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
    

Crea el evento

La función create_event crea un evento asociando cada componente del mensaje de correo electrónico con los campos de evento correspondientes:

  1. Define la función 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. Crea un diccionario para los campos de eventos. Los campos obligatorios son event["StartTime"], event["EndTime"], event["event_name"] y 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
    

Cada alerta contiene uno o más eventos. En este ejemplo, una alerta contiene un solo evento que corresponde a un mensaje de correo electrónico. Después de crear el evento, crea la alerta que contiene la información del evento.

Crea la alerta y, luego, inicializa los campos de información de la alerta

La función create_alert crea la alerta. Cada alerta contiene uno o más eventos. En este ejemplo, cada alerta contiene un evento que representa un solo mensaje de correo electrónico:

  1. Define la función 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. Inicializa los campos 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. Valida el evento y agrégalo a 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
    

Busca URLs en el cuerpo del correo electrónico

La función find_url_in_email_message_body analiza el cuerpo del correo electrónico en busca de URLs:

  1. Para cada mensaje de correo electrónico, busca la parte del cuerpo del mensaje con contenido de texto sin formato:

    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. Carga la carga útil del cuerpo del mensaje con email_message_body = part.get_payload() y busca URLs con la expresión regular URLS_REGEX:

    URLS_REGEX = r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
    
  3. Extrae las URLs que coincidan del cuerpo del correo electrónico y devuelve la lista:

    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
    

Después de revisar el código del conector, puedes configurarlo para que transfiera casos a la plataforma desde una carpeta Recibidos de Gmail seleccionada.

¿Necesitas más ayuda? Obtén respuestas de miembros de la comunidad y profesionales de Google SecOps.