Securely overwrite Python variables in RAM? [dupli

2019-02-23 03:14发布

问题:

This question already has an answer here:

  • Securely Erasing Password in Memory (Python) 7 answers

I'm making a program in Python that will involve hashing a password. Assuming I use this to get the password:

import getpass
password = getpass.getpass("Password: ")

And then hash it, is there any way to securely remove all traces of the unhashed password from RAM?

回答1:

As previously discussed there is no foolproof way to do this in python even if you had a custom implementation (although this might be a way).

Now I don't know what your application is supposed to do but what I can tell you without any doubt is that your data is safer in the RAM than it is in your database, even after the hash.

The way memory works is so complex. Every process has its own virtual memory space which doesn't have to be contiguous. Full blocks of memory are swapped to the disk and put back in another memory block. The whole memory is just a set of bytes and it's almost impossible to tell the difference between an array of integers, a string, a cat or simple random data.

Some data blocks are partially reallocated creating a large quantity of partial data. Imagine what this would like, 1, 2, 8 or even 16Gb of random data, and the potential hacker would have to find a password in all those 0s and 1s.

If someone wanted to hack your password during the execution of the process he would need to have live access to the machine as root; he cannot do it by just looking at the swap afterward for the reasons I stated earlier.

But if some one has this kind of access there are so many other ways to get the password. For instance simply debug the program, or better, just change the source and make it print the password :)

Most hackers will not bother going through such a hassle. Hacking is mostly about social engineering, which is basically making the user give the hacker its password willingly. Phishing is one such method.