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:
- Attacker has root privileges. At that point all is lost anyway
- Attacker has the same user privileges. At that point they can just read your process memory
- 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
/run
– Warrantableio.BytesIO
) instead of a path? – Electrotechnology