安全擦除内存中的密码 (Python) [英] Securely Erasing Password in Memory (Python)

查看:24
本文介绍了安全擦除内存中的密码 (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)

调用login方法后,我们需要做些什么来将包含密码的内存区域填充为乱码,以至于有人无法通过core dump恢复密码?

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?

有一个类似的问题,但它是在 Java 中并且解决方案使用字符数组:如何将密码哈希安全地存储在内存,创建帐户时?

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?

这可以用 Python 完成吗?

Can this be done in Python?

推荐答案

Python 对内存的控制没有那么低.接受它,然后继续前进.您可以做的最好是在调用 mail.logindel password,这样就不会保留对密码字符串对象的引用.任何声称能够做更多事情的解决方案只会给您一种虚假的安全感.

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 字符串对象是不可变的;没有直接的方法可以在创建字符串后更改其内容.即使你能够以某种方式覆盖由 password 引用的字符串的内容(这在技术上用愚蠢的 ctypes 技巧是可能的),仍然会有其他副本在各种字符串操作中创建的密码:

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:

  • 通过 getpass 模块从输入的密码中去除尾随换行符
  • 通过 imaplib 模块引用密码,然后在将其传递给套接字之前创建完整的 IMAP 命令

您必须以某种方式获取对所有这些字符串的引用并覆盖它们的内存.

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

这篇关于安全擦除内存中的密码 (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆