Versions Compared

Key

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

...

In this noncompliant code example, sensitive information is supposedly stored in the dynamically allocated buffer, secret, which is processed and eventually deallocated by a call to free(). The memory page containing secret can be swapped out to disk. If the program crashes before the call to free(), the information stored in secret may be stored in the core dump.

Code Block
bgColor#FFcccc
langc
char *secret;

secret = (char *)malloc(size+1);
if (!secret) {
  /* Handle error */
}

/* Perform operations using secret... */

free(secret);
secret = NULL;

...

To prevent the information from being written to a core dump, the size of core dumps that the program will generate should be set to 0. This can be accomplished by using setrlimit().

Code Block
bgColor#ccccff
langc
#include <sys/resource.h>
/* ... */
struct rlimit limit;
limit.rlim_cur = 0;
limit.rlim_max = 0;
if (setrlimit(RLIMIT_CORE, &limit) != 0) {
    /* Handle error */
}

char *secret;

secret = (char *)malloc(size+1);
if (!secret) {
  /* Handle error */
}

/* Perform operations using secret... */

free(secret);
secret = NULL;

...

This compliant solution not only disables the creation of core files, but also ensures that the buffer is not swapped to hard disk.

Code Block
bgColor#CCCCFF
langc
#include <sys/resource.h>
/* ... */
struct rlimit limit;
limit.rlim_cur = 0;
limit.rlim_max = 0;
if (setrlimit(RLIMIT_CORE, &limit) != 0) {
    /* Handle error */
}

long pagesize = sysconf(_SC_PAGESIZE);
if (pagesize == -1) {
  /* Handle error */
}

char *secret_buf;
char *secret;

secret_buf = (char *)malloc(size+1+pagesize);
if (!secret_buf) {
  /* Handle error */
}

/* mlock() may require that the address is a multiple of PAGESIZE */
secret = (char *)((((intptr_t)secret_buf + pagesize - 1) / pagesize) * pagesize);

if (mlock(secret, size+1) != 0) {
    /* Handle error */
}

/* Perform operations using secret... */

if (munlock(secret, size+1) != 0) {
    /* Handle error */
}
secret = NULL;

free(secret_buf);
secret_buf = NULL;

...

Windows processes running with elevated privileges can disable paging by locking memory in place using VirtualLock() (Windows) [MSDN]:

Code Block
bgColor#CCCCFF
langc
char *secret;

secret = (char *)malloc(size+1);
if (!secret) {
  /* Handle error */
}

if (VirtualLock(secret, size+1) != 0) {
    /* Handle error */
}

/* Perform operations using secret... */

free(secret);
secret = NULL;

...