A comprehensive scanner for detecting SQL injection vulnerabilities in Python code
Project description
SQL Injection Scanner
A comprehensive Python tool to scan your codebase for potential SQL injection vulnerabilities, with a focus on detecting unsafe f-strings and string formatting in database queries.
Overview
The SQL Injection Scanner analyzes Python source code to identify potentially dangerous SQL query construction patterns. It detects multiple vulnerability patterns and generates detailed, color-coded Excel reports with risk level classifications.
Key Features
-
🎯 Multi-Pattern Detection
- F-strings in SQL queries (HIGH RISK)
- String concatenation in SQL queries (HIGH RISK)
.format()method usage (MEDIUM RISK)%formatting in SQL queries (MEDIUM RISK)
-
📊 Risk Level Classification
- HIGH: Immediate action required
- MEDIUM: Should be reviewed and fixed
- LOW: Monitor for patterns
-
📈 Excel Report Generation
- Formatted Excel workbook with detailed findings
- Summary sheet with statistics
- Color-coded rows by risk level
- Sortable and filterable data
-
🚀 Easy Integration
- Command-line interface
- Python API for programmatic use
- Configurable scanning patterns
- Smart filtering for safe parameterized queries
Installation
From PyPI
pip install sql-injection-scanner
From Source
git clone https://github.com/PioManojDatt/sql-query-injection-scanner.git
cd sql-query-injection-scanner
pip install -e .
Requirements
- Python 3.6+
- openpyxl (automatically installed as a dependency)
Usage
Command Line
Run the scanner on the current directory:
sql-injection-scanner
Scan a specific directory:
sql-injection-scanner /path/to/your/project
Specify output file:
sql-injection-scanner /path/to/project -o custom_report.xlsx
View help:
sql-injection-scanner --help
Python API
from sql_injection_scanner import SQLInjectionScanner
# Create scanner instance
scanner = SQLInjectionScanner('/path/to/your/project')
# Run scan
findings = scanner.scan()
# Generate Excel report
scanner.generate_excel_report('vulnerability_report.xlsx')
# Access findings programmatically
for finding in findings:
print(f"{finding['file_path']}:{finding['line_number']} - {finding['risk_level']}")
Output
Excel Report
The scanner generates sql_injection_report.xlsx with two sheets:
Sheet 1: "SQL Injection Findings"
| Column | Description |
|---|---|
| File Path | Relative path to the vulnerable file |
| Module Name | Python module name (filename without extension) |
| Line Number | Line number where issue was detected |
| Pattern | Type of vulnerability detected |
| Risk Level | HIGH, MEDIUM, or LOW |
| Code Snippet | The actual problematic code |
Rows are color-coded:
- 🔴 RED (HIGH): Immediate action required
- 🟠 ORANGE (MEDIUM): Should be reviewed and fixed
- 🟡 YELLOW (LOW): Monitor for patterns
Sheet 2: "Summary"
Summary statistics including:
- Total number of findings
- Breakdown by risk level (HIGH, MEDIUM, LOW)
- Scan location
Vulnerability Patterns Detected
HIGH RISK: F-String SQL Construction
# ❌ VULNERABLE
user_id = request.args.get('id')
query = f"SELECT * FROM users WHERE id = {user_id}"
Fix: Use parameterized queries
# ✅ SAFE
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
HIGH RISK: String Concatenation
# ❌ VULNERABLE
query = "SELECT * FROM users WHERE name = '" + username + "'"
Fix: Use parameterized queries
# ✅ SAFE
cursor.execute("SELECT * FROM users WHERE name = %s", (username,))
MEDIUM RISK: .format() Method
# ❌ POTENTIALLY VULNERABLE
query = "SELECT * FROM users WHERE email = '{}'".format(email)
Fix: Use parameterized queries
# ✅ SAFE
cursor.execute("SELECT * FROM users WHERE email = %s", (email,))
MEDIUM RISK: % Formatting
# ❌ POTENTIALLY VULNERABLE
query = "SELECT * FROM users WHERE id = %s" % (user_id)
Fix: Use parameterized queries with proper libraries
# ✅ SAFE
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
Configuration
Python API Options
scanner = SQLInjectionScanner(
root_dir='/path/to/project' # Directory to scan
)
# Customize output
scanner.generate_excel_report(
output_file='my_report.xlsx'
)
Best Practices
Using Parameterized Queries
psycopg2:
import psycopg2
conn = psycopg2.connect("dbname=test user=postgres")
cursor = conn.cursor()
# Safe: Use parameterized queries
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
results = cursor.fetchall()
SQLAlchemy (ORM - Recommended):
from sqlalchemy import create_engine, text
engine = create_engine('postgresql://user:password@localhost/dbname')
with engine.connect() as conn:
result = conn.execute(
text("SELECT * FROM users WHERE id = :user_id"),
{"user_id": user_id}
)
Django ORM (Recommended):
from django.db import connection
# Safe: Use ORM
users = User.objects.filter(id=user_id)
# Or use parameterized raw SQL
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM users WHERE id = %s", [user_id])
row = cursor.fetchone()
Understanding Results
False Positives
The scanner may flag safe code patterns if they:
- Contain SQL keywords in comments or documentation strings
- Use variables that happen to match keyword patterns
Handling False Positives
- Review findings in context - Check the actual code and risk level
- Use parameterized queries - Even if flagged as LOW risk
- Report issues - If you find consistent false positives
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Bug Reports
Found a bug? Please report it on GitHub Issues.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Disclaimer
This tool provides automated scanning for common SQL injection patterns. It is not a substitute for professional security audits and code reviews. Always conduct thorough security testing before deploying applications to production.
Support
For questions, issues, or suggestions:
- Open an issue on GitHub
- Email: contact@PioManojDatt.com
Related Resources
Version: 1.0.0
Last Updated: 2024
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sql_injection_scanner-1.0.1.tar.gz.
File metadata
- Download URL: sql_injection_scanner-1.0.1.tar.gz
- Upload date:
- Size: 14.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
598d6c2f64fd2ca6683b666cff4379afd28dcfd51be3d1e0925e9cda7a4f7628
|
|
| MD5 |
3ec60056e1b019457eabc00592a8d4ae
|
|
| BLAKE2b-256 |
781ed4eebf2cf0f6b13b63530f6c59192a316694357e28e852ed60d6938e5feb
|
File details
Details for the file sql_injection_scanner-1.0.1-py3-none-any.whl.
File metadata
- Download URL: sql_injection_scanner-1.0.1-py3-none-any.whl
- Upload date:
- Size: 11.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
88e5bf2dbdaf1fa2e93927b821ba91ff33e7aabc4dd465993fabe35e41667714
|
|
| MD5 |
46b6b35113350e6684035dcfa4548aa0
|
|
| BLAKE2b-256 |
f06203d752f40bfcac70c7b2e71bc63660cb095ddd644ffa6f4121e43641b72b
|