Debian Codegraph @

lib/ansible/plugins/lookup/password.py

raw
1 # (c) 2012, Daniel Hokka Zakrisson <[email protected]>
2 # (c) 2013, Javier Candeira <[email protected]>
3 # (c) 2013, Maykel Moya <[email protected]>
4 # (c) 2017 Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6 from __future__ import annotations
7
8 DOCUMENTATION = """
9 name: password
10 version_added: "1.1"
11 author:
12 - Daniel Hokka Zakrisson (!UNKNOWN) <[email protected]>
13 - Javier Candeira (!UNKNOWN) <[email protected]>
14 - Maykel Moya (!UNKNOWN) <[email protected]>
15 short_description: retrieve or generate a random password, stored in a file
16 description:
17 - Generates a random plaintext password and stores it in a file at a given filepath.
18 - If the file exists previously, it will retrieve its contents, behaving just like with_file.
19 - 'Usage of variables like C("{{ inventory_hostname }}") in the filepath can be used to set up random passwords per host,
20 which simplifies password management in C("host_vars") variables.'
21 - A special case is using /dev/null as a path. The password lookup will generate a new random password each time,
22 but will not write it to /dev/null. This can be used when you need a password without storing it on the controller.
23 positional: _terms
24 options:
25 _terms:
26 description:
27 - path to the file that stores/will store the passwords
28 required: True
29 encrypt:
30 description:
31 - Which hash scheme to encrypt the returning password, should be one hash scheme from C(passlib.hash);
32 V(md5_crypt), V(bcrypt), V(sha256_crypt), V(sha512_crypt).
33 - If not provided, the password will be returned in plain text.
34 - Note that the password is always stored as plain text, only the returning password is encrypted.
35 - Encrypt also forces saving the salt value for idempotence.
36 - Note that before 2.6 this option was incorrectly labeled as a boolean for a long time.
37 ident:
38 description:
39 - Specify version of Bcrypt algorithm to be used while using O(encrypt) as V(bcrypt).
40 - The parameter is only available for V(bcrypt) - U(https://passlib.readthedocs.io/en/stable/lib/passlib.hash.bcrypt.html#passlib.hash.bcrypt).
41 - Other hash types will simply ignore this parameter.
42 - 'Valid values for this parameter are: V(2), V(2a), V(2y), V(2b).'
43 type: string
44 version_added: "2.12"
45 chars:
46 version_added: "1.4"
47 description:
48 - A list of names that compose a custom character set in the generated passwords.
49 - This parameter defines the possible character sets in the resulting password, not the required character sets.
50 If you want to require certain character sets for passwords, you can use the P(community.general.random_string#lookup) lookup plugin.
51 - 'By default generated passwords contain a random mix of upper and lowercase ASCII letters, the numbers 0-9, and punctuation (". , : - _").'
52 - "They can be either parts of Python's string module attributes or represented literally ( :, -)."
53 - "Though string modules can vary by Python version, valid values for both major releases include:
54 'ascii_lowercase', 'ascii_uppercase', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation' and 'whitespace'."
55 - Be aware that Python's 'hexdigits' includes lower and upper case versions of a-f, so it is not a good choice as it doubles
56 the chances of those values for systems that won't distinguish case, distorting the expected entropy.
57 - "when using a comma separated string, to enter comma use two commas ',,' somewhere - preferably at the end.
58 Quotes and double quotes are not supported."
59 type: list
60 elements: str
61 default: ['ascii_letters', 'digits', ".,:-_"]
62 length:
63 description: The length of the generated password.
64 default: 20
65 type: integer
66 seed:
67 version_added: "2.12"
68 description:
69 - A seed to initialize the random number generator.
70 - Identical seeds will yield identical passwords.
71 - B(Note) that a weak seed, one without enough entropy, will not create a sufficiently secure encryption for the password.
72 type: str
73 notes:
74 - A great alternative to the password lookup plugin,
75 if you don't need to generate random passwords on a per-host basis,
76 would be to use Vault in playbooks.
77 Read the documentation there and consider using it first,
78 it will be more desirable for most applications.
79 - If the file already exists, no data will be written to it.
80 If the file has contents, those contents will be read in as the password.
81 Empty files cause the password to return as an empty string.
82 - 'As all lookups, this runs on the Ansible host as the user running the playbook, and "become" does not apply,
83 the target file must be readable by the playbook user, or, if it does not exist,
84 the playbook user must have sufficient privileges to create it.
85 (So, for example, attempts to write into areas such as /etc will fail unless the entire playbook is being run as root).'
86 """
87
88 EXAMPLES = """
89 - name: create a mysql user with a random password
90 community.mysql.mysql_user:
91 name: "{{ client }}"
92 password: "{{ lookup('ansible.builtin.password', 'credentials/' + client + '/' + tier + '/' + role + '/mysqlpassword', length=15) }}"
93 priv: "{{ client }}_{{ tier }}_{{ role }}.*:ALL"
94
95 - name: create a mysql user with a random password using only ascii letters
96 community.mysql.mysql_user:
97 name: "{{ client }}"
98 password: "{{ lookup('ansible.builtin.password', '/tmp/passwordfile', chars=['ascii_letters']) }}"
99 priv: '{{ client }}_{{ tier }}_{{ role }}.*:ALL'
100
101 - name: create a mysql user with an 8 character random password using only digits
102 community.mysql.mysql_user:
103 name: "{{ client }}"
104 password: "{{ lookup('ansible.builtin.password', '/tmp/passwordfile', length=8, chars=['digits']) }}"
105 priv: "{{ client }}_{{ tier }}_{{ role }}.*:ALL"
106
107 - name: create a mysql user with a random password using many different char sets
108 community.mysql.mysql_user:
109 name: "{{ client }}"
110 password: "{{ lookup('ansible.builtin.password', '/tmp/passwordfile', chars=['ascii_letters', 'digits', 'punctuation']) }}"
111 priv: "{{ client }}_{{ tier }}_{{ role }}.*:ALL"
112
113 - name: create lowercase 8 character name for Kubernetes pod name
114 ansible.builtin.set_fact:
115 random_pod_name: "web-{{ lookup('ansible.builtin.password', '/dev/null', chars=['ascii_lowercase', 'digits'], length=8) }}"
116
117 - name: create idempotent password for use in testing/CI, not recommended for production
118 ansible.builtin.set_fact:
119 password: "{{ lookup('ansible.builtin.password', '/dev/null', seed=inventory_hostname) }}"
120 """
121
122 RETURN = """
123 _raw:
124 description:
125 - a password
126 type: list
127 elements: str
128 """
129
130 import contextlib
131 import os
132 import string
133 import time
134 import hashlib
135
136 from ansible.errors import AnsibleError, AnsibleAssertionError
137 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
138 from ansible.module_utils.secrets import register_secret
139 from ansible.parsing.splitter import parse_kv
140 from ansible.plugins.lookup import LookupBase
141 from ansible.utils.encrypt import BaseHash, do_encrypt, random_password, random_salt
142 from ansible.utils.path import makedirs_safe
143
144
145 VALID_PARAMS = frozenset(('length', 'encrypt', 'chars', 'ident', 'seed'))
146
147
148 def _read_password_file(b_path):
149 """Read the contents of a password file and return it
150 :arg b_path: A byte string containing the path to the password file
151 :returns: a text string containing the contents of the password file or
152 None if no password file was present.
153 """
154 content = None
155
156 if os.path.exists(b_path):
157 with open(b_path, 'rb') as f:
158 b_content = f.read().rstrip()
159 content = to_text(b_content, errors='surrogate_or_strict')
160
161 return content
162
163
164 def _gen_candidate_chars(characters):
165 """Generate a string containing all valid chars as defined by ``characters``
166
167 :arg characters: A list of character specs. The character specs are
168 shorthand names for sets of characters like 'digits', 'ascii_letters',
169 or 'punctuation' or a string to be included verbatim.
170
171 The values of each char spec can be:
172
173 * a name of an attribute in the 'strings' module ('digits' for example).
174 The value of the attribute will be added to the candidate chars.
175 * a string of characters. If the string isn't an attribute in 'string'
176 module, the string will be directly added to the candidate chars.
177
178 For example::
179
180 characters=['digits', '?|']``
181
182 will match ``string.digits`` and add all ascii digits. ``'?|'`` will add
183 the question mark and pipe characters directly. Return will be the string::
184
185 u'0123456789?|'
186 """
187 chars = []
188 for chars_spec in characters:
189 # getattr from string expands things like "ascii_letters" and "digits"
190 # into a set of characters.
191 chars.append(to_text(getattr(string, to_native(chars_spec), chars_spec), errors='strict'))
192 chars = u''.join(chars).replace(u'"', u'').replace(u"'", u'')
193 return chars
194
195
196 def _parse_content(content):
197 """parse our password data format into password and salt
198
199 :arg content: The data read from the file
200 :returns: password and salt
201 """
202 password = content
203 salt = None
204 ident = None
205
206 salt_slug = u' salt='
207 ident_slug = u' ident='
208 rem = u''
209 try:
210 sep = content.rindex(salt_slug)
211 except ValueError:
212 # No salt
213 pass
214 else:
215 rem = content[sep + len(salt_slug):]
216 password = content[:sep]
217
218 if rem:
219 try:
220 sep = rem.rindex(ident_slug)
221 except ValueError:
222 # no ident
223 salt = rem
224 else:
225 ident = rem[sep + len(ident_slug):]
226 salt = rem[:sep]
227
228 return password, salt, ident
229
230
231 def _format_content(password, salt, encrypt=None, ident=None):
232 """Format the password and salt for saving
233 :arg password: the plaintext password to save
234 :arg salt: the salt to use when encrypting a password
235 :arg encrypt: Which method the user requests that this password is encrypted.
236 Note that the password is saved in clear. Encrypt just tells us if we
237 must save the salt value for idempotence. Defaults to None.
238 :arg ident: Which version of BCrypt algorithm to be used.
239 Valid only if value of encrypt is bcrypt.
240 Defaults to None.
241 :returns: a text string containing the formatted information
242
243 .. warning:: Passwords are saved in clear. This is because the playbooks
244 expect to get cleartext passwords from this lookup.
245 """
246 if not encrypt and not salt:
247 return password
248
249 # At this point, the calling code should have assured us that there is a salt value.
250 if not salt:
251 raise AnsibleAssertionError('_format_content was called with encryption requested but no salt value')
252
253 if ident:
254 return u'%s salt=%s ident=%s' % (password, salt, ident)
255 return u'%s salt=%s' % (password, salt)
256
257
258 def _write_password_file(b_path, content):
259 b_pathdir = os.path.dirname(b_path)
260 makedirs_safe(b_pathdir, mode=0o700)
261
262 with open(b_path, 'wb') as f:
263 os.chmod(b_path, 0o600)
264 b_content = to_bytes(content, errors='surrogate_or_strict') + b'\n'
265 f.write(b_content)
266
267
268 def _get_lock(b_path):
269 """Get the lock for writing password file."""
270 first_process = False
271 b_pathdir = os.path.dirname(b_path)
272 lockfile_name = to_bytes("%s.ansible_lockfile" % hashlib.sha1(b_path).hexdigest())
273 lockfile = os.path.join(b_pathdir, lockfile_name)
274 if b_path != b'/dev/null':
275 makedirs_safe(b_pathdir, mode=0o700)
276 with contextlib.suppress(FileExistsError):
277 fd = os.open(lockfile, os.O_CREAT | os.O_EXCL)
278 os.close(fd)
279 first_process = True
280
281 counter = 0
282 # if the lock is got by other process, wait until it's released
283 while os.path.exists(lockfile) and not first_process:
284 time.sleep(2 ** counter)
285 if counter >= 2:
286 raise AnsibleError("Password lookup cannot get the lock in 7 seconds, abort..."
287 "This may caused by un-removed lockfile"
288 "you can manually remove it from controller machine at %s and try again" % lockfile)
289 counter += 1
290 return first_process, lockfile
291
292
293 def _release_lock(lockfile):
294 """Release the lock so other processes can read the password file."""
295 if os.path.exists(lockfile):
296 os.remove(lockfile)
297
298
299 class LookupModule(LookupBase):
300
301 def _parse_parameters(self, term):
302 """Hacky parsing of params
303
304 See https://github.com/ansible/ansible-modules-core/issues/1968#issuecomment-136842156
305 and the first_found lookup For how we want to fix this later
306 """
307 first_split = term.split(' ', 1)
308 if len(first_split) <= 1:
309 # Only a single argument given, therefore it's a path
310 relpath = term
311 params = dict()
312 else:
313 relpath = first_split[0]
314 params = parse_kv(first_split[1])
315 if '_raw_params' in params:
316 # Spaces in the path?
317 relpath = u' '.join((relpath, params['_raw_params']))
318 del params['_raw_params']
319
320 # Check that we parsed the params correctly
321 if not term.startswith(relpath):
322 # Likely, the user had a non parameter following a parameter.
323 # Reject this as a user typo
324 raise AnsibleError('Unrecognized value after key=value parameters given to password lookup')
325 # No _raw_params means we already found the complete path when
326 # we split it initially
327
328 # Check for invalid parameters. Probably a user typo
329 invalid_params = frozenset(params.keys()).difference(VALID_PARAMS)
330 if invalid_params:
331 raise AnsibleError('Unrecognized parameter(s) given to password lookup: %s' % ', '.join(invalid_params))
332
333 # update options with what we got
334 if params:
335 self.set_options(direct=params)
336
337 # chars still might need more
338 chars = params.get('chars', self.get_option('chars'))
339 if chars and isinstance(chars, str):
340 tmp_chars = []
341 if u',,' in chars:
342 tmp_chars.append(u',')
343 tmp_chars.extend(c for c in chars.replace(u',,', u',').split(u',') if c)
344 self.set_option('chars', tmp_chars)
345
346 # return processed params
347 for field in VALID_PARAMS:
348 params[field] = self.get_option(field)
349
350 return relpath, params
351
352 def run(self, terms, variables=None, **kwargs):
353 ret = []
354
355 for term in terms:
356
357 self.set_options(var_options=variables, direct=kwargs)
358
359 changed = None
360 relpath, params = self._parse_parameters(term)
361 path = self._loader.path_dwim(relpath)
362 b_path = to_bytes(path, errors='surrogate_or_strict')
363 chars = _gen_candidate_chars(params['chars'])
364 ident = None
365 first_process = None
366 lockfile = None
367
368 try:
369 # make sure only one process finishes all the job first
370 first_process, lockfile = _get_lock(b_path)
371
372 content = _read_password_file(b_path)
373
374 if content is None or b_path == to_bytes('/dev/null'):
375 plaintext_password = random_password(params['length'], chars, params['seed'])
376 salt = None
377 changed = True
378 else:
379 plaintext_password, salt, ident = _parse_content(content)
380
381 encrypt = params['encrypt']
382 if encrypt and not salt:
383 changed = True
384 try:
385 salt = random_salt(BaseHash.algorithms[encrypt].salt_size)
386 except KeyError:
387 salt = random_salt()
388
389 if not ident:
390 ident = params['ident']
391 elif params['ident'] and ident != params['ident']:
392 raise AnsibleError('The ident parameter provided (%s) does not match the stored one (%s).' % (ident, params['ident']))
393
394 if encrypt and not ident:
395 try:
396 ident = BaseHash.algorithms[encrypt].implicit_ident
397 except KeyError:
398 ident = None
399 if ident:
400 changed = True
401
402 if changed and b_path != to_bytes('/dev/null'):
403 content = _format_content(plaintext_password, salt, encrypt=encrypt, ident=ident)
404 _write_password_file(b_path, content)
405
406 finally:
407 if first_process:
408 # let other processes continue
409 _release_lock(lockfile)
410
411 register_secret(plaintext_password)
412
413 if encrypt:
414 password = do_encrypt(plaintext_password, encrypt, salt=salt, ident=ident)
415 ret.append(password)
416 else:
417 ret.append(plaintext_password)
418
419 return ret