SQL injection remains one of the most critical web application vulnerabilities. In this post, I’ll walk through a real-world SQL injection discovery, exploitation, and remediation.
Background
During a recent penetration testing engagement, I discovered a second-order SQL injection vulnerability in a client’s web application that could lead to complete database compromise.
Discovery
The vulnerability was found in the user profile update functionality. While the initial input was properly sanitized, the stored data was later used in an unsafe SQL query:
# Vulnerable code example
username = sanitize_input(request.POST['username'])
save_to_database(username) # Stored safely
# Later in the code...
user_data = get_from_database(user_id)
query = f"SELECT * FROM logs WHERE username = '{user_data['username']}'" # VULNERABLE!
execute_query(query)
Exploitation
Payload used:
admin' UNION SELECT table_name,column_name,NULL FROM information_schema.columns--
This second-order injection allowed me to:
- Extract database schema
- Retrieve sensitive user data
- Potentially execute system commands (depending on DB permissions)
Impact Assessment
- Severity: Critical (CVSS 9.1)
- Data at Risk: All user PII, authentication credentials
- Potential Impact: Complete account takeover, data breach
Remediation
Immediate Fixes
- Use Parameterized Queries:
# Secure code
cursor.execute("SELECT * FROM logs WHERE username = ?", (username,))
- Input Validation:
- Whitelist allowed characters
- Implement length limits
- Validate data type expectations
- Least Privilege:
- Database user should have minimal required permissions
- Never use ‘root’ or ‘sa’ accounts for web applications
Long-term Security Improvements
- Implement Web Application Firewall (WAF)
- Regular security code reviews
- Automated SAST/DAST in CI/CD pipeline
- Security awareness training for developers
Testing Your Applications
Use tools like:
- sqlmap: Automated SQL injection detection
- Burp Suite: Manual testing and validation
- OWASP ZAP: Free alternative for vulnerability scanning
# Example sqlmap command
sqlmap -u "http://target.com/profile?id=1" --batch --dbs
Key Takeaways
- Second-order SQL injection is often overlooked
- Never trust data from your own database without validation
- Defense in depth: combine multiple security controls
- Regular security testing is essential
References
This blog post is part of my web application security series. Follow along for more deep dives into common vulnerabilities and exploitation techniques.
