#!/usr/bin/env python3
"""Build the site's curated HackTricks collection from an upstream clone.
The selected trees are broad enough to be useful while excluding marketing,
privacy/attribution-evasion material, unfinished notes, and project metadata.
Markdown is adapted for Astro: GitBook-only wrappers and training banners are
removed, links are pinned or internalized, and images continue to load from the
upstream repository. The source is CC BY-NC 4.0; attribution is rendered by the
site on every generated page.
Usage: python3 scripts/sync-hacktricks.py /path/to/hacktricks-clone <sha>
"""
from __future__ import annotations
import json
import os
import posixpath
import re
import shutil
import sys
from pathlib import Path
from urllib.parse import quote, unquote
sys.path.insert(0, str(Path(__file__).resolve().parent))
import safe_source
REPO = Path(__file__).resolve().parent.parent
OUT = REPO / "src" / "content" / "hacktricks"
UPSTREAM = "https://github.com/HackTricks-wiki/hacktricks"
SOURCE = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else None
SHA = sys.argv[2] if len(sys.argv) > 2 else "master"
if SOURCE is None or not (SOURCE / "src").is_dir():
raise SystemExit("usage: sync-hacktricks.py <hacktricks-clone-dir> <sha>")
SOURCE_ROOT = SOURCE / "src"
# These five trees cover the material most useful in a field cheatsheet site.
# Keeping the selection explicit prevents a future upstream directory from
# silently becoming public here merely because it was added to the repository.
SECTIONS = {
"network-services-pentesting": "Network Services",
"pentesting-web": "Web Pentesting",
"windows-hardening": "Windows",
"linux-hardening": "Linux",
"mobile-pentesting": "Mobile",
}
SKIP_NAMES = {"license.md", "summary.md"}
def slugify(value: str) -> str:
value = value.strip().lower()
value = re.sub(r"[^a-z0-9]+", "-", value)
return re.sub(r"-+", "-", value).strip("-") or "x"
def quoted_blob(path: str) -> str:
return f"{UPSTREAM}/blob/{SHA}/{quote('src/' + path, safe='/')}"
def quoted_raw(path: str) -> str:
return (
"https://raw.githubusercontent.com/HackTricks-wiki/hacktricks/"
f"{SHA}/{quote('src/' + path, safe='/')}"
)
def markdown_files(root: Path) -> list[Path]:
"""Every .md under ``root`` that is a real file inside the clone.
The clone is third-party input. Git stores symbolic links and an ordinary
read follows them, so a linked page would copy whatever the link names on
this machine into the published collection. A link anywhere on the way to
a selected page stops the sync before the existing output is replaced.
"""
found: list[Path] = []
if not os.path.lexists(root):
return found # upstream dropped or renamed this section
try:
safe_source.check_dir(SOURCE, root)
# os.walk does not descend into linked directories; rglob may.
for current, dirs, files in os.walk(root):
dirs.sort()
for name in files:
if name.lower().endswith(".md"):
found.append(Path(safe_source.check_file(SOURCE, os.path.join(current, name))))
except (safe_source.UnsafeSource, OSError) as err:
raise SystemExit(f"sync-hacktricks: unsafe source, nothing written: {err}")
return sorted(found)
records: list[dict[str, object]] = []
route_by_source: dict[str, str] = {}
for section_slug, section_title in SECTIONS.items():
root = SOURCE_ROOT / section_slug
for source_file in markdown_files(root):
if source_file.name.lower() in SKIP_NAMES:
continue
source_path = source_file.relative_to(SOURCE_ROOT).as_posix()
inner = source_file.relative_to(root).as_posix()
parts = inner[:-3].split("/")
is_index = parts[-1].lower() == "readme"
if is_index:
parts[-1] = "overview"
output_parts = [slugify(part) for part in parts]
output_id = "/".join([section_slug, *output_parts])
route = f"/hacktricks/{output_id}"
route_by_source[source_path.lower()] = route
records.append(
{
"section_slug": section_slug,
"section_title": section_title,
"source_file": source_file,
"source_path": source_path,
"output_id": output_id,
"is_index": is_index,
}
)
MARKDOWN_LINK = re.compile(r"(!?)\[([^\]]*)\]\(([^)]+)\)")
ANGLE_MARKDOWN_LINK = re.compile(r"(!?)\[([^\]]*)\]\(<([^>]+)>\)")
HTML_ASSET = re.compile(r'(?P<prefix>\b(?:src|href)=["\'])(?P<url>[^"\']+)(?P<suffix>["\'])', re.I)
UPSTREAM_GITHUB = re.compile(
r"^https?://(?:www\.)?github\.com/(?:HackTricks-wiki/hacktricks|carlospolop/hacktricks)/"
r"(?:blob|tree|raw)/[^/]+/(?:src/)?(.*)$",
re.I,
)
def route_for_source(path: str, anchor: str = "") -> str | None:
normalized = posixpath.normpath(path).lstrip("./")
route = route_by_source.get(normalized.lower())
return route + anchor if route else None
def resolve_target(current_source: str, target: str, image: bool) -> str | None:
target = target.strip().strip("<>")
if not target or target.startswith("#"):
return None
anchor = ""
if "#" in target:
target, fragment = target.split("#", 1)
anchor = f"#{fragment}"
upstream_match = UPSTREAM_GITHUB.match(target)
if upstream_match:
path = unquote(upstream_match.group(1)).split("?", 1)[0]
if path.lower().endswith(".md"):
return route_for_source(path, anchor) or quoted_blob(path) + anchor
return quoted_raw(path) + anchor
if re.match(r"^(?:[a-z][a-z0-9+.-]*:|//|mailto:)", target, re.I):
return None
current_dir = posixpath.dirname(current_source)
raw_target = unquote(target)
# A bare directory reference (upstream {{#ref}} blocks often point at a
# whole section, not a file) means "that section's index page".
if raw_target.endswith("/"):
raw_target += "README.md"
resolved = posixpath.normpath(posixpath.join(current_dir, raw_target))
if resolved.startswith("../"):
return None
if resolved.lower().endswith(".md"):
return route_for_source(resolved, anchor) or quoted_blob(resolved) + anchor
if image or re.search(r"\.(?:png|jpe?g|gif|webp|svg|pdf|zip|txt|py|sh|ps1)$", resolved, re.I):
return quoted_raw(resolved) + anchor
return None
# Upstream has at least one typo'd close tag ({{/ref}} instead of
# {{#endref}} — see ssti-server-side-template-injection/README.md around its
# LESS section). Accepting that variant here matters: with only the correct
# spelling recognized, the non-greedy match instead runs on to the *next*
# real {{#endref}}, silently swallowing every heading and paragraph between
# the two into a single garbled link. MAX_BLOCK_LINES below is the backstop
# for whatever variant of this a future upstream edit introduces.
REF_BLOCK = re.compile(r"^[ \t]*\{\{#ref\}\}[ \t]*\n(.*?)\n[ \t]*\{\{(?:#end|/)ref\}\}[ \t]*$", re.M | re.S)
FILE_BLOCK = re.compile(r"^[ \t]*\{\{#file\}\}[ \t]*\n(.*?)\n[ \t]*\{\{(?:#end|/)file\}\}[ \t]*$", re.M | re.S | re.I)
MAX_BLOCK_LINES = 8
CONTENT_REF_BLOCK = re.compile(
r'^[ \t]*\{%\s*content-ref\s+url=["\']([^"\']+)["\'][^%]*%\}[ \t]*\n(.*?)\n[ \t]*\{%\s*endcontent-ref\s*%\}[ \t]*$',
re.M | re.S | re.I,
)
WRAPPING_LINK = re.compile(r"^\[([^\]]*)\]\(([^)]+)\)$")
def humanize_ref_label(path: str) -> str:
""""protections/no-new-privileges.md" -> "No New Privileges" — same
dash-to-title-case fallback page_title() already uses for a page's own
title, so a ref link reads like a page name rather than a bare path."""
stem = path.rstrip("/").rsplit("/", 1)[-1]
stem = re.sub(r"\.md$", "", stem, flags=re.I)
return stem.replace("-", " ").replace("_", " ").title() or path
def linkify_ref_blocks(body: str) -> str:
"""
{{#ref}}/{{#file}} wrap a bare relative path with no markdown link syntax
at all — upstream renders these as GitBook card links. Deleting the
wrapper (as this script used to) left the bare path behind as plain,
unclickable text throughout every synced page. Turning each path into a
real `[label](target)` link here lets rewrite_links() below resolve it
to the right on-site route exactly like an ordinary inline link.
"""
def ref_repl(match: "re.Match[str]") -> str:
lines = [line.strip() for line in match.group(1).splitlines() if line.strip()]
# A legitimate {{#ref}} block is a short list of bare paths. Anything
# longer, or containing a heading, is a sign the regex ran past its
# real closing tag onto unrelated content — leave it untouched rather
# than turn a chunk of the page into garbage nested links.
if not lines or len(lines) > MAX_BLOCK_LINES or any(line.startswith("#") for line in lines):
return match.group(0)
# A raw filename can contain spaces or literal parentheses (seen in
# an upstream PDF name); MARKDOWN_LINK's `([^)]+)` target group can't
# tell those apart from the link's own closing paren, so quote the
# target the same way quoted_blob()/quoted_raw() already do.
return "\n\n".join(
f"[{humanize_ref_label(line)}]({quote(line, safe='/')})" for line in lines
)
body = REF_BLOCK.sub(ref_repl, body)
body = FILE_BLOCK.sub(ref_repl, body)
def content_ref_repl(match: "re.Match[str]") -> str:
target = match.group(1).strip()
label = match.group(2).strip()
# The label is sometimes already `[text](target)` — unwrap it rather
# than nesting a link inside a link.
wrapped = WRAPPING_LINK.match(label)
if wrapped:
label = wrapped.group(1)
label = label or humanize_ref_label(target)
return f"[{label}]({target})"
return CONTENT_REF_BLOCK.sub(content_ref_repl, body)
def clean_gitbook(body: str) -> str:
body = linkify_ref_blocks(body)
# The banner is repeated at the top and bottom of most upstream pages.
body = re.sub(r"^\s*\{\{#include\s+[^}]*banners/hacktricks-training\.md\}\}\s*$", "", body, flags=re.M | re.I)
# Other mdBook/GitBook includes cannot be expanded safely without copying
# arbitrary non-selected files. Leave a source-facing note instead.
body = re.sub(
r"^\s*\{\{#include\s+([^}]+)\}\}\s*$",
r"> Included upstream fragment: `\1` (see source link).",
body,
flags=re.M,
)
# Newer mdBook-style tab blocks use double braces instead of Liquid.
body = re.sub(
r'^\s*\{\{#tab\s+name=["\']([^"\']+)["\'][^}]*\}\}\s*$',
r"### \1",
body,
flags=re.M | re.I,
)
body = re.sub(r"^\s*\{\{#(?:end)?tabs?[^}]*\}\}\s*$", "", body, flags=re.M | re.I)
# Keep the useful content inside GitBook wrappers while dropping syntax
# Astro would otherwise display as literal template tags.
body = re.sub(r"^\s*\{%\s*tab\s+title=[\"']([^\"']+)[\"'][^%]*%\}\s*$", r"### \1", body, flags=re.M | re.I)
body = re.sub(r"^\s*\{%\s*(?:end)?(?:hint|tabs|tab|code|endcode|embed)[^%]*%\}\s*$", "", body, flags=re.M | re.I)
body = re.sub(r"\n{4,}", "\n\n\n", body)
return body.strip() + "\n"
def rewrite_links(source_path: str, body: str) -> str:
def markdown_replacement(match: re.Match[str]) -> str:
bang, label, target = match.groups()
replacement = resolve_target(source_path, target, image=bool(bang))
if replacement is None:
return match.group(0)
return f"{bang}[{label}]({replacement})"
body = ANGLE_MARKDOWN_LINK.sub(markdown_replacement, body)
body = MARKDOWN_LINK.sub(markdown_replacement, body)
def html_replacement(match: re.Match[str]) -> str:
target = match.group("url")
replacement = resolve_target(source_path, target, image=True)
if replacement is None:
return match.group(0)
return f'{match.group("prefix")}{replacement}{match.group("suffix")}'
return HTML_ASSET.sub(html_replacement, body)
SUPPORTED_FENCES = {
"bash", "batch", "c", "cpp", "csharp", "css", "diff", "dockerfile",
"go", "graphql", "html", "http", "ini", "java", "javascript", "json",
"jsx", "kotlin", "lua", "makefile", "markdown", "nginx", "perl", "php",
"plaintext", "powershell", "python", "regex", "ruby", "rust", "sql",
"swift", "text", "toml", "tsx", "typescript", "xml", "yaml",
}
# A CommonMark fence is 3+ backticks. Longer runs exist upstream specifically
# so the block can contain a literal ``` in its own content (e.g. an example
# that itself shows markdown syntax) without that line closing the block
# early — see mssql-injection.md, which wraps a ```sql-quoting example in a
# 4-backtick fence. A closer must be a bare run of backticks at least as long
# as its opener; anything shorter, or followed by other text, is just content.
CANDIDATE_FENCE_LINE = re.compile(r"^(`{3,})([^`]*)$")
BARE_FENCE_LINE = re.compile(r"^(`{3,})\s*$")
def normalize_code_fences(body: str) -> str:
"""
Drop GitBook filename annotations and unsupported Shiki language ids —
on OPENING fences only.
A closing fence (bare ```) is syntactically identical to an opening
fence with an empty info string, and a naive regex substitution matches
both alike. An earlier version of this function treated every match the
same way: empty language -> not in SUPPORTED_FENCES -> default to
"text". That silently turned every *closing* ``` into ```text, which a
markdown parser reads as a new OPENING fence rather than a close. The
real closer never arrives, so the block swallows everything until the
next accidental ```text, and every fence after that is shifted the same
way for the rest of the file. Tracking open/close state (and the
opening fence's exact backtick count, for the 4-backtick case above) is
what CommonMark expects and what Astro's renderer needs.
"""
aliases = {
"bat": "batch", "cmd": "batch", "console": "text", "cs": "csharp",
"js": "javascript", "ps1": "powershell", "py": "python", "sh": "bash",
"shell": "bash", "yml": "yaml",
}
def opening_replacement(ticks: str, info: str) -> str:
raw = info.strip()
head = raw.split(":", 1)[0].strip() if raw else ""
tokens = head.split()
language = tokens[0].lower() if tokens else ""
language = aliases.get(language, language)
if language not in SUPPORTED_FENCES:
language = "text"
return f"{ticks}{language}" if language else ticks
lines = body.split("\n")
in_fence = False
fence_len = 0
for i, line in enumerate(lines):
if in_fence:
# Only a bare run of at least as many backticks as the opener
# closes a fence (CommonMark); anything shorter, or followed by
# other text, is fence *content* and must be left untouched.
bare = BARE_FENCE_LINE.match(line)
if bare and len(bare.group(1)) >= fence_len:
lines[i] = "`" * fence_len
in_fence = False
continue
match = CANDIDATE_FENCE_LINE.match(line)
if match:
fence_len = len(match.group(1))
lines[i] = opening_replacement(match.group(1), match.group(2))
in_fence = True
return "\n".join(lines)
def page_title(body: str, fallback: str) -> str:
match = re.search(r"^\s*#\s+(.+?)\s*$", body, re.M)
if not match:
return fallback
title = re.sub(r"[*_`]+", "", match.group(1)).strip()
return title or fallback
if OUT.exists():
shutil.rmtree(OUT)
OUT.mkdir(parents=True)
for record in records:
source_file = record["source_file"]
assert isinstance(source_file, Path)
source_path = str(record["source_path"])
raw = safe_source.read_text(SOURCE, source_file, errors="replace")
body = normalize_code_fences(rewrite_links(source_path, clean_gitbook(raw)))
fallback = source_file.parent.name if source_file.name.lower() == "readme.md" else source_file.stem
title = page_title(raw, fallback.replace("-", " ").title())
frontmatter = {
"title": title,
"section": record["section_title"],
"sectionSlug": record["section_slug"],
"sourcePath": f"src/{source_path}",
"sourceUrl": quoted_blob(source_path),
"sha": SHA,
"isIndex": bool(record["is_index"]),
"modified": True,
"license": "CC-BY-NC-4.0",
}
output_path = OUT / f'{record["output_id"]}.md'
output_path.parent.mkdir(parents=True, exist_ok=True)
lines = ["---"]
for key, value in frontmatter.items():
lines.append(f"{key}: {json.dumps(value, ensure_ascii=False)}")
lines.extend(["---", "", body])
output_path.write_text("\n".join(lines), encoding="utf-8")
print(f"synced {len(records)} HackTricks pages from {SHA}")