Repository navigation
Expand file tree
/
Copy pathreconpipegui.py
More file actions
4243 lines (3930 loc) · 199 KB
/
Copy pathreconpipegui.py
File metadata and controls
4243 lines (3930 loc) · 199 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import argparse
import inspect
import json
import os
import queue
import re
import signal
import subprocess
import sys
import threading
import time
import zipfile
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
import asyncio
HERE = Path(__file__).resolve().parent
if str(HERE) not in sys.path:
sys.path.insert(0, str(HERE))
try:
from nicegui import app, ui
except ImportError:
print(
"NiceGUI is required for the GUI.\n"
" pip3 install nicegui\n"
" or: pip3 install -r requirements.txt",
file=sys.stderr,
)
sys.exit(1)
try:
from nicegui import events as ng_events
except Exception:
ng_events = None
try:
from nicegui import run as nicegui_run
except Exception:
nicegui_run = None
async def run_io_bound(func: Any, *args: Any, **kwargs: Any) -> Any:
"""Run a blocking function off the UI loop (NiceGUI 1.x–3.x)."""
bound = getattr(ui, "run_io_bound", None)
if callable(bound):
return await bound(func, *args, **kwargs)
io_bound = getattr(nicegui_run, "io_bound", None) if nicegui_run is not None else None
if callable(io_bound):
return await io_bound(func, *args, **kwargs)
loop = asyncio.get_running_loop()
if kwargs:
return await loop.run_in_executor(None, lambda: func(*args, **kwargs))
return await loop.run_in_executor(None, func, *args)
import reconpipe as rp
ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
FINDINGS_RENDER_CAP = 80
CONSOLE_PUSH_CHARS = 800
DOMAIN_RE = re.compile(
r"^(?=.{1,253}$)(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.(?!-)[A-Za-z0-9-]{1,63}(?<!-))+$"
)
ARTIFACT_FILES = [
"findings.json",
"valid_keys.json",
"informational.json",
"source_map_exposures.json",
"quarantine.json",
"summary.txt",
"results.sarif",
"subdomains.txt",
"live_hosts.txt",
"files_to_scan.txt",
"scan_status.json",
"hits/summary.txt",
"hits/findings.json",
"hits/valid_keys.json",
"hits/INDEX.txt",
"report.html",
"report.md",
"findings.csv",
"findings_diff.json",
"report.jsonld",
"pipeline_metrics.json",
"js_endpoints.json",
"js_secrets.json",
"unique_findings.json",
"checkpoint.json",
"export_hackerone.md",
"export_jira.md",
"findings_stream.jsonl",
"wayback_sources.json",
"reconstructed_sources.json",
"js_history.json",
"js_history_removed.json",
"sensitive_paths.txt",
"docker_hub_images.json",
"image_refs.json",
"ai_verdict.json",
"gitleaks.json",
"gitleaks_git.json",
"spray_urls.txt",
"jsleak.txt",
"jsleak_secrets.json",
"code_search_urls.txt",
"ci_logs.json",
"paste_urls.json",
"buckets.json",
"openapi_urls.txt",
"download_etag.json",
"remediation.md",
"llm_report.json",
"vendors.json",
"vendors.html",
"report_pentest.md",
"report_executive.md",
"report_executive.html",
"findings_report.html",
]
ARTIFACT_ZIP_NAME = "reconpipe_artifacts.zip"
def _artifact_rel_ok(rel: str) -> bool:
name = (rel or "").replace("\\", "/").lstrip("/")
if not name or name.startswith("../") or "/../" in f"/{name}/" or name.endswith("/.."):
return False
allowed = {n.replace("\\", "/") for n in ARTIFACT_FILES}
allowed.add(ARTIFACT_ZIP_NAME)
return name in allowed
def resolve_workspace_file(workspace: Path, rel: str) -> Optional[Path]:
"""Return an existing artifact under workspace, or None if off-limits/missing."""
name = (rel or "").replace("\\", "/").lstrip("/")
if not _artifact_rel_ok(name):
return None
try:
ws = Path(workspace).expanduser().resolve()
path = (ws / name).resolve()
path.relative_to(ws)
except (OSError, ValueError):
return None
return path if path.is_file() else None
def existing_artifact_files(workspace: Path) -> List[Tuple[str, Path]]:
ws = Path(workspace)
rows: List[Tuple[str, Path]] = []
for name in ARTIFACT_FILES:
path = resolve_workspace_file(ws, name)
if path is not None:
rows.append((name.replace("\\", "/"), path))
return rows
def write_artifacts_zip(workspace: Path) -> Optional[Path]:
"""Zip existing report artifacts (not downloaded_files/)."""
files = existing_artifact_files(workspace)
if not files:
return None
dest = Path(workspace) / ARTIFACT_ZIP_NAME
with zipfile.ZipFile(dest, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for name, path in files:
zf.write(path, arcname=name)
return dest if dest.is_file() else None
def trigger_browser_download(path: Path, filename: Optional[str] = None) -> bool:
"""Send a workspace file to the browser (NiceGUI 1.x–3.x)."""
if not path.is_file():
ui.notify(f"File not found: {path.name}", type="negative")
return False
name = filename or path.name
download = getattr(ui, "download", None)
if download is None:
ui.notify("Download is not available in this NiceGUI build", type="negative")
return False
file_fn = getattr(download, "file", None)
try:
if callable(file_fn):
try:
file_fn(path, filename=name)
except TypeError:
file_fn(path)
elif callable(download):
try:
download(path, filename=name)
except TypeError:
download(path.read_bytes(), name)
else:
ui.notify("Download is not available in this NiceGUI build", type="negative")
return False
ui.notify(f"Downloading {name}", type="positive")
return True
except Exception as exc:
ui.notify(f"Download failed: {exc}", type="negative")
return False
def strip_ansi(text: str) -> str:
return ANSI_RE.sub("", text or "")
def redact_secret(value: str, reveal: bool = False) -> str:
if not value:
return ""
if reveal or len(value) <= 8:
return value if reveal else ("*" * len(value))
return f"{value[:4]}…{value[-4:]}" if not reveal else value
def load_json_list(path: Path) -> List[Dict]:
if not path.is_file():
return []
try:
data = json.loads(path.read_text(encoding="utf-8", errors="ignore"))
except Exception:
return []
return data if isinstance(data, list) else []
def load_jsonl_list(path: Path, limit: int = 2500) -> List[Dict]:
if not path.is_file():
return []
rows: List[Dict] = []
try:
text = path.read_text(encoding="utf-8", errors="ignore")
lines = text.splitlines()
if limit and len(lines) > limit:
lines = lines[-limit:]
for line in lines:
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
except Exception:
continue
if isinstance(obj, dict):
rows.append(obj)
except Exception:
return []
return rows
def finding_identity(row: Dict) -> Tuple[Any, Any, Any]:
return (row.get("hash"), row.get("type"), row.get("key"))
def merge_finding_rows(dst: List[Dict], incoming: Iterable[Dict]) -> int:
"""Upsert streamed/workspace findings. Returns new + updated count."""
if not incoming:
return 0
index = {finding_identity(f): i for i, f in enumerate(dst)}
changed = 0
for item in incoming:
if not isinstance(item, dict):
continue
ident = finding_identity(item)
if ident in index and (ident[0] or ident[2]):
i = index[ident]
merged = dict(dst[i])
merged.update(item)
if merged != dst[i]:
dst[i] = merged
changed += 1
continue
dst.append(item)
index[ident] = len(dst) - 1
changed += 1
return changed
def workspace_file_sig(path: Path) -> Tuple[int, int]:
try:
st = path.stat()
return (int(getattr(st, "st_mtime_ns", int(st.st_mtime * 1_000_000_000))), int(st.st_size))
except OSError:
return (0, 0)
def ingest_workspace_findings(workspace: Path) -> int:
"""Merge live stream + JSON artifacts into STATE. Returns how many rows changed."""
ws = Path(workspace)
n = 0
n += merge_finding_rows(STATE.findings, load_jsonl_list(ws / "findings_stream.jsonl"))
n += merge_finding_rows(STATE.findings, load_json_list(ws / "unique_findings.json"))
n += merge_finding_rows(STATE.findings, load_json_list(ws / "findings.json"))
n += merge_finding_rows(STATE.informational, load_json_list(ws / "informational.json"))
n += merge_finding_rows(STATE.exposures, load_json_list(ws / "source_map_exposures.json"))
return n
def load_scan_status(path: Path) -> Dict[str, Any]:
if not path.is_file():
return {}
try:
data = json.loads(path.read_text(encoding="utf-8", errors="ignore"))
except Exception:
return {}
return data if isinstance(data, dict) else {}
_LINE_CACHE: Dict[str, tuple] = {}
def count_lines(path: Path) -> int:
"""Count non-empty lines, cached by size+mtime so the GUI can poll cheaply."""
try:
st = path.stat()
except OSError:
return 0
key = str(path)
stamp = (int(getattr(st, "st_mtime_ns", int(st.st_mtime * 1e9))), st.st_size)
cached = _LINE_CACHE.get(key)
if cached and cached[0] == stamp:
return cached[1]
n = 0
try:
with path.open("rb") as fh:
while True:
chunk = fh.read(1024 * 1024)
if not chunk:
break
n += chunk.count(b"\n")
except OSError:
return 0
_LINE_CACHE[key] = (stamp, n)
return n
def default_output_dir(domain: str) -> Path:
safe = (domain or "target").replace(".", "_")
env = (os.environ.get("RECONPIPE_WORKDIR") or "").strip()
root = Path(env) if env else HERE
return root / f"recon_{safe}"
APK_SUFFIXES = (".apk", ".xapk", ".apkm", ".aab", ".apks")
IPA_SUFFIXES = (".ipa",)
def work_root() -> Path:
env = (os.environ.get("RECONPIPE_WORKDIR") or "").strip()
return Path(env) if env else HERE
def running_in_docker() -> bool:
if (os.environ.get("RECONPIPE_WORKDIR") or "").strip():
return True
try:
return Path("/.dockerenv").exists()
except OSError:
return False
def classify_mobile_path(raw: str) -> str:
path = (raw or "").strip().strip('"').strip("'")
low = path.lower()
if low.endswith(IPA_SUFFIXES):
return "ipa"
if low.endswith(APK_SUFFIXES):
return "apk"
return ""
def parse_mobile_paths(text: str) -> Tuple[List[str], List[str]]:
apk: List[str] = []
ipa: List[str] = []
for ln in (text or "").splitlines():
raw = ln.strip().strip('"').strip("'")
if not raw:
continue
kind = classify_mobile_path(raw)
if kind == "apk":
apk.append(raw)
elif kind == "ipa":
ipa.append(raw)
return apk, ipa
def split_mobile_file_list(paths: List[str]) -> Tuple[List[str], List[str]]:
apk: List[str] = []
ipa: List[str] = []
for raw in paths or []:
kind = classify_mobile_path(raw)
if kind == "apk":
apk.append(raw.strip().strip('"').strip("'"))
elif kind == "ipa":
ipa.append(raw.strip().strip('"').strip("'"))
return apk, ipa
def sanitize_upload_name(name: str) -> str:
base = Path(name or "app.bin").name
cleaned = re.sub(r"[^a-zA-Z0-9._-]", "_", base).strip("._") or "app.bin"
return cleaned[:180]
def upload_event_name(e: Any) -> str:
"""Filename from NiceGUI 2 (e.name) or 3 (e.file.name)."""
file_obj = getattr(e, "file", None)
raw = getattr(file_obj, "name", None) or getattr(e, "name", None) or ""
return str(raw).strip()
async def read_upload_bytes(e: Any) -> bytes:
"""File bytes from NiceGUI 2 (e.content) or 3 (await e.file.read())."""
file_obj = getattr(e, "file", None)
if file_obj is not None:
read = getattr(file_obj, "read", None)
if callable(read):
data = read()
if inspect.isawaitable(data):
data = await data
return data or b""
content = getattr(e, "content", None)
if content is not None and hasattr(content, "read"):
try:
content.seek(0)
except Exception:
pass
return content.read() or b""
return b""
def stage_mobile_bytes(filename: str, data: bytes) -> Path:
dest_dir = work_root() / "mobile_uploads"
dest_dir.mkdir(parents=True, exist_ok=True)
dest = dest_dir / sanitize_upload_name(filename)
dest.write_bytes(data or b"")
return dest
def mobile_path_missing_hint(path: str) -> str:
msg = f"App package not found: {path}"
if running_in_docker():
msg += (
" — this GUI is in Docker and cannot see host paths. "
"Upload the file on the Apps tab, or copy it into scans/ and use /work/<filename>."
)
return msg
def fmt_bytes(n: int) -> str:
"""Human size for the CPU/RAM meter (1024-based)."""
n = max(0, int(n or 0))
for unit, size in (("GB", 1024 ** 3), ("MB", 1024 ** 2), ("KB", 1024)):
if n >= size:
val = n / size
return f"{val:.1f} {unit}" if val < 10 else f"{val:.0f} {unit}"
return f"{n} B"
def parse_proc_stat_cpu_ticks(line: str) -> int:
"""utime+stime from a /proc/<pid>/stat line (field 14+15)."""
rpar = (line or "").rfind(")")
if rpar < 0:
return 0
fields = line[rpar + 1 :].split()
if len(fields) < 13:
return 0
try:
return int(fields[11]) + int(fields[12])
except (TypeError, ValueError):
return 0
def parse_status_vmrss_bytes(text: str) -> int:
for raw in (text or "").splitlines():
if raw.startswith("VmRSS:"):
parts = raw.split()
if len(parts) >= 2:
try:
return int(parts[1]) * 1024
except ValueError:
return 0
return 0
def parse_meminfo_bytes(text: str) -> tuple:
"""Return (MemTotal, MemAvailable) in bytes from /proc/meminfo."""
total = 0
avail = 0
for raw in (text or "").splitlines():
if raw.startswith("MemTotal:"):
parts = raw.split()
if len(parts) >= 2:
total = int(parts[1]) * 1024
elif raw.startswith("MemAvailable:"):
parts = raw.split()
if len(parts) >= 2:
avail = int(parts[1]) * 1024
return total, avail
def usage_html(snap: Dict[str, Any]) -> str:
cpu = float(snap.get("cpu_pct") or 0.0)
rss = int(snap.get("rss_bytes") or 0)
total = int(snap.get("host_total") or 0)
cpu_w = max(0, min(100, int(round(cpu))))
ram_w = 0
if total > 0:
ram_w = max(0, min(100, int(round(rss / total * 100.0))))
ram = fmt_bytes(rss)
if total:
ram = f"{ram} / {fmt_bytes(total)}"
cpu_cls = "hot" if cpu >= 85 else "ok"
ram_cls = "hot" if ram_w >= 85 else "ok"
pids = int(snap.get("pids") or 0)
return (
f'<div class="rp-usage" title="ReconPipe GUI + scan tools ({pids} processes)">'
f'<div class="rp-usage-item"><span class="k">CPU</span>'
f'<span class="bar"><span class="{cpu_cls}" style="width:{cpu_w}%"></span></span>'
f'<span class="v">{cpu:.0f}%</span></div>'
f'<div class="rp-usage-item"><span class="k">RAM</span>'
f'<span class="bar"><span class="{ram_cls}" style="width:{ram_w}%"></span></span>'
f'<span class="v">{ram}</span></div></div>'
)
class ResourceMonitor:
"""CPU % of the machine and RSS for this GUI + the scan process tree."""
_PID_CAP = 400
def __init__(self) -> None:
self._prev_t = 0.0
self._prev_cpu = 0.0
self._ncpu = max(1, os.cpu_count() or 1)
self._clk = 100.0
try:
self._clk = float(os.sysconf("SC_CLK_TCK")) or 100.0
except (AttributeError, ValueError, OSError):
pass
self._linux = Path("/proc/self/stat").is_file()
self._win = os.name == "nt"
def snapshot(self, extra_pid: Optional[int] = None) -> Dict[str, Any]:
pids = self._tree_pids(os.getpid())
if extra_pid:
try:
pids.update(self._tree_pids(int(extra_pid)))
except (TypeError, ValueError):
pass
cpu_sec = 0.0
rss = 0
for pid in pids:
cpu_sec += self._cpu_seconds(pid)
rss += self._rss_bytes(pid)
now = time.monotonic()
cpu_pct = 0.0
if self._prev_t and now > self._prev_t:
dcpu = max(0.0, cpu_sec - self._prev_cpu)
cpu_pct = (dcpu / (now - self._prev_t)) / self._ncpu * 100.0
cpu_pct = max(0.0, min(100.0, cpu_pct))
self._prev_t = now
self._prev_cpu = cpu_sec
host_total, host_avail = self._host_ram()
return {
"cpu_pct": cpu_pct,
"rss_bytes": rss,
"host_total": host_total,
"host_avail": host_avail,
"pids": len(pids),
}
def _tree_pids(self, root: int) -> Set[int]:
found: Set[int] = set()
if root <= 0:
return found
stack = [root]
while stack and len(found) < self._PID_CAP:
pid = stack.pop()
if pid in found:
continue
found.add(pid)
for child in self._children(pid):
if child not in found:
stack.append(child)
return found
def _children(self, pid: int) -> List[int]:
if self._linux:
return self._linux_children(pid)
if self._win:
return self._win_children(pid)
return []
def _linux_children(self, pid: int) -> List[int]:
kids: List[int] = []
task = Path(f"/proc/{pid}/task")
try:
for tid_dir in task.iterdir():
try:
text = (tid_dir / "children").read_text(encoding="ascii", errors="ignore")
except OSError:
continue
for tok in text.split():
try:
kids.append(int(tok))
except ValueError:
pass
except OSError:
pass
return kids
def _win_children(self, pid: int) -> List[int]:
try:
import ctypes
from ctypes import wintypes
except Exception:
return []
TH32CS_SNAPPROCESS = 0x00000002
class PROCESSENTRY32W(ctypes.Structure):
_fields_ = [
("dwSize", wintypes.DWORD),
("cntUsage", wintypes.DWORD),
("th32ProcessID", wintypes.DWORD),
("th32DefaultHeapID", ctypes.POINTER(ctypes.c_ulong)),
("th32ModuleID", wintypes.DWORD),
("cntThreads", wintypes.DWORD),
("th32ParentProcessID", wintypes.DWORD),
("pcPriClassBase", ctypes.c_long),
("dwFlags", wintypes.DWORD),
("szExeFile", wintypes.WCHAR * 260),
]
k32 = ctypes.windll.kernel32
snap = k32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
if snap == -1 or snap == 0xFFFFFFFF:
return []
kids: List[int] = []
try:
entry = PROCESSENTRY32W()
entry.dwSize = ctypes.sizeof(PROCESSENTRY32W)
if not k32.Process32FirstW(snap, ctypes.byref(entry)):
return []
while True:
if int(entry.th32ParentProcessID) == int(pid):
kids.append(int(entry.th32ProcessID))
if not k32.Process32NextW(snap, ctypes.byref(entry)):
break
finally:
k32.CloseHandle(snap)
return kids
def _cpu_seconds(self, pid: int) -> float:
if self._linux:
try:
line = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="ignore")
except OSError:
return 0.0
return parse_proc_stat_cpu_ticks(line) / self._clk
if self._win:
return self._win_cpu_seconds(pid)
return 0.0
def _rss_bytes(self, pid: int) -> int:
if self._linux:
try:
text = Path(f"/proc/{pid}/status").read_text(encoding="utf-8", errors="ignore")
except OSError:
return 0
return parse_status_vmrss_bytes(text)
if self._win:
return self._win_rss_bytes(pid)
return 0
def _host_ram(self) -> tuple:
if self._linux:
try:
text = Path("/proc/meminfo").read_text(encoding="utf-8", errors="ignore")
except OSError:
return 0, 0
return parse_meminfo_bytes(text)
if self._win:
return self._win_host_ram()
return 0, 0
def _win_cpu_seconds(self, pid: int) -> float:
try:
import ctypes
from ctypes import wintypes
except Exception:
return 0.0
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
k32 = ctypes.windll.kernel32
handle = k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
if not handle:
return 0.0
create = wintypes.FILETIME()
exit_t = wintypes.FILETIME()
kernel = wintypes.FILETIME()
user = wintypes.FILETIME()
try:
if not k32.GetProcessTimes(
handle,
ctypes.byref(create),
ctypes.byref(exit_t),
ctypes.byref(kernel),
ctypes.byref(user),
):
return 0.0
def _sec(ft: Any) -> float:
val = (int(ft.dwHighDateTime) << 32) | int(ft.dwLowDateTime)
return val / 10_000_000.0
return _sec(kernel) + _sec(user)
finally:
k32.CloseHandle(handle)
def _win_rss_bytes(self, pid: int) -> int:
try:
import ctypes
from ctypes import wintypes
except Exception:
return 0
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
k32 = ctypes.windll.kernel32
class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
_fields_ = [
("cb", wintypes.DWORD),
("PageFaultCount", wintypes.DWORD),
("PeakWorkingSetSize", ctypes.c_size_t),
("WorkingSetSize", ctypes.c_size_t),
("QuotaPeakPagedPoolUsage", ctypes.c_size_t),
("QuotaPagedPoolUsage", ctypes.c_size_t),
("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t),
("QuotaNonPagedPoolUsage", ctypes.c_size_t),
("PagefileUsage", ctypes.c_size_t),
("PeakPagefileUsage", ctypes.c_size_t),
("PrivateUsage", ctypes.c_size_t),
]
handle = k32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, pid)
if not handle:
handle = k32.OpenProcess(0x1000, False, pid)
if not handle:
return 0
counters = PROCESS_MEMORY_COUNTERS_EX()
counters.cb = ctypes.sizeof(PROCESS_MEMORY_COUNTERS_EX)
try:
psapi = ctypes.windll.psapi
if psapi.GetProcessMemoryInfo(handle, ctypes.byref(counters), counters.cb):
return int(counters.WorkingSetSize)
except Exception:
return 0
finally:
k32.CloseHandle(handle)
return 0
def _win_host_ram(self) -> tuple:
try:
import ctypes
from ctypes import wintypes
except Exception:
return 0, 0
class MEMORYSTATUSEX(ctypes.Structure):
_fields_ = [
("dwLength", wintypes.DWORD),
("dwMemoryLoad", wintypes.DWORD),
("ullTotalPhys", ctypes.c_uint64),
("ullAvailPhys", ctypes.c_uint64),
("ullTotalPageFile", ctypes.c_uint64),
("ullAvailPageFile", ctypes.c_uint64),
("ullTotalVirtual", ctypes.c_uint64),
("ullAvailVirtual", ctypes.c_uint64),
("ullAvailExtendedVirtual", ctypes.c_uint64),
]
info = MEMORYSTATUSEX()
info.dwLength = ctypes.sizeof(MEMORYSTATUSEX)
if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(info)):
return 0, 0
return int(info.ullTotalPhys), int(info.ullAvailPhys)
def guess_key_types(key: str) -> List[str]:
"""Return pattern types that match a pasted key (longest / most specific first)."""
text = (key or "").strip()
if not text:
return []
hits: List[tuple] = []
for name, pattern in rp.PATTERNS.items():
try:
m = re.search(pattern, text)
except re.error:
continue
if m:
hits.append((len(m.group(0)), name))
hits.sort(reverse=True)
names = [name for _, name in hits]
refined = rp.refine_secret_type(names[0] if names else "", text)
if refined:
names = [refined] + [n for n in names if n != refined]
return names
def validator_type_options() -> List[str]:
return sorted(rp.VALIDATORS.keys())
def validate_form(opts: Dict[str, Any]) -> List[str]:
errors: List[str] = []
domain = rp.normalize_scan_domain(opts.get("domain") or "")
domain_list = (opts.get("domain_list") or "").strip()
if not domain and not domain_list:
errors.append("Target domain is required.")
elif domain and not DOMAIN_RE.match(domain):
errors.append(f"Invalid domain syntax: {domain}")
for label, key in (
("Subdomains file", "subdomains"),
("URL list", "files"),
("Domain list", "domain_list"),
("Exclude patterns", "exclude_pattern"),
("Include patterns", "include_pattern"),
):
path = (opts.get(key) or "").strip()
if path and not Path(path).expanduser().is_file():
errors.append(f"{label} not found: {path}")
for cfg in opts.get("config") or []:
cfg = str(cfg).strip()
if cfg and not Path(cfg).expanduser().is_file():
errors.append(f"Config overlay not found: {cfg}")
try:
conc = int(opts.get("concurrency", 10))
if conc < 1 or conc > 200:
errors.append("Concurrency must be between 1 and 200.")
except (TypeError, ValueError):
errors.append("Concurrency must be an integer.")
try:
gt = int(opts.get("gau_threads", 5))
if gt < 1 or gt > 100:
errors.append("gau threads must be between 1 and 100.")
except (TypeError, ValueError):
errors.append("gau threads must be an integer.")
out = (opts.get("output") or "").strip()
if out:
try:
Path(out).expanduser()
except Exception:
errors.append(f"Invalid output directory: {out}")
for key, label in (("apk", "APK"), ("ipa", "IPA")):
for raw in opts.get(key) or []:
path = str(raw or "").strip()
if not path:
continue
if not Path(path).expanduser().is_file():
errors.append(mobile_path_missing_hint(path))
return errors
# Pipeline worker
class PipelineRunner:
def __init__(self) -> None:
self.proc: Optional[subprocess.Popen] = None
self.thread: Optional[threading.Thread] = None
self.log_q: "queue.Queue[str]" = queue.Queue(maxsize=400)
self.running = False
self.exit_code: Optional[int] = None
self.started_at: Optional[str] = None
self.finished_at: Optional[str] = None
self.command: List[str] = []
self.output_dir: Optional[Path] = None
self.domain: str = ""
self._lock = threading.Lock()
def start(self, opts: Dict[str, Any]) -> None:
with self._lock:
if self.running:
raise RuntimeError("A scan is already running.")
argv = rp.argv_from_options(opts)
domain = (opts.get("domain") or "").strip() or "multi"
out = (opts.get("output") or "").strip()
work = Path(os.environ.get("RECONPIPE_WORKDIR") or HERE)
self.output_dir = Path(out).expanduser() if out else default_output_dir(domain)
self.output_dir.mkdir(parents=True, exist_ok=True)
if not out:
argv += ["--output", str(self.output_dir)]
cmd = [sys.executable, str(HERE / "reconpipe.py"), *argv]
self.command = cmd
self.domain = domain
self.exit_code = None
self.started_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.finished_at = None
self.running = True
env = os.environ.copy()
env["PYTHONUNBUFFERED"] = "1"
env.setdefault("PYTHONIOENCODING", "utf-8")
self.proc = subprocess.Popen(
cmd,
cwd=str(work),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding="utf-8",
errors="replace",
bufsize=1,
env=env,
start_new_session=True,
)
self.thread = threading.Thread(target=self._reader, daemon=True)
self.thread.start()
self.log_q.put(f"[gui] Started: {' '.join(cmd)}")
self.log_q.put(f"[gui] Output directory: {self.output_dir}")
def _offer_log(self, line: str) -> None:
text = strip_ansi((line or "").rstrip("\n"))
if not rp.console_keep_line(text):
return
try:
self.log_q.put_nowait(text)
except queue.Full:
return
def _reader(self) -> None:
assert self.proc is not None
try:
assert self.proc.stdout is not None
for line in self.proc.stdout:
self._offer_log(line)
except Exception as exc:
self._offer_log(f"[gui] Log reader error: {exc}")
finally:
code = self.proc.wait()
self.exit_code = code
self.finished_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.running = False
self._offer_log(f"[gui] Pipeline finished with exit code {code}")
def stop(self) -> None:
with self._lock:
if not self.proc or not self.running:
return
self._offer_log("[gui] Stopping pipeline…")
try:
if os.name == "nt":
self.proc.terminate()
else:
os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)
except Exception:
try:
self.proc.kill()
except Exception:
pass
def drain_logs(self) -> List[str]:
lines: List[str] = []
while len(lines) < 20:
try:
lines.append(self.log_q.get_nowait())
except queue.Empty:
break
return lines
# UI state
class GuiState:
def __init__(self) -> None:
self.runner = PipelineRunner()
self.log_lines: List[str] = []
self.history: List[Dict[str, Any]] = []
self.findings: List[Dict] = []
self.informational: List[Dict] = []
self.exposures: List[Dict] = []
self.revealed: set = set()
self.selected_idx: Optional[int] = None
self.last_test_note: str = ""
self.workspace: Optional[Path] = None
self.domain: str = ""
self.shopify_domain: str = ""
self.config_overlays: List[str] = []
self.filter_type: str = "All"
self.filter_status: str = "All"
self.filter_tier: str = "All"
self.filter_query: str = ""
self.min_confidence: int = 0
self.filter_severity: str = "All"
self.filter_company: str = "All"
self.filter_file: str = ""
self.scan_queue: List[str] = []