💉 SQL Injection Attack Flow
Interactive diagram showing how SQL injection attacks work
flowchart TD
A[👤 Attacker] -->|1. Enters malicious input| B[🌐 Web Application]
B -->|2. Constructs SQL query with unsanitized input| C[(🗄️ Database)]
C -->|3. Executes malicious query| D[📊 Sensitive Data Exposed]
D -->|4. Returns data to application| B
B -->|5. Displays data to attacker| A
style A fill:#ff3131,stroke:#cc0000,stroke-width:2px,color:#fff
style B fill:#fbbf24,stroke:#00cc74,stroke-width:2px,color:#0d1117
style C fill:#f59e0b,stroke:#00cc33,stroke-width:2px,color:#0d1117
style D fill:#ff3131,stroke:#cc0000,stroke-width:2px,color:#fff
E[🔒 Defense:
Parameterized Queries] -.->|Prevents| B
F[🛡️ Defense:
Input Validation] -.->|Sanitizes| B
G[⚙️ Defense:
Least Privilege] -.->|Limits| C
style E fill:#f59e0b,stroke:#00cc33,stroke-width:2px,color:#0d1117
style F fill:#f59e0b,stroke:#00cc33,stroke-width:2px,color:#0d1117
style G fill:#f59e0b,stroke:#00cc33,stroke-width:2px,color:#0d1117
📋 Attack Flow Breakdown
1
Attacker Input: The attacker enters malicious SQL code into a form field, URL parameter, or any user input.
Example: admin' OR '1'='1
2
Unsafe Query Construction: The application builds a SQL query by concatenating the malicious input without proper sanitization.
query = "SELECT * FROM users WHERE username='" + input + "'"
3
Malicious Execution: The database executes the tampered query, bypassing authentication or exposing data.
Executed: SELECT * FROM users WHERE username='admin' OR '1'='1'
4
Data Breach: Sensitive data (passwords, credit cards, personal info) is returned to the application.
5
Information Disclosure: The attacker receives unauthorized access to data or bypasses authentication.
🛡️ Defense Mechanisms
✅ Parameterized Queries (Best Practice):
Use prepared statements that separate SQL code from data.
cursor.execute("SELECT * FROM users WHERE username=?", (input,))
✅ Input Validation:
Validate and sanitize all user input using whitelisting.
Reject suspicious characters: ' " ; -- /* */
✅ Least Privilege:
Database accounts should have minimal permissions.
Don't use admin accounts for web applications!
✅ Use ORMs:
Object-Relational Mappers (SQLAlchemy, Hibernate, Entity Framework) automatically prevent SQL injection.