rtci_ice/agent/remote_policy.rs
1//! Where connectivity checks may be sent: the remote-address policy.
2//!
3//! Remote candidates come from whoever wrote the remote description (or trickled candidates,
4//! or answered an mDNS query), so the destination of every connectivity check is chosen by the
5//! peer. RFC 8445 §5.1.1.1 says what a candidate address may be (never the unspecified address,
6//! a multicast group or a broadcast address), and §5.1.1.1 also leaves loopback addresses out
7//! unless they are the only ones in use. The agent enforces that here:
8//!
9//! - a remote candidate on an address that cannot be a unicast destination (unspecified,
10//! `0.0.0.0/8`, multicast, the limited broadcast address) or on port 0 is dropped when it is
11//! added, whatever the settings;
12//! - a loopback remote address is paired only with a loopback local candidate, and a
13//! link-local one (`169.254.0.0/16`, `fe80::/10`) only with a link-local local candidate,
14//! unless [`AgentConfig::allow_loopback_remote_candidates`] /
15//! [`AgentConfig::allow_link_local_remote_candidates`] say otherwise. An application that
16//! adds a loopback host candidate has chosen loopback; one that hasn't is never made to send
17//! checks into the host's own services or the link's metadata address;
18//! - [`AgentConfig::remote_address_filter`], when set, is asked about every remote candidate's
19//! address and can refuse it;
20//! - [`AgentConfig::address_policy`], an [`IceAddressPolicy`], is the embedder's policy for
21//! both directions: it is asked about remote candidates, peer-reflexive sources and the
22//! source of every datagram that reaches the agent (and, in the peer connection, about STUN
23//! and TURN servers and ICE-TCP connections), and what it refuses the agent never holds,
24//! answers or takes in.
25//!
26//! IPv4-mapped IPv6 addresses (`::ffff:a.b.c.d`) are judged as the IPv4 address they carry.
27//!
28//! [`AgentConfig::allow_loopback_remote_candidates`]: super::agent_config::AgentConfig::allow_loopback_remote_candidates
29//! [`AgentConfig::allow_link_local_remote_candidates`]: super::agent_config::AgentConfig::allow_link_local_remote_candidates
30//! [`AgentConfig::remote_address_filter`]: super::agent_config::AgentConfig::remote_address_filter
31//! [`AgentConfig::address_policy`]: super::agent_config::AgentConfig::address_policy
32
33use std::net::{IpAddr, SocketAddr};
34use std::sync::Arc;
35
36/// Decides whether connectivity checks may be sent to a remote candidate's address.
37///
38/// Called with the candidate's resolved address (an mDNS candidate's after it resolves) when the
39/// candidate is added; returning `false` drops the candidate. See [`AgentConfig::remote_address_filter`](super::agent_config::AgentConfig::remote_address_filter).
40pub type RemoteAddressFilter = Arc<dyn Fn(SocketAddr) -> bool + Send + Sync>;
41
42/// Which way an address is used, as an [`IceAddressPolicy`] is asked about it.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub enum AddressDirection {
45 /// Traffic from the address would be taken in.
46 Inbound,
47 /// Traffic would be sent to the address.
48 Outbound,
49}
50
51/// Why an [`IceAddressPolicy`] is asked about an address: the point where the address enters
52/// the ICE agent or the peer connection. Each purpose has one direction
53/// ([`AddressPurpose::direction`]).
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
55#[non_exhaustive]
56pub enum AddressPurpose {
57 /// A remote candidate the peer signalled (in a description or trickled), an mDNS candidate
58 /// once its name resolved, or a remote TCP candidate a TURN TCP allocation would open a
59 /// permission or a connection for: a destination of connectivity checks. Outbound.
60 RemoteCandidate,
61 /// The source of an authenticated Binding request that is no known remote candidate, about
62 /// to be learned as a peer-reflexive remote candidate (RFC 8445 Section 7.3.1.3). Inbound.
63 PeerReflexiveSource,
64 /// A STUN or TURN server's address, after its name resolved (or its literal address),
65 /// before the engine sends it anything. Outbound.
66 StunTurnServer,
67 /// The source of a datagram (or of ICE-TCP stream data, or of a peer's connection to a
68 /// listener or a relayed TCP address) about to reach the ICE agent or the peer
69 /// connection's media and DTLS. Inbound.
70 InboundDatagramSource,
71}
72
73impl AddressPurpose {
74 /// The direction the address is used in for this purpose.
75 pub const fn direction(self) -> AddressDirection {
76 match self {
77 AddressPurpose::RemoteCandidate | AddressPurpose::StunTurnServer => {
78 AddressDirection::Outbound
79 }
80 AddressPurpose::PeerReflexiveSource | AddressPurpose::InboundDatagramSource => {
81 AddressDirection::Inbound
82 }
83 }
84 }
85}
86
87/// The predicate of an [`IceAddressPolicy`]: `true` lets the address be used.
88pub type AddressPolicyFn =
89 dyn Fn(SocketAddr, AddressDirection, AddressPurpose) -> bool + Send + Sync;
90
91/// An embedder's address policy for ICE: one predicate asked at every point where an address
92/// enters the ICE agent or the peer connection's stream, TURN and server-reflexive code,
93/// whichever way traffic would go.
94///
95/// - [`AddressPurpose::InboundDatagramSource`]: a datagram (or ICE-TCP stream data) from a
96/// refused source is dropped before the agent reads it: it gets no STUN response, teaches no
97/// peer-reflexive candidate, refreshes no consent, creates no pair, and no DTLS record or
98/// media from it is taken. An ICE-TCP connection from such a source is refused when the
99/// driver reports it accepted, and one a TURN server announces for a relayed TCP address is
100/// not bound.
101/// - [`AddressPurpose::RemoteCandidate`]: a remote candidate on a refused address is never
102/// held or paired (the peer connection treats it as W3C webrtc-pc 4.4.2 "administratively
103/// prohibited": `addIceCandidate` succeeds, no check is ever sent there).
104/// - [`AddressPurpose::PeerReflexiveSource`]: a refused source is not learned as a
105/// peer-reflexive remote candidate, so its request is not answered.
106/// - [`AddressPurpose::StunTurnServer`]: a server address the engine would send its Binding
107/// request or its Allocate to (after the name's resolution) is skipped, as if it had failed.
108///
109/// The predicate sees the address with an IPv4-mapped IPv6 address (`::ffff:a.b.c.d`) given as
110/// the IPv4 address it carries, so one rule covers both forms. The default allows everything
111/// and asks nothing: the agent behaves as it does without a policy.
112///
113/// RFC 8445's procedures (Section 7.3: answer every authenticated request, Section 7.3.1.3:
114/// learn its source as a peer-reflexive candidate) apply to what reaches the agent; a datagram
115/// the policy refuses is dropped before that, as a host firewall would drop it. This is how an
116/// embedder carries out the address handling of RFC 8828 (which modes of address exposure and
117/// which routes are allowed) beyond what the candidate types alone can say.
118#[derive(Clone, Default)]
119pub struct IceAddressPolicy(Option<Arc<AddressPolicyFn>>);
120
121impl IceAddressPolicy {
122 /// A policy asking `predicate` about every address; `false` refuses it.
123 pub fn new(
124 predicate: impl Fn(SocketAddr, AddressDirection, AddressPurpose) -> bool + Send + Sync + 'static,
125 ) -> Self {
126 Self(Some(Arc::new(predicate)))
127 }
128
129 /// The default: every address is allowed and the predicate is never asked.
130 pub fn allow_all() -> Self {
131 Self(None)
132 }
133
134 /// Whether this is the allow-everything default.
135 pub fn is_allow_all(&self) -> bool {
136 self.0.is_none()
137 }
138
139 /// Whether `addr` may be used for `purpose` (in that purpose's direction).
140 pub fn allows(&self, addr: SocketAddr, purpose: AddressPurpose) -> bool {
141 let Some(predicate) = &self.0 else {
142 return true;
143 };
144 let addr = SocketAddr::new(addr.ip().to_canonical(), addr.port());
145 predicate(addr, purpose.direction(), purpose)
146 }
147}
148
149impl std::fmt::Debug for IceAddressPolicy {
150 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151 f.write_str(if self.0.is_some() {
152 "IceAddressPolicy(predicate)"
153 } else {
154 "IceAddressPolicy(allow all)"
155 })
156 }
157}
158
159/// What kind of destination an address is, for the policy.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub(crate) enum AddressScope {
162 /// Never a valid unicast destination (or port 0).
163 Invalid,
164 /// `127.0.0.0/8`, `::1`.
165 Loopback,
166 /// `169.254.0.0/16`, `fe80::/10`.
167 LinkLocal,
168 /// Anything else.
169 Other,
170}
171
172/// Classifies `addr` as a destination: port 0 is [`AddressScope::Invalid`] too.
173pub(crate) fn address_scope(addr: SocketAddr) -> AddressScope {
174 if addr.port() == 0 {
175 return AddressScope::Invalid;
176 }
177 ip_scope(addr.ip())
178}
179
180/// Classifies `ip`; an IPv4-mapped IPv6 address is judged as its IPv4 address.
181pub(crate) fn ip_scope(ip: IpAddr) -> AddressScope {
182 match ip.to_canonical() {
183 IpAddr::V4(v4) => {
184 if v4.octets()[0] == 0 || v4.is_multicast() || v4.is_broadcast() {
185 // 0.0.0.0/8 is "this network" (RFC 1122 §3.2.1.3): a source, never a
186 // destination; 0.0.0.0 itself is the unspecified address.
187 AddressScope::Invalid
188 } else if v4.is_loopback() {
189 AddressScope::Loopback
190 } else if v4.is_link_local() {
191 AddressScope::LinkLocal
192 } else {
193 AddressScope::Other
194 }
195 }
196 IpAddr::V6(v6) => {
197 if v6.is_unspecified() || v6.is_multicast() {
198 AddressScope::Invalid
199 } else if v6.is_loopback() {
200 AddressScope::Loopback
201 } else if v6.is_unicast_link_local() {
202 AddressScope::LinkLocal
203 } else {
204 AddressScope::Other
205 }
206 }
207 }
208}
209
210/// The agent's remote-address policy, built once from its [`AgentConfig`](super::agent_config::AgentConfig).
211#[derive(Clone, Default)]
212pub(crate) struct RemotePolicy {
213 pub(crate) allow_loopback: bool,
214 pub(crate) allow_link_local: bool,
215 pub(crate) filter: Option<RemoteAddressFilter>,
216 /// The embedder's address policy ([`AgentConfig::address_policy`](super::agent_config::AgentConfig::address_policy)).
217 pub(crate) address: IceAddressPolicy,
218}
219
220impl RemotePolicy {
221 /// Whether a remote candidate on `remote` may be held, for `purpose` (a signalled or
222 /// resolved candidate, or a peer-reflexive source): [`Self::allows_candidate`] and the
223 /// embedder's address policy.
224 pub(crate) fn allows_remote(&self, remote: SocketAddr, purpose: AddressPurpose) -> bool {
225 self.allows_candidate(remote) && self.address.allows(remote, purpose)
226 }
227
228 /// Whether traffic from `source` may reach the agent at all.
229 pub(crate) fn allows_source(&self, source: SocketAddr) -> bool {
230 self.address
231 .allows(source, AddressPurpose::InboundDatagramSource)
232 }
233
234 /// Whether a remote candidate on `remote` may be held at all.
235 pub(crate) fn allows_candidate(&self, remote: SocketAddr) -> bool {
236 if address_scope(remote) == AddressScope::Invalid {
237 return false;
238 }
239 self.filter.as_ref().is_none_or(|filter| filter(remote))
240 }
241
242 /// Whether checks may be sent from the local candidate based at `local` to `remote`.
243 pub(crate) fn allows_pair(&self, local: SocketAddr, remote: SocketAddr) -> bool {
244 // RFC 8445 Section 6.1.2.2: "IPv6 link-local addresses MUST NOT be paired with other
245 // than link-local addresses", in either direction, whatever the settings say.
246 let v6_link_local =
247 |ip: IpAddr| matches!(ip.to_canonical(), IpAddr::V6(v6) if v6.is_unicast_link_local());
248 if v6_link_local(local.ip()) != v6_link_local(remote.ip())
249 && address_scope(remote) != AddressScope::Invalid
250 {
251 return false;
252 }
253 match address_scope(remote) {
254 AddressScope::Invalid => false,
255 AddressScope::Loopback => {
256 self.allow_loopback || ip_scope(local.ip()) == AddressScope::Loopback
257 }
258 AddressScope::LinkLocal => {
259 self.allow_link_local || ip_scope(local.ip()) == AddressScope::LinkLocal
260 }
261 AddressScope::Other => true,
262 }
263 }
264}