该教程适用于YubiKey、CanoKey等支持GPG的物理密钥,目标是在Linux系统上使用简短的PIN而非较长的数据库密钥解锁KeePass数据库。
本文使用的环境是 Arch Linux,KDE桌面环境,KeePassXC。
首先你需要在硬件密钥中生成一个GPG密钥,该过程已有很多教程,此处不再赘述。
使用gpg -K
或gpg --card-status
,获得主密钥的ID,或智能卡中任一子密钥的ID,形如69D6E8DCB9E4117864368CA0EE4FB075119CE61F
或7C4464C89E529178
,以下统一以前者代替,请根据实际修改。
执行read -s password && echo -n "$password" | gpg --encrypt --armor -r 69D6E8DCB9E4117864368CA0EE4FB075119CE61F > ENCRYPTED_PASS_FILE.gpg
,输入数据库密钥后生成其加密副本。此处的--armor
仅用于以ASCII格式保存文件,若省略则以二进制格式保存。
将以下文件保存为unlock_keepassxc_with_key.sh
,使用chmod a+x unlock_keepassxc_with_key.sh
赋予可执行权限。
#!/usr/bin/env bash
# https://young-lord.github.io/posts/keepass-security-key
# Configuration
ENCRYPTED_PASS_FILE="/path/to/ENCRYPTED_PASS_FILE.gpg"
DATABASE_FILE="/path/to/keepass_database.kdbx"
unlock_with_secrutiy_key() {
echo "Please tap your key."
# idk why terminal doesn't show in KDE autostart, so the kind notice is useless.
local decrypted_pass
if decrypted_pass=$(gpg --quiet --decrypt "$ENCRYPTED_PASS_FILE" 2>/dev/null); then
nohup keepassxc --pw-stdin "$DATABASE_FILE" <<<"$decrypted_pass" >/dev/null 2>&1 &
disown
return 0
else
echo "Failed to decrypt password using security key."
return 1
fi
}
manual_unlock() {
nohup keepassxc >/dev/null 2>&1 &
disown
}
# Main execution
if gpg --card-status >/dev/null 2>&1; then
unlock_with_secrutiy_key || manual_unlock
else
manual_unlock
fi
在KeePassXC的设置中,关闭“系统运行时自动启动 KeePassXC”,打开“在应用程序启动时最小化窗口”。
对于KDE,在 System Settings -> System -> Autostart -> Add New -> Login Script 中添加该脚本。对于GNOME、Xfce等其他桌面环境,对应配置位置可能不同。
对于其他操作系统、原版KeePass,本方式经微调后亦可使用。
如果一切顺利,在插入硬件密钥的条件下,下次登录时,即会弹出输入OpenPGP PIN的窗口,输入PIN后,KeePassXC即在后台自动解锁。
目前仅可在开机(用户首次登录)时调用该脚本解锁,若重新锁定数据库,仍然需要输入数据库密码解锁。
该脚本未对内存中已解密的数据库密钥进行销毁等处理,可能存在泄露风险。
本文遵守 CC BY-NC-SA-4.0 许可协议。(不允许转载至简书或 CSDN)