Files
linux-cloud-router/bin/otp.py
T

77 lines
3.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""An authenticator app on the command line: make a TOTP secret or print its current code: otp.py new|code.
The secret, base32, is kept in the file --secret-file or OTP_FILE names, readable by its owner
only. new makes a new secret of 20 random bytes in that file, refusing to replace one without
--force, and prints its otpauth URI, labelled with --account and --issuer when given. code prints
the code of the secret now, or at the Unix time --at. The codes are RFC 6238's, with --algorithm
(sha1 by default), --digits (6) and --period (30 seconds).
"""
import argparse
import base64
import hashlib
import hmac
import os
import pathlib
import secrets
import struct
import sys
import time
import urllib.parse
ALGORITHMS = ('sha1', 'sha256', 'sha512')
def code_of(secret, now=None, digits=6, period=30, algorithm='sha1'):
"""The TOTP code of the base32 secret at the Unix time now, the current time by default."""
counter = int((time.time() if now is None else now) // period)
key = base64.b32decode(secret.upper() + '=' * (-len(secret) % 8))
digest = hmac.new(key, struct.pack('>Q', counter), getattr(hashlib, algorithm)).digest()
offset = digest[-1] & 0x0F
value = struct.unpack('>I', digest[offset:offset + 4])[0] & 0x7FFFFFFF
return f'{value % 10 ** digits:0{digits}d}'
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('action', choices=('new', 'code'))
parser.add_argument('--secret-file', default=os.environ.get('OTP_FILE'),
help='the file of the base32 secret (OTP_FILE)')
parser.add_argument('--algorithm', choices=ALGORITHMS, default='sha1', help='the HMAC hash (default sha1)')
parser.add_argument('--digits', type=int, default=6, help='the digits of a code (default 6)')
parser.add_argument('--period', type=int, default=30, help='the seconds a code is valid (default 30)')
parser.add_argument('--at', type=float, help='code: the Unix time of the code instead of now')
parser.add_argument('--account', help='new: the account name in the otpauth URI')
parser.add_argument('--issuer', help='new: the issuer in the otpauth URI')
parser.add_argument('--force', action='store_true', help='new: replace an existing secret')
args = parser.parse_args()
if not args.secret_file:
parser.error('--secret-file or OTP_FILE is required')
if not 6 <= args.digits <= 10 or args.period < 1:
parser.error('--digits must be 6 to 10 and --period at least 1')
secret_file = pathlib.Path(args.secret_file)
if args.action == 'code':
if not secret_file.is_file():
sys.exit(f'no {secret_file}; make a secret with new')
print(code_of(secret_file.read_text(encoding='utf-8').strip(), args.at, args.digits, args.period, args.algorithm))
return
if secret_file.exists() and not args.force:
sys.exit(f'{secret_file} exists; give --force to replace its secret')
secret = base64.b32encode(secrets.token_bytes(20)).decode()
secret_file.parent.mkdir(parents=True, exist_ok=True)
secret_file.touch(mode=0o600)
secret_file.chmod(0o600)
secret_file.write_text(f'{secret}\n', encoding='utf-8')
label = urllib.parse.quote(':'.join(part for part in (args.issuer, args.account) if part) or 'otp')
query = {'secret': secret, 'algorithm': args.algorithm.upper(), 'digits': args.digits, 'period': args.period}
if args.issuer:
query['issuer'] = args.issuer
print(f'otpauth://totp/{label}?{urllib.parse.urlencode(query)}')
if __name__ == '__main__':
main()