3

I know there is a gpg-agent config to set how long we can cache a password into gpg-agent. The setting is called --max-cache-ttl n

But when a passphrase is cached in gpg-agent for example for 10 seconds, how do I obtain the current cache duration like how many seconds left until it will be expired? Is there a query option for this where I can obtain directly from gpg-agent?

1 Answer 1

4

Not sure about the built-in feature that gpg-agent has. I don't think it is possible but I'm showing a trick how you can get cache duration left:

First rule: When you cache a passphrase in gpg-agent, you first store the date in unix timestamp as a variable inside a config file:

GPG_MY_CONFIG="~/.gnupg/my-gpg.conf"
function set_config() {

    sudo sed -i "s/^\($1\s*=\s*\).*\$/\1$2/" $GPG_MY_CONFIG
}

echo "date_cached=$(date +%s)" | sudo tee --append $GPG_MY_CONFIG
# Now you got the following date (with unix timestamp) inside my-gpg.conf like below:
# date_cached=1599710839
# When you cached a new password, then run this code to update new date in unix timestamp:
# set_config date_cached "$(date +%s)"

It's best to have the current --max-cache-ttl n value from gpg-agent.conf file, so we can query this:

# ~/.gnupg/gpg-agent.conf
allow-preset-passphrase
default-cache-ttl 10
max-cache-ttl 10

First, read the setting max-cache-ttl value and save it in a variable expired_in_second like this:

# location of gpg config file
GPG_CONFIG_FILE="~/.gnupg/gpg-agent.conf"
# read the config file for value max-cache-ttl
expired_in_second=$(grep -oP 'max-cache-ttl\s*\K\d+' $GPG_CONFIG_FILE)

So now you got 2 important variables, you can get expired date by using this 2 variables:

# First source the config file:
source $GPG_MY_CONFIG
# expired_date = date_cached_previously + expired_duration (from max-cache-ttl)
expired_date=$(date -d "(date -d @${date_cached}) + $expired_in_second seconds")

and to get the duration left you can use this (compare the expired date with the current time):

# second_left = expired_date - current_date
second_left="$(( $(date -d "$expired_date" "+%s") - $(date +%s) ))"

echo "$second_left seconds remaining before password is going to be expired"

Output:

10 seconds remaining before password is going to be expired

I believe the above code can be simplified more. Hope this help :)

1
  • 1
    Thanks. It seems working perfectly with this hack .
    – Kalib Zen
    Commented Sep 10, 2020 at 6:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .