netstack3_filter/
state.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5pub mod validation;
6
7use alloc::format;
8use alloc::string::ToString as _;
9use alloc::sync::Arc;
10use alloc::vec::Vec;
11use core::fmt::Debug;
12use core::hash::{Hash, Hasher};
13use core::num::NonZeroU16;
14use core::ops::RangeInclusive;
15
16use derivative::Derivative;
17use net_types::ip::{GenericOverIp, Ip};
18use netstack3_base::{
19    CoreTimerContext, Inspectable, InspectableValue, Inspector as _, MarkDomain,
20    MatcherBindingsTypes,
21};
22use packet_formats::ip::IpExt;
23
24use crate::actions::MarkAction;
25use crate::conntrack::{self, ConnectionDirection};
26use crate::context::{FilterBindingsContext, FilterBindingsTypes};
27use crate::logic::FilterTimerId;
28use crate::logic::nat::NatConfig;
29use crate::matchers::PacketMatcher;
30use crate::state::validation::ValidRoutines;
31
32/// The action to take on a packet.
33#[derive(Derivative)]
34#[derivative(Clone(bound = "RuleInfo: Clone"), Debug(bound = ""))]
35pub enum Action<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> {
36    /// Accept the packet.
37    ///
38    /// This is a terminal action for the current *installed* routine, i.e. no
39    /// further rules will be evaluated for this packet in the installed routine
40    /// (or any subroutines) in which this rule is installed. Subsequent
41    /// routines installed on the same hook will still be evaluated.
42    Accept,
43    /// Drop the packet.
44    ///
45    /// This is a terminal action for the current hook, i.e. no further rules
46    /// will be evaluated for this packet, even in other routines on the same
47    /// hook.
48    Drop,
49    /// Jump from the current routine to the specified uninstalled routine.
50    Jump(UninstalledRoutine<I, BT, RuleInfo>),
51    /// Stop evaluation of the current routine and return to the calling routine
52    /// (the routine from which the current routine was jumped), continuing
53    /// evaluation at the next rule.
54    ///
55    /// If invoked in an installed routine, equivalent to `Accept`, given
56    /// packets are accepted by default in the absence of any matching rules.
57    Return,
58    /// Redirect the packet to a local socket without changing the packet header
59    /// in any way.
60    ///
61    /// This is a terminal action for the current hook, i.e. no further rules
62    /// will be evaluated for this packet, even in other routines on the same
63    /// hook. However, note that this does not preclude actions on *other* hooks
64    /// from having an effect on this packet; for example, a packet that hits
65    /// TransparentProxy in INGRESS could still be dropped in LOCAL_INGRESS.
66    ///
67    /// This action is only valid in the INGRESS hook. This action is also only
68    /// valid in a rule that ensures the presence of a TCP or UDP header by
69    /// matching on the transport protocol, so that the packet can be properly
70    /// dispatched.
71    ///
72    /// Also note that transparently proxied packets will only be delivered to
73    /// sockets with the transparent socket option enabled.
74    TransparentProxy(TransparentProxy<I>),
75    /// A special case of destination NAT (DNAT) that redirects the packet to
76    /// the local host.
77    ///
78    /// This is a terminal action for all NAT routines on the current hook. The
79    /// packet is redirected by rewriting the destination IP address to one
80    /// owned by the ingress interface (if operating on incoming traffic in
81    /// INGRESS) or the loopback address (if operating on locally-generated
82    /// traffic in LOCAL_EGRESS). If this rule is installed on INGRESS and no IP
83    /// address is assigned to the incoming interface, the packet is dropped.
84    ///
85    /// As with all DNAT actions, this action is only valid in the INGRESS and
86    /// LOCAL_EGRESS hooks. If a destination port is specified, this action is
87    /// only valid in a rule that ensures the presence of a TCP or UDP header by
88    /// matching on the transport protocol, so that the destination port can be
89    /// rewritten.
90    ///
91    /// This is analogous to the `redirect` statement in Netfilter.
92    Redirect {
93        /// The optional range of destination ports used to rewrite the packet.
94        ///
95        /// If specified, the destination port of the packet will be rewritten
96        /// to some randomly chosen port in the range. If absent, the
97        /// destination port of the packet will not be rewritten.
98        dst_port: Option<RangeInclusive<NonZeroU16>>,
99    },
100    /// A special case of source NAT (SNAT) that reassigns the source IP address
101    /// of the packet to an address that is assigned to the outgoing interface.
102    ///
103    /// This is a terminal action for all NAT routines on the current hook. If
104    /// no address is assigned to the outgoing interface, the packet will be
105    /// dropped.
106    ///
107    /// This action is only valid in the EGRESS hook. If a source port range is
108    /// specified, this action is only valid in a rule that ensures the presence
109    /// of a TCP or UDP header by matching on the transport protocol, so that
110    /// the source port can be rewritten.
111    ///
112    /// This is analogous to the `masquerade` statement in Netfilter.
113    Masquerade {
114        /// The optional range of source ports used to rewrite the packet.
115        ///
116        /// The source port will be rewritten if necessary to ensure the
117        /// packet's flow does not conflict with an existing tracked connection.
118        /// Note that the source port may be rewritten whether or not this range
119        /// is specified.
120        ///
121        /// If specified, this overrides the default behavior and restricts the
122        /// range of possible values to which the source port can be rewritten.
123        src_port: Option<RangeInclusive<NonZeroU16>>,
124    },
125    /// Applies the mark action to the given mark domain.
126    ///
127    /// This is a non-terminal action for both routines and hooks. This is also
128    /// only available in [`IpRoutines`] because [`NatRoutines`] only runs on
129    /// the first packet in a connection and it is likely a misconfiguration
130    /// that packets after the first are marked differently or unmarked.
131    ///
132    /// Note: If we find use cases that justify this being in [`NatRoutines`] we
133    /// should relax this limitation and support it.
134    ///
135    /// This is analogous to the `mark` statement in Netfilter.
136    Mark {
137        /// The domain to apply the mark action.
138        domain: MarkDomain,
139        /// The action to apply.
140        action: MarkAction,
141    },
142
143    /// No action.
144    None,
145}
146
147/// Transparently intercept the packet and deliver it to a local socket without
148/// changing the packet header.
149///
150/// When a local address is specified, it is the bound address of the local
151/// socket to redirect the packet to. When absent, the destination IP address of
152/// the packet is used for local delivery.
153///
154/// When a local port is specified, it is the bound port of the local socket to
155/// redirect the packet to. When absent, the destination port of the packet is
156/// used for local delivery.
157#[derive(Debug, Clone)]
158#[allow(missing_docs)]
159pub enum TransparentProxy<I: IpExt> {
160    LocalAddr(I::Addr),
161    LocalPort(NonZeroU16),
162    LocalAddrAndPort(I::Addr, NonZeroU16),
163}
164
165impl<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> Inspectable for Action<I, BT, RuleInfo> {
166    fn record<Inspector: netstack3_base::Inspector>(&self, inspector: &mut Inspector) {
167        let value = match self {
168            Self::Accept
169            | Self::Drop
170            | Self::Return
171            | Self::TransparentProxy(_)
172            | Self::Redirect { .. }
173            | Self::Masquerade { .. }
174            | Self::Mark { .. }
175            | Self::None => {
176                format!("{self:?}")
177            }
178            Self::Jump(UninstalledRoutine { routine: _, id }) => {
179                format!("Jump(UninstalledRoutine({id:?}))")
180            }
181        };
182        inspector.record_string("action", value);
183    }
184}
185
186/// A handle to a [`Routine`] that is not installed in a particular hook, and
187/// therefore is only run if jumped to from another routine.
188#[derive(Derivative)]
189#[derivative(Clone(bound = ""), Debug(bound = ""))]
190pub struct UninstalledRoutine<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> {
191    pub(crate) routine: Arc<Routine<I, BT, RuleInfo>>,
192    id: usize,
193}
194
195impl<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> UninstalledRoutine<I, BT, RuleInfo> {
196    /// Creates a new uninstalled routine with the provided contents.
197    pub fn new(rules: Vec<Rule<I, BT, RuleInfo>>, id: usize) -> Self {
198        Self { routine: Arc::new(Routine { rules }), id }
199    }
200
201    /// Returns the inner routine.
202    pub fn get(&self) -> &Routine<I, BT, RuleInfo> {
203        &*self.routine
204    }
205}
206
207impl<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> PartialEq
208    for UninstalledRoutine<I, BT, RuleInfo>
209{
210    fn eq(&self, other: &Self) -> bool {
211        let Self { routine: lhs, id: _ } = self;
212        let Self { routine: rhs, id: _ } = other;
213        Arc::ptr_eq(lhs, rhs)
214    }
215}
216
217impl<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> Eq for UninstalledRoutine<I, BT, RuleInfo> {}
218
219impl<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> Hash for UninstalledRoutine<I, BT, RuleInfo> {
220    fn hash<H: Hasher>(&self, state: &mut H) {
221        let Self { routine, id: _ } = self;
222        Arc::as_ptr(routine).hash(state)
223    }
224}
225
226impl<I: IpExt, BT: MatcherBindingsTypes> Inspectable for UninstalledRoutine<I, BT, ()> {
227    fn record<Inspector: netstack3_base::Inspector>(&self, inspector: &mut Inspector) {
228        let Self { routine, id } = self;
229        inspector.record_child(&id.to_string(), |inspector| {
230            inspector.delegate_inspectable(&**routine);
231        });
232    }
233}
234
235/// A set of criteria (matchers) and a resultant action to take if a given
236/// packet matches.
237#[derive(Derivative, GenericOverIp)]
238#[generic_over_ip(I, Ip)]
239#[derivative(Clone(bound = "RuleInfo: Clone"), Debug(bound = ""))]
240pub struct Rule<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> {
241    /// The criteria that a packet must match for the action to be executed.
242    pub matcher: PacketMatcher<I, BT>,
243    /// The action to take on a matching packet.
244    pub action: Action<I, BT, RuleInfo>,
245    /// Opaque information about this rule for use when validating and
246    /// converting state provided by Bindings into Core filtering state. This is
247    /// only used when installing filtering state, and allows Core to report to
248    /// Bindings which rule caused a particular error. It is zero-sized for
249    /// validated state.
250    #[derivative(Debug = "ignore")]
251    pub validation_info: RuleInfo,
252}
253
254impl<I: IpExt, BT: MatcherBindingsTypes> Inspectable for Rule<I, BT, ()> {
255    fn record<Inspector: netstack3_base::Inspector>(&self, inspector: &mut Inspector) {
256        let Self { matcher, action, validation_info: () } = self;
257        inspector.record_child("matchers", |inspector| {
258            let PacketMatcher {
259                in_interface,
260                out_interface,
261                src_address,
262                dst_address,
263                transport_protocol,
264                external_matcher,
265            } = matcher;
266
267            fn record_matcher<Inspector: netstack3_base::Inspector, M: InspectableValue>(
268                inspector: &mut Inspector,
269                name: &str,
270                matcher: &Option<M>,
271            ) {
272                if let Some(matcher) = matcher {
273                    inspector.record_inspectable_value(name, matcher);
274                }
275            }
276
277            record_matcher(inspector, "in_interface", in_interface);
278            record_matcher(inspector, "out_interface", out_interface);
279            record_matcher(inspector, "src_address", src_address);
280            record_matcher(inspector, "dst_address", dst_address);
281            record_matcher(inspector, "transport_protocol", transport_protocol);
282            record_matcher(inspector, "external_matcher", external_matcher);
283        });
284        inspector.delegate_inspectable(action);
285    }
286}
287
288/// A sequence of [`Rule`]s.
289#[derive(Derivative, GenericOverIp)]
290#[generic_over_ip(I, Ip)]
291#[derivative(Clone(bound = "RuleInfo: Clone"), Debug(bound = ""))]
292pub struct Routine<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> {
293    /// The rules to be executed in order.
294    pub rules: Vec<Rule<I, BT, RuleInfo>>,
295}
296
297impl<I: IpExt, BT: MatcherBindingsTypes> Inspectable for Routine<I, BT, ()> {
298    fn record<Inspector: netstack3_base::Inspector>(&self, inspector: &mut Inspector) {
299        let Self { rules } = self;
300        inspector.record_usize("rules", rules.len());
301        for rule in rules {
302            inspector.record_unnamed_child(|inspector| inspector.delegate_inspectable(rule));
303        }
304    }
305}
306
307/// A particular entry point for packet processing in which filtering routines
308/// are installed.
309#[derive(Derivative, GenericOverIp)]
310#[generic_over_ip(I, Ip)]
311#[derivative(Default(bound = ""), Debug(bound = ""))]
312pub struct Hook<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> {
313    /// The routines to be executed in order.
314    pub routines: Vec<Routine<I, BT, RuleInfo>>,
315}
316
317impl<I: IpExt, BT: MatcherBindingsTypes> Inspectable for Hook<I, BT, ()> {
318    fn record<Inspector: netstack3_base::Inspector>(&self, inspector: &mut Inspector) {
319        let Self { routines } = self;
320        inspector.record_usize("routines", routines.len());
321        for routine in routines {
322            inspector.record_unnamed_child(|inspector| {
323                inspector.delegate_inspectable(routine);
324            });
325        }
326    }
327}
328
329/// Routines that perform ordinary IP filtering.
330#[derive(Derivative)]
331#[derivative(Default(bound = ""), Debug(bound = ""))]
332pub struct IpRoutines<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> {
333    /// Occurs for incoming traffic before a routing decision has been made.
334    pub ingress: Hook<I, BT, RuleInfo>,
335    /// Occurs for incoming traffic that is destined for the local host.
336    pub local_ingress: Hook<I, BT, RuleInfo>,
337    /// Occurs for incoming traffic that is destined for another node.
338    pub forwarding: Hook<I, BT, RuleInfo>,
339    /// Occurs for locally-generated traffic before a final routing decision has
340    /// been made.
341    pub local_egress: Hook<I, BT, RuleInfo>,
342    /// Occurs for all outgoing traffic after a routing decision has been made.
343    pub egress: Hook<I, BT, RuleInfo>,
344}
345
346impl<I: IpExt, BT: MatcherBindingsTypes> Inspectable for IpRoutines<I, BT, ()> {
347    fn record<Inspector: netstack3_base::Inspector>(&self, inspector: &mut Inspector) {
348        let Self { ingress, local_ingress, forwarding, local_egress, egress } = self;
349
350        inspector.record_child("ingress", |inspector| inspector.delegate_inspectable(ingress));
351        inspector.record_child("local_ingress", |inspector| {
352            inspector.delegate_inspectable(local_ingress)
353        });
354        inspector
355            .record_child("forwarding", |inspector| inspector.delegate_inspectable(forwarding));
356        inspector
357            .record_child("local_egress", |inspector| inspector.delegate_inspectable(local_egress));
358        inspector.record_child("egress", |inspector| inspector.delegate_inspectable(egress));
359    }
360}
361
362/// Routines that can perform NAT.
363///
364/// Note that NAT routines are only executed *once* for a given connection, for
365/// the first packet in the flow.
366#[derive(Derivative)]
367#[derivative(Default(bound = ""), Debug(bound = ""))]
368pub struct NatRoutines<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> {
369    /// Occurs for incoming traffic before a routing decision has been made.
370    pub ingress: Hook<I, BT, RuleInfo>,
371    /// Occurs for incoming traffic that is destined for the local host.
372    pub local_ingress: Hook<I, BT, RuleInfo>,
373    /// Occurs for locally-generated traffic before a final routing decision has
374    /// been made.
375    pub local_egress: Hook<I, BT, RuleInfo>,
376    /// Occurs for all outgoing traffic after a routing decision has been made.
377    pub egress: Hook<I, BT, RuleInfo>,
378}
379
380impl<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> NatRoutines<I, BT, RuleInfo> {
381    pub(crate) fn contains_rules(&self) -> bool {
382        let Self { ingress, local_ingress, local_egress, egress } = self;
383
384        let hook_contains_rules =
385            |hook: &Hook<_, _, _>| hook.routines.iter().any(|routine| !routine.rules.is_empty());
386        hook_contains_rules(&ingress)
387            || hook_contains_rules(&local_ingress)
388            || hook_contains_rules(&local_egress)
389            || hook_contains_rules(&egress)
390    }
391}
392
393impl<I: IpExt, BT: MatcherBindingsTypes> Inspectable for NatRoutines<I, BT, ()> {
394    fn record<Inspector: netstack3_base::Inspector>(&self, inspector: &mut Inspector) {
395        let Self { ingress, local_ingress, local_egress, egress } = self;
396
397        inspector.record_child("ingress", |inspector| inspector.delegate_inspectable(ingress));
398        inspector.record_child("local_ingress", |inspector| {
399            inspector.delegate_inspectable(local_ingress)
400        });
401        inspector
402            .record_child("local_egress", |inspector| inspector.delegate_inspectable(local_egress));
403        inspector.record_child("egress", |inspector| inspector.delegate_inspectable(egress));
404    }
405}
406
407/// IP version-specific filtering routine state.
408#[derive(Derivative, GenericOverIp)]
409#[generic_over_ip(I, Ip)]
410#[derivative(Default(bound = ""), Debug(bound = ""))]
411pub struct Routines<I: IpExt, BT: MatcherBindingsTypes, RuleInfo> {
412    /// Routines that perform IP filtering.
413    pub ip: IpRoutines<I, BT, RuleInfo>,
414    /// Routines that perform IP filtering and NAT.
415    pub nat: NatRoutines<I, BT, RuleInfo>,
416}
417
418/// A one-way boolean toggle that can only go from `false` to `true`.
419///
420/// Once it has been flipped to `true`, it will remain in that state forever.
421#[derive(Default)]
422pub struct OneWayBoolean(bool);
423
424impl OneWayBoolean {
425    /// A [`OneWayBoolean`] that is enabled on creation.
426    pub const TRUE: Self = Self(true);
427
428    /// Get the value of the boolean.
429    pub fn get(&self) -> bool {
430        let Self(inner) = self;
431        *inner
432    }
433
434    /// Toggle the boolean to `true`.
435    ///
436    /// This operation is idempotent: even though the [`OneWayBoolean`]'s value will
437    /// only ever change from `false` to `true` once, this method can be called any
438    /// number of times safely and the value will remain `true`.
439    pub fn set(&mut self) {
440        let Self(inner) = self;
441        *inner = true;
442    }
443}
444
445/// IP version-specific filtering state.
446pub struct State<I: IpExt, A, BT: FilterBindingsTypes> {
447    /// Routines used for filtering packets that are installed on hooks.
448    pub installed_routines: ValidRoutines<I, BT>,
449    /// Routines that are only executed if jumped to from other routines.
450    ///
451    /// Jump rules refer to their targets by holding a reference counted pointer
452    /// to the inner routine; we hold this index of all uninstalled routines
453    /// that have any references in order to report them in inspect data.
454    pub(crate) uninstalled_routines: Vec<UninstalledRoutine<I, BT, ()>>,
455    /// Connection tracking state.
456    pub conntrack: conntrack::Table<I, NatConfig<I, A>, BT>,
457    /// One-way boolean toggle indicating whether any rules have ever been added to
458    /// an installed NAT routine. If not, performing NAT can safely be skipped.
459    ///
460    /// This is useful because if any NAT is being performed, we have to check
461    /// whether it's necessary to perform implicit NAT for *all* traffic -- even if
462    /// it doesn't match any NAT rules -- to avoid conflicting tracked connections.
463    /// If we know that no NAT is being performed at all, this extra work can be
464    /// avoided.
465    ///
466    /// Note that this value will only ever go from false to true; it does not
467    /// indicate whether any NAT rules are *currently* installed. This avoids a race
468    /// condition where NAT rules are removed but connections are still being NATed
469    /// based on those rules, and therefore must be considered when creating new
470    /// connection tracking entries.
471    pub nat_installed: OneWayBoolean,
472}
473
474impl<I: IpExt, A, BC: FilterBindingsContext> State<I, A, BC> {
475    /// Create a new State.
476    pub fn new<CC: CoreTimerContext<FilterTimerId<I>, BC>>(bindings_ctx: &mut BC) -> Self {
477        Self {
478            installed_routines: Default::default(),
479            uninstalled_routines: Default::default(),
480            conntrack: conntrack::Table::new::<CC>(bindings_ctx),
481            nat_installed: OneWayBoolean::default(),
482        }
483    }
484}
485
486impl<I: IpExt, A: InspectableValue, BT: FilterBindingsTypes> Inspectable for State<I, A, BT> {
487    fn record<Inspector: netstack3_base::Inspector>(&self, inspector: &mut Inspector) {
488        let Self { installed_routines, uninstalled_routines, conntrack, nat_installed: _ } = self;
489        let Routines { ip, nat } = installed_routines.get();
490
491        inspector.record_child("IP", |inspector| inspector.delegate_inspectable(ip));
492        inspector.record_child("NAT", |inspector| inspector.delegate_inspectable(nat));
493        inspector.record_child("uninstalled", |inspector| {
494            inspector.record_usize("routines", uninstalled_routines.len());
495            for routine in uninstalled_routines {
496                inspector.delegate_inspectable(routine);
497            }
498        });
499
500        inspector.record_child("conntrack", |inspector| {
501            inspector.delegate_inspectable(conntrack);
502        });
503    }
504}
505
506/// A trait for interacting with the pieces of packet metadata that are
507/// important for filtering.
508pub trait FilterIpMetadata<I: IpExt, A, BT: FilterBindingsTypes>: FilterMarkMetadata {
509    /// Removes the conntrack connection and packet direction, if they exist.
510    fn take_connection_and_direction(
511        &mut self,
512    ) -> Option<(conntrack::Connection<I, NatConfig<I, A>, BT>, ConnectionDirection)>;
513
514    /// Puts a new conntrack connection and packet direction into the metadata
515    /// struct, returning the previous connection value, if one existed.
516    fn replace_connection_and_direction(
517        &mut self,
518        conn: conntrack::Connection<I, NatConfig<I, A>, BT>,
519        direction: ConnectionDirection,
520    ) -> Option<conntrack::Connection<I, NatConfig<I, A>, BT>>;
521}
522
523/// A trait for interacting with packet mark metadata.
524//
525// The reason why we split this trait from the `FilterIpMetadata` is to avoid
526// introducing trait bounds and type parameters into methods that only need
527// to change the mark, for example, all the `check_routine*` methods. Those
528// methods does not need the ability to take conntrack related information. This
529// becomes a meaningful simplification for those cases.
530pub trait FilterMarkMetadata {
531    /// Applies the mark action to the metadata.
532    fn apply_mark_action(&mut self, domain: MarkDomain, action: MarkAction);
533}