use arrayref::array_ref;
use arrayref::array_refs;
use chacha20::cipher::KeyIvInit;
use chacha20::cipher::StreamCipher;
use chacha20::ChaCha20;
use hmac::digest::Key;
use hmac::Hmac;
use hmac::KeyInit;
use hmac::Mac;
use rand::CryptoRng;
use rand::RngCore;
use rings_core::delegation::DelegateeKey;
use rings_core::ecc::prime_order::NonIdentityPoint;
use rings_core::ecc::prime_order::NonZeroScalar;
use rings_core::ecc::prime_order::SHARED_SECRET_BYTES;
use rings_core::ecc::prime_order::WIDE_SCALAR_BYTES;
use rings_core::ecc::PublicKey;
use rings_core::ecc::Secp256k1;
use sha2::Sha256;
use subtle::Choice;
use subtle::ConstantTimeEq;
use zeroize::Zeroizing;
use super::class::OnionLoopClass;
use super::hkdf_expand;
use super::hkdf_extract;
use super::layer::OnionLayer;
use super::layer::OnionLayerError;
use super::layer::ONION_LAYER_BYTES;
use super::xor_in_place;
use crate::onion::loop_shape::MAX_ONION_LOOP_HOPS;
const ONION_GROUP_ELEMENT_BYTES: usize = 33;
pub(crate) const ONION_HEADER_MAC_BYTES: usize = 16;
pub(crate) const ONION_HEADER_ROUTING_BYTES: usize = MAX_ONION_LOOP_HOPS * ONION_LAYER_BYTES;
pub(crate) const ONION_HEADER_BYTES: usize =
ONION_GROUP_ELEMENT_BYTES + ONION_HEADER_ROUTING_BYTES + ONION_HEADER_MAC_BYTES;
const HEADER_KDF_SALT: &[u8] = b"rings-node:onion-sphinx-header";
const STREAM_INFO: &[u8] = b"prg";
const MAC_INFO: &[u8] = b"mac";
const BLIND_INFO: &[u8] = b"blind";
const STREAM_KEY_BYTES: usize = 32;
const MAC_KEY_BYTES: usize = 64;
type Block = [u8; ONION_LAYER_BYTES];
type Routing = [Block; MAX_ONION_LOOP_HOPS];
type Stream = [Block; MAX_ONION_LOOP_HOPS + 1];
#[derive(Clone, Copy, Debug)]
pub(crate) struct OnionHeaderMac([u8; ONION_HEADER_MAC_BYTES]);
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub(crate) struct OnionLoopTag([u8; ONION_HEADER_MAC_BYTES]);
impl OnionLoopTag {
pub(crate) const fn new(bytes: [u8; ONION_HEADER_MAC_BYTES]) -> Self {
Self(bytes)
}
#[cfg(all(test, rings_native))]
pub(crate) const fn as_bytes(&self) -> &[u8; ONION_HEADER_MAC_BYTES] {
&self.0
}
}
#[derive(Clone, Debug)]
pub(crate) struct OnionHeader {
alpha: PublicKey<ONION_GROUP_ELEMENT_BYTES>,
routing: Routing,
mac: OnionHeaderMac,
}
pub(crate) struct OnionHeaderHop {
pub(crate) public_key: PublicKey<33>,
pub(crate) layer: OnionLayer,
}
struct OnionRoutePosition {
recipient: NonIdentityPoint<Secp256k1>,
layer: OnionLayer,
}
pub(crate) struct OnionHeaderRoute {
outer: Vec<OnionRoutePosition>,
last: OnionRoutePosition,
}
#[cfg(test)]
pub(crate) struct OnionPeeledHeader {
pub(crate) layer: OnionLayer,
pub(crate) next: OnionHeader,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub(crate) enum OnionHeaderRouteError {
#[error("loop of {0} positions is outside 1..={MAX_ONION_LOOP_HOPS}")]
HopCount(usize),
#[error("onion hop public key is not a secp256k1 point")]
PublicKey,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
#[error("onion header blinding factor is zero")]
pub(crate) struct OnionBlindingError;
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub(crate) enum OnionPeelError {
#[error("onion header is invalid")]
Invalid,
#[error(transparent)]
Blinding(#[from] OnionBlindingError),
#[error(transparent)]
Layer(#[from] OnionLayerError),
}
struct OnionHopSecrets {
stream: Zeroizing<Stream>,
mac_key: Zeroizing<[u8; MAC_KEY_BYTES]>,
blinding: NonZeroScalar<Secp256k1>,
}
impl OnionHeaderMac {
pub(crate) const fn new(bytes: [u8; ONION_HEADER_MAC_BYTES]) -> Self {
Self(bytes)
}
pub(crate) const fn to_bytes(self) -> [u8; ONION_HEADER_MAC_BYTES] {
self.0
}
}
impl ConstantTimeEq for OnionHeaderMac {
fn ct_eq(&self, other: &Self) -> Choice {
self.0.ct_eq(&other.0)
}
}
impl OnionHeaderRoute {
pub(crate) fn new(hops: Vec<OnionHeaderHop>) -> Result<Self, OnionHeaderRouteError> {
let count = hops.len();
let mut positions = hops
.into_iter()
.map(|hop| {
NonIdentityPoint::try_from(hop.public_key)
.map(|recipient| OnionRoutePosition {
recipient,
layer: hop.layer,
})
.map_err(|_| OnionHeaderRouteError::PublicKey)
})
.collect::<Result<Vec<_>, _>>()?;
positions
.pop()
.filter(|_| count <= MAX_ONION_LOOP_HOPS)
.map(|last| Self {
outer: positions,
last,
})
.ok_or(OnionHeaderRouteError::HopCount(count))
}
}
impl OnionHopSecrets {
fn derive(
alpha: &PublicKey<ONION_GROUP_ELEMENT_BYTES>,
shared: &[u8; SHARED_SECRET_BYTES],
) -> Result<Self, OnionBlindingError> {
let kdf = hkdf_extract(HEADER_KDF_SALT, &[alpha.0.as_slice(), shared.as_slice()]);
let blinding =
NonZeroScalar::from_wide_bytes(&hkdf_expand::<WIDE_SCALAR_BYTES>(&kdf, &[BLIND_INFO]))
.ok_or(OnionBlindingError)?;
let mut stream = Zeroizing::new([[0; ONION_LAYER_BYTES]; MAX_ONION_LOOP_HOPS + 1]);
ChaCha20::new(
&(*hkdf_expand::<STREAM_KEY_BYTES>(&kdf, &[STREAM_INFO])).into(),
&[0; 12].into(),
)
.apply_keystream(stream.as_flattened_mut());
Ok(Self {
stream,
mac_key: hkdf_expand(&kdf, &[MAC_INFO]),
blinding,
})
}
fn mac(&self, class: OnionLoopClass, routing: &[Block]) -> OnionHeaderMac {
let mut key = Zeroizing::new(Key::<Hmac<Sha256>>::default());
key.iter_mut()
.zip(self.mac_key.iter())
.for_each(|(slot, byte)| *slot = *byte);
let mut mac = <Hmac<Sha256> as KeyInit>::new(&key);
mac.update(&class.mac_label());
mac.update(routing.as_flattened());
let mut truncated = [0; ONION_HEADER_MAC_BYTES];
truncated
.iter_mut()
.zip(mac.finalize().into_bytes())
.for_each(|(slot, byte)| *slot = byte);
OnionHeaderMac(truncated)
}
fn mask(&self, blocks: &mut [Block]) {
blocks
.iter_mut()
.zip(self.stream.iter())
.for_each(|(block, mask)| xor_in_place(block.iter_mut(), mask.iter()));
}
}
impl OnionHeader {
pub(super) fn of(bytes: &[u8; ONION_HEADER_BYTES]) -> Self {
let (alpha, routing, mac) = array_refs![
bytes,
ONION_GROUP_ELEMENT_BYTES,
ONION_HEADER_ROUTING_BYTES,
ONION_HEADER_MAC_BYTES
];
Self {
alpha: PublicKey(*alpha),
routing: std::array::from_fn(|slot| {
*array_ref![routing, slot * ONION_LAYER_BYTES, ONION_LAYER_BYTES]
}),
mac: OnionHeaderMac(*mac),
}
}
pub(super) fn encode_into(&self, bytes: &mut Vec<u8>) {
bytes.extend_from_slice(self.alpha.0.as_slice());
bytes.extend_from_slice(self.routing.as_flattened());
bytes.extend_from_slice(self.mac.0.as_slice());
}
#[cfg(test)]
pub(super) fn to_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::with_capacity(ONION_HEADER_BYTES);
self.encode_into(&mut bytes);
bytes
}
#[cfg(test)]
pub(super) const fn loop_tag(&self) -> OnionLoopTag {
OnionLoopTag(self.mac.0)
}
pub(super) fn build(
route: &OnionHeaderRoute,
class: OnionLoopClass,
rng: &mut (impl CryptoRng + RngCore),
) -> Result<(Self, OnionLoopTag), OnionBlindingError> {
let mut tag = OnionLoopTag([0; ONION_HEADER_MAC_BYTES]);
rng.fill_bytes(&mut tag.0);
let (exponent, outer) = route.outer.iter().try_fold(
(
NonZeroScalar::random_with_rng(&mut *rng),
Vec::with_capacity(route.outer.len()),
),
|(exponent, mut schedule), position| {
let (alpha, secrets) = Self::position(position, &exponent)?;
let next = &exponent * &secrets.blinding;
schedule.push((alpha, secrets));
Ok::<_, OnionBlindingError>((next, schedule))
},
)?;
let (alpha, secrets) = Self::position(&route.last, &exponent)?;
let filler = outer
.iter()
.fold(Vec::<Block>::new(), |mut filler, (_, secrets)| {
filler.push([0; ONION_LAYER_BYTES]);
filler
.iter_mut()
.rev()
.zip(secrets.stream.iter().rev())
.for_each(|(block, mask)| xor_in_place(block.iter_mut(), mask.iter()));
filler
});
let mut routing: Routing = [[0; ONION_LAYER_BYTES]; MAX_ONION_LOOP_HOPS];
rng.fill_bytes(routing.as_flattened_mut());
let [first, ..] = &mut routing;
*first = *route.last.layer.encode(&OnionHeaderMac(tag.0));
secrets.mask(&mut routing);
routing
.iter_mut()
.rev()
.zip(filler.iter().rev())
.for_each(|(block, filler)| *block = *filler);
let innermost = Self {
alpha,
mac: secrets.mac(class, &routing),
routing,
};
let header = route.outer.iter().zip(outer.iter()).rev().fold(
innermost,
|next, (position, (alpha, secrets))| {
let mut routing = next.routing;
routing.rotate_right(1);
let [first, ..] = &mut routing;
*first = *position.layer.encode(&next.mac);
secrets.mask(&mut routing);
Self {
alpha: *alpha,
mac: secrets.mac(class, &routing),
routing,
}
},
);
Ok((header, tag))
}
fn position(
position: &OnionRoutePosition,
exponent: &NonZeroScalar<Secp256k1>,
) -> Result<(PublicKey<ONION_GROUP_ELEMENT_BYTES>, OnionHopSecrets), OnionBlindingError> {
let alpha = PublicKey::from(&NonIdentityPoint::generator_mul(exponent));
let secrets = OnionHopSecrets::derive(&alpha, &position.recipient.shared_secret(exponent))?;
Ok((alpha, secrets))
}
#[cfg(test)]
pub(super) fn peel(
&self,
class: OnionLoopClass,
key: &DelegateeKey,
) -> Result<OnionPeeledHeader, OnionPeelError> {
let mut bytes = [0; ONION_HEADER_BYTES];
bytes
.iter_mut()
.zip(self.to_bytes())
.for_each(|(slot, byte)| *slot = byte);
let layer = peel_in_place(&mut bytes, class, std::slice::from_ref(key))?;
let next = Self::of(&bytes);
Ok(OnionPeeledHeader { layer, next })
}
}
pub(super) fn peel_in_place(
bytes: &mut [u8; ONION_HEADER_BYTES],
class: OnionLoopClass,
keys: &[DelegateeKey],
) -> Result<OnionLayer, OnionPeelError> {
let (alpha_bytes, rest) = bytes
.split_first_chunk_mut::<ONION_GROUP_ELEMENT_BYTES>()
.ok_or(OnionPeelError::Invalid)?;
let (routing, mac) = rest
.split_last_chunk_mut::<ONION_HEADER_MAC_BYTES>()
.ok_or(OnionPeelError::Invalid)?;
let encoded_alpha = PublicKey(*alpha_bytes);
let alpha = NonIdentityPoint::<Secp256k1>::try_from(encoded_alpha)
.map_err(|_| OnionPeelError::Invalid)?;
let (blocks, []) = routing.as_chunks_mut::<ONION_LAYER_BYTES>() else {
return Err(OnionPeelError::Invalid);
};
let expected_mac = OnionHeaderMac(*mac);
let secrets = keys
.iter()
.find_map(|key| {
match OnionHopSecrets::derive(&encoded_alpha, &key.diffie_hellman(&alpha)) {
Ok(secrets) => bool::from(secrets.mac(class, blocks).ct_eq(&expected_mac))
.then_some(Ok(secrets)),
Err(error) => Some(Err(OnionPeelError::from(error))),
}
})
.ok_or(OnionPeelError::Invalid)??;
let mut padded = Zeroizing::new([[0; ONION_LAYER_BYTES]; MAX_ONION_LOOP_HOPS + 1]);
padded
.iter_mut()
.zip(blocks.iter())
.for_each(|(block, routing)| *block = *routing);
secrets.mask(padded.as_mut_slice());
let [layer, next_routing @ ..] = &*padded;
let (layer, next_mac) = OnionLayer::decode(layer.as_slice())?;
*alpha_bytes = PublicKey::<ONION_GROUP_ELEMENT_BYTES>::from(&(&alpha * &secrets.blinding)).0;
blocks
.iter_mut()
.zip(next_routing.iter())
.for_each(|(block, next)| *block = *next);
*mac = next_mac.to_bytes();
Ok(layer)
}