
Section Subclause 5.1.2.3 of the C Standard [ISO/IEC 9899:2011] states:
...
This noncompliant code example accesses the buffer again after the call to memset()
. This technique prevents some compilers from optimizing out the call to memset()
but does not work for all implementations. For example, the MIPSpro compiler and versions 3 and later of GCC cleverly nullify only the first byte and leave the rest intact. Check compiler documentation to guarantee this behavior for a specific platform.
...
A call to ZeroMemory()
may be optimized out in a similar manner as to a call to memset()
.
Compliant Code Example (Windows)
...
However, note that both calling functions and accessing volatile
-qualified objects can still be optimized out (while maintaining strict conformance to the standard), so without a C-conforming implementation, this compliant solution still might not work in some cases.
...
The C Standard includes a memset_s
function. Section Subclause K.3.7.4.1, paragraph 4 [ISO/IEC 9899:2011], states:
Unlike
memset
, any call to thememset_s
function shall be evaluated strictly according to the rules of the abstract machine as described in (5.1.2.3). That is, any call to thememset_s
function shall assume that the memory indicated bys
andn
may be accessible in the future and thus must contain the values indicated byc
.
...
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC06-C | mediumMedium | probableProbable | mediumMedium | P8 | L2 |
Related Vulnerabilities
...
CERT C++ Secure Coding Standard | MSC06-CPP. Be aware of compiler optimization when dealing with sensitive data |
MITRE CWE | CWE-14, Compiler removal of code to clear buffers |
Bibliography
[ISO/IEC 9899:2011] | Section Subclause K.3.7.4.1, "The memset_s Function" |
[MSDN] | "SecureZeroMemory" "Optimize (C/C++)" |
[US-CERT] | "MEMSET" |
[Wheeler 2003] | Section 11.4, "Specially Protect Secrets (Passwords and Keys) in User Memory" |
...