Metadata-Version: 2.4
Name: pyrsistencesniper
Version: 0.11.0
Summary: Offline Windows and Linux Persistence Detection
License-Expression: MIT
License-File: LICENSE
Keywords: forensics,dfir,incident-response,persistence,windows,linux,registry,threat-hunting,security,malware-analysis
Author: Maurice Fielenbach
Author-email: info@hexastrike.com
Requires-Python: >=3.11
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Information Technology
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Security
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: Utilities
Requires-Dist: asn1crypto (>=1.5,<2.0)
Requires-Dist: defusedxml (>=0.7,<1.0)
Requires-Dist: jinja2 (>=3.1,<4.0)
Requires-Dist: libregf-python (>=20240421)
Requires-Dist: lief (>=0.17,<2.0)
Requires-Dist: openpyxl (>=3.1,<4.0)
Requires-Dist: platformdirs (>=4.0,<5.0)
Requires-Dist: python-evtx (>=0.8,<1.0)
Requires-Dist: pyyaml (>=6.0.1,<7.0)
Requires-Dist: rich (>=13.7,<16.0)
Project-URL: Homepage, https://github.com/Hexastrike/PyrsistenceSniper
Project-URL: Issues, https://github.com/Hexastrike/PyrsistenceSniper/issues
Project-URL: Repository, https://github.com/Hexastrike/PyrsistenceSniper
Description-Content-Type: text/markdown

<div align="center">

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/Hexastrike/PyrsistenceSniper/main/assets/logo-white.png">
  <img src="https://raw.githubusercontent.com/Hexastrike/PyrsistenceSniper/main/assets/logo.png" alt="PyrsistenceSniper" width="220">
</picture>

# PyrsistenceSniper

**Offline Windows and Linux Persistence Detection**

[![PyPI](https://img.shields.io/pypi/v/pyrsistencesniper?color=blue)](https://pypi.org/project/pyrsistencesniper/) [![CI](https://github.com/Hexastrike/PyrsistenceSniper/actions/workflows/ci.yml/badge.svg)](https://github.com/Hexastrike/PyrsistenceSniper/actions/workflows/ci.yml) [![codecov](https://codecov.io/gh/Hexastrike/PyrsistenceSniper/graph/badge.svg)](https://codecov.io/gh/Hexastrike/PyrsistenceSniper) [![Python](https://img.shields.io/badge/python-3.11--3.14-3776AB?logo=python&logoColor=white)](https://pypi.org/project/pyrsistencesniper/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/Hexastrike/PyrsistenceSniper/blob/main/LICENSE) [![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20Linux%20%7C%20macOS-blue)](https://github.com/Hexastrike/PyrsistenceSniper)

We took PersistenceSniper, merged it with Python, and misspelled it on purpose. Meet **Py**rsistenceSniper.

Point it at a KAPE dump, a Velociraptor or UAC collection, or a mounted disk image and get offline persistence detection for Windows and Linux in seconds.<br>
No live system access, no admin privileges, no PowerShell. Runs on Windows, Linux, and macOS.

[Key Features](#-key-features) • [Installation](#-installation) • [Usage](#-usage) • [How It Works](#-how-it-works) • [Supported Checks](#%EF%B8%8F-supported-checks) • [Detection Profiles](#%EF%B8%8F-detection-profiles) • [Development](#%EF%B8%8F-development) • [Roadmap](#%EF%B8%8F-roadmap)

</div>

---

## 🚀 Key Features

- **Wide persistence coverage**: 166 checks across 13 MITRE ATT&CK techniques. Run keys, services, COM hijacking, scheduled tasks, WMI subscriptions, Office add-ins, IFEO injection, accessibility backdoors, startup folders, LSA packages, and more on Windows. Cron, at and anacron jobs, systemd services and timers, shell startup files, SSH keys and commands, PAM modules, sudoers rules, kernel modules, udev rules, and more on Linux.
- **Windows and Linux, one command**: The operating system is detected from the layout of the collection.
- **Signature-based filtering**: On Windows, Authenticode signatures that verify against the file separate real persistence from OS defaults. This catches swapped binaries and DLL proxying, which value-based whitelists miss.
- **Custom detection profiles**: YAML allow and block rules, globally or per check.
- **Finding context**: Every finding carries file existence, SHA-256, LOLBin classification, and an approximate last-change timestamp. Windows findings add the signer.
- **Flexible output**: Console, CSV, HTML, and XLSX.
- **Extensible plugin system**: A new persistence check is one file, usually declarative.
- **Speed**: Native registry parsing via libregf. Windows scans complete in roughly 10 to 30 seconds on heavily used systems, Linux scans in a few seconds.

## 📦 Installation

### From PyPI

```bash
pip install pyrsistencesniper
```

### From source

```bash
git clone https://github.com/Hexastrike/PyrsistenceSniper.git
cd PyrsistenceSniper
poetry install
```

### Docker

```bash
# Build the image
docker build -t pyrsistencesniper .

# Scan a triage collection
docker run --rm -v /path/to/triage:/evidence:ro pyrsistencesniper /evidence

# Export as CSV (evidence stays read-only, reports go to a separate writable mount)
docker run --rm -v /path/to/triage:/evidence:ro -v "$PWD/out":/out pyrsistencesniper /evidence --format csv --output /out/results.csv

# Full HTML report with no filtering
docker run --rm -v /path/to/triage:/evidence:ro -v "$PWD/out":/out pyrsistencesniper /evidence --min-severity info --format html --output /out/report.html
```

## 🎯 Usage

```
python -m pyrsistencesniper [options] path
```

The `path` argument is the root of your forensic collection. As long as the artifacts sit at their expected paths relative to that root, PyrsistenceSniper will find them.

| System | Root is the folder that holds | Typical sources |
|--------|-------------------------------|-----------------|
| Windows | `Windows/` | KAPE output, Velociraptor collections, mounted E01s, raw directory copies |
| Linux | `etc/` | UAC collections (`[root]`), Velociraptor collections (`uploads/auto`), mounted images |

The operating system is detected from that layout. If it matches neither, name the system with `--os`.

| Flag | Description |
|------|-------------|
| `--os {windows,linux}` | Operating system of the collection (default: detected from its layout) |
| `--format {console,csv,html,xlsx}` | Output format (default: `console`) |
| `--output FILE` | Write the report to a file (default: stdout). Required for `xlsx` |
| `--profile FILE` | YAML detection profile. Replaces the built-in allow/block rules; a file that is missing or malformed stops the scan |
| `--technique ID [...]` | Filter by MITRE ATT&CK technique or check ID |
| `--min-severity {info,low,medium,high}` | Minimum severity to include (default: `medium`). Use `info` to show everything |
| `--hostname NAME` | Override hostname (otherwise read from the collection) |
| `--mft FILE` | Windows: externally collected `$MFT` for change timestamps. Takes precedence over one auto-discovered in the collection |
| `--bodyfile FILE` | Linux: bodyfile for file existence, link targets and change timestamps. Takes precedence over one auto-discovered beside the root |
| `--no-timeline` | Skip last-change timestamp resolution |
| `--list-checks` | List all available checks and exit |
| `--update-lolbins` | Download the LOLBin lists (LOLBAS for Windows, GTFOBins for Linux) into the user cache and exit |
| `-v, --verbose` | Enable debug logging to stderr |

`--mft` is for Windows scans and `--bodyfile` for Linux scans. A scan that is given the other system's option, or both, stops with an error before any check runs.

### Examples

```bash
# Scan a KAPE collection
python -m pyrsistencesniper /mnt/case042/C

# Scan a UAC collection of a Linux host
python -m pyrsistencesniper '/mnt/case042/uac-web01/[root]'

# Export as CSV for stacking across multiple systems
python -m pyrsistencesniper /mnt/case042/C --format csv --output host1.csv

# Generate an HTML report
python -m pyrsistencesniper /mnt/case042/C --format html --output report.html

# Show everything, including OS defaults
python -m pyrsistencesniper /mnt/case042/C --min-severity info

# Only check specific MITRE ATT&CK techniques
python -m pyrsistencesniper /mnt/case042/C --technique T1547 T1546

# Apply a custom detection profile
python -m pyrsistencesniper /mnt/case042/C --profile ./profiles/customer_baseline.yaml

# Correlate change times against an externally collected $MFT
python -m pyrsistencesniper /mnt/case042/C --mft /mnt/case042/'$MFT' --format html --output report.html

# Scan a mounted Linux image with a bodyfile made from it
python -m pyrsistencesniper /mnt/case042/web01 --bodyfile /mnt/case042/web01.body

# List all available persistence checks
python -m pyrsistencesniper --list-checks
```

### Linux collections

A triage collection usually leaves out the system's programs, and symbolic links often get lost when it is collected or unpacked. A bodyfile closes that gap. It is the plain-text file listing that forensic tools exchange, one line per file with its mode, owner, link target and inode times, taken from the original filesystem. UAC writes one into its `bodyfile/` folder, and `fls -r -m / <device>` makes one from a disk image. A bodyfile beside the root is picked up automatically when it describes the same host.

With a bodyfile, a finding shows whether its target exists, where a link points, whether a systemd unit is enabled, and when its file last changed. Without one, those fields stay blank and there are no change timestamps.

### Standalone artifact scanning

Pass a single Windows hive file directly, no directory structure needed:

```bash
# Scan a standalone NTUSER.DAT
python -m pyrsistencesniper /path/to/NTUSER.DAT

# Scan a standalone SYSTEM hive with verbose output
python -m pyrsistencesniper /path/to/SYSTEM -v

# Scan a standalone SOFTWARE hive with CSV output
python -m pyrsistencesniper /path/to/SOFTWARE --format csv --output results.csv
```

Supported standalone artifacts: `SYSTEM`, `SOFTWARE`, `SAM`, `DEFAULT`, `NTUSER.DAT`, `UsrClass.dat`.

PyrsistenceSniper auto-detects standalone mode and runs only the checks that apply to the given hive. A single hive comes without a filesystem, so file existence, hashes and signers stay empty.

## 🔍 How It Works

PyrsistenceSniper runs each finding through a multi-stage pipeline:

1. **Plugin execution**: Each check reads the artifacts it knows. Registry hives, scheduled task XMLs, and WMI repositories on Windows. Cron tables, systemd units, shell startup files, and the SSH, PAM and sudo configuration on Linux.
2. **Resolution**: Findings are enriched with file existence, SHA-256 hash, signer, LOLBin classification, OS directory detection, and short triage notes.
3. **Severity classification**: Each finding is classified as `HIGH` (block rule match), `MEDIUM` (no rules match), `LOW` (partial allow match), or `INFO` (full allow match), then filtered by `--min-severity`. Plugins also reject invalid data (empty values, non-executable flags) unconditionally. On Windows this cuts output by 80 to 90% in most environments.
4. **Change timeline**: Each finding gets an approximate last-change timestamp, taken only from evidence that copying cannot rewrite.
5. **Output**: Findings are rendered in the requested format.

Console output groups findings by MITRE technique and warns when an evidence source or a check failed and produced nothing. CSV, XLSX and HTML list those gaps as `ERROR` rows ahead of the findings, and CSV and XLSX carry every column. The HTML report is a single standalone file with a search across all fields and columns you can sort and filter. Each row expands to the full finding and every timestamp candidate that was considered.

### Output columns

| Column | Description |
|--------|-------------|
| `Path` | Registry key or file the entry was read from |
| `Value` | Registry value, command line, or DLL path |
| `Technique`, `MITRE ID` | Human-readable technique name and its ATT&CK ID |
| `Access Gained` | `USER` or `SYSTEM` on Windows, `USER` or `ROOT` on Linux |
| `Severity` | `INFO`, `LOW`, `MEDIUM`, or `HIGH`. `ERROR` rows report something the scan could not read or a limit of the collection |
| `Last Change`, `Change Source`, `Change Evidence` | Approximate UTC time the mechanism last changed, which evidence set it, and why the cell holds what it holds |
| `Exists`, `SHA256` | Whether the referenced file exists on disk, and its hash |
| `Signer` | Authenticode signer name (Windows). Filled only when the embedded signature verifies against the file, or a catalog in the collection lists the file's own hash |
| `LOLBin`, `Launcher` | Whether the entry executes via a known LOLBin, and the launcher the value proxies through |
| `Builtin`, `OS Directory` | Whether the file is a known built-in Windows process, and whether it sits in a system directory |
| `Triage Notes` | Why the resolved file deserves a second look |
| `Check ID`, `Description`, `References`, `Hostname` | Which check fired, what the technique does, where to read more, and on which host |

### LOLBin classification

`LOLBin` describes **how the entry executes**. A value like `rundll32.exe C:\ProgramData\evil.dll,Start` resolves its payload to the DLL, which is what gets hashed and signer-checked, while `LOLBin` stays true and `Launcher` records `rundll32.exe`.

On Windows the LOLBin set is the [LOLBAS](https://lolbas-project.github.io/) list plus the shells LOLBAS leaves out (`powershell.exe`, `pwsh.exe`, `cmd.exe`). For persistence triage a payload launched through PowerShell is as notable as one launched through `mshta`.

On Linux the set is the [GTFOBins](https://gtfobins.org/) list. An entry is flagged when the program it runs or its interpreter is on it, so `python3 /opt/job.py` counts through `python`.

> **Note:** Both lists are downloaded on request. Run `python -m pyrsistencesniper --update-lolbins` once to store them in the user cache, and again whenever you want them refreshed. Until then the `LOLBin` column is empty.

### Last change timestamps

`Last Change` approximates when each persistence mechanism was last modified. A timestamp appears only when it comes from evidence that copying cannot rewrite:

| System | Evidence | Dates |
|--------|----------|-------|
| Windows | A file's `$MFT` record | File-backed findings |
| Windows | A matching event log entry: task registered, updated or deleted (`4698`, `4702`, `4699`, `106`, `140`, `141`), service installed (`7045`) | Scheduled tasks and services |
| Windows | A Sysmon registry value event (`13`) that names the value | Registry findings, where Sysmon was logging |
| Linux | A file's bodyfile entry | The file a finding was read from |

Plugins declare which artifact and which events date their findings. Otherwise a file-backed finding falls back to its own record and a registry finding to the Sysmon event that recorded the write, so it stays blank on a host without Sysmon.

Two sources are left out. The modification times of collected files can be copy times in a repacked collection. Registry key write times stamp the whole key, so any value in a shared key changes them. Those cells stay empty.

On Linux the timestamp candidate shown in the HTML report also carries the inode change and creation times where the filesystem kept them, with a backdating hint when the content time is older than the file itself.

`Change Evidence` is `RESOLVED` when the cell holds a time. For an empty cell it gives the reason:

| Value | Meaning |
|-------|---------|
| `NOT_RUN` | The timeline pass was switched off with `--no-timeline` |
| `NOT_APPLICABLE` | No evidence source applies: nothing dates this kind of finding, or the key belongs to a user whose SID the image does not record |
| `NO_ARTIFACT` | Evidence was declared, but the `$MFT`, event log, or bodyfile it needs was absent or cleared. Going back for that artifact would fill the cell |
| `NO_MATCH` | The artifact was read and had nothing to say about this entry |
| `REJECTED` | Times were found and every one of them was implausible |

Supply an externally collected `$MFT` with `--mft` or a bodyfile with `--bodyfile` (either wins over an auto-discovered one), or turn the pass off with `--no-timeline`.

## 🛡️ Supported Checks

166 persistence checks across 13 MITRE ATT&CK techniques: 125 for Windows and 41 for Linux. Run `python -m pyrsistencesniper --list-checks` for every check with its ID and sub-technique. The ID is what `--technique` and per-check profile rules take, and every finding carries it in the `Check ID` column.

### Windows

| MITRE ID | Technique | Covers |
|----------|-----------|--------|
| T1037 | Boot or Logon Initialization Scripts | Logon scripts, Group Policy scripts |
| T1053 | Scheduled Task/Job | Scheduled task files, hidden tasks, ghost tasks |
| T1098 | Account Manipulation | Administrators group membership, RID hijacking |
| T1137 | Office Application Startup | Add-ins, default templates, test DLL, DLL overrides, Outlook home page, VBA monitors |
| T1197 | BITS Jobs | Job notification commands |
| T1543 | Create or Modify System Process | Service image paths, service DLLs, failure commands |
| T1546 | Event Triggered Execution | WMI event subscriptions, COM hijacking, IFEO and Silent Process Exit, AeDebug and WER debuggers, accessibility features, AppInit and AppCert DLLs, application shims, AMSI providers, netsh helpers, file association and protocol handlers, screensaver, PowerShell profiles, cmd AutoRun, Windows Terminal profiles, Power Automate flows, and more |
| T1547 | Boot or Logon Autostart Execution | Run keys, startup folders, Winlogon values, Active Setup, LSA authentication and security packages, LSA protection settings, boot and session manager execution, print monitors and processors, time providers, Explorer extensions, RDP and Terminal Services startup, Shell Launcher, and more |
| T1556 | Modify Authentication Process | LSA password filters, network provider DLLs |
| T1564 | Hide Artifacts | Hidden local accounts |
| T1574 | Hijack Execution Flow | .NET profilers, startup hooks and AppDomainManager, KnownDLLs and DLL search order, the DiagTrack trace log, DLL overrides for MSDTC, DNS server, SNMP, Search and Winsock, Group Policy extensions, LSA extensions, and more |

### Linux

| MITRE ID | Technique | Covers |
|----------|-----------|--------|
| T1037 | Boot or Logon Initialization Scripts | `rc.local`, System V and OpenRC init scripts, `inittab`, message-of-the-day scripts, SSH rc files |
| T1053 | Scheduled Task/Job | System crontabs, per-user crontabs, periodic cron scripts, anacron jobs, at jobs, systemd system and user timers |
| T1098 | Account Manipulation | SSH authorized keys, including forced commands and the key files `AuthorizedKeysFile` adds, service accounts with a password, members of the groups sudoers rules name |
| T1136 | Create Account | Accounts other than root with user ID 0 |
| T1543 | Create or Modify System Process | systemd system and user services, including drop-ins, systemd generators, D-Bus services |
| T1546 | Event Triggered Execution | Shell startup files, udev rules, APT hooks, Python startup hooks, SSH daemon and client commands, network hook scripts, git configuration commands, logrotate scripts |
| T1547 | Boot or Logon Autostart Execution | XDG autostart entries, kernel modules loaded at boot, modprobe install and remove commands |
| T1548 | Abuse Elevation Control Mechanism | sudoers rules, doas rules, polkit rule files |
| T1556 | Modify Authentication Process | PAM modules, `pam_exec` commands |
| T1574 | Hijack Execution Flow | `/etc/ld.so.preload`, `LD_PRELOAD` and `LD_AUDIT` in environment files and service units |

## ⚙️ Detection Profiles

Detection profiles suppress known-good findings or force-flag specific values. Rules are written in YAML and apply globally or per check.

```yaml
# Global allow rules, applied to all checks. Keep these narrow: a global rule
# merges into every check, so it cannot be anchored to any one artifact.
allow:
  - path_matches: "\\\\Contoso\\\\"
    reason: "Known enterprise software"

# Global block rules, force-flag regardless of other rules
block:
  - value_matches: "suspicious\\.exe"
    reason: "Known malicious binary"

# Per-check overrides
checks:
  run_keys:
    allow:
      - value_matches: "SecurityHealthSystray"
        signer: "Microsoft"
        reason: "Built-in Windows Security tray icon"

  ghost_task:
    enabled: false  # Disable this check entirely
```

Each operating system ships a built-in profile. A profile passed with `--profile` replaces it, so start from a copy of `pyrsistencesniper/windows/profile.yaml` to keep the Windows defaults.

A profile that cannot be applied as written stops the scan, with a message naming the place. That covers a missing file, a file in neither UTF-8 nor UTF-16, a key repeated in one mapping, an unknown key, a rule without a condition, a rule field that is not text or is blank, a `hash` other than 64 hex digits, an `enabled` that is not `true` or `false`, and an invalid regular expression.

### Rule fields

A rule needs at least one condition field (`signer`, `path_matches`, `value_matches` or `hash`). Comparisons are case-insensitive.

| Field | Match Type | Description |
|-------|-----------|-------------|
| `signer` | substring | Authenticode signer name |
| `path_matches` | regex | Registry key or file path |
| `value_matches` | regex | Registry value or command line |
| `hash` | exact | SHA-256 hash of the referenced file |
| `reason` | n/a | Human-readable justification. It documents the rule and is not shown in any output |

`path_matches`, `value_matches` and `hash` are **hard** conditions: every one present must match for the rule to apply. `signer` is a **soft** condition. When the hard conditions match and the `signer` does not, the rule matches partially and the finding is rated `LOW`. A full match rates it `INFO`. A rule with only a `signer` applies when the signer matches. The partial match exists because a binary the collection never captured has no signer to compare.

### Rule evaluation

Rules come from two layers, evaluated together:

| Layer | Source | Scope |
|-------|--------|-------|
| **Profile global** | Top-level `allow`/`block` in the YAML | All checks |
| **Profile per-check** | `checks.<id>.allow`/`block` in the YAML | That check only |

Per-check profile rules **add to** global rules. A check with one per-check allow rule and two global allow rules has three allow rules total.

**Block rules win.** The pipeline evaluates block rules first. If any block rule from any layer matches in full, the finding is `HIGH` and allow rules are not considered. Allow rules only affect findings that no block rule matched.

## 🛠️ Development

Poetry for dependency management, ruff for linting and formatting, mypy in strict mode, pytest for testing.

```bash
poetry install                    # Install with dev dependencies
poetry run pytest                 # Run tests
poetry run ruff check             # Lint
poetry run ruff format            # Format
poetry run mypy pyrsistencesniper # Type check
make all                          # All of the above
make cov                          # Tests with coverage report
```

### Project layout

```
pyrsistencesniper/
  cli.py              # Entry point and argument parsing
  core/               # Knows no operating system: domain models, platform contract,
                      #   detection profiles, scan ledger, timeline selection, logging
  windows/            # Registry and its declarative engine, contained path lookup,
                      #   signer verification, SAM, Office and shell link parsing,
                      #   $MFT and event log evidence, built-in profile
  posix/              # Shared by Unix-like systems: image tree with symlink
                      #   resolution, bodyfile, account, shell, cron and SSH key parsers
  linux/              # Accounts, systemd units, SSH, sudoers and PAM configuration,
                      #   resolution, bodyfile evidence, built-in profile
  detection/          # Pipeline orchestration and operating system detection
  output/             # Row shaping and the console, CSV, HTML, XLSX writers
  plugins/            # Detection plugins
    __init__.py       # Plugin discovery and registration
    base.py           # PersistencePlugin base class
    windows/          # WindowsPlugin base class, checks grouped by technique
    linux/            # LinuxPlugin base class, checks grouped by technique
  ui/                 # CLI presentation: banner, progress display
```

### Adding a plugin

Plugins live in `pyrsistencesniper/plugins/<system>/`, organized by technique ID. Most checks are fully declarative:

```python
"""Detect user logon script persistence via UserInitMprLogonScript (T1037.001)."""

from __future__ import annotations

from pyrsistencesniper.core.models import CheckDefinition
from pyrsistencesniper.plugins import register_plugin
from pyrsistencesniper.plugins.windows.base import WindowsPlugin
from pyrsistencesniper.windows.engine import HiveScope, RegistryTarget


@register_plugin
class LogonScripts(WindowsPlugin):
    """Reports the UserInitMprLogonScript value of each user's Environment key."""

    definition = CheckDefinition(
        id="logon_scripts",
        technique="Logon Scripts (UserInitMprLogonScript)",
        mitre_id="T1037.001",
        description=(
            "UserInitMprLogonScript in a user's Environment key runs a "
            "script at each logon of that user, in that user's own context."
        ),
        targets=(
            RegistryTarget(
                path="Environment",
                values="UserInitMprLogonScript",
                scope=HiveScope.HKU,
            ),
        ),
    )
```

The base class reads the declared targets and builds the findings. A `RegistryTarget` can select one value, several, or all of them (`values`), read each direct subkey (`recurse`), add the 32-bit view (`include_wow64`), read RunOnceEx style section subkeys (`sections`), or report value names where the names are the entries (`report_names`). For custom logic (filesystem walking, cross-referencing several hives), override `run()` and return a `list[Finding]`. The plugin gets `self.context` (`machine_key`, `control_set_key`, `services`, `class_roots`, `iter_user_hives`), `self.registry` (`open_key`, `default_value`) and `self.filesystem`, whose `resolve()` maps a Windows path into the image and returns `None` for one that leaves it, and whose `files()` and `directories()` list a folder without following links. Anything a check could not read is recorded with `record_artifact_failure`, so it shows up in the report.

A Linux check has the same shape: derive from `LinuxPlugin` and declare a `FileTarget` from `pyrsistencesniper.linux.engine`, where every file found in the listed paths is one finding. The plugin gets `self.context` (accounts and their home directories) and `self.filesystem`, which resolves symbolic links inside the image.

When a finding's value is not the command line the entry runs, pass `command` to `make_finding` (an empty string when nothing is executed) or `resolve_target` for the file to inspect, so the resolution columns describe the right file. Pass `time_evidence` to tell the timeline stage what dates a finding: a `FileWriteTime` for the artifact's `$MFT` record or bodyfile entry, an `EventLogTime` to correlate against a Windows log channel, or both.

## 🗺️ Roadmap

PyrsistenceSniper is an offline hunter for Windows and Linux. These are the directions being considered, roughly in the order they are likely to land.

| Area | What it would add | Notes |
|------|-------------------|-------|
| **Live mode** | Scan the running host directly | The engine is offline-only today: every read goes through `pyregf` against hive files. Live mode means a second registry backend behind the same `WindowsContext` API, plus the privilege and locked-hive handling that comes with it. |
| **macOS persistence** | Launch agents and daemons, login items, `emond`, configuration profiles, TCC abuse | Same shape as the Linux work, reusing the `posix/` layer Linux already stands on. |
| **Entra ID** | Tenant-side persistence: app registrations and consent grants, federation trust changes, long-lived refresh tokens, role assignments | Identity persistence in the tenant. Would read exported tenant data, so it is the furthest from the current architecture. |

## 📖 Background

[PersistenceSniper](https://github.com/last-byte/PersistenceSniper) by Federico Lagrasta and [Autoruns](https://learn.microsoft.com/en-us/sysinternals/downloads/autoruns) by Sysinternals are the two tools that come up every time someone talks about Windows persistence detection. Both are great. Both were direct inspiration for this project.

Where we kept running into friction was the workflow. Autoruns is a Windows binary. If your analysis box runs Linux, you're out of luck. PersistenceSniper is PowerShell, which is powerful on live systems but awkward when you have twenty KAPE collections on a SIFT workstation. And when a new persistence technique drops, adding a check means working through a larger codebase. We wanted to drop in a single file.

We kept writing one-off scripts to cover the gaps, and at some point it made more sense to build something purpose-built.

## 🙏 Credits

- [PersistenceSniper](https://github.com/last-byte/PersistenceSniper) by Federico Lagrasta
- [Autoruns](https://learn.microsoft.com/en-us/sysinternals/downloads/autoruns) by Sysinternals
- [libregf](https://github.com/libyal/libregf) by Joachim Metz
- [MITRE ATT&CK](https://attack.mitre.org/)

## ⚖️ License

Distributed under the **MIT License**. See [LICENSE](https://github.com/Hexastrike/PyrsistenceSniper/blob/main/LICENSE).

