diff options
author | Aaron LI <aly@aaronly.me> | 2018-03-13 13:46:52 +0800 |
---|---|---|
committer | Aaron LI <aly@aaronly.me> | 2018-03-13 13:46:52 +0800 |
commit | 327a519a234629c547fff704b36a8f537a325e0e (patch) | |
tree | e84193b63d03e368093be9084ba04cb489966356 /bin | |
parent | e22556fca6c254497626e85f5c26a59a97d85a17 (diff) | |
download | atoolbox-327a519a234629c547fff704b36a8f537a325e0e.tar.bz2 |
add bin/check-gpg-pass.sh to help cron tasks using gpg
Diffstat (limited to 'bin')
-rwxr-xr-x | bin/check-gpg-pass.sh | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/bin/check-gpg-pass.sh b/bin/check-gpg-pass.sh new file mode 100755 index 0000000..ed29c9f --- /dev/null +++ b/bin/check-gpg-pass.sh @@ -0,0 +1,77 @@ +#!/bin/sh +# +# Copyright (c) 2018 Aaron LI <aly@aaronly.me> +# MIT License +# +# `gpg-agent` is required by `gpg` to manage the private keys. It also +# caches the passphrase of the private keys, and will ask user if the +# cached passphrase expired, which may be annoying for the cron tasks. +# +# Workaround the `gpg-agent` asking for passphrase by testing its current +# status about the cached passphrase, i.e., with *pinentry* disabled +# (by passing the `--pinentry-mode error` to `gpg`), invoke `gpg` to try +# to sign a message, if it succeed, then the necessary passphrase has +# already been cached by `gpg-agent`. +# +# Reference: +# * Programmatically determine if gpg-agent will ask for passphrase +# https://superuser.com/a/1212720/731908 +# +# Aaron LI +# 2018-03-13 +# + +# Workaround to make `notify-send` work with cron +# Credit: https://stackoverflow.com/a/16520076 +export DISPLAY=:0 +export XAUTHORITY="${HOME}/.Xauthority" + +PROG="${0##*/}" +# Command to send notification +NOTIFY_CMD="notify-send" + + +error() { + echo "$*" >&2 +} + +exists() { + command -v "$1" >/dev/null 2>&1 +} + +notify() { + local message="$1" + if exists ${NOTIFY_CMD}; then + command ${NOTIFY_CMD} ${PROG} "${message}" + fi +} + + +# Check whether `gpg-agent` already cached the needed passphrase, +# if return 0 (i.e., success), then the passphrase is already cached, +# then `pass` can decrypt the password without triggering `gpg-agent` +# to ask user for the passphrase. +check_cached_passphrase() { + local key + [ -n "$1" ] && key="--local-user $1" || key="" + echo "test" | \ + gpg --sign --batch --no-tty --pinentry-mode error \ + ${key} -o /dev/null >/dev/null 2>&1 +} + + +case "$1" in + -h|--help) + echo "usage: ${PROG} [keyname]" + exit 1 + ;; +esac + +check_cached_passphrase "$1" +rv=$? +if [ ${rv} -ne 0 ]; then + msg="GPG passphrase not cached!" + error "${msg}" + notify "${msg}" +fi +exit ${rv} |