CWE-194 Variante Incomplet High likelihood

Unexpected Sign Extension

This vulnerability occurs when a signed number from a smaller data type is moved or cast to a larger type, causing its sign bit to be incorrectly extended. If the original value is negative, this…

Définition

What is CWE-194?

This vulnerability occurs when a signed number from a smaller data type is moved or cast to a larger type, causing its sign bit to be incorrectly extended. If the original value is negative, this sign extension can fill the new, higher-order bits with '1's, leading to unexpectedly large positive values and causing logic errors, buffer overflows, or security bypasses.
Sign extension is a standard behavior in programming languages like C and C++ when promoting a signed integer (e.g., a signed 8-bit `char`) to a larger signed type (e.g., a 32-bit `int`). The problem arises when developers don't account for this automatic behavior, especially when treating the resulting value as an unsigned number or using it for operations like memory allocation, array indexing, or length validation. A classic example is reading a byte value of `0xFF` (-1 as a signed char) into an unsigned integer, which becomes `0xFFFFFFFF` (a very large positive number), potentially leading to out-of-bounds access. To prevent this, developers must be explicit about data types during conversions. Always consider if the source data should be treated as signed or unsigned before widening it. Use explicit casts to the intended target type, and when working with raw byte data or protocol parsing, prefer unsigned types for counts and indices. Performing range checks on the source value before the conversion or using bit masks (e.g., `new_value = old_value & 0xFF`) can effectively strip unwanted sign-extended bits and ensure the resulting value matches the intended logic.
Impact réel

Real-world CVEs caused by CWE-194

  • Chain: unexpected sign extension (CWE-194) leads to integer overflow (CWE-190), causing an out-of-bounds read (CWE-125)

  • Sign extension error produces -1 value that is treated as a command separator, enabling OS command injection.

  • Product uses "char" type for input character. When char is implemented as a signed type, ASCII value 0xFF (255), a sign extension produces a -1 value that is treated as a program-specific separator value, effectively disabling a length check and leading to a buffer overflow. This is also a multiple interpretation error.

  • chain: signed short width value in image processor is sign extended during conversion to unsigned int, which leads to integer overflow and heap-based buffer overflow.

  • chain: signedness error allows bypass of a length check; later sign extension makes exploitation easier.

  • Sign extension when manipulating Pascal-style strings leads to integer overflow and improper memory copy.

Comment les attaquants l'exploitent

Parcours de l'attaquant étape par étape

  1. 1

    Identifier un chemin de code qui traite des entrées non fiables sans validation.

  2. 2

    Élaborer une charge utile qui exploite le comportement non sécurisé — injection, traversal, débordement ou abus de logique.

  3. 3

    Délivrer la charge utile via une requête normale et observer la réaction de l'application.

  4. 4

    Itérer jusqu'à ce que la réponse divulgue des données, exécute le code de l'attaquant ou élève les privilèges.

Exemple de code vulnérable

Vulnerable C

The following code reads a maximum size and performs a sanity check on that size. It then performs a strncpy, assuming it will not exceed the boundaries of the array. While the use of "short s" is forced in this particular example, short int's are frequently used within real-world code, such as code that processes structured data.

Vulnérable C
int GetUntrustedInt () {
  	return(0x0000FFFF);
  }
  void main (int argc, char **argv) {
  		char path[256];
  		char *input;
  		int i;
  		short s;
  		unsigned int sz;
  		i = GetUntrustedInt();
  		s = i;
  		/* s is -1 so it passes the safety check - CWE-697 */
  		if (s > 256) {
  			DiePainfully("go away!\n");
  		}
  		/* s is sign-extended and saved in sz */
  		sz = s;
  		/* output: i=65535, s=-1, sz=4294967295 - your mileage may vary */
  		printf("i=%d, s=%d, sz=%u\n", i, s, sz);
  		input = GetUserInput("Enter pathname:");
  		/* strncpy interprets s as unsigned int, so it's treated as MAX_INT
  		(CWE-195), enabling buffer overflow (CWE-119) */
  		strncpy(path, input, s);
  		path[255] = '\0'; /* don't want CWE-170 */
  		printf("Path is: %s\n", path);
  }
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-194

  • Implementation Avoid using signed variables if you don't need to represent negative values. When negative values are needed, perform validation after you save those values to larger data types, or before passing them to functions that are expecting unsigned values.
Signaux de détection

How to detect CWE-194

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

This vulnerability occurs when a signed number from a smaller data type is moved or cast to a larger type, causing its sign bit to be incorrectly extended. If the original value is negative, this sign extension can fill the new, higher-order bits with '1's, leading to unexpectedly large positive values and causing logic errors, buffer overflows, or security bypasses.

Quelle est la gravité de CWE-194 ?

MITRE évalue la probabilité d'exploitation comme Élevée — cette faiblesse est activement exploitée et doit être priorisée pour la remédiation.

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

MITRE lists the following affected platforms: C, C++.

Comment puis-je prévenir CWE-194 ?

Avoid using signed variables if you don't need to represent negative values. When negative values are needed, perform validation after you save those values to larger data types, or before passing them to functions that are expecting unsigned values.

Comment Plexicus détecte et corrige CWE-194 ?

Le moteur SAST de Plexicus reconnaît la signature de flux de données de CWE-194 à 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-194 ?

MITRE publie la définition canonique à https://cwe.mitre.org/data/definitions/194.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.