Debian Codegraph @

pkg/storaged/crypto/luksmeta-monitor-hack.py

raw
1 #! /usr/bin/python3
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 # This simulates the org.freedesktop.UDisks.Encrypted.Slots property
5 # et al for versions of UDisks that don't have them yet.
6
7 import atexit
8 import base64
9 import json
10 import os
11 import re
12 import signal
13 import subprocess
14 import sys
15
16
17 def b64_decode(data):
18 # The data we get doesn't seem to have any padding, but the base64
19 # module requires it. So we add it back. Can't anyone agree on
20 # anything? Not even base64?
21 return base64.urlsafe_b64decode((data + '=' * ((4 - len(data) % 4) % 4)).encode('ascii', 'ignore'))
22
23
24 def get_clevis_config_from_protected_header(protected_header):
25 header = b64_decode(protected_header).decode()
26 header_object = json.loads(header)
27 clevis = header_object.get("clevis", None)
28 if clevis is None:
29 return None
30
31 pin = clevis.get("pin", None)
32 if pin == "tang":
33 return clevis
34 elif pin == "sss":
35 subpins = {}
36 jwes = clevis["sss"]["jwe"]
37 for jwe in jwes:
38 subconf = get_clevis_config_from_jwe(jwe)
39 subpin = subconf["pin"]
40 if subpin not in subpins:
41 subpins[subpin] = [subconf[subpin]]
42 else:
43 subpins[subpin].append(subconf[subpin])
44 return {"pin": "sss", "sss": {"t": clevis["sss"]["t"], "pins": subpins}}
45 else:
46 return {"pin": pin, pin: {}}
47
48
49 def get_clevis_config_from_jwe(jwe):
50 return get_clevis_config_from_protected_header(jwe.split(".")[0])
51
52
53 def info(dev):
54 slots = {}
55 version = 1
56 max_slots = 8
57
58 try:
59 result = subprocess.check_output(["cryptsetup", "luksDump", dev], stderr=subprocess.PIPE)
60 except subprocess.CalledProcessError:
61 return {"version": version, "slots": [], "max_slots": max_slots}
62
63 in_luks2_slot_section = False
64 in_luks2_token_section = False
65 for line in result.splitlines():
66 if not (line.startswith((b' ', b'\t'))):
67 in_luks2_slot_section = False
68 in_luks2_token_section = False
69 if line == b"Keyslots:":
70 in_luks2_slot_section = True
71 version = 2
72 max_slots = 32
73 elif line == b"Tokens:":
74 in_luks2_token_section = True
75
76 if in_luks2_slot_section:
77 match = re.match(rb" ([0-9]+): luks2$", line)
78 else:
79 match = re.match(rb"Key Slot ([0-9]+): ENABLED$", line)
80 if match:
81 slot = int(match.group(1))
82 entry = {"Index": {"v": slot}}
83 if version == 1:
84 try:
85 luksmeta = subprocess.check_output(["luksmeta", "load", "-d", dev, "-s", str(slot),
86 "-u", "cb6e8904-81ff-40da-a84a-07ab9ab5715e"],
87 stderr=subprocess.PIPE)
88 entry["ClevisConfig"] = {
89 "v": json.dumps(get_clevis_config_from_jwe(luksmeta.decode()))
90 }
91 except (subprocess.CalledProcessError, FileNotFoundError):
92 pass
93 if slot not in slots:
94 slots[slot] = entry
95
96 if in_luks2_token_section:
97 match = re.match(rb" ([0-9]+): clevis$", line)
98 if match:
99 try:
100 token = subprocess.check_output(["cryptsetup", "token", "export",
101 dev, "--token-id", match.group(1)],
102 stderr=subprocess.PIPE)
103 token_object = json.loads(token.decode())
104 if token_object.get("type") == "clevis":
105 config = json.dumps(get_clevis_config_from_protected_header(token_object["jwe"]["protected"]))
106 for slot_str in token_object.get("keyslots", []):
107 slot = int(slot_str)
108 slots[slot] = {"Index": {"v": slot},
109 "ClevisConfig": {"v": config}}
110 except subprocess.CalledProcessError:
111 pass
112
113 return {"version": version, "slots": list(slots.values()), "max_slots": max_slots}
114
115
116 def monitor(dev):
117 mon = None
118
119 # We have to kill the udevadm process explicitly when Cockpit
120 # kills us. It will eventually exit on its own since its stdout
121 # will be closed when we exit, but that will only happen when it
122 # actually writes something.
123 #
124 # We use a process group to do the killing, since the Rust version
125 # of stdbuf will fork/exec udevadm and we thus need to kill both
126 # the stdbuf process and the udevadm process. (The GNU version of
127 # stdbuf will just exec udevadm and there was only one process to
128 # kill in that case.)
129
130 def killmon():
131 if mon:
132 os.killpg(mon.pid, signal.SIGTERM)
133
134 def sigexit(_signo, _stack):
135 killmon()
136 os._exit(0)
137
138 atexit.register(killmon)
139 signal.signal(signal.SIGTERM, sigexit)
140 signal.signal(signal.SIGINT, sigexit)
141 signal.signal(signal.SIGHUP, sigexit)
142
143 path = subprocess.check_output(["udevadm", "info", "-q", "path", dev]).rstrip(b"\n")
144 mon = subprocess.Popen(["stdbuf", "-o", "L", "udevadm", "monitor", "-u", "-s", "block"],
145 stdout=subprocess.PIPE, preexec_fn=lambda: os.setpgid(0, 0))
146
147 old_infos = info(dev)
148 sys.stdout.write(json.dumps(old_infos) + "\n")
149 sys.stdout.flush()
150 while True:
151 line = mon.stdout.readline()
152 if path in line:
153 new_infos = info(dev)
154 if new_infos != old_infos:
155 sys.stdout.write(json.dumps(new_infos) + "\n")
156 sys.stdout.flush()
157 old_infos = new_infos
158
159
160 monitor(sys.argv[1])