Posts filed under ‘posix’

Secure memory (a.k.a. mlock)

Last week, while trying to slim down the software dependencies of an application, I figured it out that one library could be dismissed if we could provide a secure/safe memory block to store a key.

This is a common requisite in 2 areas (real time systems and security applications): having a way to ensure that a segment of memory will not be swapped to the disk. For real time, swapping from the disk back to the memory can ruin the purpose of having deterministic performance and for security let’s just say that is bad to save passwords/keys in a non encrypted filesystem (even worst if you run our swap in a filesystem that can’t couple with user privileges).

After googling a lot to no avail, I decided to ask Arnaldo Carvalho (a.k.a. acme) if there was a syscall for letting the O.S. know that a memory block should not be swapped. The answer: man mlock (it turned to be a POSIX 2001 function to my surprise).

The idea is quite simple:

  • malloc some memory;
  • ask the O.S. to lock it (make it un-swappable);
  • use it;
  • unlock the memory and clean it later.

The only tricky part is that thanks to COW (Copy On Write), you can have access to a segment of memory that is being shared by your process parent (so the way to ensure that the memory is actually being duplicated to your process is by writing on it). A memset could do it, but I decided to be fancier and use another POSIX call sysconf (getpagesize is marked as deprecated in the man pages) to mark as dirty only one byte at each page. You can have the code here.

The way to use it:

unsigned int size;
char *ptr;
ptr = alloc_secure_memory(size);
if (ptr) {
//do something with the memory and later clean it

free_secure_memory(ptr, size);


I limited the amount of memory lockable to 20K, since it is way more than you usually need for storing a key and besides linux (in my case, Ubuntu) will limit the amount of lockable memory to 64K (of course if you are the root user you can set another value with ‘ulimit -l xxxx’).

Pay attention that mlockall can lock the whole memory of your application (with the risk of bringing the whole system performance down if you are running out of memory for other processes) and you should not use it.


March 30, 2010 at 11:00 am 3 comments


July 2018
« Apr    

Posts by Month

Posts by Category