Debian Codegraph @

bin/ansible-vault

raw symbols SCIP
1 #!/usr/bin/env python3
2 # (c) 2014, James Tanner <[email protected]>
3 # Copyright: (c) 2018, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # PYTHON_ARGCOMPLETE_OK
6
7 from __future__ import annotations
8
9 # ansible.cli needs to be imported first, to ensure the source bin/* scripts run that code first
10 from ansible.cli import CLI
11
12 import os
13 import sys
14
15 from ansible import constants as C
16 from ansible import context
17 from ansible.cli.arguments import option_helpers as opt_help
18 from ansible.errors import AnsibleOptionsError
19 from ansible.module_utils.common.text.converters import to_text, to_bytes
20 from ansible.parsing.dataloader import DataLoader
21 from ansible.parsing.vault import VaultEditor, VaultLib, match_encrypt_secret
22 from ansible.utils.display import Display
23
24 display = Display()
25
26
27 class VaultCLI(CLI):
28 """ can encrypt any structured data file used by Ansible.
29 This can include *group_vars/* or *host_vars/* inventory variables,
30 variables loaded by *include_vars* or *vars_files*, or variable files
31 passed on the ansible-playbook command line with *-e @file.yml* or *-e @file.json*.
32 Role variables and defaults are also included!
33
34 Because Ansible tasks, handlers, and other objects are data, these can also be encrypted with vault.
35 If you'd like to not expose what variables you are using, you can keep an individual task file entirely encrypted.
36 """
37
38 name = 'ansible-vault'
39
40 FROM_STDIN = "stdin"
41 FROM_ARGS = "the command line args"
42 FROM_PROMPT = "the interactive prompt"
43
44 def __init__(self, args):
45
46 self.b_vault_pass = None
47 self.b_new_vault_pass = None
48 self.encrypt_string_read_stdin = False
49
50 self.encrypt_secret = None
51 self.encrypt_vault_id = None
52 self.new_encrypt_secret = None
53 self.new_encrypt_vault_id = None
54
55 super(VaultCLI, self).__init__(args)
56
57 def init_parser(self):
58 super(VaultCLI, self).init_parser(
59 desc="encryption/decryption utility for Ansible data files",
60 epilog="\nSee '%s <command> --help' for more information on a specific command.\n\n" % os.path.basename(sys.argv[0])
61 )
62
63 common = opt_help.ArgumentParser(add_help=False)
64 opt_help.add_vault_options(common)
65 opt_help.add_verbosity_options(common)
66
67 subparsers = self.parser.add_subparsers(dest='action')
68 subparsers.required = True
69
70 output = opt_help.ArgumentParser(add_help=False)
71 output.add_argument('--output', default=None, dest='output_file',
72 help='output file name for encrypt or decrypt; use - for stdout',
73 type=opt_help.unfrack_path())
74
75 # For encrypting actions, we can also specify which of multiple vault ids should be used for encrypting
76 vault_id = opt_help.ArgumentParser(add_help=False)
77 vault_id.add_argument('--encrypt-vault-id', default=[], dest='encrypt_vault_id',
78 action='store', type=str,
79 help='the vault id used to encrypt (required if more than one vault-id is provided)')
80
81 create_parser = subparsers.add_parser('create', help='Create new vault encrypted file', parents=[vault_id, common])
82 create_parser.set_defaults(func=self.execute_create)
83 create_parser.add_argument('args', help='Filename', metavar='file_name', nargs='*')
84 create_parser.add_argument('--skip-tty-check', default=False, help='allows editor to be opened when no tty attached',
85 dest='skip_tty_check', action='store_true')
86
87 decrypt_parser = subparsers.add_parser('decrypt', help='Decrypt vault encrypted file or string', parents=[output, common])
88 decrypt_parser.set_defaults(func=self.execute_decrypt)
89 decrypt_parser.add_argument('args', help='Filename', metavar='file_name', nargs='*')
90
91 edit_parser = subparsers.add_parser('edit', help='Edit vault encrypted file', parents=[vault_id, common])
92 edit_parser.set_defaults(func=self.execute_edit)
93 edit_parser.add_argument('args', help='Filename', metavar='file_name', nargs='*')
94
95 view_parser = subparsers.add_parser('view', help='View vault encrypted file', parents=[common])
96 view_parser.set_defaults(func=self.execute_view)
97 view_parser.add_argument('args', help='Filename', metavar='file_name', nargs='*')
98
99 encrypt_parser = subparsers.add_parser('encrypt', help='Encrypt YAML file', parents=[common, output, vault_id])
100 encrypt_parser.set_defaults(func=self.execute_encrypt)
101 encrypt_parser.add_argument('args', help='Filename', metavar='file_name', nargs='*')
102
103 enc_str_parser = subparsers.add_parser('encrypt_string', help='Encrypt a string', parents=[common, output, vault_id])
104 enc_str_parser.set_defaults(func=self.execute_encrypt_string)
105 enc_str_parser.add_argument('args', help='String to encrypt', metavar='string_to_encrypt', nargs='*')
106 enc_str_parser.add_argument('-p', '--prompt', dest='encrypt_string_prompt',
107 action='store_true',
108 help="Prompt for the string to encrypt")
109 enc_str_parser.add_argument('--show-input', dest='show_string_input', default=False, action='store_true',
110 help='Do not hide input when prompted for the string to encrypt')
111 enc_str_parser.add_argument('-n', '--name', dest='encrypt_string_names',
112 action='append',
113 help="Specify the variable name")
114 enc_str_parser.add_argument('--stdin-name', dest='encrypt_string_stdin_name',
115 default=None,
116 help="Specify the variable name for stdin")
117
118 rekey_parser = subparsers.add_parser('rekey', help='Re-key a vault encrypted file', parents=[common, vault_id])
119 rekey_parser.set_defaults(func=self.execute_rekey)
120 rekey_new_group = rekey_parser.add_mutually_exclusive_group()
121 rekey_new_group.add_argument('--new-vault-password-file', default=None, dest='new_vault_password_file',
122 help="new vault password file for rekey", type=opt_help.unfrack_path())
123 rekey_new_group.add_argument('--new-vault-id', default=None, dest='new_vault_id', type=str,
124 help='the new vault identity to use for rekey')
125 rekey_parser.add_argument('args', help='Filename', metavar='file_name', nargs='*')
126
127 def post_process_args(self, options):
128 options = super(VaultCLI, self).post_process_args(options)
129
130 display.verbosity = options.verbosity
131
132 if options.vault_ids:
133 for vault_id in options.vault_ids:
134 if u';' in vault_id:
135 raise AnsibleOptionsError("'%s' is not a valid vault id. The character ';' is not allowed in vault ids" % vault_id)
136
137 if getattr(options, 'output_file', None) and len(options.args) > 1:
138 raise AnsibleOptionsError("At most one input file may be used with the --output option")
139
140 if options.action == 'encrypt_string':
141 if '-' in options.args or options.encrypt_string_stdin_name or (not options.args and not options.encrypt_string_prompt):
142 # prompting from stdin and reading from stdin are mutually exclusive, if stdin is still provided, it is ignored
143 self.encrypt_string_read_stdin = True
144
145 if options.encrypt_string_prompt and self.encrypt_string_read_stdin:
146 # should only trigger if prompt + either - or encrypt string stdin name were provided
147 raise AnsibleOptionsError('The --prompt option is not supported if also reading input from stdin')
148
149 return options
150
151 def run(self):
152 super(VaultCLI, self).run()
153 loader = DataLoader()
154
155 # set default restrictive umask
156 old_umask = os.umask(0o077)
157
158 vault_ids = list(context.CLIARGS['vault_ids'])
159
160 # there are 3 types of actions, those that just 'read' (decrypt, view) and only
161 # need to ask for a password once, and those that 'write' (create, encrypt) that
162 # ask for a new password and confirm it, and 'read/write (rekey) that asks for the
163 # old password, then asks for a new one and confirms it.
164
165 default_vault_ids = C.DEFAULT_VAULT_IDENTITY_LIST
166 vault_ids = default_vault_ids + vault_ids
167
168 action = context.CLIARGS['action']
169
170 # TODO: instead of prompting for these before, we could let VaultEditor
171 # call a callback when it needs it.
172 if action in ['decrypt', 'view', 'rekey', 'edit']:
173 vault_secrets = self.setup_vault_secrets(loader, vault_ids=vault_ids,
174 vault_password_files=list(context.CLIARGS['vault_password_files']),
175 ask_vault_pass=context.CLIARGS['ask_vault_pass'])
176 if not vault_secrets:
177 raise AnsibleOptionsError("A vault password is required to use Ansible's Vault")
178
179 if action in ['encrypt', 'encrypt_string', 'create']:
180
181 encrypt_vault_id = None
182 # no --encrypt-vault-id context.CLIARGS['encrypt_vault_id'] for 'edit'
183 if action not in ['edit']:
184 encrypt_vault_id = context.CLIARGS['encrypt_vault_id'] or C.DEFAULT_VAULT_ENCRYPT_IDENTITY
185
186 vault_secrets = None
187 vault_secrets = \
188 self.setup_vault_secrets(loader,
189 vault_ids=vault_ids,
190 vault_password_files=list(context.CLIARGS['vault_password_files']),
191 ask_vault_pass=context.CLIARGS['ask_vault_pass'],
192 create_new_password=True)
193
194 if len(vault_secrets) > 1 and not encrypt_vault_id:
195 raise AnsibleOptionsError("The vault-ids %s are available to encrypt. Specify the vault-id to encrypt with --encrypt-vault-id" %
196 ','.join([x[0] for x in vault_secrets]))
197
198 if not vault_secrets:
199 raise AnsibleOptionsError("A vault password is required to use Ansible's Vault")
200
201 encrypt_secret = match_encrypt_secret(vault_secrets,
202 encrypt_vault_id=encrypt_vault_id)
203
204 # only one secret for encrypt for now, use the first vault_id and use its first secret
205 # TODO: exception if more than one?
206 self.encrypt_vault_id = encrypt_secret[0]
207 self.encrypt_secret = encrypt_secret[1]
208
209 if action in ['rekey']:
210 encrypt_vault_id = context.CLIARGS['encrypt_vault_id'] or C.DEFAULT_VAULT_ENCRYPT_IDENTITY
211 # print('encrypt_vault_id: %s' % encrypt_vault_id)
212 # print('default_encrypt_vault_id: %s' % default_encrypt_vault_id)
213
214 # new_vault_ids should only ever be one item, from
215 # load the default vault ids if we are using encrypt-vault-id
216 new_vault_ids = []
217 if encrypt_vault_id:
218 new_vault_ids = default_vault_ids
219 if context.CLIARGS['new_vault_id']:
220 new_vault_ids.append(context.CLIARGS['new_vault_id'])
221
222 new_vault_password_files = []
223 if context.CLIARGS['new_vault_password_file']:
224 new_vault_password_files.append(context.CLIARGS['new_vault_password_file'])
225
226 new_vault_secrets = \
227 self.setup_vault_secrets(loader,
228 vault_ids=new_vault_ids,
229 vault_password_files=new_vault_password_files,
230 ask_vault_pass=context.CLIARGS['ask_vault_pass'],
231 initialize_context=False,
232 create_new_password=True)
233
234 if not new_vault_secrets:
235 raise AnsibleOptionsError("A new vault password is required to use Ansible's Vault rekey")
236
237 # There is only one new_vault_id currently and one new_vault_secret, or we
238 # use the id specified in --encrypt-vault-id
239 new_encrypt_secret = match_encrypt_secret(new_vault_secrets,
240 encrypt_vault_id=encrypt_vault_id)
241
242 self.new_encrypt_vault_id = new_encrypt_secret[0]
243 self.new_encrypt_secret = new_encrypt_secret[1]
244
245 loader.set_vault_secrets(vault_secrets)
246
247 # FIXME: do we need to create VaultEditor here? its not reused
248 vault = VaultLib(vault_secrets)
249 self.editor = VaultEditor(vault)
250
251 context.CLIARGS['func']()
252
253 # and restore umask
254 os.umask(old_umask)
255
256 def execute_encrypt(self):
257 """ encrypt the supplied file using the provided vault secret """
258
259 if not context.CLIARGS['args'] and sys.stdin.isatty():
260 display.display("Reading plaintext input from stdin", stderr=True)
261
262 for f in context.CLIARGS['args'] or ['-']:
263 # FIXME: use the correct vau
264 self.editor.encrypt_file(f, self.encrypt_secret,
265 vault_id=self.encrypt_vault_id,
266 output_file=context.CLIARGS['output_file'])
267
268 if sys.stdout.isatty():
269 display.display("Encryption successful", stderr=True)
270
271 @staticmethod
272 def format_ciphertext_yaml(b_ciphertext, indent=None, name=None):
273 indent = indent or 10
274
275 block_format_var_name = ""
276 if name:
277 block_format_var_name = "%s: " % name
278
279 block_format_header = "%s!vault |" % block_format_var_name
280 lines = []
281 vault_ciphertext = to_text(b_ciphertext)
282
283 lines.append(block_format_header)
284 for line in vault_ciphertext.splitlines():
285 lines.append('%s%s' % (' ' * indent, line))
286
287 yaml_ciphertext = '\n'.join(lines)
288 return yaml_ciphertext
289
290 def execute_encrypt_string(self):
291 """ encrypt the supplied string using the provided vault secret """
292 b_plaintext = None
293
294 # Holds tuples (the_text, the_source_of_the_string, the variable name if its provided).
295 b_plaintext_list = []
296
297 # remove the non-option '-' arg (used to indicate 'read from stdin') from the candidate args so
298 # we don't add it to the plaintext list
299 args = [x for x in context.CLIARGS['args'] if x != '-']
300
301 # We can prompt and read input, or read from stdin, but not both.
302 if context.CLIARGS['encrypt_string_prompt']:
303 msg = "String to encrypt: "
304
305 name = None
306 name_prompt_response = display.prompt('Variable name (enter for no name): ')
307
308 # TODO: enforce var naming rules?
309 if name_prompt_response != "":
310 name = name_prompt_response
311
312 # TODO: could prompt for which vault_id to use for each plaintext string
313 # currently, it will just be the default
314 hide_input = not context.CLIARGS['show_string_input']
315 if hide_input:
316 msg = "String to encrypt (hidden): "
317 else:
318 msg = "String to encrypt:"
319
320 prompt_response = display.prompt(msg, private=hide_input)
321
322 if prompt_response == '':
323 raise AnsibleOptionsError('The plaintext provided from the prompt was empty, not encrypting')
324
325 b_plaintext = to_bytes(prompt_response)
326 b_plaintext_list.append((b_plaintext, self.FROM_PROMPT, name))
327
328 # read from stdin
329 if self.encrypt_string_read_stdin:
330 if sys.stdout.isatty():
331 display.display("Reading plaintext input from stdin. (ctrl-d to end input, twice if your content does not already have a newline)", stderr=True)
332
333 stdin_text = sys.stdin.read()
334 if stdin_text == '':
335 raise AnsibleOptionsError('stdin was empty, not encrypting')
336
337 if sys.stdout.isatty() and not stdin_text.endswith("\n"):
338 display.display("\n")
339
340 b_plaintext = to_bytes(stdin_text)
341
342 # defaults to None
343 name = context.CLIARGS['encrypt_string_stdin_name']
344 b_plaintext_list.append((b_plaintext, self.FROM_STDIN, name))
345
346 # use any leftover args as strings to encrypt
347 # Try to match args up to --name options
348 if context.CLIARGS.get('encrypt_string_names', False):
349 name_and_text_list = list(zip(context.CLIARGS['encrypt_string_names'], args))
350
351 # Some but not enough --name's to name each var
352 if len(args) > len(name_and_text_list):
353 # Trying to avoid ever showing the plaintext in the output, so this warning is vague to avoid that.
354 display.display('The number of --name options do not match the number of args.',
355 stderr=True)
356 display.display('The last named variable will be "%s". The rest will not have'
357 ' names.' % context.CLIARGS['encrypt_string_names'][-1],
358 stderr=True)
359
360 # Add the rest of the args without specifying a name
361 for extra_arg in args[len(name_and_text_list):]:
362 name_and_text_list.append((None, extra_arg))
363
364 # if no --names are provided, just use the args without a name.
365 else:
366 name_and_text_list = [(None, x) for x in args]
367
368 # Convert the plaintext text objects to bytestrings and collect
369 for name_and_text in name_and_text_list:
370 name, plaintext = name_and_text
371
372 if plaintext == '':
373 raise AnsibleOptionsError('The plaintext provided from the command line args was empty, not encrypting')
374
375 b_plaintext = to_bytes(plaintext)
376 b_plaintext_list.append((b_plaintext, self.FROM_ARGS, name))
377
378 # TODO: specify vault_id per string?
379 # Format the encrypted strings and any corresponding stderr output
380 outputs = self._format_output_vault_strings(b_plaintext_list, vault_id=self.encrypt_vault_id)
381
382 b_outs = []
383 for output in outputs:
384 err = output.get('err', None)
385 out = output.get('out', '')
386 if err:
387 sys.stderr.write(err)
388 b_outs.append(to_bytes(out))
389
390 # The output must end with a newline to play nice with terminal representation.
391 # Refs:
392 # * https://stackoverflow.com/a/729795/595220
393 # * https://github.com/ansible/ansible/issues/78932
394 b_outs.append(b'')
395 self.editor.write_data(b'\n'.join(b_outs), context.CLIARGS['output_file'] or '-')
396
397 if sys.stdout.isatty():
398 display.display("Encryption successful", stderr=True)
399
400 # TODO: offer block or string ala eyaml
401
402 def _format_output_vault_strings(self, b_plaintext_list, vault_id=None):
403 # If we are only showing one item in the output, we don't need to included commented
404 # delimiters in the text
405 show_delimiter = False
406 if len(b_plaintext_list) > 1:
407 show_delimiter = True
408
409 # list of dicts {'out': '', 'err': ''}
410 output = []
411
412 # Encrypt the plaintext, and format it into a yaml block that can be pasted into a playbook.
413 # For more than one input, show some differentiating info in the stderr output so we can tell them
414 # apart. If we have a var name, we include that in the yaml
415 for index, b_plaintext_info in enumerate(b_plaintext_list):
416 # (the text itself, which input it came from, its name)
417 b_plaintext, src, name = b_plaintext_info
418
419 b_ciphertext = self.editor.encrypt_bytes(b_plaintext, self.encrypt_secret, vault_id=vault_id)
420
421 # block formatting
422 yaml_text = self.format_ciphertext_yaml(b_ciphertext, name=name)
423
424 err_msg = None
425 if show_delimiter:
426 human_index = index + 1
427 if name:
428 err_msg = '# The encrypted version of variable ("%s", the string #%d from %s).\n' % (name, human_index, src)
429 else:
430 err_msg = '# The encrypted version of the string #%d from %s.)\n' % (human_index, src)
431 output.append({'out': yaml_text, 'err': err_msg})
432
433 return output
434
435 def execute_decrypt(self):
436 """ decrypt the supplied file using the provided vault secret """
437
438 if not context.CLIARGS['args'] and sys.stdin.isatty():
439 display.display("Reading ciphertext input from stdin", stderr=True)
440
441 for f in context.CLIARGS['args'] or ['-']:
442 self.editor.decrypt_file(f, output_file=context.CLIARGS['output_file'])
443
444 if sys.stdout.isatty():
445 display.display("Decryption successful", stderr=True)
446
447 def execute_create(self):
448 """ create and open a file in an editor that will be encrypted with the provided vault secret when closed"""
449
450 if len(context.CLIARGS['args']) != 1:
451 raise AnsibleOptionsError("ansible-vault create can take only one filename argument")
452
453 if sys.stdout.isatty() or context.CLIARGS['skip_tty_check']:
454 self.editor.create_file(context.CLIARGS['args'][0], self.encrypt_secret,
455 vault_id=self.encrypt_vault_id)
456 else:
457 raise AnsibleOptionsError("not a tty, editor cannot be opened")
458
459 def execute_edit(self):
460 """ open and decrypt an existing vaulted file in an editor, that will be encrypted again when closed"""
461 for f in context.CLIARGS['args']:
462 self.editor.edit_file(f)
463
464 def execute_view(self):
465 """ open, decrypt and view an existing vaulted file using a pager using the supplied vault secret """
466
467 for f in context.CLIARGS['args']:
468 # Note: vault should return byte strings because it could encrypt
469 # and decrypt binary files. We are responsible for changing it to
470 # unicode here because we are displaying it and therefore can make
471 # the decision that the display doesn't have to be precisely what
472 # the input was (leave that to decrypt instead)
473 plaintext = self.editor.plaintext(f)
474 self.pager(to_text(plaintext))
475
476 def execute_rekey(self):
477 """ re-encrypt a vaulted file with a new secret, the previous secret is required """
478 for f in context.CLIARGS['args']:
479 # FIXME: plumb in vault_id, use the default new_vault_secret for now
480 self.editor.rekey_file(f, self.new_encrypt_secret,
481 self.new_encrypt_vault_id)
482
483 display.display("Rekey successful", stderr=True)
484
485
486 def main(args=None):
487 VaultCLI.cli_executor(args)
488
489
490 if __name__ == '__main__':
491 main()