Back to skill

Security audit

ext4-recovery

Security checks for vulnerabilities and agentic risk

Overview

This ext4 recovery skill is mostly purpose-aligned, but it gives users raw disk write-capable permissions and lacks safeguards that could prevent accidental data loss.

Review before installing. Use this only on a correctly identified offline source device, prefer a forensic image or narrowly scoped sudo read-only commands, do not follow the chmod 660/chown device workaround, and choose an empty output directory on a separate filesystem. Treat shell history and logs as sensitive and redact unrelated secrets before sharing them with an agent.

Vulnerability Patterns
  • Unauthorized Access and Privilege EscalationObtains permissions beyond the task's legitimate needs
  • Insecure Skill Coding PracticesFinds exploitable flaws such as hardcoded secrets or command injection
  • Skill Instruction HijackingAlters the agent's session goals or safety constraints when the skill loads
  • Agent Memory PoisoningWrites attacker-controlled rules into memory that affect later sessions
  • Remote Payload Retrieval and ExecutionFetches external code whose behavior can change after review
Findings (2)

T05 · Unauthorized Access and Privilege Escalation

Error
Location
SKILL.md:19
Finding
Recovery instructions grant unnecessary write access to the raw target device<![CDATA[ ## Vulnerability Details **File Location**: `SKILL.md:19-22`; repeated in `scripts/diag.sh:18-22` and `references/tool-limits.md:78` **Vulnerability Type**: Violation of least privilege for raw block-device access **Risk Level**: High ### Vulnerable Code and Instructions From `SKILL.md:19-22`: ```markdown 2. **All operations must open the device read-only**. When permissions are required, granting read permission is sufficient (`sudo chown $USER:disk <dev> && sudo chmod 660 <dev>`); do not use `sudo mount`. ``` The same recommendation is presented to users by `scripts/diag.sh:18-22`: ```bash if [ ! -r "$DEV" ]; then echo "!! No permission to read $DEV. Run as root, or execute:" echo " sudo chown \$USER:disk $DEV && sudo chmod 660 $DEV" exit 1 fi ``` It is also repeated in `references/tool-limits.md:78`: ```markdown 2. Is the device readable? → No: sudo chown $USER:disk <dev> ``` ### Technical Analysis The documented `chmod 660` operation grants both read and write access to the device owner and group. Changing the device owner to the interactive user additionally gives every process running under that account direct write access to the raw block device. This contradicts the project's stated read-only recovery model. Raw block-device write access is not necessary for the diagnostic or recovery scripts: both Python code and `diag.sh` only require read access. A mistaken shell command, compromised user process, parser defect, or unrelated application running under the same account could consequently write directly to filesystem metadata and data blocks. The permission change can also persist until the device node is recreated or its ownership and mode are manually restored. ### Attack Path 1. A user cannot initially read the recovery device. 2. The user follows the supplied instruction and runs: ```bash sudo chown "$USER":disk /dev/sdb1 sudo chmod 660 /dev/sdb1 ``` 3. The interactive user and members of the `disk` grou ...[truncated 967 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Remove every recommendation to use `chmod 660` or transfer ownership of a block device to an interactive user. 2. Use a narrowly scoped privileged invocation that preserves root ownership and opens the device read-only. 3. If an access-control change is unavoidable, grant read-only access through an appropriate temporary ACL or mode, for example: ```bash sudo setfacl -m "u:$USER:r--" /dev/sdb1 ``` Remove the ACL immediately after recovery: ```bash sudo setfacl -x "u:$USER" /dev/sdb1 ``` 4. Update `diag.sh` to treat write access as an error instead of a warning: ```bash if [ -w "$DEV" ]; then echo "Refusing to continue: the target device is writable." >&2 exit 1 fi ``` 5. Preserve and restore the original ownership, mode, and ACLs if the workflow modifies device permissions. 6. Apply the corrected guidance consistently in `SKILL.md`, `scripts/diag.sh`, and `references/tool-limits.md`. ]]>

T09 · Insecure Skill Coding Practices

Error
Location
scripts/ext4recover.py:273
Finding
Recovery output can be written onto the source filesystem and overwrite recoverable data<![CDATA[ ## Vulnerability Details **File Location**: `scripts/ext4recover.py:108-149` and `scripts/ext4recover.py:273-284` **Vulnerability Type**: Missing destination-filesystem validation and unsafe output-file replacement **Risk Level**: High ### Vulnerable Code The recursive recovery logic creates and writes to the caller-provided path without validating its backing filesystem: ```python if typ == E.S_IFDIR: ents = js.dir_entries(info) if ents is None: self.stats["unreadable_dir"] += 1 if not quiet: print(" %s%s/ !! Directory data unreadable (ino=%d)" % (" " * depth, path, ino)) return 0, 0 if outdir: os.makedirs(outdir, exist_ok=True) nf = nb = 0 for (cino, name, ft) in sorted(ents, key=lambda x: x[1]): if name in (b".", b".."): continue nm = name.decode("utf-8", "replace") sub, sb = self.walk(cino, nm, os.path.join(outdir, nm) if outdir else None, depth + 1, maxdepth, quiet) ``` Recovered files are opened in truncating mode: ```python if outdir: d = os.path.dirname(outdir) if d: os.makedirs(d, exist_ok=True) with open(outdir, "wb") as fh: fh.write(data) ``` The command only verifies that an output argument was supplied: ```python def cmd_recover(dev, target, outdir, limit_mb=None, quiet=False): fs = E.Ext4FS(dev) js = E.JournalScanner(fs).build() if target.isdigit(): ino = int(target) else: ino = resolve_path(js, target) if ino is None: die("Path resolution failed: %s" % target) if not outdir: die("--out must specify an output directory on another filesystem") print("\n=== Recover inode %d -> %s ===" % (ino, outdir)) w = Walker(js, limit_mb * 2**20 if limit_mb else None) nf, nb = w.walk(ino, str(ino), outdir, quiet=quiet) ``` ### Technical Analysis Although the error message says that the output must reside on anoth ...[truncated 2632 chars]
Remediation
<![CDATA[ ## Remediation Suggestions 1. Refuse recovery when the source block device or its parent filesystem is mounted. Perform this check inside `ext4recover.py`; do not rely on users running `diag.sh` first. 2. Resolve the destination's backing mount using `/proc/self/mountinfo` or equivalent platform APIs. 3. Compare the destination mount's device major and minor numbers with the source device. Abort if they identify the same filesystem or underlying block device. 4. Account for device-mapper, partition, bind-mount, and symbolic-link cases by canonicalizing both source and destination and resolving the complete backing-device relationship. 5. Require the destination to be a newly created, empty directory on a verified different filesystem. 6. Prevent replacement of existing files by using exclusive, no-follow creation: ```python flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL if hasattr(os, "O_NOFOLLOW"): flags |= os.O_NOFOLLOW fd = os.open(path, flags, 0o600) with os.fdopen(fd, "wb") as fh: fh.write(data) ``` 7. Reject symbolic links in all destination path components, or use directory file descriptors with `openat`-style operations and `O_NOFOLLOW`. 8. Write to a temporary file in the verified destination, flush and synchronize it, then atomically rename it to the final name. 9. Abort safely if a destination collision occurs instead of truncating or silently replacing the existing file. ]]>
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Tool MisuseTool Parameter Abuse, Chaining Abuse, Unsafe Defaults
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
Findings (11)

Chaining Abuse

High
Category
Tool Misuse
Content
if [ ! -r "$DEV" ]; then
  echo "!! 无读取 $DEV 的权限。请用 root 运行,或执行:"
  echo "   sudo chown \$USER:disk $DEV && sudo chmod 660 $DEV"
  exit 1
fi
Confidence
75% confidence
Finding
Tool calls are chained to bypass individual safety checks or escalate capabilities beyond what any single tool call would allow.

Chaining Abuse

High
Category
Tool Misuse
Content
if [ ! -r "$DEV" ]; then
  echo "!! 无读取 $DEV 的权限。请用 root 运行,或执行:"
  echo "   sudo chown \$USER:disk $DEV && sudo chmod 660 $DEV"
  exit 1
fi
Confidence
75% confidence
Finding
Tool calls are chained to bypass individual safety checks or escalate capabilities beyond what any single tool call would allow.

Lp3

Medium
Category
MCP Least Privilege
Confidence
92% confidence
Finding
The skill invokes shell commands and local scripts against raw block devices but does not declare any tool or permission scope. Without explicit allowed-tools/permissions, an agent may execute broad shell operations in an under-constrained way, increasing the chance of unsafe device access or misuse beyond the intended read-only recovery workflow.

Sudo/Root Execution

Medium
Category
Privilege Escalation
Content
1. **绝不挂载待恢复分区**(读写挂载会立刻开始复用空闲块,覆盖待恢复数据)。
   不要点文件管理器、不要自动挂载、不要 `fsck` 修复。
2. **所有操作只读打开设备**。需要写权限时只授予读权限即可
   (`sudo chown $USER:disk <dev> && sudo chmod 660 <dev>`),不要用 `sudo mount`。
3. **恢复结果必须写到另一个文件系统**,绝不能写回待恢复分区。
4. 恢复产物先落地并校验,**之后**才考虑写回原盘。
5. 先做体检与可行性判断,再动手;不要在主盘上反复试探工具。
Confidence
90% confidence
Finding
Setting `chmod 660` on the block device broadens direct access to the raw device for the owner and group, which can enable accidental or unauthorized disk interaction. In the context of a recovery workflow, even small mistakes can destroy evidence or recovered data, so permission changes on the source device are especially risky.

Sudo/Root Execution

Medium
Category
Privilege Escalation
Content
1. **绝不挂载待恢复分区**(读写挂载会立刻开始复用空闲块,覆盖待恢复数据)。
   不要点文件管理器、不要自动挂载、不要 `fsck` 修复。
2. **所有操作只读打开设备**。需要写权限时只授予读权限即可
   (`sudo chown $USER:disk <dev> && sudo chmod 660 <dev>`),不要用 `sudo mount`。
3. **恢复结果必须写到另一个文件系统**,绝不能写回待恢复分区。
4. 恢复产物先落地并校验,**之后**才考虑写回原盘。
5. 先做体检与可行性判断,再动手;不要在主盘上反复试探工具。
Confidence
90% confidence
Finding
Setting `chmod 660` on the block device broadens direct access to the raw device for the owner and group, which can enable accidental or unauthorized disk interaction. In the context of a recovery workflow, even small mistakes can destroy evidence or recovered data, so permission changes on the source device are especially risky.

Missing User Warnings

Medium
Confidence
95% confidence
Finding
The skill instructs collection of shell history and system logs, which can expose sensitive user activity, credentials, hostnames, paths, and unrelated operational data. Because no privacy warning, consent step, or minimization guidance is provided, an agent could over-collect forensic evidence beyond what is necessary for ext4 recovery.

Missing User Warnings

Medium
Confidence
90% confidence
Finding
The document includes operational guidance that can directly affect a live filesystem, including immediate unmount actions and a device ownership change, but it does not present a clear, explicit warning that these steps can disrupt services, weaken device access controls, or cause further data loss if run on the wrong target. In a recovery/forensics skill, such commands are contextually relevant, but the lack of prominent safety guardrails makes accidental misuse materially more likely.

Sudo/Root Execution

Medium
Category
Privilege Escalation
Content
```
1. 分区是否已挂载?          → 是:立即 umount。绝不要在挂载状态下恢复。
2. 设备是否可读?            → 否:sudo chown $USER:disk <dev>
3. dumpe2fs -h 看三件事:
     a. Filesystem state 是否 clean(决定 s_start 是否为 0)
     b. Total journal size(决定覆盖窗口长度)
Confidence
86% confidence
Finding
The instruction `sudo chown $USER:disk <dev>` changes ownership of a block device node to the invoking user, granting broader direct access to raw disk contents and potentially persisting an unsafe permission state beyond the recovery session. In the context of filesystem recovery this may be suggested for convenience, but it is risky because a typo or inappropriate device selection can expose sensitive data or enable destructive writes to the wrong disk.

Sudo/Root Execution

Medium
Category
Privilege Escalation
Content
# 用法: bash diag.sh /dev/sdb1 [输出目录]
#
# 严格只读:不写入目标设备、不挂载该分区。若发现分区已挂载会立即中止。
# 需要能读设备节点(root,或先 `sudo chown $USER:disk <dev>`)。

DEV="${1:?用法: bash diag.sh /dev/sdbX [输出目录]}"
OUT="${2:-$PWD/ext4-recovery-diag}"
Confidence
70% confidence
Finding
Commands invoke sudo or root privileges. Verify this elevated access is necessary and justified.

Sudo/Root Execution

Medium
Category
Privilege Escalation
Content
if [ ! -r "$DEV" ]; then
  echo "!! 无读取 $DEV 的权限。请用 root 运行,或执行:"
  echo "   sudo chown \$USER:disk $DEV && sudo chmod 660 $DEV"
  exit 1
fi
Confidence
91% confidence
Finding
The explicit recommendation to run 'chmod 660' on the device node grants write permission in addition to read permission. On a block device containing recoverable evidence, enabling write access materially increases the risk of data alteration, evidence contamination, or destructive operator mistakes.

Sudo/Root Execution

Medium
Category
Privilege Escalation
Content
if [ ! -r "$DEV" ]; then
  echo "!! 无读取 $DEV 的权限。请用 root 运行,或执行:"
  echo "   sudo chown \$USER:disk $DEV && sudo chmod 660 $DEV"
  exit 1
fi
Confidence
91% confidence
Finding
The explicit recommendation to run 'chmod 660' on the device node grants write permission in addition to read permission. On a block device containing recoverable evidence, enabling write access materially increases the risk of data alteration, evidence contamination, or destructive operator mistakes.

Static analysis

No suspicious patterns detected.