diff --git a/subiquity/cloudinit.py b/subiquity/cloudinit.py index 9ba3e3cdb..8e800151f 100644 --- a/subiquity/cloudinit.py +++ b/subiquity/cloudinit.py @@ -3,8 +3,8 @@ import asyncio import json import logging -import random import re +import secrets from collections.abc import Awaitable, Sequence from string import ascii_letters, digits from subprocess import CompletedProcess @@ -162,8 +162,8 @@ async def validate_cloud_init_schema() -> None: return None -def rand_str(strlen: int = 32, select_from: Optional[Sequence] = None) -> str: - r: random.SystemRandom = random.SystemRandom() +def rand_password(strlen: int = 32, select_from: Optional[Sequence] = None) -> str: + r: secrets.SystemRandom = secrets.SystemRandom() if not select_from: select_from: str = ascii_letters + digits return "".join([r.choice(select_from) for _x in range(strlen)]) @@ -172,4 +172,4 @@ def rand_str(strlen: int = 32, select_from: Optional[Sequence] = None) -> str: # Generate random user passwords the same way cloud-init does # https://github.com/canonical/cloud-init/blob/6e4153b346bc0d3f3422c01a3f93ecfb28269da2/cloudinit/config/cc_set_passwords.py#L249 # noqa: E501 def rand_user_password(pwlen: int = 20) -> str: - return rand_str(strlen=pwlen, select_from=CLOUD_INIT_PW_SET) + return rand_password(strlen=pwlen, select_from=CLOUD_INIT_PW_SET) diff --git a/subiquity/tests/test_cloudinit.py b/subiquity/tests/test_cloudinit.py index 09e316aa6..d22a3b2a3 100644 --- a/subiquity/tests/test_cloudinit.py +++ b/subiquity/tests/test_cloudinit.py @@ -24,7 +24,7 @@ cloud_init_status_wait, cloud_init_version, get_schema_failure_keys, - rand_str, + rand_password, rand_user_password, read_json_extended_status, read_legacy_status, @@ -238,13 +238,13 @@ def test_passwd_constraints(self): def test_rand_string_generation(self): # random string is 32 characters by default - password = rand_str() + password = rand_password() self.assertEqual(len(password), 32) # password is requested length - password = rand_str(strlen=20) + password = rand_password(strlen=20) self.assertEqual(len(password), 20) # password characters sampled from provided set choices = ["a"] - self.assertEqual("a" * 32, rand_str(select_from=choices)) + self.assertEqual("a" * 32, rand_password(select_from=choices))