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

keyring: initial ECDSA support (YubiHSM2 only) #76

Merged
merged 1 commit into from
Jun 15, 2020
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
1 change: 1 addition & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ tendermint = "0.13"
thiserror = "1"
wait-timeout = "0.2"
x25519-dalek = "0.6"
yubihsm = { version = "0.33", features = ["setup", "usb"], optional = true }
yubihsm = { version = "0.33", features = ["secp256k1", "setup", "usb"], optional = true }
zeroize = "1"
merlin = "2"

Expand Down
32 changes: 25 additions & 7 deletions src/chain/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,53 @@ use crate::{
error::{Error, ErrorKind::*},
keyring,
prelude::*,
Map,
};
use once_cell::sync::Lazy;
use std::{collections::BTreeMap, sync::RwLock};
use std::sync::RwLock;

/// State of Tendermint blockchain networks
pub static REGISTRY: Lazy<GlobalRegistry> = Lazy::new(GlobalRegistry::default);

/// Registry of blockchain networks known to the KMS
#[derive(Default)]
pub struct Registry(BTreeMap<Id, Chain>);
pub struct Registry(Map<Id, Chain>);

impl Registry {
/// Add a key to a keyring for a chain stored in the registry
pub fn add_to_keyring(
/// Add an account key to a keyring for a chain stored in the registry
pub fn add_account_key(
&mut self,
chain_id: &Id,
signer: keyring::ecdsa::Signer,
) -> Result<(), Error> {
let chain = self.0.get_mut(chain_id).ok_or_else(|| {
format_err!(
InvalidKey,
"can't add ECDSA signer {} to unregistered chain: {}",
signer.provider(),
chain_id
)
})?;

chain.keyring.add_ecdsa(signer)
}

/// Add a consensus key to a keyring for a chain stored in the registry
pub fn add_consensus_key(
&mut self,
chain_id: &Id,
signer: keyring::ed25519::Signer,
) -> Result<(), Error> {
// TODO(tarcieri):
let chain = self.0.get_mut(chain_id).ok_or_else(|| {
format_err!(
InvalidKey,
"can't add signer {} to unregistered chain: {}",
"can't add Ed25519 signer {} to unregistered chain: {}",
signer.provider(),
chain_id
)
})?;

chain.keyring.add(signer)
chain.keyring.add_ed25519(signer)
}

/// Register a `Chain` with the registry
Expand Down
4 changes: 2 additions & 2 deletions src/commands/yubihsm/keys/list.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
//! List keys inside the YubiHSM2

use crate::{application::app_config, chain, keyring, prelude::*};
use crate::{application::app_config, chain, keyring, prelude::*, Map};
use abscissa_core::{Command, Options, Runnable};
use std::{collections::BTreeMap as Map, path::PathBuf, process};
use std::{path::PathBuf, process};
use tendermint::{PublicKey, TendermintKey};

/// The `yubihsm keys list` subcommand
Expand Down
20 changes: 20 additions & 0 deletions src/config/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,23 @@ pub struct ProviderConfig {
#[serde(default)]
pub ledgertm: Vec<LedgerTendermintConfig>,
}

/// Types of cryptographic keys
// TODO(tarcieri): move this into a provider-agnostic module
#[derive(Clone, Debug, Deserialize)]
pub enum KeyType {
/// Account keys
#[serde(rename = "account")]
Account,

/// Consensus keys
#[serde(rename = "consensus")]
Consensus,
}

impl Default for KeyType {
/// Backwards compat for existing configuration files
fn default() -> Self {
KeyType::Consensus
}
}
5 changes: 5 additions & 0 deletions src/config/provider/yubihsm.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Configuration for the `YubiHSM` backend

use super::KeyType;
use crate::{chain, prelude::*};
use abscissa_core::secret::{CloneableSecret, DebugSecret, ExposeSecret, Secret};
use serde::Deserialize;
Expand Down Expand Up @@ -117,6 +118,10 @@ pub struct SigningKeyConfig {

/// Signing key ID
pub key: u16,

/// Type of key
#[serde(default, rename = "type")]
pub key_type: KeyType,
}

/// Default value for `AdapterConfig::Usb { timeout_ms }`
Expand Down
67 changes: 53 additions & 14 deletions src/keyring.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,30 @@
//! Signing keyring. Presently specialized for Ed25519.

pub mod ecdsa;
pub mod ed25519;
pub mod format;
pub mod providers;

use self::ed25519::Signer;
pub use self::{format::Format, providers::SigningProvider};
use crate::{
chain,
config::provider::ProviderConfig,
error::{Error, ErrorKind::*},
prelude::*,
Map,
};
use std::collections::BTreeMap;
use tendermint::TendermintKey;

/// File encoding for software-backed secret keys
pub type SecretKeyEncoding = subtle_encoding::Base64;

/// Signing keyring
pub struct KeyRing {
/// Keys in the keyring
keys: BTreeMap<TendermintKey, Signer>,
/// ECDSA keys in the keyring
ecdsa_keys: Map<TendermintKey, ecdsa::Signer>,

/// Ed25519 keys in the keyring
ed25519_keys: Map<TendermintKey, ed25519::Signer>,

/// Formatting configuration when displaying keys (e.g. bech32)
format: Format,
Expand All @@ -31,28 +34,64 @@ impl KeyRing {
/// Create a new keyring
pub fn new(format: Format) -> Self {
Self {
keys: BTreeMap::new(),
ecdsa_keys: Map::new(),
ed25519_keys: Map::new(),
format,
}
}

/// Add a key to the keyring, returning an error if we already have a
/// Add na ECDSA key to the keyring, returning an error if we already have a
/// signer registered for the given public key
pub fn add(&mut self, signer: Signer) -> Result<(), Error> {
pub fn add_ecdsa(&mut self, signer: ecdsa::Signer) -> Result<(), Error> {
let provider = signer.provider();
let public_key = signer.public_key();
let public_key_serialized = self.format.serialize(public_key);
let key_type = match public_key {
TendermintKey::AccountKey(_) => "account",
TendermintKey::ConsensusKey(_) => unimplemented!(
"ECDSA consensus keys unsupported: {:?}",
public_key_serialized
),
};

info!(
"[keyring:{}] added {} ECDSA key: {}",
provider, key_type, public_key_serialized
);

if let Some(other) = self.ecdsa_keys.insert(public_key, signer) {
fail!(
InvalidKey,
"[keyring:{}] duplicate key {} already registered as {}",
provider,
public_key_serialized,
other.provider(),
)
} else {
Ok(())
}
}

/// Add a key to the keyring, returning an error if we already have a
/// signer registered for the given public key
pub fn add_ed25519(&mut self, signer: ed25519::Signer) -> Result<(), Error> {
let provider = signer.provider();
let public_key = signer.public_key();
let public_key_serialized = self.format.serialize(public_key);
let key_type = match public_key {
TendermintKey::AccountKey(_) => unimplemented!(
"Ed25519 account keys unsupported: {:?}",
public_key_serialized
),
TendermintKey::ConsensusKey(_) => "consensus",
};

info!(
"[keyring:{}] added {} key {}",
"[keyring:{}] added {} Ed25519 key: {}",
provider, key_type, public_key_serialized
);

if let Some(other) = self.keys.insert(public_key, signer) {
if let Some(other) = self.ed25519_keys.insert(public_key, signer) {
fail!(
InvalidKey,
"[keyring:{}] duplicate key {} already registered as {}",
Expand All @@ -65,9 +104,9 @@ impl KeyRing {
}
}

/// Get the default public key for this keyring
pub fn default_pubkey(&self) -> Result<TendermintKey, Error> {
let mut keys = self.keys.keys();
/// Get the default Ed25519 (i.e. consensus) public key for this keyring
pub fn default_ed25519_pubkey(&self) -> Result<TendermintKey, Error> {
let mut keys = self.ed25519_keys.keys();

if keys.len() == 1 {
Ok(*keys.next().unwrap())
Expand All @@ -84,11 +123,11 @@ impl KeyRing {
msg: &[u8],
) -> Result<ed25519::Signature, Error> {
let signer = match public_key {
Some(public_key) => self.keys.get(public_key).ok_or_else(|| {
Some(public_key) => self.ed25519_keys.get(public_key).ok_or_else(|| {
format_err!(InvalidKey, "not in keyring: {}", public_key.to_bech32(""))
})?,
None => {
let mut vals = self.keys.values();
let mut vals = self.ed25519_keys.values();

if vals.len() > 1 {
fail!(SigningError, "expected only one key in keyring");
Expand Down
58 changes: 58 additions & 0 deletions src/keyring/ecdsa.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
//! ECDSA keys

pub use signatory::ecdsa::curve::secp256k1::{FixedSignature as Signature, PublicKey};

use crate::{
error::{Error, ErrorKind::*},
keyring::SigningProvider,
prelude::*,
};
use signatory::signature;
use std::sync::Arc;
use tendermint::TendermintKey;

/// ECDSA signer
#[derive(Clone)]
pub struct Signer {
/// Provider for this signer
provider: SigningProvider,

/// Tendermint public key
public_key: TendermintKey,

/// Signer trait object
signer: Arc<Box<dyn signature::Signer<Signature> + Send + Sync>>,
}

impl Signer {
/// Create a new signer
pub fn new(
provider: SigningProvider,
public_key: TendermintKey,
signer: Box<dyn signature::Signer<Signature> + Send + Sync>,
) -> Self {
Self {
provider,
public_key,
signer: Arc::new(signer),
}
}

/// Get the Tendermint public key for this signer
pub fn public_key(&self) -> TendermintKey {
self.public_key
}

/// Get the provider for this signer
pub fn provider(&self) -> SigningProvider {
self.provider
}

/// Sign the given message using this signer
pub fn sign(&self, msg: &[u8]) -> Result<Signature, Error> {
Ok(self
.signer
.try_sign(msg)
.map_err(|e| format_err!(SigningError, "{}", e))?)
}
}
2 changes: 1 addition & 1 deletion src/keyring/ed25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use signatory::signature;
use std::sync::Arc;
use tendermint::TendermintKey;

/// Trait object wrapper for an Ed25519 signers
/// Ed25519 signer
#[derive(Clone)]
pub struct Signer {
/// Provider for this signer
Expand Down
2 changes: 1 addition & 1 deletion src/keyring/providers/ledgertm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub fn init(
);

for chain_id in &ledgertm_configs[0].chain_ids {
chain_registry.add_to_keyring(chain_id, signer.clone())?;
chain_registry.add_consensus_key(chain_id, signer.clone())?;
}

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion src/keyring/providers/softsign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ pub fn init(chain_registry: &mut chain::Registry, configs: &[SoftsignConfig]) ->
);

for chain_id in &config.chain_ids {
chain_registry.add_to_keyring(chain_id, signer.clone())?;
chain_registry.add_consensus_key(chain_id, signer.clone())?;
}

Ok(())
Expand Down
Loading