CWE-187 Variante Incompleto

Partial String Comparison

This weakness occurs when software checks only part of a string or token to determine a match, instead of comparing the entire value. This incomplete validation can lead to incorrect security…

Definição

What is CWE-187?

This weakness occurs when software checks only part of a string or token to determine a match, instead of comparing the entire value. This incomplete validation can lead to incorrect security decisions.
Partial string comparison happens when a system, such as an authentication module, validates only the first few characters of an input against a stored value. For example, if a password check only verifies the initial 5 characters, an attacker could gain access by providing any password that starts with those same 5 characters, regardless of the full correct password. This flaw fundamentally undermines security logic by treating partially matching inputs as fully authorized. Developers should always enforce complete, exact-string comparisons for security-critical operations like authentication, authorization tokens, or integrity checks to prevent attackers from exploiting these predictable shortcuts.
Impacto no mundo real

Real-world CVEs caused by CWE-187

  • Product does not prevent access to restricted directories due to partial string comparison with a public directory

  • Argument parser of an IMAP server treats a partial command "body[p" as if it is "body.peek", leading to index error and out-of-bounds corruption.

  • Web browser only checks the hostname portion of a certificate when the hostname portion of the URI is not a fully qualified domain name (FQDN), which allows remote attackers to spoof trusted certificates.

  • One-character password by attacker checks only against first character of real password.

  • One-character password by attacker checks only against first character of real password.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    This example defines a fixed username and password. The AuthenticateUser() function is intended to accept a username and a password from an untrusted user, and check to ensure that it matches the username and password. If the username and password match, AuthenticateUser() is intended to indicate that authentication succeeded.

  2. 2

    In AuthenticateUser(), the strncmp() call uses the string length of an attacker-provided inPass parameter in order to determine how many characters to check in the password. So, if the attacker only provides a password of length 1, the check will only examine the first byte of the application's password before determining success.

  3. 3

    As a result, this partial comparison leads to improper authentication (CWE-287).

  4. 4

    Any of these passwords would still cause authentication to succeed for the "admin" user:

  5. 5

    This significantly reduces the search space for an attacker, making brute force attacks more feasible.

Exemplo de código vulnerável

Vulnerable C

This example defines a fixed username and password. The AuthenticateUser() function is intended to accept a username and a password from an untrusted user, and check to ensure that it matches the username and password. If the username and password match, AuthenticateUser() is intended to indicate that authentication succeeded.

Vulnerável C
```
/* Ignore CWE-259 (hard-coded password) and CWE-309 (use of password system for authentication) for this example. */* 
  
  char *username = "admin";
  char *pass = "password";
  
  int AuthenticateUser(char *inUser, char *inPass) {
  ```
  	if (strncmp(username, inUser, strlen(inUser))) {
  		logEvent("Auth failure of username using strlen of inUser");
  		return(AUTH_FAIL);
  	}
  	if (! strncmp(pass, inPass, strlen(inPass))) {
  		logEvent("Auth success of password using strlen of inUser");
  		return(AUTH_SUCCESS);
  	}
  	else {
  		logEvent("Auth fail of password using sizeof");
  		return(AUTH_FAIL);
  	}
  }
  int main (int argc, char **argv) {
  		int authResult;
  		if (argc < 3) {
  			ExitError("Usage: Provide a username and password");
  		}
  		authResult = AuthenticateUser(argv[1], argv[2]);
  		if (authResult == AUTH_SUCCESS) {
  			DoAuthenticatedTask(argv[1]);
  		}
  		else {
  			ExitError("Authentication failed");
  		}
  }
Payload do atacante

Any of these passwords would still cause authentication to succeed for the "admin" user:

Payload do atacante
p
  pa
  pas
  pass
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-187

  • Testing Thoroughly test the comparison scheme before deploying code into production. Perform positive testing as well as negative testing.
Sinais de deteção

How to detect CWE-187

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

This weakness occurs when software checks only part of a string or token to determine a match, instead of comparing the entire value. This incomplete validation can lead to incorrect security decisions.

Qual a gravidade do CWE-187?

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

A MITRE não especificou as plataformas afetadas por este CWE — pode aplicar-se à maioria das stacks de aplicações.

Como posso prevenir o CWE-187?

Thoroughly test the comparison scheme before deploying code into production. Perform positive testing as well as negative testing.

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

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

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