From 492cd3ddfaa149b64050ccb56d50ba577ee9a752 Mon Sep 17 00:00:00 2001 From: Erik Karulf Date: Wed, 2 Dec 2026 20:47:55 -0600 Subject: [PATCH] Add Linux TPM 2.0 support for hardware-backed identities Use a local TPM resource manager and wrapped P-256 signing keys. Add Linux CI, release packaging, and a physical hardware regression test. --- .github/workflows/ci.yml | 27 +- .github/workflows/release.yml | 26 +- Cargo.lock | 218 +++++++++++ Cargo.toml | 1 + README.md | 52 ++- crates/keystone-cli/Cargo.toml | 8 +- crates/keystone-cli/src/backend.rs | 27 +- crates/keystone-cli/src/commands/doctor.rs | 6 +- crates/keystone-cli/src/commands/inspect.rs | 6 +- crates/keystone-core/src/identity.rs | 14 +- crates/keystone-linux/Cargo.toml | 21 ++ crates/keystone-linux/src/lib.rs | 345 ++++++++++++++++++ crates/keystone-linux/tests/tpm.rs | 54 +++ crates/keystone-macos/src/aws.rs | 135 +------ crates/keystone-roles-anywhere/Cargo.toml | 1 + .../src/certificate_identity.rs | 108 ++++++ crates/keystone-roles-anywhere/src/lib.rs | 9 +- crates/keystone-windows/src/aws.rs | 130 +------ docs/DESIGN.md | 37 +- 19 files changed, 932 insertions(+), 293 deletions(-) create mode 100644 crates/keystone-linux/Cargo.toml create mode 100644 crates/keystone-linux/src/lib.rs create mode 100644 crates/keystone-linux/tests/tpm.rs create mode 100644 crates/keystone-roles-anywhere/src/certificate_identity.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 295b164..cc5345f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -# Formatting, lints, and tests on both platforms Keystone supports. +# Formatting, lints, and tests on the platforms Keystone supports. # # Only first-party actions are used, and the toolchain comes from the `rustup` # already on the runner image rather than a third-party setup action. Keystone's @@ -40,7 +40,7 @@ jobs: # failure in one says nothing about the other. fail-fast: false matrix: - os: [macos-latest, windows-latest] + os: [macos-latest, windows-latest, ubuntu-24.04] steps: - uses: actions/checkout@v7 @@ -52,6 +52,12 @@ jobs: rustc --version echo "version=$(rustc --version | tr ' ()' '-')" >> "$GITHUB_OUTPUT" + - name: Install Linux TPM dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y pkg-config libtss2-dev + # The compiler version is part of the key, not just the lockfile: a cached # `target` directory built by a different rustc is not reusable, and a # restore-keys fallback onto one produces a confusing full rebuild at best. @@ -65,7 +71,7 @@ jobs: key: ${{ runner.os }}-cargo-${{ steps.toolchain.outputs.version }}-${{ hashFiles('**/Cargo.lock') }} restore-keys: ${{ runner.os }}-cargo-${{ steps.toolchain.outputs.version }}- - # Formatting is platform-independent, so it runs once rather than twice. + # Formatting is platform-independent, so it runs once. - name: cargo fmt if: runner.os == 'macOS' run: cargo fmt --all --check @@ -73,7 +79,7 @@ jobs: - name: cargo clippy run: cargo clippy --workspace --all-targets --locked -- -D warnings - # The hardware tests early-return when the platform has no key store, and + # The hardware tests are opt-in on Linux or skip without a key store, and # GitHub's runners have neither a Secure Enclave nor a TPM. That is the # design's fail-closed behaviour observed from the outside: everything # that does not need hardware still runs, and nothing silently falls back @@ -83,8 +89,11 @@ jobs: run: cargo test --workspace --locked msrv: - name: msrv (1.88) - runs-on: macos-latest + name: msrv (1.88, ${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [macos-latest, ubuntu-24.04] steps: - uses: actions/checkout@v7 @@ -96,4 +105,10 @@ jobs: rustup toolchain install 1.88 --profile minimal rustup default 1.88 + - name: Install Linux TPM dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y pkg-config libtss2-dev + - run: cargo check --workspace --all-targets --locked diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2de015d..06fac4b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,11 +5,8 @@ # nothing else. That way the release path is exercised routinely rather than only # at the moment it matters. # -# The build matrix follows the design document's Platform Support section -# exactly: Apple Silicon macOS and x86-64 Windows. Intel macOS is listed there as -# "may be supported later after integration testing", so there is deliberately no -# `x86_64-apple-darwin` entry — shipping a binary for a configuration the project -# has not tested would make an untested claim. +# Ship Apple Silicon macOS, x86-64 Windows, and x86-64 Linux builds. Linux +# links against the TPM2 software stack from the Ubuntu 24.04 runner. name: Release on: @@ -59,6 +56,11 @@ jobs: # does not have — Windows decides by extension. A container would # add an extraction step and protect nothing. archive: none + - name: linux-x86_64 + os: ubuntu-24.04 + target: x86_64-unknown-linux-gnu + binary: keystone + archive: tar.gz steps: - uses: actions/checkout@v7 @@ -68,6 +70,12 @@ jobs: rustup default stable rustc --version + - name: Install Linux TPM dependencies + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y pkg-config libtss2-dev + # `--locked` so a release binary is built from the dependency versions in # the committed lockfile and not from whatever resolves that day. - name: Build @@ -167,13 +175,13 @@ jobs: run: | # An empty glob would expand to a literal pattern and attach nothing, # so the file list is checked before the release is created rather than - # discovered as a release with no binaries on it. Four files: an - # archive and a checksum for each of the two platforms. + # discovered as a release with no binaries on it. Six files: an + # archive and a checksum for each of the three platforms. shopt -s nullglob assets=(dist/*.tar.gz dist/*.exe dist/*.sha256) printf '%s\n' "${assets[@]}" - if [ "${#assets[@]}" -ne 4 ]; then - echo "expected 4 assets, found ${#assets[@]}" >&2 + if [ "${#assets[@]}" -ne 6 ]; then + echo "expected 6 assets, found ${#assets[@]}" >&2 exit 1 fi diff --git a/Cargo.lock b/Cargo.lock index e7e0675..aac64b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + [[package]] name = "anstream" version = "1.0.0" @@ -452,6 +461,26 @@ dependencies = [ "serde", ] +[[package]] +name = "bitfield" +version = "0.19.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b45721c9db4c7a20899d05efb7ad9235f50b256e980db30ffb229abf732934c3" +dependencies = [ + "bitfield-macros", +] + +[[package]] +name = "bitfield-macros" +version = "0.19.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0cb6f3d4773a2107b94cbeccaa5b5f0b35a88389b5d522d13d659f64317b22d" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "bitflags" version = "2.13.1" @@ -801,6 +830,26 @@ dependencies = [ "zeroize", ] +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -1016,6 +1065,12 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "hostname-validator" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f558a64ac9af88b5ba400d99b579451af0d39c6d360980045b91aac966d705e2" + [[package]] name = "http" version = "0.2.12" @@ -1305,6 +1360,7 @@ dependencies = [ "hmac 0.13.0", "keystone-core", "keystone-infra", + "keystone-linux", "keystone-macos", "keystone-pki", "keystone-roles-anywhere", @@ -1355,6 +1411,18 @@ dependencies = [ "toml", ] +[[package]] +name = "keystone-linux" +version = "0.1.3" +dependencies = [ + "keystone-core", + "keystone-pki", + "serde_json", + "sha2 0.11.1", + "time", + "tss-esapi", +] + [[package]] name = "keystone-macos" version = "0.1.3" @@ -1396,6 +1464,7 @@ dependencies = [ "base64 0.23.1", "hex", "keystone-core", + "keystone-pki", "keystone-roles-anywhere", "p256", "rand 0.8.7", @@ -1485,6 +1554,16 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" +[[package]] +name = "mbox" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d142aeadbc4e8c679fc6d93fbe7efe1c021fa7d80629e615915b519e3bc6de" +dependencies = [ + "libc", + "stable_deref_trait", +] + [[package]] name = "memchr" version = "2.8.3" @@ -1534,6 +1613,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "num-integer" version = "0.1.46" @@ -1552,6 +1642,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "oid" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c19903c598813dba001b53beeae59bb77ad4892c5c1b9b3500ce4293a0d06c2" +dependencies = [ + "serde", +] + [[package]] name = "oid-registry" version = "0.8.1" @@ -1623,6 +1722,41 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "picky-asn1" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9e56b8955035e2593f7f7e7f8d30c9c7a0ce5a5e31cc529f8f087a9e0437526" +dependencies = [ + "oid", + "serde", + "serde_bytes", +] + +[[package]] +name = "picky-asn1-der" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0bc2b14f272c0ecc6b524afbd1c46d050e131c1d388269755c5364b80b8eeb6" +dependencies = [ + "picky-asn1", + "serde", + "serde_bytes", +] + +[[package]] +name = "picky-asn1-x509" +version = "0.15.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98dd311a5e525d1200365273a509b9d07bccf3481aaa901047fdca19830ca721" +dependencies = [ + "base64 0.23.1", + "oid", + "picky-asn1", + "picky-asn1-der", + "serde", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -1645,6 +1779,12 @@ dependencies = [ "spki", ] +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "potential_utf" version = "0.1.5" @@ -1846,12 +1986,41 @@ dependencies = [ "yasna", ] +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + [[package]] name = "regex-lite" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + [[package]] name = "reqwest" version = "0.12.28" @@ -2074,6 +2243,16 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_core" version = "1.0.229" @@ -2278,6 +2457,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + [[package]] name = "tera" version = "2.4.0" @@ -2522,6 +2707,39 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "tss-esapi" +version = "7.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f10b25a84912b894d0e6d68f4a3771c923e9c44ddaaed7920cde92ed28aa84e" +dependencies = [ + "bitfield", + "enumflags2", + "getrandom 0.4.3", + "hostname-validator", + "log", + "mbox", + "num-derive", + "num-traits", + "oid", + "picky-asn1", + "picky-asn1-x509", + "regex", + "serde", + "tss-esapi-sys", + "zeroize", +] + +[[package]] +name = "tss-esapi-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7f972672926a3d3d18ecc04524720e4d20b7d1664a3fb73dbf7d4274196dbd9" +dependencies = [ + "pkg-config", + "target-lexicon", +] + [[package]] name = "typenum" version = "1.20.1" diff --git a/Cargo.toml b/Cargo.toml index afc3cbe..48623a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ repository = "https://github.com/ekarulf/keystone" [workspace.dependencies] keystone-core = { path = "crates/keystone-core" } +keystone-linux = { path = "crates/keystone-linux" } keystone-macos = { path = "crates/keystone-macos" } keystone-win32-sys = { path = "crates/keystone-win32-sys" } keystone-windows = { path = "crates/keystone-windows" } diff --git a/README.md b/README.md index 813c89b..7f8aac5 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Keystone -Hardware-backed temporary AWS credentials on macOS and Windows, plus a Secure -Enclave SSH agent on macOS. +Hardware-backed temporary AWS credentials on macOS, Windows, and Linux, plus a +Secure Enclave SSH agent on macOS. ## Status @@ -39,7 +39,7 @@ X.509 certificate, then returns ordinary temporary AWS credentials, which Keysto emits through the standard AWS `credential_process` contract. ```text -Secure Enclave (macOS) or TPM (Windows) +Secure Enclave (macOS) or TPM (Windows and Linux) P-256 signing key │ ▼ @@ -69,7 +69,7 @@ Requires a recent Rust toolchain, and hardware with the key store for the target platform: a Mac with a Secure Enclave, or a PC with a TPM 2.0 enabled in firmware. There is no software fallback: creating or using a hardware identity requires the corresponding key store. SSH identities require the macOS Secure Enclave; -the Windows TPM backend currently serves the AWS workflow. +the Windows and Linux TPM backends serve the AWS workflow. On macOS the Secure Enclave binding compiles a Swift bridge, so Xcode command line tools must be installed. On Windows nothing beyond the toolchain is needed; CNG is @@ -91,25 +91,53 @@ AR_x86_64_pc_windows_gnu=x86_64-w64-mingw32-ar \ cargo clippy --workspace --all-targets --target x86_64-pc-windows-gnu ``` -That checks the code but runs nothing: the TPM tests need a TPM, so they are -compiled only for Windows and must be run there. +That checks the Windows code. The Windows hardware tests need a Windows machine +with a TPM. + +### Linux TPM setup + +Keystone uses TPM 2.0 through the Linux kernel resource manager at +`/dev/tpmrm0`. Enable the TPM in firmware and give the account that runs +Keystone read/write access to that device. On Debian and Ubuntu, first check +the device's group with `ls -l /dev/tpmrm0`; if it is `tss`, an administrator +can run `sudo usermod -aG tss `. Sign out and back in for the +group change to take effect. + +To build on Debian or Ubuntu, install `pkg-config` and `libtss2-dev`, then +run `cargo build --release --locked -p keystone-cli`. The x86-64 Linux release +is built on Ubuntu 24.04 and needs the TPM2 TSS ESYS, MU, TCTI loader, and device +TCTI runtime libraries. On Ubuntu 24.04, these are provided by +`libtss2-esys-3.0.2-0t64`, `libtss2-mu-4.0.1-0t64`, +`libtss2-tctildr0t64`, and `libtss2-tcti-device0t64`. + +The TPM owner hierarchy must accept empty authorization. Keystone stores +the wrapped signing key in its private identity metadata and uses transient +TPM handles. Clearing the TPM or losing the metadata makes the key +unrecoverable. Linux uses file and TPM-device permissions for unattended +access, so the macOS screen-lock policy has no effect. + +Run the hardware regression test on a machine with a TPM: + +```sh +cargo test --locked -p keystone-linux --test tpm -- --ignored +``` ## Continuous integration Two workflows under `.github/workflows`: * `ci.yml` — formatting, `clippy -D warnings`, and the test suite on macOS and - Windows runners, plus a `cargo check` against the declared MSRV of 1.88. -* `release.yml` — builds `aarch64-apple-darwin` and `x86_64-pc-windows-msvc` - binaries, each with a SHA-256 checksum beside it. macOS ships as a `.tar.gz`, + Windows and Linux runners, plus a `cargo check` against the declared MSRV of 1.88. +* `release.yml` — builds `aarch64-apple-darwin`, `x86_64-pc-windows-msvc`, and + `x86_64-unknown-linux-gnu` with SHA-256 checksums. macOS and Linux use `.tar.gz`, because a tarball is what preserves the executable bit; Windows ships the `keystone.exe` itself, since Windows decides executability by extension and a - container would only add a step. A `v*` tag drafts a GitHub release with both + container would only add a step. A `v*` tag drafts a GitHub release with all three attached; a manual dispatch produces the same files as run artifacts and publishes nothing. -Neither runner has a Secure Enclave or a TPM, so the hardware tests early-return -and CI never exercises a signing path. That is the fail-closed design observed +The CI runners do not provide a Secure Enclave or a TPM. The hardware tests +skip without the hardware or require an explicit opt-in on Linux. That is the fail-closed design observed from the outside, and it is also the limit of what CI can tell you: a release binary should be run through `keystone doctor` on real hardware before it is published, which is why the release is drafted rather than published outright. diff --git a/crates/keystone-cli/Cargo.toml b/crates/keystone-cli/Cargo.toml index 72f165b..2612784 100644 --- a/crates/keystone-cli/Cargo.toml +++ b/crates/keystone-cli/Cargo.toml @@ -14,10 +14,7 @@ path = "src/main.rs" [dependencies] keystone-core.workspace = true keystone-infra.workspace = true -# `keystone-macos` builds on every target: on a non-macOS one its operations -# return `SecureEnclaveUnavailable`, which is what "no silent fallback" means for -# a cross-compiled build. `crate::backend` selects it everywhere except Windows, -# so that an unsupported platform gets the fail-closed stub rather than nothing. +# The SSH agent uses the Secure Enclave directly and fails closed on other platforms. keystone-macos.workspace = true keystone-pki.workspace = true keystone-roles-anywhere.workspace = true @@ -51,6 +48,9 @@ rustix = { workspace = true, features = ["fs"] } [target.'cfg(windows)'.dependencies] keystone-windows.workspace = true +[target.'cfg(target_os = "linux")'.dependencies] +keystone-linux.workspace = true + [dev-dependencies] rand.workspace = true diff --git a/crates/keystone-cli/src/backend.rs b/crates/keystone-cli/src/backend.rs index 0ec598f..8235fa8 100644 --- a/crates/keystone-cli/src/backend.rs +++ b/crates/keystone-cli/src/backend.rs @@ -1,6 +1,6 @@ //! Which hardware key store this build uses. //! -//! Keystone has two backends — the Secure Enclave and the Windows TPM — with the +//! Keystone has Secure Enclave and TPM backends with the //! same shape and the same guarantees. Selecting between them in one module means //! the commands are written once: they refer to [`DeviceKey`], [`KeyPolicy`], and //! [`CertificateIdentity`] without knowing which platform supplies them. @@ -9,12 +9,12 @@ //! selection and no configuration for it. A machine has the key store its hardware //! has; offering a choice would only offer a way to pick the weaker one. //! -//! A target that is neither macOS nor Windows gets the Secure Enclave backend, +//! A target that is neither macOS, Linux, nor Windows gets the Secure Enclave backend, //! whose non-macOS build is a fail-closed stub. That is deliberate: an unsupported //! platform must produce "no hardware-backed key store is available", not a //! working software key. -#[cfg(not(windows))] +#[cfg(not(any(windows, target_os = "linux")))] mod selected { pub use keystone_macos::aws::CertificateIdentity; pub use keystone_macos::enclave::SecureEnclaveIdentity as DeviceKey; @@ -32,6 +32,25 @@ mod selected { } } +#[cfg(target_os = "linux")] +mod selected { + pub use keystone_linux::{TpmIdentity as DeviceKey, TpmPolicy as KeyPolicy}; + + pub type CertificateIdentity = keystone_roles_anywhere::CertificateIdentity; + + pub const KEY_STORE: &str = "TPM 2.0"; + + pub fn report() -> super::KeyStoreReport { + let detail = keystone_linux::check_available() + .err() + .map(|error| error.to_string()); + super::KeyStoreReport { + available: detail.is_none(), + detail, + } + } +} + #[cfg(windows)] mod selected { pub use keystone_windows::aws::CertificateIdentity; @@ -54,7 +73,7 @@ pub use selected::{report, CertificateIdentity, DeviceKey, KeyPolicy, KEY_STORE} /// What the key store reports about this machine, for `keystone doctor`. /// -/// The two backends' report types are structurally identical but distinct, so they +/// The backends' report types are structurally identical but distinct, so they /// are normalized here rather than making every caller cfg on the platform. /// `supported_platform` is dropped: it only ever distinguishes "wrong build" from /// "no hardware", and both are already spelled out in `detail`. diff --git a/crates/keystone-cli/src/commands/doctor.rs b/crates/keystone-cli/src/commands/doctor.rs index 1509d4d..e9b7134 100644 --- a/crates/keystone-cli/src/commands/doctor.rs +++ b/crates/keystone-cli/src/commands/doctor.rs @@ -284,7 +284,11 @@ fn check_identity( Outcome::Pass(format!( "restored {} ({})", key.key_id(), - profile.key_accessibility.describe() + if cfg!(target_os = "linux") { + crate::backend::KeyPolicy::new(profile.key_accessibility).describe() + } else { + profile.key_accessibility.describe().to_owned() + } )), ); Some(key) diff --git a/crates/keystone-cli/src/commands/inspect.rs b/crates/keystone-cli/src/commands/inspect.rs index 6a2001d..e7f0011 100644 --- a/crates/keystone-cli/src/commands/inspect.rs +++ b/crates/keystone-cli/src/commands/inspect.rs @@ -42,7 +42,11 @@ pub fn run(context: &Context, args: &ProfileArgs) -> Result<()> { } out.push(format!( "Key accessibility: {}", - profile.key_accessibility.describe() + if cfg!(target_os = "linux") { + crate::backend::KeyPolicy::new(profile.key_accessibility).describe() + } else { + profile.key_accessibility.describe().to_owned() + } )); out.push(format!("Device URI SAN: {}", key_id.device_san_uri())); } diff --git a/crates/keystone-core/src/identity.rs b/crates/keystone-core/src/identity.rs index 471f87c..7553095 100644 --- a/crates/keystone-core/src/identity.rs +++ b/crates/keystone-core/src/identity.rs @@ -130,7 +130,7 @@ fn abbreviate(value: &str) -> String { /// What kind of key backs an identity. /// /// Recorded explicitly so Keystone can refuse an identity it does not understand -/// rather than misinterpreting its opaque reference. The two variants are not +/// rather than misinterpreting its opaque reference. The variants are not /// interchangeable: the reference means different things, and a backend that read /// the other's would either fail obscurely or, worse, resolve to some unrelated /// key. Each backend checks this field before touching the reference. @@ -144,6 +144,9 @@ pub enum KeyType { /// key blob: CNG persists the key itself and hands back nothing to store. #[serde(rename = "windows-tpm-p256-signing")] WindowsTpmP256Signing, + /// A TPM-generated signing key held as a wrapped TPM object. + #[serde(rename = "linux-tpm-p256-signing")] + LinuxTpmP256Signing, } impl KeyType { @@ -156,6 +159,7 @@ impl KeyType { match self { Self::SecureEnclaveP256Signing => "macOS", Self::WindowsTpmP256Signing => "Windows", + Self::LinuxTpmP256Signing => "Linux", } } } @@ -163,8 +167,8 @@ impl KeyType { /// The persisted public record of a Keystone identity. /// /// `opaque_key_reference` is whatever the backend needs to find its key again, -/// and its meaning depends on `key_type`. Neither form is an exported private -/// scalar — the private key cannot be reconstructed from either on another device +/// and its meaning depends on `key_type`. The reference contains no exported private +/// scalar and cannot be used on another device /// — but it is the only handle to the key, so losing or replacing this file makes /// the identity unusable. #[derive(Debug, Clone, Serialize, Deserialize)] @@ -178,8 +182,8 @@ pub struct IdentityMetadata { /// The backend's handle to the private key, base64-encoded. /// /// CryptoKit's wrapped Secure Enclave blob for a Secure Enclave key; the CNG - /// key name for a Windows TPM key. Base64 either way so the field's encoding - /// does not depend on the variant. + /// key name for Windows; the wrapped TPM object and its public half for Linux. + /// The field is base64 regardless of the variant. pub opaque_key_reference: String, #[serde(with = "rfc3339")] pub created_at: OffsetDateTime, diff --git a/crates/keystone-linux/Cargo.toml b/crates/keystone-linux/Cargo.toml new file mode 100644 index 0000000..6378284 --- /dev/null +++ b/crates/keystone-linux/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "keystone-linux" +description = "TPM 2.0-backed signing on Linux" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[target.'cfg(target_os = "linux")'.dependencies] +keystone-core.workspace = true +keystone-pki.workspace = true +sha2.workspace = true +time.workspace = true +tss-esapi = "=7.7.0" + +[target.'cfg(target_os = "linux")'.dev-dependencies] +serde_json.workspace = true + +[lints] +workspace = true diff --git a/crates/keystone-linux/src/lib.rs b/crates/keystone-linux/src/lib.rs new file mode 100644 index 0000000..813f981 --- /dev/null +++ b/crates/keystone-linux/src/lib.rs @@ -0,0 +1,345 @@ +//! Hardware-backed P-256 signing through the Linux TPM resource manager. +#![cfg(target_os = "linux")] + +use std::fmt; +use std::fs::OpenOptions; + +use keystone_core::config::KeyAccessibility; +use keystone_core::error::{KeystoneError, Result}; +use keystone_core::identity::{IdentityMetadata, KeyId, KeyType}; +use keystone_core::signer::{DerEcdsaSignature, KeystoneSigningIdentity, PrehashedSigner}; +use sha2::{Digest as _, Sha256}; +use time::OffsetDateTime; +use tss_esapi::attributes::{ObjectAttributesBuilder, SessionAttributesBuilder}; +use tss_esapi::constants::{tss::*, SessionType}; +use tss_esapi::handles::KeyHandle; +use tss_esapi::interface_types::{ + algorithm::{HashingAlgorithm, PublicAlgorithm}, + ecc::EccCurve, + resource_handles::Hierarchy, + session_handles::AuthSession, +}; +use tss_esapi::structures::{ + EccPoint, EccScheme, HashScheme, Private, Public, PublicBuilder, PublicEccParametersBuilder, + Signature, SignatureScheme, SymmetricDefinitionObject, +}; +use tss_esapi::tcti_ldr::TctiNameConf; +use tss_esapi::traits::{Marshall, UnMarshall}; +use tss_esapi::tss2_esys::TPMT_TK_HASHCHECK; +use tss_esapi::{utils::create_unrestricted_signing_ecc_public, Context}; + +const DEVICE: &str = "/dev/tpmrm0"; +const CIPHER: SymmetricDefinitionObject = SymmetricDefinitionObject::AES_128_CFB; + +#[derive(Debug, Default, Clone, Copy)] +pub struct TpmPolicy(KeyAccessibility); + +impl TpmPolicy { + pub fn new(accessibility: KeyAccessibility) -> Self { + Self(accessibility) + } + + pub fn accessibility(self) -> KeyAccessibility { + self.0 + } + + pub fn describe(self) -> String { + format!( + "TPM-bound key with unattended signing. Linux access depends on file and device \ + permissions. The configured accessibility ({}) applies only on macOS.", + self.0.describe() + ) + } +} + +/// The encrypted TPM object is usable only under the same TPM's owner primary. +/// Neither creation nor signing allocates a persistent handle. +pub struct TpmIdentity { + key_id: KeyId, + public: Public, + private: Private, + public_key: [u8; 65], +} + +impl fmt::Debug for TpmIdentity { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TpmIdentity") + .field("key_id", &self.key_id) + .finish_non_exhaustive() + } +} + +pub struct GeneratedIdentity { + pub identity: TpmIdentity, + pub metadata: IdentityMetadata, +} + +impl TpmIdentity { + pub fn generate( + key_id: KeyId, + _policy: TpmPolicy, + now: OffsetDateTime, + ) -> Result { + let (mut context, parent) = open_tpm()?; + let key = tpm_result( + "create P-256 signing key", + context.create(parent, signing_template()?, None, None, None, None), + )?; + let reference = encode_reference(&key.out_public, &key.out_private)?; + let public_key = public_key(&key.out_public)?; + let identity = Self { + key_id: key_id.clone(), + public: key.out_public, + private: key.out_private, + public_key, + }; + let metadata = IdentityMetadata::with_key_type( + key_id, + KeyType::LinuxTpmP256Signing, + &public_key, + &reference, + now, + ); + Ok(GeneratedIdentity { identity, metadata }) + } + + pub fn restore(metadata: &IdentityMetadata, _policy: TpmPolicy) -> Result { + metadata.validate()?; + if metadata.key_type != KeyType::LinuxTpmP256Signing { + return Err(KeystoneError::InvalidConfiguration(format!( + "identity {} is a {} key, which cannot be used on Linux", + metadata.key_id, + metadata.key_type.platform() + ))); + } + let (public, private) = decode_reference(&metadata.opaque_key_reference_bytes()?)?; + let public_key = public_key(&public)?; + if metadata.public_key_sec1_bytes()? != public_key { + return Err(KeystoneError::KeyUnavailable); + } + let identity = Self { + key_id: metadata.key_id.clone(), + public, + private, + public_key, + }; + // TPM2_Load checks that this TPM can unwrap the object and that the + // protected private blob belongs to this exact public area. + let (mut context, parent) = open_tpm()?; + identity.load(&mut context, parent)?; + Ok(identity) + } + + fn load(&self, context: &mut Context, parent: KeyHandle) -> Result { + tpm_result( + "load wrapped P-256 key", + context.load(parent, self.private.clone(), self.public.clone()), + ) + } + + pub fn self_test(&self) -> Result<()> { + let message = b"keystone linux tpm signing self-test"; + let signature = self.sign_message_ecdsa_sha256(message)?; + keystone_pki::verify_der_signature(&self.public_key, message, signature.as_bytes()) + } +} + +impl KeystoneSigningIdentity for TpmIdentity { + fn key_id(&self) -> &KeyId { + &self.key_id + } + + fn public_key_sec1(&self) -> Result<[u8; 65]> { + Ok(self.public_key) + } + + fn sign_message_ecdsa_sha256(&self, message: &[u8]) -> Result { + self.sign_prehashed_sha256(&Sha256::digest(message).into()) + } +} + +impl PrehashedSigner for TpmIdentity { + fn sign_prehashed_sha256(&self, digest: &[u8; 32]) -> Result { + let digest = tpm_result("encode SHA-256 digest", digest.as_slice().try_into())?; + let (mut context, parent) = open_tpm()?; + let key = self.load(&mut context, parent)?; + // An unrestricted signing key accepts a software-computed digest + // without a TPM hash-validation ticket. + let validation = TPMT_TK_HASHCHECK { + tag: TPM2_ST_HASHCHECK, + hierarchy: TPM2_RH_NULL, + digest: Default::default(), + }; + let validation = tpm_result("encode empty hash-validation ticket", validation.try_into())?; + let signature = tpm_result( + "sign with P-256 key", + context.sign(key, digest, SignatureScheme::Null, validation), + )?; + let Signature::EcDsa(signature) = signature else { + return Err(KeystoneError::SecureEnclave( + "TPM returned a non-ECDSA signature".into(), + )); + }; + let mut raw = [0; 64]; + write_p256_component(signature.signature_r().value(), &mut raw[..32])?; + write_p256_component(signature.signature_s().value(), &mut raw[32..])?; + keystone_pki::raw_to_der(&raw) + } +} + +pub fn check_available() -> Result<()> { + open_tpm().map(drop) +} + +fn open_tpm() -> Result<(Context, KeyHandle)> { + // Pin the local kernel device so TCTI variables cannot redirect operations + // to a simulator. Open explicitly to report permissions without ESAPI logs. + OpenOptions::new() + .read(true) + .write(true) + .open(DEVICE) + .map_err(|err| KeystoneError::io(format!("open TPM device {DEVICE}"), err))?; + let device = tpm_result("parse TPM device path", DEVICE.parse())?; + let mut context = tpm_result( + "open TPM 2.0 resource manager", + Context::new(TctiNameConf::Device(device)), + )?; + let template = storage_template()?; + let parent = tpm_result( + "create TPM owner storage primary", + context.execute_with_session(Some(AuthSession::Password), |context| { + context.create_primary(Hierarchy::Owner, template, None, None, None, None) + }), + )? + .key_handle; + // Salt the HMAC session with the TPM's storage primary. The context + // manages cleanup of the session and its transient keys, including on error. + let session = tpm_result( + "start salted TPM session", + context.start_auth_session( + Some(parent), + None, + None, + SessionType::Hmac, + CIPHER.into(), + HashingAlgorithm::Sha256, + ), + )? + .ok_or_else(|| KeystoneError::SecureEnclave("TPM returned no HMAC session".into()))?; + let (attributes, mask) = SessionAttributesBuilder::new() + .with_decrypt(true) + .with_encrypt(true) + .build(); + tpm_result( + "configure TPM session", + context.tr_sess_set_attributes(session, attributes, mask), + )?; + context.set_sessions((Some(session), None, None)); + Ok((context, parent)) +} + +fn storage_template() -> Result { + // Keep this template stable: changing it would derive a different primary + // from the same owner seed, making existing wrapped keys unusable. + let attributes = tpm_result( + "build storage key attributes", + ObjectAttributesBuilder::new() + .with_fixed_tpm(true) + .with_fixed_parent(true) + .with_sensitive_data_origin(true) + .with_user_with_auth(true) + .with_decrypt(true) + .with_restricted(true) + .build(), + )?; + let parameters = tpm_result( + "build storage key parameters", + PublicEccParametersBuilder::new_restricted_decryption_key(CIPHER, EccCurve::NistP256) + .build(), + )?; + tpm_result( + "build TPM storage key template", + PublicBuilder::new() + .with_public_algorithm(PublicAlgorithm::Ecc) + .with_name_hashing_algorithm(HashingAlgorithm::Sha256) + .with_object_attributes(attributes) + .with_ecc_parameters(parameters) + .with_ecc_unique_identifier(EccPoint::default()) + .build(), + ) +} + +fn signing_template() -> Result { + tpm_result( + "build P-256 signing key template", + create_unrestricted_signing_ecc_public( + EccScheme::EcDsa(HashScheme::new(HashingAlgorithm::Sha256)), + EccCurve::NistP256, + ), + ) +} + +fn encode_reference(public: &Public, private: &Private) -> Result> { + let public = tpm_result("marshal TPM public area", public.marshall())?; + let public_len = u16::try_from(public.len()).map_err(|_| KeystoneError::KeyUnavailable)?; + let mut bytes = public_len.to_be_bytes().to_vec(); + bytes.extend_from_slice(&public); + bytes.extend_from_slice(private.value()); + Ok(bytes) +} + +fn decode_reference(bytes: &[u8]) -> Result<(Public, Private)> { + let (length, payload) = bytes + .split_first_chunk::<2>() + .ok_or(KeystoneError::KeyUnavailable)?; + let (public_bytes, private_bytes) = payload + .split_at_checked(usize::from(u16::from_be_bytes(*length))) + .ok_or(KeystoneError::KeyUnavailable)?; + if private_bytes.is_empty() { + return Err(KeystoneError::KeyUnavailable); + } + let private = Private::try_from(private_bytes).map_err(|_| KeystoneError::KeyUnavailable)?; + let public = Public::unmarshall(public_bytes).map_err(|_| KeystoneError::KeyUnavailable)?; + if encode_reference(&public, &private)? != bytes { + return Err(KeystoneError::KeyUnavailable); + } + Ok((public, private)) +} + +fn public_key(public: &Public) -> Result<[u8; 65]> { + let Public::Ecc { unique, .. } = public else { + return Err(KeystoneError::KeyUnavailable); + }; + // Check the complete public template (including non-migratable and + // TPM-generated attributes), allowing only the coordinates to vary. + let mut expected = signing_template()?; + if let Public::Ecc { + unique: expected, .. + } = &mut expected + { + *expected = unique.clone(); + } + if *public != expected { + return Err(KeystoneError::KeyUnavailable); + } + let mut sec1 = [0; 65]; + sec1[0] = 4; + write_p256_component(unique.x().value(), &mut sec1[1..33])?; + write_p256_component(unique.y().value(), &mut sec1[33..])?; + Ok(sec1) +} + +fn write_p256_component(component: &[u8], dest: &mut [u8]) -> Result<()> { + if component.is_empty() || component.len() > dest.len() { + return Err(KeystoneError::SecureEnclave( + "TPM returned an invalid P-256 component".into(), + )); + } + let offset = dest.len() - component.len(); + dest[offset..].copy_from_slice(component); + Ok(()) +} + +fn tpm_result(operation: &str, result: tss_esapi::Result) -> Result { + result.map_err(|err| KeystoneError::SecureEnclave(format!("{operation}: {err}"))) +} diff --git a/crates/keystone-linux/tests/tpm.rs b/crates/keystone-linux/tests/tpm.rs new file mode 100644 index 0000000..0ebd7ab --- /dev/null +++ b/crates/keystone-linux/tests/tpm.rs @@ -0,0 +1,54 @@ +#![cfg(target_os = "linux")] + +use keystone_core::error::KeystoneError; +use keystone_core::identity::{IdentityMetadata, KeyId, KeyType}; +use keystone_core::signer::{KeystoneSigningIdentity, PrehashedSigner}; +use keystone_linux::{TpmIdentity, TpmPolicy}; +use sha2::{Digest, Sha256}; +use time::OffsetDateTime; + +#[test] +#[ignore = "requires a physical TPM 2.0 and access to /dev/tpmrm0"] +fn generates_restores_and_signs_with_the_same_tpm_key() { + let policy = TpmPolicy::default(); + let generated = TpmIdentity::generate(KeyId::generate(), policy, OffsetDateTime::UNIX_EPOCH) + .expect("create a hardware-backed key"); + assert_eq!(generated.metadata.key_type, KeyType::LinuxTpmP256Signing); + let public = generated.identity.public_key_sec1().unwrap(); + let persisted = serde_json::to_vec(&generated.metadata).unwrap(); + drop(generated); + + let metadata: IdentityMetadata = serde_json::from_slice(&persisted).unwrap(); + let restored = TpmIdentity::restore(&metadata, policy).expect("reopen the wrapped key"); + assert_eq!(restored.key_id(), &metadata.key_id); + assert_eq!(restored.public_key_sec1().unwrap(), public); + let message = b"verify the TPM signs the SHA-256 digest exactly once"; + let signature = restored.sign_message_ecdsa_sha256(message).unwrap(); + keystone_pki::verify_der_signature(&public, message, signature.as_bytes()).unwrap(); + assert!(keystone_pki::verify_der_signature(&public, b"wrong", signature.as_bytes()).is_err()); + let signature = restored + .sign_prehashed_sha256(&Sha256::digest(message).into()) + .unwrap(); + keystone_pki::verify_der_signature(&public, message, signature.as_bytes()).unwrap(); + + let other = + TpmIdentity::generate(KeyId::generate(), policy, OffsetDateTime::UNIX_EPOCH).unwrap(); + let mut mismatched = metadata.clone(); + mismatched.opaque_key_reference = other.metadata.opaque_key_reference; + assert!(matches!( + TpmIdentity::restore(&mismatched, policy), + Err(KeystoneError::KeyUnavailable) + )); + + let mut reference = metadata.opaque_key_reference_bytes().unwrap(); + // Keep the same public area but corrupt the integrity-protected TPM blob. + *reference.last_mut().unwrap() ^= 1; + let corrupt = IdentityMetadata::with_key_type( + metadata.key_id, + metadata.key_type, + &public, + &reference, + metadata.created_at, + ); + assert!(TpmIdentity::restore(&corrupt, policy).is_err()); +} diff --git a/crates/keystone-macos/src/aws.rs b/crates/keystone-macos/src/aws.rs index cefe538..e066afe 100644 --- a/crates/keystone-macos/src/aws.rs +++ b/crates/keystone-macos/src/aws.rs @@ -1,119 +1,8 @@ //! Binding a Secure Enclave key to its certificate for AWS. -//! -//! [`CertificateIdentity`] pairs a [`SecureEnclaveIdentity`] with the certificate -//! AWS should see, and implements -//! [`AwsX509Identity`](keystone_roles_anywhere::AwsX509Identity) over the two. -//! -//! The pairing is checked at construction, not at signing time. A key and -//! certificate that do not match produce an AWS rejection whose message names -//! neither, so the mismatch is caught here where it can be described. - -use keystone_core::error::{KeystoneError, Result}; -use keystone_core::identity::KeyId; -use keystone_core::signer::{DerEcdsaSignature, KeystoneSigningIdentity}; -use keystone_pki::validate::{validate_device_certificate, ValidationContext}; -use keystone_pki::ParsedCertificate; -use keystone_roles_anywhere::AwsX509Identity; -use time::OffsetDateTime; use crate::enclave::SecureEnclaveIdentity; -/// A Secure Enclave key together with the certificate that names it. -/// -/// This is what `keystone credential-process` hands to the Roles Anywhere client. -#[derive(Debug)] -pub struct CertificateIdentity { - identity: SecureEnclaveIdentity, - certificate: ParsedCertificate, - /// Intermediates to present, leaf-to-root, excluding the leaf and the anchor. - /// - /// Empty for an ephemeral-CA bootstrap, where the issuing CA *is* the trust - /// anchor and AWS already holds it. - chain: Vec>, -} - -impl CertificateIdentity { - /// Pair a key with its certificate, verifying they belong together. - /// - /// Runs the full device-certificate validation — version, end-entity, - /// `digitalSignature`, validity window, public-key match, and URI SAN — so a - /// certificate that AWS would reject, or that names another key or device, - /// fails before any request is built. - pub fn new( - identity: SecureEnclaveIdentity, - certificate: ParsedCertificate, - chain: Vec>, - now: OffsetDateTime, - ) -> Result { - let context = ValidationContext::new(now) - .expecting_key(identity.public_key_sec1()?) - .expecting_key_id(identity.key_id().clone()); - validate_device_certificate(&certificate, &context)?; - - for (index, der) in chain.iter().enumerate() { - // Parsing is the check: a chain entry that is not a certificate would - // otherwise be base64-encoded into a header and rejected remotely. - ParsedCertificate::from_der(der).map_err(|error| { - KeystoneError::InvalidCertificateChain(format!( - "chain entry {index} is not a usable certificate: {error}" - )) - })?; - } - - Ok(Self { - identity, - certificate, - chain, - }) - } - - pub fn key_id(&self) -> &KeyId { - self.identity.key_id() - } - - pub fn certificate(&self) -> &ParsedCertificate { - &self.certificate - } - - pub fn identity(&self) -> &SecureEnclaveIdentity { - &self.identity - } - - /// Confirm the enclave can still sign for this certificate. - /// - /// What `keystone doctor` and `keystone test` run before reporting the profile - /// healthy — it needs no network and no AWS credentials. - pub fn verify_signing_path(&self, message: &[u8]) -> Result<()> { - let signature = self.identity.sign_message_ecdsa_sha256(message)?; - keystone_pki::ephemeral_ca::verify_device_signature(&self.certificate, message, &signature) - } -} - -impl AwsX509Identity for CertificateIdentity { - fn certificate_serial_decimal(&self) -> Result { - Ok(self.certificate.serial_decimal.clone()) - } - - fn leaf_certificate_der(&self) -> &[u8] { - self.certificate.der() - } - - fn certificate_chain_der(&self) -> &[Vec] { - &self.chain - } - - /// Sign the Roles Anywhere string-to-sign. - /// - /// The string-to-sign is passed as a *message*: SHA-256 is applied once, by - /// CryptoKit. This matches the official helper's - /// `Sign(rand, stringToSign, crypto.SHA256)`. Hashing here first would hash - /// twice. - fn sign_string_to_sign(&self, string_to_sign: &[u8]) -> Result> { - self.identity - .sign_message_ecdsa_sha256(string_to_sign) - .map(DerEcdsaSignature::into_bytes) - } -} +pub type CertificateIdentity = keystone_roles_anywhere::CertificateIdentity; /// These need a real key, so they are compiled only where one can exist. /// @@ -125,7 +14,13 @@ mod tests { use super::*; use crate::access::AccessPolicy; use crate::enclave::{self, SecureEnclaveIdentity}; + use keystone_core::error::KeystoneError; + use keystone_core::identity::KeyId; + use keystone_core::signer::KeystoneSigningIdentity; use keystone_pki::params::{DeviceCertificateSpec, EphemeralCaSpec}; + use keystone_pki::ParsedCertificate; + use keystone_roles_anywhere::AwsX509Identity; + use time::OffsetDateTime; const NOW: OffsetDateTime = time::macros::datetime!(2026-07-26 01:15:00 UTC); @@ -255,9 +150,8 @@ mod tests { return; }; let expired = identity.certificate().not_after + time::Duration::days(1); - let error = - CertificateIdentity::new(identity.identity, identity.certificate, Vec::new(), expired) - .unwrap_err(); + let (key, certificate) = identity.into_parts(); + let error = CertificateIdentity::new(key, certificate, Vec::new(), expired).unwrap_err(); assert!( matches!(error, KeystoneError::CertificateExpired(_)), "{error}" @@ -269,13 +163,10 @@ mod tests { let Some((identity, _)) = bootstrap() else { return; }; - let error = CertificateIdentity::new( - identity.identity, - identity.certificate, - vec![b"not a certificate".to_vec()], - NOW, - ) - .unwrap_err(); + let (key, certificate) = identity.into_parts(); + let error = + CertificateIdentity::new(key, certificate, vec![b"not a certificate".to_vec()], NOW) + .unwrap_err(); assert!( matches!(error, KeystoneError::InvalidCertificateChain(_)), "{error}" diff --git a/crates/keystone-roles-anywhere/Cargo.toml b/crates/keystone-roles-anywhere/Cargo.toml index 975a82a..e520633 100644 --- a/crates/keystone-roles-anywhere/Cargo.toml +++ b/crates/keystone-roles-anywhere/Cargo.toml @@ -14,6 +14,7 @@ testing = ["dep:p256", "dep:rand"] [dependencies] keystone-core.workspace = true +keystone-pki.workspace = true base64.workspace = true hex.workspace = true diff --git a/crates/keystone-roles-anywhere/src/certificate_identity.rs b/crates/keystone-roles-anywhere/src/certificate_identity.rs new file mode 100644 index 0000000..1b272e9 --- /dev/null +++ b/crates/keystone-roles-anywhere/src/certificate_identity.rs @@ -0,0 +1,108 @@ +//! Pair a hardware signer with its validated X.509 certificate. + +use crate::AwsX509Identity; +use keystone_core::error::{KeystoneError, Result}; +use keystone_core::identity::KeyId; +use keystone_core::signer::{DerEcdsaSignature, KeystoneSigningIdentity}; +use keystone_pki::validate::{validate_device_certificate, ValidationContext}; +use keystone_pki::ParsedCertificate; +use time::OffsetDateTime; + +/// A hardware-backed key together with the certificate that names it. +/// +/// This is what `keystone credential-process` hands to the Roles Anywhere client. +#[derive(Debug)] +pub struct CertificateIdentity { + identity: K, + certificate: ParsedCertificate, + /// Intermediates to present, leaf-to-root, excluding the leaf and the anchor. + /// + /// Empty for an ephemeral-CA bootstrap, where the issuing CA *is* the trust + /// anchor and AWS already holds it. + chain: Vec>, +} + +impl CertificateIdentity { + /// Pair a key with its certificate, verifying they belong together. + /// + /// Runs the full device-certificate validation — version, end-entity, + /// `digitalSignature`, validity window, public-key match, and URI SAN — so a + /// certificate that AWS would reject, or that names another key or device, + /// fails before any request is built. + pub fn new( + identity: K, + certificate: ParsedCertificate, + chain: Vec>, + now: OffsetDateTime, + ) -> Result { + let context = ValidationContext::new(now) + .expecting_key(identity.public_key_sec1()?) + .expecting_key_id(identity.key_id().clone()); + validate_device_certificate(&certificate, &context)?; + + for (index, der) in chain.iter().enumerate() { + // Parsing is the check: a chain entry that is not a certificate would + // otherwise be base64-encoded into a header and rejected remotely. + ParsedCertificate::from_der(der).map_err(|error| { + KeystoneError::InvalidCertificateChain(format!( + "chain entry {index} is not a usable certificate: {error}" + )) + })?; + } + + Ok(Self { + identity, + certificate, + chain, + }) + } + + pub fn key_id(&self) -> &KeyId { + self.identity.key_id() + } + + pub fn certificate(&self) -> &ParsedCertificate { + &self.certificate + } + + pub fn identity(&self) -> &K { + &self.identity + } + + /// Recover the key and leaf certificate from this pairing. + pub fn into_parts(self) -> (K, ParsedCertificate) { + (self.identity, self.certificate) + } + + /// Confirm the hardware key can still sign for this certificate. + /// + /// What `keystone doctor` and `keystone test` run before reporting the profile + /// healthy — it needs no network and no AWS credentials. + pub fn verify_signing_path(&self, message: &[u8]) -> Result<()> { + let signature = self.identity.sign_message_ecdsa_sha256(message)?; + keystone_pki::ephemeral_ca::verify_device_signature(&self.certificate, message, &signature) + } +} + +impl AwsX509Identity for CertificateIdentity { + fn certificate_serial_decimal(&self) -> Result { + Ok(self.certificate.serial_decimal.clone()) + } + + fn leaf_certificate_der(&self) -> &[u8] { + self.certificate.der() + } + + fn certificate_chain_der(&self) -> &[Vec] { + &self.chain + } + + /// Sign the Roles Anywhere string-to-sign. + /// + /// Pass the original message so the backend applies SHA-256 exactly once. + fn sign_string_to_sign(&self, string_to_sign: &[u8]) -> Result> { + self.identity + .sign_message_ecdsa_sha256(string_to_sign) + .map(DerEcdsaSignature::into_bytes) + } +} diff --git a/crates/keystone-roles-anywhere/src/lib.rs b/crates/keystone-roles-anywhere/src/lib.rs index d2005d9..1c21f36 100644 --- a/crates/keystone-roles-anywhere/src/lib.rs +++ b/crates/keystone-roles-anywhere/src/lib.rs @@ -1,14 +1,14 @@ //! The IAM Roles Anywhere `CreateSession` client. //! //! This crate turns an X.509 signing identity into temporary AWS credentials. -//! It knows nothing about the Secure Enclave: callers supply an -//! [`request::AwsX509Identity`], which `keystone-macos` implements over a -//! hardware key and [`testing::TestIdentity`] implements over a software key -//! for tests. +//! Callers supply an [`request::AwsX509Identity`]. [`CertificateIdentity`] +//! pairs the hardware signer with a validated certificate, and +//! [`testing::TestIdentity`] provides a software identity for tests. //! //! The signing details are ported from the official AWS credential helper; see //! [`signing`] for the specific ways Roles Anywhere departs from SigV4. +mod certificate_identity; pub mod client; pub mod request; pub mod response; @@ -23,6 +23,7 @@ pub mod signing; #[cfg(any(test, feature = "testing"))] pub mod testing; +pub use certificate_identity::CertificateIdentity; pub use client::{RolesAnywhereClient, TransportConfig}; pub use request::{ endpoint_for_region, AwsX509Identity, CreateSessionRequest, RolesAnywhereRequestSigner, diff --git a/crates/keystone-windows/src/aws.rs b/crates/keystone-windows/src/aws.rs index c96daeb..82d1fe9 100644 --- a/crates/keystone-windows/src/aws.rs +++ b/crates/keystone-windows/src/aws.rs @@ -1,118 +1,8 @@ -//! Binding a TPM key to its certificate for AWS. -//! -//! The exact counterpart of `keystone_macos::aws`, and for the same reason: a key -//! and certificate that do not match produce an AWS rejection whose message names -//! neither, so the mismatch is caught here where it can be described. - -use keystone_core::error::{KeystoneError, Result}; -use keystone_core::identity::KeyId; -use keystone_core::signer::{DerEcdsaSignature, KeystoneSigningIdentity}; -use keystone_pki::validate::{validate_device_certificate, ValidationContext}; -use keystone_pki::ParsedCertificate; -use keystone_roles_anywhere::AwsX509Identity; -use time::OffsetDateTime; +//! Binding a Windows TPM key to its certificate for AWS. use crate::tpm::TpmIdentity; -/// A TPM key together with the certificate that names it. -/// -/// This is what `keystone credential-process` hands to the Roles Anywhere client -/// on Windows. -#[derive(Debug)] -pub struct CertificateIdentity { - identity: TpmIdentity, - certificate: ParsedCertificate, - /// Intermediates to present, leaf-to-root, excluding the leaf and the anchor. - /// - /// Empty for an ephemeral-CA bootstrap, where the issuing CA *is* the trust - /// anchor and AWS already holds it. - chain: Vec>, -} - -impl CertificateIdentity { - /// Pair a key with its certificate, verifying they belong together. - /// - /// Runs the full device-certificate validation — version, end-entity, - /// `digitalSignature`, validity window, public-key match, and URI SAN — so a - /// certificate that AWS would reject, or that names another key or device, - /// fails before any request is built. - pub fn new( - identity: TpmIdentity, - certificate: ParsedCertificate, - chain: Vec>, - now: OffsetDateTime, - ) -> Result { - let context = ValidationContext::new(now) - .expecting_key(identity.public_key_sec1()?) - .expecting_key_id(identity.key_id().clone()); - validate_device_certificate(&certificate, &context)?; - - for (index, der) in chain.iter().enumerate() { - // Parsing is the check: a chain entry that is not a certificate would - // otherwise be base64-encoded into a header and rejected remotely. - ParsedCertificate::from_der(der).map_err(|error| { - KeystoneError::InvalidCertificateChain(format!( - "chain entry {index} is not a usable certificate: {error}" - )) - })?; - } - - Ok(Self { - identity, - certificate, - chain, - }) - } - - pub fn key_id(&self) -> &KeyId { - self.identity.key_id() - } - - pub fn certificate(&self) -> &ParsedCertificate { - &self.certificate - } - - pub fn identity(&self) -> &TpmIdentity { - &self.identity - } - - /// Confirm the TPM can still sign for this certificate. - /// - /// What `keystone doctor` and `keystone test` run before reporting the profile - /// healthy — it needs no network and no AWS credentials. - pub fn verify_signing_path(&self, message: &[u8]) -> Result<()> { - let signature = self.identity.sign_message_ecdsa_sha256(message)?; - keystone_pki::ephemeral_ca::verify_device_signature(&self.certificate, message, &signature) - } -} - -impl AwsX509Identity for CertificateIdentity { - fn certificate_serial_decimal(&self) -> Result { - Ok(self.certificate.serial_decimal.clone()) - } - - fn leaf_certificate_der(&self) -> &[u8] { - self.certificate.der() - } - - fn certificate_chain_der(&self) -> &[Vec] { - &self.chain - } - - /// Sign the Roles Anywhere string-to-sign. - /// - /// The string-to-sign is passed as a *message*, exactly as on macOS, and the - /// backend hashes it once. That the hash happens in Keystone here rather than - /// inside CryptoKit is invisible at this seam, which is the point of routing - /// through `sign_message_ecdsa_sha256` instead of reaching for the TPM's - /// native prehashed operation: this function would then have to hash, and a - /// future edit could easily leave both hashes in place. - fn sign_string_to_sign(&self, string_to_sign: &[u8]) -> Result> { - self.identity - .sign_message_ecdsa_sha256(string_to_sign) - .map(DerEcdsaSignature::into_bytes) - } -} +pub type CertificateIdentity = keystone_roles_anywhere::CertificateIdentity; /// These need a real TPM, so they are compiled only where one can exist. /// @@ -124,8 +14,14 @@ mod tests { use super::*; use crate::access::TpmPolicy; use crate::tpm::{self, TpmIdentity}; + use keystone_core::error::KeystoneError; + use keystone_core::identity::KeyId; use keystone_core::identity::{IdentityMetadata, KeyType}; + use keystone_core::signer::KeystoneSigningIdentity; use keystone_pki::params::{DeviceCertificateSpec, EphemeralCaSpec}; + use keystone_pki::ParsedCertificate; + use keystone_roles_anywhere::AwsX509Identity; + use time::OffsetDateTime; const NOW: OffsetDateTime = time::macros::datetime!(2026-07-26 01:15:00 UTC); @@ -198,7 +94,7 @@ mod tests { .verify_signing_path(b"AWS4-X509-ECDSA-SHA256\n20260726T011500Z\nscope\ndigest") .unwrap(); keystone_pki::validate_chain(identity.certificate(), &[], &anchor, NOW).unwrap(); - let _cleanup = TempKey(Some(identity.identity)); + let _cleanup = TempKey(Some(identity.into_parts().0)); } #[test] @@ -212,7 +108,7 @@ mod tests { "serial {serial} is not decimal" ); assert!(!serial.is_empty()); - let _cleanup = TempKey(Some(identity.identity)); + let _cleanup = TempKey(Some(identity.into_parts().0)); } #[test] @@ -226,7 +122,7 @@ mod tests { identity.leaf_certificate_der(), identity.certificate().der() ); - let _cleanup = TempKey(Some(identity.identity)); + let _cleanup = TempKey(Some(identity.into_parts().0)); } #[test] @@ -248,7 +144,7 @@ mod tests { &signature, ) .unwrap(); - let _cleanup = TempKey(Some(identity.identity)); + let _cleanup = TempKey(Some(identity.into_parts().0)); } #[test] @@ -275,7 +171,7 @@ mod tests { &signature, ) .unwrap(); - let _cleanup = TempKey(Some(identity.identity)); + let _cleanup = TempKey(Some(identity.into_parts().0)); } #[test] diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 5ee9142..d8e433f 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,7 +1,7 @@ # Keystone -Hardware-backed temporary AWS credentials: the Secure Enclave on macOS, the TPM -on Windows. +Hardware-backed temporary AWS credentials: the Secure Enclave on macOS and TPM +2.0 on Windows and Linux. ## Status @@ -27,7 +27,7 @@ The long-lived private key is generated inside the Mac’s Secure Enclave, or th The two key stores are interchangeable from every other component’s point of view: each generates a non-exportable P-256 signing key, signs without a user-presence prompt, and has no software fallback. [Platform Support](#platform-support) describes where they differ. ```text -Secure Enclave (macOS) or TPM (Windows) +Secure Enclave (macOS) or TPM (Windows and Linux) P-256 signing key │ ▼ @@ -63,7 +63,7 @@ Keystone avoids: Keystone should provide: -* hardware-backed P-256 identity generation — Secure Enclave on macOS, TPM on Windows; +* hardware-backed P-256 identity generation — Secure Enclave on macOS, TPM on Windows and Linux; * unattended P-256 signing after first device unlock; * X.509 certificate generation and installation; * an optional one-shot external CA; @@ -150,7 +150,7 @@ The Secure Enclave prevents private-key export. It is not an application-level a # Platform Support -Keystone supports two hardware key stores: +Keystone supports these hardware backends: ```text Operating system: macOS @@ -170,14 +170,35 @@ Signature algorithm: ECDSA with SHA-256 AWS signing algorithm: AWS4-X509-ECDSA-SHA256 ``` +```text +Operating system: Linux +Release architecture: x86-64 +Private-key backend: TPM 2.0 via the kernel resource manager (/dev/tpmrm0) +Public-key algorithm: P-256 +Signature algorithm: ECDSA with SHA-256 +AWS signing algorithm: AWS4-X509-ECDSA-SHA256 +``` + +On Linux, Keystone creates a signing key with the fixed-TPM, fixed-parent, +and sensitive-data-origin attributes under a reproducible owner primary. +It saves the wrapped private object and public coordinates in the private +metadata file. The TPM authenticates the wrapped object when it is loaded. +Keystone verifies the key template and compares the restored public key with +the one recorded in the metadata. +The backend only opens the kernel resource manager and never consults a +TCTI environment override. It allocates no persistent TPM handles, so +retiring a key means removing its wrapped reference. The owner hierarchy +must accept empty authorization. File permissions and access to the TPM +device govern use of the key independently of the desktop lock state. + Intel Macs with a T2 chip may be supported later after integration testing. Everything above the key store is shared: the same identity records, the same ephemeral CA, the same `CreateSession` client, and the same credential-process contract. One backend is selected at compile time by target, and a target with -neither key store gets a backend whose every operation fails closed. +no supported key store gets a backend whose every operation fails closed. -Three properties are the same on both platforms, and they are what make them +Three properties are shared by the hardware backends, and they are what make them interchangeable: * the private key cannot be exported. On Windows the key is created with @@ -219,7 +240,7 @@ Keystone should fail clearly when: ## File permissions -The rule is the same on both platforms — refuse to read a file another local user +The rule is shared by the hardware backends — refuse to read a file another local user could have written, and never create one they could read — but it is expressed differently, because Windows has no mode bits.