diff --git a/hsm_secrets/piv/__init__.py b/hsm_secrets/piv/__init__.py index c9541de..fcfdf88 100644 --- a/hsm_secrets/piv/__init__.py +++ b/hsm_secrets/piv/__init__.py @@ -1,8 +1,7 @@ -import os -import random import re from typing_extensions import Literal import click +import secrets from pathlib import Path from typing import cast, get_args @@ -258,10 +257,9 @@ def yubikey_gen_user_cert(ctx: HsmSecretsCtx, user: str, slot: str, no_reset: bo with YubikeyPivManagementSession(mgt_key_bytes, pin) as ses: import_to_yubikey_piv(ses.piv, signed_cert, None, slot_enum) if not no_reset: - random.seed(os.urandom(16)) - new_pin = str(random.randint(100000, 999999)) - new_puk = str(random.randint(10000000, 99999999)) - new_mgt_key = os.urandom(24) + new_pin = str(secrets.randbelow(900000) + 100000) + new_puk = str(secrets.randbelow(90000000) + 10000000) + new_mgt_key = secrets.token_bytes(24) cli_info('') set_yubikey_piv_pin_puk_management_key(ses.piv, new_pin, new_puk, 5, new_mgt_key) cli_code_info(f"- New PIN: `{new_pin}` (give this to the user)") diff --git a/hsm_secrets/user/__init__.py b/hsm_secrets/user/__init__.py index e693cca..38e95c6 100644 --- a/hsm_secrets/user/__init__.py +++ b/hsm_secrets/user/__init__.py @@ -162,16 +162,20 @@ def add_service(ctx: HsmSecretsCtx, obj_ids: tuple[str], all_accts: bool, askpw: raise click.ClickException(f"Service user ID(s) {', '.join(unknown_ids)} not found in the configuration file.") for ad in acct_defs: + rnd: bytes|None = None with open_hsm_session(ctx, HSMAuthMethod.DEFAULT_ADMIN) as ses: if not confirm_and_delete_old_yubihsm_object_if_exists(ses, ad.id, yubihsm.defs.OBJECT.AUTHENTICATION_KEY, abort=False): cli_warn(f"Skipping service user '{ad.label}' (ID: 0x{ad.id:04x})...") continue + else: + if not askpw: + rnd = ses.get_pseudo_random(16) cli_info(f"Adding service user '{ad.label}' (ID: 0x{ad.id:04x}) to device {ctx.hsm_serial}...") if askpw: pw = prompt_for_secret(f"Enter password for service user '{ad.label}'", confirm=True) else: - rnd = secrets.token_bytes(16) + assert rnd pw = group_by_4(rnd.hex()).replace(' ', '-') retries = 0 while True: