Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path to in-memory-file without dumping in tmp

Is there a way in python to get the path to the in-memory file, so it'll behave as a normal file for methods which needs file path?

My objective is to protect the file, so avoiding dumping into /tmp.

Trying to read an encrypted file -> decrypt a file into memory -> use its path for other interfaces.

mmap does not provide path or filename.

Or any alternative solution for this problem ?

like image 448
Shubham Jain Avatar asked Sep 12 '25 14:09

Shubham Jain


1 Answers

Your tags don't mention an operating system but I assume you run Linux since you mentioned /tmp. In that case, you can use /dev/shm. It's the directory which is used for POSIX shared memory and is typically the mount point for a tmpfs filesystem. So it stays in memory unless the system has to swap but that's no different from your regular process memory.

That means this should work for you:

with tempfile.NamedTemporaryFile(dir='/dev/shm') as memfile:
    size = 1024
    memfile.file.truncate(size)
    mapped = mmap.mmap(memfile.file.fileno(), size)

I should mention that this is obviously non-portable, even to other Unix systems.

As far as this whole endeavour is concerned: One may question the point of it. What scenario are you protecting against? Named temporary files are already created with read-permissions set to user-only, so there are only three ways to read it:

  1. Attacker has root privileges. At that point all is lost anyway
  2. Attacker has the same user privileges. At that point they can just read your process memory
  3. Attacker has physical access and can read the file system / underlying disk. If that is a viable attack vector, disk encryption should be the primary defence

Of course there is nothing wrong with some defence in the deep.

Alternative

Here is another fun little trick: Use /proc/<pid>/fd

with tempfile.TemporaryFile() as outfile:
    outfile.write(b"Username, Password")
    outfile.flush()
    filepath = f"/proc/{os.getpid()}/fd/{outfile.fileno()}"
    content = open(filepath).read()

By my account it isn't any more secure (as discussed above) or portable, but maybe a bit more obfuscated. Plus, since the unnamed file is backed by the /tmp filesystem, it can potentially be much larger than the shared memory in /dev/shm

like image 178
Homer512 Avatar answered Sep 15 '25 03:09

Homer512