Volume discovery and local storage management lib
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

234 lines
9.9KB

  1. # Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
  2. # All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. from os_brick.encryptors import cryptsetup
  16. from os_brick.privileged import rootwrap as priv_rootwrap
  17. from oslo_concurrency import processutils as putils
  18. from oslo_log import log as logging
  19. LOG = logging.getLogger(__name__)
  20. def is_luks(root_helper, device, execute=None):
  21. """Checks if the specified device uses LUKS for encryption.
  22. :param device: the device to check
  23. :returns: true if the specified device uses LUKS; false otherwise
  24. """
  25. try:
  26. # check to see if the device uses LUKS: exit status is 0
  27. # if the device is a LUKS partition and non-zero if not
  28. if execute is None:
  29. execute = priv_rootwrap.execute
  30. execute('cryptsetup', 'isLuks', '--verbose', device,
  31. run_as_root=True, root_helper=root_helper,
  32. check_exit_code=True)
  33. return True
  34. except putils.ProcessExecutionError as e:
  35. LOG.warning("isLuks exited abnormally (status %(exit_code)s): "
  36. "%(stderr)s",
  37. {"exit_code": e.exit_code, "stderr": e.stderr})
  38. return False
  39. class LuksEncryptor(cryptsetup.CryptsetupEncryptor):
  40. """A VolumeEncryptor based on LUKS.
  41. This VolumeEncryptor uses dm-crypt to encrypt the specified volume.
  42. """
  43. def __init__(self, root_helper,
  44. connection_info,
  45. keymgr,
  46. execute=None,
  47. *args, **kwargs):
  48. super(LuksEncryptor, self).__init__(
  49. root_helper=root_helper,
  50. connection_info=connection_info,
  51. keymgr=keymgr,
  52. execute=execute,
  53. *args, **kwargs)
  54. def _format_volume(self, passphrase, **kwargs):
  55. """Creates a LUKS v1 header on the volume.
  56. :param passphrase: the passphrase used to access the volume
  57. """
  58. self._format_luks_volume(passphrase, 'luks1', **kwargs)
  59. def _format_luks_volume(self, passphrase, version, **kwargs):
  60. """Creates a LUKS header of a given version or type on the volume.
  61. :param passphrase: the passphrase used to access the volume
  62. :param version: the LUKS version or type to use: one of `luks`,
  63. `luks1`, or `luks2`. Be aware that `luks` gives you
  64. the default LUKS format preferred by the particular
  65. cryptsetup being used (depends on version and compile
  66. time parameters), which could be either LUKS1 or
  67. LUKS2, so it's better to be specific about what you
  68. want here
  69. """
  70. LOG.debug("formatting encrypted volume %s", self.dev_path)
  71. # NOTE(joel-coffman): cryptsetup will strip trailing newlines from
  72. # input specified on stdin unless --key-file=- is specified.
  73. cmd = ["cryptsetup", "--batch-mode", "luksFormat", "--type", version,
  74. "--key-file=-"]
  75. cipher = kwargs.get("cipher", None)
  76. if cipher is not None:
  77. cmd.extend(["--cipher", cipher])
  78. key_size = kwargs.get("key_size", None)
  79. if key_size is not None:
  80. cmd.extend(["--key-size", key_size])
  81. cmd.extend([self.dev_path])
  82. self._execute(*cmd, process_input=passphrase,
  83. check_exit_code=True, run_as_root=True,
  84. root_helper=self._root_helper,
  85. attempts=3)
  86. def _open_volume(self, passphrase, **kwargs):
  87. """Opens the LUKS partition on the volume using passphrase.
  88. :param passphrase: the passphrase used to access the volume
  89. """
  90. LOG.debug("opening encrypted volume %s", self.dev_path)
  91. self._execute('cryptsetup', 'luksOpen', '--key-file=-',
  92. self.dev_path, self.dev_name, process_input=passphrase,
  93. run_as_root=True, check_exit_code=True,
  94. root_helper=self._root_helper)
  95. def _unmangle_volume(self, key, passphrase, **kwargs):
  96. """Workaround for bug#1633518
  97. First identify if a mangled passphrase is used and if found then
  98. replace with the correct unmangled version of the passphrase.
  99. """
  100. mangled_passphrase = self._get_mangled_passphrase(key)
  101. self._open_volume(mangled_passphrase, **kwargs)
  102. self._close_volume(**kwargs)
  103. LOG.debug("%s correctly opened with a mangled passphrase, replacing "
  104. "this with the original passphrase", self.dev_path)
  105. # NOTE(lyarwood): Now that we are sure that the mangled passphrase is
  106. # used attempt to add the correct passphrase before removing the
  107. # mangled version from the volume.
  108. # luksAddKey currently prompts for the following input :
  109. # Enter any existing passphrase:
  110. # Enter new passphrase for key slot:
  111. # Verify passphrase:
  112. self._execute('cryptsetup', 'luksAddKey', self.dev_path,
  113. '--force-password',
  114. process_input=''.join([mangled_passphrase, '\n',
  115. passphrase, '\n', passphrase]),
  116. run_as_root=True, check_exit_code=True,
  117. root_helper=self._root_helper)
  118. # Verify that we can open the volume with the current passphrase
  119. # before removing the mangled passphrase.
  120. self._open_volume(passphrase, **kwargs)
  121. self._close_volume(**kwargs)
  122. # luksRemoveKey only prompts for the key to remove.
  123. self._execute('cryptsetup', 'luksRemoveKey', self.dev_path,
  124. process_input=mangled_passphrase,
  125. run_as_root=True, check_exit_code=True,
  126. root_helper=self._root_helper)
  127. LOG.debug("%s mangled passphrase successfully replaced", self.dev_path)
  128. def attach_volume(self, context, **kwargs):
  129. """Shadow the device and pass an unencrypted version to the instance.
  130. Transparent disk encryption is achieved by mounting the volume via
  131. dm-crypt and passing the resulting device to the instance. The
  132. instance is unaware of the underlying encryption due to modifying the
  133. original symbolic link to refer to the device mounted by dm-crypt.
  134. """
  135. key = self._get_key(context).get_encoded()
  136. passphrase = self._get_passphrase(key)
  137. try:
  138. self._open_volume(passphrase, **kwargs)
  139. except putils.ProcessExecutionError as e:
  140. if e.exit_code == 1 and not is_luks(self._root_helper,
  141. self.dev_path,
  142. execute=self._execute):
  143. # the device has never been formatted; format it and try again
  144. LOG.info("%s is not a valid LUKS device;"
  145. " formatting device for first use",
  146. self.dev_path)
  147. self._format_volume(passphrase, **kwargs)
  148. self._open_volume(passphrase, **kwargs)
  149. elif e.exit_code == 2:
  150. # NOTE(lyarwood): Workaround bug#1633518 by replacing any
  151. # mangled passphrases that are found on the volume.
  152. # TODO(lyarwood): Remove workaround during R.
  153. LOG.warning("%s is not usable with the current "
  154. "passphrase, attempting to use a mangled "
  155. "passphrase to open the volume.",
  156. self.dev_path)
  157. self._unmangle_volume(key, passphrase, **kwargs)
  158. self._open_volume(passphrase, **kwargs)
  159. else:
  160. raise
  161. # modify the original symbolic link to refer to the decrypted device
  162. self._execute('ln', '--symbolic', '--force',
  163. '/dev/mapper/%s' % self.dev_name, self.symlink_path,
  164. root_helper=self._root_helper,
  165. run_as_root=True, check_exit_code=True)
  166. def _close_volume(self, **kwargs):
  167. """Closes the device (effectively removes the dm-crypt mapping)."""
  168. LOG.debug("closing encrypted volume %s", self.dev_path)
  169. # NOTE(mdbooth): luksClose will return 4 (wrong device specified) if
  170. # the device doesn't exist. We assume here that the caller hasn't
  171. # specified the wrong device, and that it doesn't exist because it
  172. # isn't open. We don't fail in this case in order to make this
  173. # operation idempotent.
  174. self._execute('cryptsetup', 'luksClose', self.dev_name,
  175. run_as_root=True, check_exit_code=[0, 4],
  176. root_helper=self._root_helper,
  177. attempts=3)
  178. class Luks2Encryptor(LuksEncryptor):
  179. """A VolumeEncryptor based on LUKS v2.
  180. This VolumeEncryptor uses dm-crypt to encrypt the specified volume.
  181. """
  182. def __init__(self, root_helper,
  183. connection_info,
  184. keymgr,
  185. execute=None,
  186. *args, **kwargs):
  187. super(Luks2Encryptor, self).__init__(
  188. root_helper=root_helper,
  189. connection_info=connection_info,
  190. keymgr=keymgr,
  191. execute=execute,
  192. *args, **kwargs)
  193. def _format_volume(self, passphrase, **kwargs):
  194. """Creates a LUKS v2 header on the volume.
  195. :param passphrase: the passphrase used to access the volume
  196. """
  197. self._format_luks_volume(passphrase, 'luks2', **kwargs)