CWE-1389 Base Incompleto

Incorrect Parsing of Numbers with Different Radices

This vulnerability occurs when software processes numeric input expecting standard decimal numbers (base 10), but fails to handle inputs formatted in other bases like octal or hexadecimal. This…

Definição

What is CWE-1389?

This vulnerability occurs when software processes numeric input expecting standard decimal numbers (base 10), but fails to handle inputs formatted in other bases like octal or hexadecimal. This mismatch leads to the system interpreting the same digits as a completely different numeric value.
The core issue often arises from functions that automatically interpret numeric prefixes. A leading '0' can trigger octal parsing, while '0x' indicates hexadecimal. For instance, the IP address '0127.0.0.1' is read as octal, becoming equivalent to 87.0.0.1 in decimal—a stark and dangerous difference from the intended 127.0.0.1 (localhost). Common C functions like `inet_addr()` exhibit this behavior, but the problem can appear in any parsing logic that doesn't explicitly define or validate the input's radix. In practice, this parsing flaw can have severe security consequences. An attacker can exploit it to bypass security controls, such as network allow/deny lists or SSRF (Server-Side Request Forgery) filters, by supplying an IP address or identifier that looks correct to a developer but resolves to a different, permitted address. It can also corrupt data flows when identifiers that resemble numbers with leading zeros are processed incorrectly, leading to logical errors and unexpected system behavior.
Impacto no mundo real

Real-world CVEs caused by CWE-1389

  • Chain: Use of zero-prepended IP addresses in Perl-based IP validation module can lead to an access control bypass.

  • Chain: Use of zero-prepended IP addresses in a product that manages IP blocks can lead to an SSRF.

  • Chain: Use of zero-prepended IP addresses in a Python standard library package can lead to an SSRF.

  • Chain: Use of zero-prepended IP addresses in the net Golang library can lead to an access control bypass.

  • Chain: Use of zero-prepended IP addresses in Perl netmask module allows bypass of IP-based access control.

  • Chain: incorrect validation of intended decimal-based IP address format (CWE-1286) enables parsing of octal or hexadecimal formats (CWE-1389), allowing bypass of an SSRF protection mechanism (CWE-918).

  • Mishandling of hex-valued usernames leads to unexpected decimal conversion and privilege escalation in the systemd Linux suite.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    The below demonstrative example uses an IP validator that splits up an IP address by octet, tests to ensure each octet can be casted into an integer, and then returns the original IP address if no exceptions are raised. This validated IP address is then tested using the "ping" command.

  2. 2

    If run_ping() were to be called with one or more zero-prepended octets, validate_ip() will succeed as zero-prepended numerical strings can be interpreted as decimal by a cast ("012" would cast to 12). However, as the original IP with the prepended zeroes is returned rather than the casted IP, it will be used in the call to the ping command. Ping DOES check and support octal-based IP octets, so the IP reached via ping may be different than the IP assumed by the validator. For example, ping would considered "0127.0.0.1" the same as "87.0.0.1".

  3. 3

    This code uses a regular expression to validate an IP string prior to using it in a call to the "ping" command.

  4. 4

    Since the regular expression does not have anchors (CWE-777), i.e. is unbounded without ^ or $ characters, then prepending a 0 or 0x to the beginning of the IP address will still result in a matched regex pattern. Since the ping command supports octal and hex prepended IP addresses, it will use the unexpectedly valid IP address (CWE-1389). For example, "0x63.63.63.63" would be considered equivalent to "99.63.63.63". As a result, the attacker could potentially ping systems that the attacker cannot reach directly.

  5. 5

    Consider the following scenario, inspired by CWE team member Kelly Todd. Kelly wants to set up monitoring systems for his two cats, who pose very different threats. One cat, Night, tweets embarrassing or critical comments about his owner in ways that could cause reputational damage, so Night's blog needs to be monitored regularly. The other cat, Taki, likes to distract Kelly and his coworkers during business meetings with cute meows, so Kelly monitors Taki's location using a different web site. Suppose /etc/hosts provides the site info as follows:

Exemplo de código vulnerável

Vulnerable Python

The below demonstrative example uses an IP validator that splits up an IP address by octet, tests to ensure each octet can be casted into an integer, and then returns the original IP address if no exceptions are raised. This validated IP address is then tested using the "ping" command.

Vulnerável Python
import subprocess
   def validate_ip(ip: str):
  	 split_ip = ip.split('.')
  	 if len(split_ip) > 4 or len(split_ip) == 0:
  		 raise ValueError("Invalid IP length")
  	 for octet in split_ip:
  		 try:
  			 int(octet, 10)
  		 except ValueError as e:
  			 raise ValueError(f"Cannot convert IP octet to int - {e}")
```
# Returns original IP after ensuring no exceptions are raised* 
  	 return ip
  	
   def run_ping(ip: str):
  
  ```
  	 validated = validate_ip(ip)
```
# The ping command treats zero-prepended IP addresses as octal* 
  	 result = subprocess.call(["ping", validated])
  	 print(result)
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-1389

  • Implementation If only decimal-based values are expected in the application, conditional checks should be created in a way that prevent octal or hexadecimal strings from being checked. This can be achieved by converting any numerical string to an explicit base-10 integer prior to the conditional check, to prevent octal or hex values from ever being checked against the condition.
  • Implementation If various numerical bases do need to be supported, check for leading values indicating the non-decimal base you wish to support (such as 0x for hex) and convert the numeric strings to integers of the respective base. Reject any other alternative-base string that is not intentionally supported by the application.
  • Implementation If regular expressions are used to validate IP addresses, ensure that they are bounded using ^ and $ to prevent base-prepended IP addresses from being matched.
Sinais de deteção

How to detect CWE-1389

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

This vulnerability occurs when software processes numeric input expecting standard decimal numbers (base 10), but fails to handle inputs formatted in other bases like octal or hexadecimal. This mismatch leads to the system interpreting the same digits as a completely different numeric value.

Qual a gravidade do CWE-1389?

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

MITRE lists the following affected platforms: Not Technology-Specific.

Como posso prevenir o CWE-1389?

If only decimal-based values are expected in the application, conditional checks should be created in a way that prevent octal or hexadecimal strings from being checked. This can be achieved by converting any numerical string to an explicit base-10 integer prior to the conditional check, to prevent octal or hex values from ever being checked against the condition. If various numerical bases do need to be supported, check for leading values indicating the non-decimal base you wish to support…

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

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

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