CWE-754 Classe Incompleto Medium likelihood

Improper Check for Unusual or Exceptional Conditions

This weakness occurs when software fails to properly anticipate and handle rare or unexpected runtime situations that fall outside normal operation.

Definição

What is CWE-754?

This weakness occurs when software fails to properly anticipate and handle rare or unexpected runtime situations that fall outside normal operation.
Developers often write code assuming certain problematic events—like memory exhaustion, permission denials, or malformed data from external sources—simply won't happen. However, attackers actively seek to trigger these exact conditions to break those assumptions, leading to crashes, incorrect outputs, or security breaches. While this includes improper exception handling, the core issue is broader: it's about any missing or inadequate validation for edge cases. Proactively identifying and managing these unusual states is crucial for building resilient software that can withstand hostile environments, not just ideal ones.
Impacto no mundo real

Real-world CVEs caused by CWE-754

  • Chain: function in web caching proxy does not correctly check a return value (CWE-253) leading to a reachable assertion (CWE-617)

  • Unchecked return value leads to resultant integer overflow and code execution.

  • Program does not check return value when invoking functions to drop privileges, which could leave users with higher privileges than expected by forcing those functions to fail.

  • Program does not check return value when invoking functions to drop privileges, which could leave users with higher privileges than expected by forcing those functions to fail.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    Consider the following code segment:

  2. 2

    The programmer expects that when fgets() returns, buf will contain a null-terminated string of length 9 or less. But if an I/O error occurs, fgets() will not null-terminate buf. Furthermore, if the end of the file is reached before any characters are read, fgets() returns without writing anything to buf. In both of these situations, fgets() signals that something unusual has happened by returning NULL, but in this code, the warning will not be noticed. The lack of a null terminator in buf can result in a buffer overflow in the subsequent call to strcpy().

  3. 3

    The following code does not check to see if memory allocation succeeded before attempting to use the pointer returned by malloc().

  4. 4

    The traditional defense of this coding error is: "If my program runs out of memory, it will fail. It doesn't matter whether I handle the error or simply allow the program to die with a segmentation fault when it tries to dereference the null pointer." This argument ignores three important considerations:

  5. 5

    - Depending upon the type and size of the application, it may be possible to free memory that is being used elsewhere so that execution can continue. - It is impossible for the program to perform a graceful exit if required. If the program is performing an atomic operation, it can leave the system in an inconsistent state. - The programmer has lost the opportunity to record diagnostic information. Did the call to malloc() fail because req_size was too large or because there were too many requests being handled at the same time? Or was it caused by a memory leak that has built up over time? Without handling the error, there is no way to know.

Exemplo de código vulnerável

Vulnerable C

Consider the following code segment:

Vulnerável C
char buf[10], cp_buf[10];
  fgets(buf, 10, stdin);
  strcpy(cp_buf, buf);
Exemplo de código seguro

Secure C++

However, this code does not check the return values of the methods openFileToWrite, writeToFile, closeFile to verify that the file was properly opened and closed and that the string was successfully written to the file. The return values for these methods should be checked to determine if the method was successful and allow for detection of errors or unexpected conditions as in the following example.

Seguro C++
int outputStringToFile(char *output, char *filename) {
  		int isOutput = SUCCESS;
  		int isOpen = openFileToWrite(filename);
  		if (isOpen == FAIL) {
  			printf("Unable to open file %s", filename);
  			isOutput = FAIL;
  		}
  		else {
  				int isWrite = writeToFile(output);
  				if (isWrite == FAIL) {
  					printf("Unable to write to file %s", filename);
  					isOutput = FAIL;
  				}
  				int isClose = closeFile(filename);
  				if (isClose == FAIL)
  					isOutput = FAIL;
  		}
  		return isOutput;
  }
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-754

  • Requirements Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Choose languages with features such as exception handling that force the programmer to anticipate unusual conditions that may generate exceptions. Custom exceptions may need to be developed to handle unusual business-logic conditions. Be careful not to pass sensitive exceptions back to the user (CWE-209, CWE-248).
  • Implementation Check the results of all functions that return a value and verify that the value is expected.
  • Implementation If using exception handling, catch and throw specific exceptions instead of overly-general exceptions (CWE-396, CWE-397). Catch and handle exceptions as locally as possible so that exceptions do not propagate too far up the call stack (CWE-705). Avoid unchecked or uncaught exceptions where feasible (CWE-248).
  • Implementation Ensure that error messages only contain minimal details that are useful to the intended audience and no one else. The messages need to strike the balance between being too cryptic (which can confuse users) or being too detailed (which may reveal more than intended). The messages should not reveal the methods that were used to determine the error. Attackers can use detailed information to refine or optimize their original attack, thereby increasing their chances of success. If errors must be captured in some detail, record them in log messages, but consider what could occur if the log messages can be viewed by attackers. Highly sensitive information such as passwords should never be saved to log files. Avoid inconsistent messaging that might accidentally tip off an attacker about internal state, such as whether a user account exists or not. Exposing additional information to a potential attacker in the context of an exceptional condition can help the attacker determine what attack vectors are most likely to succeed beyond DoS.
  • Implementation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
  • Architecture and Design / Implementation If the program must fail, ensure that it fails gracefully (fails closed). There may be a temptation to simply let the program fail poorly in cases such as low memory conditions, but an attacker may be able to assert control before the software has fully exited. Alternately, an uncontrolled failure could cause cascading problems with other downstream components; for example, the program could send a signal to a downstream process so the process immediately knows that a problem has occurred and has a better chance of recovery.
  • Architecture and Design Use system limits, which should help to prevent resource exhaustion. However, the product should still handle low resource conditions since they may still occur.
Sinais de deteção

How to detect CWE-754

Automated Static Analysis Moderate

Automated static analysis may be useful for detecting unusual conditions involving system resources or common programming idioms, but not for violations of business rules.

Manual Dynamic Analysis

Identify error conditions that are not likely to occur during normal usage and trigger them. For example, run the program under low memory conditions, run with insufficient privileges or permissions, interrupt a transaction before it is completed, or disable connectivity to basic network services such as DNS. Monitor the software for any unexpected behavior. If you trigger an unhandled exception or similar error that was discovered and handled by the application's environment, it may still indicate unexpected conditions that were not handled by the application itself.

Correção automática do Plexicus

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

This weakness occurs when software fails to properly anticipate and handle rare or unexpected runtime situations that fall outside normal operation.

Qual a gravidade do CWE-754?

A MITRE classifica a probabilidade de exploração como Média — a exploração é realista mas normalmente requer condições específicas.

Que linguagens ou plataformas são afetadas pelo CWE-754?

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

Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid. Choose languages with features such as exception handling that force the programmer to anticipate unusual conditions that may generate exceptions. Custom exceptions may need to be developed to handle unusual business-logic conditions. Be careful not to pass sensitive exceptions back to the user (CWE-209, CWE-248). Check the results of all functions that return a value and…

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

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

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/754.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.

Fraquezas relacionadas

Weaknesses related to CWE-754

CWE-703 Pai

Improper Check or Handling of Exceptional Conditions

This vulnerability occurs when software fails to properly plan for or manage rare but possible error scenarios, leaving it unprepared for…

CWE-1384 Irmão

Improper Handling of Physical or Environmental Conditions

This weakness occurs when a hardware device fails to manage unexpected physical or environmental situations, whether they happen naturally…

CWE-228 Irmão

Improper Handling of Syntactically Invalid Structure

This vulnerability occurs when software fails to properly reject or process input that doesn't follow the expected format or structure,…

CWE-248 Irmão

Uncaught Exception

This vulnerability occurs when a function throws an error or exception, but the calling code does not have a proper handler to catch and…

CWE-391 Irmão

Unchecked Error Condition

This vulnerability occurs when a program fails to properly check or handle error conditions, such as exceptions or return codes. By…

CWE-392 Irmão

Missing Report of Error Condition

This vulnerability occurs when a system fails to properly signal that an error has happened. Instead of returning a clear error code,…

CWE-393 Irmão

Return of Wrong Status Code

This vulnerability occurs when a function returns an inaccurate status code or value that misrepresents the actual outcome of an…

CWE-397 Irmão

Declaration of Throws for Generic Exception

This vulnerability occurs when a method is declared to throw an overly broad exception type, such as a generic 'Exception' or 'Throwable'.…

CWE-755 Irmão

Improper Handling of Exceptional Conditions

This vulnerability occurs when software fails to properly manage unexpected situations or errors, leaving it in an unstable or insecure…

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.