Skip to content

ibrah5em/sql-injection-shield

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ” SQL Injection Prevention with Python + Flask

Python Flask SQL Server Security Status

πŸ’‘ A beginner-friendly project to explore backend development, database security, and SQL injection prevention using Python and Flask.


πŸ“˜ Introduction

When I first thought about SQL, the image that came to mind was a hacker injecting malicious queries into a website. My curiosity led me to learn about SQL Injection, how it works, and how to defend against it.

To explore this, I built a simple yet practical app with two goals:

  1. βœ… Create a Python script to connect to a SQL Server database.
  2. πŸ” Build a backend that filters and blocks SQL injection attempts.

Although I had only basic knowledge of relational databases, I saw this as a great opportunity to go beyond the assignment and learn something useful for real-world development.


πŸš€ Project Overview

In a web application:

  • The frontend sends user inputs (e.g., login credentials).
  • The backend processes requests and interacts with the database.
  • If not secured, the backend becomes vulnerable to SQL injection.

βœ… This project aims to secure the backend by validating input using regular expressions, preventing malicious SQL statements.

Data Flowchart

🧠 Tip: In real-world applications, a dedicated Secure API can be used to filter malicious requests more effectively.


🧱 Tech Stack

Layer Technology
Frontend HTML, CSS, JavaScript
Backend Python, Flask
Database Microsoft SQL Server
Security Regex-based Input Validation

🎨 Frontend Preview

A simple login form built using HTML, CSS, and JavaScript β€” no frameworks used.

Login Form

πŸ“ File Structure:

/Project-Files/
β”œβ”€β”€ template/
β”œβ”€β”€ static/

πŸ—ƒοΈ Database Setup

Created using Microsoft SQL Server:

CREATE TABLE users (
    id INT PRIMARY KEY IDENTITY(1,1),
    username NVARCHAR(50) NOT NULL,
    password NVARCHAR(50) NOT NULL
);

-- Insert example data
INSERT INTO users (username, password) VALUES ('admin', 'admin');

πŸ“Œ Database Name: myDB


πŸ”Œ Backend Setup

πŸ“¦ Installation

pip install pyodbc Flask
  • pyodbc: For connecting to SQL Server
  • Flask: Lightweight web framework

πŸ› οΈ Database Connection

import pyodbc as odbc

conn_str = (
    r'DRIVER={SQL Server};'
    r'SERVER=X\SQLEXPRESS;'
    'DATABASE=myDB;'
    'Trusted_Connection=yes;'
)

conn = odbc.connect(conn_str)

πŸ“ Replace X\SQLEXPRESS with your actual SQL Server name. Use:

SELECT @@SERVERNAME

βš™οΈ Flask App Example

from flask import Flask, render_template, request
import re

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to the secure app!'

if __name__ == '__main__':
    app.run(debug=True)

πŸ›‘οΈ SQL Injection Prevention

Using regular expressions to validate user input:

import re

if not re.match(r'^[a-zA-Z0-9_]+$', username):
    return 'Invalid username format'
if not re.match(r'^[a-zA-Z0-9_]+$', password):
    return 'Invalid password format'

βœ”οΈ Only allows alphanumeric characters and underscores ❌ Blocks characters like ', ;, --, etc., which are often used in injection attempts


πŸ§ͺ Regex Demo

pattern = r'^[a-zA-Z0-9_]+$'
username = 'user123'

if re.match(pattern, username):
    print('βœ… Valid username')

πŸ“‚ Project Files

Project structure located in /Project-Files. Built with Visual Studio Code.

To start the server:

python app.py

βœ… Output

* Running on http://127.0.0.1:5000/
* Debug mode: on

Visit: http://127.0.0.1:5000


πŸ” SQL Injection Testing

Tried a basic injection attempt on the login form:

SQL Injection Attempt

Result: βœ… Rejected with Invalid username format β€” injection blocked!


πŸ’Ύ Bonus: Run SQL from File

Included a helper function to execute .sql files if needed:

def execute_sql_file(file_path):
    with open(file_path, 'r') as file:
        sql_commands = file.read().split(';')
    conn = pyodbc.connect(conn_str)
    cursor = conn.cursor()
    for command in sql_commands:
        if command.strip():
            cursor.execute(command)
    conn.commit()
    cursor.close()
    conn.close()

Use this to auto-run /SQL/create_tables.sql (optional).


🧠 Lessons Learned

  • βœ”οΈ Connecting Python to SQL Server using pyodbc
  • βœ”οΈ Handling HTTP requests using Flask
  • βœ”οΈ Validating user input with regex
  • βœ”οΈ Preventing SQL Injection in simple web apps

πŸ“Œ Final Notes

This was my first backend project combining Flask with a relational database. The app runs securely, blocks SQL injection, and reinforces backend fundamentals. I'm excited to continue building more secure apps and learning deeper concepts!


πŸ™ Acknowledgments

This project was completed as part of the Information Security course at Antioch Syrian University, under the guidance of Ms. Nabiha Halak.

Thank you for the valuable insights and support throughout the assignment.

About

Flask app demonstrating SQL injection prevention using regex validation. Beginner-friendly backend security project with Python, SQL Server, and practical defense implementation.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors