1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//! COSE_Sign* functionality.
use crate::{
cbor,
cbor::value::Value,
common::AsCborValue,
iana,
util::{cbor_type_error, to_cbor_array, ValueTryAs},
CoseError, Header, ProtectedHeader, Result,
};
use alloc::{borrow::ToOwned, vec, vec::Vec};
#[cfg(test)]
mod tests;
/// Structure representing a cryptographic signature.
///
/// ```cddl
/// COSE_Signature = [
/// Headers,
/// signature : bstr
/// ]
/// ```
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CoseSignature {
pub protected: ProtectedHeader,
pub unprotected: Header,
pub signature: Vec<u8>,
}
impl crate::CborSerializable for CoseSignature {}
impl AsCborValue for CoseSignature {
fn from_cbor_value(value: Value) -> Result<Self> {
let mut a = value.try_as_array()?;
if a.len() != 3 {
return Err(CoseError::UnexpectedItem("array", "array with 3 items"));
}
// Remove array elements in reverse order to avoid shifts.
Ok(Self {
signature: a.remove(2).try_as_bytes()?,
unprotected: Header::from_cbor_value(a.remove(1))?,
protected: ProtectedHeader::from_cbor_bstr(a.remove(0))?,
})
}
fn to_cbor_value(self) -> Result<Value> {
Ok(Value::Array(vec![
self.protected.cbor_bstr()?,
self.unprotected.to_cbor_value()?,
Value::Bytes(self.signature),
]))
}
}
/// Builder for [`CoseSignature`] objects.
#[derive(Debug, Default)]
pub struct CoseSignatureBuilder(CoseSignature);
impl CoseSignatureBuilder {
builder! {CoseSignature}
builder_set_protected! {protected}
builder_set! {unprotected: Header}
builder_set! {signature: Vec<u8>}
}
/// Signed payload with signatures.
///
/// ```cdl
/// COSE_Sign = [
/// Headers,
/// payload : bstr / nil,
/// signatures : [+ COSE_Signature]
/// ]
/// ```
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CoseSign {
pub protected: ProtectedHeader,
pub unprotected: Header,
pub payload: Option<Vec<u8>>,
pub signatures: Vec<CoseSignature>,
}
impl crate::CborSerializable for CoseSign {}
impl crate::TaggedCborSerializable for CoseSign {
const TAG: u64 = iana::CborTag::CoseSign as u64;
}
impl AsCborValue for CoseSign {
fn from_cbor_value(value: Value) -> Result<Self> {
let mut a = value.try_as_array()?;
if a.len() != 4 {
return Err(CoseError::UnexpectedItem("array", "array with 4 items"));
}
// Remove array elements in reverse order to avoid shifts.
let signatures = a.remove(3).try_as_array_then_convert(|v| {
CoseSignature::from_cbor_value(v)
.map_err(|_e| CoseError::UnexpectedItem("non-signature", "map for COSE_Signature"))
})?;
Ok(Self {
signatures,
payload: match a.remove(2) {
Value::Bytes(b) => Some(b),
Value::Null => None,
v => return cbor_type_error(&v, "bstr or nil"),
},
unprotected: Header::from_cbor_value(a.remove(1))?,
protected: ProtectedHeader::from_cbor_bstr(a.remove(0))?,
})
}
fn to_cbor_value(self) -> Result<Value> {
Ok(Value::Array(vec![
self.protected.cbor_bstr()?,
self.unprotected.to_cbor_value()?,
match self.payload {
Some(b) => Value::Bytes(b),
None => Value::Null,
},
to_cbor_array(self.signatures)?,
]))
}
}
impl CoseSign {
/// Verify the indicated signature value, using `verifier` on the signature value and serialized
/// data (in that order).
///
/// # Panics
///
/// This method will panic if `which` is >= `self.signatures.len()`.
pub fn verify_signature<F, E>(&self, which: usize, aad: &[u8], verifier: F) -> Result<(), E>
where
F: FnOnce(&[u8], &[u8]) -> Result<(), E>,
{
let sig = &self.signatures[which];
let tbs_data = self.tbs_data(aad, sig);
verifier(&sig.signature, &tbs_data)
}
/// Verify the indicated signature value for a detached payload, using `verifier` on the
/// signature value and serialized data (in that order).
///
/// # Panics
///
/// This method will panic if `which` is >= `self.signatures.len()`.
///
/// This method will panic if `self.payload.is_some()`.
pub fn verify_detached_signature<F, E>(
&self,
which: usize,
payload: &[u8],
aad: &[u8],
verifier: F,
) -> Result<(), E>
where
F: FnOnce(&[u8], &[u8]) -> Result<(), E>,
{
let sig = &self.signatures[which];
let tbs_data = self.tbs_detached_data(payload, aad, sig);
verifier(&sig.signature, &tbs_data)
}
/// Construct the to-be-signed data for this object.
fn tbs_data(&self, aad: &[u8], sig: &CoseSignature) -> Vec<u8> {
sig_structure_data(
SignatureContext::CoseSignature,
self.protected.clone(),
Some(sig.protected.clone()),
aad,
self.payload.as_ref().unwrap_or(&vec![]),
)
}
/// Construct the to-be-signed data for this object, using a detached payload.
///
/// # Panics
///
/// This method will panic if `self.payload.is_some()`.
fn tbs_detached_data(&self, payload: &[u8], aad: &[u8], sig: &CoseSignature) -> Vec<u8> {
assert!(self.payload.is_none());
sig_structure_data(
SignatureContext::CoseSignature,
self.protected.clone(),
Some(sig.protected.clone()),
aad,
payload,
)
}
}
/// Builder for [`CoseSign`] objects.
#[derive(Debug, Default)]
pub struct CoseSignBuilder(CoseSign);
impl CoseSignBuilder {
builder! {CoseSign}
builder_set_protected! {protected}
builder_set! {unprotected: Header}
builder_set_optional! {payload: Vec<u8>}
/// Add a signature value.
#[must_use]
pub fn add_signature(mut self, sig: CoseSignature) -> Self {
self.0.signatures.push(sig);
self
}
/// Calculate the signature value, using `signer` to generate the signature bytes that will be
/// used to complete `sig`. Any protected header values should be set before using this
/// method.
#[must_use]
pub fn add_created_signature<F>(self, mut sig: CoseSignature, aad: &[u8], signer: F) -> Self
where
F: FnOnce(&[u8]) -> Vec<u8>,
{
let tbs_data = self.0.tbs_data(aad, &sig);
sig.signature = signer(&tbs_data);
self.add_signature(sig)
}
/// Calculate the signature value for a detached payload, using `signer` to generate the
/// signature bytes that will be used to complete `sig`. Any protected header values should
/// be set before using this method.
///
/// # Panics
///
/// This method will panic if `self.payload.is_some()`.
#[must_use]
pub fn add_detached_signature<F>(
self,
mut sig: CoseSignature,
payload: &[u8],
aad: &[u8],
signer: F,
) -> Self
where
F: FnOnce(&[u8]) -> Vec<u8>,
{
let tbs_data = self.0.tbs_detached_data(payload, aad, &sig);
sig.signature = signer(&tbs_data);
self.add_signature(sig)
}
/// Calculate the signature value, using `signer` to generate the signature bytes that will be
/// used to complete `sig`. Any protected header values should be set before using this
/// method.
pub fn try_add_created_signature<F, E>(
self,
mut sig: CoseSignature,
aad: &[u8],
signer: F,
) -> Result<Self, E>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, E>,
{
let tbs_data = self.0.tbs_data(aad, &sig);
sig.signature = signer(&tbs_data)?;
Ok(self.add_signature(sig))
}
/// Calculate the signature value for a detached payload, using `signer` to generate the
/// signature bytes that will be used to complete `sig`. Any protected header values should
/// be set before using this method.
///
/// # Panics
///
/// This method will panic if `self.payload.is_some()`.
pub fn try_add_detached_signature<F, E>(
self,
mut sig: CoseSignature,
payload: &[u8],
aad: &[u8],
signer: F,
) -> Result<Self, E>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, E>,
{
let tbs_data = self.0.tbs_detached_data(payload, aad, &sig);
sig.signature = signer(&tbs_data)?;
Ok(self.add_signature(sig))
}
}
/// Signed payload with a single signature.
///
/// ```cddl
/// COSE_Sign1 = [
/// Headers,
/// payload : bstr / nil,
/// signature : bstr
/// ]
/// ```
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CoseSign1 {
pub protected: ProtectedHeader,
pub unprotected: Header,
pub payload: Option<Vec<u8>>,
pub signature: Vec<u8>,
}
impl crate::CborSerializable for CoseSign1 {}
impl crate::TaggedCborSerializable for CoseSign1 {
const TAG: u64 = iana::CborTag::CoseSign1 as u64;
}
impl AsCborValue for CoseSign1 {
fn from_cbor_value(value: Value) -> Result<Self> {
let mut a = value.try_as_array()?;
if a.len() != 4 {
return Err(CoseError::UnexpectedItem("array", "array with 4 items"));
}
// Remove array elements in reverse order to avoid shifts.
Ok(Self {
signature: a.remove(3).try_as_bytes()?,
payload: match a.remove(2) {
Value::Bytes(b) => Some(b),
Value::Null => None,
v => return cbor_type_error(&v, "bstr or nil"),
},
unprotected: Header::from_cbor_value(a.remove(1))?,
protected: ProtectedHeader::from_cbor_bstr(a.remove(0))?,
})
}
fn to_cbor_value(self) -> Result<Value> {
Ok(Value::Array(vec![
self.protected.cbor_bstr()?,
self.unprotected.to_cbor_value()?,
match self.payload {
Some(b) => Value::Bytes(b),
None => Value::Null,
},
Value::Bytes(self.signature),
]))
}
}
impl CoseSign1 {
/// Verify the signature value, using `verifier` on the signature value and serialized data (in
/// that order).
pub fn verify_signature<F, E>(&self, aad: &[u8], verifier: F) -> Result<(), E>
where
F: FnOnce(&[u8], &[u8]) -> Result<(), E>,
{
let tbs_data = self.tbs_data(aad);
verifier(&self.signature, &tbs_data)
}
/// Verify the indicated signature value for a detached payload, using `verifier` on the
/// signature value and serialized data (in that order).
///
/// # Panics
///
/// This method will panic if `self.payload.is_some()`.
pub fn verify_detached_signature<F, E>(
&self,
payload: &[u8],
aad: &[u8],
verifier: F,
) -> Result<(), E>
where
F: FnOnce(&[u8], &[u8]) -> Result<(), E>,
{
let tbs_data = self.tbs_detached_data(payload, aad);
verifier(&self.signature, &tbs_data)
}
/// Construct the to-be-signed data for this object.
fn tbs_data(&self, aad: &[u8]) -> Vec<u8> {
sig_structure_data(
SignatureContext::CoseSign1,
self.protected.clone(),
None,
aad,
self.payload.as_ref().unwrap_or(&vec![]),
)
}
/// Construct the to-be-signed data for this object, using a detached payload.
///
/// # Panics
///
/// This method will panic if `self.payload.is_some()`.
fn tbs_detached_data(&self, payload: &[u8], aad: &[u8]) -> Vec<u8> {
assert!(self.payload.is_none());
sig_structure_data(
SignatureContext::CoseSign1,
self.protected.clone(),
None,
aad,
payload,
)
}
}
/// Builder for [`CoseSign1`] objects.
#[derive(Debug, Default)]
pub struct CoseSign1Builder(CoseSign1);
impl CoseSign1Builder {
builder! {CoseSign1}
builder_set_protected! {protected}
builder_set! {unprotected: Header}
builder_set! {signature: Vec<u8>}
builder_set_optional! {payload: Vec<u8>}
/// Calculate the signature value, using `signer` to generate the signature bytes. Any
/// protected header values should be set before using this method.
#[must_use]
pub fn create_signature<F>(self, aad: &[u8], signer: F) -> Self
where
F: FnOnce(&[u8]) -> Vec<u8>,
{
let sig_data = signer(&self.0.tbs_data(aad));
self.signature(sig_data)
}
/// Calculate the signature value for a detached payload, using `signer` to generate the
/// signature bytes. Any protected header values should be set before using this method.
///
/// # Panics
///
/// This method will panic if `self.payload.is_some()`.
#[must_use]
pub fn create_detached_signature<F>(self, payload: &[u8], aad: &[u8], signer: F) -> Self
where
F: FnOnce(&[u8]) -> Vec<u8>,
{
let sig_data = signer(&self.0.tbs_detached_data(payload, aad));
self.signature(sig_data)
}
/// Calculate the signature value, using `signer` to generate the signature bytes. Any
/// protected header values should be set before using this method.
pub fn try_create_signature<F, E>(self, aad: &[u8], signer: F) -> Result<Self, E>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, E>,
{
let sig_data = signer(&self.0.tbs_data(aad))?;
Ok(self.signature(sig_data))
}
/// Calculate the signature value for a detached payload, using `signer` to generate the
/// signature bytes. Any protected header values should be set before using this method.
///
/// # Panics
///
/// This method will panic if `self.payload.is_some()`.
pub fn try_create_detached_signature<F, E>(
self,
payload: &[u8],
aad: &[u8],
signer: F,
) -> Result<Self, E>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, E>,
{
let sig_data = signer(&self.0.tbs_detached_data(payload, aad))?;
Ok(self.signature(sig_data))
}
}
/// Possible signature contexts.
#[derive(Clone, Copy)]
pub enum SignatureContext {
CoseSignature,
CoseSign1,
CounterSignature,
}
impl SignatureContext {
/// Return the context string as per RFC 8152 section 4.4.
fn text(&self) -> &'static str {
match self {
SignatureContext::CoseSignature => "Signature",
SignatureContext::CoseSign1 => "Signature1",
SignatureContext::CounterSignature => "CounterSignature",
}
}
}
/// Create a binary blob that will be signed.
///
/// ```cddl
/// Sig_structure = [
/// context : "Signature" / "Signature1" / "CounterSignature",
/// body_protected : empty_or_serialized_map,
/// ? sign_protected : empty_or_serialized_map,
/// external_aad : bstr,
/// payload : bstr
/// ]
/// ```
pub fn sig_structure_data(
context: SignatureContext,
body: ProtectedHeader,
sign: Option<ProtectedHeader>,
aad: &[u8],
payload: &[u8],
) -> Vec<u8> {
let mut arr = vec![
Value::Text(context.text().to_owned()),
body.cbor_bstr().expect("failed to serialize header"), // safe: always serializable
];
if let Some(sign) = sign {
arr.push(sign.cbor_bstr().expect("failed to serialize header")); // safe: always
// serializable
}
arr.push(Value::Bytes(aad.to_vec()));
arr.push(Value::Bytes(payload.to_vec()));
let mut data = Vec::new();
cbor::ser::into_writer(&Value::Array(arr), &mut data).unwrap(); // safe: always serializable
data
}