SQL injection in Cybersecurity - Time & Space Complexity
When analyzing SQL injection, we want to understand how the attack's effort grows as the input size changes.
We ask: How does the number of operations needed to exploit or detect SQL injection scale with input length?
Analyze the time complexity of the following vulnerable SQL query construction.
user_input = get_input()
query = "SELECT * FROM users WHERE username = '" + user_input + "'"
execute(query)
This code builds a SQL query by directly inserting user input, which can be exploited by attackers.
Look for repeated actions that affect performance or attack effort.
- Primary operation: Scanning the database for matching rows based on the input.
- How many times: Once per query, but the query complexity depends on input length and injected commands.
Longer inputs can cause the database to process more complex queries, especially if injection adds conditions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Simple query, few operations |
| 100 | More complex query, more operations |
| 1000 | Very complex query, many operations |
Pattern observation: As input grows, the database work grows roughly in proportion to input length and complexity.
Time Complexity: O(n)
This means the work to process the query grows linearly with the length of the user input.
[X] Wrong: "SQL injection attacks always take constant time regardless of input size."
[OK] Correct: Longer or more complex injected inputs can cause the database to do more work, increasing execution time.
Understanding how input size affects SQL injection helps you explain risks clearly and shows you grasp how attacks scale in real systems.
What if the code used prepared statements instead of string concatenation? How would the time complexity change?