1

On Linux, is it possible that memory pages that contain the process stack get swapped to disk? If so, is there a way to prevent that, either at compile time or at runtime.

I'm asking because of a discussion on GitHub about potentially leaking secrets from local variables on the stack

In case an answer to that question not only depends on the kernel, but also depends on the userspace toolchain in use (libc, dynamic linker etc.), my question is about GNU/Linux and Android in particular.

3
  • Look up "swap encryption". Commented Sep 29, 2017 at 13:16
  • @Kusalananda: I don't have control over the target environment. At least not enough to encrypt the swap Commented Sep 29, 2017 at 13:17
  • 2
    Yes, almost all memory of a process may be swapped to disk. Commented Sep 29, 2017 at 13:20

1 Answer 1

3

On Linux, (nearly) all of a process’s memory can be swapped out, including its heap and its stack.

However it is possible to lock pages of memory into physical RAM, so that they can not be swapped out. This is done using the mlock system call (or mlockall to lock all of a process’s memory). This is a privileged operation, so the process needs to have the appropriate capability, CAP_IPC_LOCK (see gnome-keyring-daemon for an example of this: /sbin/getcap /usr/bin/gnome-keyring-daemon).

4
  • I knew about mlock. Since I don't know which pages contain the stack, and when a new page is allocated to back the stack, this only leaves me with mlockall (assuming that I am even allowed to lock that amount of memory, since it can be limited by the kernel). I was really hoping that there was a way to lock only the stack. Commented Sep 29, 2017 at 17:12
  • Yeah you need to know where the stack is and how it will grow if you want to only lock the stack; AFAIK there’s no easy way to just say “lock the stack, including any new pages it needs as it grows”. Most programs wanting to lock sensitive data process it on the heap, it’s much easier that way... You could also lock the individual buffers involved once they’re allocated on the stack, before using them. Commented Sep 29, 2017 at 17:30
  • Yes, I put my sensitive data on the heap and lock it with mlock and mprotect. This is about local variables potentially ending up on the stack instead of registers. Commented Sep 29, 2017 at 17:34
  • There’s no easy fix for that unfortunately (yet...). Commented Sep 29, 2017 at 17:52

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.