"""Create a local gateway password record; never store a default password.""" import argparse import getpass import hashlib import json import os from pathlib import Path import secrets def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--auth-file', type=Path, default=Path('.runtime-data/company-auth.json')) args = parser.parse_args() if args.auth_file.exists(): parser.error('Auth file already exists; choose a new file for rotation.') password = getpass.getpass('New company password: ') if not password or password != getpass.getpass('Confirm password: '): parser.error('Passwords must be nonempty and match.') salt = secrets.token_bytes(32) iterations = 260000 record = {'salt': salt.hex(), 'iterations': iterations, 'hash': hashlib.pbkdf2_hmac('sha256', password.encode(), salt, iterations).hex()} args.auth_file.parent.mkdir(parents=True, exist_ok=True) fd = os.open(args.auth_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, 'w', encoding='utf-8') as stream: json.dump(record, stream) stream.write('\n') print('Local authentication record created. Restart the gateway to apply.') if __name__ == '__main__': main()