CWE-426 Base Estável High likelihood

Untrusted Search Path

This vulnerability occurs when an application relies on an external search path, provided by a user or environment, to find and load critical resources like executables or libraries. Because the…

Definição

What is CWE-426?

This vulnerability occurs when an application relies on an external search path, provided by a user or environment, to find and load critical resources like executables or libraries. Because the application does not fully control this path, an attacker can manipulate it to point to malicious files.
An untrusted search path allows attackers to hijack the application's resource loading process. By manipulating environment variables like PATH or LD_PRELOAD on Linux, or the DLL search order on Windows, an attacker can trick the application into running their own malicious code, accessing sensitive data, or altering configuration. This happens because the application trusts the search path mechanism without properly validating the final location or integrity of the resources it loads. The core risk is the unauthorized elevation of control. Instead of exploiting a code flaw, the attacker subverts the trusted process of finding dependencies. To prevent this, developers must harden resource loading by using absolute paths, sanitizing environment variables, and explicitly defining safe search directories within the application's control, rather than relying on external system state.
Impacto no mundo real

Real-world CVEs caused by CWE-426

  • Application relies on its PATH environment variable to find and execute program.

  • Database application relies on its PATH environment variable to find and execute program.

  • Chain: untrusted search path enabling resultant format string by loading malicious internationalization messages.

  • Untrusted search path using malicious .EXE in Windows environment.

  • setuid program allows compromise using path that finds and loads a malicious library.

  • Server allows client to specify the search path, which can be modified to point to a program that the client has uploaded.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    This program is intended to execute a command that lists the contents of a restricted directory, then performs other actions. Assume that it runs with setuid privileges in order to bypass the permissions check by the operating system.

  2. 2

    This code may look harmless at first, since both the directory and the command are set to fixed values that the attacker can't control. The attacker can only see the contents for DIR, which is the intended program behavior. Finally, the programmer is also careful to limit the code that executes with raised privileges.

  3. 3

    However, because the program does not modify the PATH environment variable, the following attack would work:

  4. 4

    The following code from a system utility uses the system property APPHOME to determine the directory in which it is installed and then executes an initialization script based on a relative path from the specified directory.

  5. 5

    The code above allows an attacker to execute arbitrary commands with the elevated privilege of the application by modifying the system property APPHOME to point to a different path containing a malicious version of INITCMD. Because the program does not validate the value read from the environment, if an attacker can control the value of the system property APPHOME, then they can fool the application into running malicious code and take control of the system.

Exemplo de código vulnerável

Vulnerable C

This program is intended to execute a command that lists the contents of a restricted directory, then performs other actions. Assume that it runs with setuid privileges in order to bypass the permissions check by the operating system.

Vulnerável C
#define DIR "/restricted/directory"
  char cmd[500];
  sprintf(cmd, "ls -l %480s", DIR);
```
/* Raise privileges to those needed for accessing DIR. */* 
  
  RaisePrivileges(...);
  system(cmd);
  DropPrivileges(...);
  ...
Payload do atacante

However, because the program does not modify the PATH environment variable, the following attack would work:

Payload do atacante
- The user sets the PATH to reference a directory under the attacker's control, such as "/my/dir/".

  - The attacker creates a malicious program called "ls", and puts that program in /my/dir

  - The user executes the program.

  - When system() is executed, the shell consults the PATH to find the ls program

  - The program finds the attacker's malicious program, "/my/dir/ls". It doesn't find "/bin/ls" because PATH does not contain "/bin/".

  - The program executes the attacker's malicious program with the raised privileges.
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-426

  • Architecture and Design / Implementation Hard-code the search path to a set of known-safe values (such as system directories), or only allow them to be specified by the administrator in a configuration file. Do not allow these settings to be modified by an external party. Be careful to avoid related weaknesses such as CWE-426 and CWE-428.
  • Implementation When invoking other programs, specify those programs using fully-qualified pathnames. While this is an effective approach, code that uses fully-qualified pathnames might not be portable to other systems that do not use the same pathnames. The portability can be improved by locating the full-qualified paths in a centralized, easily-modifiable location within the source code, and having the code refer to these paths.
  • Implementation Remove or restrict all environment settings before invoking other programs. This includes the PATH environment variable, LD_LIBRARY_PATH, and other settings that identify the location of code libraries, and any application-specific search paths.
  • Implementation Check your search path before use and remove any elements that are likely to be unsafe, such as the current working directory or a temporary files directory.
  • Implementation Use other functions that require explicit paths. Making use of any of the other readily available functions that require explicit paths is a safe way to avoid this problem. For example, system() in C does not require a full path since the shell can take care of it, while execl() and execv() require a full path.
Sinais de deteção

How to detect CWE-426

Black Box

Use monitoring tools that examine the software's process as it interacts with the operating system and the network. This technique is useful in cases when source code is unavailable, if the software was not developed by you, or if you want to verify that the build phase did not introduce any new weaknesses. Examples include debuggers that directly attach to the running process; system-call tracing utilities such as truss (Solaris) and strace (Linux); system activity monitors such as FileMon, RegMon, Process Monitor, and other Sysinternals utilities (Windows); and sniffers and protocol analyzers that monitor network traffic. Attach the monitor to the process and look for library functions and system calls that suggest when a search path is being used. One pattern is when the program performs multiple accesses of the same file but in different directories, with repeated failures until the proper filename is found. Library calls such as getenv() or their equivalent can be checked to see if any path-related variables are being accessed.

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.)

Manual Analysis

Use tools and techniques that require manual (human) analysis, such as penetration testing, threat modeling, and interactive tools that allow the tester to record and modify an active session. These may be more effective than strictly automated techniques. This is especially the case with weaknesses that are related to design and business rules.

Correção automática do Plexicus

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

This vulnerability occurs when an application relies on an external search path, provided by a user or environment, to find and load critical resources like executables or libraries. Because the application does not fully control this path, an attacker can manipulate it to point to malicious files.

Qual a gravidade do CWE-426?

A MITRE classifica a probabilidade de exploração como Alta — esta fraqueza é ativamente explorada em campo e deve ser priorizada para remediação.

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

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

Como posso prevenir o CWE-426?

Hard-code the search path to a set of known-safe values (such as system directories), or only allow them to be specified by the administrator in a configuration file. Do not allow these settings to be modified by an external party. Be careful to avoid related weaknesses such as CWE-426 and CWE-428. When invoking other programs, specify those programs using fully-qualified pathnames. While this is an effective approach, code that uses fully-qualified pathnames might not be portable to other…

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

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

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