Compare commits
22 Commits
Author | SHA1 | Date | |
---|---|---|---|
718c9c93e6 | |||
3a6dd90ec4 | |||
f5d52ee8b5 | |||
e6166f7cbd | |||
d6b20d0ba4 | |||
857c3cd955 | |||
80c175077f | |||
addc251418 | |||
a00f8fbe3b | |||
cc48719cfa | |||
09d6484535 | |||
238c4ba791 | |||
d93b86b9f0 | |||
ec932913e1 | |||
3ca719e077 | |||
f982494d51 | |||
4b58dd12f3 | |||
61d81bda87 | |||
9b663ed7e9 | |||
b92428214a | |||
8234975ba3 | |||
3d3679d5b9 |
26
Cargo.toml
26
Cargo.toml
@ -1,12 +1,13 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "ctap"
|
name = "ctap_hmac"
|
||||||
description = "A Rust implementation of the FIDO2 CTAP protocol"
|
description = "A Rust implementation of the FIDO2 CTAP protocol, including the HMAC extension"
|
||||||
version = "0.1.0"
|
version = "0.4.5"
|
||||||
license = "Apache-2.0/MIT"
|
license = "Apache-2.0/MIT"
|
||||||
homepage = "https://github.com/ArdaXi/ctap"
|
homepage = "https://github.com/shimunn/ctap"
|
||||||
repository = "https://github.com/ArdaXi/ctap"
|
repository = "https://github.com/shimunn/ctap"
|
||||||
authors = ["Arda Xi <arda@ardaxi.com>"]
|
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,3 +20,16 @@ cbor-codec = "0.7"
|
|||||||
ring = "0.13"
|
ring = "0.13"
|
||||||
untrusted = "0.6"
|
untrusted = "0.6"
|
||||||
rust-crypto = "0.2"
|
rust-crypto = "0.2"
|
||||||
|
derive_builder = "0.9.0"
|
||||||
|
crossbeam = { version = "0.7.3", optional = true }
|
||||||
|
[dev-dependencies]
|
||||||
|
crossbeam = "0.7.3"
|
||||||
|
hex = "0.4.0"
|
||||||
|
[build-dependencies]
|
||||||
|
csv = "1.1.3"
|
||||||
|
serde = "1.0.106"
|
||||||
|
serde_derive = "1.0.106"
|
||||||
|
|
||||||
|
|
||||||
|
[features]
|
||||||
|
request_multiple = ["crossbeam"]
|
||||||
|
28
README.md
28
README.md
@ -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
|
||||||
|
41
build.rs
Normal file
41
build.rs
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
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"];")
|
||||||
|
}
|
49
ctap_error_codes.csv
Normal file
49
ctap_error_codes.csv
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
Code,Name,Description
|
||||||
|
0x00,"CTAP1_ERR_SUCCESS, CTAP2_OK",Indicates successful response.
|
||||||
|
0x01,CTAP1_ERR_INVALID_COMMAND,The command is not a valid CTAP command.
|
||||||
|
0x02,CTAP1_ERR_INVALID_PARAMETER,The command included an invalid parameter.
|
||||||
|
0x03,CTAP1_ERR_INVALID_LENGTH,Invalid message or item length.
|
||||||
|
0x04,CTAP1_ERR_INVALID_SEQ,Invalid message sequencing.
|
||||||
|
0x05,CTAP1_ERR_TIMEOUT,Message timed out.
|
||||||
|
0x06,CTAP1_ERR_CHANNEL_BUSY,Channel busy.
|
||||||
|
0x0A,CTAP1_ERR_LOCK_REQUIRED,Command requires channel lock.
|
||||||
|
0x0B,CTAP1_ERR_INVALID_CHANNEL,Command not allowed on this cid.
|
||||||
|
0x11,CTAP2_ERR_CBOR_UNEXPECTED_TYPE,Invalid/unexpected CBOR error.
|
||||||
|
0x12,CTAP2_ERR_INVALID_CBOR,Error when parsing CBOR.
|
||||||
|
0x14,CTAP2_ERR_MISSING_PARAMETER,Missing non-optional parameter.
|
||||||
|
0x15,CTAP2_ERR_LIMIT_EXCEEDED,Limit for number of items exceeded.
|
||||||
|
0x16,CTAP2_ERR_UNSUPPORTED_EXTENSION,Unsupported extension.
|
||||||
|
0x19,CTAP2_ERR_CREDENTIAL_EXCLUDED,Valid credential found in the exclude list.
|
||||||
|
0x21,CTAP2_ERR_PROCESSING,Processing (Lengthy operation is in progress).
|
||||||
|
0x22,CTAP2_ERR_INVALID_CREDENTIAL,Credential not valid for the authenticator.
|
||||||
|
0x23,CTAP2_ERR_USER_ACTION_PENDING,Authentication is waiting for user interaction.
|
||||||
|
0x24,CTAP2_ERR_OPERATION_PENDING,"Processing, lengthy operation is in progress."
|
||||||
|
0x25,CTAP2_ERR_NO_OPERATIONS,No request is pending.
|
||||||
|
0x26,CTAP2_ERR_UNSUPPORTED_ALGORITHM,Authenticator does not support requested algorithm.
|
||||||
|
0x27,CTAP2_ERR_OPERATION_DENIED,Not authorized for requested operation.
|
||||||
|
0x28,CTAP2_ERR_KEY_STORE_FULL,Internal key storage is full.
|
||||||
|
0x29,CTAP2_ERR_NOT_BUSY,Authenticator cannot cancel as it is not busy.
|
||||||
|
0x2A,CTAP2_ERR_NO_OPERATION_PENDING,No outstanding operations.
|
||||||
|
0x2B,CTAP2_ERR_UNSUPPORTED_OPTION,Unsupported option.
|
||||||
|
0x2C,CTAP2_ERR_INVALID_OPTION,Not a valid option for current operation.
|
||||||
|
0x2D,CTAP2_ERR_KEEPALIVE_CANCEL,Pending keep alive was cancelled.
|
||||||
|
0x2E,CTAP2_ERR_NO_CREDENTIALS,No valid credentials provided.
|
||||||
|
0x2F,CTAP2_ERR_USER_ACTION_TIMEOUT,Timeout waiting for user interaction.
|
||||||
|
0x30,CTAP2_ERR_NOT_ALLOWED,"Continuation command, such as, authenticatorGetNextAssertion not allowed."
|
||||||
|
0x31,CTAP2_ERR_PIN_INVALID,PIN Invalid.
|
||||||
|
0x32,CTAP2_ERR_PIN_BLOCKED,PIN Blocked.
|
||||||
|
0x33,CTAP2_ERR_PIN_AUTH_INVALID,"PIN authentication, pinAuth, verification failed."
|
||||||
|
0x34,CTAP2_ERR_PIN_AUTH_BLOCKED,"PIN authentication,pinAuth, blocked. Requires power recycle to reset."
|
||||||
|
0x35,CTAP2_ERR_PIN_NOT_SET,No PIN has been set.
|
||||||
|
0x36,CTAP2_ERR_PIN_REQUIRED,PIN is required for the selected operation.
|
||||||
|
0x37,CTAP2_ERR_PIN_POLICY_VIOLATION,PIN policy violation. Currently only enforces minimum length.
|
||||||
|
0x38,CTAP2_ERR_PIN_TOKEN_EXPIRED,pinToken expired on authenticator.
|
||||||
|
0x39,CTAP2_ERR_REQUEST_TOO_LARGE,Authenticator cannot handle this request due to memory constraints.
|
||||||
|
0x3A,CTAP2_ERR_ACTION_TIMEOUT,The current operation has timed out.
|
||||||
|
0x3B,CTAP2_ERR_UP_REQUIRED,User presence is required for the requested operation.
|
||||||
|
0x7F,CTAP1_ERR_OTHER,Other unspecified error.
|
||||||
|
0xDF,CTAP2_ERR_SPEC_LAST,CTAP 2 spec last error.
|
||||||
|
0xE0,CTAP2_ERR_EXTENSION_FIRST,Extension specific error.
|
||||||
|
0xEF,CTAP2_ERR_EXTENSION_LAST,Extension specific error.
|
||||||
|
0xF0,CTAP2_ERR_VENDOR_FIRST,Vendor specific error.
|
||||||
|
0xFF,CTAP2_ERR_VENDOR_LAST,Vendor specific error.
|
|
63
examples/hmac.rs
Normal file
63
examples/hmac.rs
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
extern crate ctap_hmac as ctap;
|
||||||
|
|
||||||
|
use crypto::digest::Digest;
|
||||||
|
use crypto::sha2::Sha256;
|
||||||
|
use ctap::extensions::hmac::HmacExtension;
|
||||||
|
use ctap::{FidoAssertionRequestBuilder, FidoCredential, FidoCredentialRequestBuilder};
|
||||||
|
use hex;
|
||||||
|
use std::env::args;
|
||||||
|
use std::io::prelude::*;
|
||||||
|
use std::io::stdin;
|
||||||
|
use std::io::stdout;
|
||||||
|
|
||||||
|
const RP_ID: &str = "ctap_demo";
|
||||||
|
|
||||||
|
fn main() -> ctap::FidoResult<()> {
|
||||||
|
let mut devices = ctap::get_devices()?;
|
||||||
|
let device_info = &mut devices.next().expect("No authenticator found");
|
||||||
|
let mut device = ctap::FidoDevice::new(device_info)?;
|
||||||
|
|
||||||
|
let credential = match args().skip(1).next().map(|h| FidoCredential {
|
||||||
|
id: hex::decode(&h).expect("Invalid credential"),
|
||||||
|
public_key: None,
|
||||||
|
}) {
|
||||||
|
Some(cred) => cred,
|
||||||
|
_ => {
|
||||||
|
let req = FidoCredentialRequestBuilder::default()
|
||||||
|
.rp_id(RP_ID)
|
||||||
|
.rp_name("ctap_hmac crate")
|
||||||
|
.user_name("example")
|
||||||
|
.uv(false)
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
println!("Authorize using your device");
|
||||||
|
let cred = device
|
||||||
|
.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));
|
||||||
|
cred
|
||||||
|
}
|
||||||
|
};
|
||||||
|
print!("Type in your message: ");
|
||||||
|
stdout().flush().unwrap();
|
||||||
|
let mut message = String::new();
|
||||||
|
stdin()
|
||||||
|
.read_line(&mut message)
|
||||||
|
.expect("Couldn't get your message\nNote: this demo does not accept binary data");
|
||||||
|
println!("Authorize using your device");
|
||||||
|
|
||||||
|
let mut salt = [0u8; 32];
|
||||||
|
let mut digest = Sha256::new();
|
||||||
|
digest.input(&message.as_bytes());
|
||||||
|
digest.result(&mut salt);
|
||||||
|
let credential = &&credential;
|
||||||
|
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));
|
||||||
|
Ok(())
|
||||||
|
}
|
49
examples/multiple.rs
Normal file
49
examples/multiple.rs
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
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)
|
||||||
|
.user_name("test")
|
||||||
|
.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(())
|
||||||
|
}
|
187
src/cbor.rs
187
src/cbor.rs
@ -4,11 +4,12 @@
|
|||||||
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
|
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
|
||||||
// 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::{Config, Encoder, Decoder, GenericDecoder, GenericEncoder};
|
|
||||||
use cbor_codec::value::Value;
|
|
||||||
use cbor_codec::value;
|
use cbor_codec::value;
|
||||||
|
use cbor_codec::value::Value;
|
||||||
|
use cbor_codec::{Config, Decoder, Encoder, GenericDecoder, GenericEncoder};
|
||||||
|
use cbor::skip::Skip;
|
||||||
|
|
||||||
use byteorder::{WriteBytesExt, ReadBytesExt, BigEndian, ByteOrder};
|
use byteorder::{BigEndian, ByteOrder, ReadBytesExt, WriteBytesExt};
|
||||||
use failure::ResultExt;
|
use failure::ResultExt;
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@ -29,25 +30,23 @@ impl<'a> Request<'a> {
|
|||||||
match self {
|
match self {
|
||||||
Request::MakeCredential(req) => req.encode(&mut encoder),
|
Request::MakeCredential(req) => req.encode(&mut encoder),
|
||||||
Request::GetAssertion(req) => req.encode(&mut encoder),
|
Request::GetAssertion(req) => req.encode(&mut encoder),
|
||||||
Request::GetInfo => {
|
Request::GetInfo => encoder
|
||||||
encoder
|
.writer()
|
||||||
.writer()
|
.write_u8(0x04)
|
||||||
.write_u8(0x04)
|
.context(FidoErrorKind::CborEncode)
|
||||||
.context(FidoErrorKind::CborEncode)
|
.map_err(From::from),
|
||||||
.map_err(From::from)
|
|
||||||
}
|
|
||||||
Request::ClientPin(req) => req.encode(&mut encoder),
|
Request::ClientPin(req) => req.encode(&mut encoder),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn decode<R: ReadBytesExt>(&self, reader: R) -> FidoResult<Response> {
|
pub fn decode<R: ReadBytesExt + Skip>(&self, reader: R) -> FidoResult<Response> {
|
||||||
Ok(match self {
|
Ok(match self {
|
||||||
Request::MakeCredential(_) => Response::MakeCredential(
|
Request::MakeCredential(_) => {
|
||||||
MakeCredentialResponse::decode(reader)?,
|
Response::MakeCredential(MakeCredentialResponse::decode(reader)?)
|
||||||
),
|
}
|
||||||
Request::GetAssertion(_) => Response::GetAssertion(
|
Request::GetAssertion(_) => {
|
||||||
GetAssertionResponse::decode(reader)?,
|
Response::GetAssertion(GetAssertionResponse::decode(reader)?)
|
||||||
),
|
}
|
||||||
Request::GetInfo => Response::GetInfo(GetInfoResponse::decode(reader)?),
|
Request::GetInfo => Response::GetInfo(GetInfoResponse::decode(reader)?),
|
||||||
Request::ClientPin(_) => Response::ClientPin(ClientPinResponse::decode(reader)?),
|
Request::ClientPin(_) => Response::ClientPin(ClientPinResponse::decode(reader)?),
|
||||||
})
|
})
|
||||||
@ -77,13 +76,18 @@ pub struct MakeCredentialRequest<'a> {
|
|||||||
|
|
||||||
impl<'a> MakeCredentialRequest<'a> {
|
impl<'a> MakeCredentialRequest<'a> {
|
||||||
pub fn encode<W: WriteBytesExt>(&self, mut encoder: &mut Encoder<W>) -> FidoResult<()> {
|
pub fn encode<W: WriteBytesExt>(&self, mut encoder: &mut Encoder<W>) -> FidoResult<()> {
|
||||||
encoder.writer().write_u8(0x01).context(
|
encoder
|
||||||
FidoErrorKind::CborEncode,
|
.writer()
|
||||||
)?; // authenticatorMakeCredential
|
.write_u8(0x01)
|
||||||
|
.context(FidoErrorKind::CborEncode)?; // authenticatorMakeCredential
|
||||||
let mut length = 4;
|
let mut length = 4;
|
||||||
length += !self.exclude_list.is_empty() as usize;
|
length += !self.exclude_list.is_empty() as usize;
|
||||||
length += !self.extensions.is_empty() as usize;
|
length += !self.extensions.is_empty() as usize;
|
||||||
length += self.options.is_some() as usize;
|
length += self
|
||||||
|
.options
|
||||||
|
.as_ref()
|
||||||
|
.map(|opt| opt.encoded())
|
||||||
|
.unwrap_or(false) as usize;
|
||||||
length += self.pin_auth.is_some() as usize;
|
length += self.pin_auth.is_some() as usize;
|
||||||
length += self.pin_protocol.is_some() as usize;
|
length += self.pin_protocol.is_some() as usize;
|
||||||
encoder.object(length)?;
|
encoder.object(length)?;
|
||||||
@ -146,7 +150,7 @@ impl MakeCredentialResponse {
|
|||||||
pub fn decode<R: ReadBytesExt>(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(status))?
|
Err(FidoErrorKind::CborError(CborErrorCode::from(status)))?
|
||||||
}
|
}
|
||||||
let mut decoder = Decoder::new(Config::default(), reader);
|
let mut decoder = Decoder::new(Config::default(), reader);
|
||||||
let mut response = MakeCredentialResponse::default();
|
let mut response = MakeCredentialResponse::default();
|
||||||
@ -176,13 +180,18 @@ pub struct GetAssertionRequest<'a> {
|
|||||||
|
|
||||||
impl<'a> GetAssertionRequest<'a> {
|
impl<'a> GetAssertionRequest<'a> {
|
||||||
pub fn encode<W: WriteBytesExt>(&self, mut encoder: &mut Encoder<W>) -> FidoResult<()> {
|
pub fn encode<W: WriteBytesExt>(&self, mut encoder: &mut Encoder<W>) -> FidoResult<()> {
|
||||||
encoder.writer().write_u8(0x02).context(
|
encoder
|
||||||
FidoErrorKind::CborEncode,
|
.writer()
|
||||||
)?; // authenticatorGetAssertion
|
.write_u8(0x02)
|
||||||
|
.context(FidoErrorKind::CborEncode)?; // authenticatorGetAssertion
|
||||||
let mut length = 2;
|
let mut length = 2;
|
||||||
length += !self.allow_list.is_empty() as usize;
|
length += !self.allow_list.is_empty() as usize;
|
||||||
length += !self.extensions.is_empty() as usize;
|
length += !self.extensions.is_empty() as usize;
|
||||||
length += self.options.is_some() as usize;
|
length += self
|
||||||
|
.options
|
||||||
|
.as_ref()
|
||||||
|
.map(|opt| opt.encoded())
|
||||||
|
.unwrap_or(false) as usize;
|
||||||
length += self.pin_auth.is_some() as usize;
|
length += self.pin_auth.is_some() as usize;
|
||||||
length += self.pin_protocol.is_some() as usize;
|
length += self.pin_protocol.is_some() as usize;
|
||||||
encoder.object(length)?;
|
encoder.object(length)?;
|
||||||
@ -236,7 +245,7 @@ impl GetAssertionResponse {
|
|||||||
pub fn decode<R: ReadBytesExt>(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(status))?
|
Err(FidoErrorKind::CborError(CborErrorCode::from(status)))?
|
||||||
}
|
}
|
||||||
let mut decoder = Decoder::new(Config::default(), reader);
|
let mut decoder = Decoder::new(Config::default(), reader);
|
||||||
let mut response = GetAssertionResponse::default();
|
let mut response = GetAssertionResponse::default();
|
||||||
@ -269,10 +278,10 @@ pub struct GetInfoResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl GetInfoResponse {
|
impl GetInfoResponse {
|
||||||
pub fn decode<R: ReadBytesExt>(mut reader: R) -> FidoResult<Self> {
|
pub fn decode<R: ReadBytesExt + Skip>(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(status))?
|
Err(FidoErrorKind::CborError(CborErrorCode::from(status)))?
|
||||||
}
|
}
|
||||||
let mut decoder = Decoder::new(Config::default(), reader);
|
let mut decoder = Decoder::new(Config::default(), reader);
|
||||||
let mut response = GetInfoResponse::default();
|
let mut response = GetInfoResponse::default();
|
||||||
@ -296,7 +305,7 @@ impl GetInfoResponse {
|
|||||||
response.pin_protocols.push(decoder.u8()?);
|
response.pin_protocols.push(decoder.u8()?);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => continue,
|
_ => decoder.skip()?,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(response)
|
Ok(response)
|
||||||
@ -315,9 +324,10 @@ pub struct ClientPinRequest<'a> {
|
|||||||
|
|
||||||
impl<'a> ClientPinRequest<'a> {
|
impl<'a> ClientPinRequest<'a> {
|
||||||
pub fn encode<W: WriteBytesExt>(&self, encoder: &mut Encoder<W>) -> FidoResult<()> {
|
pub fn encode<W: WriteBytesExt>(&self, encoder: &mut Encoder<W>) -> FidoResult<()> {
|
||||||
encoder.writer().write_u8(0x06).context(
|
encoder
|
||||||
FidoErrorKind::CborEncode,
|
.writer()
|
||||||
)?; // authenticatorClientPIN
|
.write_u8(0x06)
|
||||||
|
.context(FidoErrorKind::CborEncode)?; // authenticatorClientPIN
|
||||||
let mut length = 2;
|
let mut length = 2;
|
||||||
length += self.key_agreement.is_some() as usize;
|
length += self.key_agreement.is_some() as usize;
|
||||||
length += self.pin_auth.is_some() as usize;
|
length += self.pin_auth.is_some() as usize;
|
||||||
@ -359,7 +369,7 @@ impl ClientPinResponse {
|
|||||||
pub fn decode<R: ReadBytesExt>(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(status))?
|
Err(FidoErrorKind::CborError(CborErrorCode::from(status)))?
|
||||||
}
|
}
|
||||||
let mut decoder = Decoder::new(Config::default(), reader);
|
let mut decoder = Decoder::new(Config::default(), reader);
|
||||||
let mut response = ClientPinResponse::default();
|
let mut response = ClientPinResponse::default();
|
||||||
@ -383,7 +393,6 @@ impl ClientPinResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct OptionsInfo {
|
pub struct OptionsInfo {
|
||||||
pub plat: bool,
|
pub plat: bool,
|
||||||
@ -415,7 +424,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)
|
||||||
@ -439,21 +450,28 @@ impl AuthenticatorData {
|
|||||||
let flags = bytes[32];
|
let flags = bytes[32];
|
||||||
data.up = (flags & 0x01) == 0x01;
|
data.up = (flags & 0x01) == 0x01;
|
||||||
data.uv = (flags & 0x02) == 0x02;
|
data.uv = (flags & 0x02) == 0x02;
|
||||||
|
let is_attested = (flags & 0x40) == 0x40;
|
||||||
|
let has_extension_data = (flags & 0x80) == 0x80;
|
||||||
data.sign_count = BigEndian::read_u32(&bytes[33..37]);
|
data.sign_count = BigEndian::read_u32(&bytes[33..37]);
|
||||||
if bytes.len() < 38 {
|
if bytes.len() < 38 {
|
||||||
return Ok(data);
|
return Ok(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut cur = Cursor::new(&bytes[37..]);
|
let mut cur = Cursor::new(&bytes[37..]);
|
||||||
let attested_credential_data = AttestedCredentialData::from_bytes(&mut cur)?;
|
if is_attested {
|
||||||
data.attested_credential_data = attested_credential_data;
|
let attested_credential_data = AttestedCredentialData::from_bytes(&mut cur)?;
|
||||||
if cur.position() >= (bytes.len() - 37) as u64 {
|
data.attested_credential_data = attested_credential_data;
|
||||||
return Ok(data);
|
if cur.position() >= (bytes.len() - 37) as u64 {
|
||||||
|
return Ok(data);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let mut decoder = GenericDecoder::new(Config::default(), cur);
|
if has_extension_data {
|
||||||
for _ in 0..decoder.borrow_mut().object()? {
|
let mut decoder = GenericDecoder::new(Config::default(), cur);
|
||||||
let key = decoder.borrow_mut().text()?;
|
for _ in 0..decoder.borrow_mut().object()? {
|
||||||
let value = decoder.value()?;
|
let key = decoder.borrow_mut().text()?;
|
||||||
data.extensions.insert(key.to_string(), value);
|
let value = decoder.value()?;
|
||||||
|
data.extensions.insert(key.to_string(), value);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(data)
|
Ok(data)
|
||||||
}
|
}
|
||||||
@ -494,15 +512,15 @@ impl P256Key {
|
|||||||
if cose.key_type != 2 || cose.algorithm != -7 {
|
if cose.key_type != 2 || cose.algorithm != -7 {
|
||||||
Err(FidoErrorKind::KeyType)?
|
Err(FidoErrorKind::KeyType)?
|
||||||
}
|
}
|
||||||
if let (Some(Value::U8(curve)),
|
if let (
|
||||||
Some(Value::Bytes(value::Bytes::Bytes(x))),
|
Some(Value::U8(curve)),
|
||||||
Some(Value::Bytes(value::Bytes::Bytes(y)))) =
|
Some(Value::Bytes(value::Bytes::Bytes(x))),
|
||||||
(
|
Some(Value::Bytes(value::Bytes::Bytes(y))),
|
||||||
cose.parameters.get(&-1),
|
) = (
|
||||||
cose.parameters.get(&-2),
|
cose.parameters.get(&-1),
|
||||||
cose.parameters.get(&-3),
|
cose.parameters.get(&-2),
|
||||||
)
|
cose.parameters.get(&-3),
|
||||||
{
|
) {
|
||||||
if *curve != 1 {
|
if *curve != 1 {
|
||||||
Err(FidoErrorKind::KeyType)?
|
Err(FidoErrorKind::KeyType)?
|
||||||
}
|
}
|
||||||
@ -532,9 +550,10 @@ impl P256Key {
|
|||||||
(-1, Value::U8(1)),
|
(-1, Value::U8(1)),
|
||||||
(-2, Value::Bytes(value::Bytes::Bytes(self.x.to_vec()))),
|
(-2, Value::Bytes(value::Bytes::Bytes(self.x.to_vec()))),
|
||||||
(-3, Value::Bytes(value::Bytes::Bytes(self.y.to_vec()))),
|
(-3, Value::Bytes(value::Bytes::Bytes(self.y.to_vec()))),
|
||||||
].iter()
|
]
|
||||||
.cloned()
|
.iter()
|
||||||
.collect(),
|
.cloned()
|
||||||
|
.collect(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -579,14 +598,45 @@ 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.borrow_mut().i16()? {
|
match generic.value()? {
|
||||||
0x01 => cose_key.key_type = generic.borrow_mut().u16()?,
|
Value::Text(value::Text::Text(text)) => match &text[..] {
|
||||||
0x02 => cose_key.algorithm = generic.borrow_mut().i32()?,
|
"type" => {
|
||||||
key if key < 0 => {
|
cose_key.key_type = match generic.value()? {
|
||||||
cose_key.parameters.insert(key, generic.value()?);
|
Value::Text(value::Text::Text(type_)) if &type_ == "public-key" => 0u16,
|
||||||
|
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 => {
|
||||||
generic.value()?; // skip unknown parameter
|
(unknown, generic.value()?); // skip unknown parameter
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -684,15 +734,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")?;
|
||||||
@ -702,6 +753,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(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,15 +4,16 @@
|
|||||||
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
|
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
|
||||||
// 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 ring::{agreement, rand, digest, hmac, signature};
|
|
||||||
use ring::error::Unspecified;
|
|
||||||
use untrusted::Input;
|
|
||||||
use rust_crypto::blockmodes::NoPadding;
|
|
||||||
use rust_crypto::aes;
|
|
||||||
use rust_crypto::buffer::{RefReadBuffer, RefWriteBuffer};
|
|
||||||
use failure::ResultExt;
|
|
||||||
use super::cbor::{CoseKey, P256Key};
|
use super::cbor::{CoseKey, P256Key};
|
||||||
use super::error::*;
|
use super::error::*;
|
||||||
|
use failure::ResultExt;
|
||||||
|
use ring::error::Unspecified;
|
||||||
|
use ring::{agreement, digest, hmac, rand, signature};
|
||||||
|
use rust_crypto::aes;
|
||||||
|
use rust_crypto::blockmodes::NoPadding;
|
||||||
|
use rust_crypto::buffer::{RefReadBuffer, RefWriteBuffer};
|
||||||
|
use rust_crypto::symmetriccipher::{Decryptor, Encryptor};
|
||||||
|
use untrusted::Input;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct SharedSecret {
|
pub struct SharedSecret {
|
||||||
@ -26,9 +27,9 @@ impl SharedSecret {
|
|||||||
let private = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &rng)
|
let private = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &rng)
|
||||||
.context(FidoErrorKind::GenerateKey)?;
|
.context(FidoErrorKind::GenerateKey)?;
|
||||||
let public = &mut [0u8; agreement::PUBLIC_KEY_MAX_LEN][..private.public_key_len()];
|
let public = &mut [0u8; agreement::PUBLIC_KEY_MAX_LEN][..private.public_key_len()];
|
||||||
private.compute_public_key(public).context(
|
private
|
||||||
FidoErrorKind::GenerateKey,
|
.compute_public_key(public)
|
||||||
)?;
|
.context(FidoErrorKind::GenerateKey)?;
|
||||||
let peer = P256Key::from_cose(peer_key)
|
let peer = P256Key::from_cose(peer_key)
|
||||||
.context(FidoErrorKind::ParsePublic)?
|
.context(FidoErrorKind::ParsePublic)?
|
||||||
.bytes();
|
.bytes();
|
||||||
@ -39,7 +40,8 @@ impl SharedSecret {
|
|||||||
peer,
|
peer,
|
||||||
Unspecified,
|
Unspecified,
|
||||||
|material| Ok(digest::digest(&digest::SHA256, material)),
|
|material| Ok(digest::digest(&digest::SHA256, material)),
|
||||||
).context(FidoErrorKind::GenerateSecret)?;
|
)
|
||||||
|
.context(FidoErrorKind::GenerateSecret)?;
|
||||||
let mut res = SharedSecret {
|
let mut res = SharedSecret {
|
||||||
public_key: P256Key::from_bytes(&public)
|
public_key: P256Key::from_bytes(&public)
|
||||||
.context(FidoErrorKind::ParsePublic)?
|
.context(FidoErrorKind::ParsePublic)?
|
||||||
@ -50,42 +52,46 @@ impl SharedSecret {
|
|||||||
Ok(res)
|
Ok(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn encrypt_pin(&self, pin: &str) -> FidoResult<[u8; 16]> {
|
pub fn encryptor(&self) -> Box<dyn Encryptor + 'static> {
|
||||||
let mut encryptor = aes::cbc_encryptor(
|
aes::cbc_encryptor(
|
||||||
aes::KeySize::KeySize256,
|
aes::KeySize::KeySize256,
|
||||||
&self.shared_secret,
|
&self.shared_secret,
|
||||||
&[0u8; 16],
|
&[0u8; 16],
|
||||||
NoPadding,
|
NoPadding,
|
||||||
);
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encrypt_pin(&self, pin: &str) -> FidoResult<[u8; 16]> {
|
||||||
|
let mut encryptor = self.encryptor();
|
||||||
let pin_bytes = pin.as_bytes();
|
let pin_bytes = pin.as_bytes();
|
||||||
let hash = digest::digest(&digest::SHA256, &pin_bytes);
|
let hash = digest::digest(&digest::SHA256, &pin_bytes);
|
||||||
let in_bytes = &hash.as_ref()[0..16];
|
let in_bytes = &hash.as_ref()[0..16];
|
||||||
let mut input = RefReadBuffer::new(&in_bytes);
|
let mut input = RefReadBuffer::new(&in_bytes);
|
||||||
let mut out_bytes = [0; 16];
|
let mut out_bytes = [0; 16];
|
||||||
let mut output = RefWriteBuffer::new(&mut out_bytes);
|
let mut output = RefWriteBuffer::new(&mut out_bytes);
|
||||||
encryptor.encrypt(&mut input, &mut output, true).map_err(
|
encryptor
|
||||||
|_| {
|
.encrypt(&mut input, &mut output, true)
|
||||||
FidoErrorKind::EncryptPin
|
.map_err(|_| FidoErrorKind::EncryptPin)?;
|
||||||
},
|
|
||||||
)?;
|
|
||||||
Ok(out_bytes)
|
Ok(out_bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn decrypt_token(&self, data: &mut [u8]) -> FidoResult<PinToken> {
|
pub fn decryptor(&self) -> Box<dyn Decryptor + 'static> {
|
||||||
let mut decryptor = aes::cbc_decryptor(
|
aes::cbc_decryptor(
|
||||||
aes::KeySize::KeySize256,
|
aes::KeySize::KeySize256,
|
||||||
&self.shared_secret,
|
&self.shared_secret,
|
||||||
&[0u8; 16],
|
&[0u8; 16],
|
||||||
NoPadding,
|
NoPadding,
|
||||||
);
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decrypt_token(&self, data: &mut [u8]) -> FidoResult<PinToken> {
|
||||||
|
let mut decryptor = self.decryptor();
|
||||||
let mut input = RefReadBuffer::new(data);
|
let mut input = RefReadBuffer::new(data);
|
||||||
let mut out_bytes = [0; 16];
|
let mut out_bytes = [0; 16];
|
||||||
let mut output = RefWriteBuffer::new(&mut out_bytes);
|
let mut output = RefWriteBuffer::new(&mut out_bytes);
|
||||||
decryptor.decrypt(&mut input, &mut output, true).map_err(
|
decryptor
|
||||||
|_| {
|
.decrypt(&mut input, &mut output, true)
|
||||||
FidoErrorKind::DecryptPin
|
.map_err(|_| FidoErrorKind::DecryptPin)?;
|
||||||
},
|
|
||||||
)?;
|
|
||||||
Ok(PinToken(hmac::SigningKey::new(&digest::SHA256, &out_bytes)))
|
Ok(PinToken(hmac::SigningKey::new(&digest::SHA256, &out_bytes)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -119,5 +125,6 @@ pub fn verify_signature(
|
|||||||
public_key,
|
public_key,
|
||||||
msg,
|
msg,
|
||||||
signature,
|
signature,
|
||||||
).is_ok()
|
)
|
||||||
|
.is_ok()
|
||||||
}
|
}
|
||||||
|
78
src/error.rs
78
src/error.rs
@ -4,21 +4,53 @@
|
|||||||
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
|
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
|
||||||
// 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::{EncodeError, DecodeError};
|
use cbor_codec::{DecodeError, EncodeError};
|
||||||
|
use failure::_core::fmt::{Error, Formatter};
|
||||||
|
use failure::_core::option::Option;
|
||||||
|
use failure::{Backtrace, Context, Fail};
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
use failure::{Context, Backtrace, Fail};
|
|
||||||
|
|
||||||
pub type FidoResult<T> = Result<T, FidoError>;
|
pub type FidoResult<T> = Result<T, FidoError>;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct FidoError(Context<FidoErrorKind>);
|
pub struct FidoError(Context<FidoErrorKind>);
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone, Fail, Eq, PartialEq)]
|
||||||
|
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.")]
|
||||||
@ -41,10 +73,12 @@ 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: 0x{:x}", _0)]
|
#[fail(display = "Device returned error: {}", _0)]
|
||||||
CborError(u8),
|
CborError(CborErrorCode),
|
||||||
#[fail(display = "Device does not support FIDO2")]
|
#[fail(display = "Device does not support FIDO2")]
|
||||||
DeviceUnsupported,
|
DeviceUnsupported,
|
||||||
#[fail(display = "This operating requires a PIN but none was provided.")]
|
#[fail(display = "This operating requires a PIN but none was provided.")]
|
||||||
@ -52,7 +86,7 @@ pub enum FidoErrorKind {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Fail for FidoError {
|
impl Fail for FidoError {
|
||||||
fn cause(&self) -> Option<&Fail> {
|
fn cause(&self) -> Option<&dyn Fail> {
|
||||||
self.0.cause()
|
self.0.cause()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -99,3 +133,33 @@ impl From<DecodeError> for FidoError {
|
|||||||
FidoError(err.context(FidoErrorKind::CborDecode))
|
FidoError(err.context(FidoErrorKind::CborDecode))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<u8> for CborErrorCode {
|
||||||
|
fn from(code: u8) -> Self {
|
||||||
|
Self(code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for CborErrorCode {
|
||||||
|
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
|
||||||
|
if let Some((code, _name, desc)) = self.detail() {
|
||||||
|
write!(f, "CborError: 0x{:x?}: {}", code, desc)?;
|
||||||
|
} else {
|
||||||
|
write!(f, "CborError: 0x{:x?}: unknown", self.code())?;
|
||||||
|
}
|
||||||
|
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."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
206
src/extensions/hmac.rs
Normal file
206
src/extensions/hmac.rs
Normal file
@ -0,0 +1,206 @@
|
|||||||
|
use crate::{FidoAssertionRequest, FidoAssertionRequestBuilder, FidoCredentialRequest};
|
||||||
|
use crate::{FidoCredential, FidoDevice, FidoErrorKind, FidoResult};
|
||||||
|
use cbor_codec::value::{Bytes, Int, Key, Text, Value};
|
||||||
|
use cbor_codec::Encoder;
|
||||||
|
use cbor_codec::{Config, GenericDecoder};
|
||||||
|
use rust_crypto::buffer::{RefReadBuffer, RefWriteBuffer};
|
||||||
|
use rust_crypto::digest::Digest;
|
||||||
|
use rust_crypto::hmac::Hmac;
|
||||||
|
use rust_crypto::mac::Mac;
|
||||||
|
use rust_crypto::sha2::Sha256;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::io::Cursor;
|
||||||
|
|
||||||
|
pub trait HmacExtension {
|
||||||
|
fn extension_name() -> &'static str {
|
||||||
|
"hmac-secret"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extension_input() -> &'static Value {
|
||||||
|
&Value::Bool(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates data for the extension field as part of the assertion request
|
||||||
|
fn get_dict(&mut self, salt: &[u8; 32], salt2: Option<&[u8; 32]>) -> FidoResult<Value> {
|
||||||
|
let mut map = BTreeMap::new();
|
||||||
|
map.insert(
|
||||||
|
Key::Text(Text::Text(
|
||||||
|
<Self as HmacExtension>::extension_name().to_owned(),
|
||||||
|
)),
|
||||||
|
self.get_data(salt, salt2)?,
|
||||||
|
);
|
||||||
|
Ok(Value::Map(map))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_data(&mut self, salt: &[u8; 32], salt2: Option<&[u8; 32]>) -> FidoResult<Value>;
|
||||||
|
|
||||||
|
/// Convenience function to create an credential which includes extension specific data
|
||||||
|
/// Use `FidoDevice::make_credential` if you need more control
|
||||||
|
fn make_hmac_credential(
|
||||||
|
&mut self,
|
||||||
|
request: &FidoCredentialRequest,
|
||||||
|
) -> FidoResult<FidoCredential>;
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
/// to ensure that your salt will fit 32 bytes.
|
||||||
|
/// Salt(s), credential and the authenticator internal secret will then be used to
|
||||||
|
/// generate a secret.
|
||||||
|
///
|
||||||
|
/// This method will return the secret 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.
|
||||||
|
///
|
||||||
|
fn get_hmac_assertion<'a: 'b, 'b>(
|
||||||
|
&mut self,
|
||||||
|
assertion: &FidoAssertionRequest<'a, 'b>,
|
||||||
|
salt: &[u8; 32],
|
||||||
|
salt2: Option<&[u8; 32]>,
|
||||||
|
) -> FidoResult<(&'a FidoCredential, ([u8; 32], Option<[u8; 32]>))>;
|
||||||
|
|
||||||
|
/// Convenience function for `get_hmac_assertion` that will accept arbitrary
|
||||||
|
/// lenght input which will then be hashed and passed on
|
||||||
|
fn hmac_challange(
|
||||||
|
&mut self,
|
||||||
|
rp_id: &str,
|
||||||
|
credential: &FidoCredential,
|
||||||
|
input: &[u8],
|
||||||
|
) -> FidoResult<[u8; 32]> {
|
||||||
|
let mut salt = [0u8; 32];
|
||||||
|
let mut digest = Sha256::new();
|
||||||
|
digest.input(input);
|
||||||
|
digest.result(&mut salt);
|
||||||
|
self.get_hmac_assertion(
|
||||||
|
&FidoAssertionRequestBuilder::default()
|
||||||
|
.rp_id(rp_id)
|
||||||
|
.credential(&credential)
|
||||||
|
.build()
|
||||||
|
.unwrap(),
|
||||||
|
&salt,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.map(|(_cred, secret)| secret.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HmacExtension for FidoDevice {
|
||||||
|
fn get_data(&mut self, salt: &[u8; 32], salt2: Option<&[u8; 32]>) -> FidoResult<Value> {
|
||||||
|
let shared_secret = self.shared_secret.as_ref().unwrap();
|
||||||
|
let mut encryptor = shared_secret.encryptor();
|
||||||
|
let mut salt_enc = [0u8; 64];
|
||||||
|
let mut output = RefWriteBuffer::new(&mut salt_enc);
|
||||||
|
let mut encrypt = || {
|
||||||
|
encryptor.encrypt(&mut RefReadBuffer::new(salt), &mut output, salt2.is_none())?;
|
||||||
|
if let Some(salt2) = salt2 {
|
||||||
|
encryptor
|
||||||
|
.encrypt(&mut RefReadBuffer::new(salt2), &mut output, true)
|
||||||
|
.map(|_| ())
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
encrypt().map_err(|_| FidoErrorKind::Io)?;
|
||||||
|
|
||||||
|
let key_agreement = || {
|
||||||
|
let mut cur = Cursor::new(Vec::new());
|
||||||
|
let mut encoder = Encoder::new(&mut cur);
|
||||||
|
shared_secret.public_key.encode(&mut encoder).unwrap();
|
||||||
|
cur.set_position(0);
|
||||||
|
let mut dec = GenericDecoder::new(Config::default(), cur);
|
||||||
|
dec.value()
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut map = BTreeMap::new();
|
||||||
|
map.insert(
|
||||||
|
Key::Int(Int::from_i64(0x01)),
|
||||||
|
key_agreement().map_err(|_| FidoErrorKind::Io)?,
|
||||||
|
);
|
||||||
|
map.insert(
|
||||||
|
Key::Int(Int::from_i64(0x02)),
|
||||||
|
Value::Bytes(Bytes::Bytes(
|
||||||
|
salt_enc[0..((salt2.is_some() as usize + 1) * 32)].to_vec(),
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut salt_hmac = Hmac::new(Sha256::new(), &shared_secret.shared_secret);
|
||||||
|
salt_hmac.input(&salt_enc[0..((salt2.is_some() as usize + 1) * 32)]);
|
||||||
|
|
||||||
|
let mut authed_salt_enc = [0u8; 32];
|
||||||
|
authed_salt_enc.copy_from_slice(salt_hmac.result().code());
|
||||||
|
|
||||||
|
map.insert(
|
||||||
|
Key::Int(Int::from_i64(0x03)),
|
||||||
|
Value::Bytes(Bytes::Bytes(authed_salt_enc[0..16].to_vec())),
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(Value::Map(map))
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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 shared_secret = self.shared_secret.as_ref().unwrap();
|
||||||
|
let mut decryptor = shared_secret.decryptor();
|
||||||
|
let mut hmac_secret_combined = [0u8; 64];
|
||||||
|
let _output = RefWriteBuffer::new(&mut hmac_secret_combined);
|
||||||
|
let hmac_secret_enc = match auth_data
|
||||||
|
.extensions
|
||||||
|
.get(<Self as HmacExtension>::extension_name())
|
||||||
|
.ok_or(FidoErrorKind::CborDecode)?
|
||||||
|
{
|
||||||
|
Value::Bytes(hmac_ciphered) => Ok(match hmac_ciphered {
|
||||||
|
Bytes::Bytes(hmac_ciphered) => hmac_ciphered.to_vec(),
|
||||||
|
Bytes::Chunks(hmac_ciphered) => hmac_ciphered.iter().fold(Vec::new(), |s, i| {
|
||||||
|
let mut s = s;
|
||||||
|
s.extend_from_slice(&i);
|
||||||
|
s
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
_ => Err(FidoErrorKind::CborDecode),
|
||||||
|
}?;
|
||||||
|
let mut hmac_secret = [0u8; 64];
|
||||||
|
decryptor
|
||||||
|
.decrypt(
|
||||||
|
&mut RefReadBuffer::new(&hmac_secret_enc),
|
||||||
|
&mut RefWriteBuffer::new(&mut hmac_secret),
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
.map_err(|_| FidoErrorKind::ReadPacket)?;
|
||||||
|
let mut hmac_secret_0 = [0u8; 32];
|
||||||
|
let mut hmac_secret_1 = [0u8; 32];
|
||||||
|
hmac_secret_0.copy_from_slice(&hmac_secret[0..32]);
|
||||||
|
hmac_secret_1.copy_from_slice(&hmac_secret[32..]);
|
||||||
|
let cred = request
|
||||||
|
.credentials
|
||||||
|
.into_iter()
|
||||||
|
.find(|c| c.id == cred.id)
|
||||||
|
.unwrap();
|
||||||
|
Ok((cred, (hmac_secret_0, salt2.and(Some(hmac_secret_1)))))
|
||||||
|
}
|
||||||
|
}
|
2
src/extensions/mod.rs
Normal file
2
src/extensions/mod.rs
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
pub mod hmac;
|
||||||
|
pub use hmac::*;
|
@ -4,11 +4,11 @@
|
|||||||
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
|
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
|
||||||
// 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 std::io;
|
|
||||||
use std::fs;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
use byteorder::{ByteOrder, LittleEndian};
|
|
||||||
pub use super::hid_common::*;
|
pub use super::hid_common::*;
|
||||||
|
use byteorder::{ByteOrder, LittleEndian};
|
||||||
|
use std::fs;
|
||||||
|
use std::io;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
static REPORT_DESCRIPTOR_KEY_MASK: u8 = 0xfc;
|
static REPORT_DESCRIPTOR_KEY_MASK: u8 = 0xfc;
|
||||||
static LONG_ITEM_ENCODING: u8 = 0xfe;
|
static LONG_ITEM_ENCODING: u8 = 0xfe;
|
||||||
@ -18,9 +18,9 @@ static REPORT_SIZE: u8 = 0x74;
|
|||||||
|
|
||||||
pub fn enumerate() -> io::Result<impl Iterator<Item = DeviceInfo>> {
|
pub fn enumerate() -> io::Result<impl Iterator<Item = DeviceInfo>> {
|
||||||
fs::read_dir("/sys/class/hidraw").map(|entries| {
|
fs::read_dir("/sys/class/hidraw").map(|entries| {
|
||||||
entries.filter_map(|entry| entry.ok()).filter_map(|entry| {
|
entries
|
||||||
path_to_device(&entry.path()).ok()
|
.filter_map(|entry| entry.ok())
|
||||||
})
|
.filter_map(|entry| path_to_device(&entry.path()).ok())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
504
src/lib.rs
504
src/lib.rs
@ -9,66 +9,76 @@
|
|||||||
//! # 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)?;
|
|
||||||
//!
|
//!
|
||||||
//! // This can be omitted if the FIDO device is not configured with a PIN.
|
//!use ctap_hmac::*;
|
||||||
//! let pin = "test";
|
//!let device_info = get_devices()?.next().expect("no device connected");
|
||||||
//! device.unlock(pin)?;
|
//!let mut device = FidoDevice::new(&device_info)?;
|
||||||
//!
|
//!
|
||||||
//! // In a real application these values would come from the requesting app.
|
//!// This can be omitted if the FIDO device is not configured with a PIN.
|
||||||
//! let rp_id = "rp_id";
|
//!let pin = "test";
|
||||||
//! let user_id = [0];
|
//!device.unlock(pin)?;
|
||||||
//! let user_name = "user_name";
|
//!
|
||||||
//! let client_data_hash = [0; 32];
|
//!// In a real application these values would come from the requesting app.
|
||||||
//! let cred = device.make_credential(
|
//!let cred_request = FidoCredentialRequestBuilder::default()
|
||||||
//! rp_id,
|
//! .rp_id("rp_id")
|
||||||
//! &user_id,
|
//! .user_name("user_name")
|
||||||
//! user_name,
|
//! .build().unwrap();
|
||||||
//! &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.
|
||||||
|
//!let result = device.get_assertion(&assertion_request);
|
||||||
//!
|
//!
|
||||||
//! // In a real application the credential would be stored and used later.
|
|
||||||
//! let result = device.get_assertion(&cred, &client_data_hash);
|
|
||||||
//! # Ok(())
|
//! # Ok(())
|
||||||
//! # }
|
//! # }
|
||||||
|
|
||||||
#![allow(dead_code)]
|
#![allow(dead_code)]
|
||||||
|
|
||||||
extern crate rand;
|
|
||||||
extern crate failure;
|
extern crate failure;
|
||||||
|
extern crate rand;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate failure_derive;
|
extern crate failure_derive;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate num_derive;
|
extern crate num_derive;
|
||||||
extern crate num_traits;
|
#[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 num_traits;
|
||||||
extern crate ring;
|
extern crate ring;
|
||||||
extern crate untrusted;
|
extern crate untrusted;
|
||||||
extern crate crypto as rust_crypto;
|
|
||||||
|
|
||||||
mod packet;
|
mod cbor;
|
||||||
|
mod crypto;
|
||||||
|
mod error;
|
||||||
|
pub mod extensions;
|
||||||
mod hid_common;
|
mod hid_common;
|
||||||
mod hid_linux;
|
mod hid_linux;
|
||||||
mod error;
|
mod packet;
|
||||||
mod crypto;
|
mod util;
|
||||||
mod cbor;
|
|
||||||
|
|
||||||
use std::cmp;
|
use std::cmp;
|
||||||
use std::u8;
|
|
||||||
use std::u16;
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io::{Write, Cursor};
|
use std::io::{Cursor, Write};
|
||||||
|
use std::u16;
|
||||||
|
use std::u8;
|
||||||
|
|
||||||
use failure::{Fail, ResultExt};
|
use self::cbor::{AuthenticatorOptions, PublicKeyCredentialDescriptor};
|
||||||
use rand::prelude::*;
|
pub use self::error::*;
|
||||||
use num_traits::FromPrimitive;
|
|
||||||
use self::hid_linux as hid;
|
use self::hid_linux as hid;
|
||||||
use self::packet::CtapCommand;
|
use self::packet::CtapCommand;
|
||||||
pub use self::error::*;
|
pub use self::util::*;
|
||||||
|
use crate::cbor::{AuthenticatorData, GetAssertionRequest};
|
||||||
|
use failure::{Fail, ResultExt};
|
||||||
|
use num_traits::FromPrimitive;
|
||||||
|
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];
|
||||||
|
|
||||||
@ -76,23 +86,18 @@ static BROADCAST_CID: [u8; 4] = [0xff, 0xff, 0xff, 0xff];
|
|||||||
pub fn get_devices() -> FidoResult<impl Iterator<Item = hid::DeviceInfo>> {
|
pub fn get_devices() -> FidoResult<impl Iterator<Item = hid::DeviceInfo>> {
|
||||||
hid::enumerate()
|
hid::enumerate()
|
||||||
.context(FidoErrorKind::Io)
|
.context(FidoErrorKind::Io)
|
||||||
.map(|devices| {
|
.map(|devices| devices.filter(|dev| dev.usage_page == 0xf1d0 && dev.usage == 0x21))
|
||||||
devices.filter(|dev| dev.usage_page == 0xf1d0 && dev.usage == 0x21)
|
|
||||||
})
|
|
||||||
.map_err(From::from)
|
.map_err(From::from)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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,
|
||||||
@ -104,6 +109,145 @@ pub struct FidoDevice {
|
|||||||
aaguid: [u8; 16],
|
aaguid: [u8; 16],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct FidoCancelHandle {
|
||||||
|
device: fs::File,
|
||||||
|
packet_size: u16,
|
||||||
|
channel_id: [u8; 4],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FidoCancelHandle {
|
||||||
|
pub fn cancel(&mut self) -> FidoResult<()> {
|
||||||
|
let payload = &[1u8];
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
/// Open and initialize a given device. DeviceInfo is provided by the `get_devices`
|
/// Open and initialize a given device. DeviceInfo is provided by the `get_devices`
|
||||||
/// function. This method will allocate a channel for this application, verify that
|
/// function. This method will allocate a channel for this application, verify that
|
||||||
@ -143,10 +287,15 @@ impl FidoDevice {
|
|||||||
cbor::Response::GetInfo(resp) => resp,
|
cbor::Response::GetInfo(resp) => resp,
|
||||||
_ => Err(FidoErrorKind::CborDecode)?,
|
_ => Err(FidoErrorKind::CborDecode)?,
|
||||||
};
|
};
|
||||||
if !response.versions.iter().any(|ver| ver == "FIDO_2_0") {
|
if !response.versions.iter().any(|ver| ["FIDO_2_0", "FIDO_2_1_PRE"].contains(&ver.as_str())) {
|
||||||
Err(FidoErrorKind::DeviceUnsupported)?
|
Err(FidoErrorKind::DeviceUnsupported)?
|
||||||
}
|
}
|
||||||
if !response.pin_protocols.iter().any(|ver| *ver == 1) {
|
// Require pin protocol version 1, only if pin-protocol is supported at all
|
||||||
|
if !response
|
||||||
|
.pin_protocols
|
||||||
|
.iter()
|
||||||
|
.any(|ver| *ver == 1) && response.pin_protocols.len() > 0
|
||||||
|
{
|
||||||
Err(FidoErrorKind::DeviceUnsupported)?
|
Err(FidoErrorKind::DeviceUnsupported)?
|
||||||
}
|
}
|
||||||
self.needs_pin = response.options.client_pin == Some(true);
|
self.needs_pin = response.options.client_pin == Some(true);
|
||||||
@ -176,6 +325,11 @@ 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
|
||||||
@ -208,6 +362,93 @@ impl FidoDevice {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn cancel_handle(&mut self) -> FidoResult<FidoCancelHandle> {
|
||||||
|
Ok(self
|
||||||
|
.device
|
||||||
|
.try_clone()
|
||||||
|
.map(|device| FidoCancelHandle {
|
||||||
|
device,
|
||||||
|
packet_size: self.packet_size,
|
||||||
|
channel_id: self.channel_id,
|
||||||
|
})
|
||||||
|
.context(FidoErrorKind::Io)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn make_credential(
|
||||||
|
&mut self,
|
||||||
|
request: &FidoCredentialRequest<'_>,
|
||||||
|
) -> FidoResult<FidoCredential> {
|
||||||
|
let rp = cbor::PublicKeyCredentialRpEntity {
|
||||||
|
id: request.rp_id,
|
||||||
|
name: request.rp_name,
|
||||||
|
icon: request.rp_icon_url,
|
||||||
|
};
|
||||||
|
let user = cbor::PublicKeyCredentialUserEntity {
|
||||||
|
id: request.user_id,
|
||||||
|
name: request.user_name.unwrap_or(""),
|
||||||
|
icon: request.user_icon_url,
|
||||||
|
display_name: request.user_display_name,
|
||||||
|
};
|
||||||
|
|
||||||
|
let options = Some(AuthenticatorOptions {
|
||||||
|
up: false,
|
||||||
|
uv: request.uv,
|
||||||
|
rk: request.rk,
|
||||||
|
});
|
||||||
|
if self.needs_pin && self.pin_token.is_none() {
|
||||||
|
Err(FidoErrorKind::PinRequired)?
|
||||||
|
}
|
||||||
|
if request.client_data_hash.len() != 32 {
|
||||||
|
Err(FidoErrorKind::CborEncode)?
|
||||||
|
}
|
||||||
|
while self.shared_secret.is_none() {
|
||||||
|
self.init_shared_secret()?;
|
||||||
|
}
|
||||||
|
let pub_key_cred_params = [("public-key", -7)];
|
||||||
|
let pin_auth = self
|
||||||
|
.pin_token
|
||||||
|
.as_ref()
|
||||||
|
.map(|token| token.auth(&request.client_data_hash));
|
||||||
|
let request = cbor::MakeCredentialRequest {
|
||||||
|
client_data_hash: request.client_data_hash,
|
||||||
|
rp,
|
||||||
|
user,
|
||||||
|
pub_key_cred_params: &pub_key_cred_params,
|
||||||
|
exclude_list: &request
|
||||||
|
.exclude_list
|
||||||
|
.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_protocol: pin_auth.and(Some(0x01)),
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = match self.cbor(cbor::Request::MakeCredential(request))? {
|
||||||
|
cbor::Response::MakeCredential(resp) => resp,
|
||||||
|
_ => Err(FidoErrorKind::CborDecode)?,
|
||||||
|
};
|
||||||
|
let public_key = cbor::P256Key::from_cose(
|
||||||
|
&response
|
||||||
|
.auth_data
|
||||||
|
.attested_credential_data
|
||||||
|
.credential_public_key,
|
||||||
|
)?
|
||||||
|
.bytes();
|
||||||
|
Ok(FidoCredential {
|
||||||
|
id: response.auth_data.attested_credential_data.credential_id,
|
||||||
|
public_key: Some(Vec::from(&public_key[..])),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Request a new credential from the authenticator. The `rp_id` should be
|
/// 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
|
/// a stable string used to identify the party for whom the credential is
|
||||||
/// created, for convenience it will be returned with the credential.
|
/// created, for convenience it will be returned with the credential.
|
||||||
@ -221,121 +462,92 @@ 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 make_credential(
|
pub fn get_assertion<'a, 'b>(
|
||||||
&mut self,
|
&mut self,
|
||||||
rp_id: &str,
|
assertion: &FidoAssertionRequest<'a, 'b>,
|
||||||
user_id: &[u8],
|
) -> FidoResult<(&'a FidoCredential, AuthenticatorData)> {
|
||||||
user_name: &str,
|
while self.shared_secret.is_none() {
|
||||||
client_data_hash: &[u8],
|
self.init_shared_secret()?;
|
||||||
) -> 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 assertion.client_data_hash.len() != 32 {
|
||||||
Err(FidoErrorKind::CborEncode)?
|
Err(FidoErrorKind::CborEncode)?
|
||||||
}
|
}
|
||||||
let pin_auth = self.pin_token.as_ref().map(
|
let pin_auth = self
|
||||||
|token| token.auth(&client_data_hash),
|
.pin_token
|
||||||
);
|
.as_ref()
|
||||||
let rp = cbor::PublicKeyCredentialRpEntity {
|
.map(|token| token.auth(&assertion.client_data_hash));
|
||||||
id: rp_id,
|
let request = GetAssertionRequest {
|
||||||
name: None,
|
rp_id: assertion.rp_id,
|
||||||
icon: None,
|
client_data_hash: assertion.client_data_hash,
|
||||||
};
|
allow_list: &assertion
|
||||||
let user = cbor::PublicKeyCredentialUserEntity {
|
.credentials
|
||||||
id: user_id,
|
.iter()
|
||||||
name: user_name,
|
.map(|cred| PublicKeyCredentialDescriptor {
|
||||||
icon: None,
|
cred_type: "public-key".into(),
|
||||||
display_name: None,
|
id: cred.id.clone(),
|
||||||
};
|
})
|
||||||
let pub_key_cred_params = [("public-key", -7)];
|
.collect::<Vec<_>>()[..],
|
||||||
let request = cbor::MakeCredentialRequest {
|
extensions: &assertion
|
||||||
client_data_hash,
|
.extension_data
|
||||||
rp,
|
.iter()
|
||||||
user,
|
.map(|(name, data)| (*name, *data))
|
||||||
pub_key_cred_params: &pub_key_cred_params,
|
.collect::<Vec<_>>()[..],
|
||||||
exclude_list: Default::default(),
|
options: Some(AuthenticatorOptions {
|
||||||
extensions: Default::default(),
|
rk: assertion.rk,
|
||||||
options: Some(cbor::AuthenticatorOptions {
|
uv: assertion.uv,
|
||||||
rk: false,
|
up: assertion.up,
|
||||||
uv: true,
|
|
||||||
}),
|
}),
|
||||||
pin_auth,
|
pin_auth: pin_auth,
|
||||||
pin_protocol: pin_auth.and(Some(0x01)),
|
|
||||||
};
|
|
||||||
let response = match self.cbor(cbor::Request::MakeCredential(request))? {
|
|
||||||
cbor::Response::MakeCredential(resp) => resp,
|
|
||||||
_ => Err(FidoErrorKind::CborDecode)?,
|
|
||||||
};
|
|
||||||
let public_key = cbor::P256Key::from_cose(
|
|
||||||
&response
|
|
||||||
.auth_data
|
|
||||||
.attested_credential_data
|
|
||||||
.credential_public_key,
|
|
||||||
)?
|
|
||||||
.bytes();
|
|
||||||
Ok(FidoCredential {
|
|
||||||
id: response.auth_data.attested_credential_data.credential_id,
|
|
||||||
rp_id: String::from(rp_id),
|
|
||||||
public_key: Vec::from(&public_key[..]),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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.
|
|
||||||
pub fn get_assertion(
|
|
||||||
&mut self,
|
|
||||||
credential: &FidoCredential,
|
|
||||||
client_data_hash: &[u8],
|
|
||||||
) -> FidoResult<bool> {
|
|
||||||
if self.needs_pin && self.pin_token.is_none() {
|
|
||||||
Err(FidoErrorKind::PinRequired)?
|
|
||||||
}
|
|
||||||
if client_data_hash.len() != 32 {
|
|
||||||
Err(FidoErrorKind::CborEncode)?
|
|
||||||
}
|
|
||||||
let pin_auth = self.pin_token.as_ref().map(
|
|
||||||
|token| token.auth(&client_data_hash),
|
|
||||||
);
|
|
||||||
let allow_list = [
|
|
||||||
cbor::PublicKeyCredentialDescriptor {
|
|
||||||
cred_type: String::from("public-key"),
|
|
||||||
id: credential.id.clone(),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
let request = cbor::GetAssertionRequest {
|
|
||||||
rp_id: &credential.rp_id,
|
|
||||||
client_data_hash: client_data_hash,
|
|
||||||
allow_list: &allow_list,
|
|
||||||
extensions: Default::default(),
|
|
||||||
options: Some(cbor::AuthenticatorOptions {
|
|
||||||
rk: false,
|
|
||||||
uv: true,
|
|
||||||
}),
|
|
||||||
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(crypto::verify_signature(
|
let credential = assertion
|
||||||
&credential.public_key,
|
.credentials
|
||||||
&client_data_hash,
|
.iter()
|
||||||
&response.auth_data_bytes,
|
.flat_map(|cred| {
|
||||||
&response.signature,
|
response
|
||||||
))
|
.credential
|
||||||
|
.as_ref()
|
||||||
|
.filter(|rcred| rcred.id == cred.id)
|
||||||
|
.map(|_| *cred)
|
||||||
|
})
|
||||||
|
.next();
|
||||||
|
|
||||||
|
credential
|
||||||
|
.and_then(|cred| {
|
||||||
|
if cred
|
||||||
|
.public_key
|
||||||
|
.as_ref()
|
||||||
|
.map(|public_key| {
|
||||||
|
crypto::verify_signature(
|
||||||
|
&public_key,
|
||||||
|
&assertion.client_data_hash,
|
||||||
|
&response.auth_data_bytes,
|
||||||
|
&response.signature,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.unwrap_or(true)
|
||||||
|
{
|
||||||
|
Some(cred)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.ok_or(FidoError::from(FidoErrorKind::VerifySignature))
|
||||||
|
.map(|cred| (cred, response.auth_data))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cbor(&mut self, request: cbor::Request) -> FidoResult<cbor::Response> {
|
fn cbor(&mut self, request: cbor::Request) -> FidoResult<cbor::Response> {
|
||||||
let mut buf = Cursor::new(Vec::new());
|
let mut buf = Cursor::new(Vec::new());
|
||||||
request.encode(&mut buf).context(FidoErrorKind::CborEncode)?;
|
request
|
||||||
|
.encode(&mut buf)
|
||||||
|
.context(FidoErrorKind::CborEncode)?;
|
||||||
let response = self.exchange(CtapCommand::Cbor, &buf.into_inner())?;
|
let response = self.exchange(CtapCommand::Cbor, &buf.into_inner())?;
|
||||||
request
|
request
|
||||||
.decode(Cursor::new(response))
|
.decode(Cursor::new(response))
|
||||||
@ -372,11 +584,9 @@ impl FidoDevice {
|
|||||||
while first_packet.is_none() {
|
while first_packet.is_none() {
|
||||||
let packet = packet::InitPacket::from_reader(&mut self.device, 64)?;
|
let packet = packet::InitPacket::from_reader(&mut self.device, 64)?;
|
||||||
if packet.cmd == CtapCommand::Error {
|
if packet.cmd == CtapCommand::Error {
|
||||||
Err(
|
Err(packet::CtapError::from_u8(packet.payload[0])
|
||||||
packet::CtapError::from_u8(packet.payload[0])
|
.unwrap_or(packet::CtapError::Other)
|
||||||
.unwrap_or(packet::CtapError::Other)
|
.context(FidoErrorKind::ParseCtap))?
|
||||||
.context(FidoErrorKind::ParseCtap),
|
|
||||||
)?
|
|
||||||
}
|
}
|
||||||
if packet.cid == self.channel_id && &packet.cmd == cmd {
|
if packet.cid == self.channel_id && &packet.cmd == cmd {
|
||||||
first_packet = Some(packet);
|
first_packet = Some(packet);
|
||||||
|
@ -4,9 +4,9 @@
|
|||||||
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
|
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
|
||||||
// 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 num_traits::{FromPrimitive, ToPrimitive};
|
|
||||||
use failure::ResultExt;
|
|
||||||
use super::error::*;
|
use super::error::*;
|
||||||
|
use failure::ResultExt;
|
||||||
|
use num_traits::{FromPrimitive, ToPrimitive};
|
||||||
|
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
|
|
||||||
@ -81,9 +81,9 @@ pub fn write_init_packet<W: Write>(
|
|||||||
Err(FidoErrorKind::WritePacket)?
|
Err(FidoErrorKind::WritePacket)?
|
||||||
}
|
}
|
||||||
packet.resize(report_size + 1, 0);
|
packet.resize(report_size + 1, 0);
|
||||||
writer.write_all(&packet).context(
|
writer
|
||||||
FidoErrorKind::WritePacket,
|
.write_all(&packet)
|
||||||
)?;
|
.context(FidoErrorKind::WritePacket)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -98,9 +98,9 @@ impl InitPacket {
|
|||||||
pub fn from_reader<R: Read>(mut reader: R, report_size: usize) -> FidoResult<InitPacket> {
|
pub fn from_reader<R: Read>(mut reader: R, report_size: usize) -> FidoResult<InitPacket> {
|
||||||
let mut buf = Vec::with_capacity(report_size);
|
let mut buf = Vec::with_capacity(report_size);
|
||||||
buf.resize(report_size, 0);
|
buf.resize(report_size, 0);
|
||||||
reader.read_exact(&mut buf[0..report_size]).context(
|
reader
|
||||||
FidoErrorKind::ReadPacket,
|
.read_exact(&mut buf[0..report_size])
|
||||||
)?;
|
.context(FidoErrorKind::ReadPacket)?;
|
||||||
let mut cid = [0; 4];
|
let mut cid = [0; 4];
|
||||||
cid.copy_from_slice(&buf[0..4]);
|
cid.copy_from_slice(&buf[0..4]);
|
||||||
let cmd = match CtapCommand::from_u8(buf[4] ^ FRAME_INIT) {
|
let cmd = match CtapCommand::from_u8(buf[4] ^ FRAME_INIT) {
|
||||||
@ -142,9 +142,9 @@ pub fn write_cont_packet<W: Write>(
|
|||||||
Err(FidoErrorKind::WritePacket)?
|
Err(FidoErrorKind::WritePacket)?
|
||||||
}
|
}
|
||||||
packet.resize(report_size + 1, 0);
|
packet.resize(report_size + 1, 0);
|
||||||
writer.write_all(&packet).context(
|
writer
|
||||||
FidoErrorKind::WritePacket,
|
.write_all(&packet)
|
||||||
)?;
|
.context(FidoErrorKind::WritePacket)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -162,9 +162,9 @@ impl ContPacket {
|
|||||||
) -> FidoResult<ContPacket> {
|
) -> FidoResult<ContPacket> {
|
||||||
let mut buf = Vec::with_capacity(report_size);
|
let mut buf = Vec::with_capacity(report_size);
|
||||||
buf.resize(report_size, 0);
|
buf.resize(report_size, 0);
|
||||||
reader.read_exact(&mut buf[0..report_size]).context(
|
reader
|
||||||
FidoErrorKind::ReadPacket,
|
.read_exact(&mut buf[0..report_size])
|
||||||
)?;
|
.context(FidoErrorKind::ReadPacket)?;
|
||||||
let mut cid = [0; 4];
|
let mut cid = [0; 4];
|
||||||
cid.copy_from_slice(&buf[0..4]);
|
cid.copy_from_slice(&buf[0..4]);
|
||||||
let seq = buf[4];
|
let seq = buf[4];
|
||||||
|
88
src/util.rs
Normal file
88
src/util.rs
Normal 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)
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user