Understanding SQL Injection
SQL injection is a prevalent form of cyber attack that exploits vulnerabilities in database query construction. It typical occurs when user input is directly concatenated into SQL queries without proper validation or sanitization, allowing attackers to manipulate SQL logic or execute arbitrary commands.
Example of SQL Injection
Consider a query built using string concatenation:
String query = "SELECT id, no FROM users WHERE id = " + id;
If the input for id is 2 OR 1=1, the resulting query becomes:
SELECT id, no FROM users WHERE id = 2 OR 1=1;
This retrieves all record from the table, bypassing intended access controls. In more severe cases, atackers can delete or alter data by injecting commands like 1'; DROP TABLE users;--.
Attack Strategy Overview
- Identify input fields vulnerable to injection
- Determine backend database type and structure
- Inject malicious SQL tailored to the target system
Prevention Methods
1. Use Prepared Statements
Prepared statements separate SQL logic from data inputs, preventing attackers from altering query structure:
String sql = "SELECT * FROM users WHERE id = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, userId);
ResultSet rs = pstmt.executeQuery();
This approach ensures inputs are treated strictly as data, not executable code.
2. Input Validation with Regular Expressions
Implement pattern matching to detect dangerous keywords or syntax:
import java.util.regex.*;
boolean isSafe = Pattern.matches("^[^\\s;'\"]+$", input);
More complex regex patterns can detect SQL command patterns:
String sqlPattern = "((%27)|').*(exec|select|drop).*";
3. Blacklist Filtering
Check inputs against known dangerous keywords:
public static boolean containsMaliciousContent(String input) {
String[] blacklist = {"'", "and", "select", "delete", "union"};
for (String term : blacklist) {
if (input.contains(term)) return true;
}
return false;
}
4. Server-Side Validation Class
Implement reusable validation components:
public class SqlValidator {
public static boolean validateInput(String input) {
String[] forbidden = {"'", "--", "drop", "exec"};
for (String token : forbidden) {
if (input.contains(token)) return false;
}
return true;
}
}
5. Client-Side JavaScript Filtering
Basic front-end validation for immediate feedback:
function sanitizeInput(value) {
const forbiddenChars = ["'", "\\", "/"];
for (let char of forbiddenChars) {
if (value.includes(char)) return false;
}
return true;
}