Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Updated the Windows example so that it uses the proper memory APIs.

...

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 be 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;

Compliant Solution (

...

Windows)

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 *)mallocVirtualAlloc(0, size + 1, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (!secret) {
  /* Handle error */
}

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

/* Perform operations using secret... */

free(secretSecureZeroMemory(secret, size + 1);
VirtualUnlock(secret, size + 1);
VirtualFree(secret, 0, MEM_RELEASE);
secret = NULL;

Note that locking pages of memory on Windows may fail due to the process only being given a small number of pages it is allowed to lock by the operating system.  If your application requires more locked pages, you can use the SetProcessWorkingSetSize() API to increase the application's minimum working set size.  Locking pages has severe performance consequences and should be used sparingly.

Risk Assessment

Writing sensitive data to disk preserves it for future retrieval by an attacker, who may even be able to bypass the access restrictions of the operating system by using a disk maintenance program.

...