logo

Linux - memfd

What is it?

A memfd (Memory File Descriptors) is an anonymous file that lives entirely in RAM.

Normally, when you create a file, it is linked to a name on your hard drive (like /home/user/test.txt). A memfd has no link to the disk and no name in the global filesystem. It exists only as a File Descriptor (FD) in the process's memory.

Why use it? (The "Secret" File)

Since a memfd behaves exactly like a regular file but never touches the disk, it is used for three main reasons:

A. High-Speed Inter-Process Communication (IPC)

If Process A wants to share 1GB of data with Process B:

  • Old way: Process A writes 1GB to a temporary file on disk; Process B reads it. (Slow disk I/O).
  • Memfd way: Process A creates a memfd, writes the data into RAM, and then passes the File Descriptor to Process B. Process B can now "see" that same memory instantly.

B. File "Sealing" (The Security Feature)

This is the most unique feature of memfd. Once you have written data to a memfd, you can seal it.

  • You can seal it against writing: The file becomes permanently read-only.
  • You can seal it against shrinking/growing: The file size is locked.
  • Why? This allows you to share a memory buffer with an untrusted process. You can give a "sealed" FD to another process, knowing for a fact that the other process cannot change the data or crash your memory by resizing the file.

C. Running Binaries from RAM

Security tools (and unfortunately, malware) use memfd to run programs without leaving a trace on the hard drive. They download a binary, write it into a memfd, and then use fexecve() to execute that file descriptor directly from RAM.

How it relates to FD?

A memfd is the ultimate example of the File Descriptor concept. It is a "file" that only exists as an FD. If you close the FD and no other process has it, the memory is immediately reclaimed by the kernel. It is 100% ephemeral.

memfd vs /dev/shm

You might be familiar with /dev/shm (shared memory).

  • /dev/shm uses a name (you can see it with ls).
  • memfd is anonymous. Only processes that have been explicitly handed the FD can see it. This is much more secure because an unrelated process cannot "guess" the filename and try to peek at the data.

What does it look like?

If you want to see if your system is using them, run:

ls -l /proc/*/fd | grep memfd

You will see output like: lrwx------ 1 user user 64 Jan 1 10:00 3 -> /memfd:wayland-shm (deleted)

The (deleted) tag is Linux’s way of saying "This file has no link to a physical spot on the hard drive." It is a "ghost" file that exists only in the RAM managed by that process.

Summary

  • What is it? A file that lives in RAM, not on disk.
  • How do you access it? Only via a File Descriptor.
  • Key Feature: Sealing (making memory immutable/read-only).
  • Use case: Securely sharing data between containers or processes without the overhead of disk I/O.