Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
/* memset_s.c */
voiderrno_t *memset_s(void *vs, rsize_t smax, int c, sizersize_t n) {
  volatile unsigned char *p = v;
  while (smax-- && n--) {
    *p++ = c;
  }

  return v;
}

/* getPassword.c */
extern void *memset_s(void *v, int c, size_t n);

void getPassword(void) {
  char pwd[64];

  if (retrievePassword(pwd, sizeof(pwd))) {
     /*checking of password, secure operations, etc */
  }
  memset_s(pwd, sizeof(pwd), 0, sizeof(pwd));
}

This is the preferred solution for C99 because C1X introduces a

However, it should be noted that both calling functions and accessing volatile qualified objects can still be optimized out (while maintaining strict conformance to the standard), so this compliant solution may still not work in some cases.

Compliant Solution (C1X)

Wiki Markup
C1X includes a {{memset_s}} function.  According to the November 24, 2009 C1X Committee Draft \[Jones 09|AA. C References#Jones 09]\]:

Unlike memset, any call to the memset_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 the memset_s function shall assume that the memory indicated by s and n may be accessible in the future and thus must contain the values indicated by c.

Code Block
bgColor#ccccff

void getPassword(void) {
  char pwd[64];

  if (retrievePassword(pwd, sizeof(pwd))) {
     /* checking of password, secure operations, etc */
  }
  memset_s(pwd, 0, sizeof(pwd));
}

Risk Assessment

If the compiler optimizes out memory-clearing code, an attacker can gain access to sensitive data.

...

Wiki Markup
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.7.3, "Type qualifiers"
\[Jones 09|AA. C References#Jones 09]\] Section K.3.7.4.1, "The {{memset_s}} function"
\[[US-CERT|https://buildsecurityin.us-cert.gov/daisy/bsi-rules/home/g1/771.html]\] "MEMSET"
\[[MITRE 07|AA. C References#MITRE 07]\] [CWE ID 14|http://cwe.mitre.org/data/definitions/14.html], "Compiler Removal of Code to Clear Buffers"
\[[MSDN|AA. C References#MSDN]\] "[SecureZeroMemory|http://msdn.microsoft.com/en-us/library/aa366877.aspx]"
\[[MSDN|AA. C References#MSDN]\] "[Optimize (C/C++)|http://msdn.microsoft.com/en-us/library/chh3fb0k(VS.80).aspx]"
\[[Wheeler 03|AA. C References#Wheeler 03]\] [Section 11.4|http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/protect-secrets.html], "Specially Protect Secrets (Passwords and Keys) in User Memory"

...