2021-04-15 15:40:23 +02:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#coding: utf-8
|
|
|
|
|
|
|
|
"""
|
|
|
|
Generate an TOTP token (hex value for user.oath file and qrcode).
|
|
|
|
|
|
|
|
usage:
|
2021-04-15 17:10:35 +02:00
|
|
|
gen_otp.py [user [machine [periode [digits]]]]
|
2021-04-15 15:40:23 +02:00
|
|
|
|
|
|
|
dependancies:
|
|
|
|
pip3 install qrcode
|
|
|
|
"""
|
|
|
|
|
|
|
|
import base64
|
|
|
|
import binascii
|
|
|
|
import secrets
|
|
|
|
import sys
|
2021-04-15 17:10:35 +02:00
|
|
|
import yaml
|
2021-04-15 15:40:23 +02:00
|
|
|
|
|
|
|
import qrcode
|
|
|
|
|
2021-04-23 15:12:12 +02:00
|
|
|
VAR_FILE = "../group_vars/all/totp.yml"
|
2021-04-15 17:10:35 +02:00
|
|
|
|
|
|
|
with open(VAR_FILE) as f:
|
|
|
|
VARS = yaml.safe_load(f)
|
|
|
|
|
|
|
|
USAGE = "gen_otp.py [user [machine [periode [digits]]]]"
|
2021-04-15 15:40:23 +02:00
|
|
|
USER = "user"
|
2021-04-15 17:10:35 +02:00
|
|
|
MACHINE = VARS.get('totp_machine', 'machine')
|
|
|
|
PERIODE = VARS.get('totp_periode', 60)
|
|
|
|
DIGITS = VARS.get('totp_digits', 6)
|
2021-04-15 15:40:23 +02:00
|
|
|
|
|
|
|
if len(sys.argv) == 2 and sys.argv[1] in ['-h', 'help', '--help']:
|
|
|
|
print(USAGE)
|
|
|
|
exit(0)
|
2021-04-15 17:10:35 +02:00
|
|
|
if len(sys.argv) == 5:
|
|
|
|
DIGITS = int(sys.argv[4])
|
|
|
|
if len(sys.argv) >= 4:
|
|
|
|
PERIODE = int(sys.argv[3])
|
2021-04-15 15:40:23 +02:00
|
|
|
if len(sys.argv) >= 3:
|
|
|
|
MACHINE = sys.argv[2]
|
|
|
|
if len(sys.argv) >= 2:
|
|
|
|
USER = sys.argv[1]
|
|
|
|
|
|
|
|
token = secrets.token_bytes(15)
|
|
|
|
token_hex = binascii.hexlify(token).decode('utf-8')
|
|
|
|
token_b32 = base64.b32encode(token).decode('utf-8')
|
2021-04-15 17:10:35 +02:00
|
|
|
uri = "otpauth://totp/{user}@{machine}?secret={secret}&digits={digits}&period={periode}".format(
|
2021-04-15 15:40:23 +02:00
|
|
|
user=USER,
|
|
|
|
machine=MACHINE,
|
|
|
|
secret=token_b32,
|
2021-04-15 17:10:35 +02:00
|
|
|
digits=DIGITS,
|
2021-04-15 15:40:23 +02:00
|
|
|
periode=PERIODE)
|
|
|
|
|
|
|
|
print("hex:", token_hex)
|
|
|
|
print("base32:", token_b32)
|
|
|
|
print("uri:", uri)
|
|
|
|
qr = qrcode.QRCode()
|
|
|
|
qr.add_data(uri)
|
|
|
|
qr.print_ascii(tty=True)
|
|
|
|
|