Debian Codegraph @

ansible_collections/community/sops/plugins/module_utils/sops.py

raw
1 # Copyright (c), Edoardo Tenani <[email protected]>, 2018-2020
2 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
3 # SPDX-License-Identifier: BSD-2-Clause
4
5 from __future__ import absolute_import, division, print_function
6 __metaclass__ = type
7
8
9 import collections
10 import json
11 import os
12 import re
13
14 from ansible.module_utils.common.text.converters import to_text, to_native
15
16 # Since this is used both by plugins and modules, we need subprocess in case the `module` parameter is not used
17 from subprocess import Popen, PIPE
18
19
20 # From https://github.com/getsops/sops/blob/master/cmd/sops/codes/codes.go
21 # Should be manually updated
22 SOPS_ERROR_CODES = {
23 1: "ErrorGeneric",
24 2: "CouldNotReadInputFile",
25 3: "CouldNotWriteOutputFile",
26 4: "ErrorDumpingTree",
27 5: "ErrorReadingConfig",
28 6: "ErrorInvalidKMSEncryptionContextFormat",
29 7: "ErrorInvalidSetFormat",
30 8: "ErrorConflictingParameters",
31 21: "ErrorEncryptingMac",
32 23: "ErrorEncryptingTree",
33 24: "ErrorDecryptingMac",
34 25: "ErrorDecryptingTree",
35 49: "CannotChangeKeysFromNonExistentFile",
36 51: "MacMismatch",
37 52: "MacNotFound",
38 61: "ConfigFileNotFound",
39 85: "KeyboardInterrupt",
40 91: "InvalidTreePathFormat",
41 100: "NoFileSpecified",
42 128: "CouldNotRetrieveKey",
43 111: "NoEncryptionKeyFound",
44 200: "FileHasNotBeenModified",
45 201: "NoEditorFound",
46 202: "FailedToCompareVersions",
47 203: "FileAlreadyEncrypted"
48 }
49
50 _SOPS_VERSION = re.compile(r'^sops ([0-9]+)\.([0-9]+)\.([0-9]+)')
51
52
53 def _add_argument(arguments_pre, arguments_post, *args, **kwargs):
54 pre = kwargs.pop('pre', False)
55 (arguments_pre if pre else arguments_post).extend(args)
56
57
58 def _create_single_arg(argument_name, pre=False):
59 def f(value, arguments_pre, arguments_post, env, version):
60 _add_argument(arguments_pre, arguments_post, argument_name, to_native(value), pre=pre)
61
62 return f
63
64
65 def _create_comma_separated(argument_name, pre=False):
66 def f(value, arguments_pre, arguments_post, env, version):
67 value = ','.join([to_native(v) for v in value])
68 _add_argument(arguments_pre, arguments_post, argument_name, value, pre=pre)
69
70 return f
71
72
73 def _create_repeated(argument_name, pre=False):
74 def f(value, arguments_pre, arguments_post, env, version):
75 for v in value:
76 _add_argument(arguments_pre, arguments_post, argument_name, to_native(v), pre=pre)
77
78 return f
79
80
81 def _create_boolean(argument_name, pre=False, invert=False):
82 def f(value, arguments_pre, arguments_post, env, version):
83 if value ^ invert:
84 _add_argument(arguments_pre, arguments_post, argument_name, pre=pre)
85
86 return f
87
88
89 def _create_env_variable(argument_name):
90 def f(value, arguments_pre, arguments_post, env, version):
91 env[argument_name] = value
92
93 return f
94
95
96 GENERAL_OPTIONS = {
97 'age_key': _create_env_variable('SOPS_AGE_KEY'),
98 'age_keyfile': _create_env_variable('SOPS_AGE_KEY_FILE'),
99 'age_key_cmd': _create_env_variable('SOPS_AGE_KEY_CMD'),
100 'age_ssh_private_keyfile': _create_env_variable('SOPS_AGE_SSH_PRIVATE_KEY_FILE'),
101 'age_ssh_private_key_cmd': _create_env_variable('SOPS_AGE_SSH_PRIVATE_KEY_CMD'),
102 'aws_profile': _create_single_arg('--aws-profile'),
103 'aws_access_key_id': _create_env_variable('AWS_ACCESS_KEY_ID'),
104 'aws_secret_access_key': _create_env_variable('AWS_SECRET_ACCESS_KEY'),
105 'aws_session_token': _create_env_variable('AWS_SESSION_TOKEN'),
106 'gcp_oauth_access_token': _create_env_variable('GOOGLE_OAUTH_ACCESS_TOKEN'),
107 'gcp_kms_client_type': _create_env_variable('SOPS_GCP_KMS_CLIENT_TYPE'),
108 'config_path': _create_single_arg('--config', pre=True),
109 'enable_local_keyservice': _create_boolean('--enable-local-keyservice=false', invert=True),
110 'keyservice': _create_repeated('--keyservice'),
111 }
112
113
114 ENCRYPT_OPTIONS = {
115 'age': _create_comma_separated('--age'),
116 'kms': _create_comma_separated('--kms'),
117 'gcp_kms': _create_comma_separated('--gcp-kms'),
118 'azure_kv': _create_comma_separated('--azure-kv'),
119 'hc_vault_transit': _create_comma_separated('--hc-vault-transit'),
120 'pgp': _create_comma_separated('--pgp'),
121 'huawei_cloud_kms': _create_comma_separated('--hckms'),
122 'unencrypted_suffix': _create_single_arg('--unencrypted-suffix'),
123 'encrypted_suffix': _create_single_arg('--encrypted-suffix'),
124 'unencrypted_regex': _create_single_arg('--unencrypted-regex'),
125 'encrypted_regex': _create_single_arg('--encrypted-regex'),
126 'encryption_context': _create_comma_separated('--encryption-context'),
127 'shamir_secret_sharing_threshold': _create_single_arg('--shamir-secret-sharing-threshold'),
128 }
129
130
131 class SopsError(Exception):
132 ''' Extend Exception class with sops specific information '''
133
134 def __init__(self, filename, exit_code, message, decryption=True, operation=None):
135 if operation is None:
136 operation = 'decrypt' if decryption else 'encrypt'
137 if exit_code in SOPS_ERROR_CODES:
138 exception_name = SOPS_ERROR_CODES[exit_code]
139 message = "error with file %s: %s exited with code %d: %s" % (
140 filename, exception_name, exit_code, to_native(message))
141 else:
142 message = "could not %s file %s; Unknown sops error code: %s; message: %s" % (
143 operation, filename, exit_code, to_native(message))
144 super(SopsError, self).__init__(message)
145
146
147 SopsFileStatus = collections.namedtuple('SopsFileStatus', ['encrypted'])
148
149
150 class SopsRunner(object):
151 def _add_options(self, command_pre, command_post, env, get_option_value, options):
152 if get_option_value is None:
153 return
154 for option, f in options.items():
155 v = get_option_value(option)
156 if v is not None:
157 f(v, command_pre, command_post, env, self.version)
158
159 def _debug(self, message):
160 if self.display:
161 self.display.vvvv(message)
162 elif self.module:
163 self.module.debug(message)
164
165 def _warn(self, message):
166 if self.display:
167 self.display.warning(message)
168 elif self.module:
169 self.module.warn(message)
170
171 def __init__(self, binary, module=None, display=None):
172 self.binary = binary
173 self.module = module
174 self.display = display
175
176 self.version = (3, 7, 3) # if --disable-version-check is not supported, this is version 3.7.3 or older
177 self.version_string = '(before 3.8.0)'
178
179 exit_code, output, err = self._run_command([self.binary, '--version', '--disable-version-check'])
180 if exit_code == 0:
181 m = _SOPS_VERSION.match(output.decode('utf-8'))
182 if m:
183 self.version = int(m.group(1)), int(m.group(2)), int(m.group(3))
184 self.version_string = '%d.%d.%d' % self.version
185 self._debug('SOPS version detected as %s' % (self.version, ))
186 else:
187 self._warn('Cannot extract SOPS version from: %s' % repr(output))
188 else:
189 self._debug('Cannot detect SOPS version efficiently, likely a version before 3.8.0')
190
191 def _run_command(self, command, env=None, data=None, cwd=None):
192 if self.module:
193 return self.module.run_command(command, environ_update=env, cwd=cwd, encoding=None, data=data, binary_data=True)
194
195 process = Popen(command, stdin=None if data is None else PIPE, stdout=PIPE, stderr=PIPE, cwd=cwd, env=env)
196 output, err = process.communicate(input=data)
197 return process.returncode, output, err
198
199 def decrypt(self, encrypted_file, content=None,
200 decode_output=True, rstrip=True, input_type=None, output_type=None, get_option_value=None, extract=None):
201 # Run sops directly, python module is deprecated
202 command = [self.binary]
203 command_post = []
204 env = os.environ.copy()
205 self._add_options(command, command_post, env, get_option_value, GENERAL_OPTIONS)
206 if self.version >= (3, 9, 0):
207 command.append("decrypt")
208 command.extend(command_post)
209 if input_type is not None:
210 command.extend(["--input-type", input_type])
211 if output_type is not None:
212 command.extend(["--output-type", output_type])
213 if self.version < (3, 9, 0):
214 command.append("--decrypt")
215 if extract is not None:
216 command.extend(["--extract", extract])
217 if content is not None:
218 encrypted_file = '/dev/stdin'
219 command.append(encrypted_file)
220
221 exit_code, output, err = self._run_command(command, env=env, data=content)
222
223 if decode_output:
224 # output is binary, we want UTF-8 string
225 output = to_text(output, errors='surrogate_or_strict')
226 # the process output is the decrypted secret; be cautious
227
228 # sops logs always to stderr, as stdout is used for
229 # file content
230 if err:
231 self._debug(u'Unexpected stderr:\n' + to_text(err, errors='surrogate_or_strict'))
232
233 if exit_code != 0:
234 raise SopsError(encrypted_file, exit_code, err, decryption=True)
235
236 if rstrip:
237 output = output.rstrip()
238
239 return output
240
241 def encrypt(self, data, cwd=None, input_type=None, output_type=None, filename=None, get_option_value=None):
242 # Run sops directly, python module is deprecated
243 command = [self.binary]
244 command_post = []
245 env = os.environ.copy()
246 self._add_options(command, command_post, env, get_option_value, GENERAL_OPTIONS)
247 self._add_options(command, command_post, env, get_option_value, ENCRYPT_OPTIONS)
248 if self.version >= (3, 9, 0):
249 command.append("encrypt")
250 command.extend(command_post)
251 if input_type is not None:
252 command.extend(["--input-type", input_type])
253 if output_type is not None:
254 command.extend(["--output-type", output_type])
255 if self.version < (3, 9, 0):
256 command.append("--encrypt")
257 if self.version >= (3, 9, 0) and filename:
258 command.extend(["--filename-override", filename])
259 command.append("/dev/stdin")
260
261 exit_code, output, err = self._run_command(command, env=env, data=data, cwd=cwd)
262
263 # sops logs always to stderr, as stdout is used for
264 # file content
265 if err:
266 self._debug(u'Unexpected stderr:\n' + to_text(err, errors='surrogate_or_strict'))
267
268 if exit_code != 0:
269 raise SopsError('to stdout', exit_code, err, decryption=False)
270
271 return output
272
273 def has_filestatus(self):
274 return self.version >= (3, 9, 0)
275
276 def get_filestatus(self, path):
277 command = [self.binary, 'filestatus', path]
278
279 exit_code, output, err = self._run_command(command)
280
281 # sops logs always to stderr, as stdout is used for
282 # file content
283 if err:
284 self._debug(u'Unexpected stderr:\n' + to_text(err, errors='surrogate_or_strict'))
285
286 if exit_code != 0:
287 raise SopsError(path, exit_code, err, operation='inspect')
288
289 try:
290 result = json.loads(output)
291 return SopsFileStatus(result['encrypted'])
292 except Exception as exc:
293 self._debug(u'Unexpected stdout:\n' + to_text(output, errors='surrogate_or_strict'))
294 raise SopsError(path, 0, 'Cannot decode filestatus result: %s' % exc, operation='inspect')
295
296
297 _SOPS_RUNNER_CACHE = dict() # type: dict[str, SopsRunner]
298
299
300 class Sops():
301 ''' Utility class to perform sops CLI actions '''
302
303 @staticmethod
304 def get_sops_binary(get_option_value):
305 cmd = get_option_value('sops_binary') if get_option_value else None
306 if cmd is None:
307 cmd = 'sops'
308 return cmd
309
310 @staticmethod
311 def get_sops_runner_from_binary(sops_binary, module=None, display=None):
312 candidates = _SOPS_RUNNER_CACHE.get(sops_binary, [])
313 for cand_module, cand_runner in candidates:
314 if cand_runner is module:
315 return cand_runner
316 runner = SopsRunner(sops_binary, module=module, display=display)
317 candidates.append((module, runner))
318 _SOPS_RUNNER_CACHE[sops_binary] = candidates
319 return runner
320
321 @staticmethod
322 def get_sops_runner_from_options(get_option_value, module=None, display=None):
323 return Sops.get_sops_runner_from_binary(Sops.get_sops_binary(get_option_value), module=module, display=display)
324
325 @staticmethod
326 def decrypt(encrypted_file, content=None,
327 display=None, decode_output=True, rstrip=True, input_type=None, output_type=None, get_option_value=None, module=None, extract=None):
328 runner = Sops.get_sops_runner_from_options(get_option_value, module=module, display=display)
329 return runner.decrypt(
330 encrypted_file,
331 content=content,
332 decode_output=decode_output,
333 rstrip=rstrip,
334 input_type=input_type,
335 output_type=output_type,
336 get_option_value=get_option_value,
337 extract=extract,
338 )
339
340 @staticmethod
341 def encrypt(data, display=None, cwd=None, input_type=None, output_type=None, get_option_value=None, module=None, filename=None):
342 runner = Sops.get_sops_runner_from_options(get_option_value, module=module, display=display)
343 return runner.encrypt(
344 data,
345 cwd=cwd,
346 input_type=input_type,
347 output_type=output_type,
348 get_option_value=get_option_value,
349 filename=filename,
350 )
351
352
353 def get_sops_argument_spec(add_encrypt_specific=False):
354 argument_spec = {
355 'sops_binary': {
356 'type': 'path',
357 },
358 'age_key': {
359 'type': 'str',
360 'no_log': True,
361 },
362 'age_keyfile': {
363 'type': 'path',
364 },
365 'age_key_cmd': {
366 'type': 'str',
367 'no_log': False,
368 },
369 'age_ssh_private_keyfile': {
370 'type': 'path',
371 },
372 'age_ssh_private_key_cmd': {
373 'type': 'str',
374 'no_log': False,
375 },
376 'aws_profile': {
377 'type': 'str',
378 },
379 'aws_access_key_id': {
380 'type': 'str',
381 },
382 'aws_secret_access_key': {
383 'type': 'str',
384 'no_log': True,
385 },
386 'aws_session_token': {
387 'type': 'str',
388 'no_log': True,
389 },
390 'gcp_oauth_access_token': {
391 'type': 'str',
392 'no_log': True,
393 },
394 'gcp_kms_client_type': {
395 'type': 'str',
396 'choices': ['rest', 'grpc'],
397 },
398 'config_path': {
399 'type': 'path',
400 },
401 'enable_local_keyservice': {
402 'type': 'bool',
403 'default': True,
404 },
405 'keyservice': {
406 'type': 'list',
407 'elements': 'str',
408 },
409 }
410 if add_encrypt_specific:
411 argument_spec.update({
412 'age': {
413 'type': 'list',
414 'elements': 'str',
415 },
416 'kms': {
417 'type': 'list',
418 'elements': 'str',
419 },
420 'gcp_kms': {
421 'type': 'list',
422 'elements': 'str',
423 },
424 'azure_kv': {
425 'type': 'list',
426 'elements': 'str',
427 },
428 'hc_vault_transit': {
429 'type': 'list',
430 'elements': 'str',
431 },
432 'pgp': {
433 'type': 'list',
434 'elements': 'str',
435 },
436 'huawei_cloud_kms': {
437 'type': 'list',
438 'elements': 'str',
439 },
440 'unencrypted_suffix': {
441 'type': 'str',
442 },
443 'encrypted_suffix': {
444 'type': 'str',
445 },
446 'unencrypted_regex': {
447 'type': 'str',
448 },
449 'encrypted_regex': {
450 'type': 'str',
451 },
452 'encryption_context': {
453 'type': 'list',
454 'elements': 'str',
455 },
456 'shamir_secret_sharing_threshold': {
457 'type': 'int',
458 'no_log': False,
459 },
460 })
461 return argument_spec