#[cfg(feature = "canister-signature-authentication")]
mod canister_signature;
mod delegation;
mod ranges;
mod subnet;
#[cfg(feature = "canister-signature-authentication")]
pub use canister_signature::{
AuthenticatedCanisterSignature, CanisterSignatureKey, CanisterSignatureLimits,
CanisterSignatureVerifyError, authenticate_canister_signature,
};
pub use subnet::{
AuthenticatedSubnetTime, authenticate_subnet_time, authenticate_subnet_time_from_certificate,
};
use super::DecodedCertificate;
use candidate_types::Principal;
use ic_certification::{HashTreeNode, LookupResult};
use ic_verify_bls_signature::{PublicKey, Signature};
const DER_PREFIX: &[u8; 37] = b"\x30\x81\x82\x30\x1d\x06\x0d\x2b\x06\x01\x04\x01\x82\xdc\x7c\x05\x03\x01\x02\x01\x06\x0c\x2b\x06\x01\x04\x01\x82\xdc\x7c\x05\x03\x02\x01\x03\x61\x00";
#[derive(Clone, Debug)]
pub struct PreparedRootKey {
key: PublicKey,
der: [u8; 133],
}
impl PreparedRootKey {
pub fn from_der(bytes: &[u8]) -> Result<Self, VerifyError> {
let der: [u8; 133] = bytes.try_into().map_err(|_| VerifyError::InvalidRootKey)?;
if !der.starts_with(DER_PREFIX) {
return Err(VerifyError::InvalidRootKey);
}
let key = PublicKey::deserialize(&der[37..]).map_err(|_| VerifyError::InvalidRootKey)?;
if identity(&key.serialize()) {
return Err(VerifyError::InvalidRootKey);
}
Ok(Self { key, der })
}
#[must_use]
pub const fn as_der(&self) -> &[u8; 133] {
&self.der
}
}
fn identity(bytes: &[u8]) -> bool {
bytes[0] == 0xc0 && bytes[1..].iter().all(|byte| *byte == 0)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TimeWindow {
pub reference_ns: u64,
pub max_age_ns: u64,
pub max_future_skew_ns: u64,
}
impl TimeWindow {
fn bounds(self) -> Result<(u64, u64), VerifyError> {
Ok((
self.reference_ns
.checked_sub(self.max_age_ns)
.ok_or(VerifyError::InvalidWindow)?,
self.reference_ns
.checked_add(self.max_future_skew_ns)
.ok_or(VerifyError::InvalidWindow)?,
))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TimePolicy {
pub certificate: TimeWindow,
pub delegation: TimeWindow,
}
#[derive(Clone, Copy, Debug)]
pub struct VerificationLimits {
pub tree_nodes: usize,
pub tree_depth: usize,
pub delegation_bytes: usize,
pub canister_ranges: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum VerifyError {
#[error("invalid certificate root key")]
InvalidRootKey,
#[error("delegated certificates require the delegated verification path")]
DelegationUnsupported,
#[error("invalid certificate delegation")]
InvalidDelegation,
#[error("delegation certificate exceeds byte allowance")]
DelegationLimit,
#[error("invalid delegation certificate encoding")]
InvalidDelegationEncoding,
#[error("required certified delegation path is unavailable")]
MissingDelegationPath,
#[error("invalid certified canister ranges")]
InvalidRanges,
#[error("certified canister ranges exceed allowance")]
RangeLimit,
#[error("certificate is not authorized for the effective canister")]
NotAuthorized,
#[error("certificate does not belong to the requested subnet")]
SubnetMismatch,
#[error("direct-root certificate requires a trusted root subnet identity")]
RootSubnetRequired,
#[error("invalid certificate time window")]
InvalidWindow,
#[error("certificate tree exceeds traversal allowance")]
TreeLimit,
#[error("ambiguous certificate tree")]
InvalidTree,
#[error("invalid certificate time")]
InvalidTime,
#[error("certificate time outside admitted window")]
TimeOutsideWindow,
#[error("invalid certificate signature")]
Signature,
}
#[derive(Debug)]
pub struct AuthenticatedCertificate<'a> {
decoded: DecodedCertificate<'a>,
root_der: [u8; 133],
target: Principal,
window: TimeWindow,
time_ns: u64,
delegation: Option<(Principal, TimeWindow, u64)>,
}
impl<'a> AuthenticatedCertificate<'a> {
#[must_use]
pub const fn original_bytes(&self) -> &'a [u8] {
self.decoded.original_bytes()
}
#[must_use]
pub const fn tree(&self) -> &ic_certification::HashTree {
&self.decoded.certificate.tree
}
#[must_use]
pub const fn root_key_der(&self) -> &[u8; 133] {
&self.root_der
}
#[must_use]
pub const fn effective_canister(&self) -> Principal {
self.target
}
#[must_use]
pub const fn time_window(&self) -> TimeWindow {
self.window
}
#[must_use]
pub const fn time_ns(&self) -> u64 {
self.time_ns
}
#[must_use]
pub const fn delegation(&self) -> Option<(Principal, TimeWindow, u64)> {
self.delegation
}
#[must_use]
pub fn into_unverified(self) -> DecodedCertificate<'a> {
self.decoded
}
}
pub fn authenticate_direct_certificate<'a>(
decoded: DecodedCertificate<'a>,
root: &PreparedRootKey,
effective_canister: Principal,
window: TimeWindow,
limits: VerificationLimits,
) -> Result<AuthenticatedCertificate<'a>, VerifyError> {
if decoded.certificate.delegation.is_some() {
return Err(VerifyError::DelegationUnsupported);
}
authenticate_certificate(
decoded,
root,
effective_canister,
TimePolicy {
certificate: window,
delegation: window,
},
limits,
)
}
pub fn authenticate_certificate<'a>(
decoded: DecodedCertificate<'a>,
root: &PreparedRootKey,
effective_canister: Principal,
time: TimePolicy,
limits: VerificationLimits,
) -> Result<AuthenticatedCertificate<'a>, VerifyError> {
let verified = verify_certificate(
&decoded.certificate,
root,
Authority::Canister(effective_canister),
time,
limits,
)?;
Ok(AuthenticatedCertificate {
decoded,
root_der: root.der,
target: effective_canister,
window: time.certificate,
time_ns: verified.time_ns,
delegation: verified.delegation,
})
}
#[derive(Clone, Copy)]
enum Authority {
Canister(Principal),
#[cfg(feature = "canister-signature-authentication")]
CanisterSignature(Principal),
Subnet {
requested: Principal,
root_subnet: Option<Principal>,
},
}
struct VerifiedContext {
time_ns: u64,
delegation: Option<(Principal, TimeWindow, u64)>,
}
fn verify_certificate(
certificate: &ic_certification::Certificate,
root: &PreparedRootKey,
authority: Authority,
time: TimePolicy,
limits: VerificationLimits,
) -> Result<VerifiedContext, VerifyError> {
let bounds = time.certificate.bounds()?;
time.delegation.bounds()?;
let mut nodes = limits.tree_nodes;
forest(
certificate.tree.as_ref(),
&mut nodes,
limits.tree_depth,
&mut None,
&mut false,
)?;
let delegation = if let Some(value) = &certificate.delegation {
Some(delegation::verify(
value,
root,
authority,
time.delegation,
limits,
&mut nodes,
certificate,
)?)
} else {
if let Authority::Subnet {
requested,
root_subnet,
} = authority
{
let root_subnet = root_subnet.ok_or(VerifyError::RootSubnetRequired)?;
if requested != root_subnet {
return Err(VerifyError::SubnetMismatch);
}
}
None
};
let time_ns = checked_time(&certificate.tree, bounds)?;
if delegation.is_none() {
verify_signature(certificate, root)?;
}
Ok(VerifiedContext {
time_ns,
delegation,
})
}
fn verify_signature(
certificate: &ic_certification::Certificate,
root: &PreparedRootKey,
) -> Result<(), VerifyError> {
let signature =
Signature::deserialize(&certificate.signature).map_err(|_| VerifyError::Signature)?;
if identity(&signature.serialize()) {
return Err(VerifyError::Signature);
}
let mut message = [0; 46];
message[..14].copy_from_slice(b"\x0dic-state-root");
message[14..].copy_from_slice(&certificate.tree.digest());
root.key
.verify(&message, &signature)
.map_err(|()| VerifyError::Signature)
}
fn checked_time(tree: &ic_certification::HashTree, bounds: (u64, u64)) -> Result<u64, VerifyError> {
let LookupResult::Found(bytes) = tree.lookup_path([b"time".as_slice()]) else {
return Err(VerifyError::InvalidTime);
};
if bytes.is_empty() || bytes.len() > 10 {
return Err(VerifyError::InvalidTime);
}
let mut time = 0;
for (index, &byte) in bytes.iter().enumerate() {
if index == 9 && byte > 1 {
return Err(VerifyError::InvalidTime);
}
time |= u64::from(byte & 127) << (index * 7);
if byte & 128 == 0 {
if index + 1 != bytes.len() {
return Err(VerifyError::InvalidTime);
}
return if bounds.0 <= time && time <= bounds.1 {
Ok(time)
} else {
Err(VerifyError::TimeOutsideWindow)
};
}
}
Err(VerifyError::InvalidTime)
}
fn forest<'a>(
node: &'a HashTreeNode,
nodes: &mut usize,
depth: usize,
previous: &mut Option<&'a [u8]>,
value: &mut bool,
) -> Result<(), VerifyError> {
*nodes = nodes.checked_sub(1).ok_or(VerifyError::TreeLimit)?;
let next_depth = depth.checked_sub(1).ok_or(VerifyError::TreeLimit)?;
match node {
HashTreeNode::Fork(children) => {
forest(&children.0, nodes, next_depth, previous, value)?;
forest(&children.1, nodes, next_depth, previous, value)
}
HashTreeNode::Labeled(label, child) => {
let label = label.as_bytes();
if *value || previous.is_some_and(|old| old >= label) {
return Err(VerifyError::InvalidTree);
}
*previous = Some(label);
forest(child, nodes, next_depth, &mut None, &mut false)
}
HashTreeNode::Leaf(_) => {
if *value || previous.is_some() {
return Err(VerifyError::InvalidTree);
}
*value = true;
Ok(())
}
HashTreeNode::Empty() | HashTreeNode::Pruned(_) => Ok(()),
}
}
#[cfg(test)]
mod tests;