Skip to main content

SQL Injection Scanner

PyPI version Python 3.6+ License: MIT

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

  1. Review findings in context - Check the actual code and risk level
  2. Use parameterized queries - Even if flagged as LOW risk
  3. 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:


Version: 1.0.0
Last Updated: 2024

Metadata

Release files for sql-injection-scanner 1.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for sql-injection-scanner 1.0.3
File Size Uploaded Provenance Actions
sql_injection_scanner-1.0.3.tar.gz 28.7 kB Without provenance Details for sql_injection_scanner-1.0.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for sql-injection-scanner 1.0.3
File Interpreter ABI Platform Actions
sql_injection_scanner-1.0.3-py3-none-any.whl Python 3 none any Details for sql_injection_scanner-1.0.3-py3-none-any.whl

Total release size: 40.1 kB

Release files / sql_injection_scanner-1.0.3.tar.gz

Download URL sql_injection_scanner-1.0.3.tar.gz
Size 28.7 kB
Tags Source
SHA-256 checksum
How to use checksums
ea12f170bec4a0124f94a206ca6977e10c7fb22505d4de7fc38bb6cd18d02f74
BLAKE2b-256 checksum
How to use checksums
87c01e9b45c22bbf9eeb45f68971b4b82fb9778e471501f75fa988bddaefca5a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.9

Release files / sql_injection_scanner-1.0.3-py3-none-any.whl

Download URL sql_injection_scanner-1.0.3-py3-none-any.whl
Size 11.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7179a76509e6ea989b64c52ae37396e8dad04c0329a5d370e5f5ee791d557699
BLAKE2b-256 checksum
How to use checksums
4ffc08bae16b12b18101502ef25f964e8734009dc253294c0f6642d64fb181b4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.9

Security for sql-injection-scanner 1.0.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page