trproof 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.
trproof/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
trproof/cli.py ADDED
@@ -0,0 +1,342 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from datetime import datetime, timezone
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ import click
9
+ from rich.console import Console
10
+ from rich.panel import Panel
11
+ from rich.progress import Progress, SpinnerColumn, TextColumn
12
+
13
+ from trproof.models import AssessmentReport, ScanBundle
14
+
15
+ console = Console()
16
+
17
+ AUTHORIZATION_NOTICE = (
18
+ "AUTHORIZATION REQUIRED: You must own or have explicit written authorization to audit this environment."
19
+ )
20
+ READ_ONLY_NOTICE = (
21
+ "Read-only enforcement: never writes, modifies passwords, or disables accounts; "
22
+ "no endpoint agents; no credential storage beyond session memory; offline-capable for AD."
23
+ )
24
+
25
+
26
+ def show_safety_banner() -> None:
27
+ banner_text = f"{READ_ONLY_NOTICE}\n\n{AUTHORIZATION_NOTICE}"
28
+ console.print(Panel(banner_text, title="TrProof Safety & Ethics", border_style="yellow"))
29
+
30
+
31
+ def confirm_authorization(yes: bool) -> None:
32
+ if yes:
33
+ return
34
+ confirmed = click.confirm(
35
+ "Confirm you are authorized to scan this environment?",
36
+ default=False,
37
+ )
38
+ if not confirmed:
39
+ raise click.ClickException("Authorization not confirmed. Aborting scan.")
40
+
41
+
42
+ def to_canonical_json(
43
+ report: AssessmentReport, output_path: Optional[Path] = None
44
+ ) -> str:
45
+ """Return deterministic canonical JSON and write a pretty-printed report file."""
46
+ data = report.model_dump()
47
+ for field in ("canonical_sha256", "signature_b64", "public_key_b64"):
48
+ data.pop(field, None)
49
+
50
+ canonical = json.dumps(
51
+ data, sort_keys=True, separators=(",", ":"), ensure_ascii=False
52
+ )
53
+
54
+ if output_path is None:
55
+ timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
56
+ output_path = Path(f"trproof-report-{timestamp}.json")
57
+ output_path.parent.mkdir(parents=True, exist_ok=True)
58
+ output_path.write_text(
59
+ json.dumps(report.model_dump(), indent=2, sort_keys=True, ensure_ascii=False),
60
+ encoding="utf-8",
61
+ )
62
+
63
+ return canonical
64
+
65
+
66
+ @click.group()
67
+ def main() -> None:
68
+ """TrProof - read-only identity security assessment CLI."""
69
+
70
+
71
+ @main.command("scan")
72
+ @click.option("--ad", is_flag=True, help="Enable on-premises AD scan")
73
+ @click.option("--ldap", "ldap_host", type=str, help="LDAP server hostname/IP (e.g. dc01.corp.local)")
74
+ @click.option("--port", type=int, default=636, show_default=True, help="LDAP port")
75
+ @click.option("--use-ssl/--no-ssl", default=True, show_default=True, help="Use LDAPS")
76
+ @click.option("--base-dn", type=str, help="Search base DN (auto-discovered if omitted)")
77
+ @click.option("-u", "--username", type=str, help="AD username (e.g. audit-reader or CORP\\audit-reader)")
78
+ @click.option("-p", "--password", type=str, default=None, help="AD password (prompted if omitted)")
79
+ @click.option("--entra", is_flag=True, help="Enable Microsoft Entra ID scan")
80
+ @click.option("--tenant-id", type=str, help="Entra Tenant ID")
81
+ @click.option("--client-id", type=str, help="Optional custom Entra App Client ID")
82
+ @click.option("--mock", is_flag=True, help="Run using tests.fixtures.mock_environment.get_mock_scan_bundle() without network calls")
83
+ @click.option("--signing-key", type=click.Path(path_type=Path, exists=False), help="Path to Ed25519 private key PEM")
84
+ @click.option("-o", "--output-dir", type=click.Path(path_type=Path), default=Path("."), show_default=True, help="Directory for HTML and JSON output")
85
+ @click.option("-y", "--yes", is_flag=True, help="Acknowledge authorization banner non-interactively")
86
+ def scan(
87
+ ad: bool,
88
+ ldap_host: Optional[str],
89
+ port: int,
90
+ use_ssl: bool,
91
+ base_dn: Optional[str],
92
+ username: Optional[str],
93
+ password: Optional[str],
94
+ entra: bool,
95
+ tenant_id: Optional[str],
96
+ client_id: Optional[str],
97
+ mock: bool,
98
+ signing_key: Optional[Path],
99
+ output_dir: Path,
100
+ yes: bool,
101
+ ) -> None:
102
+ """Run a read-only identity security assessment scan."""
103
+ show_safety_banner()
104
+
105
+ if not any([ad, entra, mock]):
106
+ raise click.UsageError("At least one of --ad, --entra, or --mock must be provided.")
107
+
108
+ confirm_authorization(yes)
109
+
110
+ if ad and not mock and password is None:
111
+ password = click.prompt("AD password", hide_input=True, confirmation_prompt=False)
112
+
113
+ if mock:
114
+ _run_mock_scan(output_dir, signing_key)
115
+ return
116
+
117
+ if entra and not tenant_id:
118
+ raise click.UsageError("--tenant-id is required when --entra is enabled.")
119
+
120
+ bundles: list[ScanBundle] = []
121
+ labels: list[str] = []
122
+
123
+ if ad:
124
+ ldap_server = ldap_host or "dc01.corp.local"
125
+ bundles.append(_collect_ad_bundle(username, password, ldap_server, port, use_ssl, base_dn))
126
+ labels.append(ldap_server)
127
+
128
+ if entra:
129
+ bundles.append(_collect_entra_bundle(tenant_id or "", client_id))
130
+ labels.append(tenant_id or "entra")
131
+
132
+ if len(bundles) == 1:
133
+ bundle = bundles[0]
134
+ else:
135
+ bundle = merge_scan_bundles(*bundles)
136
+
137
+ _write_bundle(bundle, " + ".join(labels), output_dir, signing_key)
138
+
139
+
140
+ def _collect_ad_bundle(
141
+ username: Optional[str],
142
+ password: Optional[str],
143
+ ldap_host: str,
144
+ port: int,
145
+ use_ssl: bool,
146
+ base_dn: Optional[str],
147
+ ) -> ScanBundle:
148
+ from trproof.collectors.ad import ADCollector
149
+ from trproof.models import ScanBundle
150
+
151
+ pwd = password
152
+ if not pwd:
153
+ pwd = click.prompt("AD password", hide_input=True, confirmation_prompt=False)
154
+
155
+ collector = ADCollector(
156
+ server=ldap_host,
157
+ username=username or "audit-reader",
158
+ password=pwd,
159
+ port=port,
160
+ use_ssl=use_ssl,
161
+ base_dn=base_dn,
162
+ timeout=10,
163
+ )
164
+
165
+ try:
166
+ with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console) as progress:
167
+ task_id = progress.add_task("Connecting to AD...", total=None)
168
+
169
+ def progress_cb(label: str) -> None:
170
+ progress.update(task_id, description=label)
171
+
172
+ bundle: ScanBundle = collector.collect(progress_cb)
173
+ except ConnectionError as exc:
174
+ raise click.ClickException(f"Connection error: {exc}") from exc
175
+
176
+ console.print("[green]AD scan complete.[/green]")
177
+ return bundle
178
+
179
+
180
+ def _collect_entra_bundle(tenant_id: str, client_id: Optional[str]) -> ScanBundle:
181
+ from trproof.collectors.entra import EntraCollector
182
+
183
+ collector = EntraCollector(
184
+ tenant_id=tenant_id,
185
+ client_id=client_id,
186
+ timeout=15,
187
+ )
188
+
189
+ def message_callback(message: str) -> None:
190
+ console.print(message)
191
+
192
+ try:
193
+ collector.authenticate(message_callback)
194
+ except PermissionError as exc:
195
+ raise click.ClickException(f"Entra authentication error: {exc}") from exc
196
+
197
+ with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console) as progress:
198
+ task_id = progress.add_task("Connecting to Entra ID...", total=None)
199
+
200
+ def progress_cb(label: str) -> None:
201
+ progress.update(task_id, description=label)
202
+
203
+ bundle = collector.collect(progress_cb)
204
+
205
+ console.print("[green]Entra scan complete.[/green]")
206
+ return bundle
207
+
208
+
209
+ def _write_bundle(
210
+ bundle: ScanBundle, environment_label: str, output_dir: Path, signing_key: Optional[Path] = None
211
+ ) -> None:
212
+ from trproof.graph.edges import AttackGraph
213
+ from trproof.scoring.engine import compute_verdict, sort_findings
214
+ from trproof.report.signing import sign_report
215
+ from trproof.report.html import render_html_report
216
+
217
+ console.print(
218
+ f"Nodes: {len(bundle.nodes)} | Edges: {len(bundle.edges)} | "
219
+ f"Findings: {len(bundle.findings)} | Warnings: {len(bundle.warnings)}"
220
+ )
221
+
222
+ if bundle.warnings:
223
+ console.print("[yellow]Collection warnings (could not check):[/yellow]")
224
+ for w in bundle.warnings:
225
+ console.print(f" • {w.check_name} ({w.reason})")
226
+
227
+ for f in bundle.findings:
228
+ console.print(f" [{f.severity.value}] {f.id}: {f.title} (affected: {f.affected_count})")
229
+
230
+ graph = AttackGraph(bundle)
231
+ top_paths, all_paths = graph.find_shortest_paths(max_display=5, max_depth=8)
232
+ verdict = compute_verdict(bundle.findings, all_paths)
233
+ sorted_findings = sort_findings(bundle.findings)
234
+
235
+ output_dir.mkdir(parents=True, exist_ok=True)
236
+ timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
237
+ html_path = output_dir / f"trproof-report-{timestamp}.html"
238
+ json_path = output_dir / f"trproof-report-{timestamp}.json"
239
+
240
+ report = AssessmentReport(
241
+ generated_at=datetime.now(timezone.utc).isoformat(),
242
+ environment_label=environment_label,
243
+ verdict=verdict,
244
+ top_paths=top_paths,
245
+ all_paths=all_paths,
246
+ findings=sorted_findings,
247
+ warnings=bundle.warnings,
248
+ )
249
+ report = sign_report(report, signing_key)
250
+
251
+ render_html_report(report, html_path)
252
+ to_canonical_json(report, output_path=json_path)
253
+
254
+ # Terminal UX
255
+ color = {
256
+ "CRITICAL": "red",
257
+ "HIGH": "orange1",
258
+ "MEDIUM": "yellow",
259
+ "LOW": "green",
260
+ }.get(verdict.value, "white")
261
+ console.print(
262
+ Panel(
263
+ f"Your identity attack surface: {verdict.value}",
264
+ title="TrProof Verdict",
265
+ border_style=color,
266
+ )
267
+ )
268
+
269
+ console.print("Top 5 Ways a Phished Employee Could Reach Domain Admin / Global Admin:")
270
+ if top_paths:
271
+ for path in top_paths:
272
+ console.print(path.summary)
273
+ else:
274
+ console.print("No direct attack paths to Tier-0 administrators found.")
275
+
276
+ console.print(f"Full JSON report: {_display_path(json_path)}")
277
+ console.print(f"Full report: {_display_path(html_path)}")
278
+
279
+
280
+ def _display_path(path: Path) -> str:
281
+ text = path.as_posix()
282
+ if not path.is_absolute() and not text.startswith("./"):
283
+ return "./" + text
284
+ return text
285
+
286
+
287
+ def _run_mock_scan(output_dir: Path, signing_key: Optional[Path] = None) -> None:
288
+ try:
289
+ from tests.fixtures.mock_environment import get_mock_scan_bundle
290
+ except ModuleNotFoundError:
291
+ import sys
292
+ from pathlib import Path
293
+
294
+ cwd = str(Path.cwd())
295
+ if cwd not in sys.path:
296
+ sys.path.insert(0, cwd)
297
+ from tests.fixtures.mock_environment import get_mock_scan_bundle
298
+
299
+ with Progress(
300
+ SpinnerColumn(),
301
+ TextColumn("[progress.description]{task.description}"),
302
+ console=console,
303
+ ) as progress:
304
+ progress.add_task("Running mock scan...", total=None)
305
+ bundle = get_mock_scan_bundle()
306
+
307
+ console.print("[green]Mock scan complete.[/green]")
308
+ _write_bundle(bundle, "mock-corp.local", output_dir, signing_key)
309
+
310
+
311
+ @main.command("verify")
312
+ @click.argument("report_json_path", type=click.Path(path_type=Path, exists=True, dir_okay=False))
313
+ @click.option("--public-key", type=click.Path(path_type=Path, exists=False), default=None, help="Path to Ed25519 public key PEM")
314
+ def verify(report_json_path: Path, public_key: Optional[Path]) -> None:
315
+ """Verify a TrProof report JSON file."""
316
+ from trproof.report.signing import verify_report
317
+
318
+ status, message = verify_report(report_json_path, public_key)
319
+
320
+ color = {
321
+ "VALID": "green",
322
+ "INVALID": "red",
323
+ "TAMPERED": "red",
324
+ }.get(status, "white")
325
+ console.print(f"[{color}]{status}[/{color}]")
326
+ console.print(message)
327
+
328
+ if status != "VALID":
329
+ raise SystemExit(1)
330
+
331
+
332
+ def verify_main() -> None:
333
+ """Standalone entry point for trproof-verify."""
334
+ # Delegate to the verify command; Click handles argv.
335
+ import sys
336
+
337
+ sys.argv[0] = "trproof-verify"
338
+ verify.main(standalone_mode=True)
339
+
340
+
341
+ if __name__ == "__main__":
342
+ main()
@@ -0,0 +1,30 @@
1
+ """Collectors package (Phase 2+)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from trproof.models import ScanBundle
6
+
7
+
8
+ def merge_scan_bundles(*bundles: ScanBundle) -> ScanBundle:
9
+ """Merge AD and Entra scan bundles into one, deduplicating nodes by id."""
10
+ nodes_by_id: dict[str, object] = {}
11
+ edges: list = []
12
+ findings: list = []
13
+ warnings: list = []
14
+ metadata: dict = {}
15
+
16
+ for bundle in bundles:
17
+ for node in bundle.nodes:
18
+ nodes_by_id.setdefault(node.id, node)
19
+ edges.extend(bundle.edges)
20
+ findings.extend(bundle.findings)
21
+ warnings.extend(bundle.warnings)
22
+ metadata.update(bundle.metadata)
23
+
24
+ return ScanBundle(
25
+ nodes=list(nodes_by_id.values()),
26
+ edges=edges,
27
+ findings=findings,
28
+ warnings=warnings,
29
+ metadata=metadata,
30
+ )