Compare commits
11 commits
e2ea458a0b
...
aafcd1bbf7
Author | SHA1 | Date | |
---|---|---|---|
aafcd1bbf7 | |||
|
712e3dd72e | ||
|
5de6682857 | ||
|
62a4685aef | ||
|
afff5d8f53 | ||
|
ba331be121 | ||
|
fd27ca2d20 | ||
|
9dd15aaac1 | ||
|
35321c1b72 | ||
|
750b7495e4 | ||
|
2622fc93ea |
11 changed files with 601 additions and 472 deletions
1
.envrc
Normal file
1
.envrc
Normal file
|
@ -0,0 +1 @@
|
||||||
|
use flake
|
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
|
@ -31,7 +31,7 @@ jobs:
|
||||||
tpm2-tss-devel clevis \
|
tpm2-tss-devel clevis \
|
||||||
swtpm swtpm-tools \
|
swtpm swtpm-tools \
|
||||||
rust cargo clippy \
|
rust cargo clippy \
|
||||||
golang
|
golang clang-devel
|
||||||
- name: Remove clevis-pin-tpm2
|
- name: Remove clevis-pin-tpm2
|
||||||
run: |
|
run: |
|
||||||
dnf erase -y clevis-pin-tpm2
|
dnf erase -y clevis-pin-tpm2
|
||||||
|
|
3
.gitignore
vendored
3
.gitignore
vendored
|
@ -22,3 +22,6 @@ Cargo.lock
|
||||||
/tests/policy_working.json
|
/tests/policy_working.json
|
||||||
/tests/privatekey.pem
|
/tests/privatekey.pem
|
||||||
/tests/publickey.json
|
/tests/publickey.json
|
||||||
|
|
||||||
|
.direnv
|
||||||
|
.idea
|
|
@ -1,6 +1,6 @@
|
||||||
[package]
|
[package]
|
||||||
name = "clevis-pin-tpm2"
|
name = "clevis-pin-tpm2"
|
||||||
version = "0.5.1"
|
version = "0.5.3"
|
||||||
description = "Clevis TPM2 PIN with policy support"
|
description = "Clevis TPM2 PIN with policy support"
|
||||||
authors = ["Patrick Uiterwijk <patrick@puiterwijk.org>"]
|
authors = ["Patrick Uiterwijk <patrick@puiterwijk.org>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
@ -11,10 +11,10 @@ license = "MIT"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
tss-esapi = "6.1.1"
|
tss-esapi = { version = "7.2", features = ["generate-bindings"] }
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
josekit = "0.7.4"
|
josekit = "0.7.4"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
base64 = "0.12.1"
|
base64 = "0.12.1"
|
||||||
atty = "0.2.14"
|
atty = "0.2.14"
|
||||||
tpm2-policy = "0.5.3"
|
tpm2-policy = "0.6.0"
|
||||||
|
|
60
flake.lock
Normal file
60
flake.lock
Normal file
|
@ -0,0 +1,60 @@
|
||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"flake-utils": {
|
||||||
|
"inputs": {
|
||||||
|
"systems": "systems"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1701680307,
|
||||||
|
"narHash": "sha256-kAuep2h5ajznlPMD9rnQyffWG8EM/C73lejGofXvdM8=",
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"rev": "4022d587cbbfd70fe950c1e2083a02621806a725",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1702926307,
|
||||||
|
"narHash": "sha256-GVwGcCEuO1hKecwMQvFUyTg61KCoR3QkKbhfPMe5R5Q=",
|
||||||
|
"owner": "nixos",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "5a9be42754cee0d35d893cbed08737486e5f5e6d",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nixos",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-utils": "flake-utils",
|
||||||
|
"nixpkgs": "nixpkgs"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"systems": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1681028828,
|
||||||
|
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
46
flake.nix
Normal file
46
flake.nix
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
{
|
||||||
|
inputs = {
|
||||||
|
nixpkgs.url = "github:nixos/nixpkgs";
|
||||||
|
flake-utils.url = "github:numtide/flake-utils";
|
||||||
|
};
|
||||||
|
|
||||||
|
outputs = { self, nixpkgs, flake-utils }:
|
||||||
|
flake-utils.lib.eachDefaultSystem (system:
|
||||||
|
let
|
||||||
|
pkgs = nixpkgs.legacyPackages.${system};
|
||||||
|
inherit (pkgs) stdenv lib;
|
||||||
|
in {
|
||||||
|
devShell = pkgs.mkShell {
|
||||||
|
shellHook = ''
|
||||||
|
export BINDGEN_EXTRA_CLANG_ARGS="$(< ${stdenv.cc}/nix-support/libc-crt1-cflags) \
|
||||||
|
$(< ${stdenv.cc}/nix-support/libc-cflags) \
|
||||||
|
$(< ${stdenv.cc}/nix-support/cc-cflags) \
|
||||||
|
$(< ${stdenv.cc}/nix-support/libcxx-cxxflags) \
|
||||||
|
${
|
||||||
|
lib.optionalString stdenv.cc.isClang
|
||||||
|
"-idirafter ${stdenv.cc.cc}/lib/clang/${
|
||||||
|
lib.getVersion stdenv.cc.cc
|
||||||
|
}/include"
|
||||||
|
} \
|
||||||
|
${
|
||||||
|
lib.optionalString stdenv.cc.isGNU
|
||||||
|
"-isystem ${stdenv.cc.cc}/include/c++/${
|
||||||
|
lib.getVersion stdenv.cc.cc
|
||||||
|
} -isystem ${stdenv.cc.cc}/include/c++/${
|
||||||
|
lib.getVersion stdenv.cc.cc
|
||||||
|
}/${stdenv.hostPlatform.config} -idirafter ${stdenv.cc.cc}/lib/gcc/${stdenv.hostPlatform.config}/${
|
||||||
|
lib.getVersion stdenv.cc.cc
|
||||||
|
}/include"
|
||||||
|
} \
|
||||||
|
"
|
||||||
|
'';
|
||||||
|
nativeBuildInputs = with pkgs; [
|
||||||
|
llvmPackages.libclang
|
||||||
|
llvmPackages.libcxxClang
|
||||||
|
clang
|
||||||
|
];
|
||||||
|
LIBCLANG_PATH = "${pkgs.llvmPackages.libclang.lib}/lib";
|
||||||
|
buildInputs = with pkgs; [ libclang pkg-config openssl tpm2-tss ];
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
199
src/cli.rs
199
src/cli.rs
|
@ -1,198 +1,7 @@
|
||||||
use std::convert::TryFrom;
|
|
||||||
|
|
||||||
use anyhow::{anyhow, bail, Error, Result};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use tpm2_policy::TPMPolicyStep;
|
|
||||||
|
|
||||||
use crate::utils::get_authorized_policy_step;
|
use anyhow::{bail, Result};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, std::fmt::Debug)]
|
|
||||||
pub(super) struct TPM2Config {
|
|
||||||
pub hash: Option<String>,
|
|
||||||
pub key: Option<String>,
|
|
||||||
pub pcr_bank: Option<String>,
|
|
||||||
// PCR IDs can be passed in as comma-separated string or json array
|
|
||||||
pub pcr_ids: Option<serde_json::Value>,
|
|
||||||
pub pcr_digest: Option<String>,
|
|
||||||
// Whether to use a policy. If this is specified without pubkey path or policy path, they get set to defaults
|
|
||||||
pub use_policy: Option<bool>,
|
|
||||||
// Public key (in JSON format) for a wildcard policy that's possibly OR'd with the PCR one
|
|
||||||
pub policy_pubkey_path: Option<String>,
|
|
||||||
pub policy_ref: Option<String>,
|
|
||||||
pub policy_path: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TryFrom<&TPM2Config> for TPMPolicyStep {
|
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn try_from(cfg: &TPM2Config) -> Result<Self> {
|
|
||||||
if cfg.pcr_ids.is_some() && cfg.policy_pubkey_path.is_some() {
|
|
||||||
Ok(TPMPolicyStep::Or([
|
|
||||||
Box::new(TPMPolicyStep::PCRs(
|
|
||||||
cfg.get_pcr_hash_alg(),
|
|
||||||
cfg.get_pcr_ids().unwrap(),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
)),
|
|
||||||
Box::new(get_authorized_policy_step(
|
|
||||||
cfg.policy_pubkey_path.as_ref().unwrap(),
|
|
||||||
&None,
|
|
||||||
&cfg.policy_ref,
|
|
||||||
)?),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
]))
|
|
||||||
} else if cfg.pcr_ids.is_some() {
|
|
||||||
Ok(TPMPolicyStep::PCRs(
|
|
||||||
cfg.get_pcr_hash_alg(),
|
|
||||||
cfg.get_pcr_ids().unwrap(),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
))
|
|
||||||
} else if cfg.policy_pubkey_path.is_some() {
|
|
||||||
get_authorized_policy_step(
|
|
||||||
cfg.policy_pubkey_path.as_ref().unwrap(),
|
|
||||||
&None,
|
|
||||||
&cfg.policy_ref,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
Ok(TPMPolicyStep::NoStep)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) const DEFAULT_POLICY_PATH: &str = "/boot/clevis_policy.json";
|
|
||||||
pub(crate) const DEFAULT_PUBKEY_PATH: &str = "/boot/clevis_pubkey.json";
|
|
||||||
pub(crate) const DEFAULT_POLICY_REF: &str = "";
|
|
||||||
|
|
||||||
impl TPM2Config {
|
|
||||||
pub(super) fn get_pcr_hash_alg(
|
|
||||||
&self,
|
|
||||||
) -> tss_esapi::interface_types::algorithm::HashingAlgorithm {
|
|
||||||
crate::utils::get_hash_alg_from_name(self.pcr_bank.as_ref())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn get_name_hash_alg(
|
|
||||||
&self,
|
|
||||||
) -> tss_esapi::interface_types::algorithm::HashingAlgorithm {
|
|
||||||
crate::utils::get_hash_alg_from_name(self.hash.as_ref())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn get_pcr_ids(&self) -> Option<Vec<u64>> {
|
|
||||||
match &self.pcr_ids {
|
|
||||||
None => None,
|
|
||||||
Some(serde_json::Value::Array(vals)) => {
|
|
||||||
Some(vals.iter().map(|x| x.as_u64().unwrap()).collect())
|
|
||||||
}
|
|
||||||
_ => panic!("Unexpected type found for pcr_ids"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn get_pcr_ids_str(&self) -> Option<String> {
|
|
||||||
match &self.pcr_ids {
|
|
||||||
None => None,
|
|
||||||
Some(serde_json::Value::Array(vals)) => Some(
|
|
||||||
vals.iter()
|
|
||||||
.map(|x| x.as_u64().unwrap().to_string())
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
.join(","),
|
|
||||||
),
|
|
||||||
_ => panic!("Unexpected type found for pcr_ids"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn normalize(mut self) -> Result<TPM2Config> {
|
|
||||||
self.normalize_pcr_ids()?;
|
|
||||||
if self.pcr_ids.is_some() && self.pcr_bank.is_none() {
|
|
||||||
self.pcr_bank = Some("sha256".to_string());
|
|
||||||
}
|
|
||||||
// Make use of the defaults if not specified
|
|
||||||
if self.use_policy.is_some() && self.use_policy.unwrap() {
|
|
||||||
if self.policy_path.is_none() {
|
|
||||||
self.policy_path = Some(DEFAULT_POLICY_PATH.to_string());
|
|
||||||
}
|
|
||||||
if self.policy_pubkey_path.is_none() {
|
|
||||||
self.policy_pubkey_path = Some(DEFAULT_PUBKEY_PATH.to_string());
|
|
||||||
}
|
|
||||||
if self.policy_ref.is_none() {
|
|
||||||
self.policy_ref = Some(DEFAULT_POLICY_REF.to_string());
|
|
||||||
}
|
|
||||||
} else if self.policy_pubkey_path.is_some()
|
|
||||||
|| self.policy_path.is_some()
|
|
||||||
|| self.policy_ref.is_some()
|
|
||||||
{
|
|
||||||
eprintln!("To use a policy, please specifiy use_policy: true. Not specifying this will be a fatal error in a next release");
|
|
||||||
}
|
|
||||||
if (self.policy_pubkey_path.is_some()
|
|
||||||
|| self.policy_path.is_some()
|
|
||||||
|| self.policy_ref.is_some())
|
|
||||||
&& (self.policy_pubkey_path.is_none()
|
|
||||||
|| self.policy_path.is_none()
|
|
||||||
|| self.policy_ref.is_none())
|
|
||||||
{
|
|
||||||
bail!("Not all of policy pubkey, path and ref are specified",);
|
|
||||||
}
|
|
||||||
Ok(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn normalize_pcr_ids(&mut self) -> Result<()> {
|
|
||||||
// Normalize from array with one string to just string
|
|
||||||
if let Some(serde_json::Value::Array(vals)) = &self.pcr_ids {
|
|
||||||
if vals.len() == 1 {
|
|
||||||
if let serde_json::Value::String(val) = &vals[0] {
|
|
||||||
self.pcr_ids = Some(serde_json::Value::String(val.to_string()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Normalize pcr_ids from comma-separated string to array
|
|
||||||
if let Some(serde_json::Value::String(val)) = &self.pcr_ids {
|
|
||||||
// Was a string, do a split
|
|
||||||
let newval: Vec<serde_json::Value> = val
|
|
||||||
.split(',')
|
|
||||||
.map(|x| serde_json::Value::String(x.trim().to_string()))
|
|
||||||
.collect();
|
|
||||||
self.pcr_ids = Some(serde_json::Value::Array(newval));
|
|
||||||
}
|
|
||||||
// Normalize pcr_ids from array of Strings to array of Numbers
|
|
||||||
if let Some(serde_json::Value::Array(vals)) = &self.pcr_ids {
|
|
||||||
let newvals: Result<Vec<serde_json::Value>, _> = vals
|
|
||||||
.iter()
|
|
||||||
.map(|x| match x {
|
|
||||||
serde_json::Value::String(val) => {
|
|
||||||
match val.trim().parse::<serde_json::Number>() {
|
|
||||||
Ok(res) => {
|
|
||||||
let new = serde_json::Value::Number(res);
|
|
||||||
if !new.is_u64() {
|
|
||||||
bail!("Non-positive string int");
|
|
||||||
}
|
|
||||||
Ok(new)
|
|
||||||
}
|
|
||||||
Err(_) => Err(anyhow!("Unparseable string int")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
serde_json::Value::Number(n) => {
|
|
||||||
let new = serde_json::Value::Number(n.clone());
|
|
||||||
if !new.is_u64() {
|
|
||||||
return Err(anyhow!("Non-positive int"));
|
|
||||||
}
|
|
||||||
Ok(new)
|
|
||||||
}
|
|
||||||
_ => Err(anyhow!("Invalid value in pcr_ids")),
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
self.pcr_ids = Some(serde_json::Value::Array(newvals?));
|
|
||||||
}
|
|
||||||
|
|
||||||
match &self.pcr_ids {
|
|
||||||
None => Ok(()),
|
|
||||||
// The normalization above would've caught any non-ints
|
|
||||||
Some(serde_json::Value::Array(_)) => Ok(()),
|
|
||||||
_ => Err(anyhow!("Invalid type")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub(super) enum ActionMode {
|
pub(super) enum ActionMode {
|
||||||
|
@ -202,6 +11,12 @@ pub(super) enum ActionMode {
|
||||||
Help,
|
Help,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
use crate::TPM2Config;
|
||||||
|
|
||||||
|
pub const DEFAULT_POLICY_PATH: &str = "/boot/clevis_policy.json";
|
||||||
|
pub const DEFAULT_PUBKEY_PATH: &str = "/boot/clevis_pubkey.json";
|
||||||
|
pub const DEFAULT_POLICY_REF: &str = "";
|
||||||
|
|
||||||
pub(super) fn get_mode_and_cfg(args: &[String]) -> Result<(ActionMode, Option<TPM2Config>)> {
|
pub(super) fn get_mode_and_cfg(args: &[String]) -> Result<(ActionMode, Option<TPM2Config>)> {
|
||||||
if args.len() > 1 && args[1] == "--summary" {
|
if args.len() > 1 && args[1] == "--summary" {
|
||||||
return Ok((ActionMode::Summary, None));
|
return Ok((ActionMode::Summary, None));
|
||||||
|
|
215
src/lib.rs
Normal file
215
src/lib.rs
Normal file
|
@ -0,0 +1,215 @@
|
||||||
|
// Copyright 2020 Patrick Uiterwijk
|
||||||
|
//
|
||||||
|
// Licensed under the MIT license
|
||||||
|
|
||||||
|
use std::convert::{TryFrom, TryInto};
|
||||||
|
|
||||||
|
use std::io::{self, Write};
|
||||||
|
|
||||||
|
use anyhow::{bail, Context, Error, Result};
|
||||||
|
use josekit::jwe::{alg::direct::DirectJweAlgorithm::Dir, enc::A256GCM};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tpm2_policy::TPMPolicyStep;
|
||||||
|
use tpm_objects::TPM2Config;
|
||||||
|
use tss_esapi::structures::SensitiveData;
|
||||||
|
|
||||||
|
pub mod tpm_objects;
|
||||||
|
pub mod utils;
|
||||||
|
|
||||||
|
pub fn perform_encrypt(cfg: TPM2Config, input: Vec<u8>) -> Result<String> {
|
||||||
|
let key_type = match &cfg.key {
|
||||||
|
None => "ecc",
|
||||||
|
Some(key_type) => key_type,
|
||||||
|
};
|
||||||
|
let key_public = tpm_objects::get_key_public(key_type, cfg.get_name_hash_alg())?;
|
||||||
|
|
||||||
|
let mut ctx = utils::get_tpm2_ctx()?;
|
||||||
|
let key_handle = utils::get_tpm2_primary_key(&mut ctx, key_public)?;
|
||||||
|
|
||||||
|
let policy_runner: TPMPolicyStep = TPMPolicyStep::try_from(&cfg)?;
|
||||||
|
|
||||||
|
let pin_type = match policy_runner {
|
||||||
|
TPMPolicyStep::NoStep => "tpm2",
|
||||||
|
TPMPolicyStep::PCRs(_, _, _) => "tpm2",
|
||||||
|
_ => "tpm2plus",
|
||||||
|
};
|
||||||
|
|
||||||
|
let (_, policy_digest) = policy_runner.send_policy(&mut ctx, true)?;
|
||||||
|
|
||||||
|
let mut jwk = josekit::jwk::Jwk::generate_oct_key(32).context("Error generating random JWK")?;
|
||||||
|
jwk.set_key_operations(vec!["encrypt", "decrypt"]);
|
||||||
|
let jwk_str = serde_json::to_string(&jwk.as_ref())?;
|
||||||
|
|
||||||
|
let public = tpm_objects::create_tpm2b_public_sealed_object(policy_digest)?.try_into()?;
|
||||||
|
let jwk_str = SensitiveData::try_from(jwk_str.as_bytes().to_vec())?;
|
||||||
|
let jwk_result = ctx.execute_with_nullauth_session(|ctx| {
|
||||||
|
ctx.create(key_handle, public, None, Some(jwk_str), None, None)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let jwk_priv = tpm_objects::get_tpm2b_private(jwk_result.out_private.into())?;
|
||||||
|
|
||||||
|
let jwk_pub = tpm_objects::get_tpm2b_public(jwk_result.out_public.try_into()?)?;
|
||||||
|
|
||||||
|
let private_hdr = ClevisInner {
|
||||||
|
pin: pin_type.to_string(),
|
||||||
|
tpm2: Tpm2Inner {
|
||||||
|
hash: cfg.hash.as_ref().unwrap_or(&"sha256".to_string()).clone(),
|
||||||
|
key: key_type.to_string(),
|
||||||
|
jwk_pub,
|
||||||
|
jwk_priv,
|
||||||
|
pcr_bank: cfg.pcr_bank.clone(),
|
||||||
|
pcr_ids: cfg.get_pcr_ids_str(),
|
||||||
|
policy_pubkey_path: cfg.policy_pubkey_path,
|
||||||
|
policy_ref: cfg.policy_ref,
|
||||||
|
policy_path: cfg.policy_path,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut hdr = josekit::jwe::JweHeader::new();
|
||||||
|
hdr.set_algorithm(Dir.name());
|
||||||
|
hdr.set_content_encryption(A256GCM.name());
|
||||||
|
hdr.set_claim(
|
||||||
|
"clevis",
|
||||||
|
Some(serde_json::value::to_value(private_hdr).context("Error serializing private header")?),
|
||||||
|
)
|
||||||
|
.context("Error adding clevis claim")?;
|
||||||
|
|
||||||
|
let encrypter = Dir
|
||||||
|
.encrypter_from_jwk(&jwk)
|
||||||
|
.context("Error creating direct encrypter")?;
|
||||||
|
let jwe_token = josekit::jwe::serialize_compact(&input, &hdr, &encrypter)
|
||||||
|
.context("Error serializing JWE token")?;
|
||||||
|
|
||||||
|
Ok(jwe_token)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||||
|
struct Tpm2Inner {
|
||||||
|
hash: String,
|
||||||
|
#[serde(
|
||||||
|
deserialize_with = "utils::deserialize_as_base64_url_no_pad",
|
||||||
|
serialize_with = "utils::serialize_as_base64_url_no_pad"
|
||||||
|
)]
|
||||||
|
jwk_priv: Vec<u8>,
|
||||||
|
#[serde(
|
||||||
|
deserialize_with = "utils::deserialize_as_base64_url_no_pad",
|
||||||
|
serialize_with = "utils::serialize_as_base64_url_no_pad"
|
||||||
|
)]
|
||||||
|
jwk_pub: Vec<u8>,
|
||||||
|
key: String,
|
||||||
|
|
||||||
|
// PCR Binding may be specified, may not
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pcr_bank: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pcr_ids: Option<String>,
|
||||||
|
|
||||||
|
// Public key (in PEM format) for a wildcard policy that's OR'd with the PCR one
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
policy_pubkey_path: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
policy_ref: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
policy_path: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Tpm2Inner {
|
||||||
|
fn get_pcr_ids(&self) -> Option<Vec<u64>> {
|
||||||
|
Some(
|
||||||
|
self.pcr_ids
|
||||||
|
.as_ref()?
|
||||||
|
.split(',')
|
||||||
|
.map(|x| x.parse::<u64>().unwrap())
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<&Tpm2Inner> for TPMPolicyStep {
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn try_from(cfg: &Tpm2Inner) -> Result<Self> {
|
||||||
|
if cfg.pcr_ids.is_some() && cfg.policy_pubkey_path.is_some() {
|
||||||
|
Ok(TPMPolicyStep::Or([
|
||||||
|
Box::new(TPMPolicyStep::PCRs(
|
||||||
|
utils::get_hash_alg_from_name(cfg.pcr_bank.as_ref()),
|
||||||
|
cfg.get_pcr_ids().unwrap(),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
)),
|
||||||
|
Box::new(utils::get_authorized_policy_step(
|
||||||
|
cfg.policy_pubkey_path.as_ref().unwrap(),
|
||||||
|
&cfg.policy_path,
|
||||||
|
&cfg.policy_ref,
|
||||||
|
)?),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
]))
|
||||||
|
} else if cfg.pcr_ids.is_some() {
|
||||||
|
Ok(TPMPolicyStep::PCRs(
|
||||||
|
utils::get_hash_alg_from_name(cfg.pcr_bank.as_ref()),
|
||||||
|
cfg.get_pcr_ids().unwrap(),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
))
|
||||||
|
} else if cfg.policy_pubkey_path.is_some() {
|
||||||
|
utils::get_authorized_policy_step(
|
||||||
|
cfg.policy_pubkey_path.as_ref().unwrap(),
|
||||||
|
&cfg.policy_path,
|
||||||
|
&cfg.policy_ref,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Ok(TPMPolicyStep::NoStep)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||||
|
struct ClevisInner {
|
||||||
|
pin: String,
|
||||||
|
tpm2: Tpm2Inner,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn perform_decrypt(input: Vec<u8>) -> Result<Vec<u8>> {
|
||||||
|
let input = String::from_utf8(input).context("Error reading input")?;
|
||||||
|
let hdr = josekit::jwt::decode_header(&input).context("Error decoding header")?;
|
||||||
|
let hdr_clevis = hdr.claim("clevis").context("Error getting clevis claim")?;
|
||||||
|
let hdr_clevis: ClevisInner =
|
||||||
|
serde_json::from_value(hdr_clevis.clone()).context("Error deserializing clevis header")?;
|
||||||
|
|
||||||
|
if hdr_clevis.pin != "tpm2" && hdr_clevis.pin != "tpm2plus" {
|
||||||
|
bail!("JWE pin mismatch");
|
||||||
|
}
|
||||||
|
|
||||||
|
let jwkpub = tpm_objects::build_tpm2b_public(&hdr_clevis.tpm2.jwk_pub)?.try_into()?;
|
||||||
|
let jwkpriv = tpm_objects::build_tpm2b_private(&hdr_clevis.tpm2.jwk_priv)?;
|
||||||
|
|
||||||
|
let policy = TPMPolicyStep::try_from(&hdr_clevis.tpm2)?;
|
||||||
|
|
||||||
|
let name_alg = crate::utils::get_hash_alg_from_name(Some(&hdr_clevis.tpm2.hash));
|
||||||
|
let key_public = tpm_objects::get_key_public(hdr_clevis.tpm2.key.as_str(), name_alg)?;
|
||||||
|
|
||||||
|
let mut ctx = utils::get_tpm2_ctx()?;
|
||||||
|
let key_handle = utils::get_tpm2_primary_key(&mut ctx, key_public)?;
|
||||||
|
|
||||||
|
let key =
|
||||||
|
ctx.execute_with_nullauth_session(|ctx| ctx.load(key_handle, jwkpriv.try_into()?, jwkpub))?;
|
||||||
|
|
||||||
|
let (policy_session, _) = policy.send_policy(&mut ctx, false)?;
|
||||||
|
|
||||||
|
let unsealed = ctx.execute_with_session(policy_session, |ctx| ctx.unseal(key.into()))?;
|
||||||
|
let unsealed = &unsealed.value();
|
||||||
|
let mut jwk = josekit::jwk::Jwk::from_bytes(unsealed).context("Error unmarshaling JWK")?;
|
||||||
|
jwk.set_parameter("alg", None)
|
||||||
|
.context("Error removing the alg parameter")?;
|
||||||
|
let decrypter = Dir
|
||||||
|
.decrypter_from_jwk(&jwk)
|
||||||
|
.context("Error creating decrypter")?;
|
||||||
|
|
||||||
|
let (payload, _) =
|
||||||
|
josekit::jwe::deserialize_compact(&input, &decrypter).context("Error decrypting JWE")?;
|
||||||
|
|
||||||
|
Ok(payload)
|
||||||
|
}
|
246
src/main.rs
246
src/main.rs
|
@ -1,224 +1,12 @@
|
||||||
// Copyright 2020 Patrick Uiterwijk
|
use std::{
|
||||||
//
|
env,
|
||||||
// Licensed under the MIT license
|
io::{stdout, Read, Write},
|
||||||
|
};
|
||||||
|
|
||||||
use std::convert::{TryFrom, TryInto};
|
use anyhow::Result;
|
||||||
use std::env;
|
use clevis_pin_tpm2::{perform_decrypt, perform_encrypt, tpm_objects::TPM2Config};
|
||||||
use std::io::{self, Read, Write};
|
|
||||||
|
|
||||||
use anyhow::{bail, Context, Error, Result};
|
|
||||||
use josekit::jwe::{alg::direct::DirectJweAlgorithm::Dir, enc::A256GCM};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use tpm2_policy::TPMPolicyStep;
|
|
||||||
use tss_esapi::structures::SensitiveData;
|
|
||||||
|
|
||||||
mod cli;
|
mod cli;
|
||||||
mod tpm_objects;
|
|
||||||
mod utils;
|
|
||||||
|
|
||||||
use cli::TPM2Config;
|
|
||||||
|
|
||||||
fn perform_encrypt(cfg: TPM2Config, input: Vec<u8>) -> Result<()> {
|
|
||||||
let key_type = match &cfg.key {
|
|
||||||
None => "ecc",
|
|
||||||
Some(key_type) => key_type,
|
|
||||||
};
|
|
||||||
let key_public = tpm_objects::get_key_public(key_type, cfg.get_name_hash_alg())?;
|
|
||||||
|
|
||||||
let mut ctx = utils::get_tpm2_ctx()?;
|
|
||||||
let key_handle = utils::get_tpm2_primary_key(&mut ctx, &key_public)?;
|
|
||||||
|
|
||||||
let policy_runner: TPMPolicyStep = TPMPolicyStep::try_from(&cfg)?;
|
|
||||||
|
|
||||||
let pin_type = match policy_runner {
|
|
||||||
TPMPolicyStep::NoStep => "tpm2",
|
|
||||||
TPMPolicyStep::PCRs(_, _, _) => "tpm2",
|
|
||||||
_ => "tpm2plus",
|
|
||||||
};
|
|
||||||
|
|
||||||
let (_, policy_digest) = policy_runner.send_policy(&mut ctx, true)?;
|
|
||||||
|
|
||||||
let mut jwk = josekit::jwk::Jwk::generate_oct_key(32).context("Error generating random JWK")?;
|
|
||||||
jwk.set_key_operations(vec!["encrypt", "decrypt"]);
|
|
||||||
let jwk_str = serde_json::to_string(&jwk.as_ref())?;
|
|
||||||
|
|
||||||
let public = tpm_objects::create_tpm2b_public_sealed_object(policy_digest)?;
|
|
||||||
let jwk_str = SensitiveData::try_from(jwk_str.as_bytes().to_vec())?;
|
|
||||||
let jwk_result = ctx.execute_with_nullauth_session(|ctx| {
|
|
||||||
ctx.create(key_handle, &public, None, Some(&jwk_str), None, None)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let jwk_priv = tpm_objects::get_tpm2b_private(jwk_result.out_private.into())?;
|
|
||||||
|
|
||||||
let jwk_pub = tpm_objects::get_tpm2b_public(jwk_result.out_public)?;
|
|
||||||
|
|
||||||
let private_hdr = ClevisInner {
|
|
||||||
pin: pin_type.to_string(),
|
|
||||||
tpm2: Tpm2Inner {
|
|
||||||
hash: cfg.hash.as_ref().unwrap_or(&"sha256".to_string()).clone(),
|
|
||||||
key: key_type.to_string(),
|
|
||||||
jwk_pub,
|
|
||||||
jwk_priv,
|
|
||||||
pcr_bank: cfg.pcr_bank.clone(),
|
|
||||||
pcr_ids: cfg.get_pcr_ids_str(),
|
|
||||||
policy_pubkey_path: cfg.policy_pubkey_path,
|
|
||||||
policy_ref: cfg.policy_ref,
|
|
||||||
policy_path: cfg.policy_path,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut hdr = josekit::jwe::JweHeader::new();
|
|
||||||
hdr.set_algorithm(Dir.name());
|
|
||||||
hdr.set_content_encryption(A256GCM.name());
|
|
||||||
hdr.set_claim(
|
|
||||||
"clevis",
|
|
||||||
Some(serde_json::value::to_value(private_hdr).context("Error serializing private header")?),
|
|
||||||
)
|
|
||||||
.context("Error adding clevis claim")?;
|
|
||||||
|
|
||||||
let encrypter = Dir
|
|
||||||
.encrypter_from_jwk(&jwk)
|
|
||||||
.context("Error creating direct encrypter")?;
|
|
||||||
let jwe_token = josekit::jwe::serialize_compact(&input, &hdr, &encrypter)
|
|
||||||
.context("Error serializing JWE token")?;
|
|
||||||
|
|
||||||
io::stdout().write_all(jwe_token.as_bytes())?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
|
||||||
struct Tpm2Inner {
|
|
||||||
hash: String,
|
|
||||||
#[serde(
|
|
||||||
deserialize_with = "utils::deserialize_as_base64_url_no_pad",
|
|
||||||
serialize_with = "utils::serialize_as_base64_url_no_pad"
|
|
||||||
)]
|
|
||||||
jwk_priv: Vec<u8>,
|
|
||||||
#[serde(
|
|
||||||
deserialize_with = "utils::deserialize_as_base64_url_no_pad",
|
|
||||||
serialize_with = "utils::serialize_as_base64_url_no_pad"
|
|
||||||
)]
|
|
||||||
jwk_pub: Vec<u8>,
|
|
||||||
key: String,
|
|
||||||
|
|
||||||
// PCR Binding may be specified, may not
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pcr_bank: Option<String>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pcr_ids: Option<String>,
|
|
||||||
|
|
||||||
// Public key (in PEM format) for a wildcard policy that's OR'd with the PCR one
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
policy_pubkey_path: Option<String>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
policy_ref: Option<String>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
policy_path: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Tpm2Inner {
|
|
||||||
fn get_pcr_ids(&self) -> Option<Vec<u64>> {
|
|
||||||
Some(
|
|
||||||
self.pcr_ids
|
|
||||||
.as_ref()?
|
|
||||||
.split(',')
|
|
||||||
.map(|x| x.parse::<u64>().unwrap())
|
|
||||||
.collect(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TryFrom<&Tpm2Inner> for TPMPolicyStep {
|
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn try_from(cfg: &Tpm2Inner) -> Result<Self> {
|
|
||||||
if cfg.pcr_ids.is_some() && cfg.policy_pubkey_path.is_some() {
|
|
||||||
Ok(TPMPolicyStep::Or([
|
|
||||||
Box::new(TPMPolicyStep::PCRs(
|
|
||||||
utils::get_hash_alg_from_name(cfg.pcr_bank.as_ref()),
|
|
||||||
cfg.get_pcr_ids().unwrap(),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
)),
|
|
||||||
Box::new(utils::get_authorized_policy_step(
|
|
||||||
cfg.policy_pubkey_path.as_ref().unwrap(),
|
|
||||||
&cfg.policy_path,
|
|
||||||
&cfg.policy_ref,
|
|
||||||
)?),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
]))
|
|
||||||
} else if cfg.pcr_ids.is_some() {
|
|
||||||
Ok(TPMPolicyStep::PCRs(
|
|
||||||
utils::get_hash_alg_from_name(cfg.pcr_bank.as_ref()),
|
|
||||||
cfg.get_pcr_ids().unwrap(),
|
|
||||||
Box::new(TPMPolicyStep::NoStep),
|
|
||||||
))
|
|
||||||
} else if cfg.policy_pubkey_path.is_some() {
|
|
||||||
utils::get_authorized_policy_step(
|
|
||||||
cfg.policy_pubkey_path.as_ref().unwrap(),
|
|
||||||
&cfg.policy_path,
|
|
||||||
&cfg.policy_ref,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
Ok(TPMPolicyStep::NoStep)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
|
||||||
struct ClevisInner {
|
|
||||||
pin: String,
|
|
||||||
tpm2: Tpm2Inner,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn perform_decrypt(input: Vec<u8>) -> Result<()> {
|
|
||||||
let input = String::from_utf8(input).context("Error reading input")?;
|
|
||||||
let hdr = josekit::jwt::decode_header(&input).context("Error decoding header")?;
|
|
||||||
let hdr_clevis = hdr.claim("clevis").context("Error getting clevis claim")?;
|
|
||||||
let hdr_clevis: ClevisInner =
|
|
||||||
serde_json::from_value(hdr_clevis.clone()).context("Error deserializing clevis header")?;
|
|
||||||
|
|
||||||
if hdr_clevis.pin != "tpm2" && hdr_clevis.pin != "tpm2plus" {
|
|
||||||
bail!("JWE pin mismatch");
|
|
||||||
}
|
|
||||||
|
|
||||||
let jwkpub = tpm_objects::build_tpm2b_public(&hdr_clevis.tpm2.jwk_pub)?;
|
|
||||||
let jwkpriv = tpm_objects::build_tpm2b_private(&hdr_clevis.tpm2.jwk_priv)?;
|
|
||||||
|
|
||||||
let policy = TPMPolicyStep::try_from(&hdr_clevis.tpm2)?;
|
|
||||||
|
|
||||||
let name_alg = crate::utils::get_hash_alg_from_name(Some(&hdr_clevis.tpm2.hash));
|
|
||||||
let key_public = tpm_objects::get_key_public(hdr_clevis.tpm2.key.as_str(), name_alg)?;
|
|
||||||
|
|
||||||
let mut ctx = utils::get_tpm2_ctx()?;
|
|
||||||
let key_handle = utils::get_tpm2_primary_key(&mut ctx, &key_public)?;
|
|
||||||
|
|
||||||
let key =
|
|
||||||
ctx.execute_with_nullauth_session(|ctx| ctx.load(key_handle, jwkpriv.try_into()?, jwkpub))?;
|
|
||||||
|
|
||||||
let (policy_session, _) = policy.send_policy(&mut ctx, false)?;
|
|
||||||
|
|
||||||
let unsealed = ctx.execute_with_session(policy_session, |ctx| ctx.unseal(key.into()))?;
|
|
||||||
let unsealed = &unsealed.value();
|
|
||||||
let mut jwk = josekit::jwk::Jwk::from_bytes(unsealed).context("Error unmarshaling JWK")?;
|
|
||||||
jwk.set_parameter("alg", None)
|
|
||||||
.context("Error removing the alg parameter")?;
|
|
||||||
let decrypter = Dir
|
|
||||||
.decrypter_from_jwk(&jwk)
|
|
||||||
.context("Error creating decrypter")?;
|
|
||||||
|
|
||||||
let (payload, _) =
|
|
||||||
josekit::jwe::deserialize_compact(&input, &decrypter).context("Error decrypting JWE")?;
|
|
||||||
|
|
||||||
io::stdout().write_all(&payload)?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn print_summary() {
|
fn print_summary() {
|
||||||
println!("Encrypts using a TPM2.0 chip binding policy");
|
println!("Encrypts using a TPM2.0 chip binding policy");
|
||||||
|
@ -227,15 +15,16 @@ fn print_summary() {
|
||||||
fn print_help() {
|
fn print_help() {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"
|
"
|
||||||
Usage: clevis encrypt tpm2 CONFIG < PLAINTEXT > JWE
|
Usage (encryption): clevis encrypt CONFIG < PLAINTEXT > JWE
|
||||||
|
Usage (decryption): clevis decrypt CONFIG < JWE > PLAINTEXT
|
||||||
|
|
||||||
Encrypts using a TPM2.0 chip binding policy
|
Encrypts or decrypts using a TPM2.0 chip binding policy
|
||||||
|
|
||||||
This command uses the following configuration properties:
|
This command uses the following configuration properties:
|
||||||
|
|
||||||
hash: <string> Hash algorithm used in the computation of the object name (default: sha256)
|
hash: <string> Hash algorithm used in the computation of the object name (default: sha256)
|
||||||
|
|
||||||
key: <string> Algorithm type for the generated key (options: eecc, rsa; default: ecc)
|
key: <string> Algorithm type for the generated key (options: ecc, rsa; default: ecc)
|
||||||
|
|
||||||
pcr_bank: <string> PCR algorithm bank to use for policy (default: sha256)
|
pcr_bank: <string> PCR algorithm bank to use for policy (default: sha256)
|
||||||
|
|
||||||
|
@ -278,14 +67,23 @@ fn main() -> Result<()> {
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut input = Vec::new();
|
let mut input = Vec::new();
|
||||||
if let Err(e) = io::stdin().read_to_end(&mut input) {
|
if let Err(e) = std::io::stdin().read_to_end(&mut input) {
|
||||||
eprintln!("Error getting input token: {}", e);
|
eprintln!("Error getting input token: {}", e);
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
match mode {
|
match mode {
|
||||||
cli::ActionMode::Encrypt => perform_encrypt(cfg.unwrap(), input),
|
cli::ActionMode::Encrypt => {
|
||||||
cli::ActionMode::Decrypt => perform_decrypt(input),
|
let token = perform_encrypt(cfg.unwrap(), input)?;
|
||||||
|
stdout().write_all(token.as_bytes())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
cli::ActionMode::Decrypt => {
|
||||||
|
let output = perform_decrypt(input)?;
|
||||||
|
stdout().write_all(&output)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
cli::ActionMode::Summary => unreachable!(),
|
cli::ActionMode::Summary => unreachable!(),
|
||||||
cli::ActionMode::Help => unreachable!(),
|
cli::ActionMode::Help => unreachable!(),
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,35 +1,253 @@
|
||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
|
|
||||||
use anyhow::{anyhow, bail, Result};
|
use crate::utils::get_authorized_policy_step;
|
||||||
use tss_esapi::attributes::object::ObjectAttributesBuilder;
|
use anyhow::{anyhow, bail, Context, Error, Result};
|
||||||
use tss_esapi::constants::tss as tss_constants;
|
use serde::{Deserialize, Serialize};
|
||||||
use tss_esapi::interface_types::ecc::EccCurve;
|
use tpm2_policy::TPMPolicyStep;
|
||||||
use tss_esapi::structures::Digest;
|
use tss_esapi::{
|
||||||
use tss_esapi::utils::{PublicParmsUnion, Tpm2BPublicBuilder, TpmsEccParmsBuilder};
|
attributes::object::ObjectAttributesBuilder,
|
||||||
use tss_esapi::{abstraction::cipher::Cipher, interface_types::algorithm::HashingAlgorithm};
|
constants::tss as tss_constants,
|
||||||
|
interface_types::{
|
||||||
|
algorithm::{HashingAlgorithm, PublicAlgorithm},
|
||||||
|
ecc::EccCurve,
|
||||||
|
},
|
||||||
|
structures::{Digest, Public, SymmetricDefinitionObject},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, std::fmt::Debug)]
|
||||||
|
pub struct TPM2Config {
|
||||||
|
pub hash: Option<String>,
|
||||||
|
pub key: Option<String>,
|
||||||
|
pub pcr_bank: Option<String>,
|
||||||
|
// PCR IDs can be passed in as comma-separated string or json array
|
||||||
|
pub pcr_ids: Option<serde_json::Value>,
|
||||||
|
pub pcr_digest: Option<String>,
|
||||||
|
// Whether to use a policy. If this is specified without pubkey path or policy path, they get set to defaults
|
||||||
|
pub use_policy: Option<bool>,
|
||||||
|
// Public key (in JSON format) for a wildcard policy that's possibly OR'd with the PCR one
|
||||||
|
pub policy_pubkey_path: Option<String>,
|
||||||
|
pub policy_ref: Option<String>,
|
||||||
|
pub policy_path: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<&TPM2Config> for TPMPolicyStep {
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn try_from(cfg: &TPM2Config) -> Result<Self> {
|
||||||
|
if cfg.pcr_ids.is_some() && cfg.policy_pubkey_path.is_some() {
|
||||||
|
Ok(TPMPolicyStep::Or([
|
||||||
|
Box::new(TPMPolicyStep::PCRs(
|
||||||
|
cfg.get_pcr_hash_alg(),
|
||||||
|
cfg.get_pcr_ids().unwrap(),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
)),
|
||||||
|
Box::new(get_authorized_policy_step(
|
||||||
|
cfg.policy_pubkey_path.as_ref().unwrap(),
|
||||||
|
&None,
|
||||||
|
&cfg.policy_ref,
|
||||||
|
)?),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
]))
|
||||||
|
} else if cfg.pcr_ids.is_some() {
|
||||||
|
Ok(TPMPolicyStep::PCRs(
|
||||||
|
cfg.get_pcr_hash_alg(),
|
||||||
|
cfg.get_pcr_ids().unwrap(),
|
||||||
|
Box::new(TPMPolicyStep::NoStep),
|
||||||
|
))
|
||||||
|
} else if cfg.policy_pubkey_path.is_some() {
|
||||||
|
get_authorized_policy_step(
|
||||||
|
cfg.policy_pubkey_path.as_ref().unwrap(),
|
||||||
|
&None,
|
||||||
|
&cfg.policy_ref,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Ok(TPMPolicyStep::NoStep)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) const DEFAULT_POLICY_PATH: &str = "/boot/clevis_policy.json";
|
||||||
|
pub(crate) const DEFAULT_PUBKEY_PATH: &str = "/boot/clevis_pubkey.json";
|
||||||
|
pub(crate) const DEFAULT_POLICY_REF: &str = "";
|
||||||
|
|
||||||
|
impl TPM2Config {
|
||||||
|
pub(super) fn get_pcr_hash_alg(
|
||||||
|
&self,
|
||||||
|
) -> tss_esapi::interface_types::algorithm::HashingAlgorithm {
|
||||||
|
crate::utils::get_hash_alg_from_name(self.pcr_bank.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn get_name_hash_alg(
|
||||||
|
&self,
|
||||||
|
) -> tss_esapi::interface_types::algorithm::HashingAlgorithm {
|
||||||
|
crate::utils::get_hash_alg_from_name(self.hash.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn get_pcr_ids(&self) -> Option<Vec<u64>> {
|
||||||
|
match &self.pcr_ids {
|
||||||
|
None => None,
|
||||||
|
Some(serde_json::Value::Array(vals)) => {
|
||||||
|
Some(vals.iter().map(|x| x.as_u64().unwrap()).collect())
|
||||||
|
}
|
||||||
|
_ => panic!("Unexpected type found for pcr_ids"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn get_pcr_ids_str(&self) -> Option<String> {
|
||||||
|
match &self.pcr_ids {
|
||||||
|
None => None,
|
||||||
|
Some(serde_json::Value::Array(vals)) => Some(
|
||||||
|
vals.iter()
|
||||||
|
.map(|x| x.as_u64().unwrap().to_string())
|
||||||
|
.collect::<Vec<String>>()
|
||||||
|
.join(","),
|
||||||
|
),
|
||||||
|
_ => panic!("Unexpected type found for pcr_ids"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn normalize(mut self) -> Result<TPM2Config> {
|
||||||
|
self.normalize_pcr_ids()?;
|
||||||
|
if self.pcr_ids.is_some() && self.pcr_bank.is_none() {
|
||||||
|
self.pcr_bank = Some("sha256".to_string());
|
||||||
|
}
|
||||||
|
// Make use of the defaults if not specified
|
||||||
|
if self.use_policy.is_some() && self.use_policy.unwrap() {
|
||||||
|
if self.policy_path.is_none() {
|
||||||
|
self.policy_path = Some(DEFAULT_POLICY_PATH.to_string());
|
||||||
|
}
|
||||||
|
if self.policy_pubkey_path.is_none() {
|
||||||
|
self.policy_pubkey_path = Some(DEFAULT_PUBKEY_PATH.to_string());
|
||||||
|
}
|
||||||
|
if self.policy_ref.is_none() {
|
||||||
|
self.policy_ref = Some(DEFAULT_POLICY_REF.to_string());
|
||||||
|
}
|
||||||
|
} else if self.policy_pubkey_path.is_some()
|
||||||
|
|| self.policy_path.is_some()
|
||||||
|
|| self.policy_ref.is_some()
|
||||||
|
{
|
||||||
|
eprintln!("To use a policy, please specifiy use_policy: true. Not specifying this will be a fatal error in a next release");
|
||||||
|
}
|
||||||
|
if (self.policy_pubkey_path.is_some()
|
||||||
|
|| self.policy_path.is_some()
|
||||||
|
|| self.policy_ref.is_some())
|
||||||
|
&& (self.policy_pubkey_path.is_none()
|
||||||
|
|| self.policy_path.is_none()
|
||||||
|
|| self.policy_ref.is_none())
|
||||||
|
{
|
||||||
|
bail!("Not all of policy pubkey, path and ref are specified",);
|
||||||
|
}
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_pcr_ids(&mut self) -> Result<()> {
|
||||||
|
// Normalize from array with one string to just string
|
||||||
|
if let Some(serde_json::Value::Array(vals)) = &self.pcr_ids {
|
||||||
|
if vals.len() == 1 {
|
||||||
|
if let serde_json::Value::String(val) = &vals[0] {
|
||||||
|
self.pcr_ids = Some(serde_json::Value::String(val.to_string()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Normalize pcr_ids from comma-separated string to array
|
||||||
|
if let Some(serde_json::Value::String(val)) = &self.pcr_ids {
|
||||||
|
// Was a string, do a split
|
||||||
|
let newval: Vec<serde_json::Value> = val
|
||||||
|
.split(',')
|
||||||
|
.map(|x| serde_json::Value::String(x.trim().to_string()))
|
||||||
|
.collect();
|
||||||
|
self.pcr_ids = Some(serde_json::Value::Array(newval));
|
||||||
|
}
|
||||||
|
// Normalize pcr_ids from array of Strings to array of Numbers
|
||||||
|
if let Some(serde_json::Value::Array(vals)) = &self.pcr_ids {
|
||||||
|
let newvals: Result<Vec<serde_json::Value>, _> = vals
|
||||||
|
.iter()
|
||||||
|
.map(|x| match x {
|
||||||
|
serde_json::Value::String(val) => {
|
||||||
|
match val.trim().parse::<serde_json::Number>() {
|
||||||
|
Ok(res) => {
|
||||||
|
let new = serde_json::Value::Number(res);
|
||||||
|
if !new.is_u64() {
|
||||||
|
bail!("Non-positive string int");
|
||||||
|
}
|
||||||
|
Ok(new)
|
||||||
|
}
|
||||||
|
Err(_) => Err(anyhow!("Unparseable string int")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
serde_json::Value::Number(n) => {
|
||||||
|
let new = serde_json::Value::Number(n.clone());
|
||||||
|
if !new.is_u64() {
|
||||||
|
return Err(anyhow!("Non-positive int"));
|
||||||
|
}
|
||||||
|
Ok(new)
|
||||||
|
}
|
||||||
|
_ => Err(anyhow!("Invalid value in pcr_ids")),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
self.pcr_ids = Some(serde_json::Value::Array(newvals?));
|
||||||
|
}
|
||||||
|
|
||||||
|
match &self.pcr_ids {
|
||||||
|
None => Ok(()),
|
||||||
|
// The normalization above would've caught any non-ints
|
||||||
|
Some(serde_json::Value::Array(_)) => Ok(()),
|
||||||
|
_ => Err(anyhow!("Invalid type")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(target_pointer_width = "64")]
|
#[cfg(target_pointer_width = "64")]
|
||||||
type Sizedu = u64;
|
type Sizedu = u64;
|
||||||
#[cfg(target_pointer_width = "32")]
|
#[cfg(target_pointer_width = "32")]
|
||||||
type Sizedu = u32;
|
type Sizedu = u32;
|
||||||
|
|
||||||
pub(super) fn get_key_public(
|
pub(super) fn get_key_public(key_type: &str, name_alg: HashingAlgorithm) -> Result<Public> {
|
||||||
key_type: &str,
|
let object_attributes = ObjectAttributesBuilder::new()
|
||||||
name_alg: HashingAlgorithm,
|
.with_fixed_tpm(true)
|
||||||
) -> Result<tss_esapi::tss2_esys::TPM2B_PUBLIC> {
|
.with_fixed_parent(true)
|
||||||
|
.with_sensitive_data_origin(true)
|
||||||
|
.with_user_with_auth(true)
|
||||||
|
.with_decrypt(true)
|
||||||
|
.with_sign_encrypt(false)
|
||||||
|
.with_restricted(true)
|
||||||
|
.build()?;
|
||||||
|
|
||||||
|
let builder = tss_esapi::structures::PublicBuilder::new()
|
||||||
|
.with_object_attributes(object_attributes)
|
||||||
|
.with_name_hashing_algorithm(name_alg);
|
||||||
|
|
||||||
match key_type {
|
match key_type {
|
||||||
"ecc" => Ok(create_restricted_ecc_public()),
|
"ecc" => builder
|
||||||
"rsa" => Ok(tss_esapi::utils::create_restricted_decryption_rsa_public(
|
.with_public_algorithm(PublicAlgorithm::Ecc)
|
||||||
Cipher::aes_128_cfb(),
|
.with_ecc_parameters(
|
||||||
2048,
|
tss_esapi::structures::PublicEccParametersBuilder::new_restricted_decryption_key(
|
||||||
0,
|
SymmetricDefinitionObject::AES_128_CFB,
|
||||||
)?),
|
EccCurve::NistP256,
|
||||||
_ => Err(anyhow!("Unsupported key type used")),
|
)
|
||||||
|
.build()?,
|
||||||
|
)
|
||||||
|
.with_ecc_unique_identifier(Default::default()),
|
||||||
|
"rsa" => builder
|
||||||
|
.with_public_algorithm(PublicAlgorithm::Rsa)
|
||||||
|
.with_rsa_parameters(
|
||||||
|
tss_esapi::structures::PublicRsaParametersBuilder::new_restricted_decryption_key(
|
||||||
|
SymmetricDefinitionObject::AES_128_CFB,
|
||||||
|
tss_esapi::interface_types::key_bits::RsaKeyBits::Rsa2048,
|
||||||
|
tss_esapi::structures::RsaExponent::ZERO_EXPONENT,
|
||||||
|
)
|
||||||
|
.build()?,
|
||||||
|
)
|
||||||
|
.with_rsa_unique_identifier(Default::default()),
|
||||||
|
_ => return Err(anyhow!("Unsupported key type used")),
|
||||||
}
|
}
|
||||||
.map(|mut public| {
|
.build()
|
||||||
public.publicArea.nameAlg = name_alg.into();
|
.context("Error building public key")
|
||||||
public
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn create_tpm2b_public_sealed_object(
|
pub(super) fn create_tpm2b_public_sealed_object(
|
||||||
|
@ -142,28 +360,3 @@ pub(super) fn build_tpm2b_public(val: &[u8]) -> Result<tss_esapi::tss2_esys::TPM
|
||||||
|
|
||||||
Ok(resp)
|
Ok(resp)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn create_restricted_ecc_public() -> tss_esapi::tss2_esys::TPM2B_PUBLIC {
|
|
||||||
let ecc_params = TpmsEccParmsBuilder::new_restricted_decryption_key(
|
|
||||||
Cipher::aes_128_cfb(),
|
|
||||||
EccCurve::NistP256,
|
|
||||||
)
|
|
||||||
.build()
|
|
||||||
.unwrap();
|
|
||||||
let object_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_sign_encrypt(false)
|
|
||||||
.with_restricted(true);
|
|
||||||
|
|
||||||
Tpm2BPublicBuilder::new()
|
|
||||||
.with_type(tss_constants::TPM2_ALG_ECC)
|
|
||||||
.with_name_alg(tss_constants::TPM2_ALG_SHA256)
|
|
||||||
.with_object_attributes(object_attributes.build().unwrap())
|
|
||||||
.with_parms(PublicParmsUnion::EccDetail(ecc_params))
|
|
||||||
.build()
|
|
||||||
.unwrap()
|
|
||||||
}
|
|
||||||
|
|
|
@ -8,6 +8,7 @@ use tpm2_policy::{PublicKey, SignedPolicyList, TPMPolicyStep};
|
||||||
use tss_esapi::{
|
use tss_esapi::{
|
||||||
handles::KeyHandle,
|
handles::KeyHandle,
|
||||||
interface_types::{algorithm::HashingAlgorithm, resource_handles::Hierarchy},
|
interface_types::{algorithm::HashingAlgorithm, resource_handles::Hierarchy},
|
||||||
|
structures::Public,
|
||||||
Context, Tcti,
|
Context, Tcti,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -75,7 +76,7 @@ where
|
||||||
D: serde::Deserializer<'de>,
|
D: serde::Deserializer<'de>,
|
||||||
{
|
{
|
||||||
String::deserialize(deserializer).and_then(|string| {
|
String::deserialize(deserializer).and_then(|string| {
|
||||||
base64::decode_config(&string, base64::URL_SAFE_NO_PAD).map_err(serde::de::Error::custom)
|
base64::decode_config(string, base64::URL_SAFE_NO_PAD).map_err(serde::de::Error::custom)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -95,10 +96,7 @@ pub(crate) fn get_tpm2_ctx() -> Result<tss_esapi::Context> {
|
||||||
Context::new(tcti).context("Error initializing TPM2 context")
|
Context::new(tcti).context("Error initializing TPM2 context")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn get_tpm2_primary_key(
|
pub(crate) fn get_tpm2_primary_key(ctx: &mut Context, pub_template: Public) -> Result<KeyHandle> {
|
||||||
ctx: &mut Context,
|
|
||||||
pub_template: &tss_esapi::tss2_esys::TPM2B_PUBLIC,
|
|
||||||
) -> Result<KeyHandle> {
|
|
||||||
ctx.execute_with_nullauth_session(|ctx| {
|
ctx.execute_with_nullauth_session(|ctx| {
|
||||||
ctx.create_primary(Hierarchy::Owner, pub_template, None, None, None, None)
|
ctx.create_primary(Hierarchy::Owner, pub_template, None, None, None, None)
|
||||||
.map(|r| r.key_handle)
|
.map(|r| r.key_handle)
|
||||||
|
|
Loading…
Reference in a new issue