How to get 2FA on the command line
Getting Time-based One-Time-Password for 2FA on the command line.
Abstract
This HOW-TO has been succesfully tested on Ubuntu 22.04.3 LTS so let's assume you have a similar setup.
There is no shortage of OTP 2FA apps availiable for your phone, such as
Authy
, FreeOTP
or even the not so recommended Google Authenticator
.These apps take an initial secret code and create a TOTP anytime you need a 2FA code for login.
Some advantages of doing 2FA on the CLI are:
- Easy to add, maintain, and backup with a
simple key=val
text file - Copy/Paste is easier than typing digits displayed on your phone
- No issues with being locked out due to dead/lost/new phones
Installation
Make sure you're logged in as a regular user (not as root).
Install the two utility with:
sudo apt install oathtool gpg
We'll use a helper script as well as a file of initial secrets encrypted with GnuPG for better security.
sudo touch /usr/local/bin/totp
and, with your editor of choice, put the content below on the file and save it.
#!/bin/bash # # Time-based One-time Password algorithm (TOTP) helper script # Save shared secrets on disk protected with GnuPG encryption # Easily generate OTPs for two-factor authorization (2FA) # # Setup: # Install requirements with `sudo apt install oathtool gpg` # Setup gpg as per https://keyring.debian.org/creating-key.html # # Adapt the 3 variables below: # - KEYFILE: file that holds the name/key pairs # - UID: GnuPG user ID to use for encryption # - KEYID: GnuPG key ID to use for encryption # # Good to know: # - get gpg keys with: gpg --list-keys --keyid-format short user
Make it executable with :
sudo chmod +x /usr/local/bin/totp
If all went well, we can get a 2FA code on command line with:
$ totp twitter 078321
That's all folks.
Now you have a Time-based One-Time-Password for 2FA on the command line. Enjoy !!
$KEYFILE
) and the script itself have strict file permissions. This can be done usingchmod
to restrict access to only the necessary users, typically just the owner.$KEYFILE
. This can be a simple script that encrypts and copies the file to a secure location.