From fe1183f8ac0456720abc0c2cc9066c39f9041230 Mon Sep 17 00:00:00 2001 From: Abhijeet Kasurde Date: Thu, 25 Jul 2024 14:31:41 -0700 Subject: [PATCH] Replace random with secrets (#83668) Use secrets library instead of random. Signed-off-by: Abhijeet Kasurde --- changelogs/fragments/secrets.yml | 3 +++ lib/ansible/cli/pull.py | 4 ++-- lib/ansible/executor/powershell/module_manifest.py | 4 ++-- lib/ansible/module_utils/api.py | 4 ++-- lib/ansible/modules/apt.py | 4 ++-- lib/ansible/modules/apt_repository.py | 4 ++-- lib/ansible/plugins/action/__init__.py | 4 ++-- lib/ansible/plugins/action/reboot.py | 4 ++-- lib/ansible/plugins/become/__init__.py | 2 +- lib/ansible/plugins/lookup/random_choice.py | 4 ++-- lib/ansible/plugins/shell/__init__.py | 4 ++-- lib/ansible/utils/display.py | 4 ++-- lib/ansible/utils/vars.py | 4 ++-- 13 files changed, 26 insertions(+), 23 deletions(-) create mode 100644 changelogs/fragments/secrets.yml diff --git a/changelogs/fragments/secrets.yml b/changelogs/fragments/secrets.yml new file mode 100644 index 00000000000..a07b0bb7346 --- /dev/null +++ b/changelogs/fragments/secrets.yml @@ -0,0 +1,3 @@ +--- +minor_changes: + - replace random with secrets library. diff --git a/lib/ansible/cli/pull.py b/lib/ansible/cli/pull.py index fb3321efa9a..eb8436636e2 100755 --- a/lib/ansible/cli/pull.py +++ b/lib/ansible/cli/pull.py @@ -12,7 +12,7 @@ from ansible.cli import CLI import datetime import os import platform -import random +import secrets import shlex import shutil import socket @@ -140,7 +140,7 @@ class PullCLI(CLI): if options.sleep: try: - secs = random.randint(0, int(options.sleep)) + secs = secrets.randbelow(int(options.sleep)) options.sleep = secs except ValueError: raise AnsibleOptionsError("%s is not a number." % options.sleep) diff --git a/lib/ansible/executor/powershell/module_manifest.py b/lib/ansible/executor/powershell/module_manifest.py index 99b18e5ff4b..93c5c8c643e 100644 --- a/lib/ansible/executor/powershell/module_manifest.py +++ b/lib/ansible/executor/powershell/module_manifest.py @@ -8,7 +8,7 @@ import errno import json import os import pkgutil -import random +import secrets import re from importlib import import_module @@ -318,7 +318,7 @@ def _create_powershell_wrapper(b_module_data, module_path, module_args, exec_manifest["actions"].insert(0, 'async_watchdog') exec_manifest["actions"].insert(0, 'async_wrapper') - exec_manifest["async_jid"] = f'j{random.randint(0, 999999999999)}' + exec_manifest["async_jid"] = f'j{secrets.randbelow(999999999999)}' exec_manifest["async_timeout_sec"] = async_timeout exec_manifest["async_startup_timeout"] = C.config.get_config_value("WIN_ASYNC_STARTUP_TIMEOUT", variables=task_vars) diff --git a/lib/ansible/module_utils/api.py b/lib/ansible/module_utils/api.py index 8f08772278e..2415c38a839 100644 --- a/lib/ansible/module_utils/api.py +++ b/lib/ansible/module_utils/api.py @@ -28,7 +28,7 @@ from __future__ import annotations import copy import functools import itertools -import random +import secrets import sys import time @@ -131,7 +131,7 @@ def generate_jittered_backoff(retries=10, delay_base=3, delay_threshold=60): :param delay_threshold: The maximum time in seconds for any delay. """ for retry in range(0, retries): - yield random.randint(0, min(delay_threshold, delay_base * 2 ** retry)) + yield secrets.randbelow(min(delay_threshold, delay_base * 2 ** retry)) def retry_never(exception_or_result): diff --git a/lib/ansible/modules/apt.py b/lib/ansible/modules/apt.py index 59e91949751..423ff2c57d4 100644 --- a/lib/ansible/modules/apt.py +++ b/lib/ansible/modules/apt.py @@ -365,8 +365,8 @@ import datetime import fnmatch import locale as locale_module import os -import random import re +import secrets import shutil import sys import tempfile @@ -1387,7 +1387,7 @@ def main(): err = '' update_cache_retries = module.params.get('update_cache_retries') update_cache_retry_max_delay = module.params.get('update_cache_retry_max_delay') - randomize = random.randint(0, 1000) / 1000.0 + randomize = secrets.randbelow(1000) / 1000.0 for retry in range(update_cache_retries): try: diff --git a/lib/ansible/modules/apt_repository.py b/lib/ansible/modules/apt_repository.py index 774f57378f2..28d948a666d 100644 --- a/lib/ansible/modules/apt_repository.py +++ b/lib/ansible/modules/apt_repository.py @@ -174,9 +174,9 @@ import glob import json import os import re +import secrets import sys import tempfile -import random import time from ansible.module_utils.basic import AnsibleModule @@ -743,7 +743,7 @@ def main(): if update_cache: update_cache_retries = module.params.get('update_cache_retries') update_cache_retry_max_delay = module.params.get('update_cache_retry_max_delay') - randomize = random.randint(0, 1000) / 1000.0 + randomize = secrets.randbelow(1000) / 1000.0 cache = apt.Cache() for retry in range(update_cache_retries): diff --git a/lib/ansible/plugins/action/__init__.py b/lib/ansible/plugins/action/__init__.py index 7ebfd13e4c7..4177d6bad6f 100644 --- a/lib/ansible/plugins/action/__init__.py +++ b/lib/ansible/plugins/action/__init__.py @@ -8,8 +8,8 @@ from __future__ import annotations import base64 import json import os -import random import re +import secrets import shlex import stat import tempfile @@ -1114,7 +1114,7 @@ class ActionBase(ABC): remote_files.append(remote_async_module_path) async_limit = self._task.async_val - async_jid = f'j{random.randint(0, 999999999999)}' + async_jid = f'j{secrets.randbelow(999999999999)}' # call the interpreter for async_wrapper directly # this permits use of a script for an interpreter on non-Linux platforms diff --git a/lib/ansible/plugins/action/reboot.py b/lib/ansible/plugins/action/reboot.py index 3245716aa15..38d02535878 100644 --- a/lib/ansible/plugins/action/reboot.py +++ b/lib/ansible/plugins/action/reboot.py @@ -4,7 +4,7 @@ from __future__ import annotations -import random +import secrets import time from datetime import datetime, timedelta, timezone @@ -304,7 +304,7 @@ class ActionModule(ActionBase): except AnsibleConnectionFailure: pass # Use exponential backoff with a max timeout, plus a little bit of randomness - random_int = random.randint(0, 1000) / 1000 + random_int = secrets.randbelow(1000) / 1000 fail_sleep = 2 ** fail_count + random_int if fail_sleep > max_fail_sleep: diff --git a/lib/ansible/plugins/become/__init__.py b/lib/ansible/plugins/become/__init__.py index 0ac15123f8c..beb45b70e47 100644 --- a/lib/ansible/plugins/become/__init__.py +++ b/lib/ansible/plugins/become/__init__.py @@ -6,7 +6,7 @@ from __future__ import annotations import shlex from abc import abstractmethod -from random import choice +from secrets import choice from string import ascii_lowercase from gettext import dgettext diff --git a/lib/ansible/plugins/lookup/random_choice.py b/lib/ansible/plugins/lookup/random_choice.py index 2e43d2e4afa..6c0185bc959 100644 --- a/lib/ansible/plugins/lookup/random_choice.py +++ b/lib/ansible/plugins/lookup/random_choice.py @@ -31,7 +31,7 @@ RETURN = """ - random item type: raw """ -import random +import secrets from ansible.errors import AnsibleError from ansible.module_utils.common.text.converters import to_native @@ -45,7 +45,7 @@ class LookupModule(LookupBase): ret = terms if terms: try: - ret = [random.choice(terms)] + ret = [secrets.choice(terms)] except Exception as e: raise AnsibleError("Unable to choose random term: %s" % to_native(e)) diff --git a/lib/ansible/plugins/shell/__init__.py b/lib/ansible/plugins/shell/__init__.py index f96d9dbdffd..0a806573d0a 100644 --- a/lib/ansible/plugins/shell/__init__.py +++ b/lib/ansible/plugins/shell/__init__.py @@ -18,8 +18,8 @@ from __future__ import annotations import os import os.path -import random import re +import secrets import shlex import time @@ -82,7 +82,7 @@ class ShellBase(AnsiblePlugin): @staticmethod def _generate_temp_dir_name(): - return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), random.randint(0, 2**48)) + return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), secrets.randbelow(2**48)) def env_prefix(self, **kwargs): return ' '.join(['%s=%s' % (k, self.quote(text_type(v))) for k, v in kwargs.items()]) diff --git a/lib/ansible/utils/display.py b/lib/ansible/utils/display.py index 7ade08070b1..13ac9b095e7 100644 --- a/lib/ansible/utils/display.py +++ b/lib/ansible/utils/display.py @@ -33,7 +33,7 @@ import getpass import io import logging import os -import random +import secrets import subprocess import sys import termios @@ -636,7 +636,7 @@ class Display(metaclass=Singleton): if self.noncow: thecow = self.noncow if thecow == 'random': - thecow = random.choice(list(self.cows_available)) + thecow = secrets.choice(list(self.cows_available)) runcmd.append(b'-f') runcmd.append(to_bytes(thecow)) runcmd.append(to_bytes(msg)) diff --git a/lib/ansible/utils/vars.py b/lib/ansible/utils/vars.py index 373fc706a03..9e0510a766b 100644 --- a/lib/ansible/utils/vars.py +++ b/lib/ansible/utils/vars.py @@ -18,7 +18,7 @@ from __future__ import annotations import keyword -import random +import secrets import uuid from collections.abc import MutableMapping, MutableSequence @@ -37,7 +37,7 @@ ADDITIONAL_PY2_KEYWORDS = frozenset(("True", "False", "None")) _MAXSIZE = 2 ** 32 cur_id = 0 node_mac = ("%012x" % uuid.getnode())[:12] -random_int = ("%08x" % random.randint(0, _MAXSIZE))[:8] +random_int = ("%08x" % secrets.randbelow(_MAXSIZE))[:8] def get_unique_id():