Repository navigation
Expand file tree
/
Copy pathconsole.py
More file actions
885 lines (815 loc) · 35.6 KB
/
Copy pathconsole.py
File metadata and controls
885 lines (815 loc) · 35.6 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
"""Interactive console REPL for StealthOps."""
from __future__ import annotations
import argparse
import os
import re
import shlex
import subprocess
import sys
try:
import readline # noqa: F401 enables arrow-key history for input() on Linux
except ImportError:
pass
from _version import __version__
from core_ops import QueryConfig, StealthQueryEngine, internet_available
from enrichment import EnrichmentManager, PROVIDER_ALIASES
from formatter import (
_c,
color_enabled,
interactive_stdio,
truncate_text,
)
import cache as _cache_module
import time as _time_module
from runner import execute_enrichment_only, execute_query
from tor_engine import TorEngine
from utils import refang
def render_console_banner(
query_engine: StealthQueryEngine,
tor_engine: TorEngine,
tor_ok: bool,
emit_json: bool,
use_color: bool,
) -> str:
title = _c(use_color, f"[ PRIVACY-CENTRIC NETWORK INTELLIGENCE ] v{__version__}", "92")
rule = _c(use_color, " _____________________________________________________________", "90")
art_lines = [
" ____ _ _ _ _ ___ ",
" / ___|| |_ ___ __ _| | |_| |__ / _ \\ _ __ ___ ",
" \\___ \\| __/ _ \\/ _` | | __| '_ \\| | | | '_ \\/ __| ",
" ___) | || __/ (_| | | |_| | | | |_| | |_) \\__ \\ ",
" |____/ \\__\\___|\\__,_|_|\\__|_| |_|\\___/| .__/|___/ ",
" |_| ",
]
art = "\n".join(_c(use_color, line, "36") for line in art_lines)
banner = (
f"{art}\n"
f" {title}\n"
"\n"
f"{render_status_lines(query_engine, tor_engine, tor_ok, emit_json, use_color)}\n"
f"{rule}"
)
from updater import get_update_notice
notice = get_update_notice(use_color)
if notice:
banner += f"\n{notice}"
return banner
def render_status_lines(
query_engine: StealthQueryEngine,
tor_engine: TorEngine,
tor_ok: bool,
emit_json: bool,
use_color: bool,
) -> str:
route = "Stealth" if query_engine.config.route_mode == "stealth" else "Public"
if query_engine.config.route_mode == "public":
tor_status = "Bypassed (Public Mode)"
elif tor_ok:
tor_status = f"Socks Proxy {tor_engine.socks_host}:{tor_engine.socks_port}"
else:
err = truncate_text(tor_engine.last_error or "Unavailable")
tor_status = f"Unavailable ({err})"
block_mode = "On" if query_engine.config.block_non_tor else "Off"
output_mode = "JSON" if emit_json else "Pretty"
route_disp = _c(use_color, route, "96" if route == "Stealth" else "93")
tor_disp = _c(use_color, tor_status, "92" if tor_ok and query_engine.config.route_mode == "stealth" else "93")
block_disp = _c(use_color, block_mode, "91" if block_mode == "On" else "90")
output_disp = _c(use_color, output_mode, "95" if output_mode == "JSON" else "97")
return (
f" > Route Mode ...................... [{route_disp}]\n"
f" > TOR Routing ..................... [{tor_disp}]\n"
f" > Block Non-TOR ................... [{block_disp}]\n"
f" > Output Mode ..................... [{output_disp}]"
)
def run_web_background(
args: argparse.Namespace,
host_override: str | None = None,
port_override: int | None = None,
) -> subprocess.Popen:
host = host_override or args.host
port = str(port_override or args.port)
tor_update = args.tor_update
_main_py = os.path.join(os.path.dirname(os.path.abspath(__file__)), "main.py")
if getattr(sys, "frozen", False):
cmd = [sys.executable, "--web", "--host", host, "--port", port, "--tor-update", tor_update]
else:
cmd = [sys.executable, _main_py, "--web", "--host", host, "--port", port, "--tor-update", tor_update]
if args.tor_update_manifest:
cmd.extend(["--tor-update-manifest", args.tor_update_manifest])
if args.prefer_system_tor:
cmd.append("--prefer-system-tor")
return subprocess.Popen(
cmd,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def run_console(args: argparse.Namespace, tor_engine: TorEngine) -> int:
route_mode = args.mode or "public"
emit_json = bool(args.json)
block_non_tor = bool(args.block_non_tor)
include_headers = bool(args.headers)
enrich_selection = str(args.enrich or "off")
use_color = color_enabled(args.no_color)
if args.install_tor:
print("[privacy] starting managed Tor install/update")
message = tor_engine.manage_tor_runtime(force_update=True)
print(f"[privacy] tor_runtime={message}")
tor_ok = tor_engine.ensure_tor() if route_mode == "stealth" else False
if route_mode == "stealth" and not tor_ok and not args.install_tor and not block_non_tor:
tor_ok = _maybe_prompt_install_tor(tor_engine)
query_engine = StealthQueryEngine(
tor_engine,
QueryConfig(block_non_tor=block_non_tor, route_mode=route_mode),
)
enrichment_manager = EnrichmentManager()
os.system("cls" if os.name == "nt" else "clear")
print(render_console_banner(query_engine, tor_engine, tor_ok, emit_json, use_color))
print("")
print("Type 'help' for commands.")
print("")
web_process: subprocess.Popen | None = None
last_target: str = ""
session_history: dict[str, dict] = {} # target -> result data, most recent last
def _print_interrupted() -> None:
sys.stderr.write("\r" + " " * 40 + "\r")
sys.stderr.flush()
print("\ninterrupted")
print("")
def shutdown_web() -> None:
nonlocal web_process
if not web_process:
return
try:
if web_process.poll() is None:
web_process.terminate()
web_process.wait(timeout=2.0)
except Exception:
try:
if web_process.poll() is None:
web_process.kill()
except Exception:
pass
web_process = None
while True:
try:
raw_in = input("stealthops> ")
except EOFError:
shutdown_web()
print("")
return 0
except KeyboardInterrupt:
print("")
continue
if "\x0c" in raw_in and raw_in.replace("\x0c", "").strip() == "":
os.system("cls" if os.name == "nt" else "clear")
print("")
continue
raw = raw_in.strip()
if not raw:
continue
# Re-sync keystore file → os.environ and rebuild the enrichment manager
# so keys saved externally (web UI, another terminal) take effect
# immediately without restarting the console.
if not os.environ.get("SERVER_MODE") and not os.environ.get("TRAINING_MODE"):
try:
from keystore import sync_into_environ as _ks_sync
_ks_sync()
enrichment_manager.reload_keys()
except ImportError:
pass
try:
parts = shlex.split(raw)
except ValueError as exc:
print(f"error: {exc}")
continue
cmd = parts[0].lower()
if cmd in {"exit", "quit"}:
shutdown_web()
return 0
if cmd == "help":
def _h(text: str) -> str:
return _c(use_color, text, "1;96")
print("")
print(f" {_h('Query')}")
print(" <target> run lookup (IP, domain, ASN, or URL)")
print(" defanged indicators accepted (e.g. 8.8[.]8.8, example[.]com)")
print(" last [clear] show or clear last successful target")
print(" reload re-run last query bypassing 6h cache")
print(" full re-display last result with all truncation removed")
print("")
print(f" {_h('Enrichment')}")
print(" enrich <all|off|provider,...> set persistent enrichment mode")
print(" all [target] run all providers now (uses last target if omitted)")
print(" <provider> [target] run single provider (uses last target if omitted)")
print(" providers provider status, keys, aliases, and session usage")
print("")
print(f" {_h('Keys')}")
print(" set-key [provider key] add or update API key (no args = wizard)")
print(" delete-key <provider> remove a key")
print("")
print(f" {_h('Output')}")
print(" json <on|off> toggle JSON output")
print(" headers <on|off> toggle HTTP header inspection")
print(" report [target] [path] save PDF report (default: ~/Downloads)")
print(" bulk [target,target,...] triage indicators to CSV — inline list, file path, or paste mode")
print("")
print(f" {_h('Routing')}")
print(" mode <stealth|public> switch routing mode")
print(" block <on|off> block non-Tor traffic")
print(" tor install|status Tor runtime management")
print("")
print(f" {_h('Session')}")
print(" web [host] [port] start web server in background")
print(" status print console status")
print(" clear / version / update utility commands")
print(" exit quit")
print("")
continue
if cmd == "version":
print(f"StealthOps {__version__}")
print("")
continue
if cmd == "update":
from updater import do_update
try:
new_tag = do_update(use_color)
if new_tag:
try:
ans = input(f" Restart now to use {new_tag}? [y/N] ").strip().lower()
except (EOFError, KeyboardInterrupt):
ans = ""
if ans == "y":
import os as _os
_os.execv(sys.executable, sys.argv)
except KeyboardInterrupt:
_print_interrupted()
continue
if cmd == "keys":
import os as _os
if _os.environ.get("SERVER_MODE"):
print("In SERVER_MODE — manage keys via the web UI at /settings")
print("")
continue
from keystore import get_all as _ks_all
_key_data = _ks_all()
for line in enrichment_manager.format_provider_status_lines(use_color=use_color, key_data=_key_data):
print(line)
continue
if cmd == "set-key":
import os as _os
if _os.environ.get("SERVER_MODE"):
print("In SERVER_MODE — manage keys via the web UI at /settings")
print("")
continue
if len(parts) == 1:
from keystore import run_setup_wizard
run_setup_wizard()
elif len(parts) == 3:
from keystore import set_key as _ks_set, set_config as _ks_set_cfg, WIZARD_ORDER as _WO, _CONFIG_BY_NAME as _CFG
provider_arg = parts[1].lower()
if provider_arg in _CFG:
if _ks_set_cfg(provider_arg, parts[2]):
print(f"config saved for {parts[1]}")
else:
print(f"error: could not save config for '{parts[1]}'")
elif provider_arg not in _WO:
print(f"error: unknown provider or config '{parts[1]}'")
known = list(_WO) + list(_CFG.keys())
print(f" known: {', '.join(known)}")
elif _ks_set(provider_arg, parts[2]):
print(f"key saved for {parts[1]}")
else:
print(f"error: could not save key for '{parts[1]}'")
else:
print("usage: set-key [provider key]")
print("")
continue
if cmd == "delete-key":
import os as _os
if _os.environ.get("SERVER_MODE"):
print("In SERVER_MODE — manage keys via the web UI at /settings")
print("")
continue
if len(parts) != 2:
print("usage: delete-key <provider>")
print("")
continue
from keystore import delete_key as _ks_del, delete_config as _ks_del_cfg, WIZARD_ORDER as _WO, _CONFIG_BY_NAME as _CFG
provider_arg = parts[1].lower()
if provider_arg in _CFG:
_ks_del_cfg(provider_arg)
print(f"config cleared for {parts[1]}")
print("")
continue
if provider_arg not in _WO:
print(f"error: unknown provider or config '{parts[1]}'")
known = list(_WO) + list(_CFG.keys())
print(f" known: {', '.join(known)}")
elif _ks_del(provider_arg):
print(f"key removed for {parts[1]}")
else:
print(f"error: could not remove key for '{parts[1]}'")
print("")
continue
if cmd == "last":
if len(parts) == 1:
print(f"last target: {last_target or '-'}")
print("")
continue
if len(parts) == 2 and parts[1].lower() == "clear":
last_target = ""
print("last target cleared")
print("")
continue
print("usage: last [clear]")
print("")
continue
if cmd == "full":
if not last_target or last_target not in session_history:
print("no query results in this session — run a query first")
print("")
continue
from formatter import colorize_report, format_cli_report
data = session_history[last_target]
print(colorize_report(format_cli_report(data, full=True), use_color))
print("")
continue
if cmd in ("providers", "quota"):
import os as _os
_key_data = None
if not _os.environ.get("SERVER_MODE"):
from keystore import get_all as _ks_all
_key_data = _ks_all()
for line in enrichment_manager.format_provider_status_lines(use_color=use_color, key_data=_key_data):
print(line)
continue
if cmd == "enrich":
if len(parts) != 2:
print("usage: enrich <all|off|provider,...>")
print("")
continue
enrich_selection = parts[1].strip().lower()
resolved = enrichment_manager.resolve_requested(enrich_selection)
print(f"enrichment selection: {enrich_selection}")
print(f"resolved providers: {', '.join(resolved) if resolved else '-'}")
print("")
continue
if cmd == "all":
if len(parts) == 2:
target = refang(parts[1])
elif len(parts) == 1 and last_target:
target = last_target
print(f"[notice] using last target: {target}")
elif len(parts) == 1:
print("usage: all <target> (or run a target first, then type 'all')")
print("")
continue
else:
print("usage: all [target]")
print("")
continue
try:
rc, _enrich = execute_enrichment_only(enrichment_manager, target, "all-enabled", emit_json, use_color=use_color)
except KeyboardInterrupt:
_print_interrupted()
continue
if rc == 0:
last_target = target
if _enrich and target in session_history:
stored_enrich = session_history[target].setdefault("enrichment", {
"enabled": True, "selection": [], "resolved": [], "skipped": [], "providers": {},
})
stored_enrich["enabled"] = True
stored_enrich.setdefault("providers", {}).update(_enrich.get("providers", {}))
for key in ("selection", "resolved"):
bucket = stored_enrich.setdefault(key, [])
for item in _enrich.get(key, []):
if item not in bucket:
bucket.append(item)
print("")
continue
if cmd == "clear":
os.system("cls" if os.name == "nt" else "clear")
print("")
continue
if cmd == "web":
host = args.host
port = args.port
if len(parts) >= 2:
host = parts[1]
if len(parts) >= 3:
try:
port = int(parts[2])
except ValueError:
print("usage: web [host] [port]")
print("")
continue
if len(parts) > 3:
print("usage: web [host] [port]")
print("")
continue
if web_process and web_process.poll() is None:
print("web server already running in background")
print("")
continue
if not internet_available(timeout=1.0):
print("[notice] internet connectivity check failed; web UI will start but queries may fail until connectivity returns")
print(f"Starting web server in background on {host}:{port}")
print("")
web_process = run_web_background(args, host_override=host, port_override=port)
print(f"[web] pid={web_process.pid} url=http://{host}:{port}")
print("")
continue
if cmd == "banner":
print(render_console_banner(query_engine, tor_engine, tor_ok, emit_json, use_color))
print("")
continue
if cmd == "status":
print(render_status_lines(query_engine, tor_engine, tor_ok, emit_json, use_color))
print("")
continue
if cmd == "query":
if len(parts) < 2:
print("usage: query <target>")
print("")
continue
target = refang(parts[1])
_cache_hit = _cache_module.get(target, "full")
if _cache_hit is not None:
_cached_data, _cached_ts = _cache_hit
if include_headers and _cached_data.get("headers", {}).get("skipped"):
_headers_result = query_engine.header_inspect(target)
_cached_data = dict(_cached_data)
_cached_data["headers"] = _headers_result
_cache_module.put(target, "full", _cached_data)
if emit_json:
import json as _json
print(_json.dumps(_cached_data, indent=2))
else:
from formatter import format_cli_report, colorize_report
print(colorize_report(format_cli_report(_cached_data), use_color))
_age_m = int((_time_module.time() - _cached_ts) / 60)
_age_s = f"{_age_m}m" if _age_m < 60 else f"{_age_m // 60}h {_age_m % 60}m"
print(f"[cached {_age_s} ago — type 'reload' to refresh]")
last_target = target
session_history.pop(target, None)
session_history[target] = _cached_data
if len(session_history) > 50:
del session_history[next(iter(session_history))]
print("")
continue
try:
rc, _result = execute_query(
query_engine, target, emit_json,
use_color=use_color, include_headers=include_headers,
enrichment_manager=enrichment_manager, enrichment_selection=enrich_selection,
)
except KeyboardInterrupt:
_print_interrupted()
continue
if rc == 0 and _result:
last_target = target
_cache_module.put(target, "full", _result)
session_history.pop(target, None)
session_history[target] = _result
if len(session_history) > 50:
del session_history[next(iter(session_history))]
elif rc == 0:
last_target = target
print("")
continue
provider_cmd = PROVIDER_ALIASES.get(cmd)
if provider_cmd:
if len(parts) == 2:
target = refang(parts[1])
elif len(parts) == 1 and last_target:
target = last_target
print(f"[notice] using last target: {target}")
elif len(parts) == 1:
print(f"usage: {cmd} <target> (or run a target first, then use {cmd})")
print("")
continue
else:
print(f"usage: {cmd} [target]")
print("")
continue
try:
rc, _enrich = execute_enrichment_only(enrichment_manager, target, provider_cmd, emit_json, use_color=use_color)
except KeyboardInterrupt:
_print_interrupted()
continue
if rc == 0:
last_target = target
if _enrich and target in session_history:
stored_enrich = session_history[target].setdefault("enrichment", {
"enabled": True, "selection": [], "resolved": [], "skipped": [], "providers": {},
})
stored_enrich["enabled"] = True
stored_enrich.setdefault("providers", {}).update(_enrich.get("providers", {}))
for key in ("selection", "resolved"):
bucket = stored_enrich.setdefault(key, [])
for item in _enrich.get(key, []):
if item not in bucket:
bucket.append(item)
print("")
continue
if cmd == "mode":
if len(parts) != 2 or parts[1].lower() not in {"stealth", "public"}:
print("usage: mode <stealth|public>")
print("")
continue
route_mode = parts[1].lower()
query_engine.config.route_mode = route_mode
if route_mode == "stealth":
tor_ok = tor_engine.ensure_tor()
if not tor_ok and not query_engine.config.block_non_tor:
tor_ok = _maybe_prompt_install_tor(tor_engine)
else:
tor_ok = False
print(render_status_lines(query_engine, tor_engine, tor_ok, emit_json, use_color))
print("")
continue
if cmd == "tor":
if len(parts) != 2 or parts[1].lower() not in {"install", "status"}:
print("usage: tor <install|status>")
print("")
continue
action = parts[1].lower()
if action == "install":
print("[privacy] starting managed Tor install/update")
try:
message = tor_engine.manage_tor_runtime(force_update=True)
except KeyboardInterrupt:
_print_interrupted()
continue
print(f"[privacy] tor_runtime={message}")
tor_ok = tor_engine.ensure_tor() if query_engine.config.route_mode == "stealth" else False
print(render_status_lines(query_engine, tor_engine, tor_ok, emit_json, use_color))
else:
if query_engine.config.route_mode == "stealth":
tor_ok = tor_engine.ensure_tor()
print(render_status_lines(query_engine, tor_engine, tor_ok, emit_json, use_color))
if tor_engine.last_update_message:
print(f"[privacy] tor_runtime={tor_engine.last_update_message}")
if tor_engine.last_error:
print(f"[privacy] notice={tor_engine.last_error}")
print("")
continue
if cmd == "block":
if len(parts) != 2 or parts[1].lower() not in {"on", "off"}:
print("usage: block <on|off>")
print("")
continue
block_non_tor = parts[1].lower() == "on"
query_engine.config.block_non_tor = block_non_tor
print(render_status_lines(query_engine, tor_engine, tor_ok, emit_json, use_color))
print("")
continue
if cmd == "json":
if len(parts) != 2 or parts[1].lower() not in {"on", "off"}:
print("usage: json <on|off>")
print("")
continue
emit_json = parts[1].lower() == "on"
print(render_status_lines(query_engine, tor_engine, tor_ok, emit_json, use_color))
print("")
continue
if cmd == "headers":
if len(parts) != 2 or parts[1].lower() not in {"on", "off"}:
print("usage: headers <on|off>")
print("")
continue
include_headers = parts[1].lower() == "on"
print(f"http headers: {'on' if include_headers else 'off'}")
print("")
continue
if cmd == "reload":
if not last_target:
print("no previous query — run a query first")
print("")
continue
target = last_target
try:
rc, _result = execute_query(
query_engine, target, emit_json,
use_color=use_color, include_headers=include_headers,
enrichment_manager=enrichment_manager, enrichment_selection=enrich_selection,
)
except KeyboardInterrupt:
_print_interrupted()
continue
if rc == 0 and _result:
last_target = target
_cache_module.put(target, "full", _result)
session_history.pop(target, None)
session_history[target] = _result
if len(session_history) > 10:
del session_history[next(iter(session_history))]
print("")
continue
if cmd == "report":
out_path_arg: str | None = None
target_arg: str | None = None
if len(parts) == 2:
arg = parts[1]
if "/" in arg or "\\" in arg or arg.lower().endswith(".pdf"):
out_path_arg = arg
else:
target_arg = arg
elif len(parts) == 3:
target_arg = parts[1]
out_path_arg = parts[2]
elif len(parts) > 3:
print("usage: report [target] [path]")
print("")
continue
if target_arg is not None:
if target_arg not in session_history:
print(f"error: no cached result for '{target_arg}' — run a query first")
print("")
continue
report_target = target_arg
report_data = session_history[target_arg]
elif not session_history:
print("no query results in this session — run a query first")
print("")
continue
elif len(session_history) == 1:
report_target = next(iter(session_history))
report_data = session_history[report_target]
else:
targets_rev = list(reversed(list(session_history.keys())))
print("Select indicator for report:")
for i, t in enumerate(targets_rev, 1):
suffix = _c(use_color, " (most recent)", "90") if i == 1 else ""
print(f" {_c(use_color, str(i), '1;93')}. {t}{suffix}")
print("")
try:
pick = input("Enter number [Enter for most recent]: ").strip()
except EOFError:
print("")
continue
if not pick:
report_target = targets_rev[0]
else:
try:
idx = int(pick) - 1
if 0 <= idx < len(targets_rev):
report_target = targets_rev[idx]
else:
print("invalid selection")
print("")
continue
except ValueError:
print("invalid selection")
print("")
continue
report_data = session_history[report_target]
try:
from report import generate_report
print(f"generating report for {report_target}...")
saved = generate_report(
target=report_target,
result=report_data,
out_path=out_path_arg,
route_mode=query_engine.config.route_mode,
)
print(f"report saved: {_c(use_color, str(saved), '92')}")
except KeyboardInterrupt:
_print_interrupted()
continue
except RuntimeError as exc:
print(f"error: {exc}")
except Exception as exc:
print(f"error generating report: {exc}")
print("")
continue
if cmd == "bulk":
if len(parts) >= 2:
# Single arg that is an existing file → read line by line
if len(parts) == 2 and os.path.isfile(parts[1]):
try:
with open(parts[1], encoding="utf-8", errors="replace") as _f:
raw_targets = [ln.strip() for ln in _f if ln.strip()]
except OSError as exc:
print(f"error: cannot read file: {exc}")
print("")
continue
else:
# Inline indicators — split on commas and/or whitespace
raw_targets = [t for t in re.split(r"[,\s]+", " ".join(parts[1:])) if t]
else:
print("Enter indicators (one per line). Blank line when done:")
raw_targets = []
while True:
try:
_line = input(" ").strip()
except (EOFError, KeyboardInterrupt):
print("")
break
if not _line:
break
raw_targets.append(_line)
if not raw_targets:
print("no targets provided")
print("")
continue
seen: set[str] = set()
bulk_targets: list[str] = []
for _t in raw_targets:
_t = refang(_t)
if _t not in seen:
seen.add(_t)
bulk_targets.append(_t)
print(f"running bulk triage for {len(bulk_targets)} indicator(s)...")
def _bulk_progress(done: int, total: int) -> None:
sys.stderr.write(f"\r [{done}/{total}] processing...")
sys.stderr.flush()
from bulk import bulk_query as _bulk_query, write_csv as _write_csv
from pathlib import Path as _Path
try:
_bulk_rows = _bulk_query(
bulk_targets,
query_engine,
enrichment_manager,
enrich_selection=enrich_selection,
force_refresh=False,
on_progress=_bulk_progress,
)
except KeyboardInterrupt:
_print_interrupted()
continue
sys.stderr.write("\r" + " " * 40 + "\r")
sys.stderr.flush()
_downloads = _Path.home() / "Downloads"
_downloads.mkdir(exist_ok=True)
_ts = _time_module.strftime("%Y%m%d-%H%M%S")
_csv_path = _downloads / f"stealthops-bulk-{_ts}.csv"
_write_csv(_bulk_rows, _csv_path)
print(f"saved: {_c(use_color, str(_csv_path), '92')}")
print("")
continue
shorthand_target = refang(raw)
if shorthand_target != raw:
print(f"→ Refanged: {shorthand_target}")
if shorthand_target:
_cache_hit = _cache_module.get(shorthand_target, "full")
if _cache_hit is not None:
_cached_data, _cached_ts = _cache_hit
if include_headers and _cached_data.get("headers", {}).get("skipped"):
_headers_result = query_engine.header_inspect(shorthand_target)
_cached_data = dict(_cached_data)
_cached_data["headers"] = _headers_result
_cache_module.put(shorthand_target, "full", _cached_data)
if emit_json:
import json as _json
print(_json.dumps(_cached_data, indent=2))
else:
from formatter import format_cli_report, colorize_report
print(colorize_report(format_cli_report(_cached_data), use_color))
_age_m = int((_time_module.time() - _cached_ts) / 60)
_age_s = f"{_age_m}m" if _age_m < 60 else f"{_age_m // 60}h {_age_m % 60}m"
print(f"[cached {_age_s} ago — type 'reload' to refresh]")
last_target = shorthand_target
session_history.pop(shorthand_target, None)
session_history[shorthand_target] = _cached_data
if len(session_history) > 50:
del session_history[next(iter(session_history))]
print("")
continue
try:
rc, _result = execute_query(
query_engine, shorthand_target, emit_json,
use_color=use_color, include_headers=include_headers,
enrichment_manager=enrichment_manager, enrichment_selection=enrich_selection,
)
except KeyboardInterrupt:
_print_interrupted()
continue
if rc == 0 and _result:
last_target = shorthand_target
_cache_module.put(shorthand_target, "full", _result)
session_history.pop(shorthand_target, None)
session_history[shorthand_target] = _result
if len(session_history) > 50:
del session_history[next(iter(session_history))]
elif rc == 0:
last_target = shorthand_target
print("")
continue
print("unknown command. type 'help'")
print("")
def _maybe_prompt_install_tor(tor_engine: TorEngine) -> bool:
if not interactive_stdio():
return False
try:
answer = input("Tor is unavailable. Install managed Tor now? [Y/n]: ").strip().lower()
except EOFError:
return False
if answer in ("", "y", "yes"):
print("[privacy] starting managed Tor install/update")
message = tor_engine.manage_tor_runtime(force_update=True)
print(f"[privacy] tor_runtime={message}")
return tor_engine.ensure_tor()
return False