hackforge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
forge/gemini.py ADDED
@@ -0,0 +1,147 @@
1
+ """Gemini protocol client — stdlib only (socket + ssl), evolved from
2
+ /tmp/secretscan/gmi.py left by the secret-hunter agent.
3
+
4
+ Capsules speak gemini over TCP on port 1965: the client sends the request
5
+ URL as one CRLF-terminated line, the server replies with a 2-digit status,
6
+ a space, metadata, CRLF, then (for text responses) the body.
7
+
8
+ Status classes (geminispace.org/spec/gemini):
9
+ 1x input required (10/11 sensitive input)
10
+ 2x success (20 text/gemini, 21 binary)
11
+ 3x redirect (30 temporary, 31 permanent) — Location may be relative
12
+ 4x client error / not found (40-44)
13
+ 5x server error (50-59)
14
+ 6x certificate required (60-61)
15
+ """
16
+ import socket
17
+ import ssl
18
+ import time
19
+ import urllib.parse
20
+ from dataclasses import dataclass
21
+
22
+ PORT = 1965
23
+ UA = "hackforge/0.1 gemini client"
24
+
25
+
26
+ @dataclass
27
+ class GmiResponse:
28
+ url: str # original request URL
29
+ status: int # 2-digit status (0 = fetch error)
30
+ meta: str # text after the status code
31
+ body: str = ""
32
+ final_url: str = ""
33
+ error: str = ""
34
+ elapsed_ms: int = 0
35
+
36
+ @property
37
+ def ok(self) -> bool:
38
+ return 20 <= self.status < 30
39
+
40
+ @property
41
+ def is_redirect(self) -> bool:
42
+ return 30 <= self.status < 40
43
+
44
+
45
+ def _connect(host: int | str, port: int, timeout: float, use_tls: bool):
46
+ s = socket.create_connection((host, port), timeout=timeout)
47
+ if use_tls:
48
+ # capsules are mostly self-signed / let's-encrypt mix; verify when we
49
+ # can, fall back to no-verify below (gmi.py behaviour)
50
+ ctx = ssl.create_default_context()
51
+ ctx.check_hostname = False
52
+ ctx.verify_mode = ssl.CERT_NONE
53
+ s = ctx.wrap_socket(s, server_hostname=host)
54
+ return s
55
+
56
+
57
+ def parse(raw: str, url: str) -> GmiResponse:
58
+ """Split a full gemini reply into status / meta / body."""
59
+ head, sep, body = raw.partition("\r\n")
60
+ try:
61
+ status = int(head[:2])
62
+ meta = head[2:].strip() if len(head) > 2 else ""
63
+ except ValueError:
64
+ status, meta = 0, head
65
+ return GmiResponse(url=url, status=status, meta=meta, body=body if sep else "")
66
+
67
+
68
+ def fetch(url: str, timeout: float = 10.0, max_hops: int = 5,
69
+ max_bytes: int = 400_000) -> GmiResponse:
70
+ """Fetch a gemini:// URL, following 3x redirects. Plain-TLS-first with a
71
+ plain-text fallback (some old capsules still run :1965 unencrypted)."""
72
+ t0 = time.monotonic()
73
+ r = _fetch(url, timeout, max_hops, max_bytes)
74
+ r.elapsed_ms = int((time.monotonic() - t0) * 1000)
75
+ return r
76
+
77
+
78
+ def _fetch(url: str, timeout: float, max_hops: int, max_bytes: int) -> GmiResponse:
79
+ seen = set()
80
+ hops = 0
81
+ current = url
82
+ while hops <= max_hops:
83
+ if current in seen:
84
+ return GmiResponse(url=url, status=0, meta="", final_url=current,
85
+ error=f"redirect loop at {current}")
86
+ seen.add(current)
87
+ u = urllib.parse.urlsplit(current)
88
+ host, port = u.hostname, u.port or PORT
89
+ r = None
90
+ for use_tls in (True, False):
91
+ try:
92
+ s = _connect(host, port, timeout, use_tls)
93
+ try:
94
+ s.sendall((current + "\r\n").encode("utf-8"))
95
+ # read the response header line first
96
+ buf = b""
97
+ while b"\r\n" not in buf:
98
+ c = s.recv(4096)
99
+ if not c:
100
+ break
101
+ buf += c
102
+ # then the body until EOF (gemini bodies end at connection close)
103
+ data = buf
104
+ while len(data) < max_bytes:
105
+ c = s.recv(65536)
106
+ if not c:
107
+ break
108
+ data += c
109
+ finally:
110
+ s.close()
111
+ r = parse(data.decode("utf-8", "replace"), current)
112
+ r.final_url = current
113
+ break
114
+ except (OSError, ssl.SSLError):
115
+ continue
116
+ if r is None:
117
+ return GmiResponse(url=url, status=0, meta="", final_url=current,
118
+ error=f"connect failed: {host}:{port}")
119
+ if not r.is_redirect:
120
+ return r
121
+ loc = r.meta.strip()
122
+ if not loc:
123
+ return r # redirect with no Location — treat as final
124
+ r.final_url = current
125
+ hops += 1
126
+ current = urllib.parse.urljoin(current, loc)
127
+ return GmiResponse(url=url, status=r.status if r else 0, meta=r.meta if r else "",
128
+ body=r.body if r else "", final_url=current,
129
+ error=f"too many redirects (>{max_hops})")
130
+
131
+
132
+ def links(text: str, base: str) -> list:
133
+ """Parse gemtext `=> url label` lines into absolute (url, label) pairs."""
134
+ out = []
135
+ for line in text.splitlines():
136
+ line = line.lstrip()
137
+ if not line.startswith("=>"):
138
+ continue
139
+ rest = line[2:].strip()
140
+ if not rest:
141
+ continue
142
+ parts = rest.split(None, 1)
143
+ target = urllib.parse.urljoin(base, parts[0])
144
+ label = parts[1].strip() if len(parts) > 1 else ""
145
+ if target.startswith(("gemini://", "http://", "https://")):
146
+ out.append((target, label))
147
+ return out
forge/llm.py ADDED
@@ -0,0 +1,75 @@
1
+ """Local LLM client — Qwen4 via the qwen38 llama.cpp unit (:8093)."""
2
+ import json
3
+ import os
4
+ import re
5
+
6
+ import httpx
7
+
8
+ ENDPOINT = os.environ.get("FORGE_LLM", "http://127.0.0.1:8093/v1/chat/completions")
9
+ MODEL = os.environ.get("FORGE_MODEL", "qwen4")
10
+
11
+
12
+ def ask(system: str, user: str, max_tokens: int = 1600, temperature: float = 0.4,
13
+ timeout: int = 900) -> str:
14
+ payload = {
15
+ "model": MODEL,
16
+ "messages": [
17
+ {"role": "system", "content": system},
18
+ {"role": "user", "content": user},
19
+ ],
20
+ "max_tokens": max_tokens,
21
+ "temperature": temperature,
22
+ "stream": False,
23
+ "chat_template_kwargs": {"enable_thinking": False},
24
+ }
25
+ r = httpx.post(ENDPOINT, json=payload, timeout=timeout)
26
+ r.raise_for_status()
27
+ return r.json()["choices"][0]["message"]["content"] or ""
28
+
29
+
30
+ def _extract_json(text: str):
31
+ """Pull the first balanced JSON object/array out of model output."""
32
+ for opener, closer in (("[", "]"), ("{", "}")):
33
+ start = text.find(opener)
34
+ if start == -1:
35
+ continue
36
+ depth = 0
37
+ in_str = False
38
+ esc = False
39
+ for i in range(start, len(text)):
40
+ c = text[i]
41
+ if in_str:
42
+ if esc:
43
+ esc = False
44
+ elif c == "\\":
45
+ esc = True
46
+ elif c == '"':
47
+ in_str = False
48
+ continue
49
+ if c == '"':
50
+ in_str = True
51
+ elif c == opener:
52
+ depth += 1
53
+ elif c == closer:
54
+ depth -= 1
55
+ if depth == 0:
56
+ candidate = text[start:i + 1]
57
+ try:
58
+ return json.loads(candidate)
59
+ except json.JSONDecodeError:
60
+ break # try next opener style
61
+ # last resort: whole text
62
+ try:
63
+ return json.loads(text)
64
+ except json.JSONDecodeError:
65
+ return None
66
+
67
+
68
+ def ask_json(system: str, user: str, max_tokens: int = 2400, temperature: float = 0.3,
69
+ timeout: int = 900):
70
+ """Ask and parse JSON; raises ValueError if unparseable."""
71
+ out = ask(system, user, max_tokens=max_tokens, temperature=temperature, timeout=timeout)
72
+ data = _extract_json(out)
73
+ if data is None:
74
+ raise ValueError(f"no JSON in model output: {out[:300]!r}")
75
+ return data
forge/mcp_server.py ADDED
@@ -0,0 +1,210 @@
1
+ #!/usr/bin/env python3
2
+ """hackforge MCP server — stdio JSON-RPC 2.0.
3
+
4
+ Exposes the 7 forge tools as MCP tools so Claude Code (and any MCP client)
5
+ can drive the H4CK1NG suite natively:
6
+
7
+ forge_recon forge_probes forge_attacks forge_scan
8
+ forge_patrol forge_findings forge_targets
9
+
10
+ NAMING CHOICE: tools are prefixed `forge_` (not the bare tool names) so
11
+ several MCP servers can coexist in one client without collisions — the same
12
+ reason the official MCP registry namespaces servers by owner. Bare names
13
+ (`recon`, `probes`, ...) are also accepted in tools/call for convenience.
14
+
15
+ DEPENDENCIES: the official `mcp` package is NOT installed on this box, so the
16
+ protocol is hand-rolled: newline-delimited JSON-RPC 2.0 over stdio
17
+ (initialize / notifications/initialized / tools/list / tools/call / ping).
18
+ Stdlib + httpx only, matching the rest of the suite.
19
+
20
+ Dispatch is in-process via the forge package (same pattern as forge/bridge.py).
21
+ `forge_attacks` / `forge_scan` / `forge_patrol` run SYNCHRONOUSLY and can take
22
+ 1-10 minutes (LLM plan + sandbox) — clients should use a generous timeout.
23
+
24
+ Run: python3 ~/hackforge/forge/mcp_server.py
25
+ """
26
+ import json
27
+ import os
28
+ import sys
29
+
30
+ HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ~/hackforge
31
+ if HERE not in sys.path:
32
+ sys.path.insert(0, HERE)
33
+
34
+ from forge import __version__, attack, probes, runner # noqa: E402
35
+ from forge.recon import recon # noqa: E402
36
+ from forge.report import load_findings # noqa: E402
37
+
38
+ SERVER_INFO = {"name": "hackforge", "version": __version__}
39
+ # Protocol versions we can speak; echo the client's if known, else default.
40
+ KNOWN_PROTOCOLS = {"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"}
41
+ DEFAULT_PROTOCOL = "2025-06-18"
42
+
43
+ _URL = {"type": "string", "description": "Target URL (scheme optional; https:// assumed)"}
44
+ _NO_ATTACK = {"type": "boolean", "description": "Skip the LLM attack phase", "default": False}
45
+
46
+ # mcp name -> (description, inputSchema)
47
+ TOOLS = {
48
+ "forge_recon": (
49
+ "Fetch + fingerprint a URL: status, server, tech, title, links, forms, "
50
+ "cookies, well-known surface (llms.txt, agent.json, .env, .git...).",
51
+ {"type": "object", "properties": {"url": _URL}, "required": ["url"]}),
52
+ "forge_probes": (
53
+ "Deterministic probe suite (headers, cookies, forms, well-known) "
54
+ "→ findings with severity + evidence + fix, plus a 0-100 score.",
55
+ {"type": "object", "properties": {"url": _URL}, "required": ["url"]}),
56
+ "forge_attacks": (
57
+ "Qwen4 attack hypotheses from recon+probes, executed in the sandbox "
58
+ "→ REPRODUCED / NOT_REPRODUCED / INCONCLUSIVE verdicts. "
59
+ "Long: up to ~2-5 min (LLM plan + sandbox).",
60
+ {"type": "object",
61
+ "properties": {"url": _URL,
62
+ "n": {"type": "integer",
63
+ "description": "Max hypotheses (default 5)", "default": 5}},
64
+ "required": ["url"]}),
65
+ "forge_scan": (
66
+ "Full end-to-end scan of one target: recon → probes → attacks → "
67
+ "markdown report file + findings.jsonl. Long: up to ~5 min.",
68
+ {"type": "object", "properties": {"url": _URL, "no_attack": _NO_ATTACK},
69
+ "required": ["url"]}),
70
+ "forge_patrol": (
71
+ "Autonomous wave over targets/seed.txt with link discovery; "
72
+ "writes reports/last-patrol.json + LATEST.md. Longest: minutes per target.",
73
+ {"type": "object",
74
+ "properties": {"limit": {"type": "integer",
75
+ "description": "Max targets (default 8)", "default": 8},
76
+ "no_attack": _NO_ATTACK}}),
77
+ "forge_findings": (
78
+ "Recent rows from reports/findings.jsonl (probe + attack findings).",
79
+ {"type": "object",
80
+ "properties": {"n": {"type": "integer",
81
+ "description": "Row limit (default 50)", "default": 50}}}),
82
+ "forge_targets": (
83
+ "The seed target list (targets/seed.txt).",
84
+ {"type": "object", "properties": {}}),
85
+ }
86
+
87
+
88
+ def dispatch(name: str, arguments: dict):
89
+ """Run one forge tool in-process; returns a JSON-serialisable result."""
90
+ args = arguments or {}
91
+ if name in ("recon", "probes", "attacks", "scan") and not args.get("url"):
92
+ raise ValueError(f"tool {name!r} needs argument 'url'")
93
+ if name == "recon":
94
+ return recon(args["url"]).summary()
95
+ if name == "probes":
96
+ rec = recon(args["url"])
97
+ f = probes.run_probes(rec)
98
+ return {"score": probes.score(f), "findings": f}
99
+ if name == "attacks":
100
+ rec = recon(args["url"])
101
+ f = probes.run_probes(rec)
102
+ return attack.run_attacks(rec, f, n=int(args.get("n", 5)))
103
+ if name == "scan":
104
+ return runner.scan_target(args["url"],
105
+ do_attack=not args.get("no_attack", False)).to_dict()
106
+ if name == "patrol":
107
+ return runner.patrol(limit_targets=int(args.get("limit", 8)),
108
+ do_attack=not args.get("no_attack", False))
109
+ if name == "findings":
110
+ return load_findings(int(args.get("n", 50)))
111
+ if name == "targets":
112
+ return runner.load_seeds()
113
+ raise KeyError(f"unknown tool {name!r}")
114
+
115
+
116
+ def _resolve(name: str):
117
+ """Map an MCP tool name (or bare forge name) to (mcp_name, forge_name)."""
118
+ if name in TOOLS:
119
+ return name, name[len("forge_"):]
120
+ if ("forge_" + name) in TOOLS: # bare name accepted too
121
+ return "forge_" + name, name
122
+ return None, None
123
+
124
+
125
+ # ---------------------------------------------------------------- json-rpc
126
+
127
+ def _send(msg: dict):
128
+ sys.stdout.write(json.dumps(msg, default=str) + "\n")
129
+ sys.stdout.flush()
130
+
131
+
132
+ def _result(msg_id, result):
133
+ _send({"jsonrpc": "2.0", "id": msg_id, "result": result})
134
+
135
+
136
+ def _error(msg_id, code, message):
137
+ _send({"jsonrpc": "2.0", "id": msg_id, "error": {"code": code, "message": message}})
138
+
139
+
140
+ def handle(msg: dict) -> bool:
141
+ """Handle one JSON-RPC message; True to keep the loop running."""
142
+ method = msg.get("method")
143
+ msg_id = msg.get("id")
144
+ params = msg.get("params") or {}
145
+
146
+ if method == "initialize":
147
+ version = params.get("protocolVersion")
148
+ if version not in KNOWN_PROTOCOLS:
149
+ version = DEFAULT_PROTOCOL
150
+ _result(msg_id, {"protocolVersion": version,
151
+ "capabilities": {"tools": {"listChanged": False}},
152
+ "serverInfo": SERVER_INFO,
153
+ "instructions":
154
+ "hackforge — H4CK1NG suite on local models (Qwen4). "
155
+ "Scan targets: forge_scan for one end-to-end run, "
156
+ "forge_patrol for a wave over targets/seed.txt, "
157
+ "forge_probes/forge_recon for quick checks, "
158
+ "forge_findings for recent history. "
159
+ "forge_attacks/forge_scan/forge_patrol are synchronous "
160
+ "and can take minutes."})
161
+ return True
162
+ if msg_id is None: # notification (initialized / cancelled / ...) — no reply
163
+ return True
164
+
165
+ if method == "ping":
166
+ _result(msg_id, {})
167
+ elif method == "tools/list":
168
+ _result(msg_id, {"tools": [
169
+ {"name": n, "description": d, "inputSchema": s}
170
+ for n, (d, s) in TOOLS.items()]})
171
+ elif method == "tools/call":
172
+ name = params.get("name", "")
173
+ mcp_name, forge_name = _resolve(name)
174
+ if mcp_name is None:
175
+ _error(msg_id, -32602, f"unknown tool {name!r}; "
176
+ f"try one of {sorted(TOOLS)}")
177
+ else:
178
+ try:
179
+ result = dispatch(forge_name, params.get("arguments") or {})
180
+ _result(msg_id, {"content": [
181
+ {"type": "text",
182
+ "text": json.dumps(result, default=str, indent=1)}],
183
+ "isError": False})
184
+ except Exception as e: # noqa: BLE001 — tool errors are content, not protocol errors
185
+ _result(msg_id, {"content": [
186
+ {"type": "text", "text": f"error: {str(e)[:500]}"}],
187
+ "isError": True})
188
+ else:
189
+ _error(msg_id, -32601, f"method not found: {method!r}")
190
+ return True
191
+
192
+
193
+ def main():
194
+ sys.stderr.write(f"[hackforge-mcp] {SERVER_INFO['name']} v{SERVER_INFO['version']} "
195
+ f"— stdio MCP server, {len(TOOLS)} tools\n")
196
+ for line in sys.stdin:
197
+ line = line.strip()
198
+ if not line:
199
+ continue
200
+ try:
201
+ msg = json.loads(line)
202
+ except json.JSONDecodeError as e:
203
+ _error(None, -32700, f"parse error: {e}")
204
+ continue
205
+ if not handle(msg):
206
+ break
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()