tendermint / yubihsm-rs

Pure Rust client for YubiHSM2 devices
https://docs.rs/yubihsm/
70 stars 10 forks source link

Process stuck when putting wrap key #243

Closed marcelbuesing closed 4 years ago

marcelbuesing commented 4 years ago

Hi,

i'm trying to put a wrap key to the HSM but the process is stuck indefinitely. It never reaches

println!("labelXYZ: Created! Label: labelXYZ, ID: 0");

I also encounter this issue when using the http connector, so I am assuming this is somehow my mistake. Using the yubihsm-shell it works as described below.

use anyhow::Result;
use yubihsm::{capability::Capability, wrap, Client, Connector, Credentials, UsbConfig};

fn main() -> Result<()> {

    let usb_cfg = UsbConfig::default();
    let connector = Connector::usb(&usb_cfg);
    let credentials = Credentials::default();

    println!("HSM: Opening connection to HSM via USB");
    let hsm_client = Client::open(connector, credentials, true)?;
    println!("HSM: Connected to HSM");

    println!("HSM: Opening session using default password");
    let session_guard = hsm_client.session()?;
    println!("HSM: Session (id: {}) open", session_guard.id());

    println!("labelXYZ: Generating AES-256 random wrap key");
    let mut key_builder = wrap::Key::generate_random(0, wrap::Algorithm::Aes256Ccm);
    key_builder = key_builder.label("labelXYZ".into());
    key_builder = key_builder.capabilities(
        Capability::WRAP_DATA
            | Capability::UNWRAP_DATA
            | Capability::EXPORT_WRAPPED
            | Capability::IMPORT_WRAPPED,
    );
    println!("labelXYZ: Creating key within HSM");
    key_builder.create(&hsm_client)?;
    println!("labelXYZ: Created! Label: labelXYZ, ID: 0");
}

Output:

HSM: Opening connection to HSM via USB
HSM: Connected to HSM
HSM: Opening session using default password
HSM: Session (id: 0) open
labelXYZ: Generating AES-256 random wrap key
labelXYZ: Creating key within HSM

Using yubi-shell succeeds:

connect
session open 1 password
get random 0 32
put wrapkey 0 0 labelXYZ 1 wrap-data,unwrap-data export-wrapped,import-wrapped RANDOMOUTPUT
--> Stored Wrap key ...

Hardware: Yubihsm 2

tarcieri commented 4 years ago

I’m traveling at the moment and don’t have access to a YubiHSM2, however I’ll try your repro when I have time.

What OS are you running?

Can you try enabling debug logging? e.g. add env_logger and set RUST_LOG=debug

marcelbuesing commented 4 years ago

Thanks for replying even when you are on vacation. I found the issue: there is a deadlock due to the following line

let session_guard = hsm_client.session()?;

Replacing this with the following line fixes the issue.

let session_id = hsm_client.session()?.id();

The dead lock occurs because this line acquired the session mutex and then during the put_wrap_key fails to acquire the mutex here, blocking indefinitely.

Anyway, enjoy your vacation!