init commit
This commit is contained in:
77
lab5/train_http_model.py
Normal file
77
lab5/train_http_model.py
Normal file
@@ -0,0 +1,77 @@
|
||||
import joblib
|
||||
import csv
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from scipy.sparse import hstack
|
||||
from sklearn.feature_extraction.text import TfidfVectorizer
|
||||
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.svm import LinearSVC
|
||||
|
||||
sys.path.append(str(Path(__file__).resolve().parent.parent))
|
||||
from common.features import handcrafted_feature_matrix # noqa: E402
|
||||
|
||||
XSS_KEYWORDS = [
|
||||
"<script", "onerror", "onload", "javascript:", "onclick", "onfocus",
|
||||
"<iframe", "<svg", "alert(", "system(", "etc/passwd", "cmd", "eval(",
|
||||
]
|
||||
|
||||
|
||||
def load_data(path="data.csv"):
|
||||
texts, labels = [], []
|
||||
with open(path, newline="", encoding="utf-8") as f:
|
||||
for row in csv.DictReader(f):
|
||||
texts.append(row["text"])
|
||||
labels.append(int(row["label"]))
|
||||
return texts, np.array(labels)
|
||||
|
||||
|
||||
def main():
|
||||
texts, labels = load_data()
|
||||
X_train_txt, X_test_txt, y_train, y_test = train_test_split(
|
||||
texts, labels, test_size=0.25, random_state=42, stratify=labels
|
||||
)
|
||||
|
||||
vectorizer = TfidfVectorizer(analyzer="char_wb", ngram_range=(2, 4), max_features=1500)
|
||||
Xtr_tfidf = vectorizer.fit_transform(X_train_txt)
|
||||
Xte_tfidf = vectorizer.transform(X_test_txt)
|
||||
|
||||
Xtr_hand = handcrafted_feature_matrix(X_train_txt, XSS_KEYWORDS)
|
||||
Xte_hand = handcrafted_feature_matrix(X_test_txt, XSS_KEYWORDS)
|
||||
|
||||
X_train = hstack([Xtr_tfidf, Xtr_hand])
|
||||
X_test = hstack([Xte_tfidf, Xte_hand])
|
||||
|
||||
clf = LinearSVC(random_state=42, max_iter=5000)
|
||||
clf.fit(X_train, y_train)
|
||||
y_pred = clf.predict(X_test)
|
||||
|
||||
print("HTTP / XSS Injection Detection")
|
||||
print(f"Accuracy: {accuracy_score(y_test, y_pred):.3f}")
|
||||
print(classification_report(y_test, y_pred, target_names=["benign", "malicious"]))
|
||||
print("Confusion matrix [[TN FP][FN TP]]:")
|
||||
print(confusion_matrix(y_test, y_pred))
|
||||
|
||||
print("\nTest Samples")
|
||||
samples = [
|
||||
"<script>alert(document.cookie)</script>",
|
||||
"search term: comfortable running shoes",
|
||||
"<img src=x onerror=alert(1)>",
|
||||
"notes: please call before 5pm",
|
||||
]
|
||||
Xd_tfidf = vectorizer.transform(samples)
|
||||
Xd_hand = handcrafted_feature_matrix(samples, XSS_KEYWORDS)
|
||||
Xd = hstack([Xd_tfidf, Xd_hand])
|
||||
preds = clf.predict(Xd)
|
||||
for text, label in zip(samples, preds):
|
||||
verdict = "MALICIOUS" if label == 1 else "benign"
|
||||
print(f"[{verdict}] {text}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
joblib.dump(vectorizer, "xss_vectorizer.joblib")
|
||||
joblib.dump(clf, "xss_classifier.joblib")
|
||||
print("\nSaved model artifacts. Run: python test_model.py")
|
||||
main()
|
||||
Reference in New Issue
Block a user