Skip to content

Commit 5884dcc

Browse files
Add info folder with module explanations
Includes beginner-friendly .txt files explaining the purpose and code of each script (e.g., run.py, utils.py, etc.).
1 parent ef8fa36 commit 5884dcc

7 files changed

Lines changed: 623 additions & 0 deletions

info/detector_info.txt

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
2+
Filename: detector_info.txt
3+
4+
Line-by-Line Beginner-Friendly Explanation:
5+
6+
1. import sys
7+
- 'import' is a Python keyword used to include modules.
8+
- 'sys' is a built-in module that provides access to system-specific parameters and functions.
9+
10+
2. from utils import load_patterns, detect_sqli, log_attack
11+
- This imports specific functions from a custom module named 'utils'.
12+
- 'load_patterns' loads SQL injection patterns.
13+
- 'detect_sqli' checks if an input matches SQLi patterns.
14+
- 'log_attack' records details about suspicious input.
15+
16+
3. import colorama
17+
- Imports the 'colorama' module, which helps color text in the terminal.
18+
19+
4. from colorama import Fore, Style
20+
- Imports specific classes from colorama.
21+
- 'Fore' is used to change text color.
22+
- 'Style' is used to reset or style the text (like bold, reset, etc.).
23+
24+
6. colorama.init(autoreset=True)
25+
- Initializes colorama (needed for Windows compatibility).
26+
- 'autoreset=True' means colors reset automatically after each print.
27+
28+
8. patterns = load_patterns()
29+
- Calls 'load_patterns()' function and stores the result (list of patterns) in 'patterns'.
30+
31+
10. def main():
32+
- Defines a new function named 'main'. The main logic goes here.
33+
34+
11. print(f"{Fore.YELLOW}=== SQL Injection Detection Tool ==={Style.RESET_ALL}")
35+
- Displays a title in yellow color using f-string (formatted string).
36+
37+
12. print("Type 'exit' to quit.\n")
38+
- Shows instruction. '\n' adds a new line.
39+
40+
14. while True:
41+
- Starts an infinite loop. Will keep asking for input until user types 'exit'.
42+
43+
15. payload = input("Enter input (simulated payload): ").strip()
44+
- Asks the user for input.
45+
- '.strip()' removes any leading/trailing whitespace.
46+
47+
16. if payload.lower() == 'exit':
48+
- Checks if the input (in lowercase) is 'exit'.
49+
50+
17. print(f"{Fore.YELLOW}Exiting the tool.{Style.RESET_ALL}")
51+
- If yes, prints exit message in yellow.
52+
53+
18. break
54+
- Stops the loop.
55+
56+
20. ip = "127.0.0.1"
57+
- Sets a dummy IP address (localhost).
58+
59+
21. endpoint = "/test"
60+
- Sets a dummy endpoint name.
61+
62+
23. matched_pattern = detect_sqli(payload, patterns)
63+
- Calls 'detect_sqli' function to check if the input matches SQLi patterns.
64+
65+
24. if matched_pattern:
66+
- If SQLi is detected (function returned a pattern):
67+
68+
25. print(f"{Fore.RED}[!] SQL Injection Detected!{Style.RESET_ALL} Pattern matched: {Fore.RED}{matched_pattern}{Style.RESET_ALL}\n")
69+
- Displays a red warning message and the matched pattern.
70+
71+
26. log_attack(ip, endpoint, payload, matched_pattern)
72+
- Records the suspicious input to a log (e.g., a file or console).
73+
74+
28. else:
75+
- If no pattern matched (no SQLi detected):
76+
77+
29. print(f"{Fore.GREEN}[+] Clean input. No SQLi detected.{Style.RESET_ALL}\n")
78+
- Shows green success message.
79+
80+
31. if __name__ == "__main__":
81+
- Ensures the 'main()' function only runs when the file is executed directly (not when imported).
82+
83+
32. main()
84+
- Calls the main function to start the tool.

info/pattern_info.txt

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Detects common SQL injection symbols:
2+
# It is a single non-capturing group that checks for:
3+
# (?i) → Case-insensitive
4+
# - %27 = URL encoded single quote (')
5+
# - '-- = Comment to ignore the rest of the SQL query
6+
# - %23 or # = URL encoded or direct comment marker
7+
# # (SQL comment)
8+
(?i)(%27|'|--|%23|#)
9+
10+
# Detects use of OR/AND with always-true logic like: OR 1=1 or AND 1=1
11+
# This is a classic SQL injection trick to bypass authentication
12+
#\bOR\b / \bAND\b → Detects "OR" or "AND" as full words
13+
#\s+ → Requires space after OR/AND
14+
#\d+=\d+ → Looks for always-true condition (e.g., 1=1)
15+
(?i)(\bOR\b|\bAND\b)\s+\d+=\d+
16+
17+
# Detects use of UNION SELECT which is often used to extract data from another table
18+
# E.g., ' UNION SELECT username, password FROM users
19+
#UNION SELECT → Used to extract data from another table
20+
(?i)UNION\s+SELECT
21+
22+
# Detects SELECT queries with a common typo (SELECT ... FORM instead of FROM)
23+
# This may catch obfuscated or malformed injections
24+
#SELECT.+FORM → Catches SELECT queries with typo "FORM" instead of "FROM"
25+
(?i)SELECT.+FORM
26+
27+
# Detects INSERT INTO statements, used to insert malicious or unauthorized data
28+
#INSERT INTO → Used to add data to a table
29+
(?i)INSERT\s+INTO
30+
31+
# Detects DROP TABLE statements, which can delete database tables
32+
# Very dangerous if executed
33+
#DROP TABLE → Deletes a table
34+
(?i)DROP\s+TABLE
35+
36+
# Detects UPDATE queries that try to change values in a table (like passwords or access levels)
37+
#UPDATE <table> SET → Changes data in the table
38+
(?i)UPDATE\s+\w+\s+SET
39+
40+
# Detects EXEC commands that can run stored procedures or system commands (e.g., xp_cmdshell)
41+
#EXEC command → Executes stored procedures or commands
42+
(?i)EXEC\s+\w+
43+
44+
# Detects WAITFOR DELAY used in time-based blind SQL injections
45+
# E.g., WAITFOR DELAY '00:00:05'
46+
#WAITFOR DELAY '00:00:05' → Causes time delay
47+
(?i)WAITFOR\s+DELAY
48+
49+
# Detects use of SLEEP(seconds) in SQL, another form of time delay attack
50+
#SLEEP(5) → Pauses SQL execution for 5 seconds
51+
(?i)SLEEP\(\d+\)

info/report_generation_info.txt

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
# IMPORTING REQUIRED MODULES
2+
3+
import os
4+
# 'os' is a built-in Python module used to interact with the operating system.
5+
# os.path.join() combines directory and file names into a full path that works on all systems.
6+
7+
from fpdf import FPDF
8+
# 'fpdf' is a third-party library to create PDF files. 'FPDF' is the main class for PDF creation.
9+
10+
from datetime import datetime
11+
# 'datetime' is a built-in module. 'datetime.now()' gives the current date and time.
12+
13+
14+
# SETTING FILE PATHS
15+
16+
LOG_FILE = os.path.join("logs", "sqli_logs.txt")
17+
# Full path to the log file: "logs/sqli_logs.txt"
18+
19+
REPORTS_DIR = "reports"
20+
# Directory name where generated PDF reports will be saved.
21+
22+
23+
# CREATING CUSTOM PDF CLASS
24+
25+
class PDFReport(FPDF):
26+
# Inheriting from FPDF class to customize PDF behavior
27+
28+
def header(self):
29+
# This method defines what will appear at the top of each page
30+
self.set_font("Arial", "B", 14)
31+
# Sets font to Arial, Bold, size 14
32+
self.cell(0, 10, "SQL Injection Detection Report", 0, 1, "C")
33+
# Adds a centered title across full width (0), height 10
34+
self.ln(5)
35+
# Adds a 5-unit line break
36+
37+
def footer(self):
38+
# This method defines what appears at the bottom of each page
39+
self.set_y(-15)
40+
# Moves cursor 15 units from the bottom
41+
self.set_font("Arial", "I", 8)
42+
# Sets font to Arial, Italic, size 8
43+
page_num = f"Page {self.page_no()}"
44+
# f-string: embeds current page number dynamically
45+
self.cell(0, 10, page_num, 0, 0, "C")
46+
# Adds page number centered at the bottom
47+
48+
49+
# PARSING A SINGLE LOG LINE
50+
51+
def parse_log_line(line):
52+
# Accepts a single line from log file and extracts info
53+
54+
# Sample line format:
55+
# [2025-07-17 14:20:15] IP: 192.168.1.100 | Endpoint: /batch-test | Payload: 1 OR 1=1 | Pattern: OR\s\d+=\d+
56+
57+
parts = line.strip().split("|")
58+
# Removes leading/trailing spaces and splits line at '|'
59+
60+
if len(parts) < 4:
61+
return None
62+
# If parts are less than expected, return nothing
63+
64+
try:
65+
timestamp = line.split("]")[0].strip("[")
66+
# Extracts text inside square brackets at start
67+
68+
ip = parts[0].split("IP:")[1].strip()
69+
# Extracts IP address after "IP:"
70+
71+
endpoint = parts[1].split("Endpoint:")[1].strip()
72+
# Extracts URL endpoint
73+
74+
payload = parts[2].split("Payload:")[1].strip()
75+
# Extracts detected payload (e.g., SQLi input)
76+
77+
pattern = parts[3].split("Pattern:")[1].strip()
78+
# Extracts regex pattern that matched
79+
80+
return {
81+
"timestamp": timestamp,
82+
"ip": ip,
83+
"endpoint": endpoint,
84+
"payload": payload,
85+
"pattern": pattern
86+
}
87+
# Returns a dictionary of parsed values
88+
89+
except IndexError:
90+
# In case any split or index fails
91+
return None
92+
93+
94+
# MAIN FUNCTION TO GENERATE PDF REPORT
95+
96+
def generate_report():
97+
print("No logd Found to generate report.")
98+
# Message (but typo: 'logd' should be 'logs')
99+
return
100+
# Stops function here (you need to remove this to generate real reports)
101+
102+
os.makedirs(REPORTS_DIR, exist_ok=True)
103+
# Creates 'reports' directory if it doesn't exist
104+
105+
pdf = PDFReport()
106+
# Creates an instance of our custom PDF class
107+
108+
pdf.add_page()
109+
# Adds a new page to PDF
110+
111+
pdf.set_font("Arial", size=12)
112+
# Sets default font
113+
114+
with open(LOG_FILE, "r") as file:
115+
lines = file.readlines()
116+
# Opens the log file and reads all lines
117+
118+
if not lines:
119+
print("Log file is empty. No report generated.")
120+
return
121+
# Stops if no log entries found
122+
123+
for line in lines:
124+
entry = parse_log_line(line)
125+
# Parses each line into a structured dictionary
126+
127+
if entry:
128+
pdf.set_font("Arial", "B", 11)
129+
pdf.cell(0, 10, f"Timestamp: {entry['timestamp']}", ln=1)
130+
131+
pdf.set_font("Arial", size=11)
132+
pdf.cell(0, 8, f"IP: {entry['ip']} | Endpoint: {entry['endpoint']}", ln=1)
133+
134+
pdf.multi_cell(0, 8, f"Payload: {entry['payload']}")
135+
pdf.multi_cell(0, 8, f"Matched Pattern: {entry['pattern']}")
136+
pdf.ln(5)
137+
# Adds space after each log block
138+
139+
# Define filename with current datetime
140+
report_filename = os.path.join(REPORTS_DIR, f"sqli_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf")
141+
142+
pdf.output(report_filename)
143+
# Saves the generated PDF
144+
145+
print(f"Report generated: {report_filename}")
146+
# Confirms report generation
147+
148+
149+
# ENTRY POINT OF THE SCRIPT
150+
151+
if __name__ == "__main__":
152+
# Python keyword: runs code only if file is run directly, not imported
153+
generate_report()
154+
# Calls the report generation function

info/requirements_info.txt

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
2+
📦 PYTHON LIBRARY: FLASK
3+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
4+
• Flask is a **lightweight web framework** used to create web applications and APIs.
5+
6+
🔑 Common Flask Components:
7+
---------------------------
8+
from flask import Flask
9+
# Imports the main Flask class to create an app
10+
11+
app = Flask(__name__)
12+
# Creates a Flask web app instance
13+
14+
@app.route('/')
15+
# Decorator to define a URL route (e.g., "/")
16+
17+
def home():
18+
return "Welcome!"
19+
# Defines what to show when user visits the route
20+
21+
app.run(debug=True)
22+
# Starts the Flask server
23+
# debug=True auto-reloads and shows errors
24+
25+
26+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
27+
📦 PYTHON LIBRARY: FPDF
28+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
29+
• FPDF is a **Python library to generate PDF files** (like invoices, reports, etc.)
30+
31+
🔑 Common FPDF Usage:
32+
---------------------
33+
from fpdf import FPDF
34+
# Imports the FPDF class
35+
36+
pdf = FPDF()
37+
# Creates a new PDF object
38+
39+
pdf.add_page()
40+
# Adds a blank page to the PDF
41+
42+
pdf.set_font("Arial", size=12)
43+
# Sets the font for writing text
44+
45+
pdf.cell(200, 10, txt="Hello PDF", ln=1, align='C')
46+
# Adds a text cell: width=200, height=10, text, new line, centered
47+
48+
pdf.output("output.pdf")
49+
# Saves the PDF file with this name
50+
51+
52+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
53+
📦 PYTHON LIBRARY: COLORAMA
54+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
55+
• Colorama is used to **add colors to terminal output** (text in red, green, etc.)
56+
• Works on Windows, Linux, macOS.
57+
58+
🔑 Common Colorama Usage:
59+
-------------------------
60+
from colorama import Fore, Style, init
61+
# Fore: for text color
62+
# Style: for styles like RESET
63+
# init(): to initialize colorama
64+
65+
init()
66+
# Initializes colorama (needed on Windows)
67+
68+
print(Fore.RED + "Error occurred")
69+
# Prints red text
70+
71+
print(Style.RESET_ALL)
72+
# Resets color to default
73+
74+
75+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
76+
📦 PYTHON LIBRARY: REQUESTS
77+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
78+
• Requests is used to **send HTTP requests** (GET, POST, etc.) easily in Python.
79+
80+
🔑 Common Requests Usage:
81+
-------------------------
82+
import requests
83+
# Imports the requests module
84+
85+
res = requests.get("http://example.com")
86+
# Sends a GET request to the URL
87+
88+
print(res.text)
89+
# Prints the response body (HTML/text)
90+
91+
data = {"username": "admin", "password": "1234"}
92+
res = requests.post("http://site.com/login", data=data)
93+
# Sends POST request with form data
94+
95+
if res.status_code == 200:
96+
print("Success!")
97+
# Checks if response was OK (status code 200)

0 commit comments

Comments
 (0)