Skip to content

Building your own cheap OTP setup

A simple OTP setup

Sometimes you want to add a bit of extra security to an ssh server but don’t want to depend on external services like Google. As it appears, setting up OTP for yourself isn’t that big of an issue. In my concept I’m using email, since for me this is secure enough, you could ofcourse also connect an sms-box to the machine to send the OTP. The script will first authenticate you with your own credentials, secondly you will be asked to provide your OTP.

 

The script below makes the following assumptions:

  • You have an .otpkey  file in your homedir
  • /etc/profile is parsed on this machine during user login
  • You enter your pin followed directly by your password i.e.:  1234MyPassword

 

The .otpkey file looks like this.

pin=1234
email=user@myredfedora.com

 

The script which you append to /etc/profile which manages your OTP keyfile

 

# Disable echoing to screen
stty -echo

# Generating OTP
genpw=$(strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 6 | tr -d '\n'; echo)
# Reading PIN
otpin=$(grep pin "$HOME"/.otpkey | cut -d "=" -f2)
# Reading email address
otpmail=$(grep mail "$HOME"/.otpkey | cut -d "=" -f2)
# Sending OTP
echo "$genpw" | mail -s OTP "$otpmail"
# Trapping logout
trap logout INT
echo "A One-time password has been sent to your device. Please enter your pin and the password below followed by [enter]:"
# Read user input
read otp
# Re-enable echo to screen
stty echo
# Check if pin+OTP are valid, else logout
if [ ${otp} == ${otpin}${genpw} ];
then
    echo "OTP Validated."
else
    echo "OTP Invalid. Disconnecting."
    logout
fi

 

As you can see the script is quite simple but also forms an effective second layer of security.