CWE-674 Classe Rascunho

Uncontrolled Recursion

This vulnerability occurs when an application fails to limit how deeply a function can call itself. Without proper controls, this uncontrolled recursion can exhaust system resources like memory or…

Definição

What is CWE-674?

This vulnerability occurs when an application fails to limit how deeply a function can call itself. Without proper controls, this uncontrolled recursion can exhaust system resources like memory or stack space, leading to crashes or denial-of-service.
Uncontrolled recursion happens when a recursive function lacks a proper termination condition or depth limit. This allows it to run indefinitely or until it consumes all available stack memory, causing a stack overflow. Common triggers include processing deeply nested user input (like XML/JSON), complex graph traversals, or mathematical sequences without safety checks. Developers should always implement a maximum recursion depth or convert recursive logic to iterative loops for critical operations. Detecting these flaws manually in a large codebase is challenging, as recursion paths can be complex. While SAST tools can identify the risky pattern, Plexicus uses AI to not only flag the issue but also generate specific, safe code fixes—such as adding depth counters or suggesting iterative alternatives—saving significant manual review and remediation time.
Impacto no mundo real

Real-world CVEs caused by CWE-674

  • Deeply nested arrays trigger stack exhaustion.

  • Self-referencing pointers create infinite loop and resultant stack exhaustion.

  • Javascript application accidentally changes input in a way that prevents a recursive call from detecting an exit condition.

  • An attempt to recover a corrupted XML file infinite recursion protection counter was not always incremented missing the exit condition.

  • USB-audio driver's descriptor code parsing allows unlimited recursion leading to stack exhaustion.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    Identificar um caminho de código que trata input não confiável sem validação.

  2. 2

    Criar um payload que explora o comportamento inseguro — injeção, traversal, overflow ou abuso de lógica.

  3. 3

    Entregar o payload através de um pedido normal e observar a reação da aplicação.

  4. 4

    Iterar até que a resposta exponha dados, execute código do atacante ou escale privilégios.

Exemplo de código vulnerável

Vulnerable C

In this example a mistake exists in the code where the exit condition contained in flg is never called. This results in the function calling itself over and over again until the stack is exhausted.

Vulnerável C
void do_something_recursive (int flg)
 {

```
   ... // Do some real work here, but the value of flg is unmodified
   if (flg) { do_something_recursive (flg); } // flg is never modified so it is always TRUE - this call will continue until the stack explodes
 }
 int flag = 1; // Set to TRUE
 do_something_recursive (flag);
Exemplo de código seguro

Secure C

Note that the only difference between the Good and Bad examples is that the recursion flag will change value and cause the recursive call to return.

Seguro C
void do_something_recursive (int flg)
 {

```
   ... // Do some real work here
   // Modify value of flg on done condition
   if (flg) { do_something_recursive (flg); } // returns when flg changes to 0
 }
 int flag = 1; // Set to TRUE
 do_something_recursive (flag);
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-674

  • Implementation Ensure an end condition will be reached under all logic conditions. The end condition may include testing against the depth of recursion and exiting with an error if the recursion goes too deep. The complexity of the end condition contributes to the effectiveness of this action.
  • Implementation Increase the stack size.
Sinais de deteção

How to detect CWE-674

Automated Static Analysis High

Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then searching for potentially-vulnerable patterns that connect "sources" (origins of input) with "sinks" (destinations where the data interacts with external components, a lower layer such as the OS, etc.)

Correção automática do Plexicus

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

This vulnerability occurs when an application fails to limit how deeply a function can call itself. Without proper controls, this uncontrolled recursion can exhaust system resources like memory or stack space, leading to crashes or denial-of-service.

Qual a gravidade do CWE-674?

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

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

Ensure an end condition will be reached under all logic conditions. The end condition may include testing against the depth of recursion and exiting with an error if the recursion goes too deep. The complexity of the end condition contributes to the effectiveness of this action. Increase the stack size.

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

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

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