96 lines
4.8 KiB
Python
Executable File
96 lines
4.8 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 is kept in the file --secret-file or OTP_FILE names, readable by its owner only, as
|
|
nothing but its base32 secret, or with --url as its otpauth URI, each without a line end, so the
|
|
file is a value Vault's TOTP engine imports as it is (key=@FILE or url=@FILE). 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, from either form of the file. The codes are RFC 6238's, with
|
|
--algorithm (sha1 by default), --digits (6) and --period (30 seconds); a file holding an otpauth
|
|
URI gives those of the URI instead.
|
|
"""
|
|
|
|
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 stored(text, digits, period, algorithm):
|
|
"""The secret, digits, period and algorithm of the file's text: a base32 secret with the given settings, or an
|
|
otpauth URI with its own, the given ones where it has none."""
|
|
if not text.startswith('otpauth://'):
|
|
return text, digits, period, algorithm
|
|
query = {name: values[0] for name, values in urllib.parse.parse_qs(urllib.parse.urlsplit(text).query).items()}
|
|
found = query.get('algorithm', algorithm).lower()
|
|
if found not in ALGORITHMS:
|
|
sys.exit(f'the otpauth URI has the unknown algorithm {found}')
|
|
return query.get('secret', ''), int(query.get('digits', digits)), int(query.get('period', period)), found
|
|
|
|
|
|
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 or its otpauth URI (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('--url', action='store_true', help='new: store the otpauth URI instead of the secret alone')
|
|
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')
|
|
secret, digits, period, algorithm = stored(secret_file.read_text(encoding='utf-8').strip(), args.digits,
|
|
args.period, args.algorithm)
|
|
print(code_of(secret, args.at, digits, period, 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()
|
|
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
|
|
uri = f'otpauth://totp/{label}?{urllib.parse.urlencode(query)}'
|
|
secret_file.parent.mkdir(parents=True, exist_ok=True)
|
|
secret_file.touch(mode=0o600)
|
|
secret_file.chmod(0o600)
|
|
secret_file.write_text(uri if args.url else secret, encoding='utf-8')
|
|
print(uri)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|