flawopen.com/SQL-Injection/Java

SQL-Injection in Java

Kritisch CWE-89 Draft — pending review
Language: English Português (Brasil) Español Français Deutsch Русский 简体中文 日本語 हिन्दी 한국어 Bahasa Indonesia
Einfach erklärt

Stell dir ein Formular vor, das nur eine Ticketnummer erwartet. SQL-Injection passiert, wenn jemand Code in dieses Feld eingibt, der die Datenbank dazu bringt, alle Daten herauszugeben, weil die Eingabe unbereinigt in den Befehl eingefügt wurde.

Schlüsselbegriffe auf dieser Seite
output encoding
Converting special markup characters into safe entities so browsers display them as text rather than script.

Was passiert

SQL-Injection in Java occurs when unvalidated strings are concatenated into JDBC Statement or HQL/JPQL queries.

Auswirkung in der Praxis

In 2005, the Samy XSS worm infected over 1 million user profiles on MySpace in under 20 hours, forcing the platform offline.

Documented historical AppSec case study.

Verwundbar vs. behoben

VULNERABLE
// userId comes straight from the request
String query = "SELECT * FROM users "
    + "WHERE id = " + userId;
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
FIXED
// value is bound, never concatenated
String query = "SELECT * FROM users WHERE id = ?";
PreparedStatement stmt =
    connection.prepareStatement(query);
stmt.setString(1, userId);
ResultSet rs = stmt.executeQuery();

Warum die Behebung funktioniert

PreparedStatement precompiles the query structure in the database engine, binding parameter values separately.

Sprachspezifische Gotchas

MyBatis: ${} vs #{}

#{} uses safe parameterized binding, while ${} performs raw string substitution.

Hibernate HQL/JPQL

Concatenating HQL queries is just as dangerous as raw SQL. Always use setParameter().

Häufige Missverständnisse

"Stored procedures prevent injection"

Only if the stored procedure itself uses parameters rather than dynamic EXECUTE strings.

Wie Sie prüfen, ob Sie betroffen sind

grep -rn "createStatement().*executeQuery(.*+" --include="*.java" .
Run SpotBugs with the FindSecBugs plugin in CI to catch SQL_INJECTION_JDBC automatically.

Präventions-Checkliste

Häufig gestellte Fragen

Is Spring Data JPA safe?

Derived queries (@Query) are safe if method parameters are bound with :param or ?1.

Referenzen

Siehe auch: Cross-Site Scripting Command InjectionPath Traversal