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

Keypair verifies #62

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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: 20 additions & 1 deletion src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,7 @@ impl SkfClient {
devaddr: skf.devaddr.into(),
session_key: skf.session_key.to_owned(),
action: ActionV1::Remove.into(),
max_copies: 0
max_copies: 0,
})
.collect(),
timestamp: current_timestamp()?,
Expand Down Expand Up @@ -757,6 +757,24 @@ fn current_timestamp() -> Result<u64> {
Ok(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64)
}

pub fn verify_keypair(keypair: &Keypair) -> Result<bool> {
let mut req = RouteListReqV1 {
oui: 0,
timestamp: current_timestamp()?,
signer: keypair.public_key().to_vec(),
signature: vec![],
};
req.signature = req
.sign(keypair)
.map_err(|e| anyhow!("failed to sign: {e:?}"))?;

let _verified = req
.verify(&keypair.public_key())
.map_err(|e| anyhow!("keypair corrupted: {e:?}"))?;

Ok(true)
}

pub trait MsgSign: Message + std::clone::Clone {
fn sign(&self, keypair: &Keypair) -> Result<Vec<u8>>
where
Expand Down Expand Up @@ -819,6 +837,7 @@ macro_rules! impl_verify {
};
}

impl_verify!(RouteListReqV1, signature);
impl_verify!(OrgListResV1, signature);
impl_verify!(OrgResV1, signature);
impl_verify!(OrgEnableResV1, signature);
Expand Down
55 changes: 38 additions & 17 deletions src/cmds/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::{env, fs, path::PathBuf};
use super::{
EnvInfo, GenerateKeypair, ENV_CONFIG_HOST, ENV_KEYPAIR_BIN, ENV_MAX_COPIES, ENV_NET_ID, ENV_OUI,
};
use crate::{hex_field, Msg, Oui, PrettyJson, Result};
use crate::{client::verify_keypair, hex_field, Msg, Oui, PrettyJson, Result};
use anyhow::Context;
use dialoguer::Input;
use helium_crypto::Keypair;
Expand Down Expand Up @@ -65,10 +65,10 @@ pub async fn env_init() -> Result<Msg> {

pub fn env_info(args: EnvInfo) -> Result<Msg> {
let env_keypair = env::var(ENV_KEYPAIR_BIN).ok().map(|i| i.into());
let (env_keypair_location, env_public_key, env_key_type) =
get_public_key_from_path(env_keypair);
let (arg_keypair_location, arg_public_key, arg_key_type) =
get_public_key_from_path(args.keypair);
let (env_keypair_location, env_public_key, env_key_type, env_verifies) =
get_public_key_from_path(&env_keypair);
let (arg_keypair_location, arg_public_key, arg_key_type, arg_verifies) =
get_public_key_from_path(&args.keypair);

let output = json!({
"environment": {
Expand All @@ -79,6 +79,7 @@ pub fn env_info(args: EnvInfo) -> Result<Msg> {
ENV_KEYPAIR_BIN: env_keypair_location,
"public_key_from_keypair": env_public_key,
"key_type_from_keypair": env_key_type,
"keypair_verifies_own_sig": env_verifies,
},
"arguments": {
"config_host": args.config_host,
Expand All @@ -87,7 +88,8 @@ pub fn env_info(args: EnvInfo) -> Result<Msg> {
"max_copies": args.max_copies,
"keypair": arg_keypair_location,
"public_key_from_keypair": arg_public_key,
"key_type_from_keypair": arg_key_type
"key_type_from_keypair": arg_key_type,
"keypair_verifies_own_sig": arg_verifies,
}
});
Msg::ok(output.pretty_json()?)
Expand Down Expand Up @@ -123,24 +125,38 @@ pub fn generate_keypair(args: GenerateKeypair) -> Result<Msg> {
))
}

pub fn get_public_key_from_path(path: Option<PathBuf>) -> (String, String, String) {
pub fn get_public_key_from_path(path: &Option<PathBuf>) -> (String, String, String, String) {
match path {
None => (
"unset".to_string(),
"unset".to_string(),
"unset".to_string(),
"unset".to_string(),
),
Some(path) => {
let display_path = path.as_path().display().to_string();
match fs::read(path).with_context(|| format!("path does not exist: {display_path}")) {
Err(e) => (e.to_string(), "".to_string(), "".to_string()),
Err(e) => (
e.to_string(),
"".to_string(),
"".to_string(),
"".to_string(),
),
Ok(data) => match Keypair::try_from(&data[..]) {
Err(e) => (display_path, e.to_string(), "".to_string()),
Ok(keypair) => (
display_path,
keypair.public_key().to_string(),
keypair.key_tag().key_type.to_string(),
),
Err(e) => (display_path, e.to_string(), "".to_string(), "".to_string()),
Ok(keypair) => {
let verified = match verify_keypair(&keypair) {
Err(e) => format!("failed to verify: {e:?}"),
Ok(_) => "verified".to_string(),
};

(
display_path,
keypair.public_key().to_string(),
keypair.key_tag().key_type.to_string(),
verified,
)
}
},
}
}
Expand Down Expand Up @@ -226,10 +242,12 @@ mod tests {

#[test]
fn get_keypair_does_not_exist() {
let (location, pubkey, key_type) = get_public_key_from_path(Some("./nowhere.bin".into()));
let (location, pubkey, key_type, verified) =
get_public_key_from_path(&Some("./nowhere.bin".into()));
assert_eq!(location, "path does not exist: ./nowhere.bin");
assert!(pubkey.is_empty());
assert!(key_type.is_empty());
assert!(verified.is_empty());
}

#[test]
Expand All @@ -240,17 +258,20 @@ mod tests {
fs::write(arg_keypair.clone(), "invalid key").unwrap();

// =======
let (location, pubkey, key_type) = get_public_key_from_path(Some(arg_keypair.clone()));
let (location, pubkey, key_type, verified) =
get_public_key_from_path(&Some(arg_keypair.clone()));
assert_eq!(location, arg_keypair.display().to_string());
assert_eq!(pubkey, "decode error");
assert_eq!(key_type, "");
assert_eq!(verified, "");
}

#[test]
fn get_keypair_not_provided() {
let (location, pubkey, key_type) = get_public_key_from_path(None);
let (location, pubkey, key_type, verified) = get_public_key_from_path(&None);
assert_eq!(location, "unset");
assert_eq!(pubkey, "unset");
assert_eq!(key_type, "unset");
assert_eq!(verified, "unset");
}
}
6 changes: 3 additions & 3 deletions src/cmds/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,11 +191,11 @@ pub struct GetRoute {

#[derive(Debug, Args)]
pub struct NewRoute {
#[arg(long, env = ENV_NET_ID, default_value = "000024")]
#[arg(long, env = ENV_NET_ID)]
pub net_id: HexNetID,
#[arg(long, env = ENV_OUI)]
pub oui: Oui,
#[arg(long, env = ENV_MAX_COPIES, default_value = "5")]
#[arg(long, env = ENV_MAX_COPIES)]
pub max_copies: u32,

#[arg(from_global)]
Expand Down Expand Up @@ -952,7 +952,7 @@ pub trait PathBufKeypair {

impl PathBufKeypair for PathBuf {
fn to_keypair(&self) -> Result<helium_crypto::Keypair> {
let data = std::fs::read(self).context("reading keypair file")?;
let data = std::fs::read(&self).context("reading keypair file")?;
Ok(helium_crypto::Keypair::try_from(&data[..])?)
}
}
2 changes: 1 addition & 1 deletion tests/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub fn generate_keypair(path: PathBuf) -> Result<PublicKey> {
commit: true,
})?;
info!("generate_keypair: {out}");
let (_, public_key, _) = cmds::env::get_public_key_from_path(Some(path));
let (_, public_key, _, _) = cmds::env::get_public_key_from_path(&Some(path));
let public_key = PublicKey::from_str(&public_key)?;
Ok(public_key)
}
Expand Down