Skip to content

Instantly share code, notes, and snippets.

@zouppen
Last active September 16, 2022 15:25
Show Gist options
  • Save zouppen/d93e442a7586775897d5f3ec5f9e816f to your computer and use it in GitHub Desktop.
Save zouppen/d93e442a7586775897d5f3ec5f9e816f to your computer and use it in GitHub Desktop.
Command line TOTP (Google Authenticator) validator

TOTP (Google Authenticator) support in shell scripts

Here is a POSIX shell compliant TOTP validator.

Requires oathtool which is available from Debian / Ubuntu repositories and probably many other distros as well.

Usage

Drop TOTP secret in base32 format to otp.key to the directory where the script is. Remember to adjust file permissions!

The script exits with code 0 if the code is correct (see echo $?).

How to generate TOTP secret

To generate 180-bit shared secret:

openssl rand 20 | base32 >otp.key

To generate the secret with QR code with the secret to stdout. Requires qrencode (available from Debian / Ubuntu repositories as well:

echo -n "otpauth://totp/Spurdo?secret=`openssl rand 20 | base32 | tee otp.key`" | qrencode -t ansi

Have fun and stay secure!

#!/bin/sh -eu
#
# Exits with code 0 if given TOTP (Google Authenticator) code is
# correct. Accepting one earlier and one later code as well.
oathtool -b --totp "@`dirname "$0"`/otp.key" -w 2 -N '-30sec' | {
while read -r good; do
test "$good" != "$1" || exit 0
done
exit 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment