CWE-111 Variante Rascunho

Direct Use of Unsafe JNI

This weakness occurs when a Java application directly calls native code through the Java Native Interface (JNI), exposing the entire application to security risks present in that external code, even…

Definição

What is CWE-111?

This weakness occurs when a Java application directly calls native code through the Java Native Interface (JNI), exposing the entire application to security risks present in that external code, even if Java itself is safe from those specific flaws.
Using JNI bypasses the critical security safeguards built into the Java runtime. Native code operates outside the protections of Java's memory management, strong type checking, and automatic array bounds validation. This means vulnerabilities like buffer overflows, which Java prevents, become possible and can compromise your application. You must manually audit all native code called via JNI, as you cannot rely on Java's runtime security. The languages used for native implementations (like C/C++) often require careful manual memory and input validation. A flaw in the native component can undermine the security of your entire Java application.
Impacto no mundo real

Real-world CVEs caused by CWE-111

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

    The following code defines a class named Echo. The class declares one native method (defined below), which uses C to echo commands entered on the console back to the user. The following C code defines the native method implemented in the Echo class:

  2. 2

    Because the example is implemented in Java, it may appear that it is immune to memory issues like buffer overflow vulnerabilities. Although Java does do a good job of making memory operations safe, this protection does not extend to vulnerabilities occurring in source code written in other languages that are accessed using the Java Native Interface. Despite the memory protections offered in Java, the C code in this example is vulnerable to a buffer overflow because it makes use of gets(), which does not check the length of its input.

  3. 3

    The Sun Java(TM) Tutorial provides the following description of JNI [See Reference]: The JNI framework lets your native method utilize Java objects in the same way that Java code uses these objects. A native method can create Java objects, including arrays and strings, and then inspect and use these objects to perform its tasks. A native method can also inspect and use objects created by Java application code. A native method can even update Java objects that it created or that were passed to it, and these updated objects are available to the Java application. Thus, both the native language side and the Java side of an application can create, update, and access Java objects and then share these objects between them.

  4. 4

    The vulnerability in the example above could easily be detected through a source code audit of the native method implementation. This may not be practical or possible depending on the availability of the C source code and the way the project is built, but in many cases it may suffice. However, the ability to share objects between Java and native methods expands the potential risk to much more insidious cases where improper data handling in Java may lead to unexpected vulnerabilities in native code or unsafe operations in native code corrupt data structures in Java. Vulnerabilities in native code accessed through a Java application are typically exploited in the same manner as they are in applications written in the native language. The only challenge to such an attack is for the attacker to identify that the Java application uses native code to perform certain operations. This can be accomplished in a variety of ways, including identifying specific behaviors that are often implemented with native code or by exploiting a system information exposure in the Java application that reveals its use of JNI [See Reference].

Exemplo de código vulnerável

Vulnerable Java

The following code defines a class named Echo. The class declares one native method (defined below), which uses C to echo commands entered on the console back to the user. The following C code defines the native method implemented in the Echo class:

Vulnerável Java
class Echo {
  		public native void runEcho();
  		static {
  				System.loadLibrary("echo");
  		}
  		public static void main(String[] args) {
  				new Echo().runEcho();
  		}
  }
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-111

  • Implementation Implement error handling around the JNI call.
  • Implementation Do not use JNI calls if you don't trust the native library.
  • Implementation Be reluctant to use JNI calls. A Java API equivalent may exist.
Sinais de deteção

How to detect CWE-111

Automated Static Analysis High

Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect "sources" (origins of input) with "sinks" (destinations where the data interacts with external components, a lower layer such as the OS, etc.)

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-111 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-111?

This weakness occurs when a Java application directly calls native code through the Java Native Interface (JNI), exposing the entire application to security risks present in that external code, even if Java itself is safe from those specific flaws.

Qual a gravidade do CWE-111?

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-111?

MITRE lists the following affected platforms: Java.

Como posso prevenir o CWE-111?

Implement error handling around the JNI call. Do not use JNI calls if you don't trust the native library.

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

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-111 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-111?

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/111.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.