feat(scripts): add dual-path forensic_timeline_audit.py CLI wrapper and auditor
- Add ingglish-aq-archive/scripts/forensic_timeline_audit.py with dual-path /workspace/ delegation and opt-out controls (--no-workspace-wrapper, --standalone, --disable-workspace-cli, --enable-workspace-cli, and FORENSIC_NO_WORKSPACE_WRAPPER=1). - Implement inode timestamp forensics (btime, mtime, ctime, atime and atomic-create vs. in-place-overwrite classification), PNG chunk/IDAT and PDF /CreationDate binary header inspection, and recent Git commit history correlation.
This commit is contained in:
1 parent
57d1baad77
commit
d2cf901ce8
1 file changed
+313
+313
@@ -0,0 +1,313 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Dual-path wrapper + standalone CLI for forensic_timeline_audit.py.
|
||||||
|
|
||||||
|
Default behavior:
|
||||||
|
- Accessible directly from /workspace/ container path:
|
||||||
|
/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/forensic_timeline_audit.py
|
||||||
|
- When invoked via the skill copy (~/.hermes/skills/.../scripts/forensic_timeline_audit.py),
|
||||||
|
acts as a dual-path wrapper resolving:
|
||||||
|
1. /workspace/ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/forensic_timeline_audit.py
|
||||||
|
2. /workspace/ingglish-aq-archive/scripts/forensic_timeline_audit.py
|
||||||
|
3. /workspace/forensic_timeline_audit.py
|
||||||
|
|
||||||
|
Opt-out mechanisms:
|
||||||
|
- Pass `--no-workspace-wrapper` (or `--standalone`) or set `FORENSIC_NO_WORKSPACE_WRAPPER=1`
|
||||||
|
to bypass dual-path `/workspace/` delegation and run the embedded auditor in-process.
|
||||||
|
- Pass `--disable-workspace-cli` to remove the `/workspace/` CLI script copies (opting out of
|
||||||
|
`/workspace/` CLI script accessibility on disk), or `--enable-workspace-cli` to re-provision it.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import datetime
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import struct
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
WORKSPACE_CANDIDATES = (
|
||||||
|
"/workspace/ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/forensic_timeline_audit.py",
|
||||||
|
"/workspace/ingglish-aq-archive/scripts/forensic_timeline_audit.py",
|
||||||
|
"/workspace/forensic_timeline_audit.py",
|
||||||
|
)
|
||||||
|
|
||||||
|
OPT_OUT_FLAGS = {"--no-workspace-wrapper", "--standalone"}
|
||||||
|
OPT_OUT_ENV = os.environ.get("FORENSIC_NO_WORKSPACE_WRAPPER", "").strip().lower() in ("1", "true", "yes") or (
|
||||||
|
os.environ.get("FORENSIC_DISABLE_WORKSPACE_CLI", "").strip().lower() in ("1", "true", "yes")
|
||||||
|
)
|
||||||
|
|
||||||
|
# Dual-path wrapper dispatch (unless opted out or already executing from target)
|
||||||
|
if not OPT_OUT_ENV and not any(arg in OPT_OUT_FLAGS for arg in sys.argv[1:]) and "--disable-workspace-cli" not in sys.argv[1:] and "--enable-workspace-cli" not in sys.argv[1:]:
|
||||||
|
try:
|
||||||
|
self_real = os.path.realpath(__file__)
|
||||||
|
except Exception:
|
||||||
|
self_real = ""
|
||||||
|
for target in WORKSPACE_CANDIDATES:
|
||||||
|
if os.path.exists(target):
|
||||||
|
try:
|
||||||
|
if os.path.realpath(target) != self_real:
|
||||||
|
os.execv(sys.executable, [sys.executable, target] + sys.argv[1:])
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def parse_timestamp(ts_str: str) -> float:
|
||||||
|
s = ts_str.strip()
|
||||||
|
if re.fullmatch(r"\d+(?:\.\d+)?", s):
|
||||||
|
return float(s)
|
||||||
|
if s.endswith("Z"):
|
||||||
|
s = s[:-1] + "+00:00"
|
||||||
|
dt = datetime.datetime.fromisoformat(s)
|
||||||
|
if dt.tzinfo is None:
|
||||||
|
dt = dt.replace(tzinfo=datetime.timezone.utc)
|
||||||
|
return dt.timestamp()
|
||||||
|
|
||||||
|
|
||||||
|
def fmt_utc(epoch: float | None) -> str | None:
|
||||||
|
if epoch is None:
|
||||||
|
return None
|
||||||
|
return datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def get_stat_forensics(path: Path) -> dict:
|
||||||
|
st = path.stat()
|
||||||
|
mtime = st.st_mtime
|
||||||
|
ctime = st.st_ctime
|
||||||
|
atime = st.st_atime
|
||||||
|
btime = getattr(st, "st_birthtime", None)
|
||||||
|
if btime is None:
|
||||||
|
try:
|
||||||
|
out = subprocess.check_output(["stat", "-c", "%W", str(path)], text=True).strip()
|
||||||
|
if out and out != "0" and out != "-":
|
||||||
|
btime = float(out)
|
||||||
|
else:
|
||||||
|
out_full = subprocess.check_output(["stat", str(path)], text=True)
|
||||||
|
m = re.search(
|
||||||
|
r"Birth:\s+(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}(?:\.\d+)?)\s+([+-]\d{4})",
|
||||||
|
out_full,
|
||||||
|
)
|
||||||
|
if m:
|
||||||
|
iso = f"{m.group(1).replace(' ', 'T')}{m.group(2)[:3]}:{m.group(2)[3:]}"
|
||||||
|
btime = datetime.datetime.fromisoformat(iso).timestamp()
|
||||||
|
except Exception:
|
||||||
|
btime = None
|
||||||
|
|
||||||
|
if btime is not None and abs(mtime - btime) < 2.0:
|
||||||
|
write_mode = "ATOMIC_CREATE_OR_REPLACE (btime ~= mtime)"
|
||||||
|
elif btime is not None and mtime - btime >= 2.0:
|
||||||
|
write_mode = "IN_PLACE_OVERWRITE (mtime > btime on existing inode)"
|
||||||
|
else:
|
||||||
|
write_mode = "UNKNOWN_BTIME"
|
||||||
|
|
||||||
|
if ctime - mtime > 2.0:
|
||||||
|
post_write_meta = "MOVED_OR_CHMOD_AFTER_WRITE (ctime > mtime)"
|
||||||
|
else:
|
||||||
|
post_write_meta = "NONE (ctime == mtime)"
|
||||||
|
|
||||||
|
return {
|
||||||
|
"inode": st.st_ino,
|
||||||
|
"size_bytes": st.st_size,
|
||||||
|
"btime_epoch": btime,
|
||||||
|
"btime_utc": fmt_utc(btime),
|
||||||
|
"mtime_epoch": mtime,
|
||||||
|
"mtime_utc": fmt_utc(mtime),
|
||||||
|
"ctime_epoch": ctime,
|
||||||
|
"ctime_utc": fmt_utc(ctime),
|
||||||
|
"atime_epoch": atime,
|
||||||
|
"atime_utc": fmt_utc(atime),
|
||||||
|
"write_mechanics": write_mode,
|
||||||
|
"post_write_metadata_activity": post_write_meta,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def inspect_png_binary(data: bytes) -> dict:
|
||||||
|
if not data.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||||
|
return {"valid_png": False}
|
||||||
|
pos = 8
|
||||||
|
info = {
|
||||||
|
"valid_png": True,
|
||||||
|
"idat_chunks": 0,
|
||||||
|
"idat_bytes": 0,
|
||||||
|
"text_chunks": [],
|
||||||
|
"time_chunk": None,
|
||||||
|
}
|
||||||
|
while pos + 8 <= len(data):
|
||||||
|
length = struct.unpack(">I", data[pos : pos + 4])[0]
|
||||||
|
ctype = data[pos + 4 : pos + 8].decode("latin1", errors="replace")
|
||||||
|
cdata = data[pos + 8 : pos + 8 + length]
|
||||||
|
if ctype == "IHDR" and len(cdata) >= 13:
|
||||||
|
w, h, bd, ct, comp, filt, inter = struct.unpack(">IIBBBBB", cdata[:13])
|
||||||
|
info["width"] = w
|
||||||
|
info["height"] = h
|
||||||
|
info["bit_depth"] = bd
|
||||||
|
info["color_type"] = ct
|
||||||
|
elif ctype == "IDAT":
|
||||||
|
info["idat_chunks"] += 1
|
||||||
|
info["idat_bytes"] += length
|
||||||
|
elif ctype == "tIME" and len(cdata) == 7:
|
||||||
|
yr, mo, dy, hr, mn, sc = struct.unpack(">HBBBBB", cdata)
|
||||||
|
info["time_chunk"] = f"{yr:04d}-{mo:02d}-{dy:02d}T{hr:02d}:{mn:02d}:{sc:02d}Z"
|
||||||
|
elif ctype in ("tEXt", "iTXt", "zTXt"):
|
||||||
|
info["text_chunks"].append(cdata.decode("latin1", errors="replace")[:120])
|
||||||
|
pos += 12 + length
|
||||||
|
return info
|
||||||
|
|
||||||
|
|
||||||
|
def inspect_pdf_binary(data: bytes) -> dict:
|
||||||
|
m_create = re.search(rb"/CreationDate\s*\(([^)]+)\)", data)
|
||||||
|
m_mod = re.search(rb"/ModDate\s*\(([^)]+)\)", data)
|
||||||
|
m_prod = re.search(rb"/Producer\s*\(([^)]+)\)", data)
|
||||||
|
return {
|
||||||
|
"creation_date_raw": m_create.group(1).decode("latin1", errors="replace") if m_create else None,
|
||||||
|
"mod_date_raw": m_mod.group(1).decode("latin1", errors="replace") if m_mod else None,
|
||||||
|
"producer": m_prod.group(1).decode("latin1", errors="replace") if m_prod else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_git_history(repo: str | None, path: Path) -> list[dict]:
|
||||||
|
git_dir = repo or str(path.parent)
|
||||||
|
try:
|
||||||
|
rel = os.path.relpath(path, git_dir)
|
||||||
|
out = subprocess.check_output(
|
||||||
|
["git", "-C", git_dir, "log", "-n", "3", "--pretty=format:%H|%ai|%ci|%s", "--", rel],
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
text=True,
|
||||||
|
).strip()
|
||||||
|
if not out:
|
||||||
|
return []
|
||||||
|
commits = []
|
||||||
|
for line in out.splitlines():
|
||||||
|
sha, ad, cd, subj = line.split("|", 3)
|
||||||
|
commits.append({"commit": sha[:10], "author_date": ad, "commit_date": cd, "subject": subj})
|
||||||
|
return commits
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def handle_workspace_provisioning(enable: bool) -> int:
|
||||||
|
if not enable:
|
||||||
|
removed = []
|
||||||
|
for cand in WORKSPACE_CANDIDATES:
|
||||||
|
if os.path.exists(cand) and os.path.realpath(cand) != os.path.realpath(__file__):
|
||||||
|
os.remove(cand)
|
||||||
|
removed.append(cand)
|
||||||
|
print(json.dumps({"workspace_cli_enabled": False, "removed_paths": removed}, indent=2))
|
||||||
|
return 0
|
||||||
|
else:
|
||||||
|
target = Path(WORKSPACE_CANDIDATES[0])
|
||||||
|
if not target.parent.exists() and Path("/workspace/ingglish-aq-archive/scripts").exists():
|
||||||
|
target = Path(WORKSPACE_CANDIDATES[1])
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
if os.path.realpath(str(target)) != os.path.realpath(__file__):
|
||||||
|
shutil.copy2(__file__, target)
|
||||||
|
os.chmod(target, 0o755)
|
||||||
|
print(json.dumps({"workspace_cli_enabled": True, "provisioned_path": str(target)}, indent=2))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser(description="Audit file provenance via stat, binary headers, and git log.")
|
||||||
|
ap.add_argument("--paths", nargs="+", default=[], help="File paths to audit")
|
||||||
|
ap.add_argument("--anchor-time", default=None, help="ISO-8601 UTC or epoch float anchor timestamp")
|
||||||
|
ap.add_argument("--anchor-label", default="Anchor Event", help="Label for the anchor timestamp")
|
||||||
|
ap.add_argument("--repo", default=None, help="Optional git repository root")
|
||||||
|
ap.add_argument("--json", action="store_true", help="Emit JSON output")
|
||||||
|
ap.add_argument(
|
||||||
|
"--no-workspace-wrapper",
|
||||||
|
"--standalone",
|
||||||
|
dest="no_workspace_wrapper",
|
||||||
|
action="store_true",
|
||||||
|
help="Opt out of dual-path /workspace/ wrapper delegation for this run",
|
||||||
|
)
|
||||||
|
ap.add_argument(
|
||||||
|
"--disable-workspace-cli",
|
||||||
|
action="store_true",
|
||||||
|
help="Opt out of /workspace/ CLI script accessibility by removing provisioned /workspace/ copies",
|
||||||
|
)
|
||||||
|
ap.add_argument(
|
||||||
|
"--enable-workspace-cli",
|
||||||
|
action="store_true",
|
||||||
|
help="Provision/restore the CLI script into /workspace/ingglish-hyperdope-gematria/ingglish-aq-archive/scripts/",
|
||||||
|
)
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
if args.disable_workspace_cli:
|
||||||
|
sys.exit(handle_workspace_provisioning(enable=False))
|
||||||
|
if args.enable_workspace_cli:
|
||||||
|
sys.exit(handle_workspace_provisioning(enable=True))
|
||||||
|
if not args.paths:
|
||||||
|
ap.error("the following arguments are required: --paths (unless --disable-workspace-cli or --enable-workspace-cli is used)")
|
||||||
|
|
||||||
|
anchor_epoch = parse_timestamp(args.anchor_time) if args.anchor_time else None
|
||||||
|
results = []
|
||||||
|
|
||||||
|
for p_str in args.paths:
|
||||||
|
p = Path(p_str).resolve()
|
||||||
|
if not p.exists():
|
||||||
|
results.append({"path": str(p), "exists": False})
|
||||||
|
continue
|
||||||
|
data = p.read_bytes()
|
||||||
|
sha256 = hashlib.sha256(data).hexdigest()
|
||||||
|
st_info = get_stat_forensics(p)
|
||||||
|
|
||||||
|
verdict = None
|
||||||
|
delta_s = None
|
||||||
|
if anchor_epoch is not None:
|
||||||
|
delta_s = round(st_info["mtime_epoch"] - anchor_epoch, 3)
|
||||||
|
verdict = "REGENERATED_AFTER_ANCHOR" if delta_s > 0 else "STALE_PRE_ANCHOR"
|
||||||
|
|
||||||
|
bin_info = {}
|
||||||
|
if p.suffix.lower() == ".png":
|
||||||
|
bin_info = inspect_png_binary(data)
|
||||||
|
elif p.suffix.lower() == ".pdf":
|
||||||
|
bin_info = inspect_pdf_binary(data)
|
||||||
|
|
||||||
|
results.append(
|
||||||
|
{
|
||||||
|
"executed_script": os.path.realpath(__file__),
|
||||||
|
"workspace_wrapper_bypassed": bool(args.no_workspace_wrapper or OPT_OUT_ENV),
|
||||||
|
"path": str(p),
|
||||||
|
"exists": True,
|
||||||
|
"sha256": sha256,
|
||||||
|
"anchor_label": args.anchor_label if anchor_epoch else None,
|
||||||
|
"anchor_utc": fmt_utc(anchor_epoch),
|
||||||
|
"mtime_minus_anchor_seconds": delta_s,
|
||||||
|
"verdict": verdict,
|
||||||
|
"stat": st_info,
|
||||||
|
"binary_header": bin_info,
|
||||||
|
"git_commits": get_git_history(args.repo, p),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if args.json:
|
||||||
|
print(json.dumps(results, indent=2))
|
||||||
|
else:
|
||||||
|
if anchor_epoch is not None:
|
||||||
|
print(f"Anchor [{args.anchor_label}]: {fmt_utc(anchor_epoch)} (epoch {anchor_epoch:.3f})")
|
||||||
|
print("-" * 88)
|
||||||
|
for r in results:
|
||||||
|
if not r["exists"]:
|
||||||
|
print(f"[MISSING] {r['path']}")
|
||||||
|
continue
|
||||||
|
s = r["stat"]
|
||||||
|
v = f" [{r['verdict']} ({r['mtime_minus_anchor_seconds']:+.1f}s)]" if r["verdict"] else ""
|
||||||
|
print(f"File: {r['path']}{v}")
|
||||||
|
print(f" Exec: {r['executed_script']} (wrapper_bypassed={r['workspace_wrapper_bypassed']})")
|
||||||
|
print(f" Inode: {s['inode']} | Size: {s['size_bytes']} B | SHA-256: {r['sha256'][:16]}...")
|
||||||
|
print(f" Birth: {s['btime_utc']}")
|
||||||
|
print(f" Modify: {s['mtime_utc']} <-- {s['write_mechanics']}")
|
||||||
|
print(f" Change: {s['ctime_utc']} <-- {s['post_write_metadata_activity']}")
|
||||||
|
if r["binary_header"]:
|
||||||
|
print(f" Header: {r['binary_header']}")
|
||||||
|
if r["git_commits"]:
|
||||||
|
c = r["git_commits"][0]
|
||||||
|
print(f" Git: {c['commit']} ({c['commit_date']}) {c['subject']}")
|
||||||
|
print()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in new issue
Block a user