Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Securely Erasing Password in Memory (Python)

How do you store a password entered by the user in memory and erase it securely after it is no longer need?

To elaborate, currently we have the following code:

username = raw_input('User name: ') password = getpass.getpass() mail = imaplib.IMAP4(MAIL_HOST) mail.login(username, password) 

After calling the login method, what do we need to do to fill the area of memory that contains password with garbled characters so that someone cannot recover the password by doing a core dump?

There is a similar question, however it is in Java and the solution uses character arrays: How does one store password hashes securely in memory, when creating accounts?

Can this be done in Python?

like image 665
maxyfc Avatar asked Apr 08 '09 01:04

maxyfc


People also ask

Is Getpass secure in Python?

getpass() and getuser() in Python (Password without echo) getpass() prompts the user for a password without echoing. The getpass module provides a secure way to handle the password prompts where programs interact with the users via the terminal.

How do I hide a password in Python?

There are various Python modules that are used to hide the user's inputted password, among them one is maskpass() module. In Python with the help of maskpass() module and base64() module we can hide the password of users with asterisk(*) during input time and then with the help of base64() module it can be encrypted.

How do I store login details in python?

The fastest way to get the password will be to add a print statement to the Python script just before it uses the password with the third-party service. So store the password as a string in the script, and base64 encode it so that just reading the file isn't enough, then call it a day.


1 Answers

Python doesn't have that low of a level of control over memory. Accept it, and move on. The best you can do is to del password after calling mail.login so that no references to the password string object remain. Any solution that purports to be able to do more than that is only giving you a false sense of security.

Python string objects are immutable; there's no direct way to change the contents of a string after it is created. Even if you were able to somehow overwrite the contents of the string referred to by password (which is technically possible with stupid ctypes tricks), there would still be other copies of the password that have been created in various string operations:

  • by the getpass module when it strips the trailing newline off of the inputted password
  • by the imaplib module when it quotes the password and then creates the complete IMAP command before passing it off to the socket

You would somehow have to get references to all of those strings and overwrite their memory as well.

like image 176
Miles Avatar answered Sep 28 '22 01:09

Miles