The location in memory of a function is computed at compile time and then stored for later use by the program. If an attacker can overwrite certain function pointers, they may be able to execute arbitrary code. To mitigate the effects of such attacks, pointers to functions can be encrypted at runtime based on some characteristics of the execution process so that only a running process will be able to decode them.
Noncompliant Code Example
This noncompliant code example assigns the address of the printf()
function to the log_fn
function pointer, which can be allocated in the stack or data segment.
int (*log_fn)(const char *, ...) = printf; /* ... */ log_fn("foo");
If a vulnerability exists in this program that allows an attacker to overwrite the log_fn
function pointer, such as a buffer overflow or arbitrary memory write, the attacker may be able to overwrite the value of printf
with the location of an arbitrary function.
Compliant Solution (Windows)
Microsoft Windows provides the EncodePointer()
and DecodePointer()
function that encrypt and decrypt pointers using a secret that is unique to the given process.
int (*log_fn)(const char *, ...) = EncodePointer(printf); /* ... */ DecodePointer(log_fn)("foo");
Compliant Solution (C1X)
Two similar functions are under consideration for the C1X major revision to the C Standard.
C1X defines encode_pointer()
to have the following behavior:
The encode_pointer function shall perform a transformation on the
pf
argument, such that thedecode_pointer
function shall reverse that transformation. Thus, for any pointer to functionpfun
,decode_pointer(encode_pointer( (void(*)()) pfun )when converted to the type of
pfun
, shall equalpfun
.
int (*log_fn)(const char *, ...) = encode_pointer(printf); /* ... */ decode_pointer(log_fn)("foo");
Risk Assessment
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
MSC16-C |
high |
unlikely |
low |
P9 |
L2 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard: MSC16-CPP. Consider encrypting function pointers
MITRE CWE: CWE-311, "Missing Encryption of Sensitive Data"
Bibliography
[MSDN] EncodePointer()
, DecodePointer()