forked from intruder-io/autoswagger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautoswagger.py
More file actions
1501 lines (1366 loc) · 64.7 KB
/
Copy pathautoswagger.py
File metadata and controls
1501 lines (1366 loc) · 64.7 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
# Autoswagger - Cale Anderson @ Intruder
import argparse
import json
import os
import re
import sys
import threading
import time
from itertools import product as itertools_product
from urllib.parse import urljoin, urlencode, urlparse
import requests
import urllib3
from bs4 import BeautifulSoup
from dicttoxml import dicttoxml
import yaml
import xml.etree.ElementTree as ET
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
# Import Presidio for PII detection
from presidio_analyzer import AnalyzerEngine, RecognizerRegistry, Pattern, PatternRecognizer
from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
from rich.table import Table
from rich.logging import RichHandler
import logging
# ------------------------------
# Global Variables for Stats
# ------------------------------
TOTAL_REQUESTS = 0 # Tracks total requests sent by the tool
SCAN_START_TIME = 0.0 # Records scan start time (for RPS calculation)
SCAN_END_TIME = 0.0 # Records scan end time (for RPS calculation)
# Initialize Presidio Analyzer with custom recognizers
registry = RecognizerRegistry()
# Initialize file_handler for log data output
file_handler = None
def setup_pii_recognizers():
"""
Adds custom recognizers for Person, Phone, Email, and Address to the Presidio registry
with context words. Each recognizer uses a pattern and context to detect potential PII.
"""
# Person
person_pattern = Pattern(
name="person",
regex=r"\b[A-Z][a-z]+\s[A-Z][a-z]+\b",
score=0.85
)
person_recognizer = PatternRecognizer(
supported_entity="PERSON",
patterns=[person_pattern],
context=["name","first_name","last_name","firstname","lastname"]
)
# Phone Number
phone_pattern = Pattern(
name="phone_number",
regex=r"(\+?\d{1,3}[-.\s]?(\d{3})[-.\s]?(\d{3,4})[-.\s]?(\d{4}))",
score=0.85
)
phone_recognizer = PatternRecognizer(
supported_entity="PHONE_NUMBER",
patterns=[phone_pattern],
context=["phone","mobile","telephone","tel","phone_number"]
)
# Email Address
email_pattern = Pattern(
name="email",
regex=r"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)",
score=0.85
)
email_recognizer = PatternRecognizer(
supported_entity="EMAIL_ADDRESS",
patterns=[email_pattern],
context=["email","email_address","contact"]
)
# Address
address_pattern = Pattern(
name="address",
regex=r"\b\d{1,5}\s\w+\s\w+\b",
score=0.85
)
address_recognizer = PatternRecognizer(
supported_entity="ADDRESS",
patterns=[address_pattern],
context=["addr","address","location"]
)
# Add each recognizer to the registry
registry.add_recognizer(person_recognizer)
registry.add_recognizer(phone_recognizer)
registry.add_recognizer(email_recognizer)
registry.add_recognizer(address_recognizer)
# Call setup function to prepare custom PII recognizers
setup_pii_recognizers()
# Initialize Presidio context-aware enhancer
from presidio_analyzer.context_aware_enhancers import LemmaContextAwareEnhancer
context_aware_enhancer = LemmaContextAwareEnhancer(
context_similarity_factor=0.35,
min_score_with_context_similarity=0.4
)
# Analyzer engine for detection
analyzer = AnalyzerEngine(
registry=registry,
context_aware_enhancer=context_aware_enhancer
)
# Initialize Rich Console for formatted output
console = Console()
# Suppress warnings about unverified HTTPS requests
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Default request timeout
TIMEOUT = 10
# Paths for detecting swagger/openapi specs in UI or direct spec endpoints
SWAGGER_UI_PATHS = sorted({
"/", "/apidocs/", "/swagger/ui/index", "/swagger/index.html", "/swagger-ui.html",
"/swagger/swagger-ui.html", "/api/swagger-ui.html", "/api_docs", "/api/index.html",
"/api/doc", "/api/docs/", "/api/swagger/index.html", "/api/swagger/swagger-ui.html",
"/api/swagger-ui/api-docs", "/api/api-docs", "/api/apidocs", "/api/swagger",
"/api/swagger/static/index.html", "/api/swagger-resources",
"/api/swagger-resources/restservices/v2/api-docs", "/api/__swagger__/", "/api/_swagger_/",
"/docu", "/docs", "/swagger", "/api-doc", "/doc/",
"/webjars/swagger-ui/index.html", "/3.0.0/swagger-ui.html",
"/MobiControl/api/docs/index/index.html", "/Swagger", "/Swagger/", "/Swagger/index.html",
"/V2/api-docs/ui", "/admin/swagger-ui/index.html", "/api-doc/", "/api-docs/",
"/api-docs/ui/", "/api-docs/v1/index.html", "/api-documentation/index.html",
"/api/", "/api/api-docs", "/api/api-docs/index.html", "/api/api/",
"/api/apidocs", "/api/config", "/api/doc", "/api/doc/", "/api/spec/", "/spec/",
})
DIRECT_SPEC_PATHS = sorted({
"/swagger.json", "/swagger.yaml", "/swagger.yml", "/api/swagger.json",
"/api/swagger.yaml", "/api/swagger.yml", "/v1/swagger.json",
"/v1/swagger.yaml", "/v1/swagger.yml", "/openapi.json",
"/openapi.yaml", "/openapi.yml", "/api/openapi.json",
"/api/openapi.yaml", "/api/openapi.yml", "/docs/swagger.json",
"/docs/swagger.yaml", "/docs/openapi.json", "/docs/openapi.yaml",
"/api-docs/swagger.json", "/api-docs/swagger.yaml",
"/swagger/v1/swagger.json", "/swagger/v1/swagger.yaml",
"/rest/swagger.json", "/rest/swagger.yaml", "/rest-api/swagger.json",
"/swagger/v1/docs.json", "/api/swagger/docs.json",
"/swagger/docs/v1.json", "/swagger/swagger.json", "/swagger/swagger.yaml",
"/api-doc.json", "/api/spec/swagger.json", "/api/spec/swagger.yaml",
"/api/v1/swagger-ui/swagger.json", "/api/v1/swagger-ui/swagger.yaml",
"/api/swagger_doc.json", "/v2/swagger.json", "/v2/swagger.yaml",
"/v3/swagger.json", "/v3/swagger.yaml", "/openapi2.json",
"/openapi2.yaml", "/openapi2.yml", "/api/v3/openapi.json",
"/api/v3/openapi.yaml", "/api/v3/openapi.yml", "/spec/swagger.json",
"/spec/swagger.yaml", "/spec/openapi.json", "/spec/openapi.yaml",
"/api-docs/swagger-ui.json", "/api-docs/swagger-ui.yaml",
"/api-docs/openapi.json", "/api-docs/openapi.yaml",
"/swagger-ui.json", "/swagger-ui.yaml"
})
# Regex patterns for secrets (similar to TruffleHog)
TRUFFLEHOG_REGEXES = {
"Slack Token": r"(xox[pborsa]-[0-9]{12}-[0-9]{12}-[0-9]{12}-[a-z0-9]{32})",
"RSA private key": r"-----BEGIN RSA PRIVATE KEY-----",
"SSH (DSA) private key": r"-----BEGIN DSA PRIVATE KEY-----",
"SSH (EC) private key": r"-----BEGIN EC PRIVATE KEY-----",
"PGP private key block": r"-----BEGIN PGP PRIVATE KEY BLOCK-----",
"AWS API Key": r"AKIA[0-9A-Z]{16}",
"Amazon MWS Auth Token": r"amzn\.mws\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
"AWS AppSync GraphQL Key": r"da2-[a-z0-9]{26}",
"Facebook Access Token": r"EAACEdEose0cBA[0-9A-Za-z]+",
"Facebook OAuth": r"[fF][aA][cC][eE][bB][oO][oO][kK].*['\"]?[0-9a-f]{32}['\"]?",
"GitHub": r"[gG][iI][tT][hH][uU][bB].*['\"]?[0-9a-zA-Z]{35,40}['\"]?",
"Generic API Key": r"[aA][pP][iI]_?[kK][eE][yY].*['\"]?[0-9a-zA-Z]{32,45}['\"]?",
"Generic Secret": r"[sS][eE][cC][rR][eE][tT].*['\"]?[0-9a-zA-Z]{32,45}['\"]?",
"Google API Key": r"AIza[0-9A-Za-z\-_]{35}",
"Google Cloud Platform OAuth": r"[0-9]+-[0-9A-Za-z_]{32}\.apps\.googleusercontent\.com",
"MailChimp API Key": r"[0-9a-f]{32}-us[0-9]{1,2}",
"Mailgun API Key": r"key-[0-9a-zA-Z]{32}",
"Password in URL": r"[a-zA-Z]{3,10}://[^/\s:@]{3,20}:[^/\s:@]{3,20}@.{1,100}['\"\s]",
"PayPal Braintree Access Token": r"access_token\$production\$[0-9a-z]{16}\$[0-9a-f]{32}",
"Picatic API Key": r"sk_live_[0-9a-z]{32}",
"Slack Webhook": r"https://hooks\.slack\.com/services/T[a-zA-Z0-9_]{8}/B[a-zA-Z0-9_]{8}/[a-zA-Z0-9_]{24}",
"Stripe API Key": r"sk_live_[0-9a-zA-Z]{24}",
"Stripe Restricted API Key": r"rk_live_[0-9a-zA-Z]{24}",
"Square Access Token": r"sq0atp-[0-9A-Za-z\-_]{22}",
"Square OAuth Secret": r"sq0csp-[0-9A-Za-z\-_]{43}",
"Telegram Bot API Key": r"[0-9]+:AA[0-9A-Za-z\-_]{33}",
"Twilio API Key": r"SK[0-9a-fA-F]{32}",
"Twitter Access Token": r"[tT][wW][iI][tT][tT][eE][rR].*[1-9][0-9]+-[0-9a-zA-Z]{40}",
"Twitter OAuth": r"[tT][wW][iI][tT][tT][eE][rR].*['\"]?[0-9a-zA-Z]{35,44}['\"]?"
}
# Compile the regexes for performance
COMPILED_TRUFFLEHOG_REGEXES = {name: re.compile(pattern) for name, pattern in TRUFFLEHOG_REGEXES.items()}
# Debug info regex pattern
DEBUG_INFO_PATTERN = re.compile(r'\b(?:env\.[A-Za-z_]+|AWS_[A-Z_]+|AZURE_[A-Z_]+|DEBUG|ERROR)\b')
# Default test values for parameters by type
TEST_VALUES = {
"integer": [1, 2, 100, -1, 0, 999, 123456],
"string": [
"1", "test", "example", "1234", "none", "admin", "guest", "user@email.com",
"550e8400-e29b-41d4-a716-446655440000",
"a8098c1a-f86e-11da-bd1a-00112444be1e"
],
"boolean": [True, False],
"number": [1, 0, 100, 1000, 0.1],
"base64": ["MQ==", "dXNlcjE=", "YWRtaW4xMjM=", "c2FtcGxlVXNlcg=="],
"default": ["1", "test", "123", "True","true","550e8400-e29b-41d4-a716-446655440000", "*", "All"]
}
# Lock for thread-safe operations
lock = threading.Lock()
# Initialize logger with RichHandler
logger = logging.getLogger("autoswagger")
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(message)s")
# Set to track hosts where no valid swagger was found
bad_hosts = set()
def get_timestamp():
"""
Returns current timestamp in the format [HH:MM:SS].
Used for logging messages with a consistent time prefix.
"""
return time.strftime("[%H:%M:%S]")
def log(message, level="INFO"):
"""
Logs a message with a given level to both the Rich console and the optional file_handler.
:param message: String message to log
:param level: Logging level ('INFO', 'DEBUG', 'WARNING', 'CRITICAL', 'SUCCESS')
"""
global file_handler
timestamp = get_timestamp()
levels = {
"INFO": "[green][INFO][/green]",
"DEBUG": "[cyan][DEBUG][/cyan]",
"WARNING": "[yellow][WARNING][/yellow]",
"CRITICAL": "[red][CRITICAL][/red]",
"SUCCESS": "[bold green][SUCCESS][/bold green]"
}
level_prefix = levels.get(level, f"[{level}]")
formatted_message = f"{timestamp} {level_prefix} {message}"
console.print(formatted_message, highlight=False)
if file_handler and level == "DEBUG":
logger.debug(message)
elif file_handler and level in ["INFO", "WARNING", "CRITICAL", "SUCCESS"]:
logger.info(message)
def print_banner():
"""
Prints the ASCII banner for Autoswagger with intruder.io link in yellow.
Called if not in product mode, to show the standard header.
"""
banner = f"""[white]
/ | __ __/ /_____ ______ ______ _____ _____ ____ _____
/ /| |/ / / / __/ __ \\/ ___/ | /| / / __ `/ __ `/ __ `/ _ \\/ ___/
/ ___ / /_/ / /_/ /_/ (__ )| |/ |/ / /_/ / /_/ / /_/ / __/ /
/_/ |_\\__,_/\\__/\\____/____/ |__/|__/_\\__,_/\\__, /\\__, /\\___/_/
/____//____/[/white]
[yellow]https://intruder.io[/yellow]
Find unauthenticated endpoints
"""
console.print(banner)
def generate_parameter_values(param_type, enum=None):
"""
Returns a list of test values for a given parameter type.
If an enum list is provided, uses that instead of defaults.
"""
if enum:
return enum
return TEST_VALUES.get(param_type, TEST_VALUES["default"])
def build_nested_object(schema, value_index=0):
"""
Recursively constructs a nested object (dict) for complex schemas.
Handles properties, arrays, and composite references (oneOf, anyOf, allOf).
"""
obj = {}
for key, prop in schema.get('properties', {}).items():
if '$ref' in prop:
continue
if 'oneOf' in prop or 'anyOf' in prop or 'allOf' in prop:
obj[key] = handle_composite_schemas(prop, value_index)
elif prop.get('type') == 'object':
obj[key] = build_nested_object(prop, value_index)
elif prop.get('type') == 'array':
obj[key] = build_array_item(prop, value_index)
else:
param_type = prop.get('type', 'string')
enum = prop.get('enum', None)
values = generate_parameter_values(param_type, enum)
obj[key] = values[value_index % len(values)]
return obj
def handle_composite_schemas(schema, value_index=0):
"""
Handles composite schema definitions like oneOf, anyOf, and allOf.
Calls build_nested_object recursively on the chosen sub-schema or the combined properties.
"""
if 'oneOf' in schema:
return build_nested_object(schema['oneOf'][value_index % len(schema['oneOf'])], value_index)
elif 'anyOf' in schema:
return build_nested_object(schema['anyOf'][value_index % len(schema['anyOf'])], value_index)
elif 'allOf' in schema:
combined_schema = {}
for sub_schema in schema['allOf']:
combined_schema.update(sub_schema.get('properties', {}))
return build_nested_object({'properties': combined_schema}, value_index)
return build_nested_object(schema, value_index)
def build_array_item(item_schema, value_index=0):
"""
Builds an array item from the given schema.
If the schema is an object or contains properties, delegates to build_nested_object.
Otherwise chooses from test values by type.
"""
if 'properties' in item_schema or item_schema.get('type') == 'object':
return build_nested_object(item_schema, value_index)
else:
param_type = item_schema.get('type', 'string')
enum = item_schema.get('enum', None)
values = generate_parameter_values(param_type, enum)
return values[value_index % len(values)]
def build_file_upload_body(schema, content_type, value_index=0):
"""
Builds a simple file upload body for multipart/form-data.
Returns a dict with a file-like tuple if content_type is multipart/form-data.
"""
if content_type == 'multipart/form-data':
return {'file': ('test.txt', b'This is a test file')}
return None
def build_request_body(schema, content_type, value_index=0):
"""
Builds a request body based on the schema and specified content type.
Supports JSON, XML, form-encoded, plain text, octet-stream, and multipart.
"""
if not schema:
return None
if 'oneOf' in schema or 'anyOf' in schema or 'allOf' in schema:
body = handle_composite_schemas(schema, value_index)
elif schema.get('type') == 'array':
item_schema = schema.get('items', {})
body = [build_array_item(item_schema, value_index)]
elif schema.get('type') == 'object':
body = build_nested_object(schema, value_index)
else:
param_type = schema.get('type', 'string')
enum = schema.get('enum', None)
values = generate_parameter_values(param_type, enum)
body = values[value_index % len(values)]
if content_type == 'application/x-www-form-urlencoded':
return urlencode(body)
elif content_type == 'application/xml':
return dicttoxml(body).decode()
elif content_type == 'application/json':
return json.dumps(body)
elif content_type == 'text/plain':
return str(body)
elif content_type == 'application/octet-stream':
return b'\x00\x01\x02'
elif content_type == 'multipart/form-data':
return build_file_upload_body(schema, content_type, value_index)
return json.dumps(body)
def substitute_path_parameters(path, parameters, value_mapping):
"""
Replaces path parameter placeholders (e.g. {id}, :id, <id>) with generated values.
"""
for param in parameters:
if param.get('in') == 'path':
param_name = param.get('name')
value = value_mapping.get(param_name)
if value is not None:
path = re.sub(rf'{{{param_name}}}|:{param_name}|<{param_name}>', str(value), path)
return path
def generate_query_string(parameters, value_mapping):
"""
Creates a query string (e.g. ?key=value) for parameters that are in the query location.
"""
query_params = {}
for param in parameters:
if param.get('in') == 'query':
param_name = param.get('name')
value = value_mapping.get(param_name)
if value is not None:
query_params[param_name] = value
return urlencode(query_params)
def detect_sensitive_info(content):
"""
Searches the response content for known secret patterns (TruffleHog) and debug info patterns.
Returns a dict of matches if found, along with the regex patterns used.
"""
sensitive_info = {}
regex_patterns = {}
for name, pattern in COMPILED_TRUFFLEHOG_REGEXES.items():
matches = pattern.findall(content)
if matches:
sensitive_info.setdefault(name, []).extend(matches)
regex_patterns[name] = pattern.pattern
debug_info_found = DEBUG_INFO_PATTERN.findall(content)
if debug_info_found:
sensitive_info.setdefault('Debug Information', []).extend(debug_info_found)
regex_patterns['Debug Information'] = DEBUG_INFO_PATTERN.pattern
return sensitive_info if sensitive_info else None, regex_patterns
def is_large_response(content):
"""
Checks if the response is large, specifically:
- Contains 100+ items in JSON arrays or dictionary keys
- Or 100+ elements in XML
- Or raw content_length > 100000 bytes
"""
try:
if isinstance(content, bytes):
content = content.decode('utf-8', errors='ignore')
if content.strip().startswith('{') or content.strip().startswith('['):
data = json.loads(content)
if isinstance(data, list) and len(data) >= 100:
return True
elif isinstance(data, dict):
total_items = sum(1 for _ in data.values())
if total_items >= 100:
return True
elif content.strip().startswith('<'):
root = ET.fromstring(content)
total_elements = sum(1 for _ in root.iter())
if total_elements >= 100:
return True
except (json.JSONDecodeError, ET.ParseError):
pass
return False
def test_parameter_values(method, base_url_no_path, full_path, parameters, request_body, content_type, rate, include_all, verbose, brute=False):
"""
Tests parameter values for a given method/endpoint.
If brute is false, only a single default set is tested.
If brute is true, tries enumerating multiple data types/values.
"""
best_response = None
value_mapping = {}
# Collect a default mapping from the parameter schema
for param in parameters:
if param.get('in') not in ['path', 'query']:
continue
param_name = param.get('name')
schema = param.get('schema', {})
param_type = schema.get('type', 'string')
enum = schema.get('enum', None)
values = generate_parameter_values(param_type, enum)
value_mapping[param_name] = values[0]
# Default mode: one request
if not brute:
response = send_request(
method, base_url_no_path, full_path, parameters,
value_mapping, request_body, content_type, rate, include_all, verbose
)
return [response] if response else []
# Brute mode: enumerates multiple combos or data types
else:
tested_types = set()
param_types = []
for param in parameters:
if param.get('in') not in ['path', 'query']:
continue
schema = param.get('schema', {})
param_type = schema.get('type', None)
enum = schema.get('enum', None)
if param_type:
values = generate_parameter_values(param_type, enum)
else:
values = []
param_types.append((param_type, values))
# If all parameters have known values
if all(vals for _, vals in param_types):
param_test_values = [vals for _, vals in param_types]
combos = itertools_product(*param_test_values)
for combo in combos:
val_map = {n: v for n, v in zip(value_mapping.keys(), combo)}
resp = send_request(
method, base_url_no_path, full_path, parameters,
val_map, request_body, content_type, rate, include_all, verbose
)
if resp:
return [resp]
else:
# Try different fallback types
for test_type in ['integer', 'string', 'boolean', 'number']:
if test_type in tested_types:
continue
tested_types.add(test_type)
param_test_values = [generate_parameter_values(test_type) for _ in value_mapping.keys()]
first_combos = itertools_product(*[vals[:1] for vals in param_test_values])
for combo in first_combos:
val_map = {n: v for n, v in zip(value_mapping.keys(), combo)}
resp = send_request(
method, base_url_no_path, full_path, parameters,
val_map, request_body, content_type, rate, include_all, verbose
)
if resp:
max_clen = resp['content_length']
best_response = resp
second_combos = itertools_product(*param_test_values)
for combo2 in second_combos:
val_map2 = {n: v2 for n, v2 in zip(value_mapping.keys(), combo2)}
resp2 = send_request(
method, base_url_no_path, full_path, parameters,
val_map2, request_body, content_type, rate, include_all, verbose
)
if resp2 and resp2['content_length'] > max_clen:
max_clen = resp2['content_length']
best_response = resp2
return [best_response]
return []
def send_request(method, base_url_no_path, full_path, parameters, value_mapping, request_body, content_type, rate, include_all, verbose):
"""
Sends a request to the computed endpoint, respecting rate limit.
Decodes the response, checks for secrets, PII (via line-based CSV and key:value scanning),
returns a dictionary summarizing the result (status code, content length, PII, etc.)
Skips 401 and 403 responses by default.
"""
global TOTAL_REQUESTS
substituted_path = substitute_path_parameters(full_path, parameters, value_mapping)
query_string = generate_query_string(parameters, value_mapping)
if not substituted_path.startswith('/'):
substituted_path = '/' + substituted_path
parsed_path = urlparse(substituted_path)
if parsed_path.scheme in ['http', 'https']:
full_url = substituted_path
else:
if query_string:
full_url = f"{urljoin(base_url_no_path, substituted_path)}?{query_string}"
else:
full_url = urljoin(base_url_no_path, substituted_path)
headers = {'Content-Type': content_type} if content_type else {}
data = request_body if method.upper() in ['POST', 'PUT', 'PATCH'] else None
try:
if rate > 0:
time.sleep(1.0 / rate) # Rate limiting
TOTAL_REQUESTS += 1
response = requests.request(
method, full_url, headers=headers, data=data,
verify=False, allow_redirects=False, timeout=TIMEOUT
)
status_code = response.status_code
# Skip 401 and 403 by design
if status_code in [401, 403]:
if verbose:
log(f"Skipping endpoint {method.upper()} {full_url} due to status code {status_code}", level="INFO")
return None
content_length = len(response.content)
try:
content_text = response.content.decode('utf-8', errors='ignore')
except Exception:
content_text = ''
# Detect secrets in entire content
sensitive_info, regex_patterns = detect_sensitive_info(content_text)
lines = content_text.splitlines()
pii_detected = False
pii_data = {}
pii_detection_methods = set()
interesting_response = False
context_keywords = ["name", "email", "phone", "addr", "tel", "contact", "location"]
# Simple CSV detection: check first line for multiple commas
csv_header = []
if len(lines) > 0:
first_line = lines[0]
columns = first_line.split(',')
if len(columns) >= 3:
csv_header = [col.strip().lower() for col in columns]
# If CSV header recognized, parse subsequent lines with the same number of columns
if csv_header:
for idx, line in enumerate(lines):
if idx == 0:
continue
row_cols = line.split(',')
if len(row_cols) == len(csv_header):
for i, col_name in enumerate(csv_header):
for kw in context_keywords:
if kw in col_name:
cell_value = row_cols[i].strip()
pres_res = analyzer.analyze(
text=cell_value,
entities=["PERSON","EMAIL_ADDRESS","PHONE_NUMBER","ADDRESS"],
language='en'
)
if pres_res:
pii_detected = True
for ent in pres_res:
entity_type = ent.entity_type
entity_value = cell_value[ent.start:ent.end]
detection_method = 'context'
pii_data.setdefault(entity_type, {'values': set(), 'detection_methods': set()})
pii_data[entity_type]['values'].add(entity_value)
pii_data[entity_type]['detection_methods'].add(detection_method)
pii_detection_methods.add(detection_method)
# Also do a naive "key: value" detection line by line
for line in lines:
if ':' in line:
parts = line.split(':', 1)
key_part = parts[0].strip().lower()
val_part = parts[1].strip()
for kw in context_keywords:
if kw in key_part:
pres_res = analyzer.analyze(
text=val_part,
entities=["PERSON","EMAIL_ADDRESS","PHONE_NUMBER","ADDRESS"],
language='en'
)
if pres_res:
pii_detected = True
for ent in pres_res:
entity_type = ent.entity_type
entity_value = val_part[ent.start:ent.end]
detection_method = 'context'
pii_data.setdefault(entity_type, {'values': set(), 'detection_methods': set()})
pii_data[entity_type]['values'].add(entity_value)
pii_data[entity_type]['detection_methods'].add(detection_method)
pii_detection_methods.add(detection_method)
if pii_data:
for entity_type in pii_data:
pii_data[entity_type]['values'] = list(pii_data[entity_type]['values'])[:2]
pii_data[entity_type]['detection_methods'] = list(pii_data[entity_type]['detection_methods'])
# Mark interesting if 200 (or 404 if include_all) plus big or has PII
if status_code == 200 or (include_all and status_code == 404):
if is_large_response(response.content) or content_length > 100000:
interesting_response = True
if pii_detected:
interesting_response = True
result = {
"method": method.upper(),
"url": full_url,
"path_template": full_path,
"body": data if data else "",
"status_code": status_code,
"content_length": content_length,
"pii_detected": pii_detected,
"pii_data": None,
"pii_detection_details": None,
"interesting_response": interesting_response,
"regex_patterns_found": {}
}
if pii_detected:
result["pii_data"] = {k: list(vv['values']) for k, vv in pii_data.items()}
detection_details = {}
for k, vv in pii_data.items():
detection_details[k] = {
"detection_methods": list(vv['detection_methods'])
}
result["pii_detection_details"] = detection_details
# If TruffleHog found sensitive_info, merge that with the same pii_data structure
if sensitive_info:
result["regex_patterns_found"] = {}
result["pii_detected"] = True
for key, values in sensitive_info.items():
detection_method = 'regex'
if key not in pii_data:
pii_data[key] = {'values': set(), 'detection_methods': set()}
pii_data[key]['values'].update(values)
pii_data[key]['detection_methods'].add(detection_method)
pii_detection_methods.add(detection_method)
result["regex_patterns_found"][key] = regex_patterns[key]
result["pii_data"] = {k: list(vv['values'])[:2] for k, vv in pii_data.items()}
detection_details = {}
for k, vv in pii_data.items():
detection_details[k] = {
"detection_methods": list(vv['detection_methods'])
}
result["pii_detection_details"] = detection_details
result["pii_detected"] = True
if (status_code == 200 or (include_all and status_code == 404)):
interesting_response = True
result["interesting_response"] = interesting_response
if verbose:
if status_code == 200:
log(f"{method.upper()} {full_url} returned {status_code}", level="SUCCESS")
elif status_code == 404 and include_all:
log(f"{method.upper()} {full_url} returned {status_code}", level="WARNING")
elif 400 <= status_code < 600:
log(f"{method.upper()} {full_url} returned {status_code}", level="WARNING")
else:
log(f"{method.upper()} {full_url} returned {status_code}", level="INFO")
return result
except requests.exceptions.RequestException as e:
if verbose:
log(f"Error testing {method.upper()} {full_url}: {e}", level="DEBUG")
return None
def test_endpoint(base_url, base_path, path_template, method, parameters, request_body=None,
content_type=None, verbose=False, rate=30, include_all=False,
product_mode=False, brute=False):
"""
Tests a single endpoint (method + path_template).
Prepares final path by combining base_path with path_template, then calls test_parameter_values.
Returns a list of results from that function.
"""
if base_path and not base_path.startswith("/"):
base_path = "/" + base_path
if base_path.endswith("/"):
base_path = base_path[:-1]
full_path = base_path + path_template
parsed_base_url = urlparse(base_url)
base_url_no_path = f"{parsed_base_url.scheme}://{parsed_base_url.netloc}"
results = []
try:
start_time = time.time()
endpoint_results = test_parameter_values(
method, base_url_no_path, full_path, parameters,
request_body, content_type, rate, include_all, verbose, brute=brute
)
if endpoint_results:
results.extend(endpoint_results)
except Exception as e:
if verbose:
log(f"Error testing endpoint {method.upper()} {full_path}: {e}", level="DEBUG")
finally:
elapsed_time = time.time() - start_time
if elapsed_time > TIMEOUT and verbose:
log(f"Timeout reached while testing endpoint {method.upper()} {full_path}", level="WARNING")
return results
def test_endpoints(base_url, base_path, swagger_spec, verbose=False,
include_risk=False, include_all=False, product_mode=False,
rate=30, tried_basepath_fallback=False, brute=False):
"""
Iterates over all paths and methods in the provided swagger_spec.
Submits tasks to test_endpoint if the method is allowed (GET or others if -risk).
Returns all aggregated results. Also includes fallback if 80%+ are 404.
"""
results = []
if not swagger_spec or 'paths' not in swagger_spec:
if verbose:
log("Specification does not contain 'paths' key.", level="CRITICAL")
return results
unique_endpoints = set()
all_results = []
max_workers = min(100, os.cpu_count() * 5)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_endpoint = {}
for path, methods in swagger_spec['paths'].items():
if not methods:
continue
for mthd, details in methods.items():
if mthd.lower() not in ['get','post','put','patch','delete']:
continue
if mthd.upper() != 'GET' and not include_risk:
continue
endpoint_key = (mthd.upper(), path)
if endpoint_key in unique_endpoints:
continue
unique_endpoints.add(endpoint_key)
parameters = details.get('parameters', [])
content_types = ['application/json']
schema = None
# If OpenAPI 3.x uses requestBody
if 'requestBody' in details:
rb_content = details['requestBody'].get('content', {})
if not rb_content:
continue
content_types = list(rb_content.keys())
for ct in content_types:
schema = rb_content[ct].get('schema', {})
request_body = build_request_body(schema, ct)
fut = executor.submit(
test_endpoint,
base_url, base_path, path, mthd,
parameters, request_body, ct,
verbose, rate, include_all,
product_mode=product_mode, brute=brute
)
future_to_endpoint[fut] = (mthd, path, ct)
else:
# Swagger 2.0 with parameters
if parameters:
for param in parameters:
if param.get('in') == 'body' and 'schema' in param:
schema = param['schema']
break
request_body = build_request_body(schema, 'application/json')
fut = executor.submit(
test_endpoint,
base_url, base_path, path, mthd,
parameters, request_body, 'application/json',
verbose, rate, include_all,
product_mode=product_mode, brute=brute
)
future_to_endpoint[fut] = (mthd, path, 'application/json')
for future in as_completed(future_to_endpoint):
mthd, pth, ct = future_to_endpoint[future]
try:
endpoint_results = future.result()
if endpoint_results:
all_results.extend(endpoint_results)
except Exception as exc:
if verbose:
log(f"Endpoint {mthd.upper()} {pth} with content type {ct} generated an exception: {exc}", level="DEBUG")
# Basepath fallback logic if 80%+ of responses are 404 with the same content length
if not tried_basepath_fallback:
num_responses = len(all_results)
num_404s = sum(1 for r in all_results if r['status_code'] == 404)
content_lengths = set(r['content_length'] for r in all_results if r['status_code'] == 404)
if num_404s > 0 and num_responses > 0:
proportion_404 = num_404s / num_responses
if proportion_404 > 0.8 and len(content_lengths) == 1 and base_path != '/':
if verbose:
log("Basepath fallback triggered. Retesting endpoints with basepath '/'.", level="INFO")
all_results.clear()
fallback = test_endpoints(
base_url, '/', swagger_spec, verbose,
include_risk, include_all, product_mode=product_mode,
rate=rate, tried_basepath_fallback=True, brute=brute
)
return fallback
return all_results
def fetch_swagger_spec(url, verbose=False):
"""
Attempts to fetch and parse an OpenAPI/Swagger spec from a given URL.
Checks if response code is 200, content is JSON/YAML, and contains 'swagger'/'openapi'.
Returns the parsed spec as a dictionary or None if unsuccessful.
"""
if verbose:
log(f"Fetching Swagger/OpenAPI spec directly from {url}", level="DEBUG")
try:
resp = requests.get(url, verify=False, timeout=TIMEOUT)
ctype = resp.headers.get('Content-Type', '').lower()
if resp.status_code == 200 and any(x in ctype for x in ['json','yaml','text/plain']):
if 'swagger' in resp.text.lower() or 'openapi' in resp.text.lower():
try:
if 'json' in ctype:
spec = resp.json()
else:
spec = yaml.safe_load(resp.text)
if verbose:
log("Successfully loaded spec.", level="SUCCESS")
return spec
except (json.JSONDecodeError, yaml.YAMLError) as perr:
if verbose:
log(f"Error decoding spec from {url}: {perr}", level="DEBUG")
log(f"Failed to parse spec from {url}", level="DEBUG")
else:
if verbose:
log(f"Invalid response from {url}: {resp.status_code}, Content-Type: {ctype}", level="WARNING")
log(f"Failed to parse spec from {url}", level="DEBUG")
except requests.exceptions.RequestException as e:
if verbose:
log(f"Error fetching Swagger/OpenAPI spec from {url}: {e}", level="DEBUG")
log(f"Failed to parse spec from {url}", level="DEBUG")
return None
def find_swagger_ui_docs(base_url, verbose=False):
"""
Attempts to detect a Swagger UI at known paths by scanning for references
to swagger/openapi in the HTML or embedded JavaScript. If found, attempts
to parse the discovered spec path or extract an embedded spec.
"""
for pth in SWAGGER_UI_PATHS:
swagger_ui_url = urljoin(base_url, pth)
if verbose:
log(f"Checking Swagger UI page at {swagger_ui_url}", level="DEBUG")
try:
r = requests.get(swagger_ui_url, verify=False, allow_redirects=False, timeout=TIMEOUT)
if r.status_code == 200 and ('swagger' in r.text.lower() or 'openapi' in r.text.lower()):
if verbose:
log(f"Swagger UI found at {swagger_ui_url}", level="DEBUG")
spec_url = extract_spec_url_from_html(r.text)
if spec_url:
full_spec_url = urljoin(swagger_ui_url, spec_url)
if verbose:
log(f"Found Swagger spec URL in HTML: {full_spec_url}", level="DEBUG")
if any(full_spec_url.lower().endswith(ext) for ext in ['.json', '.yaml', '.yml']):
sp = fetch_swagger_spec(full_spec_url, verbose)
if sp:
return sp
else:
if verbose:
log(f"Spec URL does not have a valid spec extension: {full_spec_url}", level="DEBUG")
if full_spec_url.lower().endswith('.js'):
try:
js_r = requests.get(full_spec_url, verify=False, timeout=TIMEOUT)
if js_r.status_code == 200:
if verbose:
log(f"Attempting to extract embedded spec from JS file: {full_spec_url}", level="DEBUG")
emb = extract_spec_from_js(js_r.text)
if emb and isinstance(emb, dict):
if verbose:
log(f"Extracted embedded Swagger spec from JS file: {full_spec_url}", level="DEBUG")
return emb
except requests.exceptions.RequestException as e:
if verbose:
log(f"Error fetching JS file {full_spec_url}: {e}", level="DEBUG")
js_files = re.findall(r'<script\s+src=["\']([^"\']+\.js)["\']', r.text, re.IGNORECASE)
if verbose:
log(f"Found {len(js_files)} JavaScript files to analyze.", level="DEBUG")
js_files = [x for x in js_files if is_local_js_file(x, swagger_ui_url)]
if verbose:
log(f"{len(js_files)} JavaScript files are local and will be analyzed.", level="DEBUG")
js_files_sorted = sorted(js_files, key=lambda x: 'init' in x.lower(), reverse=True)
for jsf in js_files_sorted:
jsu = urljoin(swagger_ui_url, jsf)
if verbose:
log(f"Fetching JS file: {jsu}", level="DEBUG")
try:
js_resp = requests.get(jsu, verify=False, timeout=TIMEOUT)
if js_resp.status_code == 200:
spec_url_js = extract_spec_url_from_js(js_resp.text)
if spec_url_js:
full_spec_url_js = urljoin(jsu, spec_url_js)
if verbose:
log(f"Found Swagger spec URL in JS: {full_spec_url_js}", level="DEBUG")
if any(full_spec_url_js.lower().endswith(ext) for ext in ['.json', '.yaml', '.yml']):
sp2 = fetch_swagger_spec(full_spec_url_js, verbose)
if sp2:
return sp2
else:
if full_spec_url_js.lower().endswith('.js'):
try:
nested_js = requests.get(full_spec_url_js, verify=False, timeout=TIMEOUT)
if nested_js.status_code == 200:
emb2 = extract_spec_from_js(nested_js.text)
if emb2 and isinstance(emb2, dict):
if verbose:
log(f"Extracted embedded Swagger spec from nested JS file: {full_spec_url_js}", level="DEBUG")
return emb2
except requests.exceptions.RequestException as e:
if verbose:
log(f"Error fetching nested JS file {full_spec_url_js}: {e}", level="DEBUG")
emb = extract_spec_from_js(js_resp.text)
if emb and isinstance(emb, dict):
if verbose:
log(f"Extracted embedded Swagger spec from JS file: {jsu}", level="DEBUG")
return emb
except requests.exceptions.RequestException as e:
if verbose: