Skip to content

Commit

Permalink
cloud-init: change rand_user_password to secrets
Browse files Browse the repository at this point in the history
The "secrets" submodule is more secure than "random". See [1].

[1] https://docs.python.org/3/library/secrets.html
  • Loading branch information
Chris-Peterson444 committed Jul 25, 2024
1 parent 047a0b1 commit d91c554
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
8 changes: 4 additions & 4 deletions subiquity/cloudinit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)])
Expand All @@ -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)
8 changes: 4 additions & 4 deletions subiquity/tests/test_cloudinit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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))

0 comments on commit d91c554

Please sign in to comment.