Compare commits
2 Commits
Author | SHA1 | Date | |
---|---|---|---|
501b28e0d9 | |||
d4c9dd913f |
13
Cargo.toml
13
Cargo.toml
@ -1,13 +1,12 @@
|
|||||||
[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.4.5"
|
version = "0.3.0"
|
||||||
license = "Apache-2.0/MIT"
|
license = "Apache-2.0/MIT"
|
||||||
homepage = "https://github.com/shimunn/ctap"
|
homepage = "https://github.com/ArdaXi/ctap/pull/2"
|
||||||
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"
|
||||||
@ -20,16 +19,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"
|
||||||
|
csv-core = "0.1.6"
|
||||||
derive_builder = "0.9.0"
|
derive_builder = "0.9.0"
|
||||||
crossbeam = { version = "0.7.3", optional = true }
|
crossbeam = { version = "0.7.3", optional = true }
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
crossbeam = "0.7.3"
|
crossbeam = "0.7.3"
|
||||||
hex = "0.4.0"
|
hex = "0.4.0"
|
||||||
[build-dependencies]
|
|
||||||
csv = "1.1.3"
|
|
||||||
serde = "1.0.106"
|
|
||||||
serde_derive = "1.0.106"
|
|
||||||
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
request_multiple = ["crossbeam"]
|
assert_devices = ["crossbeam"]
|
||||||
|
41
build.rs
41
build.rs
@ -1,41 +0,0 @@
|
|||||||
use csv::{Reader, StringRecord};
|
|
||||||
use serde_derive::Deserialize;
|
|
||||||
use std::env;
|
|
||||||
use std::fs::File;
|
|
||||||
use std::io::{Result, Write};
|
|
||||||
use std::iter::FromIterator;
|
|
||||||
use std::string::String;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
parse_error_codes().expect("Failed to parse error codes")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_error_codes() -> Result<()> {
|
|
||||||
println!("cargo:rerun-if-changed=ctap_error_codes.csv");
|
|
||||||
let mut out_file = File::create(format!(
|
|
||||||
"{}/ctap_error_codes.rs",
|
|
||||||
env::var("OUT_DIR").unwrap()
|
|
||||||
))?;
|
|
||||||
out_file.write_all(b"static CTAP_ERROR_CODES: &[(usize, &str, &str)] = &[")?;
|
|
||||||
let mut rdr = Reader::from_path("ctap_error_codes.csv")?;
|
|
||||||
rdr.set_headers(StringRecord::from_iter(&["code", "name", "desc"]));
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
struct ErrorCode {
|
|
||||||
code: String,
|
|
||||||
name: String,
|
|
||||||
desc: String,
|
|
||||||
}
|
|
||||||
for result in rdr.deserialize() {
|
|
||||||
let record: ErrorCode = result.unwrap();
|
|
||||||
out_file.write_all(
|
|
||||||
format!(
|
|
||||||
"({}, \"{}\", \"{}\"),\n",
|
|
||||||
i64::from_str_radix(&record.code[2..], 16).unwrap(),
|
|
||||||
record.name,
|
|
||||||
record.desc
|
|
||||||
)
|
|
||||||
.as_bytes(),
|
|
||||||
)?;
|
|
||||||
}
|
|
||||||
out_file.write_all(b"];")
|
|
||||||
}
|
|
@ -3,7 +3,7 @@ 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::HmacExtension;
|
use ctap::extensions::hmac::HmacExtension;
|
||||||
use ctap::{FidoAssertionRequestBuilder, FidoCredential, FidoCredentialRequestBuilder};
|
use ctap::{FidoCredential, FidoCredentialRequestBuilder, AuthenticatorOptions};
|
||||||
use hex;
|
use hex;
|
||||||
use std::env::args;
|
use std::env::args;
|
||||||
use std::io::prelude::*;
|
use std::io::prelude::*;
|
||||||
@ -17,30 +17,23 @@ fn main() -> ctap::FidoResult<()> {
|
|||||||
let device_info = &mut devices.next().expect("No authenticator 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 credential = match args().skip(1).next().map(|h| FidoCredential {
|
let mut credential = match args().skip(1).next().map(|h| FidoCredential {
|
||||||
id: hex::decode(&h).expect("Invalid credential"),
|
id: hex::decode(&h).expect("Invalid credential"),
|
||||||
public_key: None,
|
public_key: None,
|
||||||
}) {
|
}) {
|
||||||
Some(cred) => cred,
|
Some(cred) => cred,
|
||||||
_ => {
|
_ => {
|
||||||
let req = FidoCredentialRequestBuilder::default()
|
let req = FidoCredentialRequestBuilder::default().rp_id(RP_ID).rp_name("ctap_hmac crate").user_name("example").uv(false).build().unwrap();
|
||||||
.rp_id(RP_ID)
|
|
||||||
.rp_name("ctap_hmac crate")
|
|
||||||
.user_name("example")
|
|
||||||
.uv(false)
|
|
||||||
.build()
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
println!("Authorize using your device");
|
println!("Authorize using your device");
|
||||||
let cred = device
|
let cred = device.make_hmac_credential(req).expect("Failed to request credential");
|
||||||
.make_hmac_credential(&req)
|
|
||||||
.expect("Failed to request credential");
|
|
||||||
println!("Credential: {}\nNote: You can pass this credential as first argument in order to reproduce results", hex::encode(&cred.id));
|
println!("Credential: {}\nNote: You can pass this credential as first argument in order to reproduce results", hex::encode(&cred.id));
|
||||||
cred
|
cred
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
let credential = credential;
|
||||||
print!("Type in your message: ");
|
print!("Type in your message: ");
|
||||||
stdout().flush().unwrap();
|
stdout().flush();
|
||||||
let mut message = String::new();
|
let mut message = String::new();
|
||||||
stdin()
|
stdin()
|
||||||
.read_line(&mut message)
|
.read_line(&mut message)
|
||||||
@ -51,13 +44,7 @@ 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 credential = &&credential;
|
let (cred, (hash1, _hash2)) = device.get_hmac_assertion(RP_ID, &[&credential], &salt, None, None)?;
|
||||||
let request = FidoAssertionRequestBuilder::default()
|
|
||||||
.rp_id(RP_ID)
|
|
||||||
.credential(credential)
|
|
||||||
.build()
|
|
||||||
.unwrap();
|
|
||||||
let (_cred, (hash1, _hash2)) = device.get_hmac_assertion(&request, &salt, None)?;
|
|
||||||
println!("Hash: {}", hex::encode(&hash1));
|
println!("Hash: {}", hex::encode(&hash1));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -1,16 +1,24 @@
|
|||||||
extern crate ctap_hmac as ctap;
|
extern crate ctap_hmac as ctap;
|
||||||
|
|
||||||
|
use crossbeam::thread;
|
||||||
|
use crypto::digest::Digest;
|
||||||
|
use crypto::sha2::Sha256;
|
||||||
use ctap::{
|
use ctap::{
|
||||||
FidoAssertionRequestBuilder, FidoCredential, FidoCredentialRequestBuilder, FidoDevice,
|
FidoAssertionRequestBuilder, FidoCredential, FidoCredentialRequestBuilder, FidoDevice,
|
||||||
FidoResult,
|
FidoError, FidoResult,
|
||||||
};
|
};
|
||||||
|
use failure::_core::time::Duration;
|
||||||
use hex;
|
use hex;
|
||||||
use std::env::args;
|
use std::env::args;
|
||||||
use std::time::Duration;
|
use std::io::prelude::*;
|
||||||
|
use std::io::stdin;
|
||||||
|
use std::io::stdout;
|
||||||
|
use std::sync::mpsc::channel;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
const RP_ID: &str = "ctap_demo";
|
const RP_ID: &str = "ctap_demo";
|
||||||
|
|
||||||
fn main() -> ctap::FidoResult<()> {
|
fn run() -> ctap::FidoResult<()> {
|
||||||
let mut credentials = args()
|
let mut credentials = args()
|
||||||
.skip(1)
|
.skip(1)
|
||||||
.map(|id| FidoCredential {
|
.map(|id| FidoCredential {
|
||||||
@ -24,7 +32,6 @@ fn main() -> ctap::FidoResult<()> {
|
|||||||
FidoDevice::new(&h).and_then(|mut dev| {
|
FidoDevice::new(&h).and_then(|mut dev| {
|
||||||
FidoCredentialRequestBuilder::default()
|
FidoCredentialRequestBuilder::default()
|
||||||
.rp_id(RP_ID)
|
.rp_id(RP_ID)
|
||||||
.user_name("test")
|
|
||||||
.build()
|
.build()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.make_credential(&mut dev)
|
.make_credential(&mut dev)
|
||||||
@ -41,9 +48,11 @@ fn main() -> ctap::FidoResult<()> {
|
|||||||
let mut devices = ctap::get_devices()?
|
let mut devices = ctap::get_devices()?
|
||||||
.map(|handle| FidoDevice::new(&handle))
|
.map(|handle| FidoDevice::new(&handle))
|
||||||
.collect::<FidoResult<Vec<_>>>()?;
|
.collect::<FidoResult<Vec<_>>>()?;
|
||||||
// run with --features request_multiple
|
let (cred, _) = ctap::get_assertion_devices(&req, devices.iter_mut())?;
|
||||||
let (cred, _) =
|
|
||||||
ctap::get_assertion_devices(&req, devices.iter_mut(), Some(Duration::from_secs(10)))?;
|
|
||||||
println!("Success, got assertion for: {}", hex::encode(&cred.id));
|
println!("Success, got assertion for: {}", hex::encode(&cred.id));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
dbg!(run());
|
||||||
|
}
|
||||||
|
56
src/cbor.rs
56
src/cbor.rs
@ -7,7 +7,6 @@
|
|||||||
use cbor_codec::value;
|
use cbor_codec::value;
|
||||||
use cbor_codec::value::Value;
|
use cbor_codec::value::Value;
|
||||||
use cbor_codec::{Config, Decoder, Encoder, GenericDecoder, GenericEncoder};
|
use cbor_codec::{Config, Decoder, Encoder, GenericDecoder, GenericEncoder};
|
||||||
use cbor::skip::Skip;
|
|
||||||
|
|
||||||
use byteorder::{BigEndian, ByteOrder, ReadBytesExt, WriteBytesExt};
|
use byteorder::{BigEndian, ByteOrder, ReadBytesExt, WriteBytesExt};
|
||||||
use failure::ResultExt;
|
use failure::ResultExt;
|
||||||
@ -39,7 +38,7 @@ impl<'a> Request<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn decode<R: ReadBytesExt + Skip>(&self, reader: R) -> FidoResult<Response> {
|
pub fn decode<R: ReadBytesExt>(&self, reader: R) -> FidoResult<Response> {
|
||||||
Ok(match self {
|
Ok(match self {
|
||||||
Request::MakeCredential(_) => {
|
Request::MakeCredential(_) => {
|
||||||
Response::MakeCredential(MakeCredentialResponse::decode(reader)?)
|
Response::MakeCredential(MakeCredentialResponse::decode(reader)?)
|
||||||
@ -278,7 +277,7 @@ pub struct GetInfoResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl GetInfoResponse {
|
impl GetInfoResponse {
|
||||||
pub fn decode<R: ReadBytesExt + Skip>(mut reader: R) -> FidoResult<Self> {
|
pub fn decode<R: ReadBytesExt>(mut reader: R) -> FidoResult<Self> {
|
||||||
let status = reader.read_u8().context(FidoErrorKind::CborDecode)?;
|
let status = reader.read_u8().context(FidoErrorKind::CborDecode)?;
|
||||||
if status != 0 {
|
if status != 0 {
|
||||||
Err(FidoErrorKind::CborError(CborErrorCode::from(status)))?
|
Err(FidoErrorKind::CborError(CborErrorCode::from(status)))?
|
||||||
@ -305,7 +304,7 @@ impl GetInfoResponse {
|
|||||||
response.pin_protocols.push(decoder.u8()?);
|
response.pin_protocols.push(decoder.u8()?);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => decoder.skip()?,
|
_ => continue,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(response)
|
Ok(response)
|
||||||
@ -424,9 +423,7 @@ 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)
|
||||||
@ -598,45 +595,14 @@ impl CoseKey {
|
|||||||
let mut cose_key = CoseKey::default();
|
let mut cose_key = CoseKey::default();
|
||||||
cose_key.algorithm = -7;
|
cose_key.algorithm = -7;
|
||||||
for _ in 0..items {
|
for _ in 0..items {
|
||||||
match generic.value()? {
|
match generic.borrow_mut().i16()? {
|
||||||
Value::Text(value::Text::Text(text)) => match &text[..] {
|
0x01 => cose_key.key_type = generic.borrow_mut().u16()?,
|
||||||
"type" => {
|
0x02 => cose_key.algorithm = generic.borrow_mut().i32()?,
|
||||||
cose_key.key_type = match generic.value()? {
|
key if key < 0 => {
|
||||||
Value::Text(value::Text::Text(type_)) if &type_ == "public-key" => 0u16,
|
cose_key.parameters.insert(key, generic.value()?);
|
||||||
Value::U16(i) => i,
|
|
||||||
Value::U8(i) => i.into(),
|
|
||||||
_ => {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"alg" => cose_key.algorithm = generic.borrow_mut().i32()?,
|
|
||||||
_ => continue,
|
|
||||||
},
|
|
||||||
val @ Value::I8(_)
|
|
||||||
| val @ Value::I16(_)
|
|
||||||
| val @ Value::U16(_)
|
|
||||||
| val @ Value::U8(_) => {
|
|
||||||
let int_val = match val {
|
|
||||||
Value::I8(i) => i as i32,
|
|
||||||
Value::I16(i) => i as i32,
|
|
||||||
Value::U8(i) => i as i32,
|
|
||||||
Value::U16(i) => i as i32,
|
|
||||||
_ => unreachable!(),
|
|
||||||
};
|
|
||||||
match int_val {
|
|
||||||
0x01 => cose_key.key_type = generic.borrow_mut().u16()?,
|
|
||||||
0x02 => cose_key.algorithm = generic.borrow_mut().i32()?,
|
|
||||||
key if key < 0 => {
|
|
||||||
cose_key.parameters.insert(key as i16, generic.value()?);
|
|
||||||
}
|
|
||||||
unknown => {
|
|
||||||
(unknown, generic.value()?); // skip unknown parameter
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
unknown => {
|
_ => {
|
||||||
(unknown, generic.value()?); // skip unknown parameter
|
generic.value()?; // skip unknown parameter
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
96
src/error.rs
96
src/error.rs
@ -5,8 +5,8 @@
|
|||||||
// http://opensource.org/licenses/MIT>, at your option. This file may not be
|
// http://opensource.org/licenses/MIT>, at your option. This file may not be
|
||||||
// copied, modified, or distributed except according to those terms.
|
// copied, modified, or distributed except according to those terms.
|
||||||
use cbor_codec::{DecodeError, EncodeError};
|
use cbor_codec::{DecodeError, EncodeError};
|
||||||
|
use csv_core::{ReadFieldResult, Reader};
|
||||||
use failure::_core::fmt::{Error, Formatter};
|
use failure::_core::fmt::{Error, Formatter};
|
||||||
use failure::_core::option::Option;
|
|
||||||
use failure::{Backtrace, Context, Fail};
|
use failure::{Backtrace, Context, Fail};
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
@ -19,38 +19,10 @@ pub struct FidoError(Context<FidoErrorKind>);
|
|||||||
#[derive(Debug, Copy, Clone, Fail, Eq, PartialEq)]
|
#[derive(Debug, Copy, Clone, Fail, Eq, PartialEq)]
|
||||||
pub struct CborErrorCode(u8);
|
pub struct CborErrorCode(u8);
|
||||||
|
|
||||||
// generated using build.rs
|
|
||||||
include!(concat!(env!("OUT_DIR"), "/ctap_error_codes.rs"));
|
|
||||||
|
|
||||||
impl CborErrorCode {
|
|
||||||
fn detail(&self) -> Option<(u8, &'static str, &'static str)> {
|
|
||||||
for (code, name, desc) in CTAP_ERROR_CODES {
|
|
||||||
if *code == self.0 as usize {
|
|
||||||
return Some((self.0, name, desc));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn name(&self) -> Option<&'static str> {
|
|
||||||
self.detail().map(|(_, name, _)| name)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn description(&self) -> Option<&'static str> {
|
|
||||||
self.detail().map(|(_, _, desc)| desc)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn code(&self) -> u8 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail)]
|
#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail)]
|
||||||
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.")]
|
||||||
@ -75,7 +47,7 @@ pub enum FidoErrorKind {
|
|||||||
DecryptPin,
|
DecryptPin,
|
||||||
#[fail(display = "Failed to verify response signature.")]
|
#[fail(display = "Failed to verify response signature.")]
|
||||||
VerifySignature,
|
VerifySignature,
|
||||||
#[fail(display = "Failed to verify response signature.")]
|
#[fail(display = "Supplied key has incorrect type.")]
|
||||||
KeyType,
|
KeyType,
|
||||||
#[fail(display = "Device returned error: {}", _0)]
|
#[fail(display = "Device returned error: {}", _0)]
|
||||||
CborError(CborErrorCode),
|
CborError(CborErrorCode),
|
||||||
@ -142,24 +114,58 @@ impl From<u8> for CborErrorCode {
|
|||||||
|
|
||||||
impl Display for CborErrorCode {
|
impl Display for CborErrorCode {
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
|
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
|
||||||
if let Some((code, _name, desc)) = self.detail() {
|
let messages = include_str!("ctap_error_codes.csv");
|
||||||
|
let mut rdr = Reader::new();
|
||||||
|
let mut bytes = messages.as_bytes();
|
||||||
|
let mut col: usize = 0;
|
||||||
|
let mut row: usize = 0;
|
||||||
|
let mut correct_row: bool = false;
|
||||||
|
let mut field = [0u8; 1024];
|
||||||
|
let mut name: Option<String> = None;
|
||||||
|
let mut desc: Option<String> = None;
|
||||||
|
loop {
|
||||||
|
let (result, nin, read) = rdr.read_field(&bytes, &mut field);
|
||||||
|
bytes = &bytes[nin..];
|
||||||
|
match result {
|
||||||
|
ReadFieldResult::InputEmpty => {}
|
||||||
|
ReadFieldResult::OutputFull => panic!("field too large"),
|
||||||
|
ReadFieldResult::Field { record_end } => {
|
||||||
|
let text = String::from_utf8(field[..read].iter().cloned().collect()).unwrap();
|
||||||
|
if row > 0 {
|
||||||
|
match col {
|
||||||
|
0 if i64::from_str_radix(&text[2..], 16)
|
||||||
|
.expect("malformed ctap_error_codes.csv")
|
||||||
|
== self.0 as i64 =>
|
||||||
|
{
|
||||||
|
correct_row = true
|
||||||
|
}
|
||||||
|
1 | 2 if correct_row => {
|
||||||
|
if let Some(_) = name {
|
||||||
|
desc = Some(text);
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
name = Some(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
col += 1;
|
||||||
|
if record_end {
|
||||||
|
col = 0;
|
||||||
|
row += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ReadFieldResult::End => break,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some((code, _name, desc)) =
|
||||||
|
name.and_then(|name| desc.map(|desc| (self.0, name, desc)))
|
||||||
|
{
|
||||||
write!(f, "CborError: 0x{:x?}: {}", code, desc)?;
|
write!(f, "CborError: 0x{:x?}: {}", code, desc)?;
|
||||||
} else {
|
} else {
|
||||||
write!(f, "CborError: 0x{:x?}: unknown", self.code())?;
|
write!(f, "CborError: 0x{:x?}", self.0)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod test {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn cbor_error_code() {
|
|
||||||
assert_eq!(
|
|
||||||
CborErrorCode(0x33).to_string(),
|
|
||||||
"CborError: 0x33: PIN authentication, pinAuth, verification failed."
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -1,4 +1,7 @@
|
|||||||
use crate::{FidoAssertionRequest, FidoAssertionRequestBuilder, FidoCredentialRequest};
|
use crate::{
|
||||||
|
AuthenticatorOptions, 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;
|
||||||
@ -10,6 +13,7 @@ use rust_crypto::mac::Mac;
|
|||||||
use rust_crypto::sha2::Sha256;
|
use rust_crypto::sha2::Sha256;
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
|
use std::iter::FromIterator;
|
||||||
|
|
||||||
pub trait HmacExtension {
|
pub trait HmacExtension {
|
||||||
fn extension_name() -> &'static str {
|
fn extension_name() -> &'static str {
|
||||||
@ -36,10 +40,8 @@ pub trait HmacExtension {
|
|||||||
|
|
||||||
/// Convenience function to create an credential which includes extension specific data
|
/// 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(
|
fn make_hmac_credential(&mut self, request: FidoCredentialRequest) -> FidoResult<FidoCredential>;
|
||||||
&mut self,
|
|
||||||
request: &FidoCredentialRequest,
|
|
||||||
) -> 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).
|
||||||
/// at least one `salt` must be provided, consider using a hashing function like SHA256
|
/// at least one `salt` must be provided, consider using a hashing function like SHA256
|
||||||
@ -51,11 +53,13 @@ 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<'a: 'b, 'b>(
|
fn get_hmac_assertion<'a>(
|
||||||
&mut self,
|
&mut self,
|
||||||
assertion: &FidoAssertionRequest<'a, 'b>,
|
rp_id: &str,
|
||||||
|
credentials: &'a [&'a FidoCredential],
|
||||||
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<(&'a FidoCredential, ([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
|
||||||
@ -71,13 +75,11 @@ 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(
|
||||||
&FidoAssertionRequestBuilder::default()
|
rp_id,
|
||||||
.rp_id(rp_id)
|
&[credential],
|
||||||
.credential(&credential)
|
|
||||||
.build()
|
|
||||||
.unwrap(),
|
|
||||||
&salt,
|
&salt,
|
||||||
None,
|
None,
|
||||||
|
Some(AuthenticatorOptions { uv: true, rk: true, up: false }),
|
||||||
)
|
)
|
||||||
.map(|(_cred, secret)| secret.0)
|
.map(|(_cred, secret)| secret.0)
|
||||||
}
|
}
|
||||||
@ -136,35 +138,43 @@ impl HmacExtension for FidoDevice {
|
|||||||
Ok(Value::Map(map))
|
Ok(Value::Map(map))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn make_hmac_credential(
|
fn make_hmac_credential(&mut self, request: FidoCredentialRequest) -> FidoResult<FidoCredential> {
|
||||||
&mut self,
|
let mut request = request;
|
||||||
request: &FidoCredentialRequest,
|
|
||||||
) -> FidoResult<FidoCredential> {
|
|
||||||
let mut request = request.clone();
|
|
||||||
request.rk = true;
|
request.rk = true;
|
||||||
request.extension_data.insert(
|
request.extension_data.insert(<Self as HmacExtension>::extension_name(), <Self as HmacExtension>::extension_input());
|
||||||
<Self as HmacExtension>::extension_name(),
|
|
||||||
<Self as HmacExtension>::extension_input(),
|
|
||||||
);
|
|
||||||
self.make_credential(&request)
|
self.make_credential(&request)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_hmac_assertion<'a: 'b, 'b>(
|
fn get_hmac_assertion<'a>(
|
||||||
&mut self,
|
&mut self,
|
||||||
request: &FidoAssertionRequest<'a, 'b>,
|
rp_id: &str,
|
||||||
|
credentials: &'a [&'a FidoCredential],
|
||||||
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<(&'a FidoCredential, ([u8; 32], Option<[u8; 32]>))> {
|
||||||
while self.shared_secret.is_none() {
|
while self.shared_secret.is_none() {
|
||||||
self.init_shared_secret()?;
|
self.init_shared_secret()?;
|
||||||
}
|
}
|
||||||
let ext_data: Value = self.get_data(salt, salt2)?;
|
let ext_data: Value = self.get_data(salt, salt2)?;
|
||||||
let mut request = request.clone();
|
|
||||||
request
|
|
||||||
.extension_data
|
|
||||||
.insert(<Self as HmacExtension>::extension_name(), &ext_data);
|
|
||||||
|
|
||||||
let (cred, auth_data) = self.get_assertion(&request)?;
|
let ext_data: BTreeMap<&str, &Value> = BTreeMap::from_iter(
|
||||||
|
[(<Self as HmacExtension>::extension_name(), &ext_data)]
|
||||||
|
.iter()
|
||||||
|
.cloned(),
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut builder = FidoAssertionRequestBuilder::default()
|
||||||
|
.credentials(credentials)
|
||||||
|
.rp_id(rp_id)
|
||||||
|
.extension_data(ext_data);
|
||||||
|
|
||||||
|
if let Some(opts) = options {
|
||||||
|
builder = builder.uv(opts.uv).up(opts.up);
|
||||||
|
}
|
||||||
|
|
||||||
|
let (cred, auth_data) =
|
||||||
|
self.get_assertion(&builder.build().unwrap())?;
|
||||||
let shared_secret = self.shared_secret.as_ref().unwrap();
|
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];
|
||||||
@ -196,11 +206,7 @@ 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..]);
|
||||||
let cred = request
|
let cred = credentials.into_iter().find(|c| c.id == cred.id).unwrap();
|
||||||
.credentials
|
|
||||||
.into_iter()
|
|
||||||
.find(|c| c.id == cred.id)
|
|
||||||
.unwrap();
|
|
||||||
Ok((cred, (hmac_secret_0, salt2.and(Some(hmac_secret_1)))))
|
Ok((cred, (hmac_secret_0, salt2.and(Some(hmac_secret_1)))))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
22
src/lib.rs
22
src/lib.rs
@ -217,7 +217,7 @@ impl<'a> FidoCredentialRequest<'a> {
|
|||||||
#[derive(Clone, Debug, Builder)]
|
#[derive(Clone, Debug, Builder)]
|
||||||
#[builder(setter(into))]
|
#[builder(setter(into))]
|
||||||
#[builder(pattern = "owned")]
|
#[builder(pattern = "owned")]
|
||||||
pub struct FidoAssertionRequest<'a, 'b> {
|
pub struct FidoAssertionRequest<'a> {
|
||||||
#[builder(default)]
|
#[builder(default)]
|
||||||
up: bool,
|
up: bool,
|
||||||
#[builder(default)]
|
#[builder(default)]
|
||||||
@ -232,16 +232,16 @@ pub struct FidoAssertionRequest<'a, 'b> {
|
|||||||
#[builder(default = "&[0u8; 32]")]
|
#[builder(default = "&[0u8; 32]")]
|
||||||
client_data_hash: &'a [u8],
|
client_data_hash: &'a [u8],
|
||||||
#[builder(default)]
|
#[builder(default)]
|
||||||
extension_data: BTreeMap<&'b str, &'b cbor_codec::value::Value>,
|
extension_data: BTreeMap<&'a str, &'a cbor_codec::value::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, 'b> FidoAssertionRequest<'a, 'b> {
|
impl<'a> FidoAssertionRequest<'a> {
|
||||||
pub fn get_assertion(&self, device: &mut FidoDevice) -> FidoResult<&'a FidoCredential> {
|
pub fn get_assertion(&self, device: &mut FidoDevice) -> FidoResult<&'a FidoCredential> {
|
||||||
device.get_assertion(self).map(|res| res.0)
|
device.get_assertion(self).map(|res| res.0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, 'b> FidoAssertionRequestBuilder<'a, 'b> {
|
impl<'a> FidoAssertionRequestBuilder<'a> {
|
||||||
pub fn credential(mut self, credential: &'a &'a FidoCredential) -> Self {
|
pub fn credential(mut self, credential: &'a &'a FidoCredential) -> Self {
|
||||||
self.credentials = Some(std::slice::from_ref(credential));
|
self.credentials = Some(std::slice::from_ref(credential));
|
||||||
self
|
self
|
||||||
@ -287,14 +287,14 @@ impl FidoDevice {
|
|||||||
cbor::Response::GetInfo(resp) => resp,
|
cbor::Response::GetInfo(resp) => resp,
|
||||||
_ => Err(FidoErrorKind::CborDecode)?,
|
_ => Err(FidoErrorKind::CborDecode)?,
|
||||||
};
|
};
|
||||||
if !response.versions.iter().any(|ver| ["FIDO_2_0", "FIDO_2_1_PRE"].contains(&ver.as_str())) {
|
if !response.versions.iter().any(|ver| ver == "FIDO_2_0") {
|
||||||
Err(FidoErrorKind::DeviceUnsupported)?
|
Err(FidoErrorKind::DeviceUnsupported)?
|
||||||
}
|
}
|
||||||
// Require pin protocol version 1, only if pin-protocol is supported at all
|
// Require pin protocol version 1, only if pin-protocol is supported at all
|
||||||
if !response
|
if !response
|
||||||
.pin_protocols
|
.pin_protocols
|
||||||
.iter()
|
.iter()
|
||||||
.any(|ver| *ver == 1) && response.pin_protocols.len() > 0
|
.fold(true, |supported, ver| *ver == 1 && supported)
|
||||||
{
|
{
|
||||||
Err(FidoErrorKind::DeviceUnsupported)?
|
Err(FidoErrorKind::DeviceUnsupported)?
|
||||||
}
|
}
|
||||||
@ -325,11 +325,6 @@ impl FidoDevice {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// True if this authenticator requires a PIN
|
|
||||||
pub fn needs_pin(&self) -> bool {
|
|
||||||
self.needs_pin
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Unlock the device with the provided PIN. Internally this will generate
|
/// Unlock the device with the provided PIN. Internally this will generate
|
||||||
/// an ECDH keypair, send the encrypted PIN to the device and store the PIN
|
/// an ECDH keypair, send the encrypted PIN to the device and store the PIN
|
||||||
/// token that the device generates on every power cycle. The PIN itself is
|
/// token that the device generates on every power cycle. The PIN itself is
|
||||||
@ -462,9 +457,10 @@ impl FidoDevice {
|
|||||||
///
|
///
|
||||||
/// This method will fail if a PIN is required but the device is not
|
/// This method will fail if a PIN is required but the device is not
|
||||||
/// unlocked or if the device returns malformed data.
|
/// unlocked or if the device returns malformed data.
|
||||||
pub fn get_assertion<'a, 'b>(
|
|
||||||
|
pub fn get_assertion<'a>(
|
||||||
&mut self,
|
&mut self,
|
||||||
assertion: &FidoAssertionRequest<'a, 'b>,
|
assertion: &FidoAssertionRequest<'a>,
|
||||||
) -> FidoResult<(&'a FidoCredential, AuthenticatorData)> {
|
) -> FidoResult<(&'a FidoCredential, AuthenticatorData)> {
|
||||||
while self.shared_secret.is_none() {
|
while self.shared_secret.is_none() {
|
||||||
self.init_shared_secret()?;
|
self.init_shared_secret()?;
|
||||||
|
122
src/util.rs
122
src/util.rs
@ -1,88 +1,44 @@
|
|||||||
#[cfg(feature = "request_multiple")]
|
use crate::cbor::AuthenticatorData;
|
||||||
use crate::{
|
use crate::{FidoAssertionRequest, FidoCredential, FidoDevice, FidoErrorKind, FidoResult};
|
||||||
cbor::AuthenticatorData, FidoAssertionRequest, FidoCredential, FidoCredentialRequest,
|
|
||||||
FidoDevice, FidoErrorKind, FidoResult,
|
|
||||||
};
|
|
||||||
#[cfg(feature = "request_multiple")]
|
|
||||||
use crossbeam::thread;
|
|
||||||
#[cfg(feature = "request_multiple")]
|
|
||||||
use std::sync::mpsc::channel;
|
use std::sync::mpsc::channel;
|
||||||
#[cfg(feature = "request_multiple")]
|
#[cfg(feature = "assert_devices")]
|
||||||
use std::time::Duration;
|
use crossbeam::thread;
|
||||||
#[cfg(feature = "request_multiple")]
|
|
||||||
pub fn request_multiple_devices<
|
/// Will send the `assertion` to all supplied `devices` and return either the first successful assertion or the last error
|
||||||
'a,
|
#[cfg(feature = "assert_devices")]
|
||||||
T: Send + 'a,
|
pub fn get_assertion_devices<'a>(
|
||||||
F: Fn(&mut FidoDevice) -> FidoResult<T> + 'a + Sync,
|
assertion: &'a FidoAssertionRequest,
|
||||||
>(
|
devices: impl Iterator<Item = &'a mut FidoDevice>,
|
||||||
devices: impl Iterator<Item = (&'a mut FidoDevice, &'a F)>,
|
) -> FidoResult<(&'a FidoCredential, AuthenticatorData)> {
|
||||||
timeout: Option<Duration>,
|
thread::scope(
|
||||||
) -> FidoResult<T> {
|
|scope| -> FidoResult<(&'a FidoCredential, AuthenticatorData)> {
|
||||||
thread::scope(|scope| -> FidoResult<T> {
|
let (tx, rx) = channel();
|
||||||
let (tx, rx) = channel();
|
let handles = devices
|
||||||
let handles = devices
|
.map(|device| {
|
||||||
.map(|(device, fn_)| {
|
let cancel = device.cancel_handle()?;
|
||||||
let cancel = device.cancel_handle()?;
|
let tx = tx.clone();
|
||||||
let tx = tx.clone();
|
let thread_handle =
|
||||||
let thread_handle = scope.spawn(move |_| tx.send(fn_(device)));
|
scope.spawn(move |_| tx.send(device.get_assertion(assertion)));
|
||||||
Ok((cancel, thread_handle))
|
Ok((cancel, thread_handle))
|
||||||
})
|
})
|
||||||
.collect::<FidoResult<Vec<_>>>()?;
|
.collect::<FidoResult<Vec<_>>>()?;
|
||||||
let mut err = None;
|
|
||||||
let mut slept = Duration::from_millis(0);
|
let mut err = None;
|
||||||
let interval = Duration::from_millis(10);
|
for res in rx.iter().take(handles.len()) {
|
||||||
let mut received = 0usize;
|
match res {
|
||||||
let res = loop {
|
Ok(_) => {
|
||||||
match timeout {
|
for (mut cancel, join) in handles {
|
||||||
Some(t) if t < slept => {
|
// Canceling out of courtesy don't care if it fails
|
||||||
break if let Some(cause) = err {
|
let _ = cancel.cancel();
|
||||||
cause
|
let _ = join.join();
|
||||||
} else {
|
}
|
||||||
Err(FidoErrorKind::Timeout.into())
|
return res;
|
||||||
};
|
}
|
||||||
|
e => err = Some(e),
|
||||||
}
|
}
|
||||||
_ => (),
|
|
||||||
}
|
}
|
||||||
if timeout.map(|t| t < slept).unwrap_or(true) {}
|
err.unwrap_or(Err(FidoErrorKind::DeviceUnsupported.into()))
|
||||||
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()
|
.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)
|
|
||||||
}
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user