← Все записи

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)

Исходный код на GitHub Gist

Пример работы

Создадим изолированное окружение, установим зависимости:

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:])

Исходный код на GitHub Gist

Разберем работу sample.py. Сначала идет шаг регистрации двухфакторной авторизации пользователя и сохранения секретного ключа (SECRET):

  • Генерируем новый секретный ключ (SECRET);
  • Выводим QR-код;
  • Пользователь его сканирует через Google Authenticator;
  • Вводит в форму ввода на сайте полученный от Google Authenticator токен;
  • Если Пользователь ввел правилный токен, то мы сохраняем секретный ключ (SECRET) этому пользователю в БД, чтобы при авторизации использовался этот ключ для валидации токенов с Google Authenticator.

Запускаем:

$ python sample.py 
SECRET:  UG4QTQ6F4JI4BE3Y

QR-код демонстрационной TOTP-записи для Google Authenticator

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

QR-код демонстрационной TOTP-записи для Google Authenticator

Please input the token from Google Authenticator: 123123
FAILED (тут специально пользователь ввел неверный токен)
Please input the token from Google Authenticator: 394500
SUCCESS (тут пользователь ввел верный токен, можно его авторизовывать)

Таким образом мы реализовали двухфакторную авторизацию на базе TOTP и Google Authenticator. Постараюсь в ближайшее время на базе этой статьи сделать приложение для Django, которое будет хранить секретные ключи в БД и выводить QR-код когда это необходимо.

Комментарии 3

Архив обсуждения. Новые комментарии закрыты.

Борис

Я для себя написал следующий код:

import hmac, base64, struct, hashlib, time, os

def clearShell():
    os.system(['cls'][os.name == os.sys.platform])

def HOTP(secret, intervals_no):
    key = base64.b32decode(secret, True)
    msg = struct.pack(">Q", intervals_no)
    h = hmac.new(key, msg, hashlib.sha1).digest()
    o = h[19] & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return h

def TOTP(secret):
    return HOTP(secret, intervals_no=int(time.time())//30)

S = {
    'Название': 'YOURSECRETCODE01',
    'Название': 'YOURSECRETCODE02'
}

lenght = 17 # Максимальная длина названия
line = ""
for i in range(0, lenght+18):
    line += "-"
line += "\n"

while True:
    text = line
    t = 30 - (int(time.time()) % 30)

    i = 0
    for s in S:
        i = i + 1

        code = TOTP(S[s])
        c1 = str(code//1000).rjust(3, '0')
        c2 = str(code %1000).rjust(3, '0')
        code = c1 + " " + c2

        text += "|  " + str(i).ljust(3, ' ') + " " + \
            s.ljust(lenght, ' ') + " " + code + "  |\n" + line

    text += "\n   ( " + str(t) + " с. )"

    clearShell()
    print(text)

    time.sleep(1)