8 Commits

Author SHA1 Message Date
5bf210dc73 test all features
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2020-06-23 19:15:51 +02:00
0a2a054233 fmt
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2020-06-23 19:10:40 +02:00
c358202a3a drone 2020-06-23 19:01:12 +02:00
86649b56aa cleanup 2020-05-07 01:56:14 +02:00
48604d165b response enum 2020-05-06 23:53:00 +02:00
317f5ebdb4 impl get assertion 2020-04-26 17:52:40 +02:00
33229a0b3c impl make credential 2020-04-26 14:24:39 +02:00
9737a006e7 working cbor deserialize 2020-04-25 21:05:30 +02:00
11 changed files with 1384 additions and 100 deletions

24
.drone.yml Normal file
View File

@@ -0,0 +1,24 @@
kind: pipeline
name: default
steps:
- name: fmt
image: rust:1.43.0
commands:
- rustup component add rustfmt
- cargo fmt --all -- --check
- name: test
image: rust:1.43.0
commands:
- cargo test --all-features
- name: publish
image: rust:1.43.0
environment:
CARGO_REGISTRY_TOKEN:
from_secret: cargo_tkn
commands:
- grep -E 'version ?= ?"${DRONE_TAG}"' -i Cargo.toml || (printf "incorrect crate/tag version" && exit 1)
- cargo package --all-features
- cargo publish --all-features
when:
event: tag

View File

@@ -1,7 +1,7 @@
[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.4.0"
license = "Apache-2.0/MIT" license = "Apache-2.0/MIT"
homepage = "https://github.com/shimunn/ctap" homepage = "https://github.com/shimunn/ctap"
repository = "https://github.com/shimunn/ctap" repository = "https://github.com/shimunn/ctap"
@@ -20,16 +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"
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 }
serde_derive = "1.0.106"
serde = "1.0.106"
serde_cbor = "0.11.1"
serde_bytes = "0.11.3"
[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"] request_multiple = ["crossbeam"]

View File

@@ -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"];")
}

View File

@@ -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)

View File

@@ -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,32 +19,6 @@ 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.")]
@@ -142,24 +116,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."
)
}
}

View File

@@ -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

1279
src/protocol/cbor.rs Normal file

File diff suppressed because it is too large Load Diff

7
src/protocol/error.rs Normal file
View File

@@ -0,0 +1,7 @@
use thiserror::Error;
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ProtocolError {
CborEncode,
CborDecode { data: Vec<u8> },
}

4
src/protocol/mod.rs Normal file
View File

@@ -0,0 +1,4 @@
mod cbor;
mod error;
pub use self::cbor::*;
pub use self::error::*;

9
src/transport/mod.rs Normal file
View File

@@ -0,0 +1,9 @@
use crate::protocol::{CborRequest, CborResponse};
pub trait CtapTransport {
type Error;
fn cbor<'a>(&mut self, command: &CborRequest<'a>) -> Result<CborResponse, Self::Error>;
}
pub enum CtapCommand {}