Blog | G5 Cyber Security

SQL Injection: Preventing Query Substitution

TL;DR

Attackers might try to change your database queries (inject their own) if you don’t handle user input carefully. This guide shows how to protect against this using prepared statements and input validation.

What is Query Substitution?

Query substitution, often called SQL injection, happens when an attacker inserts malicious SQL code into your application through user inputs (like forms or search boxes). If your application doesn’t properly sanitise these inputs, the injected code can be executed against your database.

How to Prevent Query Substitution

  1. Use Prepared Statements (Parameterized Queries)
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()

# Bad - vulnerable to SQL injection
# user_input = input("Enter username:")
# query = "SELECT * FROM users WHERE username = '" + user_input + "'"
# cursor.execute(query)

# Good - using a prepared statement
user_input = input("Enter username:")
query = "SELECT * FROM users WHERE username = ?"
cursor.execute(query, (user_input,)) # Pass user input as a tuple

results = cursor.fetchall()
for row in results:
  print(row)
conn.close()
  • Input Validation
  • def validate_number(input_string):
      try:
        int(input_string)
        return True
      except ValueError:
        return False
    
    user_age = input("Enter your age:")
    if validate_number(user_age):
      # Use the validated age in a prepared statement
      query = "SELECT * FROM users WHERE age = ?"
      cursor.execute(query, (int(user_age),))
    else:
      print("Invalid input. Please enter a number.")
  • Least Privilege Principle
  • Web Application Firewalls (WAFs)
  • Regular Security Audits & Penetration Testing
  • Important Considerations

    Exit mobile version