Debian Codegraph @

ansible_collections/community/general/plugins/lookup/random_string.py

raw
1 # Copyright (c) 2021, Abhijeet Kasurde <[email protected]>
2 # Copyright (c) 2018, Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 name: random_string
10 author:
11 - Abhijeet Kasurde (@Akasurde)
12 short_description: Generates random string
13 version_added: '3.2.0'
14 description:
15 - Generates random string based upon the given constraints.
16 - Uses L(secrets.SystemRandom,https://docs.python.org/3/library/secrets.html#secrets.SystemRandom), so should be strong enough
17 for cryptographic purposes.
18 options:
19 length:
20 description: The length of the string.
21 default: 8
22 type: int
23 upper:
24 description:
25 - Possibly include uppercase letters in the string.
26 - To ensure atleast one uppercase letter, set O(min_upper) to V(1).
27 default: true
28 type: bool
29 lower:
30 description:
31 - Possibly include lowercase letters in the string.
32 - To ensure atleast one lowercase letter, set O(min_lower) to V(1).
33 default: true
34 type: bool
35 numbers:
36 description:
37 - Possibly include numbers in the string.
38 - To ensure atleast one numeric character, set O(min_numeric) to V(1).
39 default: true
40 type: bool
41 special:
42 description:
43 - Possibly include special characters in the string.
44 - Special characters are taken from Python standard library C(string). See L(the documentation of
45 string.punctuation,https://docs.python.org/3/library/string.html#string.punctuation)
46 for which characters are used.
47 - The choice of special characters can be changed to setting O(override_special).
48 - To ensure atleast one special character, set O(min_special) to V(1).
49 default: true
50 type: bool
51 min_numeric:
52 description:
53 - Minimum number of numeric characters in the string.
54 - If set, overrides O(numbers=false).
55 default: 0
56 type: int
57 min_upper:
58 description:
59 - Minimum number of uppercase alphabets in the string.
60 - If set, overrides O(upper=false).
61 default: 0
62 type: int
63 min_lower:
64 description:
65 - Minimum number of lowercase alphabets in the string.
66 - If set, overrides O(lower=false).
67 default: 0
68 type: int
69 min_special:
70 description:
71 - Minimum number of special character in the string.
72 default: 0
73 type: int
74 override_special:
75 description:
76 - Override a list of special characters to use in the string.
77 - If set O(min_special) should be set to a non-default value.
78 type: str
79 override_all:
80 description:
81 - Override all values of O(numbers), O(upper), O(lower), and O(special) with the given list of characters.
82 type: str
83 ignore_similar_chars:
84 description:
85 - Ignore similar characters, such as V(l) and V(1), or V(O) and V(0).
86 - These characters can be configured in O(similar_chars).
87 default: false
88 type: bool
89 version_added: 7.5.0
90 similar_chars:
91 description:
92 - Override a list of characters not to be use in the string.
93 default: "il1LoO0"
94 type: str
95 version_added: 7.5.0
96 base64:
97 description:
98 - Returns base64 encoded string.
99 type: bool
100 default: false
101 seed:
102 description:
103 - Seed for random string generator.
104 - B(Note) that this drastically reduces the security of this plugin. First, when O(seed) is provided, a non-cryptographic random number generator is used.
105 Second, if the seed does not contain enough entropy, the generated string is weak.
106 B(Do not use the generated string as a password or a secure token when using this option!)
107 type: str
108 version_added: 11.3.0
109 """
110
111 EXAMPLES = r"""
112 - name: Generate random string
113 ansible.builtin.debug:
114 var: lookup('community.general.random_string')
115 # Example result: 'DeadBeeF'
116
117 - name: Generate random string with seed
118 ansible.builtin.debug:
119 var: lookup('community.general.random_string', seed=12345)
120 # Example result: '6[~(2q5O'
121 # NOTE: Do **not** use this string as a password or a secure token,
122 # unless you know exactly what you are doing!
123 # Specifying seed uses a non-secure random number generator.
124
125 - name: Generate random string with length 12
126 ansible.builtin.debug:
127 var: lookup('community.general.random_string', length=12)
128 # Example result: 'Uan0hUiX5kVG'
129
130 - name: Generate base64 encoded random string
131 ansible.builtin.debug:
132 var: lookup('community.general.random_string', base64=True)
133 # Example result: 'NHZ6eWN5Qk0='
134
135 - name: Generate a random string with 1 lower, 1 upper, 1 number and 1 special char (at least)
136 ansible.builtin.debug:
137 var: lookup('community.general.random_string', min_lower=1, min_upper=1, min_special=1, min_numeric=1)
138 # Example result: '&Qw2|E[-'
139
140 - name: Generate a random string with all lower case characters
141 ansible.builtin.debug:
142 var: query('community.general.random_string', upper=false, numbers=false, special=false)
143 # Example result: ['exolxzyz']
144
145 - name: Generate random hexadecimal string
146 ansible.builtin.debug:
147 var: query('community.general.random_string', upper=false, lower=false, override_special=hex_chars, numbers=false)
148 vars:
149 hex_chars: '0123456789ABCDEF'
150 # Example result: ['D2A40737']
151
152 - name: Generate random hexadecimal string with override_all
153 ansible.builtin.debug:
154 var: query('community.general.random_string', override_all=hex_chars)
155 vars:
156 hex_chars: '0123456789ABCDEF'
157 # Example result: ['D2A40737']
158 """
159
160 RETURN = r"""
161 _raw:
162 description: A one-element list containing a random string.
163 type: list
164 elements: str
165 """
166
167 import base64
168 import random
169 import secrets
170 import string
171
172 from ansible.errors import AnsibleLookupError
173 from ansible.module_utils.common.text.converters import to_bytes, to_text
174 from ansible.plugins.lookup import LookupBase
175
176 from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_no_terms
177
178
179 class LookupModule(LookupBase):
180 @staticmethod
181 def get_random(random_generator, chars, length):
182 if not chars:
183 raise AnsibleLookupError("Available characters cannot be None, please change constraints")
184 return "".join(random_generator.choice(chars) for dummy in range(length))
185
186 @staticmethod
187 def b64encode(string_value, encoding="utf-8"):
188 return to_text(base64.b64encode(to_bytes(string_value, encoding=encoding, errors="surrogate_or_strict")))
189
190 def run(self, terms, variables=None, **kwargs):
191 number_chars = string.digits
192 lower_chars = string.ascii_lowercase
193 upper_chars = string.ascii_uppercase
194 special_chars = string.punctuation
195
196 self.set_options(var_options=variables, direct=kwargs)
197 check_for_no_terms(self, terms=terms, direct=kwargs)
198
199 length = self.get_option("length")
200 base64_flag = self.get_option("base64")
201 override_all = self.get_option("override_all")
202 ignore_similar_chars = self.get_option("ignore_similar_chars")
203 similar_chars = self.get_option("similar_chars")
204 seed = self.get_option("seed")
205
206 if seed is None:
207 random_generator = secrets.SystemRandom()
208 else:
209 random_generator = random.Random(seed)
210
211 values = ""
212 available_chars_set = ""
213
214 if ignore_similar_chars:
215 number_chars = "".join([sc for sc in number_chars if sc not in similar_chars])
216 lower_chars = "".join([sc for sc in lower_chars if sc not in similar_chars])
217 upper_chars = "".join([sc for sc in upper_chars if sc not in similar_chars])
218 special_chars = "".join([sc for sc in special_chars if sc not in similar_chars])
219
220 if override_all:
221 # Override all the values
222 available_chars_set = override_all
223 else:
224 upper = self.get_option("upper")
225 lower = self.get_option("lower")
226 numbers = self.get_option("numbers")
227 special = self.get_option("special")
228 override_special = self.get_option("override_special")
229
230 if override_special:
231 special_chars = override_special
232
233 if upper:
234 available_chars_set += upper_chars
235 if lower:
236 available_chars_set += lower_chars
237 if numbers:
238 available_chars_set += number_chars
239 if special:
240 available_chars_set += special_chars
241
242 mapping = {
243 "min_numeric": number_chars,
244 "min_lower": lower_chars,
245 "min_upper": upper_chars,
246 "min_special": special_chars,
247 }
248
249 for m in mapping:
250 if self.get_option(m):
251 values += self.get_random(random_generator, mapping[m], self.get_option(m))
252
253 remaining_pass_len = length - len(values)
254 values += self.get_random(random_generator, available_chars_set, remaining_pass_len)
255
256 shuffled_values = list(values)
257 if seed is None:
258 # Get pseudo randomization
259 # Randomize the order
260 random.shuffle(shuffled_values)
261
262 if base64_flag:
263 return [self.b64encode("".join(shuffled_values))]
264
265 return ["".join(shuffled_values)]