Python. Двухфакторная авторизация через Google Authenticator

Последние годы стало модно делать двухфакторную авторизацию, это безусловно повышает безопасность приложений и сайтов в частности, сегодня я расскажу как сделать дополнительную авторизацию через TOTP. В качестве клиента будем использовать мобильную версию Google Authenticator для Android.
Для этого нам понадобится два файла:
- “totp.py” - собственно реализация алгоритма TOTP;
- “totp_auth.py” - хелпер для генерации и валидации токенов.
totp.py
"""
Time-based One-time Password Algorithm
Based on the pyotp: https://github.com/nathforge/pyotp
"""
import base64
import hashlib
import hmac
import datetime
import random
import time
import sys
import urllib
def random_base32(length=16, random=random.SystemRandom(),
chars=base64._b32alphabet.values()):
return ''.join(
random.choice(chars)
for i in xrange(length)
)
class OTP(object):
def __init__(self, secret, digits=6):
self.secret = secret
def int_to_bytestring(self, int, padding=8):
"""
Turns an integer to the OATH specified
bytestring, which is fed to the HMAC
along with the secret
"""
result = []
while int != 0:
result.append(chr(int & 0xFF))
int = int >> 8
return ''.join(reversed(result)).rjust(padding, '\0')
def generate_otp(self, input):
"""
@param [Integer] input the number used seed the HMAC
Usually either the counter, or the computed integer
based on the Unix timestamp
"""
hmac_hash = hmac.new(
base64.b32decode(self.secret, casefold=True),
self.int_to_bytestring(input),
hashlib.sha1,
).digest()
offset = ord(hmac_hash[19]) & 0xf
code = ((ord(hmac_hash[offset]) & 0x7f) << 24 |
(ord(hmac_hash[offset + 1]) & 0xff) << 16 |
(ord(hmac_hash[offset + 2]) & 0xff) << 8 |
(ord(hmac_hash[offset + 3]) & 0xff))
# '6' is number of integers in the OTP
return code % 10 ** 6
class TOTP(OTP):
def __init__(self, *args, **kwargs):
"""
@option options [Integer] internval (30) the interval in seconds
This defaults to 30 which is standard.
"""
self.interval = kwargs.pop('interval', 30)
super(TOTP, self).__init__(*args, **kwargs)
def timecode(self, for_time):
i = time.mktime(for_time.timetuple())
return int(i / self.interval)
def now(self):
"""
Generate the current time OTP
@return [Integer] the OTP as an integer
"""
return self.generate_otp(self.timecode(datetime.datetime.now()))
def at(self, date):
"""
Generate the current time OTP
@return [Integer] the OTP as an integer
"""
return self.generate_otp(self.timecode(date))
def verify(self, otp, for_time=None):
"""
Verifies the OTP passed in against the current time OTP
@param [String/Integer] otp the OTP to check against
"""
if for_time is None:
for_time = datetime.datetime.now()
return otp == self.at(for_time)
def provisioning_uri(self, name):
"""
Returns the provisioning URI for the OTP
This can then be encoded in a QR Code and used
to provision the Google Authenticator app
@param [String] name of the account
@return [String] provisioning uri
"""
return 'otpauth://totp/%(name)s?secret=%(secret)s' % {
'name': urllib.quote(name, safe='@'),
'secret': self.secret,
}
if __name__ == "__main__":
secret = "AAAAAAAAAAAAAAAA"
unixtime = 0
if len(sys.argv) > 1:
unixtime = int(sys.argv[1])
if unixtime > 1:
date = datetime.datetime.fromtimestamp(unixtime)
else:
date = datetime.datetime.now()
totp = TOTP(secret)
print "TOTP token for secret '%s' at '%s' is: %s" % (
secret, date, totp.at(date))
totp_auth.py
import totp
import qrcode
import datetime
class TotpAuth(object):
def __init__(self, secret=None):
if secret is None:
secret = totp.random_base32()
self.secret = secret
self.totp = totp.TOTP(secret)
def generate_token(self):
return self.totp.now()
def valid(self, token):
try:
token = int(token)
except ValueError:
return False
now = datetime.datetime.now()
time30secsago = now + datetime.timedelta(seconds=-30)
try:
valid_now = self.totp.verify(token)
valid_past = self.totp.verify(token, for_time=time30secsago)
return valid_now or valid_past
except:
return False
def qrcode(self, username):
uri = self.totp.provisioning_uri(username)
return qrcode.make(uri, box_size=4)
Пример работы
Создадим изолированное окружение, установим зависимости:
mkdir ~/work/totp && cd ~/work/totp
wget -O totp.py https://gist.githubusercontent.com/adw0rd/0a61f53dd7a61e5aa65c/raw/totp.py
wget -O totp_auth.py https://gist.githubusercontent.com/adw0rd/0a61f53dd7a61e5aa65c/raw/totp_auth.py
virtualenv --no-site-packages --distribute venv
. venv/bin/activate
pip install qrcode PIL
Создадим файл sample.py для демонстрации работы, со следующим содержимым:
sample.py
from totp_auth import TotpAuth
def main(secret=None):
if not secret:
# WHEN SIGN UP
ta = TotpAuth()
else:
# WHEN SIGN IN
ta = TotpAuth(secret)
# SHOW SECRET AND QR CODE
qr = ta.qrcode('adw0rd@adw0rd.com')
print 'SECRET: ', ta.secret
qr._img.show()
# CHECK TOKEN
while True:
token = raw_input('Please input the token from Google Authenticator: ')
if ta.valid(token):
print "SUCCESS"
else:
print "FAILED"
if __name__ == '__main__':
import sys
main(*sys.argv[1:])
Разберем работу sample.py. Сначала идет шаг регистрации двухфакторной авторизации пользователя и сохранения секретного ключа (SECRET):
- Генерируем новый секретный ключ (SECRET);
- Выводим QR-код;
- Пользователь его сканирует через Google Authenticator;
- Вводит в форму ввода на сайте полученный от Google Authenticator токен;
- Если Пользователь ввел правилный токен, то мы сохраняем секретный ключ (SECRET) этому пользователю в БД, чтобы при авторизации использовался этот ключ для валидации токенов с Google Authenticator.
Запускаем:
$ python sample.py
SECRET: UG4QTQ6F4JI4BE3Y

Please input the token from Google Authenticator: 123123
FAILED (тут специально пользователь ввел неверный токен)
Please input the token from Google Authenticator: 613257
SUCCESS (тут пользователь ввел верный токен, сохраняем SECRET в БД)
Теперь разберем шаги авторизации:
- Пользователь входит на сайт и вводит правильные логин и пароль;
- Если мы однозначно идентифицируем пользователя и для него уже есть секретный ключ (SECRET) в БД, то выводим ему QR-код по этому секретному ключу;
- Он сканирует QR-код через Google Authenticator, либо среди свои аккаунтов находит уже созданный и вводит текущий токен на сайте;
- Если он за указанное время ввел токен, то авторизация считается успешной иначе ему предлагается повторить попытку.
Запускаем с секретным ключем:
$ python sample.py UG4QTQ6F4JI4BE3Y
SECRET: UG4QTQ6F4JI4BE3Y

Please input the token from Google Authenticator: 123123
FAILED (тут специально пользователь ввел неверный токен)
Please input the token from Google Authenticator: 394500
SUCCESS (тут пользователь ввел верный токен, можно его авторизовывать)
Таким образом мы реализовали двухфакторную авторизацию на базе TOTP и Google Authenticator. Постараюсь в ближайшее время на базе этой статьи сделать приложение для Django, которое будет хранить секретные ключи в БД и выводить QR-код когда это необходимо.
Комментарии 3
Архив обсуждения. Новые комментарии закрыты.
Есть для джанги уже django-secureauth
Да, для джанги уже куча таких либ, я уже решил ничего не писать
https://github.com/Bouke/django-two-factor-auth
https://github.com/mtigas/django-twofactor
Я для себя написал следующий код: