CWE-1389 Base Incomplet

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…

Définition

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.
Impact réel

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.

Comment les attaquants l'exploitent

Parcours de l'attaquant étape par étape

  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:

Exemple de code vulnérable

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.

Vulnérable 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)
Exemple de code sécurisé

Secure pseudo

Sécurisé 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.
Liste de contrôle de prévention

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.
Signaux de détection

How to detect CWE-1389

SAST High

Exécuter une analyse statique (SAST) sur le code source à la recherche du motif non sécurisé dans le flux de données.

DAST Moderate

Exécuter des tests de sécurité applicative dynamique (DAST) contre le point de terminaison en ligne.

Runtime Moderate

Surveiller les journaux runtime pour détecter des traces d'exception inhabituelles, des entrées malformées ou des tentatives de contournement d'autorisation.

Code review Moderate

Revue de code : signaler tout nouveau code qui traite les entrées de cette surface sans utiliser les helpers du framework validés.

Correction automatique Plexicus

Plexicus détecte automatiquement CWE-1389 et ouvre une PR de correction en moins de 60 secondes.

Codex Remedium analyse chaque commit, identifie cette faiblesse précise et livre une pull request prête à être relue avec le correctif. Pas de tickets. Pas de transferts.

Questions fréquentes

Frequently asked questions

Qu'est-ce que 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.

Quelle est la gravité de CWE-1389 ?

MITRE n'a pas publié de note de probabilité d'exploitation pour cette faiblesse. Traitez-la comme un impact moyen jusqu'à ce que votre modèle de menace prouve le contraire.

Quels langages ou plateformes sont affectés par CWE-1389 ?

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

Comment puis-je prévenir 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…

Comment Plexicus détecte et corrige CWE-1389 ?

Le moteur SAST de Plexicus reconnaît la signature de flux de données de CWE-1389 à chaque commit. Lorsqu'une correspondance est trouvée, notre agent Codex Remedium ouvre une PR de correction avec le code corrigé, les tests et un résumé d'une ligne pour le relecteur.

Où puis-je en savoir plus sur CWE-1389 ?

MITRE publie la définition canonique à https://cwe.mitre.org/data/definitions/1389.html. Vous pouvez également consulter la documentation OWASP et NIST pour des conseils adjacents.

Prêt quand vous l'êtes

Arrêtez de payer par développeur.
Commencez à fermer la boucle.

Plexicus est l'ASPM natif IA qui scanne, filtre, corrige, penteste et explique — de façon autonome. Développeurs illimités, dépôts illimités, actions IA à usage équitable. Vrai niveau gratuit, €269/mo annuel quand vous êtes prêt.