为何使用python-gnupg时任意口令均可成功解密文件?该如何规避?
遇到的问题
我尝试编写一个可用于文件加解密的简单脚本,但发现无论使用什么passphrase都不影响解密结果,示例如下:
密钥生成脚本 gen_key.py
import gnupg import os gpg = gnupg.GPG(gnupghome='gnupg') gpg.encoding = 'utf-8' input_data = gpg.gen_key_input( name_email = 'test@test.com', passphrase = 'mypassphrase', key_type = 'RSA', key_length = 1024) key = gpg.gen_key(input_data) print(key)
加密脚本 encrypt.py
import gnupg import os gpg = gnupg.GPG(gnupghome = 'gnupg') with open('test.txt', 'rb') as f: status = gpg.encrypt_file(f, recipients = ['test@test.com'], output='test.encrypted') print(status.ok)
解密脚本 decrypt.py
import gnupg import os gpg = gnupg.GPG(gnupghome='gnupg') with open('test.encrypted', 'rb') as f: status = gpg.decrypt_file(f, passphrase = 'wrongpassphrase', output = 'test2.txt') print(status.ok)
注意:
decrypt.py中我们使用的是错误的passphrase,但即便传入了错误的passphrase,脚本仍能成功解密文件。想知道这个问题的出现原因,以及要如何规避这种情况?
问题根因
这个现象没有任何加密逻辑层面的漏洞,都是python-gnupg配合gpg-agent的常见使用坑叠加出来的:
- GPG Agent的私钥缓存会直接绕过passphrase校验
你第一次用正确密码生成密钥、或是第一次解密成功用了正确密码之后,后台的gpg-agent进程会默认把已经解锁的私钥驻留在内存里,默认缓存时长能到几小时。这种状态下后续的解密操作根本不会触发passphrase校验流程——私钥已经是解锁状态,gpg直接拿缓存的私钥解密,你传入的passphrase参数压根没有被用到,自然传错、传空都不会影响解密结果。 status.ok的判断逻辑过于粗糙,会掩盖真实的流程异常
不少python-gnupg的历史版本对agent模式的状态返回有兼容问题:哪怕解密流程本该被passphrase校验拦截,只要agent已经解锁私钥完成了实际解密,status.ok就会直接返回True,不会标记“传入的passphrase和私钥要求不匹配”的异常。
还有个更少见但确实会碰到的情况:如果生成密钥的流程被后台的gpg-agent拦截自动应答了,实际落地的私钥根本没有绑定你脚本里设置的passphrase,属于无保护的私钥,那不管解密传什么密码都能成功。
可落地的规避方案
- 初始化GPG实例的时候直接禁用agent缓存,强制每次解密都校验传入的passphrase:
gpg = gnupg.GPG( gnupghome='gnupg', ignore_cache=True, options=['--agent-program=/bin/true'] # 直接替换掉gpg-agent,从根上杜绝缓存 )
配置完成后,只要传入的passphrase不对,解密就会直接返回失败,不会走缓存的解锁状态。
- 生成密钥后主动做有效性校验,确认passphrase确实绑定到了私钥上:
key = gpg.gen_key(input_data) # 用错误密码测试私钥解锁状态,预期返回False unlock_test = gpg.unlock_key(key.fingerprint, passphrase='wrong-test-pass') print(f"错误密码解锁测试结果:{unlock_test}")
如果这里传错密码也能解锁,说明生成的私钥根本没有设置密码保护,直接删掉重新生成即可。
- 不要只依赖
status.ok判断结果,要把完整的错误日志打出来排查:
print(f"解密是否成功:{status.ok}") print(f"解密流程日志:{status.stderr}")
正常如果passphrase不匹配,stderr里会直接返回Bad passphrase的明确报错,不会出现“流程跑通但逻辑不对”的问题。
- 本地做功能测试前,先把残留的gpg-agent进程全部杀掉:
执行命令gpgconf --kill gpg-agent清空所有内存里缓存的私钥状态,再跑解密脚本,彻底排除缓存带来的测试干扰。
内容的提问来源于stack exchange,提问作者user15116257
相关产品推荐
相关产品推荐

