Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Secure signing: Key rotation with CLI #1002

Merged
merged 11 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ members = [
"util/signing/integrations/aptos",
"util/signing/providers/aws-kms",
"util/signing/providers/hashicorp-vault",
"util/signing/signing-admin",
"demo/hsm"
]

Expand Down
14 changes: 7 additions & 7 deletions demo/hsm/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ use clap::Parser;
#[derive(Parser)]
#[clap(rename_all = "kebab-case")]
pub enum HsmDemo {
#[clap(subcommand)]
Server(server::Server),
#[clap(subcommand)]
Server(server::Server),
}

impl HsmDemo {
pub async fn run(&self) -> Result<(), anyhow::Error> {
match self {
HsmDemo::Server(server) => server.run().await,
}
}
pub async fn run(&self) -> Result<(), anyhow::Error> {
match self {
HsmDemo::Server(server) => server.run().await,
}
}
}
22 changes: 16 additions & 6 deletions util/signing/providers/hashicorp-vault/src/hsm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,17 @@ where
return Err(SignerError::Internal("Invalid signature format".to_string()));
}

let signature_str = res.signature.split_at(9).1;
// Extract the key version from the signature
let version_end_index = res.signature[6..]
.find(':')
.ok_or_else(|| SignerError::Internal("Invalid signature format".to_string()))?
+ 6;

// Determine split index dynamically
let split_index = version_end_index + 1;

// Split and decode the signature
let signature_str = &res.signature[split_index..];

let signature = base64::decode(signature_str)
.context("Failed to decode base64 signature from Vault")
Expand All @@ -108,15 +118,17 @@ where
}

let parsed_signature = C::Signature::try_from_bytes(&signature).map_err(|e| {
SignerError::Internal(format!("Failed to parse signature into expected format: {:?}", e))
SignerError::Internal(format!(
"Failed to parse signature into expected format: {:?}",
e
))
})?;

Ok(parsed_signature)
}


async fn public_key(&self) -> Result<C::PublicKey, SignerError> {
println!("Attempting to read key: {}", self.key_name);
println!("Attempting to read Vault key: {}", self.key_name);

// Read the key from Vault
let res = transit_key::read(
Expand Down Expand Up @@ -146,13 +158,11 @@ where
ReadKeyData::Asymmetric(keys) => {
// Use the number of items in the map as the version
let latest_version = keys.len().to_string();
println!("Using key version: {}", latest_version);

let key = keys.get(&latest_version).context("Key version not found").map_err(|e| {
println!("Key version '{}' not found: {:?}", latest_version, e);
SignerError::KeyNotFound
})?;
println!("Using public key for version {}: {}", latest_version, key.public_key);

base64::decode(&key.public_key).map_err(|e| {
println!("Failed to decode public key: {:?}", e);
Expand Down
29 changes: 29 additions & 0 deletions util/signing/signing-admin/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
[package]
name = "signing_admin"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <[email protected]>"]
description = "CLI for managing signing keys"
license = "MIT"
repository = "https://github.com/your/repo"

[dependencies]
anyhow = "1.0"
async-trait = { workspace = true }
aws-config = { workspace = true }
aws-sdk-kms = { workspace = true }
base64 = { workspace = true }
clap = { version = "4.0", features = ["derive"] }
movement-signer = { workspace = true }
movement-signer-aws-kms = { workspace = true }
movement-signer-hashicorp-vault = { workspace = true }
reqwest = { version = "0.11", features = ["json"] }
serde_json = { workspace = true }
simple_asn1 = "0.6"
tokio = { version = "1", features = ["full"] }
uuid = { workspace = true }
vaultrs = { workspace = true }

[[bin]]
name = "signing-admin"
path = "src/main.rs"
42 changes: 42 additions & 0 deletions util/signing/signing-admin/src/application/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use anyhow::Result;

#[async_trait::async_trait]
pub trait Application {
async fn notify_public_key(&self, public_key: Vec<u8>) -> Result<()>;
}

pub struct HttpApplication {
app_url: String,
}

impl HttpApplication {
pub fn new(app_url: String) -> Self {
Self { app_url }
}
}

#[async_trait::async_trait]
impl Application for HttpApplication {
async fn notify_public_key(&self, public_key: Vec<u8>) -> Result<()> {
let endpoint = format!("{}/public_key/set", self.app_url);
println!("Notifying application at {} with public key {:?}", endpoint, public_key);

let client = reqwest::Client::new();
let response = client
.post(&endpoint)
.json(&serde_json::json!({ "public_key": public_key }))
.send()
.await?;

if !response.status().is_success() {
anyhow::bail!(
"Failed to notify application. Status: {}, Body: {:?}",
response.status(),
response.text().await?
);
}

println!("Successfully notified the application.");
Ok(())
}
}
66 changes: 66 additions & 0 deletions util/signing/signing-admin/src/backend/aws.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
use anyhow::{Context, Result};
use aws_config;
use aws_sdk_kms::{Client as KmsClient};
use aws_sdk_kms::types::Tag;
use super::SigningBackend;

pub struct AwsBackend;

impl AwsBackend {
pub fn new() -> Self {
Self {}
}

async fn create_client() -> Result<KmsClient> {
let aws_config = aws_config::load_from_env().await;
Ok(KmsClient::new(&aws_config))
}

async fn create_key(client: &KmsClient) -> Result<String> {
let response = client
.create_key()
.description("Key for signing and verification")
.key_usage(aws_sdk_kms::types::KeyUsageType::SignVerify)
.customer_master_key_spec(aws_sdk_kms::types::CustomerMasterKeySpec::EccSecgP256K1)
.tags(
Tag::builder()
.tag_key("unique_id")
.tag_value("tag")
.build()
.context("Failed to build AWS KMS tag")?,
)
.send()
.await
.context("Failed to create key with AWS KMS")?;

response
.key_metadata()
.and_then(|meta| Some(meta.key_id().to_string()))
.context("Failed to retrieve key ID from AWS response")
}
}

#[async_trait::async_trait]
impl SigningBackend for AwsBackend {
async fn rotate_key(&self, key_id: &str) -> Result<()> {
let client = Self::create_client().await?;

// Ensure the key_id starts with "alias/"
let full_alias = if key_id.starts_with("alias/") {
key_id.to_string()
} else {
format!("alias/{}", key_id)
};

let new_key_id = Self::create_key(&client).await?;
client
.update_alias()
.alias_name(&full_alias)
.target_key_id(&new_key_id)
.send()
.await
.context("Failed to update AWS KMS alias")?;

Ok(())
}
}
30 changes: 30 additions & 0 deletions util/signing/signing-admin/src/backend/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
pub mod aws;
pub mod vault;

use anyhow::Result;
use async_trait::async_trait;
use aws::AwsBackend;
use vault::VaultBackend;

/// The trait that all signing backends must implement.
#[async_trait]
pub trait SigningBackend {
async fn rotate_key(&self, key_id: &str) -> Result<()>;
}

/// Enum to represent the different backends.
pub enum Backend {
Aws(AwsBackend),
Vault(VaultBackend),
}

/// Implement the SigningBackend trait for the Backend enum.
#[async_trait]
impl SigningBackend for Backend {
async fn rotate_key(&self, key_id: &str) -> Result<()> {
match self {
Backend::Aws(aws) => aws.rotate_key(key_id).await,
Backend::Vault(vault) => vault.rotate_key(key_id).await,
}
}
}
32 changes: 32 additions & 0 deletions util/signing/signing-admin/src/backend/vault.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use anyhow::{Context, Result};
use vaultrs::client::{VaultClient, VaultClientSettingsBuilder};
use vaultrs::transit::key::rotate;
use super::SigningBackend;

pub struct VaultBackend;

impl VaultBackend {
pub fn new() -> Self {
Self {}
}

async fn create_client(vault_url: &str, token: &str) -> Result<VaultClient> {
let settings = VaultClientSettingsBuilder::default()
.address(vault_url)
.token(token)
.namespace(Some("admin".to_string()))
.build()
.context("Failed to build Vault client settings")?;
VaultClient::new(settings).context("Failed to create Vault client")
}
}

#[async_trait::async_trait]
impl SigningBackend for VaultBackend {
async fn rotate_key(&self, key_id: &str) -> Result<()> {
let vault_url = std::env::var("VAULT_URL").context("Missing VAULT_URL environment variable")?;
let token = std::env::var("VAULT_TOKEN").context("Missing VAULT_TOKEN environment variable")?;
let client = Self::create_client(&vault_url, &token).await?;
rotate(&client, "transit", key_id).await.context("Failed to rotate key in Vault")
}
}
24 changes: 24 additions & 0 deletions util/signing/signing-admin/src/cli/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use clap::{Parser, Subcommand};

pub mod rotate_key;

#[derive(Parser, Debug)]
#[clap(name = "signing-admin", about = "CLI for managing signing keys")]
pub struct CLI {
#[clap(subcommand)]
pub command: Commands,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
RotateKey {
#[clap(long, help = "Canonical string of the key (alias for the backend key)")]
canonical_string: String,

#[clap(long, help = "Application URL to notify about the key rotation")]
application_url: String,

#[clap(long, help = "Backend to use (e.g., 'vault', 'aws')")]
backend: String,
},
}
Loading
Loading