flawopen.com/Injeção de SQL/Java

Injeção de SQL in Java

Crítica CWE-89 Draft — pending review
Language: English Português (Brasil) Español Français Deutsch Русский 简体中文 日本語 हिन्दी 한국어 Bahasa Indonesia
Explicação simples (ELI5)

Imagine um guichê que só espera um número de protocolo. A injeção de SQL acontece quando alguém digita uma frase mágica que faz o sistema revelar todos os protocolos salvos.

Termos-chave nesta página
output encoding
Converting special markup characters into safe entities so browsers display them as text rather than script.

O que está acontecendo

Injeção de SQL in Java occurs when unvalidated strings are concatenated into JDBC Statement or HQL/JPQL queries.

Impacto no mundo real

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.

Vulnerável vs. corrigido

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();

Por que a correção funciona

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

Armadilhas específicas da linguagem

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().

Mitos comuns

"Stored procedures prevent injection"

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

Como verificar se você foi afetado

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

Lista de verificação de prevenção

Perguntas frequentes

Is Spring Data JPA safe?

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

Referências

Veja também: Cross-Site Scripting Command InjectionPath Traversal