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.2.tar.gz (28.5 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.2-py3-none-any.whl (11.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: sql_injection_scanner-1.0.2.tar.gz
  • Upload date:
  • Size: 28.5 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.2.tar.gz
Algorithm Hash digest
SHA256 5545a8fce3e19546d6b390c77e01aa69094a2f97137895bddb2fcc7f4cf099ca
MD5 c077ce16d7c080f1e053d6b1e3014262
BLAKE2b-256 c796605378b3cd0be3de11c457cddf708057ae4eb373d7d44bd60ad29e55f81a

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for sql_injection_scanner-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 b9a344bc5ea4d6ea372295745cf2f59f2b50b6437d99bbf023d18042430e8c3f
MD5 fb7d281f781a7503a72f6f60110361e0
BLAKE2b-256 491a213ee242523e9a782ae587c96cea525d6bb88d27c25851d3c8700a320b8c

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