Debian Codegraph @

pkg/storaged/crypto/keyslots.jsx

raw
1 /*
2 * Copyright (C) 2018 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from "cockpit";
7 import React from "react";
8 import client from "../client.js";
9
10 import { CardHeader } from '@patternfly/react-core/dist/esm/components/Card/index.js';
11 import { Checkbox } from "@patternfly/react-core/dist/esm/components/Checkbox/index.js";
12 import { FormGroup } from "@patternfly/react-core/dist/esm/components/Form/index.js";
13 import { Table, Tbody, Tr, Td } from '@patternfly/react-table';
14 import { Content, ContentVariants } from "@patternfly/react-core/dist/esm/components/Content/index.js";
15 import { TextInput as TextInputPF } from "@patternfly/react-core/dist/esm/components/TextInput/index.js";
16 import { Stack } from "@patternfly/react-core/dist/esm/layouts/Stack/index.js";
17 import { EditIcon, MinusIcon, PlusIcon } from "@patternfly/react-icons";
18 import { EmptyState, EmptyStateBody } from "@patternfly/react-core/dist/esm/components/EmptyState/index.js";
19
20 import { fmt_to_fragments } from "utils.jsx";
21 import kernelopt_sh from "kernelopt.sh";
22
23 import { remember_passphrase } from "../anaconda.jsx";
24
25 import {
26 dialog_open,
27 SelectOneRadio, TextInput, PassInput, Skip
28 } from "../dialog.jsx";
29 import {
30 decode_filename, encode_filename, get_block_mntopts, block_name, for_each_async,
31 parse_options, extract_option, unparse_options, edit_crypto_config,
32 contains_rootfs,
33 } from "../utils.js";
34 import { StorageButton } from "../storage-controls.jsx";
35
36 import clevis_luks_passphrase_sh from "./clevis-luks-passphrase.sh";
37 import { validate_url, get_tang_adv, TangKeyVerification } from "./tang.jsx";
38 import { getPackageManager, InstallProgressType } from "packagemanager.js";
39
40 const _ = cockpit.gettext;
41
42 /* Clevis operations
43 */
44
45 function clevis_add(block, pin, cfg, passphrase) {
46 const dev = decode_filename(block.Device);
47 return cockpit.spawn(["clevis", "luks", "bind", "-f", "-k", "-", "-d", dev, pin, JSON.stringify(cfg)],
48 { superuser: "require", err: "message" }).input(passphrase);
49 }
50
51 function clevis_remove(block, key) {
52 // clevis-luks-unbind needs a tty on stdin for some reason.
53 return cockpit.spawn(["clevis", "luks", "unbind", "-d", decode_filename(block.Device), "-s", key.slot, "-f"],
54 { superuser: "require", pty: true, err: "message" });
55 }
56
57 export function clevis_recover_passphrase(block, just_type) {
58 const dev = decode_filename(block.Device);
59 const args = [];
60 if (just_type)
61 args.push("--type");
62 args.push(dev);
63 return cockpit.script(clevis_luks_passphrase_sh, args,
64 { superuser: "require", err: "message" })
65 .then(output => output.trim());
66 }
67
68 async function clevis_unlock(client, block, luksname, readonly) {
69 const dev = decode_filename(block.Device);
70 const clear_dev = luksname || "luks-" + block.IdUUID;
71
72 if (readonly) {
73 // HACK - clevis-luks-unlock can not unlock things readonly.
74 // But see https://github.com/latchset/clevis/pull/317 (merged
75 // Feb 2023, unreleased as of Feb 2024).
76 const passphrase = await clevis_recover_passphrase(block, false);
77 const crypto = client.blocks_crypto[block.path];
78 const unlock_options = { "read-only": { t: "b", v: readonly } };
79 await crypto.Unlock(passphrase, unlock_options);
80 return;
81 }
82
83 await cockpit.spawn(["clevis", "luks", "unlock", "-d", dev, "-n", clear_dev],
84 { superuser: "require" });
85 }
86
87 export async function unlock_with_type(client, block, passphrase, passphrase_type, override_readonly) {
88 const crypto = client.blocks_crypto[block.path];
89 let readonly = false;
90 let luksname = null;
91
92 for (const c of block.Configuration) {
93 if (c[0] == "crypttab") {
94 const options = parse_options(decode_filename(c[1].options.v));
95 readonly = extract_option(options, "readonly") || extract_option(options, "read-only");
96 luksname = decode_filename(c[1].name.v);
97 break;
98 }
99 }
100
101 if (override_readonly !== null && override_readonly !== undefined)
102 readonly = override_readonly;
103
104 const unlock_options = { "read-only": { t: "b", v: readonly } };
105
106 if (passphrase) {
107 await crypto.Unlock(passphrase, unlock_options);
108 remember_passphrase(block, passphrase);
109 } else if (passphrase_type == "stored") {
110 await crypto.Unlock("", unlock_options);
111 } else if (passphrase_type == "clevis") {
112 await clevis_unlock(client, block, luksname, readonly);
113 } else {
114 // This should always be caught and should never show up in the UI
115 throw new Error("No passphrase");
116 }
117 }
118
119 /* Passphrase operations
120 */
121
122 function passphrase_add(block, new_passphrase, old_passphrase) {
123 const dev = decode_filename(block.Device);
124 return cockpit.spawn(["cryptsetup", "luksAddKey", dev],
125 { superuser: "require", err: "message" }).input(old_passphrase + "\n" + new_passphrase);
126 }
127
128 function passphrase_change(block, key, new_passphrase, old_passphrase) {
129 const dev = decode_filename(block.Device);
130 return cockpit.spawn(["cryptsetup", "luksChangeKey", dev, "--key-slot", key.slot.toString()],
131 { superuser: "require", err: "message" }).input(old_passphrase + "\n" + new_passphrase + "\n");
132 }
133
134 function slot_remove(block, slot, passphrase) {
135 const dev = decode_filename(block.Device);
136 const opts = { superuser: "require", err: "message" };
137 const cmd = ["cryptsetup", "luksKillSlot", dev, slot.toString()];
138 if (passphrase === false) {
139 cmd.splice(2, 0, "-q");
140 opts.pty = true;
141 }
142
143 const spawn = cockpit.spawn(cmd, opts);
144 if (passphrase !== false)
145 spawn.input(passphrase + "\n");
146
147 return spawn;
148 }
149
150 function passphrase_test(block, passphrase) {
151 const dev = decode_filename(block.Device);
152 return (cockpit.spawn(["cryptsetup", "luksOpen", "--test-passphrase", dev],
153 { superuser: "require", err: "message" }).input(passphrase)
154 .then(() => true)
155 .catch(() => false));
156 }
157
158 /* Dialogs
159 */
160
161 export function existing_passphrase_fields(explanation) {
162 return [
163 Skip("medskip", { visible: vals => vals.needs_explicit_passphrase }),
164 PassInput("passphrase", _("Disk passphrase"),
165 {
166 visible: vals => vals.needs_explicit_passphrase,
167 validate: val => !val.length && _("Passphrase cannot be empty"),
168 explanation
169 })
170 ];
171 }
172
173 function get_stored_passphrase(block, just_type) {
174 const pub_config = block.Configuration.find(c => c[0] == "crypttab");
175 if (pub_config && pub_config[1]["passphrase-path"] && decode_filename(pub_config[1]["passphrase-path"].v) != "") {
176 if (just_type)
177 return Promise.resolve("stored");
178 return block.GetSecretConfiguration({}).then(function (items) {
179 for (let i = 0; i < items.length; i++) {
180 if (items[i][0] == 'crypttab' && items[i][1]['passphrase-contents'])
181 return decode_filename(items[i][1]['passphrase-contents'].v);
182 }
183 return "";
184 });
185 }
186 }
187
188 export function get_existing_passphrase(block, just_type) {
189 return clevis_recover_passphrase(block, just_type).then(passphrase => {
190 return passphrase || get_stored_passphrase(block, just_type);
191 });
192 }
193
194 export function request_passphrase_on_error_handler(dlg, vals, recovered_passphrase, block) {
195 return function (error) {
196 if (vals.passphrase === undefined && block) {
197 return (passphrase_test(block, recovered_passphrase)
198 .then(good => {
199 if (!good)
200 dlg.set_values({ needs_explicit_passphrase: true });
201 return Promise.reject(error);
202 }));
203 } else
204 return Promise.reject(error);
205 };
206 }
207
208 export function init_existing_passphrase(block, just_type, callback) {
209 return {
210 title: _("Unlocking disk"),
211 func: dlg => {
212 const backing = client.blocks[block.CryptoBackingDevice];
213 return get_existing_passphrase(backing || block, just_type).then(passphrase => {
214 if (!passphrase)
215 dlg.set_values({ needs_explicit_passphrase: true });
216 if (callback)
217 callback(passphrase);
218 return passphrase;
219 });
220 }
221 };
222 }
223
224 /* Getting the system ready for NBDE on the root filesystem.
225
226 We need the clevis module in the initrd. If it is not there, the
227 clevis-dracut package should be installed and the initrd needs to
228 be regenerated. We do this only after the user has agreed to it.
229
230 The kernel command line needs to have rd.neednet=1 in it. We just
231 do this unconditionally because it's so fast.
232 */
233
234 function ensure_package_installed(steps, progress, package_name) {
235 function status_callback(progress) {
236 return p => {
237 let text = null;
238 if (p.waiting) {
239 text = _("Waiting for other software management operations to finish");
240 } else if (p.package) {
241 let fmt;
242 if (p.info == InstallProgressType.DOWNLOADING)
243 fmt = _("Downloading $0");
244 else if (p.info == InstallProgressType.REMOVING)
245 fmt = _("Removing $0");
246 else
247 fmt = _("Installing $0");
248 text = cockpit.format(fmt, p.package);
249 }
250 progress(text, p.cancel);
251 };
252 }
253
254 progress(cockpit.format(_("Checking for $0 package"), package_name), null);
255 return getPackageManager().then(pk => {
256 return pk.check_missing_packages([package_name]).then(data => {
257 progress(null, null);
258 if (data.missing_names.length + data.unavailable_names.length > 0)
259 steps.push({
260 title: cockpit.format(_("The $0 package must be installed."), package_name),
261 func: progress => {
262 if (data.remove_names.length > 0)
263 return Promise.reject(cockpit.format(_("Installing $0 would remove $1."), name, data.remove_names[0]));
264 else if (data.unavailable_names.length > 0)
265 return Promise.reject(cockpit.format(_("The $0 package is not available from any repository."), name));
266 else
267 return pk.install_missing_packages(data, status_callback(progress));
268 }
269 });
270 });
271 })
272 .catch(error => {
273 // Something wrong with PackageKit or dnf5daemon, maybe it is not even
274 // installed. Let's show the error during fixing.
275 progress(null, null);
276 steps.push({
277 title: cockpit.format(_("The $0 package must be installed."), package_name),
278 func: progress => {
279 if (error.problem == "not-found") {
280 return Promise.reject(cockpit.format(_("Error installing $0: PackageKit or dnf5daemon-server is not installed"), package_name));
281 } else {
282 return Promise.reject(cockpit.format(_("Unexpected PackageManager error during installation of $0: $1"), package_name, error.toString())); // not-covered: OS error
283 }
284 }
285 });
286 });
287 }
288
289 function ensure_initrd_clevis_support(steps, progress, package_name) {
290 const task = cockpit.spawn(["lsinitrd", "-m"], { superuser: "require", err: "message" });
291 progress(_("Checking for NBDE support in the initrd"), () => task.close());
292 return task.then(data => {
293 progress(null, null);
294 if (data.indexOf("clevis") < 0) {
295 return ensure_package_installed(steps, progress, package_name)
296 .then(() => {
297 steps.push({
298 title: _("The initrd must be regenerated."),
299 func: progress => {
300 // dracut doesn't react to SIGINT, so let's not enable our Cancel button
301 progress(_("Regenerating initrd"), null);
302 return cockpit.spawn(["dracut", "--force", "--regenerate-all"],
303 { superuser: "require", err: "message" });
304 }
305 });
306 });
307 }
308 });
309 }
310
311 function ensure_root_nbde_support(steps, progress) {
312 progress(_("Adding rd.neednet=1 to kernel command line"), null);
313 return cockpit.script(kernelopt_sh, ["set", "rd.neednet=1"],
314 { superuser: "require", err: "message" })
315 .then(() => ensure_initrd_clevis_support(steps, progress, "clevis-dracut"));
316 }
317
318 function ensure_fstab_option(steps, progress, client, block, option) {
319 const cleartext = client.blocks_cleartext[block.path];
320 const crypto = client.blocks_crypto[block.path];
321 const fsys_config = cleartext
322 ? cleartext.Configuration.find(c => c[0] == "fstab")
323 : crypto?.ChildConfiguration.find(c => c[0] == "fstab");
324 const fsys_options = fsys_config && parse_options(get_block_mntopts(fsys_config[1]));
325
326 if (!fsys_options || fsys_options.indexOf(option) >= 0)
327 return Promise.resolve();
328
329 const new_fsys_options = fsys_options.concat([option]);
330 const new_fsys_config = [
331 "fstab",
332 Object.assign({ }, fsys_config[1],
333 {
334 opts: {
335 t: 'ay',
336 v: encode_filename(unparse_options(new_fsys_options))
337 }
338 })
339 ];
340 progress(cockpit.format(_("Adding \"$0\" to filesystem options"), option), null);
341 return block.UpdateConfigurationItem(fsys_config, new_fsys_config, { });
342 }
343
344 function ensure_crypto_option(steps, progress, client, block, option) {
345 const crypto_config = block.Configuration.find(c => c[0] == "crypttab");
346 const crypto_options = crypto_config && parse_options(decode_filename(crypto_config[1].options.v));
347 if (!crypto_options || crypto_options.indexOf(option) >= 0)
348 return Promise.resolve();
349
350 const new_crypto_options = crypto_options.concat([option]);
351 progress(cockpit.format(_("Adding \"$0\" to encryption options"), option), null);
352 return edit_crypto_config(block, (config, commit) => {
353 config.options = { t: 'ay', v: encode_filename(unparse_options(new_crypto_options)) };
354 return commit();
355 });
356 }
357
358 function ensure_systemd_unit_enabled(steps, progress, name, package_name) {
359 progress(cockpit.format(_("Enabling $0"), name));
360 return cockpit.spawn(["systemctl", "is-enabled", name], { err: "message" })
361 .catch((err, output) => {
362 if (err && (output == "" || output.trim() == "not-found") && package_name) {
363 // We assume that installing the package will enable the unit.
364 return ensure_package_installed(steps, progress, package_name);
365 } else
366 return cockpit.spawn(["systemctl", "enable", name],
367 { superuser: "require", err: "message" });
368 });
369 }
370
371 function ensure_non_root_nbde_support(steps, progress, client, block) {
372 return ensure_systemd_unit_enabled(steps, progress, "remote-cryptsetup.target")
373 .then(() => ensure_systemd_unit_enabled(steps, progress, "clevis-luks-askpass.path", "clevis-systemd"))
374 .then(() => ensure_fstab_option(steps, progress, client, block, "_netdev"))
375 .then(() => ensure_crypto_option(steps, progress, client, block, "_netdev"));
376 }
377
378 function ensure_nbde_support(steps, progress, client, block) {
379 if (contains_rootfs(client, block.path)) {
380 if (client.get_config("nbde_root_help", false)) {
381 steps.is_root = true;
382 return ensure_root_nbde_support(steps, progress);
383 } else
384 return Promise.resolve();
385 } else
386 return ensure_non_root_nbde_support(steps, progress, client, block);
387 }
388
389 function ensure_nbde_support_dialog(steps, client, block, url, adv, old_key, existing_passphrase) {
390 const dlg = dialog_open({
391 Title: _("Add Network Bound Disk Encryption"),
392 Body: (
393 <>
394 <Content component={ContentVariants.p}>
395 { steps.is_root
396 ? _("The system does not currently support unlocking the root filesystem with a Tang keyserver.")
397 : _("The system does not currently support unlocking a filesystem with a Tang keyserver during boot.")
398 }
399 </Content>
400 <Content component={ContentVariants.p}>
401 {_("These additional steps are necessary:")}
402 </Content>
403 <Content component="ul">
404 { steps.map((s, i) => <Content component="li" key={i}>{s.title}</Content>) }
405 </Content>
406 </>),
407 Fields: existing_passphrase_fields(_("Saving a new passphrase requires unlocking the disk. Please provide a current disk passphrase.")),
408 Action: {
409 Title: _("Fix NBDE support"),
410 action: (vals, progress) => {
411 return for_each_async(steps, s => s.func(progress))
412 .then(() => {
413 steps = [];
414 progress(_("Adding key"), null);
415 return add_or_update_tang(dlg, vals, block,
416 url, adv, old_key,
417 vals.passphrase || existing_passphrase);
418 });
419 }
420 }
421 });
422 }
423
424 function add_dialog(client, block) {
425 let recovered_passphrase;
426
427 dialog_open({
428 Title: _("Add key"),
429 Fields: [
430 SelectOneRadio("type", _("Key source"),
431 {
432 value: "luks-passphrase",
433 visible: vals => client.features.clevis,
434 widest_title: _("Repeat passphrase"),
435 choices: [
436 { value: "luks-passphrase", title: _("Passphrase") },
437 { value: "tang", title: _("Tang keyserver") }
438 ]
439 }),
440 Skip("medskip"),
441 PassInput("new_passphrase", _("New passphrase"),
442 {
443 visible: vals => !client.features.clevis || vals.type == "luks-passphrase",
444 validate: val => !val.length && _("Passphrase cannot be empty"),
445 new_password: true
446 }),
447 PassInput("new_passphrase2", _("Repeat passphrase"),
448 {
449 visible: vals => !client.features.clevis || vals.type == "luks-passphrase",
450 validate: (val, vals) => {
451 return (vals.new_passphrase.length &&
452 vals.new_passphrase != val &&
453 _("Passphrases do not match"));
454 },
455 new_password: true
456 }),
457 TextInput("tang_url", _("Keyserver address"),
458 {
459 visible: vals => client.features.clevis && vals.type == "tang",
460 validate: validate_url
461 })
462 ].concat(existing_passphrase_fields(_("Saving a new passphrase requires unlocking the disk. Please provide a current disk passphrase."))),
463 Action: {
464 Title: _("Add"),
465 action: function (vals, progress) {
466 const existing_passphrase = vals.passphrase || recovered_passphrase;
467 if (!client.features.clevis || vals.type == "luks-passphrase") {
468 return passphrase_add(block, vals.new_passphrase, existing_passphrase);
469 } else {
470 return get_tang_adv(vals.tang_url)
471 .then(adv => {
472 edit_tang_adv(client, block, null,
473 vals.tang_url, adv, existing_passphrase);
474 });
475 }
476 }
477 },
478 Inits: [
479 init_existing_passphrase(block, false, pp => { recovered_passphrase = pp })
480 ]
481 });
482 }
483
484 function edit_passphrase_dialog(block, key) {
485 dialog_open({
486 Title: _("Change passphrase"),
487 Fields: [
488 PassInput("old_passphrase", _("Old passphrase"),
489 { validate: val => !val.length && _("Passphrase cannot be empty") }),
490 Skip("medskip"),
491 PassInput("new_passphrase", _("New passphrase"),
492 {
493 validate: val => !val.length && _("Passphrase cannot be empty"),
494 new_password: true
495 }),
496 PassInput("new_passphrase2", _("Repeat passphrase"),
497 {
498 validate: (val, vals) => vals.new_passphrase.length && vals.new_passphrase != val && _("Passphrases do not match"),
499 new_password: true
500 })
501 ],
502 Action: {
503 Title: _("Save"),
504 action: vals => passphrase_change(block, key, vals.new_passphrase, vals.old_passphrase)
505 }
506 });
507 }
508
509 function edit_clevis_dialog(client, block, key) {
510 let recovered_passphrase;
511
512 dialog_open({
513 Title: _("Edit Tang keyserver"),
514 Fields: [
515 TextInput("tang_url", _("Keyserver address"),
516 {
517 validate: validate_url,
518 value: key.url
519 })
520 ].concat(existing_passphrase_fields(_("Saving a new passphrase requires unlocking the disk. Please provide a current disk passphrase."))),
521 Action: {
522 Title: _("Save"),
523 action: function (vals) {
524 const existing_passphrase = vals.passphrase || recovered_passphrase;
525 return get_tang_adv(vals.tang_url).then(adv => {
526 edit_tang_adv(client, block, key, vals.tang_url, adv, existing_passphrase);
527 });
528 }
529 },
530 Inits: [
531 init_existing_passphrase(block, false, pp => { recovered_passphrase = pp })
532 ]
533 });
534 }
535
536 function add_or_update_tang(dlg, vals, block, url, adv, old_key, passphrase) {
537 return clevis_add(block, "tang", { url, adv }, vals.passphrase || passphrase).then(() => {
538 if (old_key)
539 return clevis_remove(block, old_key);
540 })
541 .catch(request_passphrase_on_error_handler(dlg, vals, passphrase, block));
542 }
543
544 function edit_tang_adv(client, block, key, url, adv, passphrase) {
545 const dlg = dialog_open({
546 Title: _("Verify key"),
547 Body: <TangKeyVerification url={url} adv={adv} />,
548 Fields: existing_passphrase_fields(_("Saving a new passphrase requires unlocking the disk. Please provide a current disk passphrase.")),
549 Action: {
550 Title: _("Trust key"),
551 action: function (vals, progress) {
552 if (key) {
553 return add_or_update_tang(dlg, vals, block,
554 url, adv, key,
555 passphrase);
556 } else {
557 const steps = [];
558 return ensure_nbde_support(steps, progress, client, block)
559 .then(() => {
560 if (steps.length > 0)
561 ensure_nbde_support_dialog(steps, client, block, url,
562 adv, key, passphrase);
563 else {
564 progress(null, null);
565 return add_or_update_tang(dlg, vals, block,
566 url, adv, key,
567 passphrase);
568 }
569 });
570 }
571 }
572 }
573 });
574 }
575
576 const RemovePassphraseField = (tag, key, dev) => {
577 function validate(val) {
578 if (val === "")
579 return _("Passphrase can not be empty");
580 }
581
582 return {
583 tag,
584 title: null,
585 options: { validate },
586 initial_value: "",
587 bare: true,
588
589 render: (val, change, validated, error) => {
590 return (
591 <Stack hasGutter>
592 <p>{ fmt_to_fragments(_("Passphrase removal may prevent unlocking $0."), <b>{dev}</b>) }</p>
593 <Checkbox id="force-remove-passphrase"
594 isChecked={val !== false}
595 label={_("Confirm removal with an alternate passphrase")}
596 onChange={(_event, checked) => change(checked ? "" : false)}
597 body={val === false
598 ? <p className="slot-warning">
599 {_("Removing a passphrase without confirmation of another passphrase may prevent unlocking or key management, if other passphrases are forgotten or lost.")}
600 </p>
601 : <FormGroup label={_("Passphrase from any other key slot")} fieldId="remove-passphrase">
602 <TextInputPF id="remove-passphrase" type="password" value={val} onChange={(_event, value) => change(value)} />
603 </FormGroup>
604 }
605 />
606 </Stack>
607 );
608 }
609 };
610 };
611
612 function remove_passphrase_dialog(block, key) {
613 dialog_open({
614 Title: cockpit.format(_("Remove passphrase in key slot $0?"), key.slot),
615 Fields: [
616 RemovePassphraseField("passphrase", key, block_name(block))
617 ],
618 isFormHorizontal: false,
619 Action: {
620 DangerButton: true,
621 Title: _("Remove"),
622 action: function (vals) {
623 return slot_remove(block, key.slot, vals.passphrase);
624 }
625 }
626 });
627 }
628
629 const RemoveClevisField = (tag, key, dev) => {
630 return {
631 tag,
632 title: null,
633 options: { },
634 initial_value: "",
635 bare: true,
636
637 render: (val, change) => {
638 return (
639 <div data-field={tag}>
640 { key.url && <p>{ fmt_to_fragments(_("Remove $0?"), <b>{key.url}</b>) }</p> }
641 <p className="slot-warning">{ fmt_to_fragments(_("Removal may prevent unlocking $0."), <b>{dev}</b>) }</p>
642 </div>
643 );
644 }
645 };
646 };
647
648 function remove_clevis_dialog(client, block, key) {
649 dialog_open({
650 Title: key.url ? _("Remove Tang keyserver?") : cockpit.format(_("Remove key in slot $0?"), key.slot),
651 Fields: [
652 RemoveClevisField("keyserver", key, block_name(block))
653 ],
654 Action: {
655 DangerButton: true,
656 Title: _("Remove"),
657 action: function () {
658 return clevis_remove(block, key);
659 }
660 }
661 });
662 }
663
664 export class CryptoKeyslots extends React.Component {
665 render() {
666 const { client, block, slots, slot_error, max_slots } = this.props;
667
668 if ((slots == null && slot_error == null) || slot_error == "not-found")
669 return null;
670
671 function decode_clevis_slot(slot) {
672 if (slot.ClevisConfig) {
673 const clevis = JSON.parse(slot.ClevisConfig.v);
674 if (clevis.pin && clevis.pin == "tang" && clevis.tang) {
675 return {
676 slot: slot.Index.v,
677 type: "tang",
678 url: clevis.tang.url
679 };
680 } else {
681 return {
682 slot: slot.Index.v,
683 type: "unknown",
684 pin: clevis.pin
685 };
686 }
687 } else {
688 return {
689 slot: slot.Index.v,
690 type: "luks-passphrase"
691 };
692 }
693 }
694
695 const keys = slots ? slots.map(decode_clevis_slot).filter(k => !!k) : [];
696
697 let table;
698 if (keys.length == 0) {
699 let text;
700 if (slot_error) {
701 if (slot_error.problem == "access-denied")
702 text = _("The currently logged in user is not permitted to see information about keys.");
703 else
704 text = slot_error.toString();
705 } else {
706 text = _("No keys added");
707 }
708 table = <EmptyState>
709 <EmptyStateBody>
710 {text}
711 </EmptyStateBody>
712 </EmptyState>;
713 } else {
714 const rows = [];
715
716 const add_row = (slot, type, desc, edit, edit_excuse, remove) => {
717 rows.push(
718 <Tr key={slot} data-row-slot={slot}>
719 <Td>{type}</Td>
720 <Td>{desc}</Td>
721 <Td>{cockpit.format(_("Slot $0"), slot)}</Td>
722 <Td modifier="nowrap" className="pf-v6-c-table__action">
723 <StorageButton
724 onClick={edit}
725 ariaLabel={_("Edit")}
726 excuse={
727 edit_excuse ||
728 ((keys.length == max_slots)
729 ? _("Editing a key requires a free slot")
730 : null)
731 }
732 >
733 <EditIcon />
734 </StorageButton>
735 { "\n" }
736 <StorageButton onClick={remove}
737 ariaLabel={_("Remove")}
738 excuse={keys.length == 1 ? _("The last key slot can not be removed") : null}>
739 <MinusIcon />
740 </StorageButton>
741 </Td>
742 </Tr>
743 );
744 };
745
746 keys.sort((a, b) => a.slot - b.slot).forEach(key => {
747 if (key.type == "luks-passphrase") {
748 add_row(key.slot,
749 _("Passphrase"), "",
750 () => edit_passphrase_dialog(block, key), null,
751 () => remove_passphrase_dialog(block, key));
752 } else if (key.type == "tang") {
753 add_row(key.slot,
754 _("Keyserver"), key.url,
755 () => edit_clevis_dialog(client, block, key), null,
756 () => remove_clevis_dialog(client, block, key));
757 } else {
758 add_row(key.slot,
759 _("Unknown type"), key.pin,
760 null, _("Key slots with unknown types can not be edited here"),
761 () => remove_clevis_dialog(client, block, key));
762 }
763 });
764
765 table = (
766 <Table id="encryption-keys" aria-label={_("Keys")}>
767 <Tbody>
768 {rows}
769 </Tbody>
770 </Table>
771 );
772 }
773
774 const remaining = max_slots - keys.length;
775
776 return (
777 <>
778 <CardHeader actions={{
779 actions: <>
780 <span className="key-slot-panel-remaining">
781 { remaining < 6 ? (remaining ? cockpit.format(cockpit.ngettext("$0 slot remains", "$0 slots remain", remaining), remaining) : _("No available slots")) : null }
782 </span>
783 <StorageButton onClick={() => add_dialog(client, block)}
784 ariaLabel={_("Add")}
785 excuse={(keys.length == max_slots)
786 ? _("No free key slots")
787 : null}>
788 <PlusIcon />
789 </StorageButton>
790 </>,
791 }}>
792 <strong>{_("Keys")}</strong>
793 </CardHeader>
794 {table}
795 </>
796 );
797 }
798 }