Cloud based Two Factor Authentication with gpg+s3

This is an  experimental script I made to store encrypted TFA credentials in the cloud. It uses GPG to protect the confidentiality and integrity of the uploaded data. The tokens can be accessed anywhere on anything that has access to the GPG key.

Centralized management is possible because hosts can discover the location of the encrypted tokens is based on the hash of the gpg id. So you could take a single TFA secret and encrypt it using the gpg public keys you wish to grant access to.

For more information on TFA, check out an earlier post

#! /bin/bash

##
# Encrypt TFA secrets with Gpg and store in S3
# Download  :  https://s3.amazonaws.com/etherarp.net/s3tfa.sh
# Read more :  https://etherarp.net/cloud-based-tfa-with-gpg-and-s3
##

get_totp(){
 b="${TOTP_BUCKET}"
 g="$(echo "${TOTP_GPG_ID}" | openssl sha256|awk '/= /{print $2}')"
 k="$(echo $1 | openssl sha256|awk '/= /{print $2}')"
 oathtool --base32 --totp \
 "$(curl -fSsL https://s3.amazonaws.com/$b/$g/$k |
 gpg2 --decrypt --try-all-secrets 2>/dev/null)"
}
print_tokens(){
 g=$(echo $GPG_ID |openssl sha256|awk '/= /{print $2}' )
 for tfa_name in $@; do
  t=$(echo $tfa_name | openssl sha256|awk '/= /{print $2}' )
  printf "%s : %s\n" "${tfa_name}" "$(get_totp $t)"
 done 2>/dev/null|column -t
}
# Check for required vars
if [ -z $TOTP_GPG_ID ]; then
 echo "TOTP_GPG_ID must be set! Exiting..." >&2
 exit 255
elif [ -z $TOTP_BUCKET ]; then
 echo "TOTP_BUCKET must be set! Exiting..." >&2
 exit 255
elif [ $# -lt 2 ]; then
  echo "Usage: $0 token_names" >&2
  exit 255
fi 
# Print the tokens
print_tokens $@

The running output look like this

[rohan@desktop ~]$ s3tfa fakeacct1 fakeacct2 fakeacct3
fakeacct1   :  011899
fakeacct2   :  988191
fakeacct3   :  117253