# Querying and Writing Detections for Panther Audit Logs

## Overview

You can [enable Panther audit log ingestion into Panther](https://docs.panther.com/data-onboarding/supported-logs/panther-audit-logs/..#enabling-audit-logs-as-a-log-source), meaning you can then interact with Panther audit logs in detections, data lake queries, and more.

## Querying the Data Lake for Panther audit logs

Audit logs can be found in the data lake under `panther_logs.panther_audit`. The following query, executed in [Search](https://docs.panther.com/search/search-tool) or [Data Explorer](https://docs.panther.com/search/data-explorer), shows all audit events within the last day:

```sql
SELECT * FROM panther_logs.panther_audit WHERE p_occurs_since('1 day');
```

The result of this query would include several audit logs, an example of which can be seen below:

```json
{
	"XForwardedFor": [
		"72.72.72.72",
		"130.172.130.172"
	],
	"actionDescription": "Lists the details of all available data lake databases",
	"actionName": "LIST_DATA_LAKE_DATABASES",
	"actionParams": {},
	"actionResult": "SUCCEEDED",
	"actor": {
		"attributes": {
			"email": "foo.user@acmecorp.io",
			"emailVerified": false,
			"roleId": ""
		},
		"id": "AcmecorpSSO_foo.user@acmecorp.io",
		"name": "foo.user@acmecorp.io",
		"type": "USER"
	},
	"errors": null,
	"p_any_ip_addresses": [
		"72.72.72.72",
		"130.172.130.172"
	],
	"p_any_trace_ids": [
		"AcmecorpSSO_foo.user@acmecorp.io"
	],
	"p_any_usernames": [
		"foo.user@acmecorp.io"
	],
	"p_event_time": "2022-04-22 15:39:55.358",
	"p_log_type": "Panther.Audit",
	"p_parse_time": "2022-04-22 15:41:36.276",
	"p_row_id": "asdfdjklasdfjklasdfjlk",
	"p_source_id": "abc12345-ab12-cd12-ef12-abc1234567890",
	"p_source_label": "panther-audit-logs-us-east-1",
	"pantherVersion": "1.34.0",
	"sourceIP": "72.72.72.72",
	"timestamp": "2022-04-22 15:39:55.358",
	"userAgent": ""
}
```

## Writing a detection for Panther audit logs

Audit logs can be leveraged to write powerful detections for generating alerts when an unusual or important action has been taken within Panther.

Let's write a detection that alerts when a detection has been deleted.

### Step 1: Begin creating the detection

1. In the left-hand navigation bar of your Panther Console, click **Detections**.
2. On the Detections page, click **Create New**.
3. In the **Select Detection Type** modal, click **Rule**.
4. Enter a descriptive **Name** for your rule, e.g., `Panther detection deleted`.
5. Under **For the Following Source**, in the **Log Types** dropdown, select `Panther.Audit`.\
   ![Under a "For the Following Source" header is a "Log Types" dropdown. A "Panther.Audit" selection has been made.](https://4011785613-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LgdiSWdyJcXPahGi9Rs-2910905616%2Fuploads%2Fgit-blob-96d9f178e498d7299ce987cc62d563f6de7c786b%2FScreenshot%202024-05-14%20at%2011.25.15%20AM.png?alt=media)
6. In the **Detect** tile, click **Python Editor**.
7. In the code editor, enter the following Python code, which will generate an alert when a detection is deleted:

   ```python
   def rule(event):    
       return event.get('actionName') == 'DELETE_DETECTION'
   def title(event):
       return 'Detection deleted!'
   ```

   * This code defines a simple title using the [`title()`](https://docs.panther.com/detections/rules/python#title) function. Learn how to create a more descriptive title below, in [Creating a descriptive alert title](#creating-a-descriptive-alert-title).
8. In the **Create Alert** tile, under **Required Fields**, select a **Severity**.
9. Scroll down to the **Test** tile, and click **Add New**.
   * Continue in [Step 2: Create a test for the detection](#step-2-create-a-test-for-the-detection).

### Step 2: Create a test for the detection

In Step 1, you defined your detection and clicked **Add New** under **Test** to begin the process of testing.

Below, you will generate test data for the action you wrote a detection for. In the example, we defined a detection to check for the action of deleting a detection in the Panther Console.

1. In a separate browser tab, open your Panther Console. Perform the action you wrote a detection for to generate a test audit log.
   * In the example above, we defined a detection to check for the action of deleting a detection in the Panther Console. For this example, you would follow these steps:
     1. Navigate to **Build > Detections**.
     2. Create a test detection.
     3. After successfully creating the detection, delete it.
2. In the left sidebar, click **Investigate > Data Explorer**.
3. Execute a query to find the audit log for the action you are testing against.
   * Based on our example, we will use the following query to check for the recently deleted detection:

     ```sql
     SELECT * FROM panther_logs.panther_audit WHERE actionName = 'DELETE_DETECTION'
     ORDER BY timestamp DESC
     LIMIT 1;
     ```
   * If no results are returned, wait a few minutes and retry.
4. Copy the JSON object in the Data Explorer results representing this log. Navigate back to the detection you defined, then paste the JSON object into the **Test** text editor.
5. Leave the **The detection should trigger based on the example event** toggle set to `YES`.
6. Click **Run Test**.
   * Verify that the detection runs as expected and the alert title appears as expected.\
     ![The image shows the test from a rule in the Panther Console. At the bottom under the "Mock Testing" section, there is a message that says "PASS" and includes the alert title and dedup string for the successful test.](https://4011785613-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LgdiSWdyJcXPahGi9Rs-2910905616%2Fuploads%2Fgit-blob-a7ca9ead674dd6cc1d2ce6f830d171830ea5f435%2Faudit-detection-test.png?alt=media)
7. In the upper-right corner of the page, click **Deploy.**

### Creating a descriptive alert title

In the example above, we used a simple alert title:

```python
def title(event):
    return 'Detection deleted!'
```

You can construct a more descriptive alert title using the values found in the `actionParams` field within the audit log:

```python
def title(event):
    deleted_detection_id = event.get('actionParams').get('input').get('detections')[0].get('id')
    actor_type = event.get('actor').get('type').lower()
    actor_readable_id = event.get('actor').get('name') if event.get('actor').get('name') else event.get('actor').get('id')
    return f"Detection '{deleted_detection_id}' deleted by {actor_type} {actor_readable_id}!"
```

See the [log schema](https://docs.panther.com/data-onboarding/supported-logs/panther-audit-logs/..#schema) for more information on the audit log fields.

{% hint style="info" %}
The `actionParams` field is different for each audited action. To understand what information is present in this field for a given action, [query the data lake for audit logs for the given action](#querying-the-data-lake-for-panther-audit-logs) and use the results to inform how you write detections for that action.
{% endhint %}
