Executar análise estática (SAST) na base de código à procura do padrão inseguro no fluxo de dados.
Signal Handler with Functionality that is not Asynchronous-Safe
This weakness occurs when a program's signal handler contains code that is not asynchronous-safe. This means the handler can be interrupted or can corrupt shared data, leading to unpredictable…
What is CWE-828?
Real-world CVEs caused by CWE-828
-
Signal handler uses functions that ultimately call the unsafe syslog/malloc/s*printf, leading to denial of service via multiple login attempts
-
Chain: Signal handler contains too much functionality (CWE-828), introducing a race condition (CWE-362) that leads to a double free (CWE-415).
-
unsafe calls to library functions from signal handler
-
SIGURG can be used to remotely interrupt signal handler; other variants exist.
-
SIGCHLD signal to FTP server can cause crash under heavy load while executing non-reentrant functions like malloc/free.
-
SIGCHLD not blocked in a daemon loop while counter is modified, causing counter to get out of sync.
Trajeto do atacante passo a passo
- 1
This code registers the same signal handler function with two different signals (CWE-831). If those signals are sent to the process, the handler creates a log message (specified in the first argument to the program) and exits.
- 2
The handler function uses global state (globalVar and logMessage), and it can be called by both the SIGHUP and SIGTERM signals. An attack scenario might follow these lines:
- 3
- The program begins execution, initializes logMessage, and registers the signal handlers for SIGHUP and SIGTERM. - The program begins its "normal" functionality, which is simplified as sleep(), but could be any functionality that consumes some time. - The attacker sends SIGHUP, which invokes handler (call this "SIGHUP-handler"). - SIGHUP-handler begins to execute, calling syslog(). - syslog() calls malloc(), which is non-reentrant. malloc() begins to modify metadata to manage the heap. - The attacker then sends SIGTERM. - SIGHUP-handler is interrupted, but syslog's malloc call is still executing and has not finished modifying its metadata. - The SIGTERM handler is invoked. - SIGTERM-handler records the log message using syslog(), then frees the logMessage variable.
- 4
At this point, the state of the heap is uncertain, because malloc is still modifying the metadata for the heap; the metadata might be in an inconsistent state. The SIGTERM-handler call to free() is assuming that the metadata is inconsistent, possibly causing it to write data to the wrong location while managing the heap. The result is memory corruption, which could lead to a crash or even code execution, depending on the circumstances under which the code is running.
- 5
Note that this is an adaptation of a classic example as originally presented by Michal Zalewski [REF-360]; the original example was shown to be exploitable for code execution.
Vulnerable C
This code registers the same signal handler function with two different signals (CWE-831). If those signals are sent to the process, the handler creates a log message (specified in the first argument to the program) and exits.
char *logMessage;
void handler (int sigNum) {
syslog(LOG_NOTICE, "%s\n", logMessage);
free(logMessage);
```
/* artificially increase the size of the timing window to make demonstration of this weakness easier. */*
sleep(10);
exit(0);}
int main (int argc, char* argv[]) {
```
logMessage = strdup(argv[1]);
```
/* Register signal handlers. */*
signal(SIGHUP, handler);
signal(SIGTERM, handler);
*/* artificially increase the size of the timing window to make demonstration of this weakness easier. */*
sleep(10);} Secure pseudo
// Validate, sanitize, or use a safe API before reaching the sink.
function handleRequest(input) {
const safe = validateAndEscape(input);
return executeWithGuards(safe);
} How to prevent CWE-828
- Implementation / Architecture and Design Eliminate the usage of non-reentrant functionality inside of signal handlers. This includes replacing all non-reentrant library calls with reentrant calls. Note: This will not always be possible and may require large portions of the product to be rewritten or even redesigned. Sometimes reentrant-safe library alternatives will not be available. Sometimes non-reentrant interaction between the state of the system and the signal handler will be required by design.
- Implementation Where non-reentrant functionality must be leveraged within a signal handler, be sure to block or mask signals appropriately. This includes blocking other signals within the signal handler itself that may also leverage the functionality. It also includes blocking all signals reliant upon the functionality when it is being accessed or modified by the normal behaviors of the product.
How to detect CWE-828
Executar testes dinâmicos de segurança de aplicações (DAST) contra o endpoint em execução.
Monitorizar os registos em tempo de execução para traços de exceção invulgares, input malformado ou tentativas de contornar a autorização.
Revisão de código: sinalizar qualquer novo código que trate input desta superfície sem usar os ajudantes validados do framework.
O Plexicus deteta automaticamente o CWE-828 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.
Frequently asked questions
O que é o CWE-828?
This weakness occurs when a program's signal handler contains code that is not asynchronous-safe. This means the handler can be interrupted or can corrupt shared data, leading to unpredictable program behavior.
Qual a gravidade do CWE-828?
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-828?
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-828?
Eliminate the usage of non-reentrant functionality inside of signal handlers. This includes replacing all non-reentrant library calls with reentrant calls. Note: This will not always be possible and may require large portions of the product to be rewritten or even redesigned. Sometimes reentrant-safe library alternatives will not be available. Sometimes non-reentrant interaction between the state of the system and the signal handler will be required by design. Where non-reentrant functionality…
Como é que o Plexicus deteta e corrige o CWE-828?
O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-828 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-828?
A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/828.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.
Weaknesses related to CWE-828
Signal Handler Race Condition
A signal handler race condition occurs when a program's signal handling routine is vulnerable to timing issues, allowing its state to be…
Dangerous Signal Handler not Disabled During Sensitive Operations
This vulnerability occurs when a program's signal handler, which shares resources like global variables with other handlers, can be…
Signal Handler Function Associated with Multiple Signals
This vulnerability occurs when a single function is registered to handle multiple different operating system signals, creating potential…
Signal Handler Use of a Non-reentrant Function
This vulnerability occurs when a signal handler in your code calls a function that is not safe to re-enter. If that function is…
Further reading
- MITRE — CWE-828 oficial https://cwe.mitre.org/data/definitions/828.html
- Delivering Signals for Fun and Profit https://lcamtuf.coredump.cx/signals.txt
- Race Condition: Signal Handling https://vulncat.fortify.com/en/detail?id=desc.structural.cpp.race_condition_signal_handling#:~:text=Signal%20handling%20race%20conditions%20can,installed%20to%20handle%20multiple%20signals.s
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.