| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2014, Steve <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: crypttab |
| 11 |
short_description: Encrypted Linux block devices |
| 12 |
description: |
| 13 |
- Control Linux encrypted block devices that are set up during system boot in C(/etc/crypttab). |
| 14 |
extends_documentation_fragment: |
| 15 |
- community.general._attributes |
| 16 |
attributes: |
| 17 |
check_mode: |
| 18 |
support: full |
| 19 |
diff_mode: |
| 20 |
support: none |
| 21 |
options: |
| 22 |
name: |
| 23 |
description: |
| 24 |
- Name of the encrypted block device as it appears in the C(/etc/crypttab) file, or optionally prefixed with V(/dev/mapper/), |
| 25 |
as it appears in the filesystem. V(/dev/mapper/) is stripped from O(name). |
| 26 |
type: str |
| 27 |
required: true |
| 28 |
state: |
| 29 |
description: |
| 30 |
- Use V(present) to add a line to C(/etc/crypttab) or update its definition if already present. |
| 31 |
- Use V(absent) to remove a line with matching O(name). |
| 32 |
- Use V(opts_present) to add options to those already present; options with different values are updated. |
| 33 |
- Use V(opts_absent) to remove options from the existing set. |
| 34 |
type: str |
| 35 |
required: true |
| 36 |
choices: [absent, opts_absent, opts_present, present] |
| 37 |
backing_device: |
| 38 |
description: |
| 39 |
- Path to the underlying block device or file, or the UUID of a block-device prefixed with V(UUID=). |
| 40 |
type: str |
| 41 |
password: |
| 42 |
description: |
| 43 |
- Encryption password, the path to a file containing the password, or V(-) or unset if the password should be entered |
| 44 |
at boot. |
| 45 |
type: path |
| 46 |
opts: |
| 47 |
description: |
| 48 |
- A comma-delimited list of options. See V(crypttab(5\)) for details. |
| 49 |
type: str |
| 50 |
path: |
| 51 |
description: |
| 52 |
- Path to file to use instead of V(/etc/crypttab). |
| 53 |
- This might be useful in a chroot environment. |
| 54 |
type: path |
| 55 |
default: /etc/crypttab |
| 56 |
author: |
| 57 |
- Steve (@groks) |
| 58 |
""" |
| 59 |
|
| 60 |
EXAMPLES = r""" |
| 61 |
- name: Set the options explicitly a device which must already exist |
| 62 |
community.general.crypttab: |
| 63 |
name: luks-home |
| 64 |
state: present |
| 65 |
opts: discard,cipher=aes-cbc-essiv:sha256 |
| 66 |
|
| 67 |
- name: Add the 'discard' option to any existing options for all devices |
| 68 |
community.general.crypttab: |
| 69 |
name: '{{ item.device }}' |
| 70 |
state: opts_present |
| 71 |
opts: discard |
| 72 |
loop: '{{ ansible_mounts }}' |
| 73 |
when: "'/dev/mapper/luks-' in item.device" |
| 74 |
|
| 75 |
- name: Add entry to /etc/crypttab for luks-home with password file |
| 76 |
community.general.crypttab: |
| 77 |
name: luks-home |
| 78 |
backing_device: UUID=123e4567-e89b-12d3-a456-426614174000 |
| 79 |
password: /root/keys/luks-home.key |
| 80 |
opts: discard,cipher=aes-cbc-essiv:sha256 |
| 81 |
state: present |
| 82 |
""" |
| 83 |
|
| 84 |
import os |
| 85 |
import traceback |
| 86 |
|
| 87 |
from ansible.module_utils.basic import AnsibleModule |
| 88 |
from ansible.module_utils.common.text.converters import to_bytes |
| 89 |
|
| 90 |
|
| 91 |
def main(): |
| 92 |
module = AnsibleModule( |
| 93 |
argument_spec=dict( |
| 94 |
name=dict(type="str", required=True), |
| 95 |
state=dict(type="str", required=True, choices=["absent", "opts_absent", "opts_present", "present"]), |
| 96 |
backing_device=dict(type="str"), |
| 97 |
password=dict(type="path"), |
| 98 |
opts=dict(type="str"), |
| 99 |
path=dict(type="path", default="/etc/crypttab"), |
| 100 |
), |
| 101 |
supports_check_mode=True, |
| 102 |
) |
| 103 |
|
| 104 |
backing_device = module.params["backing_device"] |
| 105 |
password = module.params["password"] |
| 106 |
opts = module.params["opts"] |
| 107 |
state = module.params["state"] |
| 108 |
path = module.params["path"] |
| 109 |
name = module.params["name"] |
| 110 |
if name.startswith("/dev/mapper/"): |
| 111 |
name = name[len("/dev/mapper/") :] |
| 112 |
|
| 113 |
if state != "absent" and backing_device is None and password is None and opts is None: |
| 114 |
module.fail_json(msg="expected one or more of 'backing_device', 'password' or 'opts'", **module.params) |
| 115 |
|
| 116 |
if "opts" in state and (backing_device is not None or password is not None): |
| 117 |
module.fail_json(msg=f"cannot update 'backing_device' or 'password' when state={state}", **module.params) |
| 118 |
|
| 119 |
for arg_name, arg in (("name", name), ("backing_device", backing_device), ("password", password), ("opts", opts)): |
| 120 |
if arg is not None and (" " in arg or "\t" in arg or arg == ""): |
| 121 |
module.fail_json(msg=f"invalid '{arg_name}': contains white space or is empty", **module.params) |
| 122 |
|
| 123 |
try: |
| 124 |
crypttab = Crypttab(path) |
| 125 |
existing_line = crypttab.match(name) |
| 126 |
except Exception as e: |
| 127 |
module.fail_json( |
| 128 |
msg=f"failed to open and parse crypttab file: {e}", exception=traceback.format_exc(), **module.params |
| 129 |
) |
| 130 |
|
| 131 |
if "present" in state and existing_line is None and backing_device is None: |
| 132 |
module.fail_json(msg="'backing_device' required to add a new entry", **module.params) |
| 133 |
|
| 134 |
changed, reason = False, "?" |
| 135 |
|
| 136 |
if state == "absent": |
| 137 |
if existing_line is not None: |
| 138 |
changed, reason = existing_line.remove() |
| 139 |
|
| 140 |
elif state == "present": |
| 141 |
if existing_line is not None: |
| 142 |
changed, reason = existing_line.set(backing_device, password, opts) |
| 143 |
else: |
| 144 |
changed, reason = crypttab.add(Line(None, name, backing_device, password, opts)) |
| 145 |
|
| 146 |
elif state == "opts_present": |
| 147 |
if existing_line is not None: |
| 148 |
changed, reason = existing_line.opts.add(opts) |
| 149 |
else: |
| 150 |
changed, reason = crypttab.add(Line(None, name, backing_device, password, opts)) |
| 151 |
|
| 152 |
elif state == "opts_absent": |
| 153 |
if existing_line is not None: |
| 154 |
changed, reason = existing_line.opts.remove(opts) |
| 155 |
|
| 156 |
if changed and not module.check_mode: |
| 157 |
with open(path, "wb") as f: |
| 158 |
f.write(to_bytes(crypttab, errors="surrogate_or_strict")) |
| 159 |
|
| 160 |
module.exit_json(changed=changed, msg=reason, **module.params) |
| 161 |
|
| 162 |
|
| 163 |
class Crypttab: |
| 164 |
_lines: list[str] |
| 165 |
|
| 166 |
def __init__(self, path): |
| 167 |
self.path = path |
| 168 |
self._lines = [] |
| 169 |
if not os.path.exists(path): |
| 170 |
if not os.path.exists(os.path.dirname(path)): |
| 171 |
os.makedirs(os.path.dirname(path)) |
| 172 |
open(path, "a").close() |
| 173 |
|
| 174 |
with open(path) as f: |
| 175 |
for line in f.readlines(): |
| 176 |
self._lines.append(Line(line)) |
| 177 |
|
| 178 |
def add(self, line): |
| 179 |
self._lines.append(line) |
| 180 |
return True, "added line" |
| 181 |
|
| 182 |
def lines(self): |
| 183 |
for line in self._lines: |
| 184 |
if line.valid(): |
| 185 |
yield line |
| 186 |
|
| 187 |
def match(self, name): |
| 188 |
for line in self.lines(): |
| 189 |
if line.name == name: |
| 190 |
return line |
| 191 |
return None |
| 192 |
|
| 193 |
def __str__(self): |
| 194 |
lines = [] |
| 195 |
for line in self._lines: |
| 196 |
lines.append(str(line)) |
| 197 |
crypttab = "\n".join(lines) |
| 198 |
if len(crypttab) == 0: |
| 199 |
crypttab += "\n" |
| 200 |
if crypttab[-1] != "\n": |
| 201 |
crypttab += "\n" |
| 202 |
return crypttab |
| 203 |
|
| 204 |
|
| 205 |
class Line: |
| 206 |
def __init__(self, line=None, name=None, backing_device=None, password=None, opts=None): |
| 207 |
self.line = line |
| 208 |
self.name = name |
| 209 |
self.backing_device = backing_device |
| 210 |
self.password = password |
| 211 |
self.opts = Options(opts) |
| 212 |
|
| 213 |
if line is not None: |
| 214 |
self.line = self.line.rstrip("\n") |
| 215 |
if self._line_valid(line): |
| 216 |
self.name, backing_device, password, opts = self._split_line(line) |
| 217 |
|
| 218 |
self.set(backing_device, password, opts) |
| 219 |
|
| 220 |
def set(self, backing_device, password, opts): |
| 221 |
changed = False |
| 222 |
|
| 223 |
if backing_device is not None and self.backing_device != backing_device: |
| 224 |
self.backing_device = backing_device |
| 225 |
changed = True |
| 226 |
|
| 227 |
if password is not None and self.password != password: |
| 228 |
self.password = password |
| 229 |
changed = True |
| 230 |
|
| 231 |
if opts is not None: |
| 232 |
opts = Options(opts) |
| 233 |
if opts != self.opts: |
| 234 |
self.opts = opts |
| 235 |
changed = True |
| 236 |
|
| 237 |
return changed, "updated line" |
| 238 |
|
| 239 |
def _line_valid(self, line): |
| 240 |
return line.strip() and not line.startswith("#") and len(line.split()) in (2, 3, 4) |
| 241 |
|
| 242 |
def _split_line(self, line): |
| 243 |
fields = line.split() |
| 244 |
try: |
| 245 |
field2 = fields[2] |
| 246 |
except IndexError: |
| 247 |
field2 = None |
| 248 |
try: |
| 249 |
field3 = fields[3] |
| 250 |
except IndexError: |
| 251 |
field3 = None |
| 252 |
|
| 253 |
return (fields[0], fields[1], field2, field3) |
| 254 |
|
| 255 |
def remove(self): |
| 256 |
self.line, self.name, self.backing_device = "", None, None |
| 257 |
return True, "removed line" |
| 258 |
|
| 259 |
def valid(self): |
| 260 |
return self.name is not None and self.backing_device is not None |
| 261 |
|
| 262 |
def __str__(self): |
| 263 |
if self.valid(): |
| 264 |
fields = [self.name, self.backing_device] |
| 265 |
if self.password is not None or self.opts: |
| 266 |
if self.password is not None: |
| 267 |
fields.append(self.password) |
| 268 |
else: |
| 269 |
fields.append("none") |
| 270 |
if self.opts: |
| 271 |
fields.append(str(self.opts)) |
| 272 |
return " ".join(fields) |
| 273 |
return self.line |
| 274 |
|
| 275 |
|
| 276 |
class Options(dict): |
| 277 |
"""opts_string looks like: 'discard,foo=bar,baz=greeble'""" |
| 278 |
|
| 279 |
def __init__(self, opts_string): |
| 280 |
super().__init__() |
| 281 |
self.itemlist = [] |
| 282 |
if opts_string is not None: |
| 283 |
for opt in opts_string.split(","): |
| 284 |
kv = opt.split("=", 1) |
| 285 |
if len(kv) > 1: |
| 286 |
k, v = (kv[0], kv[1]) |
| 287 |
else: |
| 288 |
k, v = (kv[0], None) |
| 289 |
self[k] = v |
| 290 |
|
| 291 |
def add(self, opts_string): |
| 292 |
changed = False |
| 293 |
for k, v in Options(opts_string).items(): |
| 294 |
if k in self: |
| 295 |
if self[k] != v: |
| 296 |
changed = True |
| 297 |
else: |
| 298 |
changed = True |
| 299 |
self[k] = v |
| 300 |
return changed, "updated options" |
| 301 |
|
| 302 |
def remove(self, opts_string): |
| 303 |
changed = False |
| 304 |
for k in Options(opts_string): |
| 305 |
if k in self: |
| 306 |
del self[k] |
| 307 |
changed = True |
| 308 |
return changed, "removed options" |
| 309 |
|
| 310 |
def keys(self): |
| 311 |
return self.itemlist |
| 312 |
|
| 313 |
def values(self): |
| 314 |
return [self[key] for key in self] |
| 315 |
|
| 316 |
def items(self): |
| 317 |
return [(key, self[key]) for key in self] |
| 318 |
|
| 319 |
def __iter__(self): |
| 320 |
return iter(self.itemlist) |
| 321 |
|
| 322 |
def __setitem__(self, key, value): |
| 323 |
if key not in self: |
| 324 |
self.itemlist.append(key) |
| 325 |
super().__setitem__(key, value) |
| 326 |
|
| 327 |
def __delitem__(self, key): |
| 328 |
self.itemlist.remove(key) |
| 329 |
super().__delitem__(key) |
| 330 |
|
| 331 |
def __ne__(self, obj): |
| 332 |
return not (isinstance(obj, Options) and sorted(self.items()) == sorted(obj.items())) |
| 333 |
|
| 334 |
def __str__(self): |
| 335 |
ret = [] |
| 336 |
for k, v in self.items(): |
| 337 |
if v is None: |
| 338 |
ret.append(k) |
| 339 |
else: |
| 340 |
ret.append(f"{k}={v}") |
| 341 |
return ",".join(ret) |
| 342 |
|
| 343 |
|
| 344 |
if __name__ == "__main__": |
| 345 |
main() |