Skip to main content

A comprehensive scanner for detecting SQL injection vulnerabilities in Python code

Project description

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:

Related Resources


Version: 1.0.0
Last Updated: 2024

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sql_injection_scanner-1.0.3.tar.gz (28.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sql_injection_scanner-1.0.3-py3-none-any.whl (11.4 kB view details)

Uploaded Python 3

File details

Details for the file sql_injection_scanner-1.0.3.tar.gz.

File metadata

  • Download URL: sql_injection_scanner-1.0.3.tar.gz
  • Upload date:
  • Size: 28.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.9

File hashes

Hashes for sql_injection_scanner-1.0.3.tar.gz
Algorithm Hash digest
SHA256 ea12f170bec4a0124f94a206ca6977e10c7fb22505d4de7fc38bb6cd18d02f74
MD5 a1ed0eb4bc047b9703212866f02a31a7
BLAKE2b-256 87c01e9b45c22bbf9eeb45f68971b4b82fb9778e471501f75fa988bddaefca5a

See more details on using hashes here.

File details

Details for the file sql_injection_scanner-1.0.3-py3-none-any.whl.

File metadata

File hashes

Hashes for sql_injection_scanner-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 7179a76509e6ea989b64c52ae37396e8dad04c0329a5d370e5f5ee791d557699
MD5 e31a840dee38d9a6884f50d4689eb045
BLAKE2b-256 4ffc08bae16b12b18101502ef25f964e8734009dc253294c0f6642d64fb181b4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page