#!/usr/bin/env python3
"""Synchronise the CPTS attack-flow vault into the public Astro collection.
The source notes remain canonical. This script performs only the mechanical
changes required by the site:
* replace Obsidian frontmatter with the site's content schema;
* remove the vault-only NoteBanner/dataview bootstrap;
* rewrite links between the 32 selected sheets to their public routes;
* rewrite attachment embeds to download/hash links, plus a signature link for
every attachment whose detached signature is already in ``public/downloads``;
* copy the 51 referenced attachments into ``public/downloads``;
* generate one SHA-256 sidecar per attachment plus a combined manifest;
* remove any previously published download the vault no longer references.
Detached OpenPGP signatures are deliberately produced after this script runs:
signing requires the user's private key and must never be hidden in a content
conversion step. See the command printed at the end of a successful run. Run
the script once more after signing so the sheets link to the new signatures;
``npm run verify:downloads`` checks them before a deploy.
What may be published is an explicit list (``SLUGS``). Three further checks
stand behind it, because the vault also holds working notes:
* ``NEVER_PUBLISH`` names notes that must not be added to ``SLUGS`` again;
* a note carrying the vault's ``SENSITIVE`` banner, or a complete private-key
block, stops the run before anything is written;
* every note and attachment is read through ``safe_source``, which refuses
symbolic links and anything that resolves outside the selected folders.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import sys
import unicodedata
from pathlib import Path
from urllib.parse import quote
sys.path.insert(0, str(Path(__file__).resolve().parent))
import safe_source
REPO = Path(__file__).resolve().parent.parent
SOURCE = Path(
os.environ.get(
"PENTEST_WORKFLOW_SOURCE",
str(
Path.home()
/ "git/NetrunnerVault/02Cybersecurity/Cheatsheets/Pentest Attack Flow"
),
)
)
SHEETS = REPO / "src/content/sheets/pentest-workflow"
DOWNLOADS = REPO / "public/downloads/pentest-workflow"
DATA = REPO / "src/data/pentest-workflow-downloads.json"
UPDATED = "2026-08-29"
# Stable public filenames. Explicit names keep existing six sheet URLs intact.
SLUGS: dict[str, str] = {
"00 - Attack Flow Dashboard.md": "attack-flow-dashboard",
"01 - Stage 00 - Passive External Recon.md": "passive-external-recon",
"02 - Stage 01 - Recon and Host Discovery.md": "recon-and-host-discovery",
"03 - Stage 02 - Web Enumeration and Exploitation.md": "web-enumeration-and-exploitation",
"04 - Foothold Toolkit - File Transfers.md": "foothold-file-transfers",
"05 - Foothold Toolkit - Shells Payloads and Metasploit.md": "foothold-shells-payloads-metasploit",
"06 - Stage 03 - Service Enumeration.md": "service-enumeration",
"07 - Stage 04 - Active Directory Enumeration.md": "active-directory-enumeration",
"08 - Stage 05 - Kerberos Attacks.md": "kerberos-attacks",
"09 - Stage 06 - ACL and Object Abuse.md": "acl-and-object-abuse",
"10 - Stage 07 - ADCS and Certificate Abuse.md": "adcs-and-certificate-abuse",
"11 - Stage 08 - Password Attacks and Credential Hunting.md": "password-attacks-and-credential-hunting",
"12 - Stage 09 - Privilege Escalation.md": "privilege-escalation",
"13 - Stage 10 - Lateral Movement Pivoting and Loot.md": "lateral-movement-pivoting-and-loot",
"14 - Domain Trusts and Cross-Forest.md": "domain-trusts-and-cross-forest",
"15 - Stage 11 - Documentation and Reporting.md": "documentation-and-reporting",
"16 - Appendix - Worked Chains.md": "worked-chains",
"17 - Tool Index.md": "tool-index",
"HTB-Attack-Flow-Playbook.md": "htb-attack-flow-playbook",
"Companion Guides/Attack-Flow-Guide.md": "attack-flow-guide",
"Companion Guides/Most-Used-Commands.md": "most-used-commands",
}
# Working notes that live beside the sheets and must never be published.
# ``loot.md`` is the engagement ledger: live credentials, hashes and private
# keys. It was once listed in SLUGS and shipped to the public site and its
# search index; this list makes a repeat of that an error instead of a diff.
NEVER_PUBLISH: frozenset[str] = frozenset({"loot.md"})
# The banner the vault puts on a note that holds secrets, e.g.
# ``> [!warning]+ SENSITIVE — Live Credential Store``.
SENSITIVE_BANNER = re.compile(r"(?mi)^\s*>\s*\[![a-z]+\][+-]?\s*SENSITIVE\b")
# A complete PEM/OpenSSH private-key block: both markers with real key data
# between them. A bare ``-----BEGIN ... PRIVATE KEY-----`` on its own (a Google
# dork, a grep pattern, a truncated sample) is ordinary cheatsheet content.
PRIVATE_KEY_BLOCK = re.compile(
r"-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY)-----"
r"[A-Za-z0-9+/=\s]{200,}?"
r"-----END \1-----"
)
def publication_problem(rel: str, text: str) -> str | None:
"""Why this note must not be published, or None when it may be."""
if rel in NEVER_PUBLISH or Path(rel).name in NEVER_PUBLISH:
return "it is on the NEVER_PUBLISH list"
if SENSITIVE_BANNER.search(text):
return "it carries the vault's SENSITIVE banner"
if PRIVATE_KEY_BLOCK.search(text):
return "it contains a complete private-key block"
return None
DESCRIPTIONS: dict[str, str] = {
"attack-flow-dashboard": "The complete CPTS attack-flow index, stage map, decision points, and offline toolkit entry point.",
"attacking-common-modules-dashboard": "Focused CPTS reference cards for services, applications, privilege escalation, shells, TTY handling, and post-exploitation.",
"tool-index": "Stage-by-stage CPTS tooling index with locally mirrored, checksum-verified downloads.",
}
def yaml_scalar(frontmatter: str, key: str) -> str | None:
match = re.search(rf"(?m)^{re.escape(key)}:\s*(.+?)\s*$", frontmatter)
if not match:
return None
value = match.group(1).strip()
if value in {"", "null", "~"}:
return None
if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'"}:
value = value[1:-1]
return value
def yaml_list(frontmatter: str, *keys: str) -> list[str]:
for key in keys:
match = re.search(
rf"(?m)^{re.escape(key)}:[ \t]*\n((?:^[ \t]+-\s*[^\n]*(?:\n|$))*)",
frontmatter,
)
if not match:
continue
values: list[str] = []
for raw in re.findall(r"(?m)^[ \t]+-\s*(.+?)\s*$", match.group(1)):
value = raw.strip().strip('"\'')
if value and value not in values:
values.append(value)
if values:
return values
return []
def split_frontmatter(text: str) -> tuple[str, str]:
match = re.match(r"^---\s*\n(.*?)\n---\s*\n?", text, flags=re.S)
if not match:
return "", text
return match.group(1), text[match.end() :]
def display_title(rel: str, frontmatter: str, body: str) -> str:
title = yaml_scalar(frontmatter, "title")
if title:
return title
heading = re.search(r"(?m)^#\s+(.+?)\s*$", body)
if heading:
return heading.group(1).strip()
return re.sub(r"^\d+\s*-\s*", "", Path(rel).stem).strip()
def subcategory(rel: str) -> str:
if rel.startswith("Companion Guides/"):
return "Companion Guides"
if rel.startswith("General Pentest Cheatsheets/"):
return "General CPTS Cheatsheets"
return "CPTS Attack Flow"
def difficulty(rel: str, frontmatter: str) -> str:
raw = (yaml_scalar(frontmatter, "difficulty") or "").lower()
if raw in {"easy", "beginner"}:
return "beginner"
if raw in {"hard", "advanced"}:
return "advanced"
if any(
term in rel.lower()
for term in ("adcs", "acl", "kerberos", "trust", "lateral", "worked chains")
):
return "advanced"
return "intermediate"
def description(slug: str, title: str, rel: str) -> str:
if slug in DESCRIPTIONS:
return DESCRIPTIONS[slug]
if rel.startswith("General Pentest Cheatsheets/"):
return f"Updated CPTS field reference for {title.lower().rstrip('.')}."
if rel.startswith("Companion Guides/"):
return f"CPTS companion guide: {title.rstrip('.')} — copy-ready methodology and commands."
return f"CPTS attack-flow reference for {title.lower().rstrip('.')} in an authorised engagement."
def normalise_tag(value: str) -> str:
value = value.strip().lower().replace("&", "and")
value = re.sub(r"[^a-z0-9]+", "-", value).strip("-")
return value
def github_anchor(value: str) -> str:
value = unicodedata.normalize("NFKD", value)
value = "".join(ch for ch in value if not unicodedata.combining(ch))
value = value.lower().strip().replace(" ", "-")
value = re.sub(r"[^\w\-]", "", value)
return value
def attachment_triplet(filename: str, label: str | None = None) -> str:
if filename == "SHA256SUMS.txt":
if (DOWNLOADS / "SHA256SUMS.asc").is_file():
return "[SHA256SUMS](/downloads/pentest-workflow/SHA256SUMS) ([GPG signature](/downloads/pentest-workflow/SHA256SUMS.asc))"
return "[SHA256SUMS](/downloads/pentest-workflow/SHA256SUMS)"
encoded = quote(filename)
shown = label or filename
base = f"/downloads/pentest-workflow/{encoded}"
# Link a signature only when it has actually been published. Signing is a
# separate, manual step; a link to a file that is not there is a promise
# the release does not keep.
if (DOWNLOADS / f"{filename}.sha256.asc").is_file():
return (
f"[{shown}]({base})"
f" ([SHA-256]({base}.sha256) · [GPG signature]({base}.sha256.asc))"
)
return f"[{shown}]({base}) ([SHA-256]({base}.sha256))"
def build_link_lookup() -> dict[str, str]:
lookup: dict[str, str] = {}
for rel, slug in SLUGS.items():
rel_no_ext = rel[:-3]
lookup[rel_no_ext.lower()] = slug
lookup[Path(rel_no_ext).name.lower()] = slug
lookup[("02Cybersecurity/Cheatsheets/Pentest Attack Flow/" + rel_no_ext).lower()] = slug
return lookup
LINK_LOOKUP = build_link_lookup()
def rewrite_wikilinks(body: str) -> str:
pattern = re.compile(r"(!?)\[\[([^\]]+)\]\]")
def replace(match: re.Match[str]) -> str:
embedded = bool(match.group(1))
raw = match.group(2).strip()
target, label = (raw.split("|", 1) + [""])[:2]
target = target.strip()
label = label.strip()
target_path, anchor = (target.split("#", 1) + [""])[:2]
target_path = target_path.strip().replace("\\", "/")
basename = Path(target_path).name
if "/attachments/" in f"/{target_path.lower()}" or target_path.lower().startswith("attachments/"):
return attachment_triplet(basename, label or None)
key = target_path.removesuffix(".md").lower()
slug = LINK_LOOKUP.get(key) or LINK_LOOKUP.get(Path(key).name)
shown = label or Path(target_path).name or anchor or target
if slug:
suffix = f"#{github_anchor(anchor)}" if anchor else ""
return f"[{shown}](/sheets/pentest-workflow/{slug}{suffix})"
# Images outside the supplied attachment library cannot be rendered
# safely on the public site. Text wikilinks remain readable labels.
return shown if not embedded else f"`{shown}`"
return pattern.sub(replace, body)
def clean_body(body: str) -> str:
# Vault-only banner bootstrap. A malformed older companion note has a
# stray single ``d`` immediately before it; remove that typo as well.
body = re.sub(
r"(?ms)^d?\s*```dataviewjs\s*\n.*?^```\s*\n?",
"",
body,
)
body = re.sub(r"(?ms)^%%\s*$.*?^%%\s*$\n?", "", body)
body = rewrite_wikilinks(body)
body = body.replace("\r\n", "\n")
return body.lstrip("\n").rstrip() + "\n"
def frontmatter_for(rel: str, source_frontmatter: str, body: str, order: int) -> str:
slug = SLUGS[rel]
title = display_title(rel, source_frontmatter, body)
tools = yaml_list(source_frontmatter, "tools_used", "primary_tools")
tags = [normalise_tag(t) for t in yaml_list(source_frontmatter, "tags")]
tags = [t for t in tags if t]
for required in ("cpts", "pentest-workflow"):
if required not in tags:
tags.append(required)
updated = (
yaml_scalar(source_frontmatter, "last_updated")
or yaml_scalar(source_frontmatter, "updated")
or yaml_scalar(source_frontmatter, "date")
or UPDATED
)
if not re.fullmatch(r"\d{4}-\d{2}-\d{2}", updated):
updated = UPDATED
fields = [
"---",
f"title: {json.dumps(title, ensure_ascii=False)}",
f"description: {json.dumps(description(slug, title, rel), ensure_ascii=False)}",
"category: pentest-workflow",
f"subcategory: {json.dumps(subcategory(rel))}",
f"order: {order}",
f"tags: {json.dumps(tags, ensure_ascii=False)}",
f"tools: {json.dumps(tools, ensure_ascii=False)}",
f"difficulty: {difficulty(rel, source_frontmatter)}",
f"updated: {json.dumps(updated)}",
f"source: {json.dumps('vault:Pentest Attack Flow/' + rel, ensure_ascii=False)}",
"---",
"",
]
return "\n".join(fields)
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def human_size(size: int) -> str:
units = ("B", "KiB", "MiB", "GiB")
value = float(size)
for unit in units:
if value < 1024 or unit == units[-1]:
return f"{value:.0f} {unit}" if unit == "B" else f"{value:.1f} {unit}"
value /= 1024
raise AssertionError("unreachable")
ATTACHMENT_DIRS = ("attachments", "General Pentest Cheatsheets/attachments")
def read_source(rel: str) -> str:
"""A selected note, read without following links out of the vault folder."""
try:
return safe_source.read_text(SOURCE, SOURCE / rel)
except FileNotFoundError:
raise SystemExit(f"Missing requested sheet: {SOURCE / rel}")
except (safe_source.UnsafeSource, OSError) as err:
raise SystemExit(f"Unsafe source note, nothing written: {err}")
def source_attachment(name: str) -> Path | None:
"""The attachment called ``name`` in one of the two attachment folders.
Only a regular file that really lives there counts. A symbolic link — or a
real file behind a linked folder — is refused outright instead of skipped:
following it would publish whatever it points at on this machine.
"""
for folder in ATTACHMENT_DIRS:
candidate = SOURCE / folder / name
if not os.path.lexists(candidate):
continue
try:
return Path(safe_source.check_file(SOURCE, candidate))
except (safe_source.UnsafeSource, OSError) as err:
raise SystemExit(f"Unsafe attachment, nothing written: {err}")
return None
def attachment_names_from_sources(texts: dict[str, str]) -> list[str]:
names: set[str] = set()
for text in texts.values():
for raw in re.findall(r"!?\[\[([^\]]+)\]\]", text):
target = raw.split("|", 1)[0].split("#", 1)[0].strip().replace("\\", "/")
if "/attachments/" not in f"/{target.lower()}" and not target.lower().startswith("attachments/"):
continue
name = Path(target).name
if name in {"", ".", ".."}:
continue
if source_attachment(name) is not None:
names.add(name)
names.discard("SHA256SUMS.txt")
return sorted(names, key=str.lower)
def load_sources() -> dict[str, str]:
"""Read and vet every selected note before a single file is written."""
texts: dict[str, str] = {}
for rel in SLUGS:
text = read_source(rel)
problem = publication_problem(rel, text)
if problem:
raise SystemExit(
f"Refusing to publish {rel!r}: {problem}. Nothing was written. "
"Remove it from SLUGS or publish a separately redacted note."
)
texts[rel] = text
return texts
def sync_sheets(texts: dict[str, str]) -> None:
SHEETS.mkdir(parents=True, exist_ok=True)
for order, (rel, slug) in enumerate(SLUGS.items()):
source_frontmatter, raw_body = split_frontmatter(texts[rel])
body = clean_body(raw_body)
output = frontmatter_for(rel, source_frontmatter, body, order) + body
(SHEETS / f"{slug}.md").write_text(output, encoding="utf-8")
# A note that used to be published and is now refused must not linger.
for name in NEVER_PUBLISH:
stale = SHEETS / f"{Path(name).stem}.md"
if stale.exists():
stale.unlink()
print(f"Removed previously published sheet: {stale.relative_to(REPO)}")
def read_if_present(path: Path) -> bytes | None:
return path.read_bytes() if path.is_file() and not path.is_symlink() else None
def sync_downloads(names: list[str]) -> list[dict[str, object]]:
DOWNLOADS.mkdir(parents=True, exist_ok=True)
records: list[dict[str, object]] = []
manifest_lines: list[str] = []
keep: set[str] = {"SHA256SUMS"}
for name in names:
source = source_attachment(name)
if source is None:
raise SystemExit(f"Referenced attachment is missing: {name}")
destination = DOWNLOADS / name
safe_source.copy_file(SOURCE, source, destination)
digest = sha256(destination)
checksum_name = f"{name}.sha256"
checksum_text = f"{digest} {name}\n".encode("ascii")
checksum_path = DOWNLOADS / checksum_name
# A detached signature covers the checksum file byte for byte. It
# survives a re-sync only while that file is unchanged; a signature
# over an older checksum would be an invalid proof, so it goes.
if read_if_present(checksum_path) == checksum_text:
keep.add(f"{checksum_name}.asc")
checksum_path.write_bytes(checksum_text)
keep.update({name, checksum_name})
manifest_lines.append(f"{digest} {name}\n")
records.append(
{
"name": name,
"size": destination.stat().st_size,
"sizeLabel": human_size(destination.stat().st_size),
"sha256": digest,
"href": f"/downloads/pentest-workflow/{quote(name)}",
"checksumHref": f"/downloads/pentest-workflow/{quote(checksum_name)}",
"signatureHref": f"/downloads/pentest-workflow/{quote(checksum_name)}.asc",
}
)
manifest_text = "".join(manifest_lines).encode("ascii")
manifest_path = DOWNLOADS / "SHA256SUMS"
if read_if_present(manifest_path) == manifest_text:
keep.add("SHA256SUMS.asc")
manifest_path.write_bytes(manifest_text)
# This directory is wholly managed here, and everything in it is served.
# An attachment whose last reference left the vault has to leave the public
# tree with it, along with its checksum and signature; rewriting the
# catalogue alone would leave the old URL working.
for entry in sorted(DOWNLOADS.iterdir()):
if entry.name in keep:
continue
if entry.is_dir() and not entry.is_symlink():
raise SystemExit(f"Unexpected directory in the managed download folder: {entry}")
entry.unlink()
print(f"Removed withdrawn download: {entry.relative_to(REPO)}")
DATA.parent.mkdir(parents=True, exist_ok=True)
DATA.write_text(json.dumps(records, indent=2) + "\n", encoding="utf-8")
return records
def main() -> None:
if not SOURCE.is_dir():
raise SystemExit(f"Pentest workflow source does not exist: {SOURCE}")
overlap = sorted(rel for rel in SLUGS if rel in NEVER_PUBLISH or Path(rel).name in NEVER_PUBLISH)
if overlap:
raise SystemExit(f"SLUGS lists notes that must never be published: {', '.join(overlap)}")
# Everything is read and vetted first. Downloads go before sheets so the
# sheets can link the signatures that survived the sync.
texts = load_sources()
names = attachment_names_from_sources(texts)
records = sync_downloads(names)
sync_sheets(texts)
signed = sum(1 for r in records if (DOWNLOADS / f"{r['name']}.sha256.asc").is_file())
print(f"Synced {len(SLUGS)} sheets and {len(records)} referenced attachments.")
print(f"Downloads: {DOWNLOADS}")
print(f"Signatures present: {signed}/{len(records)} files, manifest: "
f"{'yes' if (DOWNLOADS / 'SHA256SUMS.asc').is_file() else 'no'}.")
print("Next: sign every *.sha256 file and SHA256SUMS with the user's OpenPGP key,")
print(" re-run this script so the sheets link the signatures,")
print(" then run `npm run verify:downloads`.")
if __name__ == "__main__":
main()