Debian Codegraph @

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

raw
1 # Copyright (c) 2017, Patrick Deelman <[email protected]>
2 # Copyright (c) 2017 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 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 name: passwordstore
9 author:
10 - Patrick Deelman (!UNKNOWN) <[email protected]>
11 short_description: Manage passwords with passwordstore.org's pass utility
12 description:
13 - Enables Ansible to retrieve, create or update passwords from the passwordstore.org pass utility. It can also retrieve,
14 create or update YAML style keys stored as multilines in the passwordfile.
15 - To avoid problems when accessing multiple secrets at once, add C(auto-expand-secmem) to C(~/.gnupg/gpg-agent.conf). Where
16 this is not possible, consider using O(lock=readwrite) instead.
17 options:
18 _terms:
19 description: Query key.
20 required: true
21 directory:
22 description:
23 - The directory of the password store.
24 - If O(backend=pass), the default is V(~/.password-store) is used.
25 - If O(backend=gopass), then the default is the C(path) field in C(~/.config/gopass/config.yml), falling back to V(~/.local/share/gopass/stores/root)
26 if C(path) is not defined in the gopass config.
27 type: path
28 vars:
29 - name: passwordstore
30 env:
31 - name: PASSWORD_STORE_DIR
32 create:
33 description: Create the password or the subkey if it does not already exist. Takes precedence over O(missing).
34 type: bool
35 default: false
36 overwrite:
37 description: Overwrite the password or the subkey if it does already exist.
38 type: bool
39 default: false
40 umask:
41 description:
42 - Sets the umask for the created V(.gpg) files. The first octed must be greater than 3 (user readable).
43 - Note pass' default value is V('077').
44 type: string
45 env:
46 - name: PASSWORD_STORE_UMASK
47 version_added: 1.3.0
48 returnall:
49 description: Return all the content of the password, not only the first line.
50 type: bool
51 default: false
52 subkey:
53 description:
54 - By default return a specific subkey of the password. When set to V(password), always returns the first line.
55 - With O(overwrite=true), it creates the subkey and returns it.
56 type: str
57 default: password
58 userpass:
59 description: Specify a password to save, instead of a generated one.
60 type: str
61 length:
62 description: The length of the generated password.
63 type: integer
64 default: 16
65 backup:
66 description: Used with O(overwrite=true). Backup the previous password or subkey in a subkey.
67 type: bool
68 default: false
69 nosymbols:
70 description: Use alphanumeric characters.
71 type: bool
72 default: false
73 missing:
74 description:
75 - List of preference about what to do if the password file is missing.
76 - If O(create=true), the value for this option is ignored and assumed to be V(create).
77 - If set to V(error), the lookup fails out if the passname does not exist.
78 - If set to V(create), the passname is created with the provided length O(length) if it does not exist.
79 - If set to V(empty) or V(warn), it returns a V(none) in case the passname does not exist. When using C(lookup) and
80 not C(query), this is translated to an empty string.
81 version_added: 3.1.0
82 type: str
83 default: error
84 choices:
85 - error
86 - warn
87 - empty
88 - create
89 lock:
90 description:
91 - How to synchronize operations.
92 - The default of V(write) only synchronizes write operations.
93 - V(readwrite) synchronizes all operations (including read). This makes sure that gpg-agent is never called in parallel.
94 - V(none) does not do any synchronization.
95 ini:
96 - section: passwordstore_lookup
97 key: lock
98 type: str
99 default: write
100 choices:
101 - readwrite
102 - write
103 - none
104 version_added: 4.5.0
105 locktimeout:
106 description:
107 - Lock timeout applied when O(lock) is not V(none).
108 - Time with a unit suffix, V(s), V(m), V(h) for seconds, minutes, and hours, respectively. For example, V(900s) equals
109 V(15m).
110 - Correlates with C(pinentry-timeout) in C(~/.gnupg/gpg-agent.conf), see C(man gpg-agent) for details.
111 ini:
112 - section: passwordstore_lookup
113 key: locktimeout
114 type: str
115 default: 15m
116 version_added: 4.5.0
117 backend:
118 description:
119 - Specify which backend to use.
120 - Defaults to V(pass), passwordstore.org's original pass utility.
121 - V(gopass) support is incomplete.
122 ini:
123 - section: passwordstore_lookup
124 key: backend
125 vars:
126 - name: passwordstore_backend
127 type: str
128 default: pass
129 choices:
130 - pass
131 - gopass
132 version_added: 5.2.0
133 timestamp:
134 description: Add the password generation information to the end of the file.
135 type: bool
136 default: true
137 version_added: 8.1.0
138 preserve:
139 description: Include the old (edited) password inside the pass file.
140 type: bool
141 default: true
142 version_added: 8.1.0
143 missing_subkey:
144 description:
145 - Preference about what to do if the password subkey is missing.
146 - If set to V(error), the lookup fails out if the subkey does not exist.
147 - If set to V(empty) or V(warn), it returns a V(none) in case the subkey does not exist.
148 version_added: 8.6.0
149 type: str
150 default: empty
151 choices:
152 - error
153 - warn
154 - empty
155 ini:
156 - section: passwordstore_lookup
157 key: missing_subkey
158 notes:
159 - The lookup supports passing all options as lookup parameters since community.general 6.0.0.
160 """
161 EXAMPLES = r"""
162 ansible.cfg: |
163 [passwordstore_lookup]
164 lock=readwrite
165 locktimeout=45s
166 missing_subkey=warn
167
168 tasks.yml: |-
169 ---
170
171 # Debug is used for examples, BAD IDEA to show passwords on screen
172 - name: Basic lookup. Fails if example/test does not exist
173 ansible.builtin.debug:
174 msg: "{{ lookup('community.general.passwordstore', 'example/test')}}"
175
176 - name: Basic lookup. Warns if example/test does not exist and returns empty string
177 ansible.builtin.debug:
178 msg: "{{ lookup('community.general.passwordstore', 'example/test', missing='warn')}}"
179
180 - name: Create pass with random 16 character password. If password exists just give the password
181 ansible.builtin.debug:
182 var: mypassword
183 vars:
184 mypassword: "{{ lookup('community.general.passwordstore', 'example/test', create=true)}}"
185
186 - name: Create pass with random 16 character password. If password exists just give the password
187 ansible.builtin.debug:
188 var: mypassword
189 vars:
190 mypassword: "{{ lookup('community.general.passwordstore', 'example/test', missing='create')}}"
191
192 - name: >-
193 Create a random 16 character password in a subkey. If the password file already exists, just add the subkey in it.
194 If the subkey exists, returns it
195 ansible.builtin.debug:
196 msg: "{{ lookup('community.general.passwordstore', 'example/test', create=true, subkey='foo') }}"
197
198 - name: >-
199 Create a random 16 character password in a subkey. Overwrite if it already exists and backup the old one.
200 ansible.builtin.debug:
201 msg: "{{ lookup('community.general.passwordstore', 'example/test', create=true, subkey='user', overwrite=true, backup=true) }}"
202
203 - name: Prints 'abc' if example/test does not exist, just give the password otherwise
204 ansible.builtin.debug:
205 var: mypassword
206 vars:
207 mypassword: >-
208 {{ lookup('community.general.passwordstore', 'example/test', missing='empty')
209 | default('abc', true) }}
210
211 - name: Different size password
212 ansible.builtin.debug:
213 msg: "{{ lookup('community.general.passwordstore', 'example/test', create=true, length=42)}}"
214
215 - name: >-
216 Create password and overwrite the password if it exists.
217 As a bonus, this module includes the old password inside the pass file
218 ansible.builtin.debug:
219 msg: "{{ lookup('community.general.passwordstore', 'example/test', create=true, overwrite=true)}}"
220
221 - name: Create an alphanumeric password
222 ansible.builtin.debug:
223 msg: "{{ lookup('community.general.passwordstore', 'example/test', create=true, nosymbols=true) }}"
224
225 - name: Return the value for user in the KV pair user, username
226 ansible.builtin.debug:
227 msg: "{{ lookup('community.general.passwordstore', 'example/test', subkey='user')}}"
228
229 - name: Return the entire password file content
230 ansible.builtin.set_fact:
231 passfilecontent: "{{ lookup('community.general.passwordstore', 'example/test', returnall=true)}}"
232 """
233
234 RETURN = r"""
235 _raw:
236 description:
237 - A password.
238 type: list
239 elements: str
240 """
241
242 import os
243 import re
244 import subprocess
245 import time
246 from contextlib import contextmanager
247
248 import yaml
249 from ansible import constants as C
250 from ansible.errors import AnsibleAssertionError, AnsibleError
251 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
252 from ansible.module_utils.parsing.convert_bool import boolean
253 from ansible.plugins.lookup import LookupBase
254 from ansible.utils.display import Display
255 from ansible.utils.encrypt import random_password
256
257 from ansible_collections.community.general.plugins.module_utils._filelock import FileLock
258 from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
259
260 display = Display()
261
262
263 def run_backend_cmd(cmd, *, input=None, env=None):
264 result = subprocess.run(
265 cmd,
266 check=False,
267 capture_output=True,
268 input=to_bytes(input, errors="surrogate_or_strict") if input else None,
269 env=env,
270 )
271 b_out, b_err = result.stdout, result.stderr
272 retcode = result.returncode
273 if retcode == 0 and (
274 b"encryption failed: Unusable public key" in b_out or b"encryption failed: Unusable public key" in b_err
275 ):
276 retcode = 78 # os.EX_CONFIG
277 if retcode != 0:
278 raise subprocess.CalledProcessError(retcode, cmd, to_native(b_out + b_err, errors="surrogate_or_strict"))
279 return b_out
280
281
282 class LookupModule(LookupBase):
283 def __init__(self, loader=None, templar=None, **kwargs):
284 super().__init__(loader, templar, **kwargs)
285 self.realpass = None
286
287 def is_real_pass(self):
288 if self.realpass is None:
289 try:
290 passoutput = to_text(
291 run_backend_cmd([self.pass_cmd, "--version"], env=self.env), errors="surrogate_or_strict"
292 )
293 self.realpass = "pass: the standard unix password manager" in passoutput
294 except subprocess.CalledProcessError as e:
295 raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
296
297 return self.realpass
298
299 def parse_params(self, term):
300 # I went with the "traditional" param followed with space separated KV pairs.
301 # Waiting for final implementation of lookup parameter parsing.
302 # See: https://github.com/ansible/ansible/issues/12255
303 params = term.split()
304 if len(params) > 0:
305 # the first param is the pass-name
306 self.passname = params[0]
307 # next parse the optional parameters in keyvalue pairs
308 try:
309 for param in params[1:]:
310 name, value = param.split("=", 1)
311 if name not in self.paramvals:
312 raise AnsibleAssertionError(f"{name} not in paramvals")
313 self.paramvals[name] = value
314 except (ValueError, AssertionError) as e:
315 raise AnsibleError(e) from e
316 # check and convert values
317 try:
318 for key in ["create", "returnall", "overwrite", "backup", "nosymbols"]:
319 if not isinstance(self.paramvals[key], bool):
320 self.paramvals[key] = boolean(self.paramvals[key])
321 except (ValueError, AssertionError) as e:
322 raise AnsibleError(e) from e
323 if self.paramvals["missing"] not in ["error", "warn", "create", "empty"]:
324 raise AnsibleError(f"{self.paramvals['missing']} is not a valid option for missing")
325 if not isinstance(self.paramvals["length"], int):
326 if self.paramvals["length"].isdigit():
327 self.paramvals["length"] = int(self.paramvals["length"])
328 else:
329 raise AnsibleError(f"{self.paramvals['length']} is not a correct value for length")
330
331 if self.paramvals["create"]:
332 self.paramvals["missing"] = "create"
333
334 # Collect pass environment variables from the plugin's parameters.
335 self.env = os.environ.copy()
336 self.env["LANGUAGE"] = "C" # make sure to get errors in English as required by run_backend_cmd
337
338 if self.backend == "gopass":
339 self.env["GOPASS_NO_REMINDER"] = "YES"
340 elif os.path.isdir(self.paramvals["directory"]):
341 # Set PASSWORD_STORE_DIR
342 self.env["PASSWORD_STORE_DIR"] = self.paramvals["directory"]
343 elif self.is_real_pass():
344 raise AnsibleError(f"Passwordstore directory '{self.paramvals['directory']}' does not exist")
345
346 # Set PASSWORD_STORE_UMASK if umask is set
347 if self.paramvals.get("umask") is not None:
348 if len(self.paramvals["umask"]) != 3:
349 raise AnsibleError("Passwordstore umask must have a length of 3.")
350 elif int(self.paramvals["umask"][0]) > 3:
351 raise AnsibleError("Passwordstore umask not allowed (password not user readable).")
352 else:
353 self.env["PASSWORD_STORE_UMASK"] = self.paramvals["umask"]
354
355 def check_pass(self):
356 try:
357 self.passoutput = to_text(
358 run_backend_cmd([self.pass_cmd, "show"] + [self.passname], env=self.env), errors="surrogate_or_strict"
359 ).splitlines()
360 self.password = self.passoutput[0]
361 self.passdict = {}
362 try:
363 values = yaml.safe_load("\n".join(self.passoutput[1:]))
364 for key, item in values.items():
365 self.passdict[key] = item
366 except (yaml.YAMLError, AttributeError):
367 for line in self.passoutput[1:]:
368 if ":" in line:
369 name, value = line.split(":", 1)
370 self.passdict[name.strip()] = value.strip()
371 if (
372 self.backend == "gopass"
373 or os.path.isfile(os.path.join(self.paramvals["directory"], f"{self.passname}.gpg"))
374 or not self.is_real_pass()
375 ):
376 # When using real pass, only accept password as found if there is a .gpg file for it (might be a tree node otherwise)
377 return True
378 except subprocess.CalledProcessError as e:
379 # 'not in password store' is the expected error if a password wasn't found
380 if "not in the password store" not in e.output:
381 raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
382
383 if self.paramvals["missing"] == "error":
384 raise AnsibleError(f"passwordstore: passname {self.passname} not found and missing=error is set")
385 elif self.paramvals["missing"] == "warn":
386 display.warning(f"passwordstore: passname {self.passname} not found")
387
388 return False
389
390 def get_newpass(self):
391 if self.paramvals["nosymbols"]:
392 chars = C.DEFAULT_PASSWORD_CHARS[:62]
393 else:
394 chars = C.DEFAULT_PASSWORD_CHARS
395
396 if self.paramvals["userpass"]:
397 newpass = self.paramvals["userpass"]
398 else:
399 newpass = random_password(length=self.paramvals["length"], chars=chars)
400 return newpass
401
402 def update_password(self):
403 # generate new password, insert old lines from current result and return new password
404 # if the target is a subkey, only modify the subkey
405 newpass = self.get_newpass()
406 datetime = time.strftime("%d/%m/%Y %H:%M:%S")
407 subkey = self.paramvals["subkey"]
408
409 if subkey != "password":
410 msg_lines = []
411 subkey_exists = False
412 subkey_line = f"{subkey}: {newpass}"
413 oldpass = None
414
415 for line in self.passoutput:
416 if line.startswith(f"{subkey}: "):
417 oldpass = self.passdict[subkey]
418 line = subkey_line
419 subkey_exists = True
420
421 msg_lines.append(line)
422
423 if not subkey_exists:
424 msg_lines.insert(2, subkey_line)
425
426 if self.paramvals["timestamp"] and self.paramvals["backup"] and oldpass and oldpass != newpass:
427 msg_lines.append(f"lookup_pass: old subkey '{subkey}' password was {oldpass} (Updated on {datetime})\n")
428
429 msg = os.linesep.join(msg_lines)
430
431 else:
432 msg = newpass
433
434 if self.paramvals["preserve"] or self.paramvals["timestamp"]:
435 msg += "\n"
436 if self.paramvals["preserve"] and self.passoutput[1:]:
437 msg += "\n".join(self.passoutput[1:])
438 msg += "\n"
439 if self.paramvals["timestamp"] and self.paramvals["backup"]:
440 msg += f"lookup_pass: old password was {self.password} (Updated on {datetime})\n"
441
442 try:
443 run_backend_cmd([self.pass_cmd, "insert", "-f", "-m", self.passname], input=msg, env=self.env)
444 except subprocess.CalledProcessError as e:
445 raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
446 return newpass
447
448 def generate_password(self):
449 # generate new file and insert lookup_pass: Generated by Ansible on {date}
450 # use pwgen to generate the password and insert values with pass -m
451 newpass = self.get_newpass()
452 datetime = time.strftime("%d/%m/%Y %H:%M:%S")
453 subkey = self.paramvals["subkey"]
454
455 if subkey != "password":
456 msg = f"\n\n{subkey}: {newpass}"
457 else:
458 msg = newpass
459
460 if self.paramvals["timestamp"]:
461 msg += f"\nlookup_pass: First generated by ansible on {datetime}\n"
462
463 try:
464 run_backend_cmd([self.pass_cmd, "insert", "-f", "-m", self.passname], input=msg, env=self.env)
465 except subprocess.CalledProcessError as e:
466 raise AnsibleError(f"exit code {e.returncode} while running {e.cmd}. Error output: {e.output}") from e
467
468 return newpass
469
470 def get_passresult(self):
471 if self.paramvals["returnall"]:
472 return os.linesep.join(self.passoutput)
473 if self.paramvals["subkey"] == "password":
474 return self.password
475 else:
476 if self.paramvals["subkey"] in self.passdict:
477 return self.passdict[self.paramvals["subkey"]]
478 else:
479 if self.paramvals["missing_subkey"] == "error":
480 raise AnsibleError(
481 f"passwordstore: subkey {self.paramvals['subkey']} for passname {self.passname} not found and missing_subkey=error is set"
482 )
483
484 if self.paramvals["missing_subkey"] == "warn":
485 display.warning(
486 f"passwordstore: subkey {self.paramvals['subkey']} for passname {self.passname} not found"
487 )
488
489 return None
490
491 @contextmanager
492 def opt_lock(self, type):
493 if self.get_option("lock") == type:
494 tmpdir = os.environ.get("TMPDIR", "/tmp")
495 user = os.environ.get("USER")
496 lockfile = os.path.join(tmpdir, f".{user}.passwordstore.lock")
497 with FileLock().lock_file(lockfile, tmpdir, self.lock_timeout):
498 self.locked = type
499 yield
500 self.locked = None
501 else:
502 yield
503
504 def setup(self, variables):
505 self.backend = self.get_option("backend")
506 self.pass_cmd = self.backend # pass and gopass are commands as well
507 self.locked = None
508 timeout = self.get_option("locktimeout")
509 if not re.match("^[0-9]+[smh]$", timeout):
510 raise AnsibleError(f"{timeout} is not a correct value for locktimeout")
511 unit_to_seconds = {"s": 1, "m": 60, "h": 3600}
512 self.lock_timeout = int(timeout[:-1]) * unit_to_seconds[timeout[-1]]
513
514 directory = self.get_option("directory")
515 if directory is None:
516 if self.backend == "gopass":
517 try:
518 with open(os.path.expanduser("~/.config/gopass/config.yml")) as f:
519 directory = yaml.safe_load(f)["path"]
520 except (FileNotFoundError, KeyError, yaml.YAMLError):
521 directory = os.path.expanduser("~/.local/share/gopass/stores/root")
522 else:
523 directory = os.path.expanduser("~/.password-store")
524
525 self.paramvals = {
526 "subkey": self.get_option("subkey"),
527 "directory": directory,
528 "create": self.get_option("create"),
529 "returnall": self.get_option("returnall"),
530 "overwrite": self.get_option("overwrite"),
531 "nosymbols": self.get_option("nosymbols"),
532 "userpass": self.get_option("userpass") or "",
533 "length": self.get_option("length"),
534 "backup": self.get_option("backup"),
535 "missing": self.get_option("missing"),
536 "umask": self.get_option("umask"),
537 "timestamp": self.get_option("timestamp"),
538 "preserve": self.get_option("preserve"),
539 "missing_subkey": self.get_option("missing_subkey"),
540 }
541
542 def run(self, terms, variables, **kwargs):
543 self.set_options(var_options=variables, direct=kwargs)
544 check_for_wrong_terms(self, direct=kwargs)
545 self.setup(variables)
546 result = []
547
548 for term in terms:
549 self.parse_params(term) # parse the input into paramvals
550 with self.opt_lock("readwrite"):
551 if self.check_pass(): # password file exists
552 if self.paramvals["overwrite"]: # if "overwrite", always update password
553 with self.opt_lock("write"):
554 result.append(self.update_password())
555 elif (
556 self.paramvals["subkey"] != "password"
557 and not self.passdict.get(self.paramvals["subkey"])
558 and self.paramvals["missing"] == "create"
559 ): # target is a subkey, this subkey is not in passdict BUT missing == create
560 with self.opt_lock("write"):
561 result.append(self.update_password())
562 else:
563 result.append(self.get_passresult())
564 else: # password does not exist
565 if self.paramvals["missing"] == "create":
566 with self.opt_lock("write"):
567 if (
568 self.locked == "write" and self.check_pass()
569 ): # lookup password again if under write lock
570 result.append(self.get_passresult())
571 else:
572 result.append(self.generate_password())
573 else:
574 result.append(None)
575
576 return result