decrypt_keyctl 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/bin/sh
  2. # decrypt_keyctl - to use in /etc/crypttab as keyscript
  3. # Allows to cache passwords for cryptdevices for 60s
  4. # The same password is used for for cryptdevices with the same identifier.
  5. # The keyfile parameter, which is the third field from /etc/crypttab, is
  6. # used as identifier in this keyscript.
  7. #
  8. # sample crypttab entries:
  9. # test1 /dev/sda1 test_pw luks,keyscript=decrypt_keyctl
  10. # test2 /dev/sda2 test_pw luks,keyscript=decrypt_keyctl
  11. # test3 /dev/sda3 test_other_pw luks,keyscript=decrypt_keyctl
  12. #
  13. # test1 and test2 have the same identifier thus test2 does not need a password
  14. # typed in manually
  15. die()
  16. {
  17. echo "$@" >&2
  18. exit 1
  19. }
  20. if [ -z "${CRYPTTAB_KEY:-}" ] || [ "$CRYPTTAB_KEY" = "none" ]; then
  21. # store the passphrase in the key name used by systemd-ask-password
  22. ID_="cryptsetup"
  23. else
  24. # the keyfile given from crypttab is used as identifier in the keyring
  25. # including the prefix "cryptsetup:"
  26. ID_="cryptsetup:$CRYPTTAB_KEY"
  27. fi
  28. TIMEOUT_='60'
  29. ASKPASS_='/lib/cryptsetup/askpass'
  30. PROMPT_="Caching passphrase for ${CRYPTTAB_NAME}: "
  31. if ! KID_="$(keyctl search @u user "$ID_" 2>/dev/null)" || \
  32. [ -z "$KID_" ] || [ "$CRYPTTAB_TRIED" -gt 0 ]; then
  33. # key not found or wrong, ask the user
  34. KEY_="$($ASKPASS_ "$PROMPT_")" || die "Error executing $ASKPASS_"
  35. if [ -n "$KID_" ]; then
  36. # I have cached wrong password and now i may use either `keyctl update`
  37. # to update $KID_ or just unlink old key, and add new. With `update` i
  38. # may hit "Key has expired", though. So i'll go "unlink and add" way.
  39. keyctl unlink "$KID_" @u
  40. KID_=""
  41. fi
  42. KID_="$(printf "%s" "$KEY_" | keyctl padd user "$ID_" @u)"
  43. [ -n "$KID_" ] || die "Error adding passphrase to kernel keyring"
  44. if ! keyctl timeout "$KID_" "$TIMEOUT_"; then
  45. keyctl unlink "$KID_" @u
  46. die "Error setting timeout on key ($KID_), removing"
  47. fi
  48. else
  49. echo "Using cached passphrase for ${CRYPTTAB_NAME}." >&2
  50. fi
  51. keyctl pipe "$KID_"