-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_model.py
More file actions
61 lines (52 loc) · 2.38 KB
/
Copy pathtrain_model.py
File metadata and controls
61 lines (52 loc) · 2.38 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
import pandas as pd
import re
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
# 1. Load the Adversarial Dataset (Source: Paper B) [cite: 536]
filename = 'BCCC-SFU-SQLInj-2023.csv'
df = pd.read_csv(filename)
# 2. Advanced Feature Extraction
def extract_features(query):
query = str(query).upper()
return pd.Series({
'length': len(query),
'special_chars': len(re.findall(r"['\";\-/*=]", query)),
'keywords': len(re.findall(r"(SELECT|UNION|INSERT|DELETE|DROP|WHERE|OR|AND|SLEEP)", query)),
'has_comment': 1 if "--" in query or "/*" in query else 0
})
# 3. Categorization Logic (Based on Paper A: Section III. Attack Methods) [cite: 55]
def categorize_attack(query):
query = str(query).upper()
if re.search(r"UNION.*SELECT", query):
return "Union-Based Attack" #
elif re.search(r"OR\s+['\"]?\d+['\"]?\s*=\s*['\"]?\d+", query) or "OR 1=1" in query:
return "Tautology" #
elif ";" in query and re.search(r"(DROP|DELETE|UPDATE|INSERT)", query):
return "Piggy-backed Query" # [cite: 69]
elif "SLEEP(" in query or "WAITFOR DELAY" in query:
return "Blind/Inference" # [cite: 305]
elif "--" in query or "/*" in query:
return "End-of-Line Comment" # [cite: 78]
return "Other Adversarial/Complex" # [cite: 269]
# 4. Processing Data
X = df['Data'].apply(extract_features)
y = [1] * len(df) # Labels as malicious/adversarial [cite: 468]
# 5. Model Training (Algorithm: Random Forest as used in Paper B)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)
# --- CONSOLIDATED OUTPUT REPORT ---
print("\n" + "="*50)
print(" SQL_INjection_Detection_Analysis")
print("="*50)
# Section 1: ML Performance (Paper B Focus)
print(f"Algorithm Used: Random Forest Classifier (Paper B)") #
print(f"Final Detection Accuracy: {accuracy_score(y_test, model.predict(X_test)) * 100:.2f}%") # [cite: 474]
# Section 2: Attack Vector Analysis (Paper A Focus)
print("\n--- DETAILED ATTACK ANALYSIS (PAPER A) ---")
df['Attack_Type'] = df['Data'].apply(categorize_attack)
type_counts = df['Attack_Type'].value_counts()
print(type_counts)
print("\n[✔] Analysis complete. Results map Paper A methods to Paper B data.")
print("="*50)