Introduction
Multi-factor authentication is simply an authentication process involving multiple authentication steps.
There are more and more situations today where the added security benefits of MFA are important. In this article, we'll look at using MFA in a command-line python application or process.
The Python modules, pyotp and qrcode, provide the functionality you need to enable MFA in your applications. We will be using one time passwords (OTP) and QR codes.
Process
The process is pretty straight forward:
- Generate a key for each user
- Generate a QR code from that key
- Load the QR code into appropriate software like Google Authenticator
- Verify the 6 digit code produced by Google Authenticator to authenticate someone
Implementation Details
OTP Key
The pyotp module will generate the key for you:
import pyotp
def genkey():
return pyotp.random_base32()
You will then save this key in an appropriate database, tied to the appropriate user.
The QR Code
The following code will generate a PNG image with the user's QR code, given the key and the user's email address. The key will have to be retreived from the key database based on the username.
import pyotp
import qrcode
org = "My Secure Org"
def writeqr(email, key, output):
t = pyotp.TOTP(key)
image = qrcode.make(t.provisioning_uri(email, org))
image.save(output)
print "Qrcode written to %s." % output
This image can then either be sent to the user or displayed on a website. This must be secured because it authorizes the user.
This image would then be used to configure the MFA software - like Google Authenticator.
Authenticate the user
The last step is to actually authenticate the user. All that is required is to retrieve the user's key from the database, and verify it:
import pyotp
def auth(mfa_code, key):
t = pyotp.TOTP(key)
return t.verify(mfa_code)
Comments