use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
use flate2::Compression;
use flate2::read::DeflateDecoder;
use flate2::write::DeflateEncoder;
use sha2::{Digest, Sha256};
use std::io::{Read, Write};
use zeroize::Zeroizing;
use crate::cbor::{self, Value};
use crate::core::Connection;
use super::pin_protocol::PinProtocol;
use super::session::Ctap2Session;
use super::{Ctap2Error, ctap2_cmd};
pub struct LargeBlobs<C: Connection> {
session: Ctap2Session<C>,
protocol: PinProtocol,
pin_token: Zeroizing<Vec<u8>>,
max_fragment_length: usize,
}
impl<C: Connection + 'static> LargeBlobs<C> {
pub fn is_supported(info: &super::Info) -> bool {
info.options.get("largeBlobs") == Some(&true)
}
#[allow(clippy::result_large_err)]
pub fn new(
session: Ctap2Session<C>,
protocol: PinProtocol,
pin_token: Vec<u8>,
) -> Result<Self, (Ctap2Error<C::Error>, Ctap2Session<C>)> {
if !Self::is_supported(&session.cached_info) {
return Err((
Ctap2Error::InvalidResponse("Authenticator does not support largeBlobs".into()),
session,
));
}
let max_msg = session.cached_info.max_msg_size;
let max_fragment_length = max_msg.saturating_sub(64);
Ok(Self {
session,
protocol,
pin_token: Zeroizing::new(pin_token),
max_fragment_length,
})
}
pub fn into_session(self) -> Ctap2Session<C> {
self.session
}
pub fn read_blob_array(&mut self) -> Result<Vec<u8>, Ctap2Error<C::Error>> {
log::debug!("Reading large blob array");
let mut data = Vec::new();
let mut offset: usize = 0;
loop {
let params: Vec<(Value, Value)> = vec![
(
Value::Int(0x01),
Value::Int(self.max_fragment_length as i64),
),
(Value::Int(0x03), Value::Int(offset as i64)),
];
let encoded = cbor::encode(&Value::Map(params));
let value =
self.session
.send_cbor(ctap2_cmd::LARGE_BLOBS, Some(&encoded), None, None)?;
let fragment = value
.map_get_int(0x01)
.and_then(|v| v.as_bytes())
.ok_or_else(|| {
Ctap2Error::InvalidResponse(
"Missing config (0x01) in largeBlobs response".into(),
)
})?;
let frag_len = fragment.len();
data.extend_from_slice(fragment);
offset += frag_len;
if frag_len < self.max_fragment_length {
break;
}
}
if data.len() < 16 {
return Err(Ctap2Error::InvalidResponse(
"Large blob data too short for integrity check".into(),
));
}
let (blob_data, hash_suffix) = data.split_at(data.len() - 16);
let digest = Sha256::digest(blob_data);
if &digest[..16] != hash_suffix {
return Err(Ctap2Error::InvalidResponse(
"Large blob integrity check failed".into(),
));
}
Ok(blob_data.to_vec())
}
pub fn write_blob_array(&mut self, blob_data: &[u8]) -> Result<(), Ctap2Error<C::Error>> {
log::debug!("Writing large blob array");
let digest = Sha256::digest(blob_data);
let mut data = blob_data.to_vec();
data.extend_from_slice(&digest[..16]);
let total_length = data.len();
let mut offset: usize = 0;
while offset < total_length {
let end = (offset + self.max_fragment_length).min(total_length);
let fragment = &data[offset..end];
let mut params: Vec<(Value, Value)> = Vec::new();
params.push((Value::Int(0x02), Value::Bytes(fragment.to_vec())));
params.push((Value::Int(0x03), Value::Int(offset as i64)));
if offset == 0 {
params.push((Value::Int(0x04), Value::Int(total_length as i64)));
}
let mut msg = vec![0xff; 32];
msg.extend_from_slice(&[0x0c, 0x00]);
msg.extend_from_slice(&(offset as u32).to_le_bytes());
let frag_hash = Sha256::digest(fragment);
msg.extend_from_slice(&frag_hash);
let pin_uv_param = self.protocol.authenticate(&self.pin_token, &msg);
params.push((Value::Int(0x06), Value::Int(self.protocol.version() as i64)));
params.push((Value::Int(0x05), Value::Bytes(pin_uv_param)));
let encoded = cbor::encode(&Value::Map(params));
self.session
.send_cbor(ctap2_cmd::LARGE_BLOBS, Some(&encoded), None, None)?;
offset = end;
}
log::info!("Large blob array written");
Ok(())
}
pub fn get_blob(
&mut self,
large_blob_key: &[u8],
) -> Result<Option<Vec<u8>>, Ctap2Error<C::Error>> {
log::debug!("Reading large blob");
let array_data = self.read_blob_array()?;
let blob = with_blob_array(&array_data, |array| {
for entry in array {
if let Ok(data) = lb_unpack(large_blob_key, entry) {
return Ok(Some(data));
}
}
Ok(None)
})?;
Ok(blob)
}
pub fn put_blob(
&mut self,
large_blob_key: &[u8],
data: &[u8],
) -> Result<(), Ctap2Error<C::Error>> {
log::debug!("Writing large blob");
let array_data = self.read_blob_array()?;
let mut entries = with_blob_array(&array_data, |array| {
Ok(array
.iter()
.filter(|entry| lb_unpack(large_blob_key, entry).is_err())
.cloned()
.collect::<Vec<_>>())
})?;
entries.push(lb_pack(large_blob_key, data)?);
let encoded = cbor::encode(&Value::Array(entries));
self.write_blob_array(&encoded)?;
log::info!("Large blob written");
Ok(())
}
pub fn delete_blob(&mut self, large_blob_key: &[u8]) -> Result<(), Ctap2Error<C::Error>> {
log::debug!("Deleting large blob");
let array_data = self.read_blob_array()?;
let (entries, orig_len) = with_blob_array(&array_data, |array| {
Ok((
array
.iter()
.filter(|entry| lb_unpack(large_blob_key, entry).is_err())
.cloned()
.collect::<Vec<_>>(),
array.len(),
))
})?;
if entries.len() != orig_len {
let encoded = cbor::encode(&Value::Array(entries));
self.write_blob_array(&encoded)?;
}
log::info!("Large blob deleted");
Ok(())
}
}
fn with_blob_array<E: std::error::Error + Send + Sync + 'static, T>(
data: &[u8],
f: impl FnOnce(&[Value]) -> Result<T, Ctap2Error<E>>,
) -> Result<T, Ctap2Error<E>> {
if data.is_empty() {
return f(&[]);
}
let value =
cbor::decode(data).map_err(|e| Ctap2Error::InvalidResponse(format!("CBOR error: {e}")))?;
let array = value.as_array().ok_or_else(|| {
Ctap2Error::InvalidResponse("Large blob array is not a CBOR array".into())
})?;
f(array)
}
fn lb_associated_data(orig_size: u64) -> Vec<u8> {
let mut ad = b"blob".to_vec();
ad.extend_from_slice(&orig_size.to_le_bytes());
ad
}
fn lb_pack<E: std::error::Error + Send + Sync + 'static>(
key: &[u8],
data: &[u8],
) -> Result<Value, Ctap2Error<E>> {
let orig_size = data.len() as u64;
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
encoder
.write_all(data)
.map_err(|e| Ctap2Error::InvalidResponse(format!("Compression failed: {e}")))?;
let compressed = encoder
.finish()
.map_err(|e| Ctap2Error::InvalidResponse(format!("Compression failed: {e}")))?;
let cipher = Aes256Gcm::new_from_slice(key)
.map_err(|e| Ctap2Error::InvalidResponse(format!("Invalid key: {e}")))?;
let mut nonce_bytes = [0u8; 12];
getrandom::fill(&mut nonce_bytes)
.map_err(|e| Ctap2Error::InvalidResponse(format!("RNG failed: {e}")))?;
let nonce = Nonce::from_slice(&nonce_bytes);
let ad = lb_associated_data(orig_size);
let ciphertext = cipher
.encrypt(
nonce,
aes_gcm::aead::Payload {
msg: &compressed,
aad: &ad,
},
)
.map_err(|e| Ctap2Error::InvalidResponse(format!("Encryption failed: {e}")))?;
Ok(Value::Map(vec![
(Value::Int(0x01), Value::Bytes(ciphertext)),
(Value::Int(0x02), Value::Bytes(nonce_bytes.to_vec())),
(Value::Int(0x03), Value::Int(orig_size as i64)),
]))
}
fn lb_unpack(key: &[u8], entry: &Value) -> Result<Vec<u8>, String> {
let map = entry.as_map().ok_or("not a map")?;
let ciphertext = map
.iter()
.find(|(k, _)| k.as_int() == Some(0x01))
.and_then(|(_, v)| v.as_bytes())
.ok_or("missing ciphertext")?;
let nonce_bytes = map
.iter()
.find(|(k, _)| k.as_int() == Some(0x02))
.and_then(|(_, v)| v.as_bytes())
.ok_or("missing nonce")?;
let orig_size = map
.iter()
.find(|(k, _)| k.as_int() == Some(0x03))
.and_then(|(_, v)| v.as_int())
.ok_or("missing origSize")? as u64;
let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| format!("invalid key: {e}"))?;
let nonce = Nonce::from_slice(nonce_bytes);
let ad = lb_associated_data(orig_size);
let compressed = cipher
.decrypt(
nonce,
aes_gcm::aead::Payload {
msg: ciphertext,
aad: &ad,
},
)
.map_err(|_| "wrong key")?;
let mut decoder = DeflateDecoder::new(&compressed[..]);
let mut decompressed = Vec::new();
decoder
.read_to_end(&mut decompressed)
.map_err(|e| format!("decompression failed: {e}"))?;
if decompressed.len() as u64 != orig_size {
return Err("size mismatch".into());
}
Ok(decompressed)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lb_pack_unpack_roundtrip() {
let key = [0x42u8; 32];
let data = b"hello, large blobs!";
let entry: Value = lb_pack::<std::io::Error>(&key, data).expect("pack should succeed");
let recovered = lb_unpack(&key, &entry).expect("unpack should succeed");
assert_eq!(recovered, data);
}
#[test]
fn test_lb_unpack_wrong_key() {
let key = [0x42u8; 32];
let wrong_key = [0x43u8; 32];
let data = b"secret data";
let entry: Value = lb_pack::<std::io::Error>(&key, data).expect("pack should succeed");
assert!(lb_unpack(&wrong_key, &entry).is_err());
}
#[test]
fn test_lb_pack_unpack_empty_data() {
let key = [0xaa; 32];
let data = b"";
let entry: Value = lb_pack::<std::io::Error>(&key, data).expect("pack should succeed");
let recovered = lb_unpack(&key, &entry).expect("unpack should succeed");
assert_eq!(recovered, data);
}
}