use std::borrow::Borrow;
use std::sync::Arc;
use std::sync::RwLock;
use std::time::Duration;
use async_trait::async_trait;
use rings_core::delegation::DelegateeKey;
use rings_core::dht::Did;
use rings_core::domain_tag;
use rings_core::ecc::PublicKey;
use rings_core::ecc::VerificationPublicKey;
use rings_core::error::Error as CoreError;
use rings_core::error::Result as CoreResult;
use rings_core::message::DomainTag;
use rings_core::message::MessageSigner;
use rings_core::message::MessageVerification;
use rings_core::utils::SharedClock;
#[cfg(all(test, not(target_family = "wasm")))]
use rings_core::utils::SystemClock;
use serde::Deserialize;
use serde::Serialize;
use crate::descriptor::heard_elements;
use crate::descriptor::latest_valid_by_key;
use crate::descriptor::sign_descriptor_body;
use crate::descriptor::RegistryElement;
use crate::descriptor::SignedDescriptor;
use crate::descriptor::SignedDescriptorBody;
use crate::error::Error;
use crate::error::Result;
use crate::online::OnlineNodeType;
use crate::registration::DhtRegistrationPublisher;
use crate::registration::LeaseTerms;
use crate::registration::RegistrationContext;
use crate::registration::RegistrationTask;
pub mod circuit;
pub(crate) mod directory;
mod entry_guard;
pub(crate) mod exit_accounting;
mod failure;
#[cfg(rings_native)]
mod gateway;
#[cfg(any(rings_native, rings_browser))]
pub mod https;
pub(crate) mod invoke_accounting;
pub mod invoke_descriptor;
mod loop_shape;
#[cfg(rings_native)]
pub mod native;
pub mod pipeline;
pub mod proxy;
mod role;
pub mod route;
pub(crate) mod runtime;
pub(crate) mod session;
pub mod signature;
pub(crate) mod sphinx;
pub mod target;
#[cfg(rings_native)]
pub mod tcp;
pub use circuit::OnionInvokeBackend;
pub use circuit::OnionInvokeCall;
pub use circuit::OnionInvokeFn;
pub use entry_guard::OnionEntryGuardState;
pub use entry_guard::OnionEntryGuardStorage;
pub(crate) use entry_guard::OnionEntryGuards;
pub use failure::OnionExitFailure;
pub use failure::OnionRouteError;
#[cfg(rings_native)]
pub use gateway::NativeOnionGatewayConnector;
pub use invoke_descriptor::OnionInvokeDescriptor;
pub use invoke_descriptor::OnionInvokeDescriptorBody;
pub use invoke_descriptor::OnionInvokeDescriptorDecodeReport;
pub use invoke_descriptor::OnionInvokePolicy;
pub(crate) use invoke_descriptor::OnionInvokeRegistration;
pub use invoke_descriptor::ONION_INVOKES_TOPIC;
pub use loop_shape::OnionLoop;
pub(crate) use loop_shape::OnionLoopRelay;
pub use loop_shape::OnionLoopRole;
pub use loop_shape::OnionLoopShape;
pub(crate) use loop_shape::OnionPipelineSymbols;
pub use loop_shape::MAX_ONION_LOOP_HOPS;
pub use loop_shape::MAX_ONION_LOOP_SYMBOLS;
pub use loop_shape::ONION_SEGMENT_RELAYS;
pub use pipeline::OnionInvokeArguments;
pub use pipeline::OnionInvokePipeline;
pub use pipeline::OnionInvokeStage;
pub use pipeline::OnionPipeline;
pub use pipeline::OnionPipelineError;
pub use pipeline::OnionPipelineTerm;
pub use pipeline::OnionValueType;
pub use role::OnionExitOffer;
pub use role::OnionInvokeOffer;
pub use role::OnionRole;
pub(crate) use route::select_onion_route_from_candidates;
pub use route::OnionPipelineRoute;
pub use route::OnionPipelineRouteRequest;
pub use route::OnionRoute;
pub(crate) use route::OnionRouteCandidates;
pub use route::OnionRouteHop;
pub use route::OnionRouteRequest;
pub use runtime::OnionPipelineHandle;
pub use signature::OnionBackendName;
pub use signature::OnionInputType;
pub use signature::OnionInvokeShape;
pub use signature::OnionLatencyClass;
pub use signature::OnionServiceName;
pub use signature::OnionShape;
pub use signature::OnionWidthClass;
pub use signature::ONION_BACKEND_NAME_MAX_BYTES;
pub use sphinx::class::OnionLoopClass;
pub use target::OnionProxyTarget;
pub use target::OnionProxyTargetError;
pub const ONION_EXITS_TOPIC: &str = "onion_exits";
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct OnionProcessEpoch([u8; 16]);
impl OnionProcessEpoch {
pub const fn new(bytes: [u8; 16]) -> Self {
Self(bytes)
}
pub(crate) const fn to_bytes(self) -> [u8; 16] {
self.0
}
pub fn from_rng(rng: &mut impl rand::RngCore) -> Self {
let mut bytes = [0_u8; 16];
rng.fill_bytes(&mut bytes);
Self(bytes)
}
pub fn random() -> Self {
Self::from_rng(&mut rings_core::utils::SystemEntropy)
}
}
#[derive(Clone, Debug)]
pub struct OnionProcessEpochCell(Arc<RwLock<OnionProcessEpoch>>);
impl OnionProcessEpochCell {
pub fn new(epoch: OnionProcessEpoch) -> Self {
Self(Arc::new(RwLock::new(epoch)))
}
pub fn get(&self) -> OnionProcessEpoch {
self.0
.read()
.map_or_else(|poisoned| *poisoned.into_inner(), |epoch| *epoch)
}
pub(crate) fn renew(&self, epoch: OnionProcessEpoch) {
match self.0.write() {
Ok(mut current) => *current = epoch,
Err(poisoned) => *poisoned.into_inner() = epoch,
}
}
}
const DEFAULT_ONION_EXIT_HEARTBEAT_INTERVAL_SECS: u64 = 30;
const DEFAULT_ONION_EXIT_TTL_SECS: u64 = 90;
const ONION_EXIT_DESCRIPTOR_DOMAIN_TAG: DomainTag = domain_tag!("rings-node:onion-exit-descriptor");
pub(crate) const fn default_onion_exit_heartbeat_interval_secs() -> u64 {
DEFAULT_ONION_EXIT_HEARTBEAT_INTERVAL_SECS
}
pub(crate) const fn default_onion_exit_ttl_secs() -> u64 {
DEFAULT_ONION_EXIT_TTL_SECS
}
pub(crate) const fn default_advertise_onion_relay() -> bool {
false
}
pub(crate) const fn default_advertise_onion_exit() -> bool {
false
}
pub fn default_onion_exit_services() -> Vec<OnionServiceName> {
OnionServiceName::world_facing().collect()
}
pub fn https_onion_exit_services() -> Vec<OnionServiceName> {
vec![OnionServiceName::https()]
}
pub fn default_onion_exit_policy() -> OnionExitPolicy {
OnionExitPolicy::default()
}
#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct OnionExitPolicy {
pub allowed_targets: Vec<OnionExitTarget>,
pub denied_targets: Vec<OnionExitTarget>,
pub max_sessions: u32,
pub max_bytes_per_minute: u64,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(try_from = "String", into = "String")]
pub struct OnionExitTarget(OnionExitTargetPattern);
#[derive(Clone, Debug, Eq, PartialEq)]
enum OnionExitTargetPattern {
Any,
AnyHost(u16),
Authority(OnionProxyTarget),
}
impl OnionExitTarget {
const WILDCARD: &'static str = "*";
pub fn parse(target: impl AsRef<str>) -> Result<Self> {
let raw = target.as_ref().trim();
let invalid = |error: &dyn std::fmt::Display| {
Error::InvalidConfig(format!(
"invalid onion exit target {:?}; expected host:port, *:port or *:*: {error}",
target.as_ref()
))
};
let pattern = match raw.split_once(':') {
_ if raw == Self::WILDCARD => OnionExitTargetPattern::Any,
Some((Self::WILDCARD, Self::WILDCARD)) => OnionExitTargetPattern::Any,
Some((Self::WILDCARD, port)) => match port.parse::<u16>() {
Ok(0) => return Err(invalid(&OnionProxyTargetError::ZeroPort)),
Ok(port) => OnionExitTargetPattern::AnyHost(port),
Err(_) => return Err(invalid(&OnionProxyTargetError::InvalidPort)),
},
_ => OnionExitTargetPattern::Authority(
OnionProxyTarget::parse_authority(raw).map_err(|error| invalid(&error))?,
),
};
Ok(Self(pattern))
}
pub fn matches(&self, target: &OnionProxyTarget) -> bool {
match &self.0 {
OnionExitTargetPattern::Any => true,
OnionExitTargetPattern::AnyHost(port) => target.port() == *port,
OnionExitTargetPattern::Authority(authority) => authority == target,
}
}
pub fn is_public_ip_literal_authority(&self) -> bool {
matches!(
&self.0,
OnionExitTargetPattern::Authority(target)
if target::validate_public_ip_literal(target).is_ok()
)
}
}
impl std::fmt::Display for OnionExitTarget {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
OnionExitTargetPattern::Any => write!(formatter, "*:*"),
OnionExitTargetPattern::AnyHost(port) => write!(formatter, "*:{port}"),
OnionExitTargetPattern::Authority(authority) => {
formatter.write_str(authority.authority().as_str())
}
}
}
}
impl TryFrom<String> for OnionExitTarget {
type Error = String;
fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
Self::parse(&value).map_err(|error| error.to_string())
}
}
impl From<OnionExitTarget> for String {
fn from(target: OnionExitTarget) -> Self {
target.to_string()
}
}
impl OnionExitPolicy {
pub fn from_target_strings(
allowed_targets: Vec<String>,
denied_targets: Vec<String>,
) -> Result<Self> {
Ok(Self {
allowed_targets: parse_exit_targets(allowed_targets)?,
denied_targets: parse_exit_targets(denied_targets)?,
..Self::default()
})
}
pub fn is_closed(&self) -> bool {
self.allowed_targets.is_empty()
}
pub fn validate_targets(&self) -> Result<()> {
if self.is_closed() {
return Err(Error::InvalidConfig(
"advertise_onion_exit requires at least one valid onion_exit_policy allowed target"
.to_string(),
));
}
Ok(())
}
pub fn validate_browser_targets(&self) -> Result<()> {
self.validate_targets()?;
if let Some(target) = self
.allowed_targets
.iter()
.find(|target| !target.is_public_ip_literal_authority())
{
return Err(Error::InvalidConfig(format!(
"browser HTTPS onion exit policy only supports public IP-literal allowed_targets, got {target}"
)));
}
Ok(())
}
pub fn allows_target(&self, target: &OnionProxyTarget) -> bool {
!self.is_closed() && !self.denies(target) && self.allows(target)
}
fn allows(&self, target: &OnionProxyTarget) -> bool {
self.allowed_targets
.iter()
.any(|allowed| allowed.matches(target))
}
fn denies(&self, target: &OnionProxyTarget) -> bool {
self.denied_targets
.iter()
.any(|denied| denied.matches(target))
}
}
fn parse_exit_targets(targets: Vec<String>) -> Result<Vec<OnionExitTarget>> {
targets
.into_iter()
.map(OnionExitTarget::parse)
.collect::<Result<Vec<_>>>()
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct OnionExitDescriptorBody {
pub did: Did,
pub public_key: VerificationPublicKey,
pub delegatee_public_key: PublicKey<33>,
pub process_epoch: OnionProcessEpoch,
pub node_type: OnlineNodeType,
pub network_id: u32,
pub service: OnionServiceName,
pub policy: OnionExitPolicy,
pub started_at_ms: u128,
pub fresh_for_ms: u64,
pub expires_at_ms: u128,
pub version: String,
}
impl OnionExitDescriptorBody {
fn body_ref(&self) -> OnionExitDescriptorBodyRef<'_> {
OnionExitDescriptorBodyRef {
did: self.did,
public_key: &self.public_key,
delegatee_public_key: &self.delegatee_public_key,
process_epoch: self.process_epoch,
node_type: &self.node_type,
network_id: self.network_id,
service: &self.service,
policy: &self.policy,
started_at_ms: self.started_at_ms,
fresh_for_ms: self.fresh_for_ms,
expires_at_ms: self.expires_at_ms,
version: self.version.as_str(),
}
}
fn signing_data(&self) -> CoreResult<Vec<u8>> {
self.body_ref().signing_data()
}
}
impl SignedDescriptorBody for OnionExitDescriptorBody {
type Descriptor = OnionExitDescriptor;
const DOMAIN_TAG: DomainTag = ONION_EXIT_DESCRIPTOR_DOMAIN_TAG;
fn body_did(&self) -> Did {
self.did
}
fn body_public_key(&self) -> &VerificationPublicKey {
&self.public_key
}
fn body_network_id(&self) -> u32 {
self.network_id
}
fn body_signing_data(&self) -> CoreResult<Vec<u8>> {
self.signing_data()
}
fn into_signed_descriptor(self, signature: MessageVerification) -> Self::Descriptor {
OnionExitDescriptor {
did: self.did,
public_key: self.public_key,
delegatee_public_key: self.delegatee_public_key,
process_epoch: self.process_epoch,
node_type: self.node_type,
network_id: self.network_id,
service: self.service,
policy: self.policy,
started_at_ms: self.started_at_ms,
heartbeat_at_ms: 0,
fresh_for_ms: self.fresh_for_ms,
expires_at_ms: self.expires_at_ms,
version: self.version,
signature,
}
}
}
#[derive(Serialize)]
struct OnionExitDescriptorBodyRef<'a> {
did: Did,
public_key: &'a VerificationPublicKey,
delegatee_public_key: &'a PublicKey<33>,
process_epoch: OnionProcessEpoch,
node_type: &'a OnlineNodeType,
network_id: u32,
service: &'a OnionServiceName,
policy: &'a OnionExitPolicy,
started_at_ms: u128,
fresh_for_ms: u64,
expires_at_ms: u128,
version: &'a str,
}
impl OnionExitDescriptorBodyRef<'_> {
fn signing_data(&self) -> CoreResult<Vec<u8>> {
rings_codec::serialize(self).map_err(CoreError::CodecSerialize)
}
}
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct OnionExitDescriptor {
pub did: Did,
pub public_key: VerificationPublicKey,
pub delegatee_public_key: PublicKey<33>,
pub process_epoch: OnionProcessEpoch,
pub node_type: OnlineNodeType,
pub network_id: u32,
pub service: OnionServiceName,
pub policy: OnionExitPolicy,
pub started_at_ms: u128,
#[serde(skip)]
pub heartbeat_at_ms: u128,
pub fresh_for_ms: u64,
pub expires_at_ms: u128,
pub version: String,
pub signature: MessageVerification,
}
impl OnionExitDescriptor {
pub fn new_signed(
body: OnionExitDescriptorBody,
signer: MessageSigner<impl Borrow<DelegateeKey>>,
) -> CoreResult<Self> {
sign_descriptor_body(
body,
signer,
"onion exit descriptor DID/public key/session mismatch",
)
}
fn body_ref(&self) -> OnionExitDescriptorBodyRef<'_> {
let Self {
did,
public_key,
delegatee_public_key,
process_epoch,
node_type,
network_id,
service,
policy,
started_at_ms,
heartbeat_at_ms: _,
fresh_for_ms,
expires_at_ms,
version,
signature: _,
} = self;
OnionExitDescriptorBodyRef {
did: *did,
public_key,
delegatee_public_key,
process_epoch: *process_epoch,
node_type,
network_id: *network_id,
service,
policy,
started_at_ms: *started_at_ms,
fresh_for_ms: *fresh_for_ms,
expires_at_ms: *expires_at_ms,
version: version.as_str(),
}
}
fn signing_data(&self) -> CoreResult<Vec<u8>> {
self.body_ref().signing_data()
}
pub fn offers_service(&self, service: &str) -> bool {
self.service.matches(service)
}
pub fn verify_signature(&self, network_id: u32) -> bool {
self.descriptor_verify_signature(network_id)
}
pub fn is_expired_at(&self, now_ms: u128) -> bool {
self.descriptor_is_expired_at(now_ms)
}
pub fn is_live_at(&self, now_ms: u128, network_id: u32) -> bool {
self.descriptor_is_live_at(now_ms, network_id)
}
pub fn latest_valid_by_service_did(
descriptors: impl IntoIterator<Item = Self>,
now_ms: u128,
network_id: u32,
include_expired: bool,
) -> Vec<Self> {
latest_valid_by_key(
descriptors,
Self::registration_key,
now_ms,
network_id,
include_expired,
)
.into_values()
.collect()
}
pub(crate) fn registration_key(&self) -> (Did, OnionServiceName) {
(self.did, self.service.clone())
}
}
impl SignedDescriptor for OnionExitDescriptor {
type Body = OnionExitDescriptorBody;
fn descriptor_did(&self) -> Did {
self.did
}
fn descriptor_public_key(&self) -> &VerificationPublicKey {
&self.public_key
}
fn descriptor_network_id(&self) -> u32 {
self.network_id
}
fn descriptor_signature(&self) -> &MessageVerification {
&self.signature
}
fn descriptor_heartbeat_at_ms(&self) -> u128 {
self.heartbeat_at_ms
}
fn descriptor_expires_at_ms(&self) -> u128 {
self.expires_at_ms
}
fn descriptor_fresh_for_ms(&self) -> u64 {
self.fresh_for_ms
}
fn descriptor_signing_data(&self) -> CoreResult<Vec<u8>> {
self.signing_data()
}
fn heard_at(self, heartbeat_at_ms: u128) -> Self {
Self {
heartbeat_at_ms,
..self
}
}
}
impl RegistryElement for OnionExitDescriptor {}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct OnionExitDescriptorDecodeReport {
pub descriptors: Vec<OnionExitDescriptor>,
pub rejected_values: usize,
}
impl OnionExitDescriptorDecodeReport {
pub const fn has_rejections(&self) -> bool {
self.rejected_values > 0
}
}
#[derive(Clone, Debug)]
pub(crate) struct OnionExitRegistration {
heartbeat_interval: Duration,
node_type: OnlineNodeType,
process_epoch: OnionProcessEpochCell,
clock: SharedClock,
started_at_ms: u128,
offer: OnionExitOffer,
publisher: DhtRegistrationPublisher<Vec<OnionExitDescriptor>>,
}
impl OnionExitRegistration {
#[cfg(all(test, not(target_family = "wasm")))]
pub(crate) fn new(
heartbeat_interval: Duration,
ttl: Duration,
node_type: OnlineNodeType,
offer: OnionExitOffer,
process_epoch: OnionProcessEpochCell,
) -> Self {
Self::new_with_clock(
heartbeat_interval,
ttl,
node_type,
offer,
process_epoch,
Arc::new(SystemClock),
)
}
pub(crate) fn new_with_clock(
heartbeat_interval: Duration,
ttl: Duration,
node_type: OnlineNodeType,
offer: OnionExitOffer,
process_epoch: OnionProcessEpochCell,
clock: SharedClock,
) -> Self {
let started_at_ms = clock.now_ms();
Self {
heartbeat_interval,
node_type,
process_epoch,
clock,
started_at_ms,
offer,
publisher: DhtRegistrationPublisher::new(ONION_EXITS_TOPIC, heartbeat_interval, ttl),
}
}
pub fn descriptors_at(
&self,
context: &RegistrationContext<'_>,
terms: LeaseTerms,
) -> Result<Vec<OnionExitDescriptor>> {
self.offer
.services()
.iter()
.cloned()
.map(|service| self.descriptor_for_service(context, terms, service))
.collect()
}
fn descriptor_for_service(
&self,
context: &RegistrationContext<'_>,
terms: LeaseTerms,
service: OnionServiceName,
) -> Result<OnionExitDescriptor> {
OnionExitDescriptor::new_signed(
OnionExitDescriptorBody {
did: context.did(),
public_key: context.delegator_verification_pubkey()?,
delegatee_public_key: context.delegatee_key().delegatee_public_key(),
process_epoch: self.process_epoch.get(),
node_type: self.node_type.clone(),
network_id: context.network_id(),
service,
policy: self.offer.policy().clone(),
started_at_ms: self.started_at_ms,
fresh_for_ms: terms.fresh_for_ms,
expires_at_ms: terms.expires_at_ms,
version: crate::util::build_version(),
},
context.message_signer(),
)
.map_err(Error::CoreError)
}
pub async fn publish_descriptors(
&self,
context: &RegistrationContext<'_>,
) -> Result<Vec<OnionExitDescriptor>> {
self.publisher
.publish_lease(context, self.clock.now_ms(), |terms| {
self.descriptors_at(context, terms)
})
.await
}
pub fn decode_descriptors_from_entry(
entry: &rings_core::dht::entry::Entry,
) -> OnionExitDescriptorDecodeReport {
let mut report = OnionExitDescriptorDecodeReport::default();
for (value, heard_at_ms) in heard_elements(entry) {
match OnionExitDescriptor::from_element(value) {
Ok(descriptor) => report.descriptors.push(descriptor.heard_at(heard_at_ms)),
Err(error) => {
report.rejected_values = report.rejected_values.saturating_add(1);
tracing::debug!(
"rejected onion-exit descriptor registry value at schema boundary: {error}"
);
}
}
}
report
}
pub fn descriptors_from_entry(
entry: &rings_core::dht::entry::Entry,
) -> Vec<OnionExitDescriptor> {
let report = Self::decode_descriptors_from_entry(entry);
if report.has_rejections() {
tracing::warn!(
rejected_values = report.rejected_values,
"ignored unsupported onion-exit descriptor registry values"
);
}
report.descriptors
}
}
#[cfg_attr(rings_browser, async_trait(?Send))]
#[cfg_attr(rings_native, async_trait)]
impl RegistrationTask for OnionExitRegistration {
fn name(&self) -> &'static str {
"onion-exit"
}
fn interval(&self) -> Duration {
self.heartbeat_interval
}
async fn register_once(&self, context: &RegistrationContext<'_>) -> Result<()> {
self.publish_descriptors(context).await.map(|_| ())
}
}
#[cfg(test)]
pub(crate) mod tests;