CWE-564 Variante Incompleto

SQL Injection: Hibernate

This vulnerability occurs when an application uses Hibernate to construct dynamic SQL queries with unsanitized user input, allowing an attacker to alter the query's logic or execute unauthorized SQL…

Definição

What is CWE-564?

This vulnerability occurs when an application uses Hibernate to construct dynamic SQL queries with unsanitized user input, allowing an attacker to alter the query's logic or execute unauthorized SQL commands.
Hibernate is a popular Object-Relational Mapping (ORM) framework for Java, designed to simplify database interactions. However, when developers bypass its parameterized query mechanisms and directly concatenate user-controlled data into Hibernate Query Language (HQL) or Criteria API statements, it creates the same injection risks as traditional SQL. Attackers can exploit this by injecting malicious code through form inputs, URLs, or other data channels, potentially leading to data theft, corruption, or full system compromise. To prevent this, always use Hibernate's parameter binding features, such as named parameters (:param) or positional parameters (?), which ensure input is treated as data, not executable code. Additionally, adopt the principle of least privilege for database accounts, validate and sanitize all input on the server side, and use Hibernate's built-in escaping functions for any dynamic elements. Regular security testing, including automated DAST/SAST scans and manual code reviews focused on query construction patterns, is essential for identifying and remediating these flaws early in the development lifecycle.
Impacto no mundo real

Real-world CVEs caused by CWE-564

Ainda não há referências CVE públicas associadas a este CWE no catálogo da MITRE.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    Identificar um caminho de código que trata input não confiável sem validação.

  2. 2

    Criar um payload que explora o comportamento inseguro — injeção, traversal, overflow ou abuso de lógica.

  3. 3

    Entregar o payload através de um pedido normal e observar a reação da aplicação.

  4. 4

    Iterar até que a resposta exponha dados, execute código do atacante ou escale privilégios.

Exemplo de código vulnerável

Vulnerable Java

The following code excerpt uses Hibernate's HQL syntax to build a dynamic query that's vulnerable to SQL injection.

Vulnerável Java
String street = getStreetFromUser();
  Query query = session.createQuery("from Address a where a.street='" + street + "'");
Exemplo de código seguro

Secure pseudo

Seguro pseudo
// Validate, sanitize, or use a safe API before reaching the sink.
function handleRequest(input) {
  const safe = validateAndEscape(input);
  return executeWithGuards(safe);
}
What changed: the unsafe sink is replaced (or the input is validated/escaped) so the same payload no longer triggers the weakness.
Lista de verificação de prevenção

How to prevent CWE-564

  • Requirements A non-SQL style database which is not subject to this flaw may be chosen.
  • Architecture and Design Follow the principle of least privilege when creating user accounts to a SQL database. Users should only have the minimum privileges necessary to use their account. If the requirements of the system indicate that a user can read and modify their own data, then limit their privileges so they cannot read/write others' data.
  • Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
  • Implementation Implement SQL strings using prepared statements that bind variables. Prepared statements that do not bind variables can be vulnerable to attack.
  • Implementation Use vigorous allowlist style checking on any user input that may be used in a SQL command. Rather than escape meta-characters, it is safest to disallow them entirely. Reason: Later use of data that have been entered in the database may neglect to escape meta-characters before use. Narrowly define the set of safe characters based on the expected value of the parameter in the request.
Sinais de deteção

How to detect CWE-564

SAST High

Executar análise estática (SAST) na base de código à procura do padrão inseguro no fluxo de dados.

DAST Moderate

Executar testes dinâmicos de segurança de aplicações (DAST) contra o endpoint em execução.

Runtime Moderate

Monitorizar os registos em tempo de execução para traços de exceção invulgares, input malformado ou tentativas de contornar a autorização.

Code review Moderate

Revisão de código: sinalizar qualquer novo código que trate input desta superfície sem usar os ajudantes validados do framework.

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-564 e abre um PR de correção em menos de 60 segundos.

O Codex Remedium analisa cada commit, identifica esta fraqueza exata e entrega um pull request pronto para revisão com o patch. Sem tickets. Sem transferências.

Perguntas frequentes

Frequently asked questions

O que é o CWE-564?

This vulnerability occurs when an application uses Hibernate to construct dynamic SQL queries with unsanitized user input, allowing an attacker to alter the query's logic or execute unauthorized SQL commands.

Qual a gravidade do CWE-564?

A MITRE não publicou uma classificação de probabilidade de exploração para esta fraqueza. Trate-a como impacto médio até o seu modelo de ameaças provar o contrário.

Que linguagens ou plataformas são afetadas pelo CWE-564?

MITRE lists the following affected platforms: SQL, Database Server.

Como posso prevenir o CWE-564?

A non-SQL style database which is not subject to this flaw may be chosen. Follow the principle of least privilege when creating user accounts to a SQL database. Users should only have the minimum privileges necessary to use their account. If the requirements of the system indicate that a user can read and modify their own data, then limit their privileges so they cannot read/write others' data.

Como é que o Plexicus deteta e corrige o CWE-564?

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-564 em cada commit. Quando é encontrada uma correspondência, o nosso agente Codex Remedium abre um PR de correção com o código corrigido, testes e um resumo de uma linha para o revisor.

Onde posso saber mais sobre o CWE-564?

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/564.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.

Pronto quando você estiver

Pare de pagar por desenvolvedor.
Comece a fechar o ciclo.

O Plexicus é o ASPM nativo de IA que verifica, filtra, corrige, pentesta e explica — de forma autónoma. Programadores ilimitados, repos ilimitados, ações de IA de utilização justa. Nível gratuito real, €269/mo anual quando estiver pronto.