-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathawvs.py
More file actions
4794 lines (4224 loc) · 200 KB
/
Copy pathawvs.py
File metadata and controls
4794 lines (4224 loc) · 200 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
import argparse
import csv
import hashlib
import ipaddress
import json
import logging
import os
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import warnings
from collections import deque
from datetime import datetime
from html import unescape
from urllib.parse import urlparse, urlsplit, urlunsplit
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
warnings.filterwarnings("ignore", message="urllib3 .* doesn't match a supported version!")
import requests
import urllib3
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
DEFAULT_API_KEY = "1986ad8c0a5b3df4d7028d5f3c06e936cb4217b974a8b4f40b1086d31d7e8869e"
DEFAULT_BASE_URL = "https://localhost:3443/api/v1"
DEFAULT_PROFILE_ID = "12"
LOCAL_CONFIG_FILENAME = "awvs.local.json"
TOOL_VERSION = "2026.05.05-sqlmap-followup"
SQLMAP_DEFAULT_THREADS = 5
DEFAULT_WEAK_LOGIN_USERNAME = "admin"
DEFAULT_WEAK_LOGIN_PASSWORD = "123456"
ACTIVE_STATUSES = {"processing", "starting", "queued"}
RUNNING_ONLY_STATUSES = {"processing", "starting"}
FINISHED_STATUSES = {"completed", "aborted", "failed"}
RETRYABLE_ERROR_KEYWORDS = (
"concurrent",
"limit",
"queue",
"worker",
"busy",
"engine",
"temporary",
"timeout",
"503",
"502",
"500",
"429",
)
COMMON_HTTPS_PORTS = {443, 444, 563, 636, 651, 832, 843, 844, 853, 989, 990, 992, 993, 994, 995, 1443, 2443, 3333, 3443, 4433, 4443, 5443, 6443, 7443, 8443, 9443, 10443}
COMMON_HTTP_PORTS = {80, 81, 88, 631, 3000, 3128, 5080, 5601, 6080, 7001, 7002, 7070, 7080, 7088, 8000, 8001, 8008, 8010, 8080, 8081, 8082, 8088, 8090, 8091, 8180, 8181, 8200, 8800, 8880, 8888, 8889, 9000, 9001, 9043, 9060, 9080, 9090, 9091, 9099}
HOST_PORT_RE = re.compile(r"^(?P<host>[A-Za-z0-9._-]+):(?P<port>\d{1,5})$")
HOST_RE = re.compile(r"^(?=.{1,253}\.?$)[A-Za-z0-9](?:[A-Za-z0-9_-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9_-]{0,61}[A-Za-z0-9])?)*\.?$")
PROFILE_ID_RE = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
ROUTE_POLICIES = {"auto", "direct", "http-proxy"}
DEFAULT_SCAN_HTTP_PROXY = ""
DEFAULT_SCAN_HTTP_PROXY_VALUE = "127.0.0.1:7890"
DEFAULT_PRECHECK_SOCKS5 = ""
PRECHECK_CSV_HEADERS = [
"url",
"description",
"selected_route",
"selected_reason",
"risk_level",
"risk_tag",
"direct_ok",
"http_proxy_ok",
"socks5_ok",
"http_attempts",
"details",
]
SEVERITY_NAME_TO_VALUE = {
"info": 0,
"low": 1,
"medium": 2,
"high": 3,
"critical": 4,
}
SEVERITY_VALUE_TO_NAME = {value: key for key, value in SEVERITY_NAME_TO_VALUE.items()}
SQLMAP_REQUEST_DROP_HEADERS = {
"accept-encoding",
"connection",
"content-encoding",
"content-length",
"transfer-encoding",
}
DIRECT_EXPLOIT_KEYWORDS = {
"SQL Injection": ("sql injection", "sql_injection"),
"Command Execution": ("command execution", "os command injection", "code execution", "remote code execution"),
"File Read": ("path traversal", "arbitrary file read", "local file inclusion", "file inclusion"),
"File Write": ("arbitrary file upload", "arbitrary file write"),
"SSRF": ("server side request forgery", "ssrf"),
"XXE": ("xml external entity", "xxe"),
"SSTI": ("server side template injection", "template injection"),
"Deserialization": ("deserialization", "object injection"),
"Auth Bypass": ("authentication bypass", "authorization bypass"),
}
GROUP_SYNC_ATTEMPTS = 5
GROUP_SYNC_DELAY_SECONDS = 2.0
task_tracker = {}
def setup_logger(log_path, verbose=False):
os.makedirs(os.path.dirname(os.path.abspath(log_path)), exist_ok=True)
logger = logging.getLogger("awvs_scheduler")
logger.handlers.clear()
logger.setLevel(logging.DEBUG if verbose else logging.INFO)
logger.propagate = False
formatter = logging.Formatter(
"[%(asctime)s] %(levelname)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
file_handler = logging.FileHandler(log_path, encoding="utf-8")
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
console_handler.setLevel(logging.DEBUG if verbose else logging.INFO)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
return logger
def write_dict_csv(path, fieldnames, rows):
with open(path, "w", encoding="utf-8-sig", newline="") as file_obj:
writer = csv.DictWriter(file_obj, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
def normalize_address(address):
return address.strip().lstrip("\ufeff").rstrip("/")
def format_duration_compact(seconds):
seconds = max(0, int(seconds))
minutes, sec = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
if hours > 0:
return f"{hours}h{minutes:02d}m{sec:02d}s"
if minutes > 0:
return f"{minutes}m{sec:02d}s"
return f"{sec}s"
def build_progress_snapshot(index, total, started_at):
total = max(total, 1)
index = max(0, min(index, total))
percent = (index / total) * 100
elapsed_seconds = max(0.0, time.time() - started_at)
avg_seconds = (elapsed_seconds / index) if index > 0 else 0.0
remaining_seconds = avg_seconds * max(0, total - index)
return {
"index": index,
"total": total,
"percent": percent,
"elapsed_text": format_duration_compact(elapsed_seconds),
"avg_text": format_duration_compact(avg_seconds),
"eta_text": format_duration_compact(remaining_seconds),
}
def chunked(items, size):
for index in range(0, len(items), size):
yield items[index : index + size]
def looks_like_ip_or_hostport(value):
if not value:
return False
try:
ipaddress.ip_address(value)
return True
except ValueError:
pass
return bool(HOST_PORT_RE.match(value))
def looks_like_host(value):
if not value:
return False
host = value.strip().strip("[]").rstrip(".")
if not host or "/" in host or "\\" in host or " " in host:
return False
try:
ipaddress.ip_address(host)
return True
except ValueError:
pass
return bool(HOST_RE.match(host)) and ("." in host or host.lower() == "localhost")
def infer_scheme_from_port(port, default_scheme):
if default_scheme in {"http", "https"}:
return default_scheme
if port in COMMON_HTTPS_PORTS:
return "https"
if port in COMMON_HTTP_PORTS:
return "http"
return "https"
def split_host_port(value):
value = (value or "").strip()
match = HOST_PORT_RE.match(value)
if match:
return match.group("host"), int(match.group("port"))
return value, None
def build_url_for_host(value, scheme, default_scheme="auto"):
host, port = split_host_port(value)
if port is not None and not 1 <= port <= 65535:
return None
if port is not None:
selected_scheme = scheme or infer_scheme_from_port(port, default_scheme)
return f"{selected_scheme}://{host}:{port}"
selected_scheme = scheme or ("https" if default_scheme == "auto" else default_scheme)
return f"{selected_scheme}://{host}"
def normalize_input_target(raw_value, default_scheme):
value = normalize_address(raw_value)
if not value:
return None, "empty"
lowered = value.lower()
if lowered in {"url", "urls", "target", "targets", "address", "domain", "host"}:
return None, "header"
if value.startswith(("http://", "https://")):
return value, None
match = HOST_PORT_RE.match(value)
if match:
port = int(match.group("port"))
if not 1 <= port <= 65535:
return None, "invalid_port"
scheme = infer_scheme_from_port(port, default_scheme)
return f"{scheme}://{value}", None
try:
ipaddress.ip_address(value)
scheme = "https" if default_scheme == "auto" else default_scheme
return f"{scheme}://{value}", None
except ValueError:
pass
if looks_like_host(value):
return build_url_for_host(value, None, default_scheme), None
return None, "unsupported"
def parse_proxy_endpoint(proxy_value):
if not proxy_value:
return None
value = proxy_value.strip()
if "://" in value:
parsed = urlparse(value)
host = parsed.hostname
port = parsed.port
else:
if ":" not in value:
raise RuntimeError(f"代理地址格式无效: {proxy_value}")
host, port_text = value.rsplit(":", 1)
host = host.strip()
port = int(port_text)
if not host or not port:
raise RuntimeError(f"代理地址格式无效: {proxy_value}")
return {"host": host, "port": int(port), "raw": proxy_value}
def parse_target_endpoint(address):
parsed = urlparse(address)
scheme = (parsed.scheme or "https").lower()
host = parsed.hostname
if not host:
raise RuntimeError(f"目标地址无法解析: {address}")
port = parsed.port or (443 if scheme == "https" else 80)
return {"scheme": scheme, "host": host, "port": port, "address": address}
def build_default_description(input_path, line_no, address):
base_name = os.path.splitext(os.path.basename(input_path))[0]
return f"{base_name}-{line_no:04d} {address}"
def build_precheck_cache_root():
return os.path.join(os.getcwd(), "_awvs_precheck_cache")
def build_precheck_cache_name(input_path, suffix="_precheck"):
normalized = os.path.abspath(input_path).lower()
digest = hashlib.sha1(normalized.encode("utf-8", errors="ignore")).hexdigest()[:10]
base_name = safe_filename(os.path.splitext(os.path.basename(input_path))[0] or "targets", max_length=48)
return f"{base_name}{suffix}_{digest}"
def build_default_precheck_dir(input_path, suffix="_precheck"):
return os.path.join(build_precheck_cache_root(), build_precheck_cache_name(input_path, suffix=suffix))
def build_default_precheck_file(input_path):
return os.path.join(build_default_precheck_dir(input_path), "00_全部结果.csv")
def parse_json_safe(response):
try:
return response.json()
except ValueError:
return {}
def format_response_error(response):
data = parse_json_safe(response)
pieces = [f"HTTP {response.status_code}"]
for key in ("code", "reason", "message", "details"):
value = data.get(key)
if value:
if isinstance(value, (dict, list)):
value = json.dumps(value, ensure_ascii=False)
pieces.append(str(value))
if len(pieces) == 1:
text = response.text.strip()
pieces.append(text[:300] if text else "empty response")
return " | ".join(pieces)
def is_retryable_error(message):
lowered = (message or "").lower()
return any(keyword in lowered for keyword in RETRYABLE_ERROR_KEYWORDS)
def resolve_local_config_path():
return os.path.join(os.getcwd(), LOCAL_CONFIG_FILENAME)
def load_local_config():
config_path = resolve_local_config_path()
if not os.path.exists(config_path):
return {}, config_path, None
try:
with open(config_path, "r", encoding="utf-8-sig") as file_obj:
data = json.load(file_obj)
except Exception as exc:
return {}, config_path, f"读取本地配置失败: {exc}"
if not isinstance(data, dict):
return {}, config_path, "读取本地配置失败: 顶层结构不是 JSON 对象"
return data, config_path, None
def apply_local_config(args):
config, config_path, load_error = load_local_config()
explicit = {
"key": args.key is not None,
"url": args.url is not None,
"profile_id": args.profile_id is not None,
"login_url": args.login_url is not None,
"login_username": args.login_username is not None,
"login_password": args.login_password is not None,
"login_sequence": args.login_sequence is not None,
}
if args.key is None:
args.key = config.get("key") or DEFAULT_API_KEY
if args.url is None:
args.url = config.get("url") or DEFAULT_BASE_URL
if args.profile_id is None:
args.profile_id = config.get("profile_id") or DEFAULT_PROFILE_ID
if args.login_url is None:
args.login_url = config.get("login_url") or ""
if args.login_username is None:
args.login_username = config.get("login_username") or ""
if args.login_password is None:
args.login_password = config.get("login_password") or ""
if args.login_sequence is None:
args.login_sequence = config.get("login_sequence") or ""
return config, config_path, explicit, load_error
def save_local_config(current_config, config_path, args, explicit):
updated = dict(current_config or {})
changed = False
if explicit.get("key") and args.key and updated.get("key") != args.key:
updated["key"] = args.key
changed = True
if explicit.get("url") and args.url and updated.get("url") != args.url:
updated["url"] = args.url
changed = True
if explicit.get("profile_id") and args.profile_id and updated.get("profile_id") != args.profile_id:
updated["profile_id"] = args.profile_id
changed = True
if explicit.get("login_url") and updated.get("login_url") != (args.login_url or ""):
updated["login_url"] = args.login_url or ""
changed = True
if explicit.get("login_username") and updated.get("login_username") != (args.login_username or ""):
updated["login_username"] = args.login_username or ""
changed = True
if explicit.get("login_password") and updated.get("login_password") != (args.login_password or ""):
updated["login_password"] = args.login_password or ""
changed = True
if explicit.get("login_sequence") and updated.get("login_sequence") != (args.login_sequence or ""):
updated["login_sequence"] = args.login_sequence or ""
changed = True
if not changed:
return False
with open(config_path, "w", encoding="utf-8") as file_obj:
json.dump(updated, file_obj, ensure_ascii=False, indent=2, sort_keys=True)
if isinstance(current_config, dict):
current_config.clear()
current_config.update(updated)
return True
def save_resolved_profile_id(current_config, config_path, resolved_profile_id):
if not resolved_profile_id:
return False
updated = dict(current_config or {})
if updated.get("profile_id") == resolved_profile_id:
return False
updated["profile_id"] = resolved_profile_id
with open(config_path, "w", encoding="utf-8") as file_obj:
json.dump(updated, file_obj, ensure_ascii=False, indent=2, sort_keys=True)
if isinstance(current_config, dict):
current_config.clear()
current_config.update(updated)
return True
class AwvsClient:
def __init__(self, base_url, api_key, request_timeout):
self.base_url = base_url.rstrip("/")
self.request_timeout = request_timeout
self.session = requests.Session()
self.session.trust_env = False
self.session.headers.update(
{
"X-Auth": api_key,
"Content-Type": "application/json",
}
)
self.session.verify = False
retry = Retry(
total=3,
connect=3,
read=3,
backoff_factor=1,
status_forcelist=(429, 500, 502, 503, 504),
allowed_methods=frozenset({"GET", "HEAD", "OPTIONS"}),
)
adapter = HTTPAdapter(max_retries=retry)
self.session.mount("http://", adapter)
self.session.mount("https://", adapter)
def request(self, method, path, **kwargs):
url = f"{self.base_url}{path}"
kwargs.setdefault("timeout", self.request_timeout)
try:
return self.session.request(method, url, **kwargs)
except requests.RequestException as exc:
raise RuntimeError(f"{method} {path} 请求失败: {exc}") from exc
def iter_paginated(self, path, key, page_size=100):
cursor = 0
while True:
response = self.request("GET", path, params={"l": page_size, "c": cursor})
if response.status_code != 200:
raise RuntimeError(f"{path} 拉取失败: {format_response_error(response)}")
data = parse_json_safe(response)
items = data.get(key, [])
if not items:
break
for item in items:
yield item
if len(items) < page_size:
break
cursor += page_size
def list_targets(self):
return list(self.iter_paginated("/targets", "targets"))
def list_scans(self):
return list(self.iter_paginated("/scans", "scans"))
def list_groups(self):
return list(self.iter_paginated("/target_groups", "groups"))
def iter_cursor_paginated(self, path, key, params=None, page_size=100):
query_params = dict(params or {})
query_params.setdefault("l", page_size)
cursor = None
seen_cursors = set()
while True:
request_params = dict(query_params)
if cursor:
request_params["c"] = cursor
response = self.request("GET", path, params=request_params)
if response.status_code != 200:
raise RuntimeError(f"{path} pull failed: {format_response_error(response)}")
data = parse_json_safe(response)
items = data.get(key, [])
if not items:
break
for item in items:
yield item
pagination = data.get("pagination") or {}
cursors = pagination.get("cursors") or []
next_cursor = cursors[1] if len(cursors) > 1 else None
if not next_cursor or next_cursor in seen_cursors:
break
seen_cursors.add(next_cursor)
cursor = next_cursor
def list_profiles(self):
response = self.request("GET", "/scanning_profiles")
if response.status_code != 200:
raise RuntimeError(f"/scanning_profiles 拉取失败: {format_response_error(response)}")
data = parse_json_safe(response)
for key in ("profiles", "scanning_profiles"):
items = data.get(key)
if isinstance(items, list):
return items
return []
def get_profile(self, profile_ref):
profiles = self.list_profiles()
exact_id = next((p for p in profiles if p.get("profile_id") == profile_ref), None)
if exact_id:
return exact_id
lowered = profile_ref.lower()
exact_name = [p for p in profiles if (p.get("name") or "").lower() == lowered]
if len(exact_name) == 1:
return exact_name[0]
if len(exact_name) > 1:
raise RuntimeError(f"发现多个同名扫描方案: {profile_ref},请改用 profile UUID")
fuzzy_name = [p for p in profiles if lowered in (p.get("name") or "").lower()]
if len(fuzzy_name) == 1:
return fuzzy_name[0]
if len(fuzzy_name) > 1:
names = ", ".join(sorted({p.get('name') or '-' for p in fuzzy_name}))
raise RuntimeError(f"扫描方案匹配到多个名称: {names},请改用更精确的名称或 UUID")
return None
def create_target(self, address, description=""):
payload = {
"address": address,
"description": description,
"criticality": "10",
"type": "default",
}
response = self.request("POST", "/targets", json=payload)
if response.status_code not in (200, 201):
return None, format_response_error(response)
data = parse_json_safe(response)
target_id = data.get("target_id")
if not target_id:
location = response.headers.get("Location", "")
target_id = location.rstrip("/").split("/")[-1] if location else None
if not target_id:
return None, "创建成功但未返回 target_id"
return target_id, None
def create_targets_bulk(self, targets, group_ids=None):
payload = {"targets": targets}
if group_ids:
payload["groups"] = group_ids
response = self.request("POST", "/targets/add", json=payload)
if response.status_code not in (200, 201, 204):
return False, format_response_error(response)
return True, None
def update_target_address(self, target_id, address, description=None):
payload = {"address": address}
if description is not None:
payload["description"] = description
response = self.request("PATCH", f"/targets/{target_id}", json=payload)
if response.status_code not in (200, 204):
raise RuntimeError(f"更新 Target 地址失败: {format_response_error(response)}")
def delete_target(self, target_id):
response = self.request("DELETE", f"/targets/{target_id}")
if response.status_code not in (200, 202, 204, 404):
raise RuntimeError(f"删除 Target 失败: {format_response_error(response)}")
def get_target_configuration(self, target_id):
response = self.request("GET", f"/targets/{target_id}/configuration")
if response.status_code != 200:
raise RuntimeError(f"读取 Target 配置失败: {format_response_error(response)}")
return parse_json_safe(response)
def configure_target_proxy(self, target_id, enabled, proxy_host=None, proxy_port=None, username=None, password=None):
configuration = self.get_target_configuration(target_id)
if enabled:
configuration["proxy"] = {
"enabled": True,
"protocol": "http",
"address": proxy_host,
"port": int(proxy_port),
"username": username or "",
"password": password or "",
}
else:
# AWVS 在 disabled 状态下只接受 {"enabled": false},
# 继续携带空 address/port 会触发 configuration.proxy.address 格式校验。
configuration["proxy"] = {"enabled": False}
response = self.request("PATCH", f"/targets/{target_id}/configuration", json=configuration)
if response.status_code not in (200, 204):
raise RuntimeError(f"更新 Target 代理配置失败: {format_response_error(response)}")
def configure_target_auto_login(self, target_id, login_url, username, password):
configuration = self.get_target_configuration(target_id)
login_config = configuration.get("login") or {}
login_config["kind"] = "automatic"
login_config["credentials"] = {
"enabled": True,
"url": login_url,
"username": username,
"password": password,
}
configuration["login"] = login_config
response = self.request("PATCH", f"/targets/{target_id}/configuration", json=configuration)
if response.status_code not in (200, 204):
raise RuntimeError(f"更新 Target 自动登录配置失败: {format_response_error(response)}")
def upload_target_login_sequence(self, target_id, lsr_path):
file_size = os.path.getsize(lsr_path)
descriptor = {
"name": os.path.basename(lsr_path),
"size": file_size,
}
response = self.request("POST", f"/targets/{target_id}/configuration/login_sequence", json=descriptor)
if response.status_code != 200:
raise RuntimeError(f"创建 Login Sequence 上传会话失败: {format_response_error(response)}")
upload_url = (parse_json_safe(response) or {}).get("upload_url")
if not upload_url:
raise RuntimeError("创建 Login Sequence 上传会话失败: response missing upload_url")
headers = {"Content-Type": "application/octet-stream"}
with open(lsr_path, "rb") as file_obj:
upload_response = self.session.post(upload_url, data=file_obj, headers=headers, timeout=self.request_timeout)
if upload_response.status_code not in (200, 201, 204):
raise RuntimeError(f"上传 Login Sequence 失败: {format_response_error(upload_response)}")
configuration = self.get_target_configuration(target_id)
login_config = configuration.get("login") or {}
login_config["kind"] = "sequence"
configuration["login"] = login_config
apply_response = self.request("PATCH", f"/targets/{target_id}/configuration", json=configuration)
if apply_response.status_code not in (200, 204):
raise RuntimeError(f"启用 Login Sequence 失败: {format_response_error(apply_response)}")
def start_scan(self, target_id, profile_id):
payload = {
"target_id": target_id,
"profile_id": profile_id,
"schedule": {"disable": False, "start_date": None, "time_sensitive": False},
}
response = self.request("POST", "/scans", json=payload)
if response.status_code == 201:
location = response.headers.get("Location", "")
scan_id = location.rstrip("/").split("/")[-1] if location else None
if scan_id:
return scan_id, None
data = parse_json_safe(response)
return data.get("scan_id"), None
return None, format_response_error(response)
def abort_scan(self, scan_id):
response = self.request("POST", f"/scans/{scan_id}/abort")
return response.status_code in (200, 204)
def get_group(self, group_ref):
groups = self.list_groups()
exact_id = next((g for g in groups if g.get("group_id") == group_ref), None)
if exact_id:
return exact_id
lowered = group_ref.lower()
exact_name = [g for g in groups if (g.get("name") or "").lower() == lowered]
if len(exact_name) == 1:
return exact_name[0]
if len(exact_name) > 1:
raise RuntimeError(f"发现多个同名分组: {group_ref},请直接传 group_id")
return None
def create_group(self, group_name):
payload = {"name": group_name, "description": f"Created by awvs.py at {datetime.now():%F %T}"}
response = self.request("POST", "/target_groups", json=payload)
if response.status_code not in (200, 201):
raise RuntimeError(f"创建分组失败: {format_response_error(response)}")
data = parse_json_safe(response)
group_id = data.get("group_id")
if not group_id:
location = response.headers.get("Location", "")
group_id = location.rstrip("/").split("/")[-1] if location else None
if not group_id:
raise RuntimeError("分组创建成功但未返回 group_id")
return {"group_id": group_id, "name": group_name}
def list_group_target_ids(self, group_id):
response = self.request("GET", f"/target_groups/{group_id}/targets")
if response.status_code != 200:
raise RuntimeError(f"读取分组目标失败: {format_response_error(response)}")
data = parse_json_safe(response)
target_ids = data.get("target_id_list")
if isinstance(target_ids, list):
return target_ids
targets = data.get("targets")
if isinstance(targets, list):
return [item.get("target_id") for item in targets if item.get("target_id")]
return []
def add_targets_to_group(self, group_id, target_ids):
if not target_ids:
return
seen = set()
deduped_target_ids = []
for target_id in target_ids:
if target_id and target_id not in seen:
seen.add(target_id)
deduped_target_ids.append(target_id)
existing_target_ids = set(self.list_group_target_ids(group_id))
pending_target_ids = [target_id for target_id in deduped_target_ids if target_id not in existing_target_ids]
if not pending_target_ids:
return
failures = []
for index in range(0, len(pending_target_ids), 200):
chunk = pending_target_ids[index : index + 200]
payload = {"target_id_list": chunk}
response = self.request("POST", f"/target_groups/{group_id}/targets", json=payload)
if response.status_code in (200, 201, 204):
continue
chunk_error = format_response_error(response)
for target_id in chunk:
single_payload = {"target_id_list": [target_id]}
single_response = self.request("POST", f"/target_groups/{group_id}/targets", json=single_payload)
if single_response.status_code not in (200, 201, 204):
failures.append((target_id, format_response_error(single_response)))
if failures and len(failures) == len(chunk):
raise RuntimeError(f"写入分组失败: chunk_error={chunk_error} | failed={failures[:5]}")
if failures:
raise RuntimeError(f"部分目标写入分组失败: {failures[:5]}")
def list_vulnerabilities(self, query=None, page_size=100):
params = {}
if query:
params["q"] = query
return list(self.iter_cursor_paginated("/vulnerabilities", "vulnerabilities", params=params, page_size=page_size))
def get_vulnerability(self, vuln_id):
response = self.request("GET", f"/vulnerabilities/{vuln_id}")
if response.status_code != 200:
raise RuntimeError(f"读取漏洞详情失败: {format_response_error(response)}")
return parse_json_safe(response)
def load_urls_from_file(input_file, default_scheme):
rows = load_raw_input_rows(input_file)
clean_entries = []
seen = set()
skipped = []
for line_no, raw_target, raw_description in rows:
raw_value = normalize_address(raw_target)
if not raw_value:
skipped.append((line_no, raw_value, "empty"))
continue
if raw_value.lower() in {"url", "urls", "target", "targets", "address", "domain", "host"}:
skipped.append((line_no, raw_value, "header"))
continue
normalized, reason = normalize_input_target(raw_value, default_scheme)
if not normalized:
skipped.append((line_no, raw_value, reason))
continue
dedupe_key = normalized.lower()
if dedupe_key in seen:
continue
seen.add(dedupe_key)
clean_entries.append(
{
"address": normalized,
"description": raw_description or build_default_description(input_file, line_no, normalized),
"line_no": line_no,
"raw": raw_target,
"raw_target": raw_value,
"source_file": input_file,
}
)
return clean_entries, skipped
def extract_httpx_probe_host(raw_value):
value = normalize_address(raw_value)
if not value:
return None
lowered = value.lower()
if lowered in {"url", "urls", "target", "targets", "address", "domain", "host"}:
return None
if value.startswith(("http://", "https://")):
try:
endpoint = parse_target_endpoint(value)
if endpoint["explicit_port"]:
return f"{endpoint['host']}:{endpoint['port']}"
return endpoint["host"]
except Exception:
return None
if HOST_PORT_RE.match(value):
return value
if looks_like_host(value):
return value
return None
def load_raw_input_rows(input_file):
ext = os.path.splitext(input_file)[1].lower()
rows = []
if ext == ".txt":
with open(input_file, "r", encoding="utf-8") as file_obj:
for line_no, line in enumerate(file_obj, start=1):
raw = line.strip()
if raw:
rows.append((line_no, raw, ""))
elif ext == ".csv":
with open(input_file, "r", encoding="utf-8-sig", newline="") as file_obj:
reader = csv.reader(file_obj)
for line_no, row in enumerate(reader, start=1):
if not row:
continue
target_cell = (row[0] or "").strip()
description_cell = (row[1] or "").strip() if len(row) > 1 else ""
if target_cell:
rows.append((line_no, target_cell, description_cell))
elif ext in (".xlsx", ".xls"):
try:
import pandas as pd
except ImportError as exc:
raise RuntimeError("读取 xlsx 需要安装 pandas") from exc
dataframe = pd.read_excel(input_file, header=None)
for row_index, row in dataframe.iterrows():
target_cell = str(row.iloc[0]).strip() if len(row) > 0 and not pd.isna(row.iloc[0]) else ""
description_cell = str(row.iloc[1]).strip() if len(row) > 1 and not pd.isna(row.iloc[1]) else ""
if target_cell:
rows.append((row_index + 1, target_cell, description_cell))
else:
raise RuntimeError("不支持的输入格式,仅支持 .txt / .csv / .xlsx / .xls")
return rows
def export_awvs_csv(entries, output_dir, chunk_size):
if chunk_size <= 0:
raise RuntimeError("chunk_size 必须大于 0")
os.makedirs(output_dir, exist_ok=True)
source_file = entries[0]["source_file"] if entries else "targets"
base_name = os.path.splitext(os.path.basename(source_file))[0]
generated_files = []
for index, chunk in enumerate(chunked(entries, chunk_size), start=1):
output_file = os.path.join(output_dir, f"{base_name}_awvs_part{index}.csv")
with open(output_file, "w", encoding="utf-8", newline="") as file_obj:
writer = csv.writer(file_obj)
for item in chunk:
writer.writerow([item["address"], item["description"]])
generated_files.append(output_file)
return generated_files
def safe_filename(value, fallback="item", max_length=80):
cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", (value or "").strip())
cleaned = re.sub(r"\s+", "_", cleaned).strip("._ ")
if not cleaned:
cleaned = fallback
return cleaned[:max_length].rstrip("._ ") or fallback
def default_sqlmap_quick_dir(group_ref):
return os.path.abspath(f"sqlmap_quick_{safe_filename(group_ref or 'group')}")
def severity_to_query_value(severity_name):
if not severity_name or severity_name == "all":
return None
return SEVERITY_NAME_TO_VALUE[severity_name]
def severity_to_name(severity_value):
return SEVERITY_VALUE_TO_NAME.get(severity_value, str(severity_value))
def strip_html_text(text):
normalized = (text or "").replace("<br/>", "\n").replace("<br />", "\n").replace("<br>", "\n")
normalized = re.sub(r"</li\s*>", "\n", normalized, flags=re.I)
normalized = re.sub(r"<li[^>]*>", "- ", normalized, flags=re.I)
normalized = re.sub(r"</p\s*>", "\n", normalized, flags=re.I)
normalized = re.sub(r"<[^>]+>", "", normalized)
normalized = unescape(normalized)
normalized = normalized.replace("\r\n", "\n").replace("\r", "\n")
normalized = re.sub(r"\n{3,}", "\n\n", normalized)
return normalized.strip()
def build_vulnerability_query(group_id, severity_name=None, status_name=None):
query_parts = [f"group_id:{group_id}"]
severity_value = severity_to_query_value(severity_name)
if severity_value is not None:
query_parts.append(f"severity:{severity_value}")
if status_name and status_name != "all":
query_parts.append(f"status:{status_name}")
return ";".join(query_parts)
def is_sqli_vulnerability(vuln):
name = (vuln.get("vt_name") or "").strip().lower()
tags = {str(tag).strip().lower() for tag in (vuln.get("tags") or [])}
return name == "sql injection" or "sql_injection" in tags
def detect_sqli_techniques(details_text):
lowered = (details_text or "").lower()
techniques = []
if any(token in lowered for token in ("error message found", "sql syntax", "mysql error", "odbc", "jdbc", "ora-", "postgresql query failed")):
techniques.append("error-based")
if "tests performed" in lowered or ("=> true" in lowered and "=> false" in lowered) or (" true" in lowered and " false" in lowered):
techniques.append("boolean-based")
if any(token in lowered for token in ("sleep(", "benchmark(", "pg_sleep", "waitfor delay", "dbms_pipe", "sysdate()", "time delay")):
techniques.append("time-based")
if any(token in lowered for token in ("union select", "union-based", "union query", "union all select")):
techniques.append("union-based")
return techniques
def sqlmap_technique_letters(techniques):
letters = []
mapping = {
"boolean-based": "B",
"error-based": "E",
"time-based": "T",
"union-based": "U",
}
for technique in techniques or []:
letter = mapping.get(technique)
if letter and letter not in letters:
letters.append(letter)
return "".join(letters)
def detect_sqli_dbms(details_text):
lowered = (details_text or "").lower()
dbms_tokens = [
("mysql", ("mysql", "mariadb")),
("postgresql", ("postgresql", "postgres", "pg_sleep")),
("mssql", ("microsoft sql server", "sql server", "mssql", "waitfor delay")),
("oracle", ("oracle", "ora-", "dbms_pipe")),