Metadata-Version: 2.4
Name: ubuntils
Version: 2.3.0
Summary: Ubuntu incident response tool for forensic artifact collection, detection, and guided remediation
Author-email: Asmit Desai <asmitdesai02@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/asmitdesai/ubuntils
Project-URL: Repository, https://github.com/asmitdesai/ubuntils
Project-URL: Issues, https://github.com/asmitdesai/ubuntils/issues
Keywords: incident-response,forensics,ubuntu,security,dfir
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Intended Audience :: System Administrators
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: click>=8.1.0
Requires-Dist: textual>=0.50.0
Requires-Dist: structlog>=24.0.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: python-dateutil>=2.8
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Dynamic: license-file

# ubuntils

Forensic triage for live Ubuntu systems — automated artifact collection, persistence detection, and guided remediation in about a minute.

[![CI](https://github.com/asmitdesai/ubuntils/actions/workflows/ci.yml/badge.svg)](https://github.com/asmitdesai/ubuntils/actions/workflows/ci.yml)
![Python](https://img.shields.io/badge/python-3.9%2B-blue)
![License](https://img.shields.io/badge/license-MIT-blue)
![Arch](https://img.shields.io/badge/arch-amd64%20%7C%20arm64-lightgrey)
![Ubuntu](https://img.shields.io/badge/ubuntu-22.04%20%7C%2024.04%20%7C%2026.04-orange)
![Offline analysis](https://img.shields.io/badge/offline%20analysis-collect%20%2B%20analyze-blueviolet)
![Detection rules](https://img.shields.io/badge/detection%20rules-17-informational)
![SIEM](https://img.shields.io/badge/SIEM-Wazuh-yellow)

---

## The Problem

When you suspect a Linux system is compromised, the first 30-40 minutes are usually spent running the same ten commands in sequence: check running processes, look for weird cron jobs, grep for LD_PRELOAD, scan authorized_keys for new entries, audit sudoers. Each step is manual, context-switching, and error-prone under pressure. Miss one source — say, `/etc/sudoers.d/` instead of just `/etc/sudoers`, or user crontabs in addition to `/etc/cron.d/` — and you have an incomplete picture.

Existing options don't solve this cleanly. `lynis` is a hardening auditor, not a triage tool — it reports configuration weaknesses on a clean system and generates noise on a hot one. `chkrootkit` and `rkhunter` check for known rootkit signatures but are blind to novel persistence techniques like abused systemd timers or legitimate-looking cron entries. Generic SIEM queries require log infrastructure that may not exist on the system you're looking at. And forensic suites like Volatility target memory images, not a live shell on a running host.

The gap is a tool that runs on the live system right now, covers the most common persistence vectors, correlates activity across log sources into a timeline, and tells you exactly what to look at — without requiring an external agent, a database, or an internet connection.

---

## What ubuntils does

ubuntils runs in four sequential stages:

1. **Collection** — Eleven collectors, run one after another, gather forensic artifacts from `/proc`, cron tables, systemd units, SSH keys, sudoers files, environment definitions, package integrity (`dpkg --verify`), PAM/NSS config, and loaded kernel modules. Most collectors finish in a second or two; `dpkg --verify`, which re-checks every installed package file, dominates — a full scan took 29–68 seconds on an Ubuntu 26.04 arm64 desktop VM.
2. **Detection** — A detection engine runs all seventeen built-in rules — plus any custom rules loaded with `--rules` — over the collected artifacts, producing a ranked, confidence-scored findings list in about one second.
3. **Timeline** — A timeline builder reads syslog, journald, and auditd and correlates events chronologically, adding roughly 0.3 seconds. Each finding is then auto-correlated against the timeline, so it carries the nearby events that relate to it.
4. **Output** — Results appear either in an interactive four-tab TUI (default) or as structured JSON on stdout (`--json`).

ubuntils itself makes no network calls, and every feature — custom rules and correlation included — runs against locally collected artifacts. The one way findings can leave the host is the [Wazuh integration](#wazuh-integration): if a Wazuh agent is installed, a live `scan` writes its findings to a local file that *the agent* then ships to its manager. Pass `--no-wazuh` to turn that off for a run.

`ubuntils scan` is unchanged by everything below — it is still 100% live, single-host, and every existing flag works identically. Two additional commands, `collect` and `analyze`, split the same detection/timeline pipeline into an offline-friendly acquire-then-analyze workflow for cases where you can't (or don't want to) run detection directly on the host under investigation — see [Offline analysis: collect and analyze](#offline-analysis-collect-and-analyze) below, including its detection-coverage caveats.

---

## Installation

ubuntils runs as root on a host that may be compromised, so install it where only root can change it. If the code lives somewhere your user can write (pipx's default `~/.local`, a venv in your home directory, an editable checkout), then anything running as your user, possibly the attacker, can modify ubuntils and get root the next time you run it. Before escalating, `scan`, `collect` and `rollback` check that the interpreter, `sys.prefix` and the ubuntils package, plus every directory above them, are root-owned and not writable by group or others. If any of them fails the check, ubuntils refuses to escalate unless you pass `--allow-user-install` (see below).

Install a release, not `main`. Replace `vX.Y.Z` below with the latest tag from the [Releases](https://github.com/asmitdesai/ubuntils/releases) page.

**Recommended: root-owned install with pipx 1.5+ (`--global`)**

```bash
sudo pipx install --global "git+https://github.com/asmitdesai/ubuntils.git@vX.Y.Z"
ubuntils scan              # run as your user; it re-invokes itself with sudo
```

From PyPI, pin the same release: `sudo pipx install --global "ubuntils==X.Y.Z"`.

**Root-owned virtual environment** (any Ubuntu; the `pipx` in Ubuntu 24.04's apt is older than 1.5):

```bash
sudo python3 -m venv /opt/ubuntils
sudo /opt/ubuntils/bin/pip install "git+https://github.com/asmitdesai/ubuntils.git@vX.Y.Z"
sudo ln -s /opt/ubuntils/bin/ubuntils /usr/local/bin/ubuntils
ubuntils scan
```

Both put the command on sudo's `secure_path` (`/usr/local/bin`), so `sudo ubuntils …` from a root shell works too. To pin every dependency by hash as well, see [Verified dependencies](#verified-dependencies).

**Per-user install (development, or a lab VM you don't mind trusting):**

```bash
sudo apt install pipx -y
pipx ensurepath            # then open a new shell
git clone https://github.com/asmitdesai/ubuntils.git
cd ubuntils
git checkout vX.Y.Z
pipx install -e .
ubuntils --allow-user-install scan
```

ubuntils will refuse to escalate from this install until you pass `--allow-user-install` (before the subcommand), and it lists the user-writable paths it found. Typing `sudo ubuntils …` yourself fails with `command not found`, because sudo's `secure_path` doesn't include `~/.local/bin` where pipx puts the command.

ubuntils requires root for full artifact access. If you run `ubuntils scan` as a non-root user it will automatically re-invoke itself with `sudo` using the same Python interpreter (by absolute path, in isolated mode `-I`), so the correct environment is used without forwarding your `PATH`, `PYTHON*` variables or working directory into the root process. Every external command (`ss`, `dpkg`, `systemctl`, …) is resolved on a fixed, root-owned search path, never your `PATH`. Running without root will skip `/etc/shadow`, some `/proc` entries, and protected cron files, and will log warnings for each. A report that `scan --output FILE` creates after re-invoking itself through `sudo` is owned by you (still mode `0600`), so you can open it without `sudo`; an existing file is overwritten only if it belongs to you (or root) and isn't a hard link, and it keeps its owner. `collect` bundles stay root-only because they contain `/etc/shadow`, and are never written into a file that already exists.

### Verified dependencies

`requirements.lock` pins every runtime dependency, plus the build backend, to an exact version and SHA-256. With `--require-hashes`, pip refuses anything that doesn't match, including a compromised or substituted package on the index. Take the lock from the same release tag you install:

```bash
git clone --branch vX.Y.Z https://github.com/asmitdesai/ubuntils.git ubuntils-src
sudo python3 -m venv /opt/ubuntils
sudo /opt/ubuntils/bin/pip install --require-hashes -r ubuntils-src/requirements.lock
sudo /opt/ubuntils/bin/pip install --no-deps --no-build-isolation ./ubuntils-src
sudo ln -s /opt/ubuntils/bin/ubuntils /usr/local/bin/ubuntils
```

`--no-deps --no-build-isolation` installs ubuntils itself using only the hash-checked packages from the first step. The lock targets Python 3.10+ (Ubuntu 22.04 and later). It's regenerated with `make lock` and audited by `pip-audit` in CI.

---

## Quick start

**Detection only — interactive TUI:**

```bash
ubuntils scan
```

**Detection with JSON output saved to file:**

```bash
ubuntils scan --json > /tmp/triage-$(hostname)-$(date +%Y%m%d).json
```

**Detection with CLI remediation preview (dry run — no changes applied):**

```bash
ubuntils scan --remediate
```

**Detection with CLI remediation applied:**

```bash
ubuntils scan --remediate --confirm
```

**Print version:**

```bash
ubuntils version
```

**Collect a tamper-evident bundle for later or offline analysis:**

```bash
ubuntils collect --output /path/to/bundle.tar.gz
```

**Analyze a previously collected bundle (no root required):**

```bash
ubuntils analyze /path/to/bundle.tar.gz --json
```

**Analyze a mounted forensic image or extracted filesystem tree instead of a bundle:**

```bash
ubuntils analyze --root /mnt/forensic-image --json
```

See [Offline analysis: collect and analyze](#offline-analysis-collect-and-analyze) for the bundle format and — importantly — what offline analysis cannot detect compared to a live `scan`.

---

## Flags and configuration

```
ubuntils scan [OPTIONS]
  --json              Output JSON to stdout instead of launching the TUI
  --output FILE       Write the JSON report to FILE (implies --json)
  --remediate         Run the remediation engine after detection
  --confirm           Required with --remediate to actually apply changes (else dry-run)
  --min-confidence N  Only auto-remediate findings with confidence >= N (default 40)
  --no-wazuh          Never forward findings to a local Wazuh agent
  --config FILE       YAML allowlist of findings to suppress (see below)
  --baseline FILE     YAML baseline of environment-specific known-good fingerprints to suppress (see below)
  --since TIME        Limit the timeline to events since TIME (e.g. '24h', '7d', '2026-05-20')
  --rules FILE        YAML file of custom detection rules to add (see below)
  --verbose           Verbose structlog output

ubuntils collect [OPTIONS]
  --output FILE       Bundle path to write; must not exist yet
                      (default /var/lib/ubuntils/bundles/ubuntils-bundle-<timestamp>-<random>.tar.gz)
  --verbose           Verbose structlog output

ubuntils analyze (BUNDLE | --root PATH) [OPTIONS]
  --root PATH         Analyze a mounted image / artifact tree instead of a bundle
  --json              Output JSON instead of launching the TUI
  --output FILE       Write the JSON report to FILE (implies --json)
  --config FILE       YAML allowlist of findings to suppress (same format as scan)
  --baseline FILE     YAML baseline of environment-specific known-good fingerprints to suppress (same format as scan)
  --rules FILE        YAML file of custom detection rules to add (same format as scan)
  --since TIME        Limit the timeline to events since TIME (e.g. '24h', '7d', '2026-05-20')
  --verbose           Verbose structlog output

ubuntils rollback BACKUP_PATH [--force]
  Restore a remediated file from its backup (see Remediation > Rollback)

ubuntils version
  Print version string and exit
```

### False-positive allowlisting (`--config`)

A freshly provisioned or CI-managed host generates expected noise — deploy keys, provisioning crontabs, baked-in shell init. Instead of teaching responders to mentally filter it, suppress it explicitly with a YAML allowlist:

```yaml
# allowlist.yaml
allowlist:
  rules:
    - SHELL_RC_MODIFICATION          # suppress this rule entirely
  paths:
    - /home/ci/.ssh/authorized_keys  # suppress any finding on this exact path
```

```bash
ubuntils scan --json --config allowlist.yaml
```

Suppression is always explicit — by rule id and/or exact artifact path. There is no blanket "ignore everything" switch. A sample lives at [`examples/allowlist.yaml`](examples/allowlist.yaml).

### Known-good baselining (`--baseline`)

`--config` suppresses a rule or path *everywhere, for anyone running ubuntils against this codebase*. `--baseline` is narrower and environment-specific: it says "in *this* environment, this exact artifact — this SSH key, this RC file — is known good," without muting the rule or path for every other host you scan with the same tool. Kept as a separate file from `--config` for the same reason `--rules` is separate: suppression and rule-wide allowlisting are different concerns that shouldn't live in one file.

```yaml
# baseline.yaml
baseline:
  - rule_id: SSH_UNAUTHORIZED_KEY
    fingerprint: SHA256:Qx4N…            # the key's fingerprint (as sshd logs it) or its base64 data
  - rule_id: SHELL_RC_MODIFICATION
    fingerprint: /home/deploy/.bashrc  # exact match against the finding's artifact_path
```

```bash
ubuntils scan --json --baseline baseline.yaml
```

A baseline entry matches by `rule_id` plus a `fingerprint`:
- **SSH keys** (`SSH_UNAUTHORIZED_KEY`) match the key itself: its `SHA256:` fingerprint, or a whole word of `<key type> <key data>`. They never match the key's comment or options, which whoever adds the key chooses. A baseline on `ci@ci-runner` would otherwise hide a planted key labelled `ci@ci-runner`.
- **An exact `artifact_path`** suppresses the routine findings for that file, but never a finding with a content signal (`content_match`, such as a download-and-execute line added to a baselined `.bashrc`).
- **Anything else** is a whole-word match within the finding's `raw_value`.

A match drops the finding from the report entirely. Suppression is never silent, though: the number of findings a baseline removed is always visible in `scan_metadata.suppressed_by_baseline`. Allowlist (`--config`) suppression still applies on top of baseline suppression. Works identically on `scan` and `analyze`. Baselines in this format print a deprecation warning: ubuntils 3.0 replaces them with hash-keyed entries generated by `ubuntils baseline create`. A sample lives at [`examples/baseline.yaml`](examples/baseline.yaml).

### Custom detection rules (`--rules`)

`--config` *suppresses* findings; `--rules` *adds* them. They are deliberately separate files because they are opposite concerns.

A rules file is pattern-match only — no expressions, no conditionals, and no code execution, so loading one can never run attacker-supplied logic. Each rule names an artifact `source`, a `match` mode, and a `pattern`:

```yaml
# custom_rules.yaml
rules:
  - id: CUSTOM_KNOWN_MINER
    severity: HIGH                     # HIGH | MEDIUM | LOW
    title: Known cryptominer in process cmdline
    description: A running process command line matches a known miner.
    source: process                    # cron | environment | ssh | process | network
    match: substring                   # regex | substring | glob
    pattern: xmrig
```

```bash
ubuntils scan --json --rules custom_rules.yaml
```

| `source` | Matched against |
|---|---|
| `cron` | The cron command (path: the crontab file) |
| `environment` | The raw environment/shell-init line (path: the defining file) |
| `ssh` | Key type, key data, and comment (path: the `authorized_keys` file) |
| `process` | The process cmdline (path: the exe path) |
| `network` | The connection description (path: `remote_addr:remote_port`) |

`regex` and `substring` match the text column; `glob` matches the path column — so a `network` glob such as `203.0.113.*:*` targets the remote endpoint. A `substring` rule searches the whole text. A `regex` rule searches only the first 4,096 characters, and patterns with nested quantifiers such as `(a+)+` are rejected at load time. Both guard against catastrophic backtracking on attacker-controlled text, since Python's `re` has no timeout. So prefer `substring` for anything an attacker could push past 4,096 characters with padding. Custom-rule findings are flag-only (never auto-remediated) and are still subject to `--config` suppression. A sample lives at [`examples/custom_rules.yaml`](examples/custom_rules.yaml).

### Report integrity

Every `--json` report carries a `report_sha256` field — a SHA-256 over the canonical report content. It lets you reference a specific scan by digest in a case file and detects accidental corruption or a casual edit. It is an unkeyed hash, not a signature: someone who edits the report can recompute it, so for chain of custody record the digest somewhere the report's holder can't change (your case notes, a ticket) at the time of the scan. The report also records `tool_version`, `hostname`, and a UTC `generated_at` timestamp under `scan_metadata`. For `scan`, `hostname`/`ubuntu_version` describe the machine `ubuntils` is running on; for `analyze --root` they are read from the image's own `/etc/hostname` and `/etc/os-release`. For `analyze BUNDLE`, they instead come from the bundle's own manifest — the host that was *collected*, not the host running `analyze` — along with `collection_run_id` and the collection's `collected_at_utc_start`/`collected_at_utc_end`, so the report's chain-of-custody record follows the evidence rather than the analyst's workstation.

**Verifying a report.** The report is emitted in canonical form (keys sorted, 2-space indent), and the digest covers everything except `report_sha256` itself:

```python
import hashlib, json
doc = json.load(open("report.json"))
claimed = doc.pop("report_sha256")
assert hashlib.sha256(json.dumps(doc, indent=2, sort_keys=True).encode()).hexdigest() == claimed
```

---

## Offline analysis: collect and analyze

`ubuntils scan` runs collection, detection, and timeline together against the live host. `collect` and `analyze` split that pipeline in two: `collect` acquires a tamper-evident bundle from a host (no detection runs), and `analyze` runs the same detection/timeline pipeline used by `scan` against a bundle, or against a mounted image via `--root`, without requiring root and without touching the original host again. This is for cases where you want to acquire artifacts once and analyze them later, elsewhere, or repeatedly — or where you're triaging a disk image rather than a running system.

### `ubuntils collect`

```bash
ubuntils collect --output /path/to/bundle.tar.gz
```

Requires root, like `scan`. Reads a fixed list of files (`/etc/passwd`, `/etc/group`, `/etc/shadow`, `/etc/sudoers`, `/etc/ld.so.preload`, `/etc/environment`, `/etc/crontab`, `/etc/profile`, `/etc/nsswitch.conf`, OS release, hostname and timezone, dpkg's status file and `path-exclude` config, `/var/log/syslog`, `/var/log/messages`, `/var/log/audit/audit.log`) and runs a fixed list of commands (`ss -tunap`, `netstat -tunap`, `systemctl list-timers` in both JSON and text form, and `journalctl -o json` for the last 7 days), hashes each captured item, and writes everything plus a `manifest.json` into a `.tar.gz` bundle. The captured log files and journalctl output are what let `analyze BUNDLE` build a real timeline offline. If `--output` is omitted, the bundle is written to `/var/lib/ubuntils/bundles/ubuntils-bundle-<UTC timestamp>-<random>.tar.gz`. That directory is created `0700` root-only, and `collect` refuses to use it if it is a symlink or owned by anyone else. The working directory isn't used, since it may belong to the attacker. `collect` never writes into an existing file, so an `--output` path that already exists is an error.

### `ubuntils analyze`

```bash
ubuntils analyze BUNDLE.tar.gz [--json] [--output FILE] [--config FILE] [--baseline FILE] [--rules FILE] [--since TIME]
ubuntils analyze --root /mnt/forensic-image [--json] [--output FILE] [--config FILE] [--baseline FILE] [--rules FILE] [--since TIME]
```

Takes either a bundle path as a positional argument or `--root PATH` pointing at a mounted image / extracted filesystem tree — not both. Runs the identical detection engine, custom rules, allowlist, and baseline logic used by `scan`. Does not require root. The bundle is extracted to a private temp directory that is deleted as soon as analysis finishes (it can contain `/etc/shadow`).

Coverage differs between the two offline modes, because a bundle carries *replayed* captured state from `collect` time while `--root` only has whatever is sitting on the mounted filesystem:

- **`analyze BUNDLE`** replays the real `ss`/`systemctl list-timers`/`journalctl` command output captured at `collect` time, so `NetworkCollector` and `SystemdCollector` produce genuine findings from that snapshot — they are not skipped. The timeline is built from the syslog/messages/audit.log/journalctl the bundle captured, so it is fully populated and findings get real `related_events` correlation.
- **`analyze --root PATH`** points at a dead, mounted image with no live process or kernel state to query, so command execution is disabled entirely: `NetworkCollector` and `SystemdCollector` are skipped, recorded in `scan_metadata.command_collectors_skipped`. The timeline is still built, but from the static log files present on the image (`/var/log/syslog`, `/var/log/messages`, `/var/log/audit/audit.log`) — journald replay isn't available here since there's no live `journalctl` to query a dead image.

See [Offline analysis: collect and analyze](#offline-analysis-collect-and-analyze) for the full list of offline detection-coverage gaps.

### Bundle format

A bundle is a gzipped tarball with everything under a `bundle/` prefix:

```
bundle/
├── manifest.json
├── files/
│   ├── etc/passwd
│   ├── etc/shadow
│   ├── var/log/syslog
│   └── ...            # every captured file, path-flattened under files/
└── commands/
    ├── ss.txt
    ├── netstat.txt
    ├── systemctl_list_timers_json.txt
    ├── systemctl_list_timers_text.txt
    └── journalctl.txt
```

`manifest.json` schema:

| Field | Type | Description |
|---|---|---|
| `run_id` | string | UUID generated fresh for each `collect` run |
| `host_id` | string | Reserved for future multi-host correlation; currently empty |
| `hostname` | string | `socket.gethostname()` at collection time |
| `ubuntu_version` | string | Detected Ubuntu release string |
| `collected_at_utc_start` / `collected_at_utc_end` | string (ISO 8601) | Wall-clock bounds of the collection run |
| `tool_version` | string | ubuntils version that produced the bundle |
| `files[]` | array | One entry per captured file: `source_path`, `bundle_path`, `sha256`, `size`, `mtime`, `ctime` (a file absent/unreadable on the source host is recorded with `sha256: ""`, `size: -1` rather than aborting the collection) |
| `commands[]` | array | One entry per captured command: `name`, `argv`, `bundle_path`, `sha256`, `exit_code` |
| `bundle_sha256` | string | SHA-256 over the rest of the manifest (everything above, canonically serialized) — the tamper-evidence anchor for the whole bundle |

### Bundle integrity in JSON output

`analyze`'s `scan_metadata.bundle_integrity` reports one of three values:

- `"live"` — `scan` and `analyze --root` report this; there is no bundle to verify.
- `"ok"` — `analyze BUNDLE` verified `bundle_sha256` against the manifest, every captured file's SHA-256 against its bundle content, and that every file in `files/` and `commands/` is one the manifest lists as captured. That rules out corruption and naive edits. The digests are unkeyed, though: someone who rewrites a file *and* the manifest can make a forged bundle verify, so record `sha256sum bundle.tar.gz` out-of-band when you collect it.
- `analyze` also refuses a bundle whose manifest names a path outside the bundle, or that has more than 10,000 members, a member over 512 MiB or more than 2 GiB in total (checked from the headers before anything is extracted), and never follows a path from the bundle's own files (its `/etc/passwd` home directories, its sudoers includes) out of the extraction directory — analysing a hostile host's bundle can't read the analyst's files.
- `"mismatch"` — the manifest digest, a captured file's hash, or a captured command output's hash didn't match, or the bundle holds a file the manifest doesn't vouch for: one it doesn't list at all (an injected `files/etc/cron.d/x`), or one it recorded as absent on the host (an injected `files/etc/ld.so.preload`). Something in the bundle was modified, truncated, or corrupted after collection, and nothing derived from it should be trusted as chain-of-custody-clean. `analyze` still produces its report, but prints a red warning to stderr, shows an integrity banner at the top of the TUI Summary tab, and **exits with status 3**, so scripts can't mistake a tampered bundle's results for authoritative ones.

### ⚠️ Offline analysis has real detection gaps — read this before relying on it

**A bundle- or `--root`-sourced `analyze` run does not have detection parity with a live `scan`.** These are not edge cases; they are structural limitations of static, offline acquisition, and they produce fewer (or zero) findings for the affected rules rather than an error. Where a collector *knows* it couldn't look (a failed command, an unreadable file), that is recorded in `scan_metadata.collectors_degraded` and flagged in the TUI Summary tab — but a file that simply wasn't captured looks the same as a file that doesn't exist. (The timeline itself is *not* one of these gaps any more: `analyze BUNDLE` replays the captured syslog/messages/audit.log/journalctl from `collect` time, and `analyze --root` reads the static log files present on the mounted image, so both produce a real timeline and real `related_events` correlation — see [`ubuntils analyze`](#ubuntils-analyze) above.)

- **`PROCESS_MASQUERADE` and `PROCESS_SUSPICIOUS_CONNECTION` will always report zero findings in offline mode.** Both rules key off a process's `exe` field, which is populated by reading the `/proc/<pid>/exe` symlink target through the artifact source (never the analyst's own `/proc`). A bundle has no live `/proc` to read, and `--root` points at a mounted filesystem tree with no `/proc` either — there is currently no mechanism to capture or reconstruct a resolved exe-symlink target offline, so `exe` is always empty and both rules never fire, regardless of what's actually on the host.
- **Process enumeration doesn't happen at all offline.** `collect` has no per-PID capture step (`/proc/*/status`, `/proc/*/cmdline`), so no processes exist in a bundle to analyze in the first place — this is the same root cause as the point above, from the acquisition side.
- **`CRON_TMP_PATH`, `SUDOERS_NOPASSWD`, and `SSH_UNAUTHORIZED_KEY` are limited or absent from bundle-sourced analysis.** `collect`'s file list is static and cannot glob-expand `/etc/cron.d/*`, `/etc/sudoers.d/*`, `/etc/profile.d/*`, or per-user `~/.ssh/authorized_keys` — only `/etc/crontab`, `/etc/sudoers`, and `/etc/environment`/`/etc/profile` are captured. (`--root` against a full mounted filesystem tree does not have this gap, since the real directories are present on disk.) When `SSH_UNAUTHORIZED_KEY` or `SHELL_RC_MODIFICATION` *do* fire (live scan, or `--root` with the real per-user directories present), they now also score confidence from ctime and file content, not mtime alone — see [Confidence scoring](#json-output) below. That improves how much you should trust a finding that does fire; it doesn't change whether the rule fires offline in the first place.
- **`SUSPICIOUS_SYSTEMD_TIMER` detection is weakened for bundles.** Service units are read straight from the unit directories (`/etc/systemd/system`, `/usr/lib/systemd/system`, per-user `~/.config/systemd/user`, …), so `--root` gets full service coverage. A bundle doesn't capture those directories, though: timers show up from the captured `systemctl list-timers` output, but each timer's `ExecStart` comes from a per-unit `systemctl show` call that `collect` doesn't make, so the rule can't evaluate what a bundled timer runs.

**When it matters:** if you're triaging a live, reachable host, use `ubuntils scan` — it has full detection coverage. Use `collect`/`analyze` when you need to acquire once and analyze elsewhere, need to analyze without root, or are working from a disk image where `scan` isn't an option at all — and treat a clean `analyze` result for the rules above as "not checked," not "checked and clean."

---

## The TUI

Running `ubuntils scan` (without `--json`) launches a full-terminal interactive TUI.

### Scan screen

While collectors run, ubuntils shows a live checklist — one row per collector. Each row updates in real time as the collector finishes:

```
Scanning system…

  ✓  ProcessCollector
  ✓  NetworkCollector
  ✓  UserCollector
  ⠹  CronCollector
     SystemdCollector
     SSHCollector
     SudoersCollector
     EnvironmentCollector
     PackageCollector
     PamCollector
     KernelCollector
```

`✓` marks success, `✗` marks failure, the spinner marks the active collector, and blank rows are pending. Once all collectors finish and detection + timeline complete, the TUI switches automatically to the results screen.

### Results screen

The results screen has four tabs navigated by number keys:

| Key | Tab | Contents |
|-----|-----|----------|
| `1` | Summary | Scan stats + top findings at a glance |
| `2` | Findings | Full findings list with inline detail and remediation |
| `3` | Timeline | Chronological correlated log events |
| `4` | Stats | Ubuntu version, architecture, duration, collector counts |

Press `q` or `Ctrl+C` to exit.

### Summary tab (key `1`)

Shows scan metadata and the top findings on a single screen:

```
Collectors:  11 run · 0 failed
Findings:    2 HIGH · 1 MEDIUM · 0 LOW
Timeline:    47 events
Duration:    2.8s

  ● HIGH  CRON_TMP_PATH           /etc/cron.d/cleanup
  ● HIGH  LD_PRELOAD_INJECT       /home/alice/.bashrc
  ○ MED   SSH_UNAUTHORIZED_KEY    /home/bob/.ssh/authorized_keys
```

On a clean system, this tab shows `System appears clean.`

### Findings tab (key `2`)

A scrollable list of all findings, sorted HIGH → MEDIUM → LOW. Selecting a finding (Enter or arrow keys) expands a detail pane at the bottom showing the full description, artifact path, raw triggering value, and remediation information.

```
HIGH  CRON_TMP_PATH           /etc/cron.d/cleanup
HIGH  LD_PRELOAD_INJECT       /home/alice/.bashrc
MED   SSH_UNAUTHORIZED_KEY    /home/bob/.ssh/authorized_keys
───────────────────────────────────────────────────────
A cron job was found referencing /tmp, /var/tmp, or /dev/shm.
These directories are world-writable and commonly used as
attacker staging grounds.

Artifact:  /etc/cron.d/cleanup
Raw:       0 * * * * root /tmp/.update
Fix:       Will remove the offending cron entry from
           /etc/cron.d/cleanup after creating a timestamped backup.

R: remediate
```

### In-TUI remediation

For findings that have automated remediation available, press `R` while the finding is selected. A confirmation modal appears:

```
┌─────────────────────────────────────────────────┐
│ Remediate CRON_TMP_PATH?                        │
│                                                 │
│ Will remove the offending cron entry from       │
│ /etc/cron.d/cleanup after creating a backup.   │
│ Backup will be created at /var/backups/ubuntils/…│
│                                                 │
│ Y: confirm    Esc: cancel                       │
└─────────────────────────────────────────────────┘
```

Press `Y` to confirm. The remediator runs in a background thread. When it completes, the finding row in the list is updated to `[fixed]` and the detail pane shows the outcome:

```
✓ Remediated
Backup:    /var/backups/ubuntils/20260115_142201/etc_cron.d_cleanup
Rollback:  ubuntils rollback /var/backups/ubuntils/20260115_142201/etc_cron.d_cleanup
```

On failure, the row is marked `[remediation failed]` and the detail pane shows the error. The backup is always created before any change is attempted. A finding that was fixed can't be remediated a second time.

A long detail (a package with many changed files, several signals and related events) scrolls: press `PgUp`/`PgDn`. Press `Esc` to collapse the detail pane.

### Timeline tab (key `3`)

A scrollable chronological table of correlated log events. Each row shows the timestamp (UTC), source, the logging program, and the message. Only the rows on screen are rendered, so a week of journald on a busy host (tens of thousands of events) opens in seconds. Events are pulled from syslog, journald, and auditd and deduplicated — including the copy rsyslog makes of every journald message, which otherwise doubles a large share of the timeline. Identical messages repeated within a single source (a burst of failed logins) are kept.

### Stats tab (key `4`)

A summary view of the scan: detected Ubuntu version, architecture, scan duration, collector count and failures, and finding counts per severity alongside total timeline events.

---

## What it detects

| Rule ID | Severity | Remediable | What it checks |
|---|---|---|---|
| CRON_ROOT_EXEC | HIGH | Yes | Non-root user crontabs running commands in root-owned paths or inlining sudo |
| CRON_TMP_PATH | HIGH | Yes* | Any cron job (including `@reboot`/`@daily` entries and scripts in `/etc/cron.{hourly,daily,weekly,monthly}`) referencing /tmp, /var/tmp, or /dev/shm. *Script lines are flag-only |
| LD_PRELOAD_INJECT | HIGH | Yes | Any entry in /etc/ld.so.preload (empty on stock Ubuntu), or LD_PRELOAD in any shell init file with any listed library outside /lib, /usr/lib, /lib64, /usr/lib64 |
| SUSPICIOUS_SYSTEMD_TIMER | HIGH | No | Systemd timers, service units and drop-in overrides whose `Exec*=` references a world-writable directory, runs a binary not owned by root, pipes a download into a shell, or decodes base64 |
| SSH_UNAUTHORIZED_KEY | MEDIUM | Yes | Keys in any file sshd reads (`authorized_keys`, `authorized_keys2`, every `AuthorizedKeysFile`) changed within 7 days by mtime *or* ctime, and any key in the legacy `authorized_keys2` |
| USER_UID_ZERO | HIGH | No | Any account other than `root` with UID 0 (a hidden second superuser) |
| USER_EMPTY_PASSWORD | HIGH | No | A login-shell account whose /etc/shadow password field is empty (Ubuntu's default PAM `nullok` lets it log in with no password) |
| SUDOERS_NOPASSWD | MEDIUM | Yes* | NOPASSWD (or `Defaults:user !authenticate`) sudoers grants for users with UID ≥ 1000 and a login shell, directly, via a `%group`, a user list, a `User_Alias` or `ALL`; included files are followed. *Flag-only unless the line grants exactly one user (removing `%sudo` could remove all sudo access) |
| PROCESS_MASQUERADE | HIGH / MEDIUM | No | HIGH: a userspace process named like a kernel thread (`[kworker/0:1]`). MEDIUM: processes whose name matches a known system binary but whose executable is outside the standard system directories (/usr/bin, /usr/sbin, /bin, /sbin, /usr/local/{bin,sbin}, /usr/lib, /usr/libexec, /lib, /snap) |
| PROCESS_SUSPICIOUS_CONNECTION | HIGH / MEDIUM | No | Processes holding a non-loopback connection whose executable is in a world-writable temp dir or deleted from disk (HIGH), or is outside the standard system directories, or that make an outbound connection to a non-standard remote port (MEDIUM). Inbound connections (on a listening port) skip the port check |
| SHELL_RC_MODIFICATION | LOW / MEDIUM | No | System and per-user shell init files (`/etc/bash.bashrc`, `/etc/profile.d/*`, `~/.bashrc`, `~/.zshenv`, …) changed within 48 hours by mtime or ctime (LOW), or containing a download-and-execute, base64-decode or writable-tmp `PATH` line at any age (MEDIUM) |
| PACKAGE_TAMPERED | HIGH / MEDIUM / LOW | No | Package-owned files modified, missing, or whose content/mode/size mismatches the package manifest (via `dpkg --verify`), one finding per package; MEDIUM when every changed file is under `/var`, LOW when only directories are missing |
| IMMUTABLE_FLAG_SET | MEDIUM | No | Immutable (`i`) or append-only (`a`) flags set on sensitive files like /etc/passwd, /etc/sudoers, or /etc/pam.d/* (detected via `lsattr`) |
| PAM_BACKDOOR | HIGH | No | A `pam_permit.so` line in an /etc/pam.d/* auth/account stack that can grant access on its own (`sufficient`/`success=done`, or no `pam_deny`-style gate in that stack), or an NSS module in /etc/nsswitch.conf outside an allowlist (files/sss/ldap/winbind/...) |
| KERNEL_MODULE_SUSPICIOUS | MEDIUM / LOW | No | Loaded kernel modules the kernel marks as out-of-tree, unsigned, proprietary or force-loaded (MEDIUM), unless allowlisted; modules shipped with the running kernel are not reported. Without taint data (offline, older bundles) any module outside an allowlist of common built-ins is reported LOW |
| SETUID_INVENTORY | LOW | No | Unexpected setuid or setgid binaries outside a known baseline set (the two bits are checked and reported separately) |
| USER_FILE_OVERSIZED | MEDIUM | No | An `authorized_keys` file, per-user shell init file or per-user systemd unit larger than 1 MiB (real ones are a few KB) |

### Why each rule exists

**CRON_ROOT_EXEC** — User crontabs run as the crontab owner. An entry invoking sudo or a root-owned interpreter means the user has arranged for code to run with root privileges on a schedule, without needing persistent sudo access. This survives password changes.

*Example finding:*
```
[HIGH] CRON_ROOT_EXEC
Title:         User crontab executing with sudo
Artifact:      /var/spool/cron/crontabs/alice
Raw value:     */5 * * * * sudo /usr/bin/python3 /tmp/beacon.py
Remediation:   available
```

**CRON_TMP_PATH** — World-writable directories like /tmp and /dev/shm are standard attacker staging grounds. A cron job pointing there means a payload can be swapped out between invocations without touching any persistent path. This covers `@reboot`/`@daily`-style entries and the scripts in `/etc/cron.{hourly,daily,weekly,monthly}`; findings on those scripts are flag-only, since deleting one line from a shell script isn't a safe automatic fix.

*Example finding:*
```
[HIGH] CRON_TMP_PATH
Title:         Cron job references writable temp directory
Artifact:      /etc/cron.d/cleanup
Raw value:     0 * * * * root /tmp/.update
Remediation:   available
```

**LD_PRELOAD_INJECT** — LD_PRELOAD causes the dynamic linker to load a specified shared library before all others, allowing arbitrary function interception in any dynamically linked binary. A value pointing outside standard library paths is a near-certain userspace rootkit indicator; every library in a space- or colon-separated list is checked. `/etc/ld.so.preload` injects into *every* process and is empty on stock Ubuntu, so any entry there is reported — even one planted inside `/lib`, a common rootkit trick. Remediation removes `/etc/ld.so.preload` entries rather than commenting them out, because the loader has no comment syntax in that file.

*Example finding:*
```
[HIGH] LD_PRELOAD_INJECT
Title:         LD_PRELOAD set to non-standard library path
Artifact:      /home/alice/.bashrc
Raw value:     export LD_PRELOAD=/tmp/.libssl.so
Remediation:   available
```

**SUSPICIOUS_SYSTEMD_TIMER** — Systemd timers are more persistent and less visible than cron jobs to most responders. A timer — or a plain `.service` unit, which is the more common persistence and needs no timer at all — whose ExecStart references a temp directory, runs a binary not owned by root, pipes `curl`/`wget` into a shell, or decodes base64 is a sign of attacker-created persistence. Service units are read directly from the unit directories, including per-user `~/.config/systemd/user`, and so are **drop-in overrides** (`<unit>.service.d/*.conf`): an override can swap a legitimate service's command for a backdoor while the unit file itself stays pristine. Flag-only — systemd unit removal requires human judgment.

*Example finding:*
```
[HIGH] SUSPICIOUS_SYSTEMD_TIMER
Title:         Systemd timer ExecStart points to suspicious path
Artifact:      /etc/systemd/system/update-check.timer
Raw value:     ExecStart=/tmp/.sys/update
Remediation:   not available
```

**SSH_UNAUTHORIZED_KEY** — A newly added SSH key grants persistent remote access independent of passwords. Keys are read from every file sshd would consult: `~/.ssh/authorized_keys`, the legacy `~/.ssh/authorized_keys2` (still honoured by default, and a classic hiding place — any key there is reported whatever its age), and every `AuthorizedKeysFile` in `sshd_config` and `sshd_config.d`, with `%h`/`%u` expanded. The 7-day window checks both mtime and ctime: `touch -d` can backdate mtime but not ctime, so a key whose mtime was pushed back is still reported. A recent ctime behind an old mtime adds only a weak `mtime_predates_ctime` signal (+10), since `useradd -m`, `cp -p`, `tar` and `rsync -a` produce the same pattern legitimately. File timestamps can't say *which* key in a file was added, so when a file holds several keys and none has a dangerous option, each is marked `auto_remediation_blocked` (and scored down by `ambiguous_key`, −40): `--remediate --confirm` skips it whatever its confidence, so it can't strip the admin's keys along with the attacker's. You can still remove such a key yourself with `R` in the TUI, which shows the reason as a warning first. Timeline corroboration for a key needs a login line naming that key's fingerprint (`SHA256:…`, as sshd logs it); a line naming only the user, such as `Accepted publickey for alice`, is shown as a related event but doesn't raise the score, since any user can write one with `logger -t sshd`. Remediation removes the exact line, options included.

*Example finding:*
```
[MEDIUM] SSH_UNAUTHORIZED_KEY
Title:         SSH authorized key added in last 7 days
Artifact:      /home/bob/.ssh/authorized_keys
Raw value:     ssh-rsa AAAAB3NzaC1... attacker@evil
Remediation:   available
```

**SUDOERS_NOPASSWD** — Password-free sudo for a human user account (UID ≥ 1000 with a login shell) is a privilege escalation vector that survives the removal of other persistence mechanisms. Legitimate NOPASSWD grants are almost always for service accounts with no login shell. Group rules (`%sudo ALL=(ALL) NOPASSWD:ALL`) are resolved to their members, and `#include`/`@includedir` files are followed. The parser follows sudo's own syntax rather than the common shape of a rule, so the usual ways of hiding a grant are caught too: a rule split over lines with a trailing `\`, a user list (`alice, bob ALL=…`) or `User_Alias`, `NOPASSWD:` placed before a later command in the list (`/usr/bin/id, NOPASSWD: /bin/bash`), and `Defaults:alice !authenticate`, which makes every rule for alice passwordless without the word NOPASSWD appearing anywhere. Only a single-line rule for exactly one user is auto-remediated; group, `ALL`, multi-user, multi-line and `!authenticate` findings are flag-only — deleting the line could remove other users' sudo access, every sudo grant on the system, or (for `!authenticate`) the user's sudo access outright instead of just the password exemption.

*Example finding:*
```
[MEDIUM] SUDOERS_NOPASSWD
Title:         NOPASSWD sudo grant for regular user
Artifact:      /etc/sudoers.d/alice
Raw value:     alice ALL=(ALL) NOPASSWD: ALL
Remediation:   available
```

**PROCESS_MASQUERADE** — Naming a malicious binary after a known system process (sshd, python3, bash) is a basic technique to avoid detection in `ps` output. This rule cross-references the process name from `/proc/<pid>/status` against the resolved exe path from `/proc/<pid>/exe`. Standard locations include `/usr/local/{bin,sbin}`, `/usr/lib`, `/usr/libexec`, and `/snap`, so systemd (`/usr/lib/systemd/systemd`) and snap packages don't trip it. It also catches the most common Linux masquerade: an implant that names itself after a kernel thread (`kworker/0:1`, or a bracketed `[kworker/0:1]` command line). Real kernel threads have no executable, so a kernel-thread name backed by a file on disk is reported HIGH. Only kernel spellings count: `watchdogd` and `watchdog/0` are kernel threads, the userspace `watchdog` daemon is not. Flag-only — killing a process requires human judgment.

*Example finding:*
```
[MEDIUM] PROCESS_MASQUERADE
Title:         Process masquerading as system binary
Artifact:      /proc/1337/exe
Raw value:     name=sshd, exe=/tmp/.sshd
Remediation:   not available
```

**USER_UID_ZERO** — Only `root` should hold UID 0. A second account mapped to UID 0 (CIS Ubuntu Benchmark 6.2.x) is a high-confidence backdoor: it grants full superuser rights without altering root's own credentials, and survives a root password reset. Near-zero false-positive rate. Flag-only — removing a UID-0 account requires human judgment.

*Example finding:*
```
[HIGH] USER_UID_ZERO
Title:         Non-root account with UID 0
Artifact:      /etc/passwd
Raw value:     toor:x:0:0:...:/bin/bash
Remediation:   not available
```

**USER_EMPTY_PASSWORD** — An account whose `/etc/shadow` password field is empty has no password at all, and Ubuntu's default PAM stack (`pam_unix ... nullok`) lets it log in without one. On an account with a login shell that is an open door. Flag-only — lock it with `passwd -l` while you investigate.

*Example finding:*
```
[HIGH] USER_EMPTY_PASSWORD
Title:         Login account with no password
Artifact:      /etc/shadow
Raw value:     eve::
Remediation:   not available
```

**USER_FILE_OVERSIZED** — sshd honours a key on any line of `authorized_keys`, and bash runs every line of `~/.bashrc`, however big the file is. Megabytes of padding in front of one malicious line is a cheap way to slip past tools, and people, that skip or truncate large files. ubuntils reads these files anyway, up to a 64 MiB ceiling, so the key or backdoor past the padding is still reported by its own rule. This rule reports the padding itself. Flag-only: look past the padding (`grep -nv '^\s*\(#\|$\)' FILE`) and restore the file from a known-good copy. The example Wazuh rules raise it to level 10 (rule 100105).

**PROCESS_SUSPICIOUS_CONNECTION** — Persistence is only half the picture; a foothold that never talks to anything is rarely the one you care about. This rule joins the process and network collectors by PID so a flagged process arrives with its current connections attached. An executable staged in `/tmp` holding an established outbound socket is HIGH; a legitimate binary reaching a non-standard remote port is MEDIUM and worth a look. Connections accepted on a local listening port are treated as inbound: their "remote port" is the client's ephemeral port, so they only count toward the executable-location check (a bind shell in `/tmp` is still HIGH, your own SSH session is not flagged). Loopback traffic, including IPv4-mapped `::ffff:127.0.0.1`, is ignored. This is a snapshot of current state, not continuous monitoring — a beacon that is sleeping when you scan will not appear. Flag-only.

*Example finding:*
```
[HIGH] PROCESS_SUSPICIOUS_CONNECTION
Title:         Process with suspicious network connection
Artifact:      /proc/1337/exe
Raw value:     203.0.113.9:4444
Remediation:   not available
```

**SHELL_RC_MODIFICATION** — Shell init files are a reliable persistence vector because they execute on every login or interactive shell. The rule reads the system-wide files (`/etc/profile`, `/etc/profile.d/*.sh`, `/etc/bash.bashrc`, `/etc/zsh/*`) and each login user's `.bashrc`, `.bash_profile`, `.bash_login`, `.profile`, `.zshenv`, `.zprofile`, `.zshrc` and `.zlogin`. Recent changes (mtime or ctime within 48 hours) are LOW; a download-and-execute, base64-decode or writable-tmp `PATH` line is MEDIUM however old the file is. Flag-only — shell RC content requires reading before acting on it.

*Example finding:*
```
[LOW] SHELL_RC_MODIFICATION
Title:         Shell init file recently modified
Artifact:      /root/.bashrc
Raw value:     mtime=2024-01-15 14:22:01 (6 hours ago)
Remediation:   not available
```

**PACKAGE_TAMPERED** — System-owned binaries and configuration files are the foundation of trust. This rule detects when package-owned files have been modified, deleted, or have content/mode/size mismatches using `dpkg --verify`. Conffile-only edits (expected local configuration changes) are excluded from reporting to avoid noise. Changed files are grouped into **one finding per owning package** (looked up with `dpkg-query -S`), listing up to 20 of the files; the artifact is the package name, so a known-noisy package can be allowlisted by name with `--config`. A package whose changed files are all under `/var` is reported as MEDIUM with lower confidence, because packages such as a Wazuh manager keep runtime data there that `dpkg` still lists in their manifest — a single Wazuh host otherwise produced 1,100+ HIGH findings. A missing path that isn't in the package's `/var/lib/dpkg/info/<pkg>.md5sums` (which lists only regular files) is a directory or symlink: it gets a weak `missing_directory` signal instead of `missing_file`, and a package whose only problem is missing directories is reported as LOW — an empty directory going away is housekeeping, not tampering. Missing conffiles are still treated as files. Files that dpkg was configured never to install are skipped too: Docker's official Ubuntu images and Ubuntu's minimized cloud images ship `path-exclude` filters in `/etc/dpkg/dpkg.cfg.d/` (no docs, man pages or translations), and `dpkg --verify` still reports every one of those files as missing — 375 HIGH findings on a stock `ubuntu:24.04` container. ubuntils applies the filters the way dpkg does (`dpkg.cfg.d/*` then `dpkg.cfg`, last matching `path-exclude`/`path-include` wins) to *missing* files only; a filtered path whose content changed is still reported. Packages that were removed but not purged (dpkg state `config-files`, read from `/var/lib/dpkg/status`) are skipped entirely: dpkg keeps checking the empty directory skeleton they leave behind, and its disappearance is cleanup, not tampering. Bundles don't capture `.md5sums`, so offline every missing path counts as a file. If ownership can't be determined (an older bundle, or the lookup failed) the rule falls back to one finding per file and the scan notes the degraded lookup. Flag-only — tampering may be legitimate (custom local edits) or malicious (file replacement); deciding requires human judgment.

*Example finding:*
```
[HIGH] PACKAGE_TAMPERED
Title:         Package files modified or missing since installation
Artifact:      openssh-server
Raw value:     missing     /usr/sbin/sshd
               ??5??????   /usr/lib/openssh/sshd-session
Remediation:   not available
```

**IMMUTABLE_FLAG_SET** — Attackers often set the immutable flag (`i`) or append-only flag (`a`) on files to prevent modification or deletion, even by root, including to hide tampering from further edits/log rotation. Setting these flags on sensitive system files like /etc/passwd, /etc/sudoers, /etc/pam.d/*, or the auth/syslog/wtmp/btmp log files is a strong indicator of attacker hardening. This rule detects immutable and append-only flags via `lsattr` against that fixed list of sensitive paths. Flag-only — flag changes require human review.

*Example finding:*
```
[MEDIUM] IMMUTABLE_FLAG_SET
Title:         Sensitive file has an unexpected chattr flag
Artifact:      /etc/ld.so.preload
Raw value:     ----i--------e---
Remediation:   not available
```

**PAM_BACKDOOR** — PAM (Pluggable Authentication Modules) and NSS (Name Service Switch) are the core authentication and identity systems on Linux. This rule does NOT do mtime-based "was this file modified" detection — it pattern-matches file *content*: (1) a `pam_permit.so` line that can decide an auth or account stack on its own — either it short-circuits the stack (`sufficient`, `[success=done …]`), or nothing else in that stack can fail it (the stock `requisite pam_deny.so` gate was removed or demoted). pam_permit always succeeds, so either shape is a classic auth-bypass backdoor. Stock Ubuntu's `common-*` files end every stack with `required pam_permit.so` behind that deny gate, and session/password stacks can't grant a login, so neither is flagged, or (2) an NSS module listed in /etc/nsswitch.conf that isn't in ubuntils' built-in allowlist. **Note:** the NSS check will false-positive on domain-joined/SSSD/LDAP/Winbind hosts using a module outside the built-in allowlist — it is intentionally scored at lower confidence than the pam_permit.so match for this reason; use `--config` to allowlist unrecognized module names for your environment. Flag-only — authentication configuration changes require careful verification.

*Example findings:*
```
[HIGH] PAM_BACKDOOR
Title:         PAM config unconditionally permits authentication
Artifact:      /etc/pam.d/sshd
Raw value:     auth sufficient pam_permit.so
Remediation:   not available
```
```
[HIGH] PAM_BACKDOOR
Title:         Unexpected NSS module in nsswitch.conf
Artifact:      /etc/nsswitch.conf
Raw value:     passwd: files evilmod
Remediation:   not available
```

**KERNEL_MODULE_SUSPICIOUS** — Kernel modules run in ring 0 with unrestricted access. Attackers frequently load custom kernel modules for rootkits, packet sniffing, or process hiding. Rather than guess from module names, the rule asks the kernel: every loaded module's taint flags are read from `/proc/modules`. A module built with the running kernel and signed by it carries no taint and is not reported, whatever hardware it drives — a clean Ubuntu 24.04 KVM guest has 26 such modules (`kvm_intel`, `aesni_intel`, `floppy`, …) that a name list alone flagged. An LKM rootkit is built out of tree, so the kernel marks it `O` (and `E` when module signing isn't enforced); out-of-tree, unsigned, proprietary or force-loaded modules are reported **MEDIUM**, naming the flags. Third-party drivers carry the same flags — NVIDIA and VMware modules will be reported; VirtualBox's and Ubuntu's own ZFS are allowlisted. A rootkit that hides itself from the module list entirely is beyond any live check; this rule finds the ones that don't. When taint data isn't available (offline analysis of a bundle from an older ubuntils, or `--root`), the rule falls back to comparing names against a small allowlist of common built-in modules and reports anything else as **LOW**. Responders should add their host's expected modules via `--config`, allowlisting by module name (used as the `artifact_path`). Flag-only — kernel module investigation requires forensic tools and human expertise.

*Example finding:*
```
[LOW] KERNEL_MODULE_SUSPICIOUS
Title:         Loaded kernel module not in the expected set
Artifact:      implant_rootkit
Raw value:     {'name': 'implant_rootkit', 'size': '12288', 'used_by': []}
Remediation:   not available
```

**SETUID_INVENTORY** — Setuid and setgid binaries escalate privileges automatically when executed. Attackers create custom setuid/setgid binaries to persist privilege escalation, most often outside the standard system binary directories (a mainstream install path like /opt, a user's own /home, /srv, or a world-writable temp dir). This rule inventories setuid/setgid binaries via `find -perm -4000 -o -perm -2000` across `/usr /bin /sbin /opt /home /srv /tmp /var/tmp /dev/shm` and flags any outside a known baseline set of legitimate system utilities. Flag-only — unexpected setuid/setgid binaries require investigation but may be legitimate application-installed binaries.

*Example finding:*
```
[LOW] SETUID_INVENTORY
Title:         Unexpected setuid binary
Artifact:      /tmp/.hidden/backdoor
Raw value:     setuid
Remediation:   not available
```

### Not covered

These persistence and access paths are known to be outside what ubuntils checks today. A clean report says nothing about them, so check them by hand:

- **`AuthorizedKeysCommand`** in `sshd_config`: sshd runs this program to fetch extra keys for a login, so a planted command can grant access without touching any `authorized_keys` file.
- **`~/.ssh/rc` and `/etc/ssh/sshrc`**: run by sshd at every SSH login, before the user's shell.
- **sshd `Include` directives outside `/etc/ssh/sshd_config.d/`**: `AuthorizedKeysFile` settings in other included files aren't read.
- **`pam_exec.so`** lines in `/etc/pam.d/*`: they run an arbitrary program during authentication or session setup. `PAM_BACKDOOR` only looks at `pam_permit.so` and NSS modules.

TODO: flag-only rules for `AuthorizedKeysCommand` and `pam_exec.so`. Both are easy to detect, but stock cloud images set `AuthorizedKeysCommand` (EC2 Instance Connect, GCE OS Login). The rules need a known-good list validated on real hosts first, or they would report every such host.

---

## JSON output

`--json` writes a single JSON object to stdout. Nothing else is printed.

```json
{
  "scan_metadata": {
    "tool_version": "2.3.0",
    "hostname": "web-01",
    "generated_at": "2026-06-10T08:22:03.114523+00:00",
    "ubuntu_version": "Ubuntu 22.04.3 LTS",
    "architecture": "x86_64",
    "duration_s": 2.84,
    "collector_failures": 0,
    "bundle_integrity": "live",
    "command_collectors_skipped": [],
    "collectors_degraded": {},
    "rules_failed": [],
    "detection_error": null,
    "timeline_error": null,
    "suppressed_by_baseline": 1
  },
  "artifact_counts": {
    "ProcessCollector": 142,
    "NetworkCollector": 23,
    "UserCollector": 4,
    "CronCollector": 7,
    "SystemdCollector": 12,
    "SSHCollector": 3,
    "SudoersCollector": 5,
    "EnvironmentCollector": 18
  },
  "findings": [
    {
      "rule_id": "CRON_TMP_PATH",
      "severity": "HIGH",
      "title": "Cron job references writable temp directory",
      "description": "A cron job was found referencing /tmp, /var/tmp, or /dev/shm. These directories are world-writable and commonly used as attacker staging grounds.",
      "artifact_path": "/etc/cron.d/cleanup",
      "raw_value": "0 * * * * root /tmp/.update",
      "remediation_available": true,
      "remediation_description": "Will remove the offending cron entry from /etc/cron.d/cleanup after creating a timestamped backup.",
      "related_events": [
        {
          "timestamp": "2024-01-15T08:20:00+00:00",
          "source": "syslog",
          "program": "CRON",
          "description": "(root) CMD (/tmp/.update)"
        }
      ],
      "confidence": 75,
      "confidence_band": "HIGH",
      "signals": [
        {"name": "timeline_corroboration", "weight": 25, "detail": "1 timeline event(s) name this artifact alongside related activity"}
      ]
    },
    {
      "rule_id": "PROCESS_MASQUERADE",
      "severity": "MEDIUM",
      "title": "Process masquerading as system binary",
      "description": "Process 'sshd' (pid=1337) has exe path outside standard binary directories: /tmp/.sshd",
      "artifact_path": "/proc/1337/exe",
      "raw_value": "/tmp/.sshd",
      "remediation_available": false,
      "guided_remediation": "Confirm pid 1337 is malicious (`ls -l /proc/1337/exe`, `cat /proc/1337/cmdline`), then terminate it: `kill -9 1337`.",
      "confidence": 50,
      "confidence_band": "MEDIUM",
      "signals": []
    }
  ],
  "timeline": [
    {
      "timestamp": "2024-01-15T08:22:01+00:00",
      "source": "syslog",
      "program": "sshd",
      "description": "Accepted publickey for alice from 10.0.0.42 port 52341"
    }
  ],
  "report_sha256": "a3f1c9…(64 hex chars)"
}
```

`remediation_results` appears as an additional top-level key only when `--remediate` is passed. `report_sha256` is always present and is computed over the rest of the document. `scan_metadata.bundle_integrity` is `"live"` for `scan` and `analyze --root`, `"ok"` for a verified bundle passed to `analyze`, and `"mismatch"` if a bundle's content doesn't match its manifest — see [Bundle integrity in JSON output](#bundle-integrity-in-json-output). `scan_metadata.command_collectors_skipped` names any command-based collectors (`NetworkCollector`, `SystemdCollector`, `PackageCollector`, `KernelCollector`) skipped for a `--root` run — always empty for `scan` and `analyze BUNDLE`. `scan_metadata.suppressed_by_baseline` is the count of findings a `--baseline` file removed from this report — see [Known-good baselining](#known-good-baselining---baseline) — and `suppressed_by_allowlist` the count a `--config` allowlist removed, so a report always shows that findings were hidden. `scan_metadata.collectors_degraded` maps a collector name to the reasons its data is incomplete (a command that failed or timed out, an unreadable file, a skipped malformed line), `rules_failed` lists any detection rule that crashed (`DetectionEngine` if the whole detection stage failed, with the error in `detection_error` and exit status 1), and `timeline_error` is set if the timeline couldn't be built. All of them are empty on a healthy run. Check them before reading an empty findings list as "clean".

`related_events` and `guided_remediation` appear on a finding only when they have content. `related_events` holds up to five timeline events matched to the finding, most recent first — a surfacing aid, not a causal claim. Matching is on whole words against each event's program and message: identifying tokens from the finding (a path basename, a `/home/<user>` name, a package, module or account name) and a few per-rule activity keywords (`sshd`, `cron`, `dpkg`, …). Events that name the artifact *and* show that activity come first. Findings with no identifying token (the `PROCESS_*` rules, whose artifact is `/proc/<pid>/exe`) get keyword matches only, as context. Every timeline event carries a `program` field (the syslog tag or journald `SYSLOG_IDENTIFIER`, empty for auditd). `guided_remediation` is a reviewed command sequence for you to run by hand; ubuntils never executes it.

### Confidence scoring

Every finding carries a `confidence` score (0–100, default 50) and a `confidence_band` (`HIGH` ≥ 75, `MEDIUM` ≥ 40, `LOW` below that), plus a `signals` list showing exactly how that score was reached — each entry is `{"name", "weight", "detail"}`, so the score is always explainable, never a black box. Signals are additive on top of a base confidence of 50 and are applied by whichever rule or pipeline stage produced them:

- Detection rules apply their own signals at finding time — e.g. `SSH_UNAUTHORIZED_KEY` and `SHELL_RC_MODIFICATION` add `content_match` (+30) when the artifact's content matches a known-dangerous pattern (a dangerous SSH key option; a curl/wget-to-shell or base64-decode line in a shell RC file), `ctime_corroborates_mtime` (+20) when the file's ctime is also inside the detection window (harder to forge than mtime alone), or `mtime_only` (−20) when recency is the *only* signal and ctime doesn't corroborate it — a cue the mtime may have been backdated.
- Correlation applies `timeline_corroboration` (+25) only when at least one event names the finding's artifact alongside the rule's kind of activity — e.g. `useradd` logging the UID-0 account by name, or `dpkg` touching the tampered package. Keyword-only context events are never scored: on a busy host, words like `exec` or `connect` match thousands of unrelated lines, and an earlier version gave every finding this bonus.

A `LOW`-band finding is not dismissed or hidden — it still appears in the findings list and JSON output exactly like any other — but the band tells you how much weight to put on it before investigating further. This replaces the old mtime-only heuristic for `SSH_UNAUTHORIZED_KEY`/`SHELL_RC_MODIFICATION`, where a stale but legitimately-touched file (e.g. a config management tool rewriting `.bashrc` on every run) looked identical to a genuinely new backdoor.

**Known limitation:** only content-pattern and ctime signals are live today. Ownership/fingerprint-based signals — an unknown SSH key fingerprint, a key's `from=` restriction option, or an RC-file owner/mode mismatch (an `ownership_anomaly` signal) — are not yet implemented. This is a deferred coverage gap, tracked for a future release, not something the current confidence score accounts for.

---

## Remediation

Five of the seventeen detection rules have automated remediation: `CRON_ROOT_EXEC`, `CRON_TMP_PATH`, `LD_PRELOAD_INJECT`, `SSH_UNAUTHORIZED_KEY`, and `SUDOERS_NOPASSWD`. The rest are flag-only and will never be auto-remediated, because acting on them safely needs a human to look first.

### Guided remediation

`SUSPICIOUS_SYSTEMD_TIMER`, `PROCESS_MASQUERADE`, and `SHELL_RC_MODIFICATION` carry a `guided_remediation` string: the exact commands to run once you have confirmed the finding — `systemctl disable --now <unit>`, `kill -9 <pid>`, or the RC-file review and revert. It shows in the TUI detail pane and in JSON. ubuntils never runs it for you; these rules stay out of the `--remediate --confirm` sweep by design.

### In the TUI

Select any finding with a remediation in the Findings tab, then press `R`. A confirmation modal previews the planned action. Press `Y` to apply it — the remediator runs in a background thread so the TUI stays responsive. The finding row updates to `[fixed]` when done, with the backup path and exact rollback command shown inline.

### From the CLI

`--remediate` without `--confirm` is a safe dry run: validation runs and each result says what would change, but nothing is written — no change and no backup. Pass both flags to actually make changes. The pipeline runs before the TUI launches in this mode, and the Summary tab lists every remediation outcome with its backup path and rollback command.

`--remediate --confirm` never applies a fix that has a hard block in `blocked_reasons`, whatever its confidence: `AMBIGUOUS_KEY` (one of several keys in a file), `RECENCY_ONLY` (a key whose only evidence is a recent timestamp, which is also what a freshly provisioned host's admin key looks like), and `SOLE_SUDO_ACCESS` (a NOPASSWD rule for an account with no usable password, such as the cloud-image default user, whose removal would leave it no sudo at all). Those are reported as `SKIPPED` with the reason and stay fixable by hand in the TUI. Of the rest, it only acts on findings with a confidence score of at least 40 (the MEDIUM band). Adjust that gate with `--min-confidence N`; it never lifts a hard block.

```bash
ubuntils scan --remediate          # dry run
ubuntils scan --remediate --confirm # apply changes, then open TUI
ubuntils scan --remediate --confirm --min-confidence 75  # only HIGH-confidence findings
```

### Safeguards

Every remediation follows the same pattern regardless of how it is triggered:

1. Reach the artifact's directory by walking from `/` one component at a time without following symlinks, and refuse if any component is a symlink, if the file itself is one, or if the directory isn't the one the finding was made on (its device, inode and owner are recorded at detection time). An attacker who swaps `~/.ssh` for a link to another user's `.ssh` between detection and remediation gets a refusal, not a root write into the other directory. Every later read, write, `fchmod`/`fchown` and `rename` happens relative to that directory handle
2. Create a timestamped backup at `/var/backups/ubuntils/YYYYMMDD_HHMMSS/` (directory mode `0700`, file mode `0600`)
3. Validate current state (the exact line must still be present)
4. Apply the minimum possible change — cron entries and keys removed line by line; LD_PRELOAD lines in shell init files commented out; entries in `/etc/ld.so.preload` removed (the loader has no comment syntax there, so a commented entry would still load). For sudoers, the edited content is checked with `visudo -cf` on a temporary copy *before* the real file is touched
5. Write atomically — new content goes to a randomly named temp file beside the original (same mode and owner), is fsync'd, then renamed over it, so a crash mid-write can't leave a truncated `/etc/sudoers`
6. Record a rollback sidecar, `<backup>.json`, holding the original path, owner, group and mode, the parent directory's device and inode, and the SHA-256 of the content remediation left behind
7. Verify the exact line is gone

If any step fails, remediation stops immediately, the system is left unchanged, and the full error is reported with the backup path. Sudo access is protected three ways: `%group` NOPASSWD rules (like `%sudo`) are flag-only and never auto-removed, a rule for an account with no usable password is blocked from automatic removal (`SOLE_SUDO_ACCESS`), and the sudoers remediator refuses to remove the last rule from the main sudoers file.

### Rollback

```bash
ubuntils rollback /var/backups/ubuntils/20260115_142201/etc_cron.d_cleanup
```

Every successful remediation prints this command. It reads the backup's sidecar and restores the file through the same safe path as remediation: no symlinks in any component, an atomic rename, and the original owner and mode. It refuses when the file has changed since it was remediated, when its directory is no longer the same one (a different inode), or when the backup or sidecar isn't root-owned. `--force` restores anyway after you've checked. Even with `--force`, a symlink in the path, a symlinked target or a non-regular file is always refused.

Don't roll back with `cp backup original`. Run as root, `cp` follows a symlink at the destination, so an attacker who replaced the remediated file with a link to `/etc/shadow` would get root to overwrite it with the backup's content, which they wrote in the first place.

---

## Wazuh Integration

ubuntils is built for a single-host, point-in-time triage — you run it when
you already suspect something's wrong, and it never phones home or keeps
watching after the scan ends. That's deliberate, but it also means a finding
from ubuntils lives only in that one report unless something carries it
forward. Most teams running Ubuntu at any scale already have a SIEM doing
the continuous side of detection, so rather than build ubuntils into its own
long-running monitoring agent, it hands its findings to the one you likely
already run: Wazuh.

If a Wazuh agent is present on the host (`/var/ossec/bin/wazuh-agentd` or
`/var/ossec/etc/ossec.conf` exists), `ubuntils scan` (unless run with `--no-wazuh`) appends
each finding as one JSON line to `/var/log/ubuntils/wazuh-alerts.json` for
the agent to pick up — this is a pure forwarder, not a Wazuh module: no
network call, no API key, nothing but the same local artifact writes
ubuntils already makes — though the agent will of course ship those lines
off-host to its manager; that is the point. It's auto-detected with no
flag required (use `--no-wazuh` to opt a run out), so a
scripted or scheduled `ubuntils scan` on a fleet of agent-enrolled hosts
starts feeding the SIEM immediately with no extra wiring. This never
happens during offline `ubuntils analyze` (bundle or `--root`), since
those findings describe a different host than the one running the local
Wazuh agent — forwarding a bundle's findings to the analyst's own agent
would misattribute them to the wrong machine.

The intent is to fold ubuntils into an existing alerting/escalation
pipeline instead of asking a responder to babysit a second tool: once the
example rules below are loaded, a HIGH-severity ubuntils finding (a new
UID-0 account, an LD_PRELOAD rootkit, a PAM backdoor) shows up as a normal
Wazuh alert, inherits whatever notification routing the manager already
has configured, and sits alongside every other signal in the same
timeline instead of a standalone JSON file someone has to remember to
check.

To have Wazuh parse and alert on these findings, copy the example rules
from `examples/wazuh/` onto your Wazuh manager, and add the `<localfile>`
block from `examples/wazuh/ossec_localfile_snippet.xml` to the agent's
`/var/ossec/etc/ossec.conf`. No custom decoder install is needed: the
localfile is configured with `log_format json`, so Wazuh's built-in JSON
decoder parses each line and maps every top-level JSON key `k` to `data.k`,
which `local_rules.xml` matches on directly.

1. `examples/wazuh/local_rules.xml` → manager's `/var/ossec/etc/rules/`
2. `examples/wazuh/ossec_localfile_snippet.xml`'s `<localfile>` block → agent's `/var/ossec/etc/ossec.conf`
3. Restart both: `systemctl restart wazuh-manager` (manager), `systemctl restart wazuh-agent` (agent host)

These are example templates only, provided as a starting point — they have
not been tested against a live Wazuh manager and should be verified in a
non-production environment before relying on them.

**JSON schema per line:**

| Field | Type | Description |
|---|---|---|
| `timestamp` | string (ISO 8601) | When the finding was forwarded |
| `hostname` | string | The scanned host |
| `rule_id` | string | Matches ubuntils' detection rule ID (see Detection Rules table above) |
| `severity` | string | `HIGH` \| `MEDIUM` \| `LOW` |
| `title` | string | Short human-readable title |
| `description` | string | Full finding description |
| `artifact_path` | string | File/resource path where the issue was found |
| `raw_value` | string | The raw line/value that triggered the rule |
| `remediation_available` | bool | Whether ubuntils has a remediator for this rule |
| `confidence` | int (0–100) | Confidence score — see [Confidence scoring](#confidence-scoring) |
| `confidence_band` | string | `HIGH` \| `MEDIUM` \| `LOW`; rule 100104 in the example escalates HIGH-severity findings with a HIGH band, and rule 100105 raises `USER_FILE_OVERSIZED` |
| `related_events` | array (optional) | Correlated timeline events (`timestamp`, `source`, `program`, `description`), if any |
| `truncated` | bool (optional) | `true` if anything in this line was cut to keep it bounded (see below) |

Every string field can carry attacker text, such as a forged log line or a padded file's path, so each line is bounded. String fields are cut to 2,048 characters, related event descriptions to 1,024, and if the line is still over 32 KiB its `related_events` are dropped. The full finding is always in the JSON report.

If any collector was degraded (a file it couldn't read, a command that failed), the scan also forwards one summary event with `rule_id` `UBUNTILS_SCAN_DEGRADED`, severity `MEDIUM`, the reasons in `description` and the collector names in `collectors_degraded`, so a partial scan doesn't look clean in the SIEM.

---

## Collectors

| Collector | Artifacts gathered |
|---|---|
| ProcessCollector | Running processes from `/proc` and `ps` output |
| NetworkCollector | Open connections and listeners from `ss`/`netstat` |
| UserCollector | `/etc/passwd`, `/etc/shadow`, `/etc/group` |
| CronCollector | `/etc/cron*` directories and `/var/spool/cron/crontabs/*` |
| SystemdCollector | `systemctl list-timers` output, plus `.service` unit files and drop-in overrides read from the unit directories |
| SSHCollector | `authorized_keys`, `authorized_keys2` and every `AuthorizedKeysFile` from `sshd_config`, for all users |
| SudoersCollector | `/etc/sudoers` and all files under `/etc/sudoers.d/` |
| EnvironmentCollector | `/etc/ld.so.preload`, `/etc/environment`, system shell init files (`/etc/profile`, `/etc/profile.d/*`, `/etc/bash.bashrc`, `/etc/zsh/*`), and user shell init files |
| PackageCollector | System package integrity via `dpkg --verify` (attributed to packages via `dpkg-query -S`), immutable flag attributes via `lsattr`, and setuid/setgid binaries via `find` |
| PamCollector | `/etc/pam.d/*` files and `/etc/nsswitch.conf` |
| KernelCollector | Loaded kernel modules via `lsmod`, with each module's taint flags from `/proc/modules` |

### Collector dependencies

`PackageCollector` requires three standard Ubuntu tools on the live host (`dpkg`, `lsattr`, `find` — all present on stock Ubuntu installations). If any command is unavailable, `PackageCollector` gracefully produces empty data for that portion rather than crashing. Offline analysis (`analyze BUNDLE`) replays the captured command output from `collect` time, so command availability on the analyzer's host is not required.

The setuid/setgid `find` scan passes `-xdev` to stay bounded — it does not descend into separately-mounted filesystems (a distinct mount under `/opt`, an NFS-mounted `/home`, etc.). This is a deliberate runtime-vs-coverage tradeoff: without `-xdev`, the scan could hang scanning network mounts or virtual filesystems. If your environment mounts these paths on separate filesystems, be aware they will not be scanned.

`dpkg --verify` and the setuid/setgid `find` scan use generous non-default timeouts (10 minutes and 5 minutes respectively, see `ubuntils/collectors/packages.py`) since both can legitimately run well past the library default of 30 seconds on a real host with a large package database or filesystem tree; `ubuntils collect` uses the same timeouts when capturing these commands into a bundle.

---

## Demo lab: plant something to find

`tools/lab/seed-lab.sh` plants inert, attacker-style artifacts on a **disposable** Ubuntu VM so you can watch ubuntils find them — for demos, workshops, or checking a build end to end.

```bash
sudo tools/lab/seed-lab.sh plant      # asks for confirmation; UBUNTILS_LAB_YES=1 skips it
ubuntils scan                         # or: ubuntils scan --json --output lab.json
sudo tools/lab/seed-lab.sh clean      # removes everything it planted
```

| Rule it trips | What gets planted |
|---|---|
| `USER_UID_ZERO` | `ubuntils-lab-root`, a locked UID-0 alias with a `nologin` shell (its `useradd` log line also earns timeline corroboration) |
| `CRON_TMP_PATH` | `/etc/cron.d/ubuntils-lab` running a `/tmp` script — scheduled for 31 February, so it never fires |
| `CRON_ROOT_EXEC` | a crontab for the locked `ubuntils-lab` user that calls `sudo` (same never-firing schedule) |
| `SUDOERS_NOPASSWD` | `/etc/sudoers.d/ubuntils-lab` — NOPASSWD for the locked user, `visudo`-checked |
| `SSH_UNAUTHORIZED_KEY` | a `command=` key in `authorized_keys` and a second key in `authorized_keys2` — generated fresh, private half destroyed |
| `SHELL_RC_MODIFICATION`, `LD_PRELOAD_INJECT` | a `curl … \| bash` line and a `/tmp` `LD_PRELOAD` in the locked user's `.bashrc` |
| `SUSPICIOUS_SYSTEMD_TIMER` | a unit running from `/tmp`, and a drop-in override that pipes `curl` into `bash` — neither enabled nor started |
| `PAM_BACKDOOR` | `/etc/pam.d/ubuntils-lab` with `auth sufficient pam_permit.so`, a service no program uses |
| `PROCESS_MASQUERADE` | two renamed copies of `bash` that only sleep: `kworker` from `/dev/shm` (fake kernel thread, HIGH) and `sshd` from `/var/tmp` |
| `SETUID_INVENTORY` | `/opt/ubuntils-lab/beacon`, a setuid-bit shell script — Linux ignores setuid on scripts, so it grants nothing |
| `IMMUTABLE_FLAG_SET` | the append-only flag on `/var/log/btmp` |
| `PACKAGE_TAMPERED` | one comment line appended to `base-files`' `/usr/share/base-files/dot.bashrc` (restored on `clean`) |
| `KERNEL_MODULE_SUSPICIOUS` | the harmless `dummy` network module |

Nothing it plants can run or let anyone in: cron entries never fire, units are never enabled, the lab accounts are locked, no private key exists, and URLs use the reserved `.invalid` domain. Every action is recorded in `/var/lib/ubuntils-lab/actions`, and `clean` undoes them in reverse. `PROCESS_SUSPICIOUS_CONNECTION` is left out because it needs a live outbound connection; `USER_EMPTY_PASSWORD` needs a genuinely passwordless login, so it's only planted with `plant --with-empty-password`. `USER_FILE_OVERSIZED` isn't planted: it needs a multi-megabyte padded file in a user's home.

The remediable findings make a good in-TUI remediation demo: press **R** on the cron, sudoers, SSH or `LD_PRELOAD` finding. Backups from those fixes stay in `/var/backups/ubuntils/` after `clean`.

---

## Compatibility

| | Supported |
|---|---|
| **Ubuntu** | 22.04, 24.04, 26.04 |
| **Architecture** | amd64, arm64 |
| **Python** | 3.9+ (3.10+ for the hash-verified install; ubuntils 3.0 will require 3.10) |
| **Privileges** | Root required for full artifact access |

Ubuntu 20.04 is no longer listed: its system Python is 3.8, below the 3.9 minimum, and its standard support has ended. CI runs on 22.04 and 24.04 (amd64 and arm64); 26.04 was validated by hand on arm64 for 2.2.0.

Running without root produces a partial scan with warnings. Critical paths like `/etc/shadow`, protected crontab directories, and some `/proc` entries will be skipped.

---

## Roadmap

**v1.0.0**
- [x] All 8 collectors
- [x] All 8 detection rules
- [x] Timeline builder (syslog, journald, auditd)
- [x] Live scan progress screen with per-collector ✓/✗
- [x] Interactive four-tab TUI (Summary / Findings / Timeline / Stats)
- [x] In-TUI remediation with confirmation modal and background worker
- [x] JSON output mode
- [x] CLI remediation for 5 rules with backup, rollback, and symlink guard
- [x] Ubuntu 20.04/22.04/24.04 support
- [x] 240 tests at 90% coverage

**v1.1.0**
- [x] False-positive allowlisting by rule id or path (`--config`)
- [x] `--output FILE` to write reports directly
- [x] `--since` timeline windowing
- [x] Tamper-evident reports (`report_sha256`, hostname, timestamp)
- [x] `USER_UID_ZERO` detection rule

**v1.5.0**
- [x] Custom pattern-match detection rules via YAML (`--rules`)
- [x] `PROCESS_SUSPICIOUS_CONNECTION` — process↔network correlation by PID
- [x] Automatic finding↔timeline correlation (`related_events`)
- [x] Guided remediation for the three judgment-required rules
- [x] 282 tests at 92% coverage

VirusTotal hash lookups and MISP IOC export were dropped from this release. VirusTotal only answers for *known* hashes — the case `rkhunter` already covers, and the opposite of the novel-technique gap ubuntils targets — and both features would have put a network call inside a tool whose value rests on making none. ubuntils itself still makes no network calls (see the [Wazuh integration](#wazuh-integration) for the one opt-out-able way findings can leave the host, via a local agent).

**v2.0.0 — offline collect/analyze split**
- [x] `ubuntils collect` — acquires a tamper-evident bundle (`manifest.json` + hashed files/commands) from a live host, no detection
- [x] `ubuntils analyze (BUNDLE | --root PATH)` — runs the same detection/timeline pipeline as `scan` against a bundle or a mounted image, no root required
- [x] `bundle_integrity` (`live`/`ok`/`mismatch`) surfaced in `scan_metadata`
- [x] Documented detection-coverage gaps in offline mode (`PROCESS_MASQUERADE`, `PROCESS_SUSPICIOUS_CONNECTION`, and reduced coverage for cron/sudoers/SSH glob paths and systemd timer `ExecStart`)
- [x] Trustworthy detection: confidence scoring (`confidence`/`confidence_band`/`signals`), `--baseline` suppression, replacing mtime-only heuristics in `SSH_UNAUTHORIZED_KEY`/`SHELL_RC_MODIFICATION` with ctime + content signals, and a real offline timeline for both `analyze BUNDLE` and `analyze --root`
- [x] Coverage pack: `PACKAGE_TAMPERED`, `IMMUTABLE_FLAG_SET`, `PAM_BACKDOOR`, `KERNEL_MODULE_SUSPICIOUS`, `SETUID_INVENTORY` (via `PackageCollector`, `PamCollector`, `KernelCollector`; all flag-only by design)
- [x] 400 tests at 93.79% coverage

**v2.1.0 — SIEM forwarding**
- [x] Live `ubuntils scan` findings forwarded to a local Wazuh agent as JSONL, auto-detected (no flag required)
- [x] Example Wazuh decoder/rules and `ossec.conf` `<localfile>` snippet (`examples/wazuh/`)
- [x] Forwarding intentionally scoped to live `scan` only — never fires during offline `analyze`, since a bundle or image describes a different host than the one running the agent
- [x] `--no-wazuh` to opt a scan out of forwarding

**v2.1.0 — hardening (full-codebase audit)**
- [x] Security: sudo re-exec no longer forwards the caller's `PATH`, and commands resolve on a fixed secure path; sudoers edits are `visudo`-checked *before* touching the file; atomic remediation writes; symlink-safe report/bundle output; extracted bundles deleted after `analyze`
- [x] Detection coverage: `/etc/ld.so.preload` parsed, `@reboot`/`@daily` cron entries and `/etc/cron.{hourly,daily,weekly,monthly}` scripts, systemd `.service` units and non-root-owned ExecStart binaries, `%group` sudoers rules and `#include`/`@includedir`, every element of an `LD_PRELOAD` list
- [x] New `USER_EMPTY_PASSWORD` rule (login account with no password)
- [x] Fewer false positives: separator-bounded path checks, setuid vs setgid told apart, snap/`/usr/lib` daemons treated as standard, `KERNEL_MODULE_SUSPICIOUS` demoted to LOW, one NSS finding per module
- [x] Honest reports: failed rules and degraded collectors recorded in `scan_metadata` and the TUI; a timeline failure no longer discards findings; tampered bundles warn and exit 3; syslog year/timezone handled correctly
- [x] Safer remediation: `--min-confidence` gate (default 40), results shown in the TUI after `scan --remediate`
- [x] 444 tests at 94.29% coverage

**v2.2.0 — validated on Ubuntu 26.04 LTS (arm64)** — see [CHANGELOG.md](CHANGELOG.md)
- [x] False positives from a live 26.04 scan fixed: stock PAM stacks, inbound SSH sessions, sudo-rs, arm64/virtio kernel modules — 1,243 findings on a clean VM down to 13
- [x] `PACKAGE_TAMPERED` grouped per package, with `/var`-only and missing-directory downgrades
- [x] Confidence scoring: timeline corroboration only for events that name the artifact; whole-word, program-aware correlation; syslog/journald duplicates collapsed
- [x] Pre-conference security audit: no working-directory imports on the root re-exec, contained bundle reads, bounded reads of user-controlled files, markup-safe TUI
- [x] New coverage: `authorized_keys2`/`AuthorizedKeysFile`, systemd drop-ins, `/etc/bash.bashrc` and zsh files, kernel-thread impersonation; mtime *or* ctime for timestamp rules
- [x] `tools/lab/seed-lab.sh` demo lab that trips 14 of 16 rules with inert artifacts
- [x] 509 tests at 94.65% coverage

**v3.0.0 (planned)**
- A signed single-file build that runs offline with the system `python3`
- Likely-persistence vs hygiene grouping, ATT&CK IDs, a Markdown report
- Preserve-then-fix remediation, an independent PANIX coverage benchmark
- Not planned: a web dashboard, macOS, a continuous agent

---

## Contributing

The most useful contributions right now are new detection rules (added as standalone functions in `detectors/rules.py` with a matching test), additional collectors for artifact types not yet covered, remediation modules for `SUSPICIOUS_SYSTEMD_TIMER` and `SHELL_RC_MODIFICATION` (both currently flag-only by design, but safe auto-remediation paths may exist), test cases for edge cases on specific Ubuntu configurations, and documentation improvements.

Open an issue before starting a large contribution to avoid duplicate work.

---

## License

MIT

---

## Author

Built by Asmit — BTech Computer Science, PES University, Bengaluru. The tool came out of frustration with how long manual Ubuntu triage takes compared to what a well-scoped script can automate.
