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 ?
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:
Of course there is nothing wrong with some defence in the deep.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With