406 lines
12 KiB
Python
406 lines
12 KiB
Python
|
|
#!/usr/bin/env python3
|
|
"""Generate explicitly synthetic CrackLab result packages for integration tests.
|
|
|
|
This script does not run Hashcat, access the production database, or import
|
|
results. Every generated package represents a simulated exhausted run with
|
|
zero recovered credentials.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import sys
|
|
import tempfile
|
|
import zipfile
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
|
|
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
|
|
|
if str(PROJECT_ROOT) not in sys.path:
|
|
sys.path.insert(0, str(PROJECT_ROOT))
|
|
|
|
from cracklab.client.result_package import ( # noqa: E402
|
|
create_result_package,
|
|
)
|
|
|
|
|
|
JOB_ID_RE = re.compile(r"^JOB-[0-9A-F]{12}$")
|
|
EXPECTED_JOB_FILES = {"job.json", "manifest.json"}
|
|
MANIFEST_FORMAT_VERSION = 1
|
|
|
|
|
|
class SimulationError(Exception):
|
|
"""Invalid input package or synthetic result generation failure."""
|
|
|
|
|
|
def utc_now() -> str:
|
|
return (
|
|
datetime.now(timezone.utc)
|
|
.isoformat(timespec="seconds")
|
|
.replace("+00:00", "Z")
|
|
)
|
|
|
|
|
|
def sha256_bytes(data: bytes) -> str:
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def read_json(data: bytes, description: str) -> dict[str, Any]:
|
|
try:
|
|
value = json.loads(data.decode("utf-8"))
|
|
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
|
raise SimulationError(
|
|
f"{description}: invalid UTF-8 JSON: {exc}"
|
|
) from exc
|
|
|
|
if not isinstance(value, dict):
|
|
raise SimulationError(
|
|
f"{description}: JSON root must be an object"
|
|
)
|
|
|
|
return value
|
|
|
|
|
|
def validate_job_package(
|
|
package_path: Path,
|
|
) -> tuple[dict[str, Any], int]:
|
|
if not zipfile.is_zipfile(package_path):
|
|
raise SimulationError("Not a ZIP archive")
|
|
|
|
with zipfile.ZipFile(package_path, "r") as archive:
|
|
infos = archive.infolist()
|
|
names = [info.filename for info in infos]
|
|
|
|
if len(names) != len(set(names)):
|
|
raise SimulationError("ZIP contains duplicate file names")
|
|
|
|
if (
|
|
len(names) != 3
|
|
or "job.json" not in names
|
|
or "manifest.json" not in names
|
|
or sum(
|
|
name.startswith("hashes/") and name.endswith(".22000")
|
|
for name in names
|
|
) != 1
|
|
):
|
|
raise SimulationError(
|
|
"Unexpected ZIP layout; expected job.json, manifest.json "
|
|
"and hashes/<Job ID>.22000"
|
|
)
|
|
|
|
if any(
|
|
info.is_dir()
|
|
or Path(info.filename).is_absolute()
|
|
or ".." in Path(info.filename).parts
|
|
for info in infos
|
|
):
|
|
raise SimulationError("Unsafe ZIP entry")
|
|
|
|
job = read_json(
|
|
archive.read("job.json"),
|
|
"job.json",
|
|
)
|
|
manifest = read_json(
|
|
archive.read("manifest.json"),
|
|
"manifest.json",
|
|
)
|
|
|
|
job_id = job.get("job_id")
|
|
|
|
if not isinstance(job_id, str) or not JOB_ID_RE.fullmatch(job_id):
|
|
raise SimulationError("Invalid Job ID in job.json")
|
|
|
|
hash_name = job.get("hash_file_name")
|
|
expected_hash_path = f"hashes/{job_id}.22000"
|
|
|
|
if hash_name != f"{job_id}.22000":
|
|
raise SimulationError("hash_file_name does not match Job ID")
|
|
|
|
if expected_hash_path not in names:
|
|
raise SimulationError("Hash file is missing")
|
|
|
|
hash_bytes = archive.read(expected_hash_path)
|
|
hash_sha256 = sha256_bytes(hash_bytes)
|
|
|
|
if job.get("hash_file_sha256") != hash_sha256:
|
|
raise SimulationError("Hash file SHA-256 mismatch")
|
|
|
|
hash_lines = hash_bytes.decode("utf-8").splitlines()
|
|
hash_count = job.get("hash_count")
|
|
handshake_count = job.get("handshake_count")
|
|
steps = job.get("steps")
|
|
|
|
if (
|
|
isinstance(hash_count, bool)
|
|
or not isinstance(hash_count, int)
|
|
or hash_count != len(hash_lines)
|
|
or any(not line.strip() for line in hash_lines)
|
|
or len(set(hash_lines)) != len(hash_lines)
|
|
):
|
|
raise SimulationError("Invalid hash_count or hash file")
|
|
|
|
if (
|
|
isinstance(handshake_count, bool)
|
|
or not isinstance(handshake_count, int)
|
|
or not isinstance(job.get("handshakes"), list)
|
|
or len(job["handshakes"]) != handshake_count
|
|
):
|
|
raise SimulationError("Invalid handshake_count")
|
|
|
|
if (
|
|
not isinstance(steps, list)
|
|
or not steps
|
|
or len(steps) != job.get("step_count")
|
|
):
|
|
raise SimulationError("Invalid step_count or steps")
|
|
|
|
if manifest.get("format_version") != MANIFEST_FORMAT_VERSION:
|
|
raise SimulationError("Unsupported manifest format_version")
|
|
|
|
if manifest.get("job_id") != job_id:
|
|
raise SimulationError("Manifest Job ID mismatch")
|
|
|
|
manifest_files = manifest.get("files")
|
|
if not isinstance(manifest_files, list):
|
|
raise SimulationError("Manifest files must be a list")
|
|
|
|
manifest_by_path = {
|
|
item.get("path"): item
|
|
for item in manifest_files
|
|
if isinstance(item, dict)
|
|
}
|
|
|
|
if len(manifest_by_path) != len(manifest_files):
|
|
raise SimulationError("Invalid or duplicate manifest entries")
|
|
|
|
for name in ("job.json", expected_hash_path):
|
|
entry = manifest_by_path.get(name)
|
|
if not isinstance(entry, dict):
|
|
raise SimulationError(
|
|
f"Manifest entry missing for {name}"
|
|
)
|
|
|
|
content = archive.read(name)
|
|
|
|
if entry.get("size") != len(content):
|
|
raise SimulationError(
|
|
f"Manifest size mismatch for {name}"
|
|
)
|
|
|
|
if entry.get("sha256") != sha256_bytes(content):
|
|
raise SimulationError(
|
|
f"Manifest SHA-256 mismatch for {name}"
|
|
)
|
|
|
|
return job, len(hash_lines)
|
|
|
|
|
|
def make_step_states(job: dict[str, Any]) -> list[dict[str, Any]]:
|
|
"""Create synthetic completed steps without claiming a real run."""
|
|
states: list[dict[str, Any]] = []
|
|
|
|
for step in job["steps"]:
|
|
started_at = utc_now()
|
|
completed_at = utc_now()
|
|
|
|
states.append(
|
|
{
|
|
"step_no": step["step_no"],
|
|
"step_id": step["step_id"],
|
|
"session_name": step["session_name"],
|
|
"status": "COMPLETED",
|
|
"started_at": started_at,
|
|
"completed_at": completed_at,
|
|
"exit_code": 1,
|
|
"restore_seen": False,
|
|
"error": None,
|
|
}
|
|
)
|
|
|
|
return states
|
|
|
|
|
|
def verify_result_package(
|
|
result_path: Path,
|
|
expected_job: dict[str, Any],
|
|
) -> None:
|
|
with zipfile.ZipFile(result_path, "r") as archive:
|
|
names = archive.namelist()
|
|
|
|
if len(names) != 2 or set(names) != {
|
|
"result.json",
|
|
"hashcat-show.txt",
|
|
}:
|
|
raise SimulationError(
|
|
f"Unexpected result ZIP contents: {names}"
|
|
)
|
|
|
|
result_bytes = archive.read("result.json")
|
|
result = read_json(result_bytes, "result.json")
|
|
show_bytes = archive.read("hashcat-show.txt")
|
|
|
|
if show_bytes.strip():
|
|
raise SimulationError(
|
|
"Synthetic show file must contain no credentials"
|
|
)
|
|
|
|
supplied_sha256 = result.get("result_sha256")
|
|
unsigned_result = dict(result)
|
|
unsigned_result.pop("result_sha256", None)
|
|
|
|
canonical_bytes = (
|
|
json.dumps(
|
|
unsigned_result,
|
|
ensure_ascii=False,
|
|
indent=2,
|
|
)
|
|
+ "\n"
|
|
).encode("utf-8")
|
|
|
|
if supplied_sha256 != sha256_bytes(canonical_bytes):
|
|
raise SimulationError("result.json SHA-256 mismatch")
|
|
|
|
if result.get("job_id") != expected_job["job_id"]:
|
|
raise SimulationError("Result Job ID mismatch")
|
|
|
|
if result.get("status") != "COMPLETED":
|
|
raise SimulationError("Result status is not COMPLETED")
|
|
|
|
if result.get("hash_file_sha256") != expected_job["hash_file_sha256"]:
|
|
raise SimulationError("Result hash SHA-256 mismatch")
|
|
|
|
if result.get("hash_count") != expected_job["hash_count"]:
|
|
raise SimulationError("Result hash_count mismatch")
|
|
|
|
if result.get("method") != {
|
|
"id": expected_job["method_id"],
|
|
"version": expected_job["method_version"],
|
|
}:
|
|
raise SimulationError("Result method mismatch")
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(
|
|
description=(
|
|
"Generate synthetic CrackLab result ZIPs for existing exported "
|
|
"jobs. Does not run Hashcat or import results."
|
|
)
|
|
)
|
|
parser.add_argument(
|
|
"jobs_dir",
|
|
type=Path,
|
|
help="Directory containing exported JOB-*.zip packages",
|
|
)
|
|
parser.add_argument(
|
|
"outbox",
|
|
type=Path,
|
|
help="Separate output directory for synthetic RESULT-*.zip files",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
jobs_dir = args.jobs_dir.expanduser().resolve()
|
|
outbox = args.outbox.expanduser().resolve()
|
|
|
|
if not jobs_dir.is_dir():
|
|
parser.error(f"Jobs directory does not exist: {jobs_dir}")
|
|
|
|
if jobs_dir == outbox or jobs_dir in outbox.parents:
|
|
parser.error(
|
|
"Output must be a separate directory outside the jobs directory"
|
|
)
|
|
|
|
packages = sorted(jobs_dir.glob("JOB-*.zip"))
|
|
|
|
if not packages:
|
|
parser.error(f"No JOB-*.zip packages found in {jobs_dir}")
|
|
|
|
outbox.mkdir(parents=True, exist_ok=True)
|
|
|
|
# Validate every input and every destination before generating anything.
|
|
validated: list[tuple[Path, dict[str, Any], int]] = []
|
|
seen_job_ids: set[str] = set()
|
|
|
|
for package_path in packages:
|
|
try:
|
|
job, unique_hash_count = validate_job_package(package_path)
|
|
except (SimulationError, OSError, UnicodeDecodeError, zipfile.BadZipFile) as exc:
|
|
print(f"ERROR {package_path.name}: {exc}", file=sys.stderr)
|
|
return 1
|
|
|
|
job_id = job["job_id"]
|
|
|
|
if job_id in seen_job_ids:
|
|
print(f"ERROR duplicate Job ID: {job_id}", file=sys.stderr)
|
|
return 1
|
|
|
|
seen_job_ids.add(job_id)
|
|
|
|
destination = outbox / f"RESULT-{job_id}.zip"
|
|
if destination.exists():
|
|
print(
|
|
f"ERROR output already exists; refusing to overwrite: "
|
|
f"{destination}",
|
|
file=sys.stderr,
|
|
)
|
|
return 1
|
|
|
|
validated.append((package_path, job, unique_hash_count))
|
|
|
|
print("SYNTHETIC TEST DATA — no Hashcat run was performed.")
|
|
print("No production database is opened and no result is imported.")
|
|
print(f"Jobs: {len(validated)}")
|
|
print()
|
|
|
|
with tempfile.TemporaryDirectory(prefix="cracklab-sim-") as temporary:
|
|
temporary_root = Path(temporary)
|
|
|
|
for package_path, job, unique_hash_count in validated:
|
|
job_id = job["job_id"]
|
|
work_dir = temporary_root / job_id
|
|
results_dir = work_dir / "results"
|
|
results_dir.mkdir(parents=True)
|
|
|
|
# Empty output intentionally represents zero recovered passwords.
|
|
(results_dir / "hashcat-show.txt").write_bytes(b"")
|
|
|
|
try:
|
|
result_path = create_result_package(
|
|
work_dir,
|
|
job,
|
|
make_step_states(job),
|
|
outbox,
|
|
)
|
|
verify_result_package(result_path, job)
|
|
except Exception as exc:
|
|
print(
|
|
f"ERROR {job_id}: {type(exc).__name__}: {exc}",
|
|
file=sys.stderr,
|
|
)
|
|
return 1
|
|
|
|
print(
|
|
f"OK {job_id}: "
|
|
f"unique_hashes={unique_hash_count}, "
|
|
f"handshakes={job['handshake_count']}, "
|
|
f"steps={job['step_count']}, "
|
|
"recovered=0"
|
|
)
|
|
print(f" {result_path}")
|
|
|
|
print()
|
|
print(f"Created {len(validated)} synthetic result package(s).")
|
|
print("Review them before importing through the normal CrackLab workflow.")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|
|
|