| 1 |
#!/usr/bin/python |
| 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 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
DOCUMENTATION = r""" |
| 9 |
module: luks_device |
| 10 |
|
| 11 |
short_description: Manage encrypted (LUKS) devices |
| 12 |
|
| 13 |
description: |
| 14 |
- Module manages L(LUKS,https://en.wikipedia.org/wiki/Linux_Unified_Key_Setup) on given device. Supports creating, destroying, |
| 15 |
opening and closing of LUKS container and adding or removing new keys and passphrases. |
| 16 |
extends_documentation_fragment: |
| 17 |
- community.crypto._attributes |
| 18 |
|
| 19 |
attributes: |
| 20 |
check_mode: |
| 21 |
support: full |
| 22 |
diff_mode: |
| 23 |
support: none |
| 24 |
idempotent: |
| 25 |
support: full |
| 26 |
|
| 27 |
options: |
| 28 |
device: |
| 29 |
description: |
| 30 |
- Device to work with (for example V(/dev/sda1)). Needed in most cases. Can be omitted only when O(state=closed) together |
| 31 |
with O(name) is provided. |
| 32 |
type: str |
| 33 |
state: |
| 34 |
description: |
| 35 |
- Desired state of the LUKS container. Based on its value creates, destroys, opens or closes the LUKS container on a |
| 36 |
given device. |
| 37 |
- V(present) will create LUKS container unless already present. Requires O(device) and either O(keyfile) or O(passphrase) |
| 38 |
options to be provided. |
| 39 |
- V(absent) will remove existing LUKS container if it exists. Requires O(device) or O(name) to be specified. |
| 40 |
- V(opened) will unlock the LUKS container. Requires O(device) and one of O(keyfile), O(passphrase), O(tpm2_device) to be specified. |
| 41 |
If the container does not exist it will be created first, however O(tpm2_device) can not be used for creation. |
| 42 |
Use the O(name) option to set the name of the opened container. Otherwise the name will be generated automatically and returned as a part of the result. |
| 43 |
- V(closed) will lock the LUKS container. However if the container does not exist it will be created. Requires O(device) |
| 44 |
and either O(keyfile) or O(passphrase) options to be provided. If container does already exist O(device) or O(name) |
| 45 |
will suffice. |
| 46 |
type: str |
| 47 |
default: present |
| 48 |
choices: [present, absent, opened, closed] |
| 49 |
name: |
| 50 |
description: |
| 51 |
- Sets container name when O(state=opened). Can be used instead of O(device) when closing the existing container (that |
| 52 |
is, when O(state=closed)). |
| 53 |
type: str |
| 54 |
keyfile: |
| 55 |
description: |
| 56 |
- Used to unlock the container. Either a O(keyfile) or a O(passphrase) is needed for most of the operations. Parameter |
| 57 |
value is the path to the keyfile with the passphrase. |
| 58 |
- BEWARE that working with keyfiles in plaintext is dangerous. Make sure that they are protected. |
| 59 |
type: path |
| 60 |
passphrase: |
| 61 |
description: |
| 62 |
- Used to unlock the container. Either a O(passphrase) or a O(keyfile) is needed for most of the operations. Parameter |
| 63 |
value is a string with the passphrase. |
| 64 |
- B(Note) that the passphrase must be UTF-8 encoded text. If you want to use arbitrary binary data, or text using |
| 65 |
another encoding, use the O(passphrase_encoding) option and provide the passphrase Base64 encoded. |
| 66 |
type: str |
| 67 |
version_added: '1.0.0' |
| 68 |
tpm2_device: |
| 69 |
description: |
| 70 |
- Used to unlock the container, but can not be used for container creation. A device node path referring to a TPM2 chip (for example V(/dev/tpmrm0)). |
| 71 |
Alternatively the special value V(auto) may be specified, in order to automatically determine the device node of a currently |
| 72 |
discovered TPM2 device (of which there must be exactly one). |
| 73 |
- B(Note) that only LUKS2 containers are supported |
| 74 |
- B(Note) that systemd-cryptsetup (v256 or newer) is required. |
| 75 |
type: str |
| 76 |
version_added: '3.1.0' |
| 77 |
passphrase_encoding: |
| 78 |
description: |
| 79 |
- Determine how passphrases are provided to parameters such as O(passphrase), O(new_passphrase), and O(remove_passphrase). |
| 80 |
type: str |
| 81 |
default: text |
| 82 |
choices: |
| 83 |
text: |
| 84 |
- The passphrase is provided as UTF-8 encoded text. |
| 85 |
base64: |
| 86 |
- The passphrase is provided as Base64 encoded bytes. |
| 87 |
- Use the P(ansible.builtin.b64encode#filter) filter to Base64-encode binary data. |
| 88 |
version_added: 2.23.0 |
| 89 |
keyslot: |
| 90 |
description: |
| 91 |
- Adds the O(keyfile) or O(passphrase) to a specific keyslot when creating a new container on O(device). Parameter value |
| 92 |
is the number of the keyslot. |
| 93 |
- Defines the keyslot whose priority will be changed by O(keyslot_priority) |
| 94 |
- B(Note) that a device of O(type=luks1) supports the keyslot numbers V(0)-V(7) and a device of O(type=luks2) supports |
| 95 |
the keyslot numbers V(0)-V(31). In order to use the keyslots V(8)-V(31) when creating a new container, setting O(type) |
| 96 |
to V(luks2) is required. |
| 97 |
type: int |
| 98 |
version_added: '2.16.0' |
| 99 |
keysize: |
| 100 |
description: |
| 101 |
- Sets the key size only if LUKS container does not exist. |
| 102 |
type: int |
| 103 |
version_added: '1.0.0' |
| 104 |
new_keyfile: |
| 105 |
description: |
| 106 |
- Adds additional key to given container on O(device). Needs O(keyfile) or O(passphrase) option for authorization. LUKS |
| 107 |
container supports up to 8 keyslots. Parameter value is the path to the keyfile with the passphrase. |
| 108 |
- NOTE that adding additional keys is idempotent only since community.crypto 1.4.0. For older versions, a new keyslot |
| 109 |
will be used even if another keyslot already exists for this keyfile. |
| 110 |
- BEWARE that working with keyfiles in plaintext is dangerous. Make sure that they are protected. |
| 111 |
type: path |
| 112 |
new_passphrase: |
| 113 |
description: |
| 114 |
- Adds additional passphrase to given container on O(device). Needs O(keyfile) or O(passphrase) option for authorization. |
| 115 |
LUKS container supports up to 8 keyslots. Parameter value is a string with the new passphrase. |
| 116 |
- NOTE that adding additional passphrase is idempotent only since community.crypto 1.4.0. For older versions, a new |
| 117 |
keyslot will be used even if another keyslot already exists for this passphrase. |
| 118 |
- B(Note) that the passphrase must be UTF-8 encoded text. If you want to use arbitrary binary data, or text using |
| 119 |
another encoding, use the O(passphrase_encoding) option and provide the passphrase Base64 encoded. |
| 120 |
type: str |
| 121 |
version_added: '1.0.0' |
| 122 |
new_keyslot: |
| 123 |
description: |
| 124 |
- Adds the additional O(new_keyfile) or O(new_passphrase) to a specific keyslot on the given O(device). Parameter value |
| 125 |
is the number of the keyslot. |
| 126 |
- B(Note) that a device of O(type=luks1) supports the keyslot numbers V(0)-V(7) and a device of O(type=luks2) supports |
| 127 |
the keyslot numbers V(0)-V(31). |
| 128 |
type: int |
| 129 |
version_added: '2.16.0' |
| 130 |
new_tpm2: |
| 131 |
description: |
| 132 |
- Adds a TPM2 security chip to given container on O(device). Expects a device node path referring to the TPM2 chip (e.g. V(/dev/tpmrm0)). |
| 133 |
Alternatively the special value V(auto) may be specified, in order to automatically determine the device node of a currently |
| 134 |
discovered TPM2 device (of which there must be exactly one). Requires O(new_tpm2_pcrs). |
| 135 |
- B(Note) that O(new_keyslot) does not affect the keyslot for TPM2 enrollment. |
| 136 |
- B(Note) that only LUKS2 containers are supported. |
| 137 |
- B(Note) that systemd-cryptsetup (v248 or newer) is required. |
| 138 |
type: str |
| 139 |
version_added: '3.1.0' |
| 140 |
new_tpm2_pcrs: |
| 141 |
description: |
| 142 |
- TPM2 PCRs (Platform Configuration Registers) to bind to. See systemd-cryptenroll documentation for details (C(--tpm2-pcrs) argument). |
| 143 |
type: str |
| 144 |
version_added: '3.1.0' |
| 145 |
remove_keyfile: |
| 146 |
description: |
| 147 |
- Removes given key from the container on O(device). Does not remove the keyfile from filesystem. Parameter value is |
| 148 |
the path to the keyfile with the passphrase. |
| 149 |
- NOTE that removing keys is idempotent only since community.crypto 1.4.0. For older versions, trying to remove a key |
| 150 |
which no longer exists results in an error. |
| 151 |
- NOTE that to remove the last key from a LUKS container, the O(force_remove_last_key) option must be set to V(true). |
| 152 |
- BEWARE that working with keyfiles in plaintext is dangerous. Make sure that they are protected. |
| 153 |
type: path |
| 154 |
remove_passphrase: |
| 155 |
description: |
| 156 |
- Removes given passphrase from the container on O(device). Parameter value is a string with the passphrase to remove. |
| 157 |
- NOTE that removing passphrases is idempotent only since community.crypto 1.4.0. For older versions, trying to remove |
| 158 |
a passphrase which no longer exists results in an error. |
| 159 |
- NOTE that to remove the last keyslot from a LUKS container, the O(force_remove_last_key) option must be set to V(true). |
| 160 |
- B(Note) that the passphrase must be UTF-8 encoded text. If you want to use arbitrary binary data, or text using |
| 161 |
another encoding, use the O(passphrase_encoding) option and provide the passphrase Base64 encoded. |
| 162 |
type: str |
| 163 |
version_added: '1.0.0' |
| 164 |
remove_tpm2: |
| 165 |
description: |
| 166 |
- Removes B(all) key slots on O(device) that are unlocked by a TPM2 device. |
| 167 |
Needs O(keyfile), O(passphrase), or O(tpm2_device) for authorization. |
| 168 |
- B(Note) that systemd-cryptsetup (v248 or newer) is required. |
| 169 |
- B(Note) that you should avoid using O(tpm2_device) to authorize removal of all TPM2 slots to ensure that you can still access the container afterwards. |
| 170 |
type: bool |
| 171 |
default: false |
| 172 |
version_added: '3.1.0' |
| 173 |
remove_keyslot: |
| 174 |
description: |
| 175 |
- Removes the key in the given slot on O(device). Needs O(keyfile) or O(passphrase) for authorization. |
| 176 |
- B(Note) that a device of O(type=luks1) supports the keyslot numbers V(0)-V(7) and a device of O(type=luks2) supports |
| 177 |
the keyslot numbers V(0)-V(31). |
| 178 |
- B(Note) that the given O(keyfile) or O(passphrase) must not be in the slot to be removed. |
| 179 |
type: int |
| 180 |
version_added: '2.16.0' |
| 181 |
keyslot_priority: |
| 182 |
description: |
| 183 |
- Sets the keyslot priority for the keyslot specified by O(keyslot). |
| 184 |
- B(Note) that keyslot priority is only supported for LUKS2 containers. |
| 185 |
type: str |
| 186 |
choices: [prefer, normal, ignore] |
| 187 |
version_added: '3.1.0' |
| 188 |
force_remove_last_key: |
| 189 |
description: |
| 190 |
- If set to V(true), allows removing the last key from a container. |
| 191 |
- BEWARE that when the last key has been removed from a container, the container can no longer be opened! |
| 192 |
type: bool |
| 193 |
default: false |
| 194 |
label: |
| 195 |
description: |
| 196 |
- This option allow the user to create a LUKS2 format container with label support, respectively to identify the container |
| 197 |
by label on later usages. |
| 198 |
- Will only be used on container creation, or when O(device) is not specified. |
| 199 |
- This cannot be specified if O(type) is set to V(luks1). |
| 200 |
type: str |
| 201 |
version_added: '1.0.0' |
| 202 |
uuid: |
| 203 |
description: |
| 204 |
- With this option user can identify the LUKS container by UUID. |
| 205 |
- Will only be used when O(device) and O(label) are not specified. |
| 206 |
type: str |
| 207 |
version_added: '1.0.0' |
| 208 |
type: |
| 209 |
description: |
| 210 |
- This option allow the user explicit define the format of LUKS container that wants to work with. Options are V(luks1) |
| 211 |
or V(luks2). |
| 212 |
type: str |
| 213 |
choices: [luks1, luks2] |
| 214 |
version_added: '1.0.0' |
| 215 |
cipher: |
| 216 |
description: |
| 217 |
- This option allows the user to define the cipher specification string for the LUKS container. |
| 218 |
- Will only be used on container creation. |
| 219 |
- For pre-2.6.10 kernels, use V(aes-plain) as they do not understand the new cipher spec strings. To use ESSIV, use |
| 220 |
V(aes-cbc-essiv:sha256). |
| 221 |
type: str |
| 222 |
version_added: '1.1.0' |
| 223 |
hash: |
| 224 |
description: |
| 225 |
- This option allows the user to specify the hash function used in LUKS key setup scheme and volume key digest. |
| 226 |
- Will only be used on container creation. |
| 227 |
type: str |
| 228 |
version_added: '1.1.0' |
| 229 |
pbkdf: |
| 230 |
description: |
| 231 |
- This option allows the user to configure the Password-Based Key Derivation Function (PBKDF) used. |
| 232 |
- Will only be used on container creation, and when adding keys to an existing container. |
| 233 |
type: dict |
| 234 |
version_added: '1.4.0' |
| 235 |
suboptions: |
| 236 |
iteration_time: |
| 237 |
description: |
| 238 |
- Specify the iteration time used for the PBKDF. |
| 239 |
- Note that this is in B(seconds), not in milliseconds as on the command line. |
| 240 |
- Mutually exclusive with O(pbkdf.iteration_count). |
| 241 |
type: float |
| 242 |
iteration_count: |
| 243 |
description: |
| 244 |
- Specify the iteration count used for the PBKDF. |
| 245 |
- Mutually exclusive with O(pbkdf.iteration_time). |
| 246 |
type: int |
| 247 |
algorithm: |
| 248 |
description: |
| 249 |
- The algorithm to use. |
| 250 |
- Only available for the LUKS 2 format. |
| 251 |
choices: |
| 252 |
- argon2i |
| 253 |
- argon2id |
| 254 |
- pbkdf2 |
| 255 |
type: str |
| 256 |
memory: |
| 257 |
description: |
| 258 |
- The memory cost limit in kilobytes for the PBKDF. |
| 259 |
- This is not used for PBKDF2, but only for the Argon PBKDFs. |
| 260 |
type: int |
| 261 |
parallel: |
| 262 |
description: |
| 263 |
- The parallel cost for the PBKDF. This is the number of threads that run in parallel. |
| 264 |
- This is not used for PBKDF2, but only for the Argon PBKDFs. |
| 265 |
type: int |
| 266 |
sector_size: |
| 267 |
description: |
| 268 |
- This option allows the user to specify the sector size (in bytes) used for LUKS2 containers. |
| 269 |
- Will only be used on container creation. |
| 270 |
type: int |
| 271 |
version_added: '1.5.0' |
| 272 |
perf_same_cpu_crypt: |
| 273 |
description: |
| 274 |
- Allows the user to perform encryption using the same CPU that IO was submitted on. |
| 275 |
- The default is to use an unbound workqueue so that encryption work is automatically balanced between available CPUs. |
| 276 |
- Will only be used when opening containers. |
| 277 |
type: bool |
| 278 |
default: false |
| 279 |
version_added: '2.3.0' |
| 280 |
perf_submit_from_crypt_cpus: |
| 281 |
description: |
| 282 |
- Allows the user to disable offloading writes to a separate thread after encryption. |
| 283 |
- There are some situations where offloading block write IO operations from the encryption threads to a single thread |
| 284 |
degrades performance significantly. |
| 285 |
- The default is to offload block write IO operations to the same thread. |
| 286 |
- Will only be used when opening containers. |
| 287 |
type: bool |
| 288 |
default: false |
| 289 |
version_added: '2.3.0' |
| 290 |
perf_no_read_workqueue: |
| 291 |
description: |
| 292 |
- Allows the user to bypass dm-crypt internal workqueue and process read requests synchronously. |
| 293 |
- Will only be used when opening containers. |
| 294 |
type: bool |
| 295 |
default: false |
| 296 |
version_added: '2.3.0' |
| 297 |
perf_no_write_workqueue: |
| 298 |
description: |
| 299 |
- Allows the user to bypass dm-crypt internal workqueue and process write requests synchronously. |
| 300 |
- Will only be used when opening containers. |
| 301 |
type: bool |
| 302 |
default: false |
| 303 |
version_added: '2.3.0' |
| 304 |
persistent: |
| 305 |
description: |
| 306 |
- Allows the user to store options into container's metadata persistently and automatically use them next time. Only |
| 307 |
O(perf_same_cpu_crypt), O(perf_submit_from_crypt_cpus), O(perf_no_read_workqueue), O(perf_no_write_workqueue), and |
| 308 |
O(allow_discards) can be stored persistently. |
| 309 |
- Will only work with LUKS2 containers. |
| 310 |
- Will only be used when opening containers. |
| 311 |
type: bool |
| 312 |
default: false |
| 313 |
version_added: '2.3.0' |
| 314 |
allow_discards: |
| 315 |
description: |
| 316 |
- Allow discards (also known as TRIM) requests for device. |
| 317 |
- Will only be used when opening containers. |
| 318 |
type: bool |
| 319 |
default: false |
| 320 |
version_added: '2.17.0' |
| 321 |
|
| 322 |
requirements: |
| 323 |
- "cryptsetup" |
| 324 |
- "wipefs (when O(state) is V(absent))" |
| 325 |
- "lsblk" |
| 326 |
- "blkid (when O(label) or O(uuid) options are used)" |
| 327 |
- "systemd-cryptsetup (for TPM2 only)" |
| 328 |
|
| 329 |
author: Jan Pokorny (@japokorn) |
| 330 |
""" |
| 331 |
|
| 332 |
EXAMPLES = r""" |
| 333 |
--- |
| 334 |
- name: Create LUKS container (remains unchanged if it already exists) |
| 335 |
community.crypto.luks_device: |
| 336 |
device: "/dev/loop0" |
| 337 |
state: "present" |
| 338 |
keyfile: "/vault/keyfile" |
| 339 |
|
| 340 |
- name: Create LUKS container with a passphrase |
| 341 |
community.crypto.luks_device: |
| 342 |
device: "/dev/loop0" |
| 343 |
state: "present" |
| 344 |
passphrase: "foo" |
| 345 |
|
| 346 |
- name: Create LUKS container with specific encryption |
| 347 |
community.crypto.luks_device: |
| 348 |
device: "/dev/loop0" |
| 349 |
state: "present" |
| 350 |
cipher: "aes" |
| 351 |
hash: "sha256" |
| 352 |
|
| 353 |
- name: (Create and) open the LUKS container; name it "mycrypt" |
| 354 |
community.crypto.luks_device: |
| 355 |
device: "/dev/loop0" |
| 356 |
state: "opened" |
| 357 |
name: "mycrypt" |
| 358 |
keyfile: "/vault/keyfile" |
| 359 |
|
| 360 |
- name: Close the existing LUKS container "mycrypt" |
| 361 |
community.crypto.luks_device: |
| 362 |
state: "closed" |
| 363 |
name: "mycrypt" |
| 364 |
|
| 365 |
- name: Make sure LUKS container exists and is closed |
| 366 |
community.crypto.luks_device: |
| 367 |
device: "/dev/loop0" |
| 368 |
state: "closed" |
| 369 |
keyfile: "/vault/keyfile" |
| 370 |
|
| 371 |
- name: Create container if it does not exist and add new key to it |
| 372 |
community.crypto.luks_device: |
| 373 |
device: "/dev/loop0" |
| 374 |
state: "present" |
| 375 |
keyfile: "/vault/keyfile" |
| 376 |
new_keyfile: "/vault/keyfile2" |
| 377 |
|
| 378 |
- name: Add new key to the LUKS container (container has to exist) |
| 379 |
community.crypto.luks_device: |
| 380 |
device: "/dev/loop0" |
| 381 |
keyfile: "/vault/keyfile" |
| 382 |
new_keyfile: "/vault/keyfile2" |
| 383 |
|
| 384 |
- name: Add new passphrase to the LUKS container |
| 385 |
community.crypto.luks_device: |
| 386 |
device: "/dev/loop0" |
| 387 |
keyfile: "/vault/keyfile" |
| 388 |
new_passphrase: "foo" |
| 389 |
|
| 390 |
- name: Remove existing keyfile from the LUKS container |
| 391 |
community.crypto.luks_device: |
| 392 |
device: "/dev/loop0" |
| 393 |
remove_keyfile: "/vault/keyfile2" |
| 394 |
|
| 395 |
- name: Remove existing passphrase from the LUKS container |
| 396 |
community.crypto.luks_device: |
| 397 |
device: "/dev/loop0" |
| 398 |
remove_passphrase: "foo" |
| 399 |
|
| 400 |
- name: Completely remove the LUKS container and its contents |
| 401 |
community.crypto.luks_device: |
| 402 |
device: "/dev/loop0" |
| 403 |
state: "absent" |
| 404 |
|
| 405 |
- name: Create a container with label |
| 406 |
community.crypto.luks_device: |
| 407 |
device: "/dev/loop0" |
| 408 |
state: "present" |
| 409 |
keyfile: "/vault/keyfile" |
| 410 |
label: personalLabelName |
| 411 |
|
| 412 |
- name: Open the LUKS container based on label without device; name it "mycrypt" |
| 413 |
community.crypto.luks_device: |
| 414 |
label: "personalLabelName" |
| 415 |
state: "opened" |
| 416 |
name: "mycrypt" |
| 417 |
keyfile: "/vault/keyfile" |
| 418 |
|
| 419 |
- name: Close container based on UUID |
| 420 |
community.crypto.luks_device: |
| 421 |
uuid: 03ecd578-fad4-4e6c-9348-842e3e8fa340 |
| 422 |
state: "closed" |
| 423 |
name: "mycrypt" |
| 424 |
|
| 425 |
- name: Create a container using luks2 format |
| 426 |
community.crypto.luks_device: |
| 427 |
device: "/dev/loop0" |
| 428 |
state: "present" |
| 429 |
keyfile: "/vault/keyfile" |
| 430 |
type: luks2 |
| 431 |
|
| 432 |
- name: Create a container with key in slot 4 |
| 433 |
community.crypto.luks_device: |
| 434 |
device: "/dev/loop0" |
| 435 |
state: "present" |
| 436 |
keyfile: "/vault/keyfile" |
| 437 |
keyslot: 4 |
| 438 |
|
| 439 |
- name: Add a new key in slot 5 |
| 440 |
community.crypto.luks_device: |
| 441 |
device: "/dev/loop0" |
| 442 |
keyfile: "/vault/keyfile" |
| 443 |
new_keyfile: "/vault/keyfile" |
| 444 |
new_keyslot: 5 |
| 445 |
|
| 446 |
- name: Remove the key from slot 4 (given keyfile must not be slot 4) |
| 447 |
community.crypto.luks_device: |
| 448 |
device: "/dev/loop0" |
| 449 |
keyfile: "/vault/keyfile" |
| 450 |
remove_keyslot: 4 |
| 451 |
|
| 452 |
- name: Enroll a TPM2 device using a keyfile to unlock the container |
| 453 |
community.crypto.luks_device: |
| 454 |
keyfile: "/vault/keyfile" |
| 455 |
new_tpm2: "auto" |
| 456 |
new_tpm2_pcrs: "1+3+5+7+11+12+14" |
| 457 |
|
| 458 |
- name: Remove all enrolled TPM2 devices |
| 459 |
community.crypto.luks_device: |
| 460 |
tpm2_device: "auto" |
| 461 |
remove_tpm2: true |
| 462 |
|
| 463 |
- name: Set the priority of keyslot 0 to 'prefer' |
| 464 |
community.crypto.luks_device: |
| 465 |
device: "/dev/loop0" |
| 466 |
keyslot: 0 |
| 467 |
keyslot_priority: prefer |
| 468 |
""" |
| 469 |
|
| 470 |
RETURN = r""" |
| 471 |
name: |
| 472 |
description: When O(state=opened) returns (generated or given) name of LUKS container. Returns None if no name is supplied. |
| 473 |
returned: success |
| 474 |
type: str |
| 475 |
sample: "luks-c1da9a58-2fde-4256-9d9f-6ab008b4dd1b" |
| 476 |
""" |
| 477 |
|
| 478 |
import json |
| 479 |
import os |
| 480 |
import re |
| 481 |
import stat |
| 482 |
import typing as t |
| 483 |
from base64 import b64decode |
| 484 |
|
| 485 |
from ansible.module_utils.basic import AnsibleModule |
| 486 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 487 |
|
| 488 |
# used to get <luks-name> out of lsblk output in format 'crypt <luks-name>' |
| 489 |
# regex takes care of any possible blank characters |
| 490 |
LUKS_NAME_REGEX = re.compile(r"^crypt\s+([^\s]*)\s*$") |
| 491 |
# used to get </luks/device> out of lsblk output |
| 492 |
# in format 'device: </luks/device>' |
| 493 |
LUKS_DEVICE_REGEX = re.compile(r"\s*device:\s+([^\s]*)\s*") |
| 494 |
|
| 495 |
|
| 496 |
# See https://gitlab.com/cryptsetup/cryptsetup/-/wikis/LUKS-standard/on-disk-format.pdf |
| 497 |
LUKS_HEADER = b"LUKS\xba\xbe" |
| 498 |
LUKS_HEADER_L = 6 |
| 499 |
# See https://gitlab.com/cryptsetup/LUKS2-docs/-/blob/master/luks2_doc_wip.pdf |
| 500 |
LUKS2_HEADER_OFFSETS = [ |
| 501 |
0x4000, |
| 502 |
0x8000, |
| 503 |
0x10000, |
| 504 |
0x20000, |
| 505 |
0x40000, |
| 506 |
0x80000, |
| 507 |
0x100000, |
| 508 |
0x200000, |
| 509 |
0x400000, |
| 510 |
] |
| 511 |
LUKS2_HEADER2 = b"SKUL\xba\xbe" |
| 512 |
|
| 513 |
|
| 514 |
def wipe_luks_headers(device: str) -> None: |
| 515 |
wipe_offsets = [] |
| 516 |
with open(device, "rb") as f: |
| 517 |
# f.seek(0) |
| 518 |
data = f.read(LUKS_HEADER_L) |
| 519 |
if data == LUKS_HEADER: |
| 520 |
wipe_offsets.append(0) |
| 521 |
for offset in LUKS2_HEADER_OFFSETS: |
| 522 |
f.seek(offset) |
| 523 |
data = f.read(LUKS_HEADER_L) |
| 524 |
if data == LUKS2_HEADER2: |
| 525 |
wipe_offsets.append(offset) |
| 526 |
|
| 527 |
if wipe_offsets: |
| 528 |
with open(device, "wb") as f: |
| 529 |
for offset in wipe_offsets: |
| 530 |
f.seek(offset) |
| 531 |
f.write(b"\x00\x00\x00\x00\x00\x00") |
| 532 |
|
| 533 |
|
| 534 |
class Handler: |
| 535 |
def __init__(self, module: AnsibleModule) -> None: |
| 536 |
self._module = module |
| 537 |
self._lsblk_bin = self._module.get_bin_path("lsblk", True) |
| 538 |
self._passphrase_encoding = module.params["passphrase_encoding"] |
| 539 |
|
| 540 |
def get_passphrase_from_module_params(self, parameter_name: str) -> bytes | None: |
| 541 |
passphrase = self._module.params[parameter_name] |
| 542 |
if passphrase is None: |
| 543 |
return None |
| 544 |
if self._passphrase_encoding == "text": |
| 545 |
return to_bytes(passphrase) |
| 546 |
try: |
| 547 |
return b64decode(to_text(passphrase)) |
| 548 |
except Exception as exc: |
| 549 |
self._module.fail_json( |
| 550 |
f"Error while base64-decoding '{parameter_name}': {exc}" |
| 551 |
) |
| 552 |
|
| 553 |
def _run_command( |
| 554 |
self, command: list[str], data: bytes | None = None |
| 555 |
) -> tuple[int, str, str]: |
| 556 |
return self._module.run_command(command, data=data, binary_data=True) |
| 557 |
|
| 558 |
def get_device_by_uuid(self, uuid: str | None) -> str | None: |
| 559 |
"""Returns the device that holds UUID passed by user""" |
| 560 |
blkid_bin = self._module.get_bin_path("blkid", True) |
| 561 |
if uuid is None: |
| 562 |
return None |
| 563 |
rc, stdout, dummy = self._run_command([blkid_bin, "--uuid", uuid]) |
| 564 |
if rc != 0: |
| 565 |
return None |
| 566 |
return stdout.strip() |
| 567 |
|
| 568 |
def get_device_by_label(self, label: str) -> str | None: |
| 569 |
"""Returns the device that holds label passed by user""" |
| 570 |
blkid_bin = self._module.get_bin_path("blkid", True) |
| 571 |
rc, stdout, dummy = self._run_command([blkid_bin, "--label", label]) |
| 572 |
if rc != 0: |
| 573 |
return None |
| 574 |
return stdout.strip() |
| 575 |
|
| 576 |
def generate_luks_name(self, device: str) -> str: |
| 577 |
"""Generate name for luks based on device UUID ('luks-<UUID>'). |
| 578 |
Raises ValueError when obtaining of UUID fails. |
| 579 |
""" |
| 580 |
rc, stdout, stderr = self._run_command( |
| 581 |
[self._lsblk_bin, "-n", device, "-o", "UUID"] |
| 582 |
) |
| 583 |
|
| 584 |
if rc != 0: |
| 585 |
raise ValueError(f"Error while generating LUKS name for {device}: {stderr}") |
| 586 |
dev_uuid = stdout.strip() |
| 587 |
return f"luks-{dev_uuid}" |
| 588 |
|
| 589 |
|
| 590 |
class CryptHandler(Handler): |
| 591 |
def __init__(self, module: AnsibleModule) -> None: |
| 592 |
super().__init__(module) |
| 593 |
self._cryptsetup_bin = self._module.get_bin_path("cryptsetup", True) |
| 594 |
|
| 595 |
def get_container_name_by_device(self, device: str) -> str | None: |
| 596 |
"""obtain LUKS container name based on the device where it is located |
| 597 |
return None if not found |
| 598 |
raise ValueError if lsblk command fails |
| 599 |
""" |
| 600 |
rc, stdout, stderr = self._run_command( |
| 601 |
[self._lsblk_bin, device, "-nlo", "type,name"] |
| 602 |
) |
| 603 |
if rc != 0: |
| 604 |
raise ValueError(f"Error while obtaining LUKS name for {device}: {stderr}") |
| 605 |
|
| 606 |
for line in stdout.splitlines(False): |
| 607 |
m = LUKS_NAME_REGEX.match(line) |
| 608 |
if m: |
| 609 |
return m.group(1) |
| 610 |
return None |
| 611 |
|
| 612 |
def get_container_device_by_name(self, name: str) -> str | None: |
| 613 |
"""obtain device name based on the LUKS container name |
| 614 |
return None if not found |
| 615 |
raise ValueError if lsblk command fails |
| 616 |
""" |
| 617 |
# apparently each device can have only one LUKS container on it |
| 618 |
rc, stdout, dummy = self._run_command([self._cryptsetup_bin, "status", name]) |
| 619 |
if rc != 0: |
| 620 |
return None |
| 621 |
|
| 622 |
m = LUKS_DEVICE_REGEX.search(stdout) |
| 623 |
if not m: |
| 624 |
return None |
| 625 |
device = m.group(1) |
| 626 |
return device |
| 627 |
|
| 628 |
def is_luks(self, device: str) -> bool: |
| 629 |
"""check if the LUKS container does exist""" |
| 630 |
rc, dummy, dummy2 = self._run_command([self._cryptsetup_bin, "isLuks", device]) |
| 631 |
return rc == 0 |
| 632 |
|
| 633 |
def get_luks_type(self, device: str) -> t.Literal["luks1", "luks2"] | None: |
| 634 |
"""get the luks type of a device""" |
| 635 |
if self.is_luks(device): |
| 636 |
with open(device, "rb") as f: |
| 637 |
for offset in LUKS2_HEADER_OFFSETS: |
| 638 |
f.seek(offset) |
| 639 |
data = f.read(LUKS_HEADER_L) |
| 640 |
if data == LUKS2_HEADER2: |
| 641 |
return "luks2" |
| 642 |
return "luks1" |
| 643 |
return None |
| 644 |
|
| 645 |
def is_luks_slot_set(self, device: str, keyslot: int) -> bool: |
| 646 |
"""check if a keyslot is set""" |
| 647 |
rc, stdout, dummy = self._run_command( |
| 648 |
[self._cryptsetup_bin, "luksDump", device] |
| 649 |
) |
| 650 |
if rc != 0: |
| 651 |
raise ValueError(f"Error while dumping LUKS header from {device}") |
| 652 |
result_luks1 = f"Key Slot {keyslot}: ENABLED" in stdout |
| 653 |
result_luks2 = f" {keyslot}: luks2" in stdout |
| 654 |
return result_luks1 or result_luks2 |
| 655 |
|
| 656 |
def _add_pbkdf_options(self, options: list[str], pbkdf: dict[str, t.Any]) -> None: |
| 657 |
if pbkdf["iteration_time"] is not None: |
| 658 |
options.extend(["--iter-time", str(int(pbkdf["iteration_time"] * 1000))]) |
| 659 |
if pbkdf["iteration_count"] is not None: |
| 660 |
options.extend(["--pbkdf-force-iterations", str(pbkdf["iteration_count"])]) |
| 661 |
if pbkdf["algorithm"] is not None: |
| 662 |
options.extend(["--pbkdf", pbkdf["algorithm"]]) |
| 663 |
if pbkdf["memory"] is not None: |
| 664 |
options.extend(["--pbkdf-memory", str(pbkdf["memory"])]) |
| 665 |
if pbkdf["parallel"] is not None: |
| 666 |
options.extend(["--pbkdf-parallel", str(pbkdf["parallel"])]) |
| 667 |
|
| 668 |
def run_luks_create( |
| 669 |
self, |
| 670 |
device: str, |
| 671 |
keyfile: str | None, |
| 672 |
passphrase: bytes | None, |
| 673 |
keyslot: int | None, |
| 674 |
keysize: int | None, |
| 675 |
cipher: str | None, |
| 676 |
hash_: str | None, |
| 677 |
sector_size: str | None, |
| 678 |
pbkdf: dict[str, t.Any] | None, |
| 679 |
) -> None: |
| 680 |
# create a new luks container; use batch mode to auto confirm |
| 681 |
luks_type = self._module.params["type"] |
| 682 |
label = self._module.params["label"] |
| 683 |
|
| 684 |
options = [] |
| 685 |
if keysize is not None: |
| 686 |
options.append("--key-size=" + str(keysize)) |
| 687 |
if label is not None: |
| 688 |
options.extend(["--label", label]) |
| 689 |
luks_type = "luks2" |
| 690 |
if luks_type is not None: |
| 691 |
options.extend(["--type", luks_type]) |
| 692 |
if cipher is not None: |
| 693 |
options.extend(["--cipher", cipher]) |
| 694 |
if hash_ is not None: |
| 695 |
options.extend(["--hash", hash_]) |
| 696 |
if pbkdf is not None: |
| 697 |
self._add_pbkdf_options(options, pbkdf) |
| 698 |
if sector_size is not None: |
| 699 |
options.extend(["--sector-size", str(sector_size)]) |
| 700 |
if keyslot is not None: |
| 701 |
options.extend(["--key-slot", str(keyslot)]) |
| 702 |
|
| 703 |
args = [self._cryptsetup_bin, "luksFormat"] |
| 704 |
args.extend(options) |
| 705 |
args.extend(["-q", device]) |
| 706 |
if keyfile: |
| 707 |
args.append(keyfile) |
| 708 |
else: |
| 709 |
args.append("-") |
| 710 |
|
| 711 |
rc, dummy, stderr = self._run_command(args, data=passphrase) |
| 712 |
if rc != 0: |
| 713 |
raise ValueError(f"Error while creating LUKS on {device}: {stderr}") |
| 714 |
|
| 715 |
def run_luks_open( |
| 716 |
self, |
| 717 |
device: str, |
| 718 |
keyfile: str | None, |
| 719 |
passphrase: bytes | None, |
| 720 |
perf_same_cpu_crypt: bool, |
| 721 |
perf_submit_from_crypt_cpus: bool, |
| 722 |
perf_no_read_workqueue: bool, |
| 723 |
perf_no_write_workqueue: bool, |
| 724 |
persistent: bool, |
| 725 |
allow_discards: bool, |
| 726 |
name: str, |
| 727 |
) -> None: |
| 728 |
args = [self._cryptsetup_bin] |
| 729 |
if keyfile: |
| 730 |
args.extend(["--key-file", keyfile]) |
| 731 |
else: |
| 732 |
args.extend(["--key-file", "-"]) |
| 733 |
if perf_same_cpu_crypt: |
| 734 |
args.extend(["--perf-same_cpu_crypt"]) |
| 735 |
if perf_submit_from_crypt_cpus: |
| 736 |
args.extend(["--perf-submit_from_crypt_cpus"]) |
| 737 |
if perf_no_read_workqueue: |
| 738 |
args.extend(["--perf-no_read_workqueue"]) |
| 739 |
if perf_no_write_workqueue: |
| 740 |
args.extend(["--perf-no_write_workqueue"]) |
| 741 |
if persistent: |
| 742 |
args.extend(["--persistent"]) |
| 743 |
if allow_discards: |
| 744 |
args.extend(["--allow-discards"]) |
| 745 |
args.extend(["open", "--type", "luks", device, name]) |
| 746 |
|
| 747 |
rc, dummy, stderr = self._run_command(args, data=passphrase) |
| 748 |
if rc != 0: |
| 749 |
raise ValueError( |
| 750 |
f"Error while opening LUKS container on {device}: {stderr}" |
| 751 |
) |
| 752 |
|
| 753 |
def run_luks_close(self, name: str) -> None: |
| 754 |
rc, dummy, dummy2 = self._run_command([self._cryptsetup_bin, "close", name]) |
| 755 |
if rc != 0: |
| 756 |
raise ValueError(f"Error while closing LUKS container {name}") |
| 757 |
|
| 758 |
def run_luks_remove(self, device: str) -> None: |
| 759 |
wipefs_bin = self._module.get_bin_path("wipefs", True) |
| 760 |
|
| 761 |
name = self.get_container_name_by_device(device) |
| 762 |
if name is not None: |
| 763 |
self.run_luks_close(name) |
| 764 |
rc, dummy, stderr = self._run_command([wipefs_bin, "--all", device]) |
| 765 |
if rc != 0: |
| 766 |
raise ValueError( |
| 767 |
f"Error while wiping LUKS container signatures for {device}: {stderr}" |
| 768 |
) |
| 769 |
|
| 770 |
# For LUKS2, sometimes both `cryptsetup erase` and `wipefs` do **not** |
| 771 |
# erase all LUKS signatures (they seem to miss the second header). That's |
| 772 |
# why we do it ourselves here. |
| 773 |
try: |
| 774 |
wipe_luks_headers(device) |
| 775 |
except Exception as exc: |
| 776 |
raise ValueError( |
| 777 |
f"Error while wiping LUKS container signatures for {device}: {exc}" |
| 778 |
) from exc |
| 779 |
|
| 780 |
def run_luks_add_key( |
| 781 |
self, |
| 782 |
device: str, |
| 783 |
keyfile: str | None, |
| 784 |
passphrase: bytes | None, |
| 785 |
new_keyfile: str | None, |
| 786 |
new_passphrase: bytes | None, |
| 787 |
new_keyslot: int | None, |
| 788 |
pbkdf: dict[str, t.Any] | None, |
| 789 |
) -> None: |
| 790 |
"""Add new key from a keyfile or passphrase to given 'device'; |
| 791 |
authentication done using 'keyfile' or 'passphrase'. |
| 792 |
Raises ValueError when command fails. |
| 793 |
""" |
| 794 |
data = [] |
| 795 |
args = [self._cryptsetup_bin, "luksAddKey", device] |
| 796 |
if pbkdf is not None: |
| 797 |
self._add_pbkdf_options(args, pbkdf) |
| 798 |
|
| 799 |
if new_keyslot is not None: |
| 800 |
args.extend(["--key-slot", str(new_keyslot)]) |
| 801 |
|
| 802 |
if keyfile: |
| 803 |
args.extend(["--key-file", keyfile]) |
| 804 |
elif passphrase is not None: |
| 805 |
args.extend(["--key-file", "-", "--keyfile-size", str(len(passphrase))]) |
| 806 |
data.append(passphrase) |
| 807 |
else: |
| 808 |
raise ValueError("Need passphrase or keyfile") |
| 809 |
|
| 810 |
if new_keyfile: |
| 811 |
args.append(new_keyfile) |
| 812 |
elif new_passphrase is not None: |
| 813 |
args.append("-") |
| 814 |
data.append(new_passphrase) |
| 815 |
else: |
| 816 |
raise ValueError("Need new passphrase or new keyfile") |
| 817 |
|
| 818 |
rc, dummy, stderr = self._run_command(args, data=b"".join(data) or None) |
| 819 |
if rc != 0: |
| 820 |
raise ValueError( |
| 821 |
f"Error while adding new LUKS keyslot to {device}: {stderr}" |
| 822 |
) |
| 823 |
|
| 824 |
def run_luks_remove_key( |
| 825 |
self, |
| 826 |
device: str, |
| 827 |
keyfile: str | None, |
| 828 |
passphrase: bytes | None, |
| 829 |
keyslot: int | None, |
| 830 |
force_remove_last_key: bool = False, |
| 831 |
) -> None: |
| 832 |
"""Remove key from given device |
| 833 |
Raises ValueError when command fails |
| 834 |
""" |
| 835 |
if not force_remove_last_key: |
| 836 |
rc, stdout, dummy = self._run_command( |
| 837 |
[self._cryptsetup_bin, "luksDump", device] |
| 838 |
) |
| 839 |
if rc != 0: |
| 840 |
raise ValueError(f"Error while dumping LUKS header from {device}") |
| 841 |
keyslot_count = 0 |
| 842 |
keyslot_area = False |
| 843 |
keyslot_re = re.compile(r"^Key Slot [0-9]+: ENABLED") |
| 844 |
for line in stdout.splitlines(): |
| 845 |
if line.startswith("Keyslots:"): |
| 846 |
keyslot_area = True |
| 847 |
elif line.startswith(" "): |
| 848 |
# LUKS2 header dumps use human-readable indented output. |
| 849 |
# Thus we have to look out for 'Keyslots:' and count the |
| 850 |
# number of indented keyslot numbers. |
| 851 |
if keyslot_area and line[2] in "0123456789": |
| 852 |
keyslot_count += 1 |
| 853 |
elif line.startswith("\t"): |
| 854 |
pass |
| 855 |
elif keyslot_re.match(line): |
| 856 |
# LUKS1 header dumps have one line per keyslot with ENABLED |
| 857 |
# or DISABLED in them. We count such lines with ENABLED. |
| 858 |
keyslot_count += 1 |
| 859 |
else: |
| 860 |
keyslot_area = False |
| 861 |
if keyslot_count < 2: |
| 862 |
self._module.fail_json( |
| 863 |
msg=f"LUKS device {device} has less than two active keyslots. To be able to remove a key, please set `force_remove_last_key` to `true`." |
| 864 |
) |
| 865 |
|
| 866 |
if keyslot is None: |
| 867 |
args = [self._cryptsetup_bin, "luksRemoveKey", device, "-q"] |
| 868 |
if keyfile: |
| 869 |
args.extend(["--key-file", keyfile]) |
| 870 |
elif passphrase is not None: |
| 871 |
args.extend(["--key-file", "-"]) |
| 872 |
else: |
| 873 |
# Since we supply -q no passphrase is needed |
| 874 |
args = [self._cryptsetup_bin, "luksKillSlot", device, "-q", str(keyslot)] |
| 875 |
passphrase = None |
| 876 |
rc, dummy, stderr = self._run_command(args, data=passphrase) |
| 877 |
if rc != 0: |
| 878 |
raise ValueError(f"Error while removing LUKS key from {device}: {stderr}") |
| 879 |
|
| 880 |
def luks_test_key( |
| 881 |
self, |
| 882 |
device: str, |
| 883 |
keyfile: str | None, |
| 884 |
passphrase: bytes | None, |
| 885 |
keyslot: int | None = None, |
| 886 |
) -> bool: |
| 887 |
"""Check whether the keyfile or passphrase works. |
| 888 |
Raises ValueError when command fails. |
| 889 |
""" |
| 890 |
data = None |
| 891 |
args = [self._cryptsetup_bin, "luksOpen", "--test-passphrase", device] |
| 892 |
|
| 893 |
if keyfile: |
| 894 |
args.extend(["--key-file", keyfile]) |
| 895 |
else: |
| 896 |
args.extend(["--key-file", "-"]) |
| 897 |
data = passphrase |
| 898 |
|
| 899 |
if keyslot is not None: |
| 900 |
args.extend(["--key-slot", str(keyslot)]) |
| 901 |
|
| 902 |
rc, stdout, stderr = self._run_command(args, data=data) |
| 903 |
if rc == 0: |
| 904 |
return True |
| 905 |
for output in (stdout, stderr): |
| 906 |
if "No key available with this passphrase" in output: |
| 907 |
return False |
| 908 |
if "No usable keyslot is available." in output: |
| 909 |
return False |
| 910 |
|
| 911 |
# This check is necessary due to cryptsetup in version 2.0.3 not printing 'No usable keyslot is available' |
| 912 |
# when using the --key-slot parameter in combination with --test-passphrase |
| 913 |
if rc == 1 and keyslot is not None and stdout == "" and stderr == "": |
| 914 |
return False |
| 915 |
|
| 916 |
raise ValueError( |
| 917 |
f"Error while testing whether keyslot exists on {device}: {stderr}" |
| 918 |
) |
| 919 |
|
| 920 |
def luks_dump_json_metadata(self, device: str) -> dict: |
| 921 |
"""Dump LUKS metadata in JSON format. |
| 922 |
Raises ValueError when command fails. |
| 923 |
""" |
| 924 |
rc, stdout, stderr = self._run_command( |
| 925 |
[self._cryptsetup_bin, "luksDump", "--dump-json-metadata", device] |
| 926 |
) |
| 927 |
if rc != 0: |
| 928 |
raise ValueError( |
| 929 |
f"Error while dumping LUKS JSON metadata from {device}: {stderr}" |
| 930 |
) |
| 931 |
|
| 932 |
return json.loads(stdout) |
| 933 |
|
| 934 |
def run_config(self, device: str, keyslot: int, keyslot_priority: str) -> None: |
| 935 |
"""Configure LUKS keyslot priority. |
| 936 |
Raises ValueError when command fails. |
| 937 |
""" |
| 938 |
rc, dummy, stderr = self._run_command( |
| 939 |
[ |
| 940 |
self._cryptsetup_bin, |
| 941 |
"config", |
| 942 |
f"--key-slot={keyslot}", |
| 943 |
f"--priority={keyslot_priority}", |
| 944 |
device, |
| 945 |
] |
| 946 |
) |
| 947 |
if rc != 0: |
| 948 |
raise ValueError( |
| 949 |
f"Error while configuring LUKS keyslot {keyslot} on {device}: {stderr}" |
| 950 |
) |
| 951 |
|
| 952 |
def run_systemd_cryptsetup_attach( |
| 953 |
self, |
| 954 |
device: str, |
| 955 |
tpm2_device: str | None, |
| 956 |
perf_same_cpu_crypt: bool, |
| 957 |
perf_submit_from_crypt_cpus: bool, |
| 958 |
perf_no_read_workqueue: bool, |
| 959 |
perf_no_write_workqueue: bool, |
| 960 |
allow_discards: bool, |
| 961 |
name: str, |
| 962 |
) -> None: |
| 963 |
systemd_cryptsetup_bin = self._module.get_bin_path( |
| 964 |
"systemd-cryptsetup", required=True |
| 965 |
) |
| 966 |
args = [systemd_cryptsetup_bin, name, device, "none"] |
| 967 |
options = [] |
| 968 |
|
| 969 |
if tpm2_device is not None: |
| 970 |
options.append(f"tpm2-device={tpm2_device}") |
| 971 |
|
| 972 |
if perf_same_cpu_crypt: |
| 973 |
options.append("same-cpu-crypt") |
| 974 |
|
| 975 |
if perf_submit_from_crypt_cpus: |
| 976 |
options.append("submit-from-crypt-cpus") |
| 977 |
|
| 978 |
if perf_no_read_workqueue: |
| 979 |
options.append("no-read-workqueue") |
| 980 |
|
| 981 |
if perf_no_write_workqueue: |
| 982 |
options.append("no-write-workqueue") |
| 983 |
|
| 984 |
if allow_discards: |
| 985 |
options.append("discard") |
| 986 |
|
| 987 |
args.append(",".join(options)) |
| 988 |
|
| 989 |
rc, dummy, stderr = self._run_command(args) |
| 990 |
|
| 991 |
if rc != 0: |
| 992 |
raise ValueError(f"Error while opening {device}: {stderr}") |
| 993 |
|
| 994 |
def run_systemd_cryptenroll( |
| 995 |
self, |
| 996 |
device: str, |
| 997 |
keyfile: str | None, |
| 998 |
passphrase: bytes | None, |
| 999 |
tpm2_device: str | None, |
| 1000 |
new_tpm2: str | None, |
| 1001 |
new_tpm2_pcrs: str | None, |
| 1002 |
remove_tpm2: bool, |
| 1003 |
) -> bool: |
| 1004 |
systemd_cryptenroll_bin = self._module.get_bin_path( |
| 1005 |
"systemd-cryptenroll", required=True |
| 1006 |
) |
| 1007 |
args = [systemd_cryptenroll_bin] |
| 1008 |
|
| 1009 |
if keyfile is not None: |
| 1010 |
args.append(f"--unlock-key-file={keyfile}") |
| 1011 |
|
| 1012 |
if tpm2_device: |
| 1013 |
args.append(f"--unlock-tpm2-device={tpm2_device}") |
| 1014 |
|
| 1015 |
if new_tpm2: |
| 1016 |
args.extend([f"--tpm2-device={new_tpm2}", f"--tpm2-pcrs={new_tpm2_pcrs}"]) |
| 1017 |
|
| 1018 |
if remove_tpm2: |
| 1019 |
args.append("--wipe-slot=tpm2") |
| 1020 |
|
| 1021 |
if passphrase: |
| 1022 |
# --unlock-key-file is needed both so a newline isnt required at the end of stdin |
| 1023 |
# and also because otherwise, systemd-cryptenroll will just hang if the passphrase is wrong, |
| 1024 |
# waiting for the user to input another one |
| 1025 |
rc, dummy, stderr = self._run_command( |
| 1026 |
[*args, "--unlock-key-file=/dev/stdin", device], data=passphrase |
| 1027 |
) |
| 1028 |
else: |
| 1029 |
rc, dummy, stderr = self._run_command([*args, device]) |
| 1030 |
|
| 1031 |
if rc != 0: |
| 1032 |
raise ValueError( |
| 1033 |
f"Error while adding key to {device} with {args}: {stderr}" |
| 1034 |
) |
| 1035 |
|
| 1036 |
# systemd-cryptenroll stores a policy hash in the LUKS metadata which is used to |
| 1037 |
# detect if a TPM2 device and PCR set are already enrolled. Computing it |
| 1038 |
# is very complicated, however, so rather than duplicating all of that here, |
| 1039 |
# we rely on the command's output which hopefully won't change. |
| 1040 |
# See: https://github.com/systemd/systemd/blob/7524671f74c9b0ea858a077ae9b1af3fe574d57e/src/cryptenroll/cryptenroll-tpm2.c#L529-L541 |
| 1041 |
return "This PCR set is already enrolled, executing no operation." not in stderr |
| 1042 |
|
| 1043 |
|
| 1044 |
class ConditionsHandler(Handler): |
| 1045 |
def __init__(self, module: AnsibleModule, crypthandler: CryptHandler) -> None: |
| 1046 |
super().__init__(module) |
| 1047 |
self._crypthandler = crypthandler |
| 1048 |
self.device = self.get_device_name() |
| 1049 |
|
| 1050 |
def get_device_name(self) -> str | None: |
| 1051 |
device: str | None = self._module.params.get("device") |
| 1052 |
label: str | None = self._module.params.get("label") |
| 1053 |
uuid: str | None = self._module.params.get("uuid") |
| 1054 |
name: str | None = self._module.params.get("name") |
| 1055 |
|
| 1056 |
if device is None and label is not None: |
| 1057 |
device = self.get_device_by_label(label) |
| 1058 |
elif device is None and uuid is not None: |
| 1059 |
device = self.get_device_by_uuid(uuid) |
| 1060 |
elif device is None and name is not None: |
| 1061 |
device = self._crypthandler.get_container_device_by_name(name) |
| 1062 |
|
| 1063 |
return device |
| 1064 |
|
| 1065 |
def luks_create(self) -> bool: |
| 1066 |
if ( |
| 1067 |
self.device is not None |
| 1068 |
and self._module.params["state"] in ("present", "opened", "closed") |
| 1069 |
and not self._crypthandler.is_luks(self.device) |
| 1070 |
): |
| 1071 |
|
| 1072 |
if ( |
| 1073 |
self._module.params["keyfile"] is None |
| 1074 |
and self._module.params["passphrase"] is None |
| 1075 |
): |
| 1076 |
|
| 1077 |
self._module.fail_json( |
| 1078 |
msg="Neither keyfile nor passphrase were given but the LUKS volume must be created" |
| 1079 |
) |
| 1080 |
|
| 1081 |
return True |
| 1082 |
|
| 1083 |
return False |
| 1084 |
|
| 1085 |
def opened_luks_name(self, device: str) -> str | None: |
| 1086 |
"""If luks is already opened, return its name. |
| 1087 |
If 'name' parameter is specified and differs |
| 1088 |
from obtained value, fail. |
| 1089 |
Return None otherwise |
| 1090 |
""" |
| 1091 |
if self._module.params["state"] != "opened": |
| 1092 |
return None |
| 1093 |
|
| 1094 |
# try to obtain luks name - it may be already opened |
| 1095 |
name = self._crypthandler.get_container_name_by_device(device) |
| 1096 |
|
| 1097 |
if name is None: |
| 1098 |
# container is not open |
| 1099 |
return None |
| 1100 |
|
| 1101 |
if self._module.params["name"] is None: |
| 1102 |
# container is already opened |
| 1103 |
return name |
| 1104 |
|
| 1105 |
if name != self._module.params["name"]: |
| 1106 |
# the container is already open but with different name: |
| 1107 |
# suspicious. back off |
| 1108 |
self._module.fail_json( |
| 1109 |
msg=f"LUKS container is already opened under different name '{name}'." |
| 1110 |
) |
| 1111 |
|
| 1112 |
# container is opened and the names match |
| 1113 |
return name |
| 1114 |
|
| 1115 |
def luks_open(self) -> bool: |
| 1116 |
if self.device is None or self._module.params["state"] != "opened": |
| 1117 |
# conditions for open not fulfilled |
| 1118 |
return False |
| 1119 |
|
| 1120 |
if ( |
| 1121 |
self._module.params["keyfile"] is None |
| 1122 |
and self._module.params["passphrase"] is None |
| 1123 |
and self._module.params["tpm2_device"] is None |
| 1124 |
): |
| 1125 |
self._module.fail_json( |
| 1126 |
msg="state=opened was specified but none of keyfile, passphrase, or tpm2_device were given" |
| 1127 |
) |
| 1128 |
|
| 1129 |
name = self.opened_luks_name(self.device) |
| 1130 |
|
| 1131 |
return name is None |
| 1132 |
|
| 1133 |
def luks_close(self) -> bool: |
| 1134 |
if ( |
| 1135 |
self._module.params["name"] is None and self.device is None |
| 1136 |
) or self._module.params["state"] != "closed": |
| 1137 |
# conditions for close not fulfilled |
| 1138 |
return False |
| 1139 |
luks_is_open = False |
| 1140 |
|
| 1141 |
if self.device is not None: |
| 1142 |
name = self._crypthandler.get_container_name_by_device(self.device) |
| 1143 |
# successfully getting name based on device means that luks is open |
| 1144 |
luks_is_open = name is not None |
| 1145 |
|
| 1146 |
if self._module.params["name"] is not None: |
| 1147 |
device = self._crypthandler.get_container_device_by_name( |
| 1148 |
self._module.params["name"] |
| 1149 |
) |
| 1150 |
# successfully getting device based on name means that luks is open |
| 1151 |
luks_is_open = device is not None |
| 1152 |
if device is not None: |
| 1153 |
self.device = device |
| 1154 |
|
| 1155 |
return luks_is_open |
| 1156 |
|
| 1157 |
def luks_add_key(self) -> bool: |
| 1158 |
if ( |
| 1159 |
self.device is None |
| 1160 |
or ( |
| 1161 |
self._module.params["keyfile"] is None |
| 1162 |
and self._module.params["passphrase"] is None |
| 1163 |
) |
| 1164 |
or ( |
| 1165 |
self._module.params["new_keyfile"] is None |
| 1166 |
and self._module.params["new_passphrase"] is None |
| 1167 |
) |
| 1168 |
): |
| 1169 |
# conditions for adding a key not fulfilled |
| 1170 |
return False |
| 1171 |
|
| 1172 |
if self._module.params["state"] == "absent": |
| 1173 |
self._module.fail_json( |
| 1174 |
msg="Contradiction in setup: Asking to add a key to absent LUKS." |
| 1175 |
) |
| 1176 |
|
| 1177 |
key_present = self._crypthandler.luks_test_key( |
| 1178 |
self.device, |
| 1179 |
self._module.params["new_keyfile"], |
| 1180 |
self.get_passphrase_from_module_params("new_passphrase"), |
| 1181 |
) |
| 1182 |
if self._module.params["new_keyslot"] is not None: |
| 1183 |
key_present_slot = self._crypthandler.luks_test_key( |
| 1184 |
self.device, |
| 1185 |
self._module.params["new_keyfile"], |
| 1186 |
self.get_passphrase_from_module_params("new_passphrase"), |
| 1187 |
self._module.params["new_keyslot"], |
| 1188 |
) |
| 1189 |
if key_present and not key_present_slot: |
| 1190 |
self._module.fail_json( |
| 1191 |
msg="Trying to add key that is already present in another slot" |
| 1192 |
) |
| 1193 |
|
| 1194 |
return not key_present |
| 1195 |
|
| 1196 |
def luks_remove_key(self) -> bool: |
| 1197 |
if self.device is None or ( |
| 1198 |
self._module.params["remove_keyfile"] is None |
| 1199 |
and self._module.params["remove_passphrase"] is None |
| 1200 |
and self._module.params["remove_keyslot"] is None |
| 1201 |
): |
| 1202 |
# conditions for removing a key not fulfilled |
| 1203 |
return False |
| 1204 |
|
| 1205 |
if self._module.params["state"] == "absent": |
| 1206 |
self._module.fail_json( |
| 1207 |
msg="Contradiction in setup: Asking to remove a key from absent LUKS." |
| 1208 |
) |
| 1209 |
|
| 1210 |
if self._module.params["remove_keyslot"] is not None: |
| 1211 |
if not self._crypthandler.is_luks_slot_set( |
| 1212 |
self.device, self._module.params["remove_keyslot"] |
| 1213 |
): |
| 1214 |
return False |
| 1215 |
result = self._crypthandler.luks_test_key( |
| 1216 |
self.device, |
| 1217 |
self._module.params["keyfile"], |
| 1218 |
self.get_passphrase_from_module_params("passphrase"), |
| 1219 |
) |
| 1220 |
if self._crypthandler.luks_test_key( |
| 1221 |
self.device, |
| 1222 |
self._module.params["keyfile"], |
| 1223 |
self.get_passphrase_from_module_params("passphrase"), |
| 1224 |
self._module.params["remove_keyslot"], |
| 1225 |
): |
| 1226 |
self._module.fail_json( |
| 1227 |
msg="Cannot remove keyslot with keyfile or passphrase in same slot." |
| 1228 |
) |
| 1229 |
return result |
| 1230 |
|
| 1231 |
return self._crypthandler.luks_test_key( |
| 1232 |
self.device, |
| 1233 |
self._module.params["remove_keyfile"], |
| 1234 |
self.get_passphrase_from_module_params("remove_passphrase"), |
| 1235 |
) |
| 1236 |
|
| 1237 |
def luks_remove(self) -> bool: |
| 1238 |
return ( |
| 1239 |
self.device is not None |
| 1240 |
and self._module.params["state"] == "absent" |
| 1241 |
and self._crypthandler.is_luks(self.device) |
| 1242 |
) |
| 1243 |
|
| 1244 |
def luks_config(self) -> bool: |
| 1245 |
if self.device is None or self._module.params["keyslot_priority"] is None: |
| 1246 |
return False |
| 1247 |
|
| 1248 |
if self._module.params["keyslot"] is None: |
| 1249 |
self._module.fail_json( |
| 1250 |
msg="keyslot_priority was specified but keyslot was not." |
| 1251 |
) |
| 1252 |
|
| 1253 |
json_metadata = self._crypthandler.luks_dump_json_metadata(self.device) |
| 1254 |
slot_priority = ( |
| 1255 |
json_metadata.get("keyslots", {}) |
| 1256 |
.get(str(self._module.params["keyslot"]), {}) |
| 1257 |
.get("priority", None) |
| 1258 |
) |
| 1259 |
|
| 1260 |
priority_map = {"prefer": 2, "normal": None, "ignore": 0} |
| 1261 |
return slot_priority != priority_map[self._module.params["keyslot_priority"]] |
| 1262 |
|
| 1263 |
def validate_keyslot( |
| 1264 |
self, param: str, luks_type: t.Literal["luks1", "luks2"] | None |
| 1265 |
) -> None: |
| 1266 |
if self._module.params[param] is not None: |
| 1267 |
if luks_type is None and param == "keyslot": |
| 1268 |
if 8 <= self._module.params[param] <= 31: |
| 1269 |
self._module.fail_json( |
| 1270 |
msg="You must specify type=luks2 when creating a new LUKS device to use keyslots 8-31." |
| 1271 |
) |
| 1272 |
elif not (0 <= self._module.params[param] <= 7): |
| 1273 |
self._module.fail_json( |
| 1274 |
msg="When not specifying a type, only the keyslots 0-7 are allowed." |
| 1275 |
) |
| 1276 |
|
| 1277 |
if luks_type == "luks1" and not 0 <= self._module.params[param] <= 7: |
| 1278 |
self._module.fail_json( |
| 1279 |
msg=f"{self._module.params[param]} must be between 0 and 7 when using LUKS1." |
| 1280 |
) |
| 1281 |
elif luks_type == "luks2" and not 0 <= self._module.params[param] <= 31: |
| 1282 |
self._module.fail_json( |
| 1283 |
msg=f"{self._module.params[param]} must be between 0 and 31 when using LUKS2." |
| 1284 |
) |
| 1285 |
|
| 1286 |
def systemd_cryptenroll(self) -> bool: |
| 1287 |
if self.device is None: |
| 1288 |
return False |
| 1289 |
|
| 1290 |
if ( |
| 1291 |
self._module.params["new_tpm2"] is not None |
| 1292 |
and self._module.params["new_tpm2_pcrs"] is None |
| 1293 |
): |
| 1294 |
self._module.fail_json(msg="new_tpm2_pcrs must be specified with new_tpm2") |
| 1295 |
|
| 1296 |
if self._module.params["remove_tpm2"]: |
| 1297 |
json_metadata = self._crypthandler.luks_dump_json_metadata(self.device) |
| 1298 |
tokens = json_metadata.get("tokens", {}) |
| 1299 |
tpm2_enrolled = any( |
| 1300 |
token.get("type") == "systemd-tpm2" for token in tokens.values() |
| 1301 |
) |
| 1302 |
return tpm2_enrolled or self._module.params["new_tpm2"] is not None |
| 1303 |
|
| 1304 |
return self._module.params["new_tpm2"] is not None |
| 1305 |
|
| 1306 |
|
| 1307 |
def run_module() -> t.NoReturn: # noqa: C901 |
| 1308 |
# available arguments/parameters that a user can pass |
| 1309 |
module_args = { |
| 1310 |
"state": { |
| 1311 |
"type": "str", |
| 1312 |
"default": "present", |
| 1313 |
"choices": ["present", "absent", "opened", "closed"], |
| 1314 |
}, |
| 1315 |
"device": {"type": "str"}, |
| 1316 |
"name": {"type": "str"}, |
| 1317 |
"keyfile": {"type": "path"}, |
| 1318 |
"new_keyfile": {"type": "path"}, |
| 1319 |
"remove_keyfile": {"type": "path"}, |
| 1320 |
"passphrase": {"type": "str", "no_log": True}, |
| 1321 |
"new_passphrase": {"type": "str", "no_log": True}, |
| 1322 |
"remove_passphrase": {"type": "str", "no_log": True}, |
| 1323 |
"tpm2_device": {"type": "str"}, |
| 1324 |
"new_tpm2": {"type": "str"}, |
| 1325 |
"new_tpm2_pcrs": {"type": "str"}, |
| 1326 |
"remove_tpm2": {"type": "bool", "default": False}, |
| 1327 |
"passphrase_encoding": { |
| 1328 |
"type": "str", |
| 1329 |
"default": "text", |
| 1330 |
"choices": ["text", "base64"], |
| 1331 |
"no_log": False, |
| 1332 |
}, |
| 1333 |
"keyslot": {"type": "int", "no_log": False}, |
| 1334 |
"keyslot_priority": { |
| 1335 |
"type": "str", |
| 1336 |
"no_log": False, |
| 1337 |
"choices": ["prefer", "normal", "ignore"], |
| 1338 |
}, |
| 1339 |
"new_keyslot": {"type": "int", "no_log": False}, |
| 1340 |
"remove_keyslot": {"type": "int", "no_log": False}, |
| 1341 |
"force_remove_last_key": {"type": "bool", "default": False}, |
| 1342 |
"keysize": {"type": "int"}, |
| 1343 |
"label": {"type": "str"}, |
| 1344 |
"uuid": {"type": "str"}, |
| 1345 |
"type": {"type": "str", "choices": ["luks1", "luks2"]}, |
| 1346 |
"cipher": {"type": "str"}, |
| 1347 |
"hash": {"type": "str"}, |
| 1348 |
"pbkdf": { |
| 1349 |
"type": "dict", |
| 1350 |
"options": { |
| 1351 |
"iteration_time": {"type": "float"}, |
| 1352 |
"iteration_count": {"type": "int"}, |
| 1353 |
"algorithm": { |
| 1354 |
"type": "str", |
| 1355 |
"choices": ["argon2i", "argon2id", "pbkdf2"], |
| 1356 |
}, |
| 1357 |
"memory": {"type": "int"}, |
| 1358 |
"parallel": {"type": "int"}, |
| 1359 |
}, |
| 1360 |
"mutually_exclusive": [("iteration_time", "iteration_count")], |
| 1361 |
}, |
| 1362 |
"sector_size": {"type": "int"}, |
| 1363 |
"perf_same_cpu_crypt": {"type": "bool", "default": False}, |
| 1364 |
"perf_submit_from_crypt_cpus": {"type": "bool", "default": False}, |
| 1365 |
"perf_no_read_workqueue": {"type": "bool", "default": False}, |
| 1366 |
"perf_no_write_workqueue": {"type": "bool", "default": False}, |
| 1367 |
"persistent": {"type": "bool", "default": False}, |
| 1368 |
"allow_discards": {"type": "bool", "default": False}, |
| 1369 |
} |
| 1370 |
|
| 1371 |
mutually_exclusive = [ |
| 1372 |
("keyfile", "passphrase", "tpm2_device"), |
| 1373 |
("new_keyfile", "new_passphrase"), |
| 1374 |
("remove_keyfile", "remove_passphrase", "remove_keyslot"), |
| 1375 |
] |
| 1376 |
|
| 1377 |
required_by = { |
| 1378 |
"new_tpm2": ["new_tpm2_pcrs"], |
| 1379 |
"keyslot_priority": ["keyslot"], |
| 1380 |
} |
| 1381 |
|
| 1382 |
# seed the result dict in the object |
| 1383 |
result: dict[str, t.Any] = {"changed": False, "name": None} |
| 1384 |
|
| 1385 |
module = AnsibleModule( |
| 1386 |
argument_spec=module_args, |
| 1387 |
supports_check_mode=True, |
| 1388 |
mutually_exclusive=mutually_exclusive, |
| 1389 |
required_by=required_by, |
| 1390 |
) |
| 1391 |
module.run_command_environ_update = { |
| 1392 |
"LANG": "C", |
| 1393 |
"LC_ALL": "C", |
| 1394 |
"LC_MESSAGES": "C", |
| 1395 |
"LC_CTYPE": "C", |
| 1396 |
} |
| 1397 |
|
| 1398 |
if module.params["device"] is not None: |
| 1399 |
try: |
| 1400 |
statinfo = os.stat(module.params["device"]) |
| 1401 |
mode = statinfo.st_mode |
| 1402 |
if not stat.S_ISBLK(mode) and not stat.S_ISCHR(mode): |
| 1403 |
raise Exception(f"{module.params['device']} is not a device") |
| 1404 |
except Exception as e: |
| 1405 |
module.fail_json(msg=str(e)) |
| 1406 |
|
| 1407 |
# conditions not allowed to run |
| 1408 |
if module.params["label"] is not None and module.params["type"] == "luks1": |
| 1409 |
module.fail_json(msg="You cannot combine type luks1 with the label option.") |
| 1410 |
|
| 1411 |
crypt = CryptHandler(module) |
| 1412 |
try: |
| 1413 |
conditions = ConditionsHandler(module, crypt) |
| 1414 |
except ValueError as exc: |
| 1415 |
module.fail_json(msg=str(exc)) |
| 1416 |
|
| 1417 |
if ( |
| 1418 |
module.params["keyslot"] is not None |
| 1419 |
or module.params["new_keyslot"] is not None |
| 1420 |
or module.params["remove_keyslot"] is not None |
| 1421 |
): |
| 1422 |
luks_type = ( |
| 1423 |
crypt.get_luks_type(conditions.device) |
| 1424 |
if conditions.device is not None |
| 1425 |
else None |
| 1426 |
) |
| 1427 |
if luks_type is None and module.params["type"] is not None: |
| 1428 |
luks_type = module.params["type"] |
| 1429 |
for param in ["keyslot", "new_keyslot", "remove_keyslot"]: |
| 1430 |
conditions.validate_keyslot(param, luks_type) |
| 1431 |
|
| 1432 |
for param in ["new_keyslot", "remove_keyslot"]: |
| 1433 |
if ( |
| 1434 |
module.params[param] is not None |
| 1435 |
and module.params["keyfile"] is None |
| 1436 |
and module.params["passphrase"] is None |
| 1437 |
): |
| 1438 |
module.fail_json( |
| 1439 |
msg="Removing a keyslot requires the passphrase or keyfile of another slot." |
| 1440 |
) |
| 1441 |
|
| 1442 |
# The conditions are in order to allow more operations in one run. |
| 1443 |
# (e.g. create luks and add a key to it) |
| 1444 |
|
| 1445 |
# luks create |
| 1446 |
if conditions.luks_create(): |
| 1447 |
assert conditions.device # ensured in conditions.luks_create() |
| 1448 |
if not module.check_mode: |
| 1449 |
try: |
| 1450 |
crypt.run_luks_create( |
| 1451 |
conditions.device, |
| 1452 |
module.params["keyfile"], |
| 1453 |
conditions.get_passphrase_from_module_params("passphrase"), |
| 1454 |
module.params["keyslot"], |
| 1455 |
module.params["keysize"], |
| 1456 |
module.params["cipher"], |
| 1457 |
module.params["hash"], |
| 1458 |
module.params["sector_size"], |
| 1459 |
module.params["pbkdf"], |
| 1460 |
) |
| 1461 |
except ValueError as e: |
| 1462 |
module.fail_json(msg=f"luks_device error: {e}") |
| 1463 |
result["changed"] = True |
| 1464 |
if module.check_mode: |
| 1465 |
module.exit_json(**result) |
| 1466 |
|
| 1467 |
# luks open |
| 1468 |
|
| 1469 |
if conditions.device is not None: |
| 1470 |
name = conditions.opened_luks_name(conditions.device) |
| 1471 |
if name is not None: |
| 1472 |
result["name"] = name |
| 1473 |
|
| 1474 |
if conditions.luks_open(): |
| 1475 |
assert conditions.device # ensured in conditions.luks_open() |
| 1476 |
name = module.params["name"] |
| 1477 |
if name is None: |
| 1478 |
try: |
| 1479 |
name = crypt.generate_luks_name(conditions.device) |
| 1480 |
except ValueError as e: |
| 1481 |
module.fail_json(msg=f"luks_device error: {e}") |
| 1482 |
if not module.check_mode: |
| 1483 |
try: |
| 1484 |
if ( |
| 1485 |
module.params["keyfile"] is not None |
| 1486 |
or module.params["passphrase"] is not None |
| 1487 |
): |
| 1488 |
crypt.run_luks_open( |
| 1489 |
conditions.device, |
| 1490 |
module.params["keyfile"], |
| 1491 |
conditions.get_passphrase_from_module_params("passphrase"), |
| 1492 |
module.params["perf_same_cpu_crypt"], |
| 1493 |
module.params["perf_submit_from_crypt_cpus"], |
| 1494 |
module.params["perf_no_read_workqueue"], |
| 1495 |
module.params["perf_no_write_workqueue"], |
| 1496 |
module.params["persistent"], |
| 1497 |
module.params["allow_discards"], |
| 1498 |
name, |
| 1499 |
) |
| 1500 |
else: |
| 1501 |
crypt.run_systemd_cryptsetup_attach( |
| 1502 |
conditions.device, |
| 1503 |
module.params["tpm2_device"], |
| 1504 |
module.params["perf_same_cpu_crypt"], |
| 1505 |
module.params["perf_submit_from_crypt_cpus"], |
| 1506 |
module.params["perf_no_read_workqueue"], |
| 1507 |
module.params["perf_no_write_workqueue"], |
| 1508 |
module.params["allow_discards"], |
| 1509 |
name, |
| 1510 |
) |
| 1511 |
except ValueError as e: |
| 1512 |
module.fail_json(msg=f"luks_device error: {e}") |
| 1513 |
result["name"] = name |
| 1514 |
result["changed"] = True |
| 1515 |
if module.check_mode: |
| 1516 |
module.exit_json(**result) |
| 1517 |
|
| 1518 |
# luks close |
| 1519 |
if conditions.luks_close(): |
| 1520 |
if conditions.device is not None: |
| 1521 |
try: |
| 1522 |
name = crypt.get_container_name_by_device(conditions.device) |
| 1523 |
except ValueError as e: |
| 1524 |
module.fail_json(msg=f"luks_device error: {e}") |
| 1525 |
else: |
| 1526 |
name = module.params["name"] |
| 1527 |
if name is None: |
| 1528 |
module.fail_json(msg="Cannot determine name to close device") |
| 1529 |
if not module.check_mode: |
| 1530 |
try: |
| 1531 |
crypt.run_luks_close(name) |
| 1532 |
except ValueError as e: |
| 1533 |
module.fail_json(msg=f"luks_device error: {e}") |
| 1534 |
result["name"] = name |
| 1535 |
result["changed"] = True |
| 1536 |
if module.check_mode: |
| 1537 |
module.exit_json(**result) |
| 1538 |
|
| 1539 |
# luks add key |
| 1540 |
if conditions.luks_add_key(): |
| 1541 |
assert conditions.device # ensured in conditions.luks_add_key() |
| 1542 |
if not module.check_mode: |
| 1543 |
try: |
| 1544 |
crypt.run_luks_add_key( |
| 1545 |
conditions.device, |
| 1546 |
module.params["keyfile"], |
| 1547 |
conditions.get_passphrase_from_module_params("passphrase"), |
| 1548 |
module.params["new_keyfile"], |
| 1549 |
conditions.get_passphrase_from_module_params("new_passphrase"), |
| 1550 |
module.params["new_keyslot"], |
| 1551 |
module.params["pbkdf"], |
| 1552 |
) |
| 1553 |
except ValueError as e: |
| 1554 |
module.fail_json(msg=f"luks_device error: {e}") |
| 1555 |
result["changed"] = True |
| 1556 |
if module.check_mode: |
| 1557 |
module.exit_json(**result) |
| 1558 |
|
| 1559 |
# luks remove key |
| 1560 |
if conditions.luks_remove_key(): |
| 1561 |
assert conditions.device # ensured in conditions.luks_remove_key() |
| 1562 |
if not module.check_mode: |
| 1563 |
try: |
| 1564 |
last_key = module.params["force_remove_last_key"] |
| 1565 |
crypt.run_luks_remove_key( |
| 1566 |
conditions.device, |
| 1567 |
module.params["remove_keyfile"], |
| 1568 |
conditions.get_passphrase_from_module_params("remove_passphrase"), |
| 1569 |
module.params["remove_keyslot"], |
| 1570 |
force_remove_last_key=last_key, |
| 1571 |
) |
| 1572 |
except ValueError as e: |
| 1573 |
module.fail_json(msg=f"luks_device error: {e}") |
| 1574 |
result["changed"] = True |
| 1575 |
if module.check_mode: |
| 1576 |
module.exit_json(**result) |
| 1577 |
|
| 1578 |
# luks remove |
| 1579 |
if conditions.luks_remove(): |
| 1580 |
assert conditions.device # ensured in conditions.luks_remove() |
| 1581 |
if not module.check_mode: |
| 1582 |
try: |
| 1583 |
crypt.run_luks_remove(conditions.device) |
| 1584 |
except ValueError as e: |
| 1585 |
module.fail_json(msg=f"luks_device error: {e}") |
| 1586 |
result["changed"] = True |
| 1587 |
if module.check_mode: |
| 1588 |
module.exit_json(**result) |
| 1589 |
|
| 1590 |
if conditions.systemd_cryptenroll(): |
| 1591 |
assert conditions.device is not None |
| 1592 |
if not module.check_mode: |
| 1593 |
try: |
| 1594 |
changed = crypt.run_systemd_cryptenroll( |
| 1595 |
conditions.device, |
| 1596 |
module.params["keyfile"], |
| 1597 |
conditions.get_passphrase_from_module_params("passphrase"), |
| 1598 |
module.params["tpm2_device"], |
| 1599 |
module.params["new_tpm2"], |
| 1600 |
module.params["new_tpm2_pcrs"], |
| 1601 |
module.params["remove_tpm2"], |
| 1602 |
) |
| 1603 |
except ValueError as e: |
| 1604 |
module.fail_json(msg=f"luks_device error: {e}") |
| 1605 |
result["changed"] |= changed |
| 1606 |
if module.check_mode: |
| 1607 |
module.exit_json(**result) |
| 1608 |
|
| 1609 |
if conditions.luks_config(): |
| 1610 |
assert conditions.device is not None # ensured in conditions.luks_config() |
| 1611 |
if not module.check_mode: |
| 1612 |
try: |
| 1613 |
crypt.run_config( |
| 1614 |
conditions.device, |
| 1615 |
module.params["keyslot"], |
| 1616 |
module.params["keyslot_priority"], |
| 1617 |
) |
| 1618 |
except ValueError as e: |
| 1619 |
module.fail_json(msg=f"luks_device error: {e}") |
| 1620 |
result["changed"] = True |
| 1621 |
if module.check_mode: |
| 1622 |
module.exit_json(**result) |
| 1623 |
|
| 1624 |
# Success - return result |
| 1625 |
module.exit_json(**result) |
| 1626 |
|
| 1627 |
|
| 1628 |
def main() -> t.NoReturn: |
| 1629 |
run_module() |
| 1630 |
|
| 1631 |
|
| 1632 |
if __name__ == "__main__": |
| 1633 |
main() |