| # Copyright 2026 The Fuchsia Authors. All rights reserved. | |
| # Use of this source code is governed by a BSD-style license that can be | |
| # found in the LICENSE file. | |
| """Host-side helpers for inspecting Fxfs KeyMint sealed volume metadata.""" | |
| import asyncio | |
| import dataclasses | |
| import json | |
| import logging | |
| import types | |
| from collections.abc import Mapping | |
| from typing import Self | |
| import fidl_fuchsia_fs as f_fs | |
| import fidl_fuchsia_fs_startup as f_fs_startup | |
| import fidl_fuchsia_io as f_io | |
| import fidl_fuchsia_security_keymint as f_keymint | |
| import fuchsia_controller_py | |
| _LOGGER = logging.getLogger(__name__) | |
| _FXFS_MONIKER = "bootstrap/fshost/fxfs" | |
| _UNENCRYPTED_VOLUME_CAPABILITY = "volumes/unencrypted" | |
| _KEYMINT_MONIKER = "core/tee_manager" | |
| _SEALING_KEYS_CAPABILITY = "fuchsia.security.keymint.SealingKeys" | |
| _KEYMINT_METADATA_PATH = "root/keys/keymint.0" | |
| _ADMIN_SERVICE_PATH = "svc/fuchsia.fs.Admin" | |
| _EXPECTED_SEALED_KEY_LABELS = ("data.data", "data.metadata") | |
| _AES256_KEY_SIZE = 32 | |
| _FIDL_TIMEOUT_SECONDS = 30.0 | |
| def _parse_u8_bytes(value: object, field_name: str) -> bytes: | |
| if not isinstance(value, list) or not value: | |
| raise ValueError( | |
| f"Expected non-empty list of bytes for KeyMint field {field_name!r}" | |
| ) | |
| for item in value: | |
| if ( | |
| not isinstance(item, int) | |
| or isinstance(item, bool) | |
| or not 0 <= item <= 255 | |
| ): | |
| raise ValueError( | |
| f"Invalid byte element {item!r} in KeyMint field {field_name!r}" | |
| ) | |
| return bytes(value) | |
| def _parse_label(label: object) -> str: | |
| if not isinstance(label, str): | |
| raise ValueError( | |
| f"Expected string label in 'sealed_keys', got {type(label).__name__}" | |
| ) | |
| return label | |
| def _connect_sealing_keys( | |
| ctx: fuchsia_controller_py.Context, | |
| ) -> f_keymint.SealingKeysClient: | |
| return f_keymint.SealingKeysClient( | |
| ctx.connect_device_proxy(_KEYMINT_MONIKER, _SEALING_KEYS_CAPABILITY) | |
| ) | |
| @dataclasses.dataclass(frozen=True) | |
| class KeymintSealedData: | |
| """On-disk KeyMint keybag metadata stored in Fxfs's unencrypted volume.""" | |
| sealing_key_info: bytes | |
| sealing_key_blob: bytes | |
| sealed_keys: Mapping[str, bytes] | |
| @classmethod | |
| def from_json_bytes(cls, raw: bytes) -> Self: | |
| """Parses serialized `crypt_policy::KeymintSealedData` JSON bytes.""" | |
| parsed = json.loads(raw.decode("utf-8")) | |
| if not isinstance(parsed, dict): | |
| raise ValueError("Expected JSON object in KeyMint metadata file") | |
| sealing_key_info = _parse_u8_bytes( | |
| parsed.get("sealing_key_info"), "sealing_key_info" | |
| ) | |
| sealing_key_blob = _parse_u8_bytes( | |
| parsed.get("sealing_key_blob"), "sealing_key_blob" | |
| ) | |
| raw_sealed_keys = parsed.get("sealed_keys") | |
| if not isinstance(raw_sealed_keys, dict): | |
| raise ValueError("Expected mapping for KeyMint field 'sealed_keys'") | |
| sealed_keys = { | |
| _parse_label(label): _parse_u8_bytes( | |
| payload, f"sealed_keys[{label!r}]" | |
| ) | |
| for label, payload in raw_sealed_keys.items() | |
| } | |
| missing_labels = tuple( | |
| label | |
| for label in _EXPECTED_SEALED_KEY_LABELS | |
| if label not in sealed_keys | |
| ) | |
| if missing_labels: | |
| raise ValueError( | |
| f"Missing expected KeyMint sealed key labels: {missing_labels}" | |
| ) | |
| return cls( | |
| sealing_key_info=sealing_key_info, | |
| sealing_key_blob=sealing_key_blob, | |
| sealed_keys=types.MappingProxyType(sealed_keys), | |
| ) | |
| async def read_sealed_data( | |
| ctx: fuchsia_controller_py.Context, | |
| ) -> KeymintSealedData: | |
| """Mounts Fxfs's unencrypted volume, reads `keys/keymint.0`, and unmounts.""" | |
| volume_proxy = f_fs_startup.VolumeClient( | |
| ctx.connect_device_proxy(_FXFS_MONIKER, _UNENCRYPTED_VOLUME_CAPABILITY) | |
| ) | |
| outgoing_server, outgoing_client = ctx.channel_create() | |
| try: | |
| ( | |
| await asyncio.wait_for( | |
| volume_proxy.mount( | |
| outgoing_directory=outgoing_server.take(), | |
| options=f_fs_startup.MountOptions(), | |
| ), | |
| timeout=_FIDL_TIMEOUT_SECONDS, | |
| ) | |
| ).unwrap() | |
| except BaseException: | |
| outgoing_client.close() | |
| volume_proxy.close_cleanly() | |
| raise | |
| outgoing_dir = f_io.DirectoryClient(outgoing_client) | |
| primary_exc: BaseException | None = None | |
| try: | |
| file_server, file_client = ctx.channel_create() | |
| file_proxy = f_io.FileClient(file_client) | |
| raw = bytearray() | |
| try: | |
| outgoing_dir.open_( | |
| path=_KEYMINT_METADATA_PATH, | |
| flags=f_io.Flags.PROTOCOL_FILE | f_io.PERM_READABLE, | |
| options=f_io.Options(), | |
| object_=file_server.take(), | |
| ) | |
| while True: | |
| chunk = ( | |
| await asyncio.wait_for( | |
| file_proxy.read(count=f_io.MAX_BUF), | |
| timeout=_FIDL_TIMEOUT_SECONDS, | |
| ) | |
| ).unwrap() | |
| if not chunk.data: | |
| break | |
| raw.extend(chunk.data) | |
| finally: | |
| try: | |
| ( | |
| await asyncio.wait_for( | |
| file_proxy.close(), | |
| timeout=_FIDL_TIMEOUT_SECONDS, | |
| ) | |
| ).unwrap() | |
| except Exception as err: | |
| _LOGGER.debug( | |
| "Ignoring error closing KeyMint metadata file: %s", err | |
| ) | |
| finally: | |
| file_proxy.close_cleanly() | |
| except BaseException as exc: | |
| primary_exc = exc | |
| raise | |
| finally: | |
| # Always unmount the unencrypted volume so fshost and recovery are not | |
| # blocked by an open handle. | |
| admin_proxy: f_fs.AdminClient | None = None | |
| try: | |
| admin_server, admin_client = ctx.channel_create() | |
| admin_proxy = f_fs.AdminClient(admin_client) | |
| outgoing_dir.open_( | |
| path=_ADMIN_SERVICE_PATH, | |
| flags=f_io.Flags.PROTOCOL_SERVICE, | |
| options=f_io.Options(), | |
| object_=admin_server.take(), | |
| ) | |
| await asyncio.wait_for( | |
| admin_proxy.shutdown(), | |
| timeout=_FIDL_TIMEOUT_SECONDS, | |
| ) | |
| except Exception as unmount_err: | |
| if primary_exc is not None: | |
| _LOGGER.warning( | |
| "Failed to unmount unencrypted volume after error: %s", | |
| unmount_err, | |
| ) | |
| else: | |
| raise | |
| finally: | |
| if admin_proxy is not None: | |
| admin_proxy.close_cleanly() | |
| outgoing_dir.close_cleanly() | |
| volume_proxy.close_cleanly() | |
| return KeymintSealedData.from_json_bytes(bytes(raw)) | |
| async def verify_keys_unseal( | |
| ctx: fuchsia_controller_py.Context, | |
| metadata: KeymintSealedData, | |
| ) -> None: | |
| """Verifies KeyMint unseals all expected AES-256 volume keys.""" | |
| sealing_keys = _connect_sealing_keys(ctx) | |
| try: | |
| for label in _EXPECTED_SEALED_KEY_LABELS: | |
| unseal_outcome = await asyncio.wait_for( | |
| sealing_keys.unseal( | |
| key_info=metadata.sealing_key_info, | |
| key_blob=metadata.sealing_key_blob, | |
| sealed_secret=metadata.sealed_keys[label], | |
| ), | |
| timeout=_FIDL_TIMEOUT_SECONDS, | |
| ) | |
| if unseal_outcome.err is not None: | |
| raise AssertionError( | |
| f"Expected KeyMint unseal to succeed for {label!r}, got " | |
| f"error {unseal_outcome.err}" | |
| ) | |
| if unseal_outcome.response is None: | |
| raise AssertionError( | |
| f"Missing KeyMint unseal response payload for {label!r}" | |
| ) | |
| actual_key_size = len(unseal_outcome.response.unsealed_secret) | |
| if actual_key_size != _AES256_KEY_SIZE: | |
| raise AssertionError( | |
| f"Unexpected unsealed key length for {label!r}: " | |
| f"expected {_AES256_KEY_SIZE}, got {actual_key_size}" | |
| ) | |
| finally: | |
| sealing_keys.close_cleanly() | |
| async def verify_replay_unseal_rejected( | |
| ctx: fuchsia_controller_py.Context, | |
| stale_metadata: KeymintSealedData, | |
| ) -> None: | |
| """Verifies replaying stale sealed blobs is rejected with FAILED_UNSEAL.""" | |
| sealing_keys = _connect_sealing_keys(ctx) | |
| try: | |
| for label in _EXPECTED_SEALED_KEY_LABELS: | |
| unseal_outcome = await asyncio.wait_for( | |
| sealing_keys.unseal( | |
| key_info=stale_metadata.sealing_key_info, | |
| key_blob=stale_metadata.sealing_key_blob, | |
| sealed_secret=stale_metadata.sealed_keys[label], | |
| ), | |
| timeout=_FIDL_TIMEOUT_SECONDS, | |
| ) | |
| if unseal_outcome.response is not None: | |
| raise AssertionError( | |
| f"Stale KeyMint sealed key {label!r} was unexpectedly " | |
| "unsealed (hardware DeleteAllKeys or ROLLBACK_RESISTANCE " | |
| "failed)." | |
| ) | |
| if unseal_outcome.err != f_keymint.UnsealError.FAILED_UNSEAL: | |
| raise AssertionError( | |
| "Expected FAILED_UNSEAL " | |
| f"({int(f_keymint.UnsealError.FAILED_UNSEAL)}) when " | |
| f"replaying stale key {label!r}, got {unseal_outcome.err!r}" | |
| ) | |
| finally: | |
| sealing_keys.close_cleanly() |