1739
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.
Effectiveness = High
Phase: 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.
Demonstrative Examples
Example 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.
Example Language: C (Bad)
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);
}
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:
• 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.
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
CWE Version 4.14
CWE-828: Signal Handler with Functionality that is not Asynchronous-Safe
CWE-828: Signal Handler with Functionality that is not Asynchronous-Safe