# Uploading logs from Yandex Audit Trails

[Audit Trails](../../audit-trails/index.md) helps you collect and export audit logs as well as apply the analysis and rapid response tools to events at the Yandex Cloud resources level. [OpenSearch](../index.md) acts as a SIEM system to analyze logs and respond to security events.

You will learn how to set up the export of logs from Audit Trails in just a few steps using [Yandex Data Streams](../../data-streams/index.md) and [Yandex Data Transfer](../../data-transfer/index.md), with Yandex Managed Service for OpenSearch as a SIEM system to analyze logs and respond to security events.

# Exporting audit logs to Yandex Managed Service for OpenSearch


Create a trail to upload [audit logs](../../audit-trails/concepts/format.md) for Yandex Cloud resources to a [Yandex Data Streams](../../data-streams/index.md) data stream. Once done, configure continuous log delivery to a Yandex Managed Service for OpenSearch cluster using Yandex Data Transfer.

![audit-opensearch-schema](../../_assets/mdb/audit-opensearch-schema.svg)

You can export organization, cloud, or folder logs.

To export audit logs:

1. [Get your cloud ready](#before-begin).
1. [Create a trail to send logs to the stream in Data Streams](#create-trail).
1. [Create a Managed Service for OpenSearch cluster](#create-os).
1. [Set up a transfer to deliver logs to the Managed Service for OpenSearch cluster](#configure-data-transfer).
1. [Check the result](#check-result).
1. [Upload additional content](#additional-content).

If you no longer need the resources you created, [delete them](#clear-out).

## Getting started {#before-begin}

Sign up for Yandex Cloud and create a [billing account](../../billing/concepts/billing-account.md):
1. Navigate to the [management console](https://console.yandex.cloud) and log in to Yandex Cloud or create a new account.
1. On the **[Yandex Cloud Billing](https://center.yandex.cloud/billing/accounts)** page, make sure you have a billing account linked and it has the `ACTIVE` or `TRIAL_ACTIVE` [status](../../billing/concepts/billing-account-statuses.md). If you do not have a billing account, [create one](../../billing/quickstart/index.md) and [link](../../billing/operations/pin-cloud.md) a cloud to it.

If you have an active billing account, you can create or select a [folder](../../resource-manager/concepts/resources-hierarchy.md#folder) for your infrastructure on the [cloud page](https://console.yandex.cloud/cloud).

[Learn more about clouds and folders here](../../resource-manager/concepts/resources-hierarchy.md).

### Required paid resources {#paid-resources}

* Managed Service for OpenSearch cluster, which includes the use of computing resources, storage and backup size (see [Managed Service for OpenSearch pricing](../pricing.md)).
* Public IP addresses if public access is enabled for cluster hosts (see [Virtual Private Cloud pricing](../../vpc/pricing.md)).
* Data Streams (see [Data Streams pricing](../../data-streams/pricing.md)). The cost depends on the pricing model:

    * [Based on allocated resources](../../data-streams/pricing.md#rules): You pay a fixed hourly rate for the established throughput limit and message retention period, and additionally for the number of units of actually written data.
    * [On-demand](../../data-streams/pricing.md#on-demand): You pay for the performed read/write operations, the amount of read or written data, and the actual storage used for messages that are still within their retention period.

* Managed Service for YDB database, operating in serverless mode: data operations, amount of stored data and backups (see [Managed Service for YDB pricing](../../ydb/pricing/index.md)).

## Create a trail to send logs to a Data Streams data stream {#create-trail}

[Create a trail](../../audit-trails/operations/create-trail.md) to send logs to a data stream named `audit‑trails`. Using a stream with this name makes it easier to upload the [Security Content](#additional-content) library objects.

When creating a trail, select the [log collection scope](../../audit-trails/concepts/trail.md#collecting-area).

## Create a Managed Service for OpenSearch cluster {#create-os}

{% list tabs group=instructions %}

- Manually {#manual}

  [Create a Managed Service for OpenSearch](../operations/cluster-create.md) cluster of any suitable configuration.

- Using Terraform {#tf}

    1. If you do not have Terraform yet, [install it](../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
    1. [Get the authentication credentials](../../tutorials/infrastructure-management/terraform-quickstart.md#get-credentials). You can add them to environment variables or specify them later in the provider configuration file.
    1. [Configure and initialize a provider](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). There is no need to create a provider configuration file manually, you can [download it](https://github.com/yandex-cloud-examples/yc-terraform-provider-settings/blob/main/provider.tf).
    1. Place the configuration file in a separate working directory and [specify the parameter values](../../tutorials/infrastructure-management/terraform-quickstart.md#configure-provider). If you did not add the authentication credentials to environment variables, specify them in the configuration file.

    1. Download the [trails-to-opensearch.tf](https://github.com/yandex-cloud-examples/yc-data-transfer-from-audit-trails-to-opensearch/blob/main/trails-to-opensearch.tf) configuration file to the same working directory.

       This file describes:

        * [Network](../../vpc/concepts/network.md#network).
        * [Subnet](../../vpc/concepts/network.md#subnet).
        * [Security group](../../vpc/concepts/security-groups.md) and rules for connection to a Managed Service for OpenSearch cluster.
        * Managed Service for OpenSearch target cluster.
        * Transfer.

    1. In the `trails-to-opensearch.tf` file, specify these variables:

        * `os_version`: OpenSearch version in the target cluster.
        * `os_admin_password`: `admin` user password.
        * `transfer_enabled`: Set to `0` to prevent transfer creation until you [create endpoints manually](#prepare-transfer).

    1. Validate your Terraform configuration files using this command:

        ```bash
        terraform validate
        ```

       Terraform will display any configuration errors detected in your files.

    1. Create the required infrastructure:

       1. Run this command to view the planned changes:
       
          ```bash
          terraform plan
          ```
       
          If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
       
       1. If everything looks correct, apply the changes:
          1. Run this command:
       
             ```bash
             terraform apply
             ```
       
          1. Confirm updating the resources.
          1. Wait for the operation to complete.

       All the required resources will be created in the specified folder. You can check resource availability and their settings in the [management console](https://console.yandex.cloud).

{% endlist %}

## Set up a transfer to deliver logs to the Managed Service for OpenSearch cluster {#configure-data-transfer}

1. [Create a source endpoint](../../data-transfer/operations/endpoint/source/data-streams.md):

    * **Database type**: `Yandex Data Streams`.
    * **Endpoint settings**:

        * **Connection settings**:

            * **Database**: Select the Managed Service for YDB database from the list.
            * **Stream**: Specify the name of the stream in Data Streams.
            * **Service account**: Select an existing service account or create a new one with the `yds.editor` role.

        * **Advanced settings**:

            * **Conversion rules**: `AuditTrails.v1 parser`.

1. [Create a target endpoint](../../data-transfer/operations/endpoint/target/opensearch.md):

    * **Database type**: `OpenSearch`.
    * **Endpoint parameters**:

        * **Connection**:

            * **Connection type**: `Managed Service for OpenSearch cluster`.

                * **Managed Service for OpenSearch cluster**: Select the source cluster from the list.

            * **User** and **Password**: Enter the name and password of the user who has access to the database, e.g., [`admin`](../operations/cluster-users.md) user.

1. Create and activate your transfer:

   {% list tabs group=instructions %}

    - Manually {#manual}

        1. [Create a transfer](../../data-transfer/operations/transfer.md#create) of the **Replication**-type that will use the new endpoints.
        1. [Activate the transfer](../../data-transfer/operations/transfer.md#activate) and wait for its status to change to **Replicating**.

    - Using Terraform {#tf}

        1. In the `trails-to-opensearch.tf` file, specify these variables:

            * `source_endpoint_id`: Source endpoint ID.
            * `target_endpoint_id`: Target endpoint ID.
            * `transfer_enabled`: Set to `1` to create a transfer.

        1. Validate your Terraform configuration files using this command:

            ```bash
            terraform validate
            ```

           Terraform will display any configuration errors detected in your files.

        1. Create the required infrastructure:

           1. Run this command to view the planned changes:
           
              ```bash
              terraform plan
              ```
           
              If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
           
           1. If everything looks correct, apply the changes:
              1. Run this command:
           
                 ```bash
                 terraform apply
                 ```
           
              1. Confirm updating the resources.
              1. Wait for the operation to complete.

        1. The transfer will be activated automatically. Wait for its status to change to **Replicating**.

   {% endlist %}

## Check the result {#check-result}

Make sure the data from Audit Trails is successfully uploaded to OpenSearch:

1. Wait for the transfer status to change to **Replicating**.
1. Connect to the target cluster via [OpenSearch Dashboards](../operations/connect/clients.md#dashboards).
1. Select the `Global` tenant.
1. Create a new index template named `audit-trails*`:

    1. Open the management panel by clicking ![os-dashboards-sandwich](../../_assets/console-icons/bars.svg).
    1. Under **Management**, select **Stack Management**.
    1. Go to **Index Patterns** and click **create an index pattern** at the bottom of the page.
    1. Specify `audit-trails*` in the **Index pattern name** field and click **Next step**.
    1. In **Time field**, select `application_usage_daily.timestamp` and click **Create index pattern**.

1. Open the management panel by clicking ![os-dashboards-sandwich](../../_assets/console-icons/bars.svg).
1. Under **OpenSearch Dashboards**, select **Discover**.
1. The dashboard that opens should contain data from Audit Trails in [Elastic Common Schema](https://www.elastic.co/guide/en/ecs/current/ecs-reference.html) format.

![opensearch-discover](../../_assets/mdb/opensearch-discover.png)

{% note warning %}

Data delivery to Managed Service for OpenSearch target adheres to the `at least once` mode: if the tables being transferred do not have a primary key, duplicate entries can be created in the audit logs.

{% endnote %}

## Upload additional content {#additional-content}

For your convenience, the Yandex Cloud security team created Solution Library with examples and recommendations for building a secure infrastructure in Yandex Cloud. The library is available in [this public GitHub repository](https://github.com/yandex-cloud-examples/yc-security-solutions-library). It contains the following objects to upload to OpenSearch:

* Dashboard with use cases and statistics.
* Set of ready-to-use queries to search for security events.
* Sample events with preset alerts (the client should specify the alert destination on their own).

All required event fields are converted to [Elastic Common Schema (ECS)](https://www.elastic.co/guide/en/ecs/current/index.html) format; the complete mapping table is provided in the [Yandex Cloud Security Solution Library document](https://github.com/yandex-cloud-examples/yc-export-auditlogs-to-elk/blob/main/papers/Описание%20объектов.pdf).

## To use Security Content:

1. Clone the Yandex Cloud Security Solution Library repository:

    ```bash
    git clone https://github.com/yandex-cloud-examples/yc-export-auditlogs-to-opensearch.git
    ```

1. Connect to the target cluster via [OpenSearch Dashboards](../operations/connect/clients.md#dashboards).
1. Open the management panel by clicking ![os-dashboards-sandwich](../../_assets/console-icons/bars.svg).
1. Under **Management**, select **Stack Management**.
1. Go to **Saved Objects** and import files from the `yc-export-auditlogs-to-opensearch/update-opensearch-scheme/content-for-transfer/` folder:

    * `dashboard.ndjson`
    * `filters.ndjson`
    * `search.ndjson`

### Dashboard {#dashboard}

Use the ready-made `Audit-trails-dashboard`:

1. Open the management panel by clicking ![os-dashboards-sandwich](../../_assets/console-icons/bars.svg).
1. Under **OpenSearch Dashboards**, select **Dashboard**.
1. Select `Audit-trails-dashboard` in the dashboard list.

![opensearch-audit-trails-dashboard](../../_assets/mdb/opensearch-audit-trails-dashboard.png)

### Security events {#discover}

Run a ready-to-use query to view security events that can be selected using filters.

1. Open the management panel by clicking ![os-dashboards-sandwich](../../_assets/console-icons/bars.svg).
1. Under **OpenSearch Dashboards**, select **Discover**.
1. In the **Open** tab, select `Search:Yandexcloud: Yandexcloud: Interesting fields`.

![opensearch-search-yandexcloud-interesting-fields](../../_assets/mdb/opensearch-search-yandexcloud-interesting-fields.png)

### Setting up alerts {#alerts}

Use code examples for the `monitor` and `trigger` entities when setting up [alerts](https://opensearch.org/docs/latest/monitoring-plugins/alerting/index/):

1. Open the management panel by clicking ![os-dashboards-sandwich](../../_assets/console-icons/bars.svg).
1. Under **OpenSearch Plugins**, select **Alerting**.
1. Copy the sample file contents and paste them into the creation window:

    * [monitor.json](https://github.com/yandex-cloud-examples/yc-export-auditlogs-to-opensearch/blob/main/update-opensearch-scheme/content-for-transfer/monitor.json)
    * [trigger_action_example.json](https://github.com/yandex-cloud-examples/yc-export-auditlogs-to-opensearch/blob/main/update-opensearch-scheme/content-for-transfer/trigger_action_example.json)

## Delete the resources you created {#clear-out}

{% note info %}

Before deleting any resources, [deactivate the transfer](../../data-transfer/operations/transfer.md#deactivate).

{% endnote %}

To minimize resource consumption, delete the resources you no longer need:

1. [Delete the transfer](../../data-transfer/operations/transfer.md#delete).
1. [Delete the source and target endpoints](../../data-transfer/operations/endpoint/index.md#delete).
1. [Delete the Managed Service for YDB](../../ydb/operations/manage-databases.md#delete-db) database.
1. [Delete the created service accounts](../../iam/operations/sa/delete.md).
1. Delete the [Audit Trails](../../audit-trails/concepts/trail.md) trail.
1. Delete the rest of the resources depending on how you created them:

   {% list tabs group=instructions %}

   - Manually {#manual}

       [Delete the Managed Service for OpenSearch](../operations/cluster-delete.md) cluster.

   - Using Terraform {#tf}

       1. In the terminal window, go to the directory containing the infrastructure plan.
       
           {% note warning %}
       
           Make sure the directory has no Terraform manifests with the resources you want to keep. Terraform deletes all resources that were created using the manifests in the current directory.
       
           {% endnote %}
       
       1. Delete resources:
       
           1. Run this command:
       
               ```bash
               terraform destroy
               ```
       
           1. Confirm deleting the resources and wait for the operation to complete.
       
           All the resources described in the Terraform manifests will be deleted.

   {% endlist %}