11 Commits
builder ... 2.1

13 changed files with 809 additions and 325 deletions

View File

@@ -1,12 +1,13 @@
[package] [package]
name = "ctap_hmac" name = "ctap_hmac"
description = "A Rust implementation of the FIDO2 CTAP protocol, including the HMAC extension" description = "A Rust implementation of the FIDO2 CTAP protocol, including the HMAC extension"
version = "0.2.1" version = "0.4.2"
license = "Apache-2.0/MIT" license = "Apache-2.0/MIT"
homepage = "https://github.com/ArdaXi/ctap/pull/2" homepage = "https://github.com/shimunn/ctap"
repository = "https://github.com/shimunn/ctap" repository = "https://github.com/shimunn/ctap"
authors = ["Arda Xi <arda@ardaxi.com>", "shimun <shimun@shimun.net>"] authors = ["Arda Xi <arda@ardaxi.com>", "shimun <shimun@shimun.net>"]
edition = "2018" edition = "2018"
readme = "README.md"
[dependencies] [dependencies]
rand = "0.6" rand = "0.6"
@@ -19,5 +20,12 @@ cbor-codec = "0.7"
ring = "0.13" ring = "0.13"
untrusted = "0.6" untrusted = "0.6"
rust-crypto = "0.2" rust-crypto = "0.2"
hex = "0.4.0"
csv-core = "0.1.6" csv-core = "0.1.6"
derive_builder = "0.9.0"
crossbeam = { version = "0.7.3", optional = true }
[dev-dependencies]
crossbeam = "0.7.3"
hex = "0.4.0"
[features]
request_multiple = ["crossbeam"]

View File

@@ -13,28 +13,28 @@ ctap is a library implementing the [FIDO2 CTAP](https://fidoalliance.org/specs/f
## Usage example ## Usage example
```rust ```rust
let devices = ctap::get_devices()?; use ctap_hmac::*;
let device_info = &devices[0]; let device_info = get_devices()?.next().expect("no device connected");
let mut device = ctap::FidoDevice::new(device_info)?; let mut device = FidoDevice::new(&device_info)?;
// This can be omitted if the FIDO device is not configured with a PIN. // This can be omitted if the FIDO device is not configured with a PIN.
let pin = "test"; let pin = "test";
device.unlock(pin)?; device.unlock(pin)?;
// In a real application these values would come from the requesting app. // In a real application these values would come from the requesting app.
let rp_id = "rp_id"; let cred_request = FidoCredentialRequestBuilder::default()
let user_id = [0]; .rp_id("rp_id")
let user_name = "user_name"; .user_name("user_name")
let client_data_hash = [0; 32]; .build().unwrap();
let cred = device.make_credential(
rp_id,
&user_id,
user_name,
&client_data_hash
)?;
let cred = device.make_credential(&cred_request)?;
let cred = &&cred;
let assertion_request = FidoAssertionRequestBuilder::default()
.rp_id("rp_id")
.credential(&&cred)
.build().unwrap();
// In a real application the credential would be stored and used later. // In a real application the credential would be stored and used later.
let result = device.get_assertion(&cred, &client_data_hash); let result = device.get_assertion(&assertion_request);
``` ```
## Limitations ## Limitations

View File

@@ -2,8 +2,8 @@ extern crate ctap_hmac as ctap;
use crypto::digest::Digest; use crypto::digest::Digest;
use crypto::sha2::Sha256; use crypto::sha2::Sha256;
use ctap::extensions::hmac::{FidoHmacCredential, HmacExtension}; use ctap::extensions::{self, FidoExtensionResponseParserExt};
use ctap_hmac::{AuthenticatorOptions, PublicKeyCredentialRpEntity, PublicKeyCredentialUserEntity}; use ctap::{FidoAssertionRequestBuilder, FidoCredential, FidoCredentialRequestBuilder};
use hex; use hex;
use std::env::args; use std::env::args;
use std::io::prelude::*; use std::io::prelude::*;
@@ -14,43 +14,39 @@ const RP_ID: &str = "ctap_demo";
fn main() -> ctap::FidoResult<()> { fn main() -> ctap::FidoResult<()> {
let mut devices = ctap::get_devices()?; let mut devices = ctap::get_devices()?;
let device_info = &mut devices.next().expect("No authenicator found"); let device_info = &mut devices.next().expect("No authenticator found");
let mut device = ctap::FidoDevice::new(device_info)?; let mut device = ctap::FidoDevice::new(device_info)?;
let options = || { let credential = match args().nth(1).map(|h| FidoCredential {
Some(AuthenticatorOptions {
uv: false,
rk: true,
})
};
let mut credential = match args().skip(1).next().map(|h| FidoHmacCredential {
id: hex::decode(&h).expect("Invalid credential"), id: hex::decode(&h).expect("Invalid credential"),
rp_id: RP_ID.into(), public_key: None,
}) { }) {
Some(cred) => cred, Some(cred) => cred,
_ => { _ => {
let rp = PublicKeyCredentialRpEntity { let mut req = FidoCredentialRequestBuilder::default()
id: RP_ID, .rp_id(RP_ID)
name: Some("ctap_hmac crate"), .rp_name("ctap_hmac crate")
icon: None, .user_name("example")
}; .uv(false)
let user = PublicKeyCredentialUserEntity { .build()
id: &[0u8], .unwrap();
name: "commandline",
icon: None,
display_name: None,
};
assert!(
&device.supports_extension::<extensions::HmacSecret>(),
"Your device does not support the hmac extension"
);
let hmac = extensions::HmacSecret::new();
req.with_extension(&hmac)?;
dbg!(&req);
println!("Authorize using your device"); println!("Authorize using your device");
let credential: FidoHmacCredential = device let cred = req
.make_hmac_credential_full(rp, user, &[0u8; 32], &[], options()) .make_credential(&mut device)
.map(|cred| cred.into())?; .expect("Failed to request credential");
println!("Credential: {}\nNote: You can pass this credential as first argument in order to reproduce results", hex::encode(&credential.id)); println!("Credential: {}\nNote: You can pass this credential as first argument in order to reproduce results", hex::encode(&cred.id));
credential cred
} }
}; };
let credential = credential;
print!("Type in your message: "); print!("Type in your message: ");
stdout().flush(); stdout().flush().unwrap();
let mut message = String::new(); let mut message = String::new();
stdin() stdin()
.read_line(&mut message) .read_line(&mut message)
@@ -61,14 +57,16 @@ fn main() -> ctap::FidoResult<()> {
let mut digest = Sha256::new(); let mut digest = Sha256::new();
digest.input(&message.as_bytes()); digest.input(&message.as_bytes());
digest.result(&mut salt); digest.result(&mut salt);
let hash = device let credential = &&credential;
.get_hmac_assertion( let hmac = extensions::HmacSecret::new().for_device(&mut device, &salt, None)?;
&credential, let mut request = FidoAssertionRequestBuilder::default()
&salt, .rp_id(RP_ID)
None, .credential(credential)
None, .build()
)? .unwrap();
.0; request.with_extension(&hmac)?;
println!("Hash: {}", hex::encode(&hash)); let (_cred, auth_data) = device.get_assertion(&request)?;
let (hash1, _hash2) = auth_data.parse_extension_data(&hmac)?;
println!("Hash: {}", hex::encode(&hash1));
Ok(()) Ok(())
} }

48
examples/multiple.rs Normal file
View File

@@ -0,0 +1,48 @@
extern crate ctap_hmac as ctap;
use ctap::{
FidoAssertionRequestBuilder, FidoCredential, FidoCredentialRequestBuilder, FidoDevice,
FidoResult,
};
use hex;
use std::env::args;
use std::time::Duration;
const RP_ID: &str = "ctap_demo";
fn main() -> ctap::FidoResult<()> {
let mut credentials = args()
.skip(1)
.map(|id| FidoCredential {
id: hex::decode(&id).expect("Invalid credential"),
public_key: None,
})
.collect::<Vec<_>>();
if credentials.len() == 0 {
credentials = ctap::get_devices()?
.map(|h| {
FidoDevice::new(&h).and_then(|mut dev| {
FidoCredentialRequestBuilder::default()
.rp_id(RP_ID)
.build()
.unwrap()
.make_credential(&mut dev)
})
})
.collect::<FidoResult<Vec<FidoCredential>>>()?;
}
let credentials = credentials.iter().collect::<Vec<_>>();
let req = FidoAssertionRequestBuilder::default()
.rp_id(RP_ID)
.credentials(&credentials[..])
.build()
.unwrap();
let mut devices = ctap::get_devices()?
.map(|handle| FidoDevice::new(&handle))
.collect::<FidoResult<Vec<_>>>()?;
// run with --features request_multiple
let (cred, _) =
ctap::get_assertion_devices(&req, devices.iter_mut(), Some(Duration::from_secs(10)))?;
println!("Success, got assertion for: {}", hex::encode(&cred.id));
Ok(())
}

View File

@@ -274,6 +274,12 @@ pub struct GetInfoResponse {
pub options: OptionsInfo, pub options: OptionsInfo,
pub max_msg_size: u16, pub max_msg_size: u16,
pub pin_protocols: Vec<u8>, pub pin_protocols: Vec<u8>,
pub max_credential_count_in_list: Option<u32>,
pub max_credential_id_len: Option<u32>,
pub transports: Vec<String>,
pub algorithms: Vec<CoseKey>,
pub max_authenticator_config_len: Option<u32>,
pub default_cred_protect: Option<u8>,
} }
impl GetInfoResponse { impl GetInfoResponse {
@@ -282,28 +288,49 @@ impl GetInfoResponse {
if status != 0 { if status != 0 {
Err(FidoErrorKind::CborError(CborErrorCode::from(status)))? Err(FidoErrorKind::CborError(CborErrorCode::from(status)))?
} }
let mut decoder = Decoder::new(Config::default(), reader); let mut generic = GenericDecoder::new(Config::default(), reader);
let mut response = GetInfoResponse::default(); let mut response = GetInfoResponse::default();
for _ in 0..decoder.object()? { for _ in 0..generic.borrow_mut().object()? {
match decoder.u8()? { match generic.borrow_mut().u8()? {
0x01 => { 0x01 => {
let decoder = generic.borrow_mut();
for _ in 0..decoder.array()? { for _ in 0..decoder.array()? {
response.versions.push(decoder.text()?); response.versions.push(decoder.text()?);
} }
} }
0x02 => { 0x02 => {
let decoder = generic.borrow_mut();
for _ in 0..decoder.array()? { for _ in 0..decoder.array()? {
response.extensions.push(decoder.text()?); response.extensions.push(decoder.text()?);
} }
} }
0x03 => response.aaguid.copy_from_slice(&decoder.bytes()?[..]), 0x03 => response
0x04 => response.options = OptionsInfo::decode(&mut decoder)?, .aaguid
0x05 => response.max_msg_size = decoder.u16()?, .copy_from_slice(&generic.borrow_mut().bytes()?[..]),
0x04 => response.options = OptionsInfo::decode(&mut generic.borrow_mut())?,
0x05 => response.max_msg_size = generic.borrow_mut().u16()?,
0x06 => { 0x06 => {
let decoder = generic.borrow_mut();
for _ in 0..decoder.array()? { for _ in 0..decoder.array()? {
response.pin_protocols.push(decoder.u8()?); response.pin_protocols.push(decoder.u8()?);
} }
} }
0x07 => response.max_credential_count_in_list = Some(generic.borrow_mut().u32()?),
0x08 => response.max_credential_id_len = Some(generic.borrow_mut().u32()?),
0x09 => {
let decoder = generic.borrow_mut();
for _ in 0..decoder.array()? {
response.transports.push(decoder.text()?);
}
}
0x0A => {
for _ in 0..generic.borrow_mut().array()? {
response.algorithms.push(CoseKey::decode(&mut generic)?);
}
}
0x0B => response.max_authenticator_config_len = Some(generic.borrow_mut().u32()?),
0x0C => response.default_cred_protect = Some(generic.borrow_mut().u8()?),
_ => continue, _ => continue,
} }
} }
@@ -423,7 +450,9 @@ impl OptionsInfo {
"clientPin" => options.client_pin = Some(decoder.bool()?), "clientPin" => options.client_pin = Some(decoder.bool()?),
"up" => options.up = decoder.bool()?, "up" => options.up = decoder.bool()?,
"uv" => options.uv = Some(decoder.bool()?), "uv" => options.uv = Some(decoder.bool()?),
_ => continue, _ => {
decoder.bool()?;
}
} }
} }
Ok(options) Ok(options)
@@ -563,7 +592,7 @@ impl P256Key {
} }
} }
#[derive(Debug, Default)] #[derive(Debug, Default, Clone)]
pub struct CoseKey { pub struct CoseKey {
key_type: u16, key_type: u16,
algorithm: i32, algorithm: i32,
@@ -700,15 +729,16 @@ impl PublicKeyCredentialDescriptor {
pub struct AuthenticatorOptions { pub struct AuthenticatorOptions {
pub rk: bool, pub rk: bool,
pub uv: bool, pub uv: bool,
pub up: bool,
} }
impl AuthenticatorOptions { impl AuthenticatorOptions {
pub fn encoded(&self) -> bool { pub fn encoded(&self) -> bool {
self.rk || self.uv self.rk || self.uv || self.up
} }
pub fn encode<W: WriteBytesExt>(&self, encoder: &mut Encoder<W>) -> FidoResult<()> { pub fn encode<W: WriteBytesExt>(&self, encoder: &mut Encoder<W>) -> FidoResult<()> {
let length = (self.rk as usize) + (self.uv as usize); let length = (self.rk as usize) + (self.uv as usize) + (self.up as usize);
encoder.object(length)?; encoder.object(length)?;
if self.rk { if self.rk {
encoder.text("rk")?; encoder.text("rk")?;
@@ -718,6 +748,10 @@ impl AuthenticatorOptions {
encoder.text("uv")?; encoder.text("uv")?;
encoder.bool(true)?; encoder.bool(true)?;
} }
if self.up {
encoder.text("up")?;
encoder.bool(true)?;
}
Ok(()) Ok(())
} }
} }

View File

@@ -15,7 +15,7 @@ use rust_crypto::buffer::{RefReadBuffer, RefWriteBuffer};
use rust_crypto::symmetriccipher::{Decryptor, Encryptor}; use rust_crypto::symmetriccipher::{Decryptor, Encryptor};
use untrusted::Input; use untrusted::Input;
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct SharedSecret { pub struct SharedSecret {
pub public_key: CoseKey, pub public_key: CoseKey,
pub shared_secret: [u8; 32], pub shared_secret: [u8; 32],

View File

@@ -23,6 +23,8 @@ pub struct CborErrorCode(u8);
pub enum FidoErrorKind { pub enum FidoErrorKind {
#[fail(display = "Read/write error with device.")] #[fail(display = "Read/write error with device.")]
Io, Io,
#[fail(display = "Operation timed out")]
Timeout,
#[fail(display = "Error while reading packet from device.")] #[fail(display = "Error while reading packet from device.")]
ReadPacket, ReadPacket,
#[fail(display = "Error while writing packet to device.")] #[fail(display = "Error while writing packet to device.")]
@@ -45,7 +47,9 @@ pub enum FidoErrorKind {
EncryptPin, EncryptPin,
#[fail(display = "Failed to decrypt PIN.")] #[fail(display = "Failed to decrypt PIN.")]
DecryptPin, DecryptPin,
#[fail(display = "Supplied key has incorrect type.")] #[fail(display = "Failed to verify response signature.")]
VerifySignature,
#[fail(display = "Failed to verify response signature.")]
KeyType, KeyType,
#[fail(display = "Device returned error: {}", _0)] #[fail(display = "Device returned error: {}", _0)]
CborError(CborErrorCode), CborError(CborErrorCode),

View File

@@ -0,0 +1,57 @@
use crate::extensions::FidoExtension;
use crate::FidoResult;
use crate::{FidoAssertionRequest, FidoCredentialRequest};
use cbor_codec::value::Value;
use num_traits::ToPrimitive;
#[derive(Copy, Clone, Debug, FromPrimitive, ToPrimitive, PartialEq)]
pub enum CredProtectLevel {
UvOptional = 0x01,
UvOptionalWithCredentialIDList = 0x02,
UvRequired = 0x03,
}
impl CredProtectLevel {
fn extension_input(self) -> Value {
Value::U8(self.to_u8().unwrap())
}
}
pub struct CredProtect(Value);
impl CredProtect {
pub fn level(level: CredProtectLevel) -> Self {
Self(level.extension_input())
}
fn extension_name() -> &'static str {
"credProtect"
}
fn extension_input(&self) -> &Value {
&self.0
}
}
impl FidoExtension for CredProtect {
fn extension_name() -> &'static str {
CredProtect::extension_name()
}
fn patch_assertion_request<'a, 'b>(
&'b self,
_request: &mut FidoAssertionRequest<'a, 'b>,
) -> FidoResult<()> {
Ok(())
}
fn patch_credential_request<'a>(
&'a self,
request: &mut FidoCredentialRequest<'a>,
) -> FidoResult<()> {
request
.extension_data
.insert(CredProtect::extension_name(), self.extension_input());
Ok(())
}
}

View File

@@ -1,10 +1,14 @@
use crate::{ use crate::cbor::AuthenticatorData;
cbor, AuthenticatorOptions, PublicKeyCredentialRpEntity, PublicKeyCredentialUserEntity, use crate::crypto::SharedSecret;
use crate::extensions::{
FidoExtension, FidoExtensionResponseParser, FidoExtensionResponseParserExt,
}; };
use crate::{FidoAssertionRequest, FidoAssertionRequestBuilder, FidoCredentialRequest};
use crate::{FidoCredential, FidoDevice, FidoErrorKind, FidoResult}; use crate::{FidoCredential, FidoDevice, FidoErrorKind, FidoResult};
use cbor_codec::value::{Bytes, Int, Key, Text, Value}; use cbor_codec::value::{Bytes, Int, Key, Text, Value};
use cbor_codec::Encoder; use cbor_codec::Encoder;
use cbor_codec::{Config, GenericDecoder}; use cbor_codec::{Config, GenericDecoder};
use failure::ResultExt;
use rust_crypto::buffer::{RefReadBuffer, RefWriteBuffer}; use rust_crypto::buffer::{RefReadBuffer, RefWriteBuffer};
use rust_crypto::digest::Digest; use rust_crypto::digest::Digest;
use rust_crypto::hmac::Hmac; use rust_crypto::hmac::Hmac;
@@ -13,21 +17,10 @@ use rust_crypto::sha2::Sha256;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::io::Cursor; use std::io::Cursor;
#[derive(Debug, Clone)] #[deprecated(
pub struct FidoHmacCredential { since = "0.4.2",
pub id: Vec<u8>, note = "Please use FidoAssertionRequest::with_extension(HmacSecret) instead"
pub rp_id: String, )]
}
impl From<FidoCredential> for FidoHmacCredential {
fn from(cred: FidoCredential) -> Self {
FidoHmacCredential {
id: cred.id,
rp_id: cred.rp_id,
}
}
}
pub trait HmacExtension { pub trait HmacExtension {
fn extension_name() -> &'static str { fn extension_name() -> &'static str {
"hmac-secret" "hmac-secret"
@@ -51,17 +44,11 @@ pub trait HmacExtension {
fn get_data(&mut self, salt: &[u8; 32], salt2: Option<&[u8; 32]>) -> FidoResult<Value>; fn get_data(&mut self, salt: &[u8; 32], salt2: Option<&[u8; 32]>) -> FidoResult<Value>;
/// Convenience function to create an credential with default rp_id and user_name /// Convenience function to create an credential which includes extension specific data
/// Use `FidoDevice::make_credential` if you need more control /// Use `FidoDevice::make_credential` if you need more control
fn make_hmac_credential(&mut self) -> FidoResult<FidoHmacCredential>; fn make_hmac_credential(
fn make_hmac_credential_full(
&mut self, &mut self,
rp: cbor::PublicKeyCredentialRpEntity, request: &FidoCredentialRequest,
user: cbor::PublicKeyCredentialUserEntity,
client_data_hash: &[u8],
exclude_list: &[cbor::PublicKeyCredentialDescriptor],
options: Option<cbor::AuthenticatorOptions>,
) -> FidoResult<FidoCredential>; ) -> FidoResult<FidoCredential>;
/// Request an assertion from the authenticator for a given credential and salt(s). /// Request an assertion from the authenticator for a given credential and salt(s).
@@ -74,19 +61,19 @@ pub trait HmacExtension {
/// provided, and will fail if a PIN is required but not provided or if the /// provided, and will fail if a PIN is required but not provided or if the
/// device returns malformed data. /// device returns malformed data.
/// ///
fn get_hmac_assertion( fn get_hmac_assertion<'a: 'b, 'b>(
&mut self, &mut self,
credential: &FidoHmacCredential, assertion: &FidoAssertionRequest<'a, 'b>,
salt: &[u8; 32], salt: &[u8; 32],
salt2: Option<&[u8; 32]>, salt2: Option<&[u8; 32]>,
options: Option<AuthenticatorOptions>, ) -> FidoResult<(&'a FidoCredential, ([u8; 32], Option<[u8; 32]>))>;
) -> FidoResult<([u8; 32], Option<[u8; 32]>)>;
/// Convenience function for `get_hmac_assertion` that will accept arbitrary /// Convenience function for `get_hmac_assertion` that will accept arbitrary
/// lenght input which will then be hashed and passed on /// lenght input which will then be hashed and passed on
fn hmac_challange( fn hmac_challange(
&mut self, &mut self,
credential: &FidoHmacCredential, rp_id: &str,
credential: &FidoCredential,
input: &[u8], input: &[u8],
) -> FidoResult<[u8; 32]> { ) -> FidoResult<[u8; 32]> {
let mut salt = [0u8; 32]; let mut salt = [0u8; 32];
@@ -94,18 +81,87 @@ pub trait HmacExtension {
digest.input(input); digest.input(input);
digest.result(&mut salt); digest.result(&mut salt);
self.get_hmac_assertion( self.get_hmac_assertion(
credential, &FidoAssertionRequestBuilder::default()
.rp_id(rp_id)
.credential(&credential)
.build()
.unwrap(),
&salt, &salt,
None, None,
Some(AuthenticatorOptions { uv: true, rk: true }),
) )
.map(|secret| secret.0) .map(|(_cred, secret)| secret.0)
} }
} }
#[allow(deprecated)]
impl HmacExtension for FidoDevice { impl HmacExtension for FidoDevice {
fn get_data(&mut self, salt: &[u8; 32], salt2: Option<&[u8; 32]>) -> FidoResult<Value> { fn get_data(&mut self, salt: &[u8; 32], salt2: Option<&[u8; 32]>) -> FidoResult<Value> {
let shared_secret = self.shared_secret.as_ref().unwrap(); Ok(HmacSecret::extension_input(self, salt, salt2)?)
}
fn make_hmac_credential(
&mut self,
request: &FidoCredentialRequest,
) -> FidoResult<FidoCredential> {
let mut request = request.clone();
request.rk = true;
request.extension_data.insert(
<Self as HmacExtension>::extension_name(),
<Self as HmacExtension>::extension_input(),
);
self.make_credential(&request)
}
fn get_hmac_assertion<'a: 'b, 'b>(
&mut self,
request: &FidoAssertionRequest<'a, 'b>,
salt: &[u8; 32],
salt2: Option<&[u8; 32]>,
) -> FidoResult<(&'a FidoCredential, ([u8; 32], Option<[u8; 32]>))> {
while self.shared_secret.is_none() {
self.init_shared_secret()?;
}
let mut request = request.clone();
let ext = HmacSecret::new().for_device(self, salt, salt2)?;
request.with_extension(&ext)?;
let (cred, auth_data) = self.get_assertion(&request)?;
let cred = request
.credentials
.iter()
.find(|c| c.id == cred.id)
.unwrap();
Ok((cred, auth_data.parse_extension_data(&ext)?))
}
}
#[derive(Debug, Clone)]
pub enum HmacSecret {
Assertion {
extension_data: Value,
shared_secret: SharedSecret,
salt2: bool,
},
Credential,
}
impl HmacSecret {
pub fn new() -> Self {
Self::Credential
}
fn extension_input(
device: &mut FidoDevice,
salt: &[u8; 32],
salt2: Option<&[u8; 32]>,
) -> FidoResult<Value> {
let shared_secret = loop {
if let Some(ref secret) = device.shared_secret {
break secret;
}
device.init_shared_secret()?;
};
let mut encryptor = shared_secret.encryptor(); let mut encryptor = shared_secret.encryptor();
let mut salt_enc = [0u8; 64]; let mut salt_enc = [0u8; 64];
let mut output = RefWriteBuffer::new(&mut salt_enc); let mut output = RefWriteBuffer::new(&mut salt_enc);
@@ -133,7 +189,7 @@ impl HmacExtension for FidoDevice {
let mut map = BTreeMap::new(); let mut map = BTreeMap::new();
map.insert( map.insert(
Key::Int(Int::from_i64(0x01)), Key::Int(Int::from_i64(0x01)),
key_agreement().map_err(|_| FidoErrorKind::Io)?, key_agreement().context(FidoErrorKind::Io)?,
); );
map.insert( map.insert(
Key::Int(Int::from_i64(0x02)), Key::Int(Int::from_i64(0x02)),
@@ -156,96 +212,67 @@ impl HmacExtension for FidoDevice {
Ok(Value::Map(map)) Ok(Value::Map(map))
} }
fn make_hmac_credential(&mut self) -> FidoResult<FidoHmacCredential> { pub fn for_device(
let rp = PublicKeyCredentialRpEntity {
id: "hmac",
name: None,
icon: None,
};
let user = PublicKeyCredentialUserEntity {
id: &[0u8],
name: "commandline",
icon: None,
display_name: None,
};
let options = Some(AuthenticatorOptions {
uv: true,
rk: false,
});
self.make_hmac_credential_full(rp, user, &[0u8; 32], &[], options)
.map(|cred| cred.into())
}
fn make_hmac_credential_full(
&mut self, &mut self,
rp: cbor::PublicKeyCredentialRpEntity, device: &mut FidoDevice,
user: cbor::PublicKeyCredentialUserEntity,
client_data_hash: &[u8],
exclude_list: &[cbor::PublicKeyCredentialDescriptor],
options: Option<cbor::AuthenticatorOptions>,
) -> FidoResult<FidoCredential> {
self.make_credential_full(
rp,
user,
client_data_hash,
exclude_list,
&[(
<Self as HmacExtension>::extension_name(),
<Self as HmacExtension>::extension_input(),
)],
options,
)
}
fn get_hmac_assertion(
&mut self,
credential: &FidoHmacCredential,
salt: &[u8; 32], salt: &[u8; 32],
salt2: Option<&[u8; 32]>, salt2: Option<&[u8; 32]>,
options: Option<AuthenticatorOptions>, ) -> FidoResult<Self> {
) -> FidoResult<([u8; 32], Option<[u8; 32]>)> { Ok(Self::Assertion {
let client_data_hash = [0u8; 32]; extension_data: Self::extension_input(device, salt, salt2)?,
while self.shared_secret.is_none() { shared_secret: device.shared_secret.as_ref().unwrap().clone(),
self.init_shared_secret()?; salt2: salt2.is_some(),
})
} }
if self.needs_pin && self.pin_token.is_none() {
Err(FidoErrorKind::PinRequired)?
} }
if client_data_hash.len() != 32 { impl FidoExtension for HmacSecret {
Err(FidoErrorKind::CborEncode)? fn extension_name() -> &'static str {
"hmac-secret"
} }
let pin_auth = self
.pin_token fn patch_assertion_request<'a, 'b>(
.as_ref() &'b self,
.map(|token| token.auth(&client_data_hash)); request: &mut FidoAssertionRequest<'a, 'b>,
let ext_data: Value = self.get_data(salt, salt2)?; ) -> FidoResult<()> {
let allow_list = [cbor::PublicKeyCredentialDescriptor { match self {
cred_type: String::from("public-key"), Self::Assertion { extension_data, .. } => request
id: credential.id.clone(), .extension_data
}]; .insert(Self::extension_name(), extension_data),
let request = cbor::GetAssertionRequest { _ => return Err(FidoErrorKind::DeviceUnsupported.into()),
rp_id: &credential.rp_id,
client_data_hash: &client_data_hash,
allow_list: &allow_list,
extensions: &[(<Self as HmacExtension>::extension_name(), &ext_data)],
options: options,
pin_auth,
pin_protocol: pin_auth.and(Some(0x01)),
}; };
let response = match self.cbor(cbor::Request::GetAssertion(request))? { Ok(())
cbor::Response::GetAssertion(resp) => resp, }
_ => Err(FidoErrorKind::CborDecode)?,
fn patch_credential_request<'a>(
&'a self,
request: &mut FidoCredentialRequest<'a>,
) -> FidoResult<()> {
request
.extension_data
.insert(Self::extension_name(), &Value::Bool(true));
Ok(())
}
}
impl FidoExtensionResponseParser for HmacSecret {
type Output = ([u8; 32], Option<[u8; 32]>);
fn parse_response(&self, response: &AuthenticatorData) -> FidoResult<Self::Output> {
let (shared_secret, salt2) = match self {
Self::Assertion {
shared_secret,
salt2,
..
} => (shared_secret, salt2),
_ => return Err(FidoErrorKind::DeviceUnsupported.into()),
}; };
let shared_secret = self.shared_secret.as_ref().unwrap();
let mut decryptor = shared_secret.decryptor(); let mut decryptor = shared_secret.decryptor();
let mut hmac_secret_combined = [0u8; 64]; let mut hmac_secret_combined = [0u8; 64];
let _output = RefWriteBuffer::new(&mut hmac_secret_combined); let _output = RefWriteBuffer::new(&mut hmac_secret_combined);
let hmac_secret_enc = match response let hmac_secret_enc = match response
.auth_data
.extensions .extensions
.get(<Self as HmacExtension>::extension_name()) .get(Self::extension_name())
.ok_or(FidoErrorKind::CborDecode)? .ok_or(FidoErrorKind::CborDecode)?
{ {
Value::Bytes(hmac_ciphered) => Ok(match hmac_ciphered { Value::Bytes(hmac_ciphered) => Ok(match hmac_ciphered {
@@ -270,6 +297,6 @@ impl HmacExtension for FidoDevice {
let mut hmac_secret_1 = [0u8; 32]; let mut hmac_secret_1 = [0u8; 32];
hmac_secret_0.copy_from_slice(&hmac_secret[0..32]); hmac_secret_0.copy_from_slice(&hmac_secret[0..32]);
hmac_secret_1.copy_from_slice(&hmac_secret[32..]); hmac_secret_1.copy_from_slice(&hmac_secret[32..]);
Ok((hmac_secret_0, salt2.map(|_| hmac_secret_1))) Ok((hmac_secret_0, Some(hmac_secret_1).filter(|_| *salt2)))
} }
} }

View File

@@ -1,2 +1,36 @@
pub mod hmac; pub mod hmac;
pub use hmac::*; pub use hmac::*;
mod cred_protect;
use crate::cbor::AuthenticatorData;
use crate::{FidoAssertionRequest, FidoCredentialRequest, FidoResult};
pub use cred_protect::*;
pub trait FidoExtension {
fn extension_name() -> &'static str;
fn patch_assertion_request<'a, 'b>(
&'b self,
request: &mut FidoAssertionRequest<'a, 'b>,
) -> FidoResult<()>;
fn patch_credential_request<'a>(
&'a self,
request: &mut FidoCredentialRequest<'a>,
) -> FidoResult<()>;
}
pub trait FidoExtensionResponseParser {
type Output;
fn parse_response(&self, response: &AuthenticatorData) -> FidoResult<Self::Output>;
}
pub trait FidoExtensionResponseParserExt<Ext: FidoExtensionResponseParser> {
fn parse_extension_data(&self, extension: &Ext) -> FidoResult<Ext::Output>;
}
impl<Ext: FidoExtensionResponseParser> FidoExtensionResponseParserExt<Ext> for AuthenticatorData {
fn parse_extension_data(
&self,
extension: &Ext,
) -> FidoResult<<Ext as FidoExtensionResponseParser>::Output> {
extension.parse_response(self)
}
}

View File

@@ -9,29 +9,31 @@
//! # Example //! # Example
//! //!
//! ``` //! ```
//! # fn do_fido() -> ctap::FidoResult<()> { //! # use ctap_hmac::*;
//! let mut devices = ctap::get_devices()?; //! # fn do_fido() -> FidoResult<()> {
//! let device_info = &devices.next().unwrap(); //!
//! let mut device = ctap::FidoDevice::new(device_info)?; //!use ctap_hmac::*;
//!let device_info = get_devices()?.next().expect("no device connected");
//!let mut device = FidoDevice::new(&device_info)?;
//! //!
//!// This can be omitted if the FIDO device is not configured with a PIN. //!// This can be omitted if the FIDO device is not configured with a PIN.
//!let pin = "test"; //!let pin = "test";
//!device.unlock(pin)?; //!device.unlock(pin)?;
//! //!
//!// In a real application these values would come from the requesting app. //!// In a real application these values would come from the requesting app.
//! let rp_id = "rp_id"; //!let cred_request = FidoCredentialRequestBuilder::default()
//! let user_id = [0]; //! .rp_id("rp_id")
//! let user_name = "user_name"; //! .user_name("user_name")
//! let client_data_hash = [0; 32]; //! .build().unwrap();
//! let cred = device.make_credential( //!let cred = device.make_credential(&cred_request)?;
//! rp_id, //!let cred = &&cred;
//! &user_id, //!let assertion_request = FidoAssertionRequestBuilder::default()
//! user_name, //! .rp_id("rp_id")
//! &client_data_hash //! .credential(cred)
//! )?; //! .build().unwrap();
//!
//!// In a real application the credential would be stored and used later. //!// In a real application the credential would be stored and used later.
//! let result = device.get_assertion(&cred, &client_data_hash); //!let result = device.get_assertion(&assertion_request);
//!
//! # Ok(()) //! # Ok(())
//! # } //! # }
@@ -43,6 +45,8 @@ extern crate rand;
extern crate failure_derive; extern crate failure_derive;
#[macro_use] #[macro_use]
extern crate num_derive; extern crate num_derive;
#[macro_use]
extern crate derive_builder;
extern crate byteorder; extern crate byteorder;
extern crate cbor as cbor_codec; extern crate cbor as cbor_codec;
extern crate crypto as rust_crypto; extern crate crypto as rust_crypto;
@@ -57,6 +61,7 @@ pub mod extensions;
mod hid_common; mod hid_common;
mod hid_linux; mod hid_linux;
mod packet; mod packet;
mod util;
use std::cmp; use std::cmp;
use std::fs; use std::fs;
@@ -64,16 +69,18 @@ use std::io::{Cursor, Write};
use std::u16; use std::u16;
use std::u8; use std::u8;
pub use self::cbor::{ use self::cbor::{AuthenticatorOptions, PublicKeyCredentialDescriptor};
AuthenticatorOptions, PublicKeyCredentialDescriptor, PublicKeyCredentialRpEntity,
PublicKeyCredentialUserEntity,
};
pub use self::error::*; pub use self::error::*;
use self::hid_linux as hid; use self::hid_linux as hid;
use self::packet::CtapCommand; use self::packet::CtapCommand;
pub use self::util::*;
use crate::cbor::{AuthenticatorData, GetAssertionRequest, GetInfoResponse};
use crate::packet::CtapStatus;
use crate::extensions::FidoExtension;
use failure::{Fail, ResultExt}; use failure::{Fail, ResultExt};
use num_traits::FromPrimitive; use num_traits::FromPrimitive;
use rand::prelude::*; use rand::prelude::*;
use std::collections::BTreeMap;
static BROADCAST_CID: [u8; 4] = [0xff, 0xff, 0xff, 0xff]; static BROADCAST_CID: [u8; 4] = [0xff, 0xff, 0xff, 0xff];
@@ -86,16 +93,13 @@ pub fn get_devices() -> FidoResult<impl Iterator<Item = hid::DeviceInfo>> {
} }
/// A credential created by a FIDO2 authenticator. /// A credential created by a FIDO2 authenticator.
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct FidoCredential { pub struct FidoCredential {
/// The ID provided by the authenticator. /// The ID provided by the authenticator.
pub id: Vec<u8>, pub id: Vec<u8>,
/// The public key provided by the authenticator, in uncompressed form. /// The public key provided by the authenticator, in uncompressed form.
pub public_key: Vec<u8>, pub public_key: Option<Vec<u8>>,
/// The Relying Party ID provided by the platform when this key was generated.
pub rp_id: String,
} }
/// An opened FIDO authenticator. /// An opened FIDO authenticator.
pub struct FidoDevice { pub struct FidoDevice {
device: fs::File, device: fs::File,
@@ -105,6 +109,154 @@ pub struct FidoDevice {
shared_secret: Option<crypto::SharedSecret>, shared_secret: Option<crypto::SharedSecret>,
pin_token: Option<crypto::PinToken>, pin_token: Option<crypto::PinToken>,
aaguid: [u8; 16], aaguid: [u8; 16],
info: GetInfoResponse,
}
pub struct FidoCancelHandle {
device: fs::File,
packet_size: u16,
channel_id: [u8; 4],
}
impl FidoCancelHandle {
pub fn cancel(&mut self) -> FidoResult<()> {
let payload = &[];
let to_send = payload.len() as u16;
let max_payload = (self.packet_size - 7) as usize;
let (frame, payload) = payload.split_at(cmp::min(payload.len(), max_payload));
packet::write_init_packet(
&mut self.device,
64,
&self.channel_id,
&CtapCommand::Cancel,
to_send,
frame,
)?;
if payload.is_empty() {
return Ok(());
}
let max_payload = (self.packet_size - 5) as usize;
for (seq, frame) in (0..u8::MAX).zip(payload.chunks(max_payload)) {
packet::write_cont_packet(&mut self.device, 64, &self.channel_id, seq, frame)?;
}
self.device.flush().context(FidoErrorKind::WritePacket)?;
Ok(())
}
pub fn cancel_after<T>(&mut self, body: impl Fn(()) -> T) -> FidoResult<T> {
let res = body(());
match self.cancel() {
Ok(_) => Ok(res),
Err(e) => Err(e),
}
}
}
/// Request a new credential from the authenticator. The `rp_id` should be
/// a stable string used to identify the party for whom the credential is
/// created, for convenience it will be returned with the credential.
/// `user_id` and `user_name` are not required when requesting attestations
/// but they MAY be displayed to the user and MAY be stored on the device
/// to be returned with an attestation if the device supports this.
/// `client_data_hash` SHOULD be a SHA256 hash of provided `client_data`,
/// this is only used to verify the attestation provided by the
/// authenticator. When not implementing WebAuthN this can be any random
/// 32-byte array.
///
/// This method will fail if a PIN is required but the device is not
/// unlocked or if the device returns malformed data.
#[derive(Clone, Debug, Builder)]
#[builder(setter(into))]
#[builder(pattern = "owned")]
pub struct FidoCredentialRequest<'a> {
/// create resident key
#[builder(default)]
rk: bool,
/// user verification
#[builder(default)]
uv: bool,
/// relying party id
rp_id: &'a str,
/// relying party id
#[builder(default)]
rp_name: Option<&'a str>,
/// relying party icon url
#[builder(default)]
rp_icon_url: Option<&'a str>,
/// user id
#[builder(default = "&[0u8]")]
user_id: &'a [u8],
/// user name
#[builder(default)]
user_name: Option<&'a str>,
/// user icon url
#[builder(default)]
user_icon_url: Option<&'a str>,
/// user display name
#[builder(default)]
user_display_name: Option<&'a str>,
#[builder(default = "&[]")]
exclude_list: &'a [&'a FidoCredential],
#[builder(default = "&[0u8; 32]")]
client_data_hash: &'a [u8],
#[builder(default)]
extension_data: BTreeMap<&'a str, &'a cbor_codec::value::Value>,
}
impl<'a> FidoCredentialRequest<'a> {
pub fn make_credential(&self, device: &mut FidoDevice) -> FidoResult<FidoCredential> {
device.make_credential(&self)
}
pub fn with_extension<Ext: FidoExtension>(&mut self, extension: &'a Ext) -> FidoResult<()> {
extension.patch_credential_request(self)
}
}
/// Request an assertion from the authenticator for a given credential.
/// `client_data_hash` SHOULD be a SHA256 hash of provided `client_data`,
/// this is signed and verified as part of the attestation. When not
/// implementing WebAuthN this can be any random 32-byte array.
///
/// This method will return whether the assertion matches the credential
/// provided, and will fail if a PIN is required but not provided or if the
/// device returns malformed data.
#[derive(Clone, Debug, Builder)]
#[builder(setter(into))]
#[builder(pattern = "owned")]
pub struct FidoAssertionRequest<'a, 'b> {
#[builder(default)]
up: bool,
#[builder(default)]
rk: bool,
#[builder(default)]
uv: bool,
/// The Relying Party ID provided by the platform when this key was generated.
rp_id: &'a str,
credentials: &'a [&'a FidoCredential],
#[builder(default = "&[]")]
exclude_list: &'a [&'a FidoCredential],
#[builder(default = "&[0u8; 32]")]
client_data_hash: &'a [u8],
#[builder(default)]
extension_data: BTreeMap<&'b str, &'b cbor_codec::value::Value>,
}
impl<'a, 'b> FidoAssertionRequest<'a, 'b> {
pub fn get_assertion(&self, device: &mut FidoDevice) -> FidoResult<&'a FidoCredential> {
device.get_assertion(self).map(|res| res.0)
}
pub fn with_extension<Ext: FidoExtension>(&mut self, extension: &'b Ext) -> FidoResult<()> {
extension.patch_assertion_request(self)
}
}
impl<'a, 'b> FidoAssertionRequestBuilder<'a, 'b> {
pub fn credential(mut self, credential: &'a &'a FidoCredential) -> Self {
self.credentials = Some(std::slice::from_ref(credential));
self
}
} }
impl FidoDevice { impl FidoDevice {
@@ -125,6 +277,7 @@ impl FidoDevice {
shared_secret: None, shared_secret: None,
pin_token: None, pin_token: None,
aaguid: [0; 16], aaguid: [0; 16],
info: GetInfoResponse::default(),
}; };
dev.init()?; dev.init()?;
Ok(dev) Ok(dev)
@@ -159,6 +312,7 @@ impl FidoDevice {
} }
self.needs_pin = response.options.client_pin == Some(true); self.needs_pin = response.options.client_pin == Some(true);
self.aaguid = response.aaguid; self.aaguid = response.aaguid;
self.info = response;
Ok(()) Ok(())
} }
@@ -216,88 +370,76 @@ impl FidoDevice {
} }
} }
/// Request a new credential from the authenticator. The `rp_id` should be pub fn cancel_handle(&mut self) -> FidoResult<FidoCancelHandle> {
/// a stable string used to identify the party for whom the credential is Ok(self
/// created, for convenience it will be returned with the credential. .device
/// `user_id` and `user_name` are not required when requesting attestations .try_clone()
/// but they MAY be displayed to the user and MAY be stored on the device .map(|device| FidoCancelHandle {
/// to be returned with an attestation if the device supports this. device,
/// `client_data_hash` SHOULD be a SHA256 hash of provided `client_data`, packet_size: self.packet_size,
/// this is only used to verify the attestation provided by the channel_id: self.channel_id,
/// authenticator. When not implementing WebAuthN this can be any random })
/// 32-byte array. .context(FidoErrorKind::Io)?)
/// }
/// This method will fail if a PIN is required but the device is not
/// unlocked or if the device returns malformed data. pub fn supports_extension<Ext: FidoExtension>(&self) -> bool {
self.info.extensions.iter().any(|ext| ext == Ext::extension_name())
}
pub fn make_credential( pub fn make_credential(
&mut self, &mut self,
rp_id: &str, request: &FidoCredentialRequest<'_>,
user_id: &[u8],
user_name: &str,
client_data_hash: &[u8],
) -> FidoResult<FidoCredential> { ) -> FidoResult<FidoCredential> {
//TODO: implement all options: https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html#authenticatorMakeCredential
let rp = cbor::PublicKeyCredentialRpEntity { let rp = cbor::PublicKeyCredentialRpEntity {
id: rp_id, id: request.rp_id,
name: None, name: request.rp_name,
icon: None, icon: request.rp_icon_url,
}; };
let user = cbor::PublicKeyCredentialUserEntity { let user = cbor::PublicKeyCredentialUserEntity {
id: user_id, id: request.user_id,
name: user_name, name: request.user_name.unwrap_or(""),
icon: None, icon: request.user_icon_url,
display_name: None, display_name: request.user_display_name,
}; };
let options = Some(AuthenticatorOptions { let options = Some(AuthenticatorOptions {
uv: true, up: false,
rk: false, uv: request.uv,
rk: request.rk,
}); });
self.make_credential_full(rp, user, client_data_hash, &[], &[], options)
}
/// Request a new credential from the authenticator. The `rp_id` should be
/// a stable string used to identify the party for whom the credential is
/// created, for convenience it will be returned with the credential.
/// `user_id` and `user_name` are not required when requesting attestations
/// but they MAY be displayed to the user and MAY be stored on the device
/// to be returned with an attestation if the device supports this.
/// `client_data_hash` SHOULD be a SHA256 hash of provided `client_data`,
/// this is only used to verify the attestation provided by the
/// authenticator. When not implementing WebAuthN this can be any random
/// 32-byte array.
///
/// This method will fail if a PIN is required but the device is not
/// unlocked or if the device returns malformed data.
pub fn make_credential_full(
&mut self,
rp: cbor::PublicKeyCredentialRpEntity,
user: cbor::PublicKeyCredentialUserEntity,
client_data_hash: &[u8],
exclude_list: &[cbor::PublicKeyCredentialDescriptor],
extensions: &[(&str, &cbor_codec::value::Value)],
options: Option<cbor::AuthenticatorOptions>,
) -> FidoResult<FidoCredential> {
if self.needs_pin && self.pin_token.is_none() { if self.needs_pin && self.pin_token.is_none() {
Err(FidoErrorKind::PinRequired)? Err(FidoErrorKind::PinRequired)?
} }
if client_data_hash.len() != 32 { if request.client_data_hash.len() != 32 {
Err(FidoErrorKind::CborEncode)? Err(FidoErrorKind::CborEncode)?
} }
while self.shared_secret.is_none() {
self.init_shared_secret()?;
}
let pub_key_cred_params = [("public-key", -7)]; let pub_key_cred_params = [("public-key", -7)];
let pin_auth = self let pin_auth = self
.pin_token .pin_token
.as_ref() .as_ref()
.map(|token| token.auth(&client_data_hash)); .map(|token| token.auth(&request.client_data_hash));
let rp_id = rp.id.to_owned();
let request = cbor::MakeCredentialRequest { let request = cbor::MakeCredentialRequest {
client_data_hash, client_data_hash: request.client_data_hash,
rp, rp,
user, user,
pub_key_cred_params: &pub_key_cred_params, pub_key_cred_params: &pub_key_cred_params,
exclude_list: exclude_list, exclude_list: &request
extensions: extensions, .exclude_list
options: options, .iter()
.map(|cred| PublicKeyCredentialDescriptor {
cred_type: "public-key".into(),
id: cred.id.clone(),
})
.collect::<Vec<_>>()[..],
extensions: &request
.extension_data
.iter()
.map(|(name, data)| (*name, *data))
.collect::<Vec<_>>()[..],
options,
pin_auth, pin_auth,
pin_protocol: pin_auth.and(Some(0x01)), pin_protocol: pin_auth.and(Some(0x01)),
}; };
@@ -315,85 +457,122 @@ impl FidoDevice {
.bytes(); .bytes();
Ok(FidoCredential { Ok(FidoCredential {
id: response.auth_data.attested_credential_data.credential_id, id: response.auth_data.attested_credential_data.credential_id,
rp_id: rp_id, public_key: Some(Vec::from(&public_key[..])),
public_key: Vec::from(&public_key[..]),
}) })
} }
/// Request an assertion from the authenticator for a given credential. /// Request a new credential from the authenticator. The `rp_id` should be
/// a stable string used to identify the party for whom the credential is
/// created, for convenience it will be returned with the credential.
/// `user_id` and `user_name` are not required when requesting attestations
/// but they MAY be displayed to the user and MAY be stored on the device
/// to be returned with an attestation if the device supports this.
/// `client_data_hash` SHOULD be a SHA256 hash of provided `client_data`, /// `client_data_hash` SHOULD be a SHA256 hash of provided `client_data`,
/// this is signed and verified as part of the attestation. When not /// this is only used to verify the attestation provided by the
/// implementing WebAuthN this can be any random 32-byte array. /// authenticator. When not implementing WebAuthN this can be any random
/// 32-byte array.
/// ///
/// This method will return whether the assertion matches the credential /// This method will fail if a PIN is required but the device is not
/// provided, and will fail if a PIN is required but not provided or if the /// unlocked or if the device returns malformed data.
/// device returns malformed data. pub fn get_assertion<'a, 'b>(
pub fn get_assertion(
&mut self, &mut self,
credential: &FidoCredential, assertion: &FidoAssertionRequest<'a, 'b>,
client_data_hash: &[u8], ) -> FidoResult<(&'a FidoCredential, AuthenticatorData)> {
) -> FidoResult<bool> { while self.shared_secret.is_none() {
self.get_assertion_multiple(&[credential], client_data_hash) self.init_shared_secret()?;
} }
pub fn get_assertion_multiple(
&mut self,
credentials: &[&FidoCredential],
client_data_hash: &[u8],
) -> FidoResult<bool> {
if self.needs_pin && self.pin_token.is_none() { if self.needs_pin && self.pin_token.is_none() {
Err(FidoErrorKind::PinRequired)? Err(FidoErrorKind::PinRequired)?
} }
if client_data_hash.len() != 32 { if assertion.client_data_hash.len() != 32 {
Err(FidoErrorKind::CborEncode)? Err(FidoErrorKind::CborEncode)?
} }
let pin_auth = self let pin_auth = self
.pin_token .pin_token
.as_ref() .as_ref()
.map(|token| token.auth(&client_data_hash)); .map(|token| token.auth(&assertion.client_data_hash));
let allow_list = credentials let request = GetAssertionRequest {
rp_id: assertion.rp_id,
client_data_hash: assertion.client_data_hash,
allow_list: &assertion
.credentials
.iter() .iter()
.map(|cred| cbor::PublicKeyCredentialDescriptor { .map(|cred| PublicKeyCredentialDescriptor {
cred_type: String::from("public-key"), cred_type: "public-key".into(),
id: cred.id.clone(), id: cred.id.clone(),
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>()[..],
let request = cbor::GetAssertionRequest { extensions: &assertion
rp_id: &credentials[0].rp_id, .extension_data
client_data_hash: client_data_hash, .iter()
allow_list: &allow_list, .map(|(name, data)| (*name, *data))
extensions: Default::default(), .collect::<Vec<_>>()[..],
options: Some(cbor::AuthenticatorOptions { options: Some(AuthenticatorOptions {
rk: false, rk: assertion.rk,
uv: true, uv: assertion.uv,
up: assertion.up,
}), }),
pin_auth, pin_auth: pin_auth,
pin_protocol: pin_auth.and(Some(0x01)), pin_protocol: pin_auth.and(Some(0x01)),
}; };
let response = match self.cbor(cbor::Request::GetAssertion(request))? { let response = match self.cbor(cbor::Request::GetAssertion(request))? {
cbor::Response::GetAssertion(resp) => resp, cbor::Response::GetAssertion(resp) => resp,
_ => Err(FidoErrorKind::CborDecode)?, _ => Err(FidoErrorKind::CborDecode)?,
}; };
Ok(credentials let credential = assertion
.credentials
.iter() .iter()
.filter(|cred| { .flat_map(|cred| {
response response
.credential .credential
.as_ref() .as_ref()
.map(|cred2| cred2.id == cred.id) .filter(|rcred| rcred.id == cred.id)
.unwrap_or(true) .map(|_| *cred)
}) })
.map(|cred| { .next();
credential
.and_then(|cred| {
if cred
.public_key
.as_ref()
.map(|public_key| {
crypto::verify_signature( crypto::verify_signature(
&cred.public_key, &public_key,
&client_data_hash, &assertion.client_data_hash,
&response.auth_data_bytes, &response.auth_data_bytes,
&response.signature, &response.signature,
) )
}) })
.filter(|pass| *pass) .unwrap_or(true)
.next() {
.unwrap_or(false)) Some(cred)
} else {
None
}
})
.ok_or(FidoError::from(FidoErrorKind::VerifySignature))
.map(|cred| (cred, response.auth_data))
}
pub fn ping(&mut self, data: &[u8]) -> FidoResult<Vec<u8>> {
self.exchange(CtapCommand::Ping, data)
}
pub fn wink(&mut self) -> FidoResult<()> {
self.send(&CtapCommand::Wink, &[]).map(|_| ())
}
fn lock(&mut self, time_sec: u8) -> FidoResult<()> {
self.exchange(CtapCommand::Lock, &[time_sec]).map(|_| ())
}
fn keepalive(&mut self) -> FidoResult<CtapStatus> {
self.exchange(CtapCommand::Keepalive, &[])?
.first()
.cloned()
.and_then(CtapStatus::from_u8)
.ok_or(FidoError::from(FidoErrorKind::CborDecode))
} }
fn cbor(&mut self, request: cbor::Request) -> FidoResult<cbor::Response> { fn cbor(&mut self, request: cbor::Request) -> FidoResult<cbor::Response> {
@@ -414,7 +593,7 @@ impl FidoDevice {
} }
fn send(&mut self, cmd: &CtapCommand, payload: &[u8]) -> FidoResult<()> { fn send(&mut self, cmd: &CtapCommand, payload: &[u8]) -> FidoResult<()> {
if payload.is_empty() || payload.len() > u16::MAX as usize { if payload.len() > u16::MAX as usize {
Err(FidoErrorKind::WritePacket)? Err(FidoErrorKind::WritePacket)?
} }
let to_send = payload.len() as u16; let to_send = payload.len() as u16;

View File

@@ -13,7 +13,7 @@ use std::io::{Read, Write};
static FRAME_INIT: u8 = 0x80; static FRAME_INIT: u8 = 0x80;
#[repr(u8)] #[repr(u8)]
#[derive(FromPrimitive, ToPrimitive, PartialEq)] #[derive(Debug, FromPrimitive, ToPrimitive, PartialEq)]
pub enum CtapCommand { pub enum CtapCommand {
Invalid = 0x00, Invalid = 0x00,
Ping = 0x01, Ping = 0x01,
@@ -36,6 +36,13 @@ impl CtapCommand {
} }
} }
#[repr(u8)]
#[derive(Debug, FromPrimitive, ToPrimitive, PartialEq)]
pub enum CtapStatus {
Processing = 0x01,
AwaitingUserPresence = 0x02,
}
#[repr(u8)] #[repr(u8)]
#[derive(FromPrimitive, Fail, Debug)] #[derive(FromPrimitive, Fail, Debug)]
pub enum CtapError { pub enum CtapError {

88
src/util.rs Normal file
View File

@@ -0,0 +1,88 @@
#[cfg(feature = "request_multiple")]
use crate::{
cbor::AuthenticatorData, FidoAssertionRequest, FidoCredential, FidoCredentialRequest,
FidoDevice, FidoErrorKind, FidoResult,
};
#[cfg(feature = "request_multiple")]
use crossbeam::thread;
#[cfg(feature = "request_multiple")]
use std::sync::mpsc::channel;
#[cfg(feature = "request_multiple")]
use std::time::Duration;
#[cfg(feature = "request_multiple")]
pub fn request_multiple_devices<
'a,
T: Send + 'a,
F: Fn(&mut FidoDevice) -> FidoResult<T> + 'a + Sync,
>(
devices: impl Iterator<Item = (&'a mut FidoDevice, &'a F)>,
timeout: Option<Duration>,
) -> FidoResult<T> {
thread::scope(|scope| -> FidoResult<T> {
let (tx, rx) = channel();
let handles = devices
.map(|(device, fn_)| {
let cancel = device.cancel_handle()?;
let tx = tx.clone();
let thread_handle = scope.spawn(move |_| tx.send(fn_(device)));
Ok((cancel, thread_handle))
})
.collect::<FidoResult<Vec<_>>>()?;
let mut err = None;
let mut slept = Duration::from_millis(0);
let interval = Duration::from_millis(10);
let mut received = 0usize;
let res = loop {
match timeout {
Some(t) if t < slept => {
break if let Some(cause) = err {
cause
} else {
Err(FidoErrorKind::Timeout.into())
};
}
_ => (),
}
if timeout.map(|t| t < slept).unwrap_or(true) {}
if let Ok(msg) = rx.recv_timeout(interval) {
received += 1;
match msg {
e @ Err(_) if received == handles.len() => break e,
e @ Err(_) => err = Some(e),
res @ Ok(_) => break res,
}
} else {
slept += interval;
}
};
for (mut cancel, join) in handles {
// Canceling out of courtesy don't care if it fails
let _ = cancel.cancel();
let _ = join.join();
}
res
})
.unwrap()
}
/// Will send the `assertion_request` to all supplied `devices` and return either the first successful assertion or the last error
#[cfg(feature = "request_multiple")]
pub fn get_assertion_devices<'a>(
assertion_request: &'a FidoAssertionRequest,
devices: impl Iterator<Item = &'a mut FidoDevice>,
timeout: Option<Duration>,
) -> FidoResult<(&'a FidoCredential, AuthenticatorData)> {
let get_assertion = |device: &mut FidoDevice| device.get_assertion(assertion_request);
request_multiple_devices(devices.map(|device| (device, &get_assertion)), timeout)
}
/// Will send the `credential_request` to all supplied `devices` and return either the first credential or the last error
#[cfg(feature = "request_multiple")]
pub fn make_credential_devices<'a>(
credential_request: &'a FidoCredentialRequest,
devices: impl Iterator<Item = &'a mut FidoDevice>,
timeout: Option<Duration>,
) -> FidoResult<FidoCredential> {
let make_credential = |device: &mut FidoDevice| device.make_credential(credential_request);
request_multiple_devices(devices.map(|device| (device, &make_credential)), timeout)
}