Update public source

This commit is contained in:
2026-10-06 21:08:12 +03:00
commit f231cc5b1f
102 changed files with 48249 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
"""WiFi GPS Mapper CrackLab Windows client."""
+793
View File
@@ -0,0 +1,793 @@
from __future__ import annotations
import json
import logging
import traceback
from pathlib import Path
from typing import Any
from .config import ClientConfig, load_config
from .hashcat import (
HashcatError,
run_show,
run_step,
)
from .job_package import (
ImportedJob,
JobPackageError,
JobPackageService,
)
from .client_logging import (
configure_job_logging,
configure_logging,
)
from .paths import ClientPaths
from .result_package import (
ResultPackageError,
create_result_package,
)
from .state import (
JOB_STATUS_COMPLETED,
JOB_STATUS_FAILED,
JOB_STATUS_PARTIAL,
JOB_STATUS_RUNNING,
STEP_STATUS_COMPLETED,
STEP_STATUS_FAILED,
STEP_STATUS_PARTIAL,
STEP_STATUS_RUNNING,
StateError,
get_step_state,
initialize_state,
load_state,
update_job_state,
update_step_state,
)
class ClientError(RuntimeError):
pass
class CrackLabClient:
def __init__(
self,
script_dir: Path,
) -> None:
self.script_dir = script_dir.resolve()
self.config: ClientConfig = load_config(
self.script_dir
)
self.config.potfile_path.parent.mkdir(
parents=True,
exist_ok=True,
)
self.paths = ClientPaths.from_root(
self.config.client_root
)
self.paths.initialize()
self.logger = configure_logging(
self.paths.logs / "client.log"
)
self.package_service = JobPackageService(
self.paths
)
self.logger.info(
"CrackLab client initialized"
)
self.logger.info(
"Client root: %s",
self.paths.root,
)
self.logger.info(
"Hashcat: %s",
self.config.hashcat_exe,
)
self.logger.info(
"Potfile: %s",
self.config.potfile_path,
)
self.logger.info(
"poll_seconds=%s max_parallel_jobs=%s",
self.config.poll_seconds,
self.config.max_parallel_jobs,
)
def import_jobs(self) -> list[ImportedJob]:
imported: list[ImportedJob] = []
packages = sorted(
self.paths.inbox.glob(
"JOB-*.zip"
)
)
if not packages:
self.logger.info(
"Inbox is empty."
)
return imported
for package in packages:
try:
self.logger.info(
"Importing Job package: %s",
package.name,
)
item = (
self.package_service
.import_package(package)
)
imported.append(item)
if item.idempotent:
self.logger.info(
"Job package already imported: "
"%s",
item.job_id,
)
else:
self.logger.info(
"Job imported: %s",
item.job_id,
)
except JobPackageError as exc:
self.logger.error(
"Job package rejected: %s: %s",
package.name,
exc,
)
except Exception:
self.logger.exception(
"Unexpected error importing %s",
package.name,
)
return imported
def _load_job(
self,
job_dir: Path,
) -> dict[str, Any]:
path = job_dir / "job.json"
try:
data = json.loads(
path.read_text(
encoding="utf-8"
)
)
except (OSError, json.JSONDecodeError) as exc:
raise ClientError(
f"Failed to read {path}: {exc}"
) from exc
if not isinstance(data, dict):
raise ClientError(
f"Invalid Job JSON: {path}"
)
return data
def _ensure_state(
self,
job_dir: Path,
job: dict[str, Any],
) -> dict[str, Any]:
path = job_dir / "state" / "client_state.json"
if not path.is_file():
self.logger.info(
"%s: creating client state",
job["job_id"],
)
return initialize_state(
job_dir,
job,
)
try:
state = load_state(
job_dir
)
except StateError:
self.logger.warning(
"%s: invalid state; rebuilding state",
job["job_id"],
)
return initialize_state(
job_dir,
job,
)
if state.get("job_id") != job["job_id"]:
raise ClientError(
"State job_id does not match job.json."
)
expected_steps = {
str(step["step_no"])
for step in job["steps"]
}
actual_steps = state.get(
"steps",
{},
)
if not isinstance(actual_steps, dict):
self.logger.warning(
"%s: state has invalid steps; rebuilding",
job["job_id"],
)
return initialize_state(
job_dir,
job,
)
if set(actual_steps) != expected_steps:
self.logger.warning(
"%s: state steps do not match "
"job.json; rebuilding",
job["job_id"],
)
return initialize_state(
job_dir,
job,
)
return state
def _step_result(
self,
job_dir: Path,
step: dict[str, Any],
) -> dict[str, Any]:
state = get_step_state(
job_dir,
step["step_no"],
)
return {
"step_no": step["step_no"],
"step_id": step["step_id"],
"session_name": step["session_name"],
"status": state["status"],
"started_at": state.get(
"started_at"
),
"completed_at": state.get(
"completed_at"
),
"exit_code": state.get(
"exit_code"
),
"restore_seen": bool(
state.get("restore_seen", False)
),
"error": state.get("error"),
}
def _run_step(
self,
job_dir: Path,
job: dict[str, Any],
step: dict[str, Any],
job_logger: logging.Logger,
) -> bool:
step_no = step["step_no"]
state = get_step_state(
job_dir,
step_no,
)
if (
state.get("status")
== STEP_STATUS_COMPLETED
):
job_logger.info(
"Step %s already COMPLETED; skipping.",
step_no,
)
return True
restore_file = (
job_dir
/ "state"
/ f"step-{step_no:03d}.restore"
)
restore_seen = restore_file.is_file()
mode = (
"RESTORE"
if restore_seen
else "START"
)
job_logger.info(
"Step %s (%s) starting: %s "
"session=%s",
step_no,
step["step_id"],
mode,
step["session_name"],
)
if restore_seen:
job_logger.warning(
"Step %s has restore file; "
"resuming existing Hashcat session.",
step_no,
)
update_step_state(
job_dir,
step_no,
STEP_STATUS_RUNNING,
restore_seen=restore_seen,
started=True,
)
log_path = (
job_dir
/ "logs"
/ f"step-{step_no:03d}.log"
)
try:
result = run_step(
self.config,
job_dir,
job,
step,
log_path,
restore=restore_seen,
)
except HashcatError as exc:
current_restore = (
restore_file.is_file()
)
update_step_state(
job_dir,
step_no,
(
STEP_STATUS_PARTIAL
if current_restore
else STEP_STATUS_FAILED
),
exit_code=exc.exit_code,
restore_seen=current_restore,
error=str(exc),
completed=True,
)
if current_restore:
job_logger.warning(
"Step %s interrupted/partial: %s",
step_no,
exc,
)
else:
job_logger.error(
"Step %s failed: %s",
step_no,
exc,
)
return False
except Exception as exc:
update_step_state(
job_dir,
step_no,
STEP_STATUS_FAILED,
restore_seen=restore_file.is_file(),
error=str(exc),
completed=True,
)
job_logger.exception(
"Unexpected Step %s error.",
step_no,
)
return False
if result.restore_seen:
update_step_state(
job_dir,
step_no,
STEP_STATUS_PARTIAL,
exit_code=result.exit_code,
restore_seen=True,
error=(
"Hashcat finished while "
"restore file still exists."
),
completed=True,
)
job_logger.warning(
"Step %s remains PARTIAL: "
"restore file exists after Hashcat "
"exit=%s.",
step_no,
result.exit_code,
)
return False
if result.exit_code not in (0, 1):
update_step_state(
job_dir,
step_no,
STEP_STATUS_FAILED,
exit_code=result.exit_code,
restore_seen=False,
error=(
f"Hashcat exited with "
f"code {result.exit_code}."
),
completed=True,
)
job_logger.error(
"Step %s failed: Hashcat exit=%s.",
step_no,
result.exit_code,
)
return False
marker = (
job_dir
/ "state"
/ f"step-{step_no:03d}.completed"
)
marker.write_text(
"COMPLETED\n",
encoding="utf-8",
)
update_step_state(
job_dir,
step_no,
STEP_STATUS_COMPLETED,
exit_code=result.exit_code,
restore_seen=False,
error=None,
completed=True,
)
job_logger.info(
"Step %s COMPLETED.",
step_no,
)
return True
def run_job(
self,
job_dir: Path,
) -> bool:
job = self._load_job(
job_dir
)
job_id = job["job_id"]
job_logger = configure_job_logging(
job_dir / "logs" / "client.log",
job_id,
)
job_logger.info(
"Job processing started."
)
job_logger.info(
"method=%s version=%s hashes=%s "
"handshakes=%s steps=%s",
job["method_id"],
job["method_version"],
job["hash_count"],
job["handshake_count"],
job["step_count"],
)
try:
state = self._ensure_state(
job_dir,
job,
)
if (
state.get("status")
== JOB_STATUS_COMPLETED
):
try:
archived_package = (
self.package_service.archive_job(
job_dir.name
)
)
except JobPackageError as exc:
job_logger.error(
"Job package archival failed: %s",
exc,
)
return False
except Exception:
job_logger.exception(
"Unexpected Job package archival failure."
)
return False
job_logger.info(
"Job already COMPLETED; "
"Job package finalized: %s",
archived_package,
)
return True
update_job_state(
job_dir,
JOB_STATUS_RUNNING,
)
all_completed = True
for step in job["steps"]:
if not self._run_step(
job_dir,
job,
step,
job_logger,
):
all_completed = False
break
if not all_completed:
update_job_state(
job_dir,
JOB_STATUS_PARTIAL,
)
job_logger.warning(
"Job remains PARTIAL."
)
return False
job_logger.info(
"All steps completed; running Hashcat --show."
)
show_path = (
job_dir
/ "results"
/ "hashcat-show.txt"
)
show_log = (
job_dir
/ "logs"
/ "show.log"
)
try:
show_output = run_show(
self.config,
job_dir,
job,
show_path,
show_log,
)
job_logger.info(
"Hashcat --show completed: "
"%s bytes, %s lines.",
show_path.stat().st_size,
len(show_output.splitlines()),
)
except HashcatError as exc:
update_job_state(
job_dir,
JOB_STATUS_FAILED,
error=str(exc),
)
job_logger.error(
"Hashcat --show failed: %s",
exc,
)
return False
except Exception as exc:
update_job_state(
job_dir,
JOB_STATUS_FAILED,
error=str(exc),
)
job_logger.exception(
"Unexpected --show error."
)
return False
step_states = [
self._step_result(
job_dir,
step,
)
for step in job["steps"]
]
try:
result_package = (
create_result_package(
job_dir,
job,
step_states,
self.paths.outbox,
logger=job_logger,
)
)
except ResultPackageError as exc:
update_job_state(
job_dir,
JOB_STATUS_FAILED,
error=str(exc),
)
job_logger.error(
"Result package creation failed: %s",
exc,
)
return False
except Exception as exc:
update_job_state(
job_dir,
JOB_STATUS_FAILED,
error=str(exc),
)
job_logger.exception(
"Unexpected result package error."
)
return False
update_job_state(
job_dir,
JOB_STATUS_COMPLETED,
)
try:
archived_package = (
self.package_service.archive_job(
job_dir.name
)
)
except JobPackageError as exc:
job_logger.error(
"Job package archival failed: %s",
exc,
)
return False
except Exception:
job_logger.exception(
"Unexpected Job package archival failure."
)
return False
job_logger.info(
"Job COMPLETED."
)
job_logger.info(
"Result package: %s",
result_package,
)
job_logger.info(
"Job package archived: %s",
archived_package,
)
return True
except Exception as exc:
update_job_state(
job_dir,
JOB_STATUS_FAILED,
error=str(exc),
)
job_logger.error(
"Job failed: %s",
exc,
)
job_logger.debug(
"%s",
traceback.format_exc(),
)
return False
def run_once(self) -> list[str]:
imported = self.import_jobs()
for item in imported:
self.logger.info(
"Queue item: %s idempotent=%s",
item.job_id,
item.idempotent,
)
completed: list[str] = []
for job_dir in sorted(
self.paths.jobs.glob("JOB-*")
):
if not job_dir.is_dir():
continue
try:
if self.run_job(
job_dir
):
completed.append(
job_dir.name
)
except Exception:
self.logger.exception(
"Unhandled error processing %s",
job_dir.name,
)
return completed
def run_forever(self) -> None:
self.logger.info(
"Client loop started."
)
while True:
try:
self.run_once()
except KeyboardInterrupt:
self.logger.info(
"Client stopped by user."
)
return
except Exception:
self.logger.exception(
"Unhandled client loop error."
)
import time
time.sleep(
self.config.poll_seconds
)
+64
View File
@@ -0,0 +1,64 @@
from __future__ import annotations
import logging
from datetime import datetime, timezone
from pathlib import Path
LOGGER_NAME = "cracklab.client"
class UTCFormatter(logging.Formatter):
converter = staticmethod(
lambda timestamp: datetime.fromtimestamp(
timestamp,
tz=timezone.utc,
).timetuple()
)
def _configure(
name: str,
log_path: Path,
) -> logging.Logger:
log_path.parent.mkdir(parents=True, exist_ok=True)
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
logger.propagate = False
if logger.handlers:
return logger
handler = logging.FileHandler(
log_path,
mode="a",
encoding="utf-8",
)
handler.setFormatter(
UTCFormatter(
"%(asctime)sZ %(levelname)s %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
)
logger.addHandler(handler)
return logger
def configure_logging(log_path: Path) -> logging.Logger:
return _configure(
LOGGER_NAME,
log_path,
)
def configure_job_logging(
log_path: Path,
job_id: str,
) -> logging.Logger:
return _configure(
f"{LOGGER_NAME}.{job_id}",
log_path,
)
+12
View File
@@ -0,0 +1,12 @@
{
"hashcat_exe": "F:\\hashcat\\hashcat.exe",
"potfile_path": "F:\\cracklab\\potfile\\wifi-gps-mapper.potfile",
"client_root": "F:\\cracklab\\client",
"wordlists": {
"insidePRO_WPA": "F:\\hashcat\\my-slovari\\insidePRO_WPA.txt",
"BreachCompilation": "B:\\BIG_SLOVAR\\parser\\BreachCompilation.txt",
"test": "F:\\cracklab\\test-artifacts\\wordlists\\integration-test.txt"
},
"poll_seconds": 3,
"max_parallel_jobs": 1
}
+106
View File
@@ -0,0 +1,106 @@
from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
CONFIG_NAME = "config.json"
@dataclass(frozen=True)
class ClientConfig:
hashcat_exe: Path
potfile_path: Path
client_root: Path
wordlists: dict[str, Path]
poll_seconds: int
max_parallel_jobs: int
def load_config(script_dir: Path) -> ClientConfig:
path = script_dir / CONFIG_NAME
if not path.is_file():
raise FileNotFoundError(
f"Missing {path}. "
"Copy config.example.json to config.json and edit it."
)
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ValueError(f"Invalid JSON in {path}: {exc}") from exc
if not isinstance(data, dict):
raise ValueError("Client config must contain a JSON object.")
required = (
"hashcat_exe",
"potfile_path",
"client_root",
"wordlists",
"poll_seconds",
"max_parallel_jobs",
)
missing = [name for name in required if name not in data]
if missing:
raise ValueError(
"Missing required config fields: "
+ ", ".join(missing)
)
for name in (
"hashcat_exe",
"potfile_path",
"client_root",
):
if not isinstance(data[name], str) or not data[name].strip():
raise ValueError(
f"Config field {name!r} must be a non-empty string."
)
if not isinstance(data["wordlists"], dict) or not data["wordlists"]:
raise ValueError(
"Config field 'wordlists' must be a non-empty object."
)
for name, path_value in data["wordlists"].items():
if not isinstance(name, str) or not name.strip():
raise ValueError(
"Each wordlists key must be a non-empty string."
)
if not isinstance(path_value, str) or not path_value.strip():
raise ValueError(
f"Wordlist {name!r} path must be a non-empty string."
)
for name in (
"poll_seconds",
"max_parallel_jobs",
):
value = data[name]
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError(
f"Config field {name!r} must be an integer."
)
if value <= 0:
raise ValueError(
f"Config field {name!r} must be greater than zero."
)
return ClientConfig(
hashcat_exe=Path(data["hashcat_exe"]).expanduser().resolve(),
potfile_path=Path(data["potfile_path"]).expanduser().resolve(),
client_root=Path(data["client_root"]).expanduser().resolve(),
wordlists={
name: Path(path_value).expanduser().resolve()
for name, path_value in data["wordlists"].items()
},
poll_seconds=data["poll_seconds"],
max_parallel_jobs=data["max_parallel_jobs"],
)
+673
View File
@@ -0,0 +1,673 @@
from __future__ import annotations
import hashlib
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
class HashcatError(RuntimeError):
def __init__(
self,
message: str,
*,
exit_code: int | None = None,
) -> None:
super().__init__(message)
self.exit_code = exit_code
@dataclass(frozen=True)
class HashcatRunResult:
exit_code: int
restore_seen: bool
def restore_path(
job_dir: Path,
step: dict,
) -> Path:
return (
job_dir
/ "state"
/ f"step-{step['step_no']:03d}.restore"
)
def completed_marker(
job_dir: Path,
step: dict,
) -> Path:
return (
job_dir
/ "state"
/ f"step-{step['step_no']:03d}.completed"
)
def _session_name(step: dict) -> str:
session = step.get("session_name")
if not isinstance(session, str) or not session:
raise HashcatError(
f"Step {step.get('step_no')} has no session_name."
)
return session
def _resolve_wordlist(
config,
resource: str,
step_no,
) -> Path:
if not isinstance(resource, str) or not resource:
raise HashcatError(
f"Step {step_no} has invalid dictionary resource."
)
prefix = "wordlist:"
if not resource.startswith(prefix):
raise HashcatError(
f"Step {step_no} has unsupported dictionary resource: "
f"{resource}"
)
name = resource[len(prefix):]
if not name or "/" in name or "\\" in name or name in (".", ".."):
raise HashcatError(
f"Step {step_no} has invalid dictionary resource: "
f"{resource}"
)
dictionary = config.wordlists.get(name)
if dictionary is None:
raise HashcatError(
f"Wordlist resource {resource!r} is not configured."
)
dictionary = dictionary.resolve()
if not dictionary.is_file():
raise HashcatError(
f"Configured wordlist does not exist: {dictionary}"
)
return dictionary
def build_start_command(
config,
job_dir: Path,
job: dict,
step: dict,
) -> list[str]:
exe = config.hashcat_exe.resolve()
if not exe.is_file():
raise HashcatError(
f"Hashcat executable does not exist: {exe}"
)
hash_file = (
job_dir
/ "hashes"
/ job["hash_file_name"]
).resolve()
if not hash_file.is_file():
raise HashcatError(
f"Hash file does not exist: {hash_file}"
)
restore = restore_path(
job_dir,
step,
).resolve()
session = _session_name(step)
attack_mode = step.get("definition", {}).get(
"attack_mode"
)
if not isinstance(attack_mode, int):
raise HashcatError(
f"Step {step.get('step_no')} has invalid "
"attack_mode."
)
definition = step["definition"]
cmd = [
str(exe),
"-m",
str(job["hash_mode"]),
"-a",
str(attack_mode),
"--session",
session,
"--restore-file-path",
str(restore),
"--potfile-path",
str(config.potfile_path.resolve()),
"--logfile-disable",
"-w",
str(
definition.get(
"workload_profile",
1,
)
),
]
if attack_mode in (0, 1, 6, 7):
dictionary_definition = (
definition.get(
"dictionaries"
)
if attack_mode == 1
else definition.get(
"dictionary"
)
)
if attack_mode == 0:
if not isinstance(
dictionary_definition,
dict,
):
raise HashcatError(
f"Step {step.get('step_no')} "
"attack mode 0 has no dictionary."
)
resources = [
dictionary_definition.get(
"resource"
)
]
elif attack_mode == 1:
if (
not isinstance(
dictionary_definition,
list,
)
or len(dictionary_definition) != 2
):
raise HashcatError(
f"Step {step.get('step_no')} "
"attack mode 1 requires exactly "
"two dictionaries."
)
resources = [
item.get("resource")
if isinstance(item, dict)
else None
for item in dictionary_definition
]
else:
if not isinstance(
dictionary_definition,
dict,
):
raise HashcatError(
f"Step {step.get('step_no')} "
f"attack mode {attack_mode} "
"has no dictionary."
)
resources = [
dictionary_definition.get(
"resource"
)
]
dictionaries = [
_resolve_wordlist(
config,
resource,
step.get("step_no"),
)
for resource in resources
]
induction = (
job_dir
/ "state"
/ "induct"
).resolve()
outfile_check = (
job_dir
/ "state"
/ "outfiles"
).resolve()
induction.mkdir(
parents=True,
exist_ok=True,
)
outfile_check.mkdir(
parents=True,
exist_ok=True,
)
cmd.extend(
[
"--induction-dir",
str(induction),
"--outfile-check-dir",
str(outfile_check),
str(hash_file),
]
)
cmd.extend(
str(dictionary)
for dictionary in dictionaries
)
if attack_mode in (6, 7):
mask = definition.get("mask")
if not isinstance(mask, str) or not mask:
raise HashcatError(
f"Step {step.get('step_no')} "
f"attack mode {attack_mode} has no mask."
)
if attack_mode == 6:
cmd.append(mask)
else:
cmd.insert(
len(cmd) - len(dictionaries),
mask,
)
elif attack_mode == 3:
mask = definition.get("mask")
if not isinstance(mask, str) or not mask:
raise HashcatError(
f"Step {step.get('step_no')} "
"attack mode 3 has no mask."
)
cmd.extend(
[
str(hash_file),
mask,
]
)
else:
raise HashcatError(
f"Unsupported attack mode {attack_mode}. "
"Use a structured adapter for new modes."
)
return cmd
def build_restore_command(
config,
job_dir: Path,
step: dict,
) -> list[str]:
exe = config.hashcat_exe.resolve()
if not exe.is_file():
raise HashcatError(
f"Hashcat executable does not exist: {exe}"
)
restore = restore_path(
job_dir,
step,
).resolve()
return [
str(exe),
"--session",
_session_name(step),
"--restore-file-path",
str(restore),
"--restore",
]
def build_show_command(
config,
job_dir: Path,
job: dict,
) -> list[str]:
exe = config.hashcat_exe.resolve()
if not exe.is_file():
raise HashcatError(
f"Hashcat executable does not exist: {exe}"
)
hash_file = (
job_dir
/ "hashes"
/ job["hash_file_name"]
).resolve()
if not hash_file.is_file():
raise HashcatError(
f"Hash file does not exist: {hash_file}"
)
return [
str(exe),
"-m",
str(job["hash_mode"]),
"--potfile-path",
str(config.potfile_path.resolve()),
"--show",
str(hash_file),
]
def command_text(cmd: list[str]) -> str:
return " ".join(
f'"{value}"' if " " in value else value
for value in cmd
)
def run_hashcat(
cmd: list[str],
log_path: Path,
*,
on_output: Callable[[bytes], None] | None = None,
) -> int:
log_path.parent.mkdir(
parents=True,
exist_ok=True,
)
if not cmd:
raise HashcatError(
"Hashcat command is empty."
)
hashcat_dir = (
Path(cmd[0])
.resolve()
.parent
)
text = command_text(cmd)
with log_path.open(
"ab",
) as log:
log.write(
b"\n=== START ===\n"
)
log.write(
text.encode(
"utf-8",
errors="replace",
)
)
log.write(b"\n")
log.flush()
try:
process = subprocess.Popen(
cmd,
cwd=str(hashcat_dir),
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=0,
creationflags=getattr(
subprocess,
"CREATE_NEW_PROCESS_GROUP",
0,
),
)
except OSError as exc:
log.write(
(
"\n=== PROCESS START ERROR ===\n"
f"{exc}\n"
).encode(
"utf-8",
errors="replace",
)
)
raise HashcatError(
f"Failed to start Hashcat: {exc}"
) from exc
try:
if process.stdout is None:
raise HashcatError(
"Hashcat stdout pipe was not created."
)
while True:
chunk = process.stdout.read(4096)
if not chunk:
break
log.write(chunk)
log.flush()
if on_output is not None:
on_output(chunk)
except BaseException:
try:
process.kill()
except OSError:
pass
raise
finally:
if process.stdout is not None:
process.stdout.close()
exit_code = process.wait()
log.write(
(
"\n=== END ===\n"
f"exit_code={exit_code}\n"
).encode(
"utf-8",
errors="replace",
)
)
log.flush()
return exit_code
def run_step(
config,
job_dir: Path,
job: dict,
step: dict,
log_path: Path,
*,
restore: bool = False,
) -> HashcatRunResult:
restore_file = restore_path(
job_dir,
step,
)
if restore:
if not restore_file.is_file():
raise HashcatError(
f"Restore requested but restore file "
f"does not exist: {restore_file}"
)
cmd = build_restore_command(
config,
job_dir,
step,
)
else:
cmd = build_start_command(
config,
job_dir,
job,
step,
)
exit_code = run_hashcat(
cmd,
log_path,
on_output=lambda chunk: print(
chunk.decode(
"utf-8",
errors="replace",
),
end="",
flush=True,
),
)
restore_seen = restore_file.is_file()
if exit_code not in (0, 1):
raise HashcatError(
f"Hashcat exited with unsupported "
f"code {exit_code}.",
exit_code=exit_code,
)
return HashcatRunResult(
exit_code=exit_code,
restore_seen=restore_seen,
)
def run_show(
config,
job_dir: Path,
job: dict,
output_path: Path,
log_path: Path,
) -> str:
cmd = build_show_command(
config,
job_dir,
job,
)
output_path.parent.mkdir(
parents=True,
exist_ok=True,
)
log_path.parent.mkdir(
parents=True,
exist_ok=True,
)
hashcat_dir = (
Path(cmd[0])
.resolve()
.parent
)
text = command_text(cmd)
with log_path.open(
"ab",
) as log:
log.write(
b"\n=== SHOW START ===\n"
)
log.write(
text.encode(
"utf-8",
errors="replace",
)
)
log.write(b"\n")
log.flush()
try:
process = subprocess.run(
cmd,
cwd=str(hashcat_dir),
stdin=None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
check=False,
)
except OSError as exc:
log.write(
(
"\n=== SHOW START ERROR ===\n"
f"{exc}\n"
).encode(
"utf-8",
errors="replace",
)
)
raise HashcatError(
f"Failed to start Hashcat --show: {exc}"
) from exc
output = process.stdout or b""
output_path.write_bytes(
output
)
log.write(output)
log.write(
(
"\n=== SHOW END ===\n"
f"exit_code={process.returncode}\n"
).encode(
"utf-8",
errors="replace",
)
)
log.flush()
if process.returncode not in (0, 1):
raise HashcatError(
f"Hashcat --show exited with "
f"code {process.returncode}."
)
return output.decode(
"utf-8",
errors="replace",
)
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
while True:
chunk = handle.read(1024 * 1024)
if not chunk:
break
digest.update(chunk)
return digest.hexdigest()
File diff suppressed because it is too large Load Diff
+41
View File
@@ -0,0 +1,41 @@
from __future__ import annotations
import argparse
from pathlib import Path
from .client import CrackLabClient
def main() -> int:
parser = argparse.ArgumentParser(
description="WiFi GPS Mapper CrackLab client"
)
parser.add_argument(
"--once",
action="store_true",
help="Import and process jobs once, then exit.",
)
args = parser.parse_args()
script_dir = Path(
__file__
).resolve().parent
client = CrackLabClient(
script_dir
)
if args.once:
client.run_once()
return 0
client.run_forever()
return 0
if __name__ == "__main__":
raise SystemExit(
main()
)
+46
View File
@@ -0,0 +1,46 @@
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
CLIENT_DIRECTORIES = (
"inbox",
"pending",
"jobs",
"outbox",
"logs",
"archive",
)
@dataclass(frozen=True)
class ClientPaths:
root: Path
inbox: Path
pending: Path
jobs: Path
outbox: Path
logs: Path
archive: Path
@classmethod
def from_root(cls, root: Path) -> "ClientPaths":
root = root.resolve()
return cls(
root=root,
inbox=root / "inbox",
pending=root / "pending",
jobs=root / "jobs",
outbox=root / "outbox",
logs=root / "logs",
archive=root / "archive",
)
def initialize(self) -> None:
for name in CLIENT_DIRECTORIES:
(self.root / name).mkdir(
parents=True,
exist_ok=True,
)
+310
View File
@@ -0,0 +1,310 @@
from __future__ import annotations
import hashlib
import json
import os
import tempfile
import zipfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
class ResultPackageError(RuntimeError):
pass
def utc_now() -> str:
return (
datetime.now(timezone.utc)
.replace(microsecond=0)
.isoformat()
.replace("+00:00", "Z")
)
def _sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def _sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
while True:
chunk = handle.read(1024 * 1024)
if not chunk:
break
digest.update(chunk)
return digest.hexdigest()
def _json_bytes(data: dict[str, Any]) -> bytes:
return (
json.dumps(
data,
ensure_ascii=False,
indent=2,
)
+ "\n"
).encode("utf-8")
def _atomic_write(
path: Path,
data: bytes,
) -> None:
path.parent.mkdir(
parents=True,
exist_ok=True,
)
fd, temporary = tempfile.mkstemp(
prefix=f".{path.name}.",
suffix=".tmp",
dir=str(path.parent),
)
temporary_path = Path(temporary)
try:
with os.fdopen(fd, "wb") as handle:
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
temporary_path.replace(path)
except BaseException:
temporary_path.unlink(
missing_ok=True
)
raise
def _validate_result_steps(
job: dict[str, Any],
step_states: list[dict[str, Any]],
) -> None:
job_steps = job.get("steps")
if not isinstance(job_steps, list):
raise ResultPackageError(
"Job has no valid steps list."
)
if len(job_steps) != len(step_states):
raise ResultPackageError(
"Result step count does not match Job step count."
)
for job_step, result_step in zip(
job_steps,
step_states,
):
if (
result_step.get("step_no")
!= job_step.get("step_no")
):
raise ResultPackageError(
"Result step_no does not match Job."
)
if (
result_step.get("step_id")
!= job_step.get("step_id")
):
raise ResultPackageError(
"Result step_id does not match Job."
)
if (
result_step.get("session_name")
!= job_step.get("session_name")
):
raise ResultPackageError(
"Result session_name does not match Job."
)
if result_step.get("status") != "COMPLETED":
raise ResultPackageError(
f"Step {job_step.get('step_no')} "
"is not COMPLETED."
)
if result_step.get("exit_code") not in (0, 1):
raise ResultPackageError(
f"Step {job_step.get('step_no')} "
"has unsupported exit_code."
)
if result_step.get("restore_seen"):
raise ResultPackageError(
f"Step {job_step.get('step_no')} "
"still has an active restore state."
)
def build_result(
job: dict[str, Any],
step_states: list[dict[str, Any]],
*,
completed_at: str | None = None,
) -> tuple[dict[str, Any], bytes]:
job_id = job.get("job_id")
if not isinstance(job_id, str) or not job_id:
raise ResultPackageError(
"Job has no valid job_id."
)
method_id = job.get("method_id")
method_version = job.get("method_version")
if not isinstance(method_id, str) or not method_id:
raise ResultPackageError(
"Job has no valid method_id."
)
if (
isinstance(method_version, bool)
or not isinstance(method_version, int)
):
raise ResultPackageError(
"Job has no valid method_version."
)
_validate_result_steps(
job,
step_states,
)
result = {
"schema_version": 1,
"job_id": job_id,
"status": "COMPLETED",
"completed_at": completed_at or utc_now(),
"hash_file_sha256": job["hash_file_sha256"],
"hash_count": job["hash_count"],
"method": {
"id": method_id,
"version": method_version,
},
"steps": step_states,
"show_file": "hashcat-show.txt",
}
unsigned_bytes = _json_bytes(result)
result["result_sha256"] = _sha256_bytes(
unsigned_bytes
)
return result, _json_bytes(result)
def create_result_package(
job_dir: Path,
job: dict[str, Any],
step_states: list[dict[str, Any]],
outbox: Path,
*,
logger=None,
) -> Path:
results_dir = job_dir / "results"
show_path = results_dir / "hashcat-show.txt"
if not show_path.is_file():
raise ResultPackageError(
f"Missing Hashcat show output: {show_path}"
)
result, result_bytes = build_result(
job,
step_states,
)
result_path = results_dir / "result.json"
_atomic_write(
result_path,
result_bytes,
)
result_sha256 = _sha256_file(
result_path
)
if result_sha256 != _sha256_bytes(
result_bytes
):
raise ResultPackageError(
"Written result.json SHA-256 mismatch."
)
outbox.mkdir(
parents=True,
exist_ok=True,
)
job_id = job["job_id"]
destination = (
outbox / f"RESULT-{job_dir.name}.zip"
)
if destination.exists():
raise ResultPackageError(
f"Result package already exists: "
f"{destination}"
)
fd, temporary = tempfile.mkstemp(
prefix=f".RESULT-{job_dir.name}.",
suffix=".zip.tmp",
dir=str(outbox),
)
temporary_path = Path(temporary)
try:
os.close(fd)
with zipfile.ZipFile(
temporary_path,
mode="w",
compression=zipfile.ZIP_DEFLATED,
) as archive:
archive.write(
result_path,
"result.json",
)
archive.write(
show_path,
"hashcat-show.txt",
)
temporary_path.replace(
destination
)
except BaseException:
temporary_path.unlink(
missing_ok=True
)
raise
if logger is not None:
logger.info(
"Result package created: %s "
"result_sha256=%s "
"show_sha256=%s",
destination.name,
result["result_sha256"],
_sha256_file(show_path),
)
return destination
+258
View File
@@ -0,0 +1,258 @@
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
JOB_STATUS_QUEUED = "QUEUED"
JOB_STATUS_RUNNING = "RUNNING"
JOB_STATUS_COMPLETED = "COMPLETED"
JOB_STATUS_PARTIAL = "PARTIAL"
JOB_STATUS_FAILED = "FAILED"
STEP_STATUS_PENDING = "PENDING"
STEP_STATUS_RUNNING = "RUNNING"
STEP_STATUS_COMPLETED = "COMPLETED"
STEP_STATUS_PARTIAL = "PARTIAL"
STEP_STATUS_FAILED = "FAILED"
def utc_now() -> str:
return (
datetime.now(timezone.utc)
.replace(microsecond=0)
.isoformat()
.replace("+00:00", "Z")
)
class StateError(RuntimeError):
pass
def _atomic_write_json(
path: Path,
data: dict[str, Any],
) -> None:
path.parent.mkdir(
parents=True,
exist_ok=True,
)
temp_path = path.with_name(
f".{path.name}.tmp"
)
payload = json.dumps(
data,
ensure_ascii=False,
indent=2,
) + "\n"
temp_path.write_text(
payload,
encoding="utf-8",
)
temp_path.replace(path)
def _load_json(path: Path) -> dict[str, Any]:
try:
data = json.loads(
path.read_text(
encoding="utf-8",
)
)
except FileNotFoundError as exc:
raise StateError(
f"Missing state file: {path}"
) from exc
except json.JSONDecodeError as exc:
raise StateError(
f"Invalid JSON in state file {path}: {exc}"
) from exc
if not isinstance(data, dict):
raise StateError(
f"State file must contain an object: {path}"
)
return data
def state_path(job_dir: Path) -> Path:
return job_dir / "state" / "client_state.json"
def load_state(job_dir: Path) -> dict[str, Any]:
return _load_json(
state_path(job_dir)
)
def save_state(
job_dir: Path,
state: dict[str, Any],
) -> None:
_atomic_write_json(
state_path(job_dir),
state,
)
def initialize_state(
job_dir: Path,
job: dict[str, Any],
) -> dict[str, Any]:
job_id = job.get("job_id")
if not isinstance(job_id, str) or not job_id:
raise StateError(
"Job is missing a valid job_id."
)
steps = job.get("steps")
if not isinstance(steps, list) or not steps:
raise StateError(
f"Job {job_id} has no steps."
)
now = utc_now()
state: dict[str, Any] = {
"job_id": job_id,
"status": JOB_STATUS_QUEUED,
"created_at": now,
"updated_at": now,
"steps": {},
}
for step in steps:
step_no = step.get("step_no")
if not isinstance(step_no, int):
raise StateError(
f"Job {job_id} contains invalid step_no."
)
state["steps"][str(step_no)] = {
"step_no": step_no,
"step_id": step.get("step_id"),
"session_name": step.get("session_name"),
"status": STEP_STATUS_PENDING,
"started_at": None,
"completed_at": None,
"exit_code": None,
"restore_seen": False,
"error": None,
}
save_state(
job_dir,
state,
)
return state
def update_job_state(
job_dir: Path,
status: str,
*,
error: str | None = None,
) -> dict[str, Any]:
state = load_state(job_dir)
state["status"] = status
state["updated_at"] = utc_now()
if error is not None:
state["error"] = error
elif status != JOB_STATUS_FAILED:
state.pop("error", None)
save_state(
job_dir,
state,
)
return state
def update_step_state(
job_dir: Path,
step_no: int,
status: str,
*,
exit_code: int | None = None,
restore_seen: bool | None = None,
error: str | None = None,
started: bool = False,
completed: bool = False,
) -> dict[str, Any]:
state = load_state(job_dir)
key = str(step_no)
steps = state.get("steps")
if not isinstance(steps, dict) or key not in steps:
raise StateError(
f"Unknown step {step_no}."
)
step_state = steps[key]
step_state["status"] = status
if started:
step_state["started_at"] = utc_now()
if completed:
step_state["completed_at"] = utc_now()
if exit_code is not None:
step_state["exit_code"] = exit_code
if restore_seen is not None:
step_state["restore_seen"] = restore_seen
if error is not None:
step_state["error"] = error
elif status != STEP_STATUS_FAILED:
step_state["error"] = None
state["updated_at"] = utc_now()
save_state(
job_dir,
state,
)
return state
def get_step_state(
job_dir: Path,
step_no: int,
) -> dict[str, Any]:
state = load_state(job_dir)
steps = state.get("steps")
if not isinstance(steps, dict):
raise StateError(
f"Invalid steps state in {job_dir}."
)
step = steps.get(str(step_no))
if not isinstance(step, dict):
raise StateError(
f"Unknown step {step_no}."
)
return step