> For the complete documentation index, see [llms.txt](https://support.attackforge.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://support.attackforge.com/app/automations-and-integrations/configuring-splunk-integration.md).

# Configuring Splunk Integration

## Overview

Send AttackForge's audit logs to Splunk, so you can search, alert on and keep a record of activity in AttackForge alongside your other security data.

A small script runs on your Splunk Heavy Forwarder every 5 minutes. It fetches new audit log entries through the [Self-Service RESTful API](https://support.attackforge.com/app/automations-and-integrations/self-service-restful-api), and Splunk indexes each entry as an event.

<figure><img src="https://372186556-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M8s1QY2Q6YTHB4a6DMu%2Fuploads%2F1rDoXMjbyJFA21ZcHwVz%2Fsplunk-integration-at-a-glance.svg?alt=media&amp;token=04f8c596-e0a8-4514-af07-ecf50a135a8a" alt=""><figcaption></figcaption></figure>

## Why it matters

| Benefit                      | What it means                                                               |
| ---------------------------- | --------------------------------------------------------------------------- |
| **One place to investigate** | Search AttackForge activity alongside your other logs                       |
| **Alerting**                 | Alert on activity such as failed logins, permission changes or bulk exports |
| **Retention and compliance** | Keep audit logs for as long as your policy requires                         |
| **No duplicates**            | The script saves its place, so each entry is collected once                 |
| **Safe retries**             | If a run fails, the next one picks up where it left off                     |

## Who uses it

| Role                           | Typical use                                  |
| ------------------------------ | -------------------------------------------- |
| **Security operations teams**  | Monitor and alert on AttackForge activity    |
| **Splunk administrators**      | Install and run the scripted input           |
| **AttackForge administrators** | Create the service user and grant API access |
| **Compliance and audit teams** | Keep and review a record of activity         |

## What you need

* An AttackForge administrator, to create the service user and grant access
* A Splunk Heavy Forwarder that can reach your AttackForge tenant over HTTPS
* Python 3 and the `requests` library on the Heavy Forwarder.
* A Splunk index for the events. The example uses `security`.

## Set up AttackForge

1. **Create a service user for Splunk.** Use a dedicated user, so the integration's access is easy to review and switch off.
2. **Give the user access to the audit logs API.** Go to **Users**, select the user, then **Access > Self-Service RESTful API > Add Access**, and add **GetApplicationAuditLogs**.
3. **Create the user's API key.** Log in as the service user, go to **Profile > Secrets**, and copy the key from **API Key**.

The script sends the key in the `X-SSAPI-KEY` header. Every call must use HTTPS.

<figure><img src="https://372186556-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M8s1QY2Q6YTHB4a6DMu%2Fuploads%2FKi9tHpqbcf4kX5UiU6Pe%2Fimage.png?alt=media&amp;token=97ec6fc1-375e-4d43-8bac-e8a8b87474bb" alt=""><figcaption></figcaption></figure>

<figure><img src="https://372186556-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M8s1QY2Q6YTHB4a6DMu%2Fuploads%2FLCKxFwt6elWfoFGGT2uw%2Fimage.png?alt=media&amp;token=ff71f605-d657-4874-9e8b-fead32adf862" alt=""><figcaption></figcaption></figure>

<figure><img src="https://372186556-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M8s1QY2Q6YTHB4a6DMu%2Fuploads%2FX38aKyGwN71M1v8HqBAz%2Fimage.png?alt=media&amp;token=5e857712-e16f-4200-b770-8e7e278f23b4" alt=""><figcaption></figcaption></figure>

## Set up Splunk

Do these steps on the Heavy Forwarder.

### 1. Create the app folders

```
$SPLUNK_HOME/etc/apps/attackforge_app/
├── bin/
│   └── af_auditlogs.py
└── default/
    └── inputs.conf
```

### 2. Add the script

Save this as `bin/af_auditlogs.py`:

```python
#!/usr/bin/env python3
import json, os, sys
import requests

BASE       = os.environ["AF_BASE_URL"]          # https://<tenant>.attackforge.com
API_KEY    = os.environ["AF_SSAPI_KEY"]
LIMIT      = 5000                                # max supported
CHECKPOINT = os.path.join(
    os.environ.get("SPLUNK_DB", "/opt/splunk/var/lib/splunk"),
    "modinputs", "af_auditlogs", "offset.json"
)

def read_offset():
    try:
        with open(CHECKPOINT) as fh:
            return int(json.load(fh)["skip"])
    except (OSError, ValueError, KeyError):
        return 0                                 # first run: start from the beginning

def write_offset(skip):
    os.makedirs(os.path.dirname(CHECKPOINT), exist_ok=True)
    tmp = CHECKPOINT + ".tmp"
    with open(tmp, "w") as fh:
        json.dump({"skip": skip}, fh)
        fh.flush()
        os.fsync(fh.fileno())
    os.replace(tmp, CHECKPOINT)                  # atomic; never leaves a half-written file

def main():
    skip    = read_offset()
    session = requests.Session()
    session.headers.update({
        "X-SSAPI-KEY": API_KEY,
        "Content-Type": "application/json",
        "Connection": "close",
    })

    while True:
        resp = session.get(
            f"{BASE}/api/ss/auditlogs",
            params={
                "skip": skip,
                "limit": LIMIT,
                "include_request_body": "true",
            },
            timeout=120,
        )
        resp.raise_for_status()

        logs = resp.json().get("logs", [])
        if not logs:
            break

        for entry in logs:
            sys.stdout.write(json.dumps(entry) + "\n")
        sys.stdout.flush()                       # get events out before advancing the offset

        skip += len(logs)
        write_offset(skip)

        if len(logs) < LIMIT:
            break                                # caught up; wait for the next interval

if __name__ == "__main__":
    try:
        main()
    except Exception as exc:
        # stderr from a scripted input lands in splunkd.log — offset stays put, so the
        # next run re-requests the same page rather than skipping it
        sys.stderr.write(f"ERROR af_auditlogs: {exc}\n")
        sys.exit(1)
```

On Linux, make it executable: `chmod +x bin/af_auditlogs.py`.

#### **How the script works**

| Step           | What happens                                                                                                     |
| -------------- | ---------------------------------------------------------------------------------------------------------------- |
| Read its place | Reads the number of entries already collected (`skip`) from `offset.json`. On the first run, it starts from 0.   |
| Fetch a page   | Calls `GET /api/ss/auditlogs` for up to 5,000 entries (`limit`), starting after `skip`, including request bodies |
| Send to Splunk | Writes each entry to standard output as one JSON line, which Splunk indexes as an event                          |
| Save its place | Adds the number of entries to `skip`, and saves it safely to `offset.json`                                       |
| Repeat or stop | Fetches the next page, or stops when there are no more entries or fewer than 5,000                               |
| Handle errors  | Writes the error to `splunkd.log` and leaves `skip` unchanged, so the next run tries the same page again         |

### 3. Set the AttackForge URL and API key

The script reads two environment variables:

| Variable       | Value                                                            |
| -------------- | ---------------------------------------------------------------- |
| `AF_BASE_URL`  | Your AttackForge URL, such as `https://<tenant>.attackforge.com` |
| `AF_SSAPI_KEY` | The service user's API key                                       |

Set them where Splunk's scripted inputs can read them, such as in `$SPLUNK_HOME/etc/splunk-launch.conf`, then restart Splunk.

{% hint style="info" %}
**Warning:** Anyone who can read the variable or file can use the key. Restrict access to it.
{% endhint %}

### 4. Configure the input

Save this as `default/inputs.conf`:

```
[script://$SPLUNK_HOME/etc/apps/attackforge_app/bin/af_auditlogs.py]
disabled = 1
interval = 300
index = security
sourcetype = attackforge:auditlog
source = attackforge:ssapi
python.version = python3
```

| Setting                             | What it does                                                                          |
| ----------------------------------- | ------------------------------------------------------------------------------------- |
| `disabled = 1`                      | The input starts switched off                                                         |
| `interval = 300`                    | Runs the script every 300 seconds (5 minutes)                                         |
| `index = security`                  | Stores the events in the `security` index. Make sure this index exists, or change it. |
| `sourcetype = attackforge:auditlog` | Labels the events, so you can search and parse them                                   |
| `source = attackforge:ssapi`        | Records where the events came from                                                    |
| `python.version = python3`          | Runs the script with Python 3                                                         |

### 5. Turn on the input

The input ships switched off. To turn it on, create `local/inputs.conf` with the same stanza and `disabled = 0`, or enable it under **Settings > Data inputs > Scripts**. Then restart Splunk.

## Check it's working

After the first interval, search for:

```
index=security sourcetype=attackforge:auditlog
```

If nothing appears:

| Check                     | How                                                                                  |
| ------------------------- | ------------------------------------------------------------------------------------ |
| Errors from the script    | Search `splunkd.log` for `ERROR af_auditlogs`                                        |
| The input is on           | Check `disabled = 0` in `local/inputs.conf`, or **Settings > Data inputs > Scripts** |
| The environment variables | Check `AF_BASE_URL` and `AF_SSAPI_KEY` are set for Splunk                            |
| API access                | Check the service user has **GetApplicationAuditLogs**, and the key is current       |
| The index                 | Check the `security` index exists                                                    |
| Python                    | Check Python 3 and `requests` are available to Splunk                                |

To collect everything again from the start, stop Splunk, delete `offset.json` under `$SPLUNK_DB/modinputs/af_auditlogs/`, and start Splunk. This re-indexes every entry, so you'll get duplicates of events already collected.

## Tips

* **Use a dedicated service user** with only **GetApplicationAuditLogs**, so the integration can't do anything else.
* **Protect the API key.** Store it where only Splunk can read it, and rotate it on a schedule.
* **Test the script by hand first.** Run it once with the environment variables set and check it prints JSON lines, before you turn on the input.
* **Expect a large first run.** The first run collects your whole audit history, 5,000 entries at a time.
* **Use a dedicated index** if you want separate retention or access controls for AttackForge logs.
* **Build alerts on the sourcetype.** Search `sourcetype=attackforge:auditlog` for events such as failed logins or permission changes.
* **Keep the interval sensible.** Every 5 minutes is a good balance. Shorter intervals add load without much benefit.
* **Don't delete `offset.json` casually.** It's how the script avoids duplicates.

## FAQ

**What data is sent to Splunk?** AttackForge's application audit logs, including request bodies (`include_request_body=true`).

**How often is data collected?** Every 5 minutes (`interval = 300`). Change the interval in `inputs.conf`.

**Will I get duplicate events?** No, in normal running. The script saves how many entries it has collected and continues from there. You'll get duplicates only if you delete `offset.json`.

**What happens if AttackForge can't be reached?** The run fails and logs an error in `splunkd.log`. The next run tries the same page again, so nothing is missed.

**Do I need a Heavy Forwarder?** The page is written for one.

**Can I use a different index?** Yes. Change `index` in `inputs.conf`, and make sure the index exists.

**Can an administrator create the service user's API key?** No. Users create their own key, so log in as the service user to create it.

**Do I need to exclude request bodies?** Remove `include_request_body` from the script if you don't want them, for example to reduce data volume.

## Related pages

* [Self-Service RESTful API](https://support.attackforge.com/app/automations-and-integrations/self-service-restful-api): give users access to API methods, and create API keys.
* [API documentation](https://docs.attackforge.com/rest-api/pages/getting-started): the audit logs API method and its fields.
* [Self-Service Events API](https://support.attackforge.com/app/automations-and-integrations/self-service-events-api): receive events as they happen.
* [Flows](https://support.attackforge.com/app/automations-and-integrations/flows): send AttackForge data to other systems.
* [Splunk: Scripted inputs](https://docs.splunk.com/Documentation/Splunk/latest/AdvancedDev/ScriptedInputsIntro): how Splunk runs scripts.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://support.attackforge.com/app/automations-and-integrations/configuring-splunk-integration.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
