Skip to content

Commit

Permalink
wip: elementary files
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris Frantz committed Nov 21, 2024
1 parent 6f386ba commit f00b8d2
Show file tree
Hide file tree
Showing 12 changed files with 180 additions and 0 deletions.
2 changes: 2 additions & 0 deletions sw/host/hsmtool/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ rust_library(
"src/commands/object/destroy.rs",
"src/commands/object/list.rs",
"src/commands/object/mod.rs",
"src/commands/object/read.rs",
"src/commands/object/write.rs",
"src/commands/object/show.rs",
"src/commands/object/update.rs",
"src/commands/rsa/decrypt.rs",
Expand Down
1 change: 1 addition & 0 deletions sw/host/hsmtool/src/commands/ecdsa/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ impl Dispatch for Generate {
success: true,
id: id.clone(),
label: AttrData::Str(self.label.as_ref().cloned().unwrap_or_default()),
value: None,
error: None,
});

Expand Down
1 change: 1 addition & 0 deletions sw/host/hsmtool/src/commands/ecdsa/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ impl Dispatch for Import {
success: true,
id: id.clone(),
label: AttrData::Str(self.label.as_ref().cloned().unwrap_or_default()),
value: None,
error: None,
});
public_attrs.insert(AttributeType::Id, id.clone());
Expand Down
4 changes: 4 additions & 0 deletions sw/host/hsmtool/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ pub struct BasicResult {
#[serde(skip_serializing_if = "AttrData::is_none")]
label: AttrData,
#[serde(skip_serializing_if = "Option::is_none")]
value: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
}

Expand All @@ -111,6 +113,7 @@ impl Default for BasicResult {
success: true,
id: AttrData::None,
label: AttrData::None,
value: None,
error: None,
}
}
Expand All @@ -122,6 +125,7 @@ impl BasicResult {
success: false,
id: AttrData::None,
label: AttrData::None,
value: None,
error: Some(format!("{:?}", e)),
})
}
Expand Down
8 changes: 8 additions & 0 deletions sw/host/hsmtool/src/commands/object/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,19 @@ use crate::module::Module;

mod destroy;
mod list;
mod read;
mod show;
mod update;
mod write;

#[derive(clap::Subcommand, Debug, Serialize, Deserialize)]
pub enum Object {
Destroy(destroy::Destroy),
List(list::List),
Read(read::Read),
Show(show::Show),
Update(update::Update),
Write(write::Write),
}

#[typetag::serde(name = "__object__")]
Expand All @@ -35,8 +39,10 @@ impl Dispatch for Object {
match self {
Object::Destroy(x) => x.run(context, hsm, session),
Object::List(x) => x.run(context, hsm, session),
Object::Read(x) => x.run(context, hsm, session),
Object::Show(x) => x.run(context, hsm, session),
Object::Update(x) => x.run(context, hsm, session),
Object::Write(x) => x.run(context, hsm, session),
}
}
fn leaf(&self) -> &dyn Dispatch
Expand All @@ -46,8 +52,10 @@ impl Dispatch for Object {
match self {
Object::Destroy(x) => x.leaf(),
Object::List(x) => x.leaf(),
Object::Read(x) => x.leaf(),
Object::Show(x) => x.leaf(),
Object::Update(x) => x.leaf(),
Object::Write(x) => x.leaf(),
}
}
}
67 changes: 67 additions & 0 deletions sw/host/hsmtool/src/commands/object/read.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

use anyhow::Result;
use cryptoki::session::Session;
use serde::{Deserialize, Serialize};
use serde_annotate::Annotate;
use std::any::Any;
use std::collections::HashSet;
use std::path::PathBuf;

use crate::commands::{BasicResult, Dispatch};
use crate::error::HsmError;
use crate::module::Module;
use crate::util::attribute::{AttributeMap, AttributeType, AttributeError, AttrData};
use crate::util::helper;

#[derive(clap::Args, Debug, Serialize, Deserialize)]
pub struct Read {
#[arg(long)]
id: Option<String>,
#[arg(short, long)]
label: Option<String>,
/// Search spec
#[arg(short, long)]
spec: Option<AttributeMap>,
#[arg()]
output: PathBuf,
}

#[typetag::serde(name = "object-read")]
impl Dispatch for Read {
fn run(
&self,
_context: &dyn Any,
_hsm: &Module,
session: Option<&Session>,
) -> Result<Box<dyn Annotate>> {
let session = session.ok_or(HsmError::SessionRequired)?;
let mut attr = AttributeMap::default();
if let Some(id) = &self.id {
attr.insert(AttributeType::Id, AttrData::Str(id.into()));
}
if let Some(label) = &self.label {
attr.insert(AttributeType::Label, AttrData::Str(label.into()));
}
if attr.is_empty() {
return Err(HsmError::NoSearchCriteria.into());
}
if let Some(spec) = &self.spec {
attr.merge(spec.clone());
}
let attr = attr.to_vec()?;
let object = helper::find_one_object(session, &attr)?;
let map = AttributeMap::from_object(session, object)?;
let value = map.get(&AttributeType::Value).ok_or(AttributeError::AttributeNotFound(AttributeType::Value))?;
let value = Vec::<u8>::try_from(value)?;
let mut result = Box::<BasicResult>::default();
if self.output.to_str() == Some("-") {
result.value = Some(String::from_utf8(value)?);
} else {
std::fs::write(&self.output, value)?;
}
Ok(result)
}
}
91 changes: 91 additions & 0 deletions sw/host/hsmtool/src/commands/object/write.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

use anyhow::Result;
use cryptoki::session::Session;
use serde::{Deserialize, Serialize};
use serde_annotate::Annotate;
use std::any::Any;
use std::collections::HashSet;
use std::path::PathBuf;

use crate::commands::{BasicResult, Dispatch};
use crate::error::HsmError;
use crate::module::Module;
use crate::util::attribute::{AttributeMap, AttributeType, AttributeError, AttrData, ObjectClass};
use crate::util::helper;

use cryptoki_sys::*;

#[derive(clap::Args, Debug, Serialize, Deserialize)]
pub struct Write {
#[arg(long)]
id: Option<String>,
#[arg(short, long)]
label: Option<String>,
#[arg(short, long, default_value="false")]
private: bool,
#[arg(short, long)]
application: Option<String>,
#[arg(short, long)]
template: Option<AttributeMap>,
#[arg()]
input: PathBuf,
}

#[typetag::serde(name = "object-write")]
impl Dispatch for Write {
fn run(
&self,
_context: &dyn Any,
_hsm: &Module,
session: Option<&Session>,
) -> Result<Box<dyn Annotate>> {
let session = session.ok_or(HsmError::SessionRequired)?;

let mut attr = AttributeMap::default();
let id = self.id.as_ref().map_or(AttrData::None, |id| AttrData::Str(id.into()));
let label = self.label.as_ref().map_or(AttrData::None, |label| AttrData::Str(label.into()));
if !id.is_none() {
attr.insert(AttributeType::Id, id.clone());
}
if !label.is_none() {
attr.insert(AttributeType::Label, label.clone());
}
if id.is_none() && label.is_none() {
return Err(HsmError::NoSearchCriteria.into());
}

let result = Box::new(BasicResult {
success: true,
id,
label,
value: None,
error: None,
});

attr.insert(AttributeType::Class, AttrData::ObjectClass(ObjectClass::Data));
attr.insert(AttributeType::Token, AttrData::from(true));
attr.insert(AttributeType::Private, AttrData::from(self.private));
if let Some(application) = &self.application {
attr.insert(AttributeType::Application, AttrData::Str(application.into()));
}
if let Some(template) = &self.template {
attr.merge(template.clone());
}
let value = std::fs::read(&self.input)?;
attr.insert(AttributeType::Value, AttrData::from(value.as_slice()));
let attr = attr.to_vec()?;
for a in attr.iter() {
println!("a = {a:?}");
}
let mut template: Vec<CK_ATTRIBUTE> = attr.iter().map(|attr| attr.into()).collect();
for t in template.iter() {
println!("t = {:?} {:?} {:?}", t.type_, t.pValue, t.ulValueLen);
}

session.create_object(&attr)?;
Ok(result)
}
}
1 change: 1 addition & 0 deletions sw/host/hsmtool/src/commands/rsa/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ impl Dispatch for Generate {
success: true,
id: id.clone(),
label: AttrData::Str(self.label.as_ref().cloned().unwrap_or_default()),
value: None,
error: None,
});

Expand Down
1 change: 1 addition & 0 deletions sw/host/hsmtool/src/commands/rsa/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ impl Dispatch for Import {
success: true,
id: id.clone(),
label: AttrData::Str(self.label.as_ref().cloned().unwrap_or_default()),
value: None,
error: None,
});
public_attrs.insert(AttributeType::Id, id.clone());
Expand Down
1 change: 1 addition & 0 deletions sw/host/hsmtool/src/commands/spx/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ impl Dispatch for Generate {
success: true,
id: AttrData::Str(key.hash.expect("key hash")),
label: AttrData::Str(key.alias),
value: None,
error: None,
}))
}
Expand Down
1 change: 1 addition & 0 deletions sw/host/hsmtool/src/commands/spx/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ impl Dispatch for Import {
success: true,
id: AttrData::Str(key.hash.expect("key hash")),
label: AttrData::Str(key.alias),
value: None,
error: None,
}))
}
Expand Down
2 changes: 2 additions & 0 deletions sw/host/hsmtool/src/util/attribute/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ pub enum AttributeError {
UnknownAttribute(Attribute),
#[error("Unknown attribute type: {0:?}")]
UnknownAttributeType(AttributeType),
#[error("Attribute not found: {0:?}")]
AttributeNotFound(AttributeType),
}

0 comments on commit f00b8d2

Please sign in to comment.