Skip to main content

netstack3_filter/logic/
nat.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
5//! Network Address Translation.
6
7use core::fmt::Debug;
8use core::num::NonZeroU16;
9use core::ops::{ControlFlow, RangeInclusive};
10
11use derivative::Derivative;
12use log::{error, warn};
13use net_types::SpecifiedAddr;
14use net_types::ip::IpVersionMarker;
15use netstack3_base::sync::{Mutex, OnceLock};
16use netstack3_base::{
17    Inspectable, InspectableValue, Inspector as _, IpAddressId as _, IpDeviceAddr, WeakIpAddressId,
18};
19use packet_formats::ip::IpExt;
20use rand::RngExt as _;
21
22use crate::FilterBindingsContext;
23use crate::conntrack::{
24    CompatibleWith, Connection, ConnectionDirection, ConnectionExclusive, Table, TransportTuple,
25    Tuple,
26};
27use crate::context::{FilterBindingsTypes, NatContext};
28use crate::logic::{Accept, DropPacket, Interfaces, RoutineResult, Verdict};
29use crate::packets::{
30    FilterIpExt, FilterIpPacket, IcmpErrorMut, IpPacket, MaybeIcmpErrorMut as _,
31    MaybeTransportPacketMut as _, TransportPacketMut as _,
32};
33use crate::state::{FilterPacketMetadata, Hook};
34
35/// The NAT configuration for a given conntrack connection.
36///
37/// Each type of NAT (source and destination) is configured exactly once for a
38/// given connection, for the first packet encountered on that connection. This
39/// is not to say that all connections are NATed: the configuration can be
40/// either `ShouldNat::Yes` or `ShouldNat::No`, but the `OnceLock` containing
41/// the configuration should, in most cases, be initialized by the time a
42/// connection is inserted in the conntrack table.
43#[derive(Derivative)]
44#[derivative(Default(bound = ""), Debug(bound = "A: Debug"), PartialEq(bound = ""))]
45pub struct NatConfig<I: IpExt, A, BT: FilterBindingsTypes> {
46    destination: OnceLock<ShouldNat<I, A, BT>, BT::Once>,
47    source: OnceLock<ShouldNat<I, A, BT>, BT::Once>,
48}
49
50/// The NAT configuration for a given type of NAT (either source or
51/// destination).
52#[derive(Derivative)]
53#[derivative(Debug(bound = "A: Debug"), PartialEq(bound = ""))]
54pub(crate) enum ShouldNat<I: IpExt, A, BT: FilterBindingsTypes> {
55    /// NAT should be performed on this connection.
56    ///
57    /// Optionally contains a `CachedAddr`, which is a weak reference to the address
58    /// used for NAT, if it is a dynamically assigned IP address owned by the stack.
59    Yes(#[derivative(PartialEq = "ignore")] Option<CachedAddr<I, A, BT>>),
60    /// NAT should not be performed on this connection.
61    No,
62}
63
64impl<I: IpExt, A: PartialEq, BT: FilterBindingsTypes> CompatibleWith for NatConfig<I, A, BT> {
65    fn compatible_with(&self, other: &Self) -> bool {
66        // Check for both SNAT and DNAT that either NAT is configured with the same
67        // value, or that it is unconfigured. When determining whether two connections
68        // are compatible, if NAT is configured differently for both, they are not
69        // compatible, but if NAT is either unconfigured or matches, they are considered
70        // to be compatible.
71        self.source.get().unwrap_or(&ShouldNat::No) == other.source.get().unwrap_or(&ShouldNat::No)
72            && self.destination.get().unwrap_or(&ShouldNat::No)
73                == other.destination.get().unwrap_or(&ShouldNat::No)
74    }
75}
76
77impl<I: IpExt, A, BT: FilterBindingsTypes> Connection<I, NatConfig<I, A, BT>, BT> {
78    pub fn destination_nat(&self) -> bool {
79        match self.external_data().destination.get() {
80            Some(ShouldNat::Yes(_)) => true,
81            Some(ShouldNat::No) | None => false,
82        }
83    }
84}
85
86impl<I: IpExt, A: InspectableValue, BT: FilterBindingsTypes> Inspectable for NatConfig<I, A, BT> {
87    fn record<Inspector: netstack3_base::Inspector>(&self, inspector: &mut Inspector) {
88        fn record_nat_status<
89            I: IpExt,
90            A: InspectableValue,
91            BT: FilterBindingsTypes,
92            Inspector: netstack3_base::Inspector,
93        >(
94            inspector: &mut Inspector,
95            config: &OnceLock<ShouldNat<I, A, BT>, BT::Once>,
96        ) {
97            let status = match config.get() {
98                None => "Unconfigured",
99                Some(ShouldNat::No) => "No-op",
100                Some(ShouldNat::Yes(cached_addr)) => {
101                    if let Some(CachedAddr { id, _marker }) = cached_addr {
102                        match &*id.lock() {
103                            Some(id) => inspector.record_inspectable_value("To", id),
104                            None => inspector.record_str("To", "InvalidAddress"),
105                        }
106                    }
107                    "NAT"
108                }
109            };
110            inspector.record_str("Status", status);
111        }
112
113        let Self { source, destination } = self;
114        inspector.record_child("NAT", |inspector| {
115            inspector
116                .record_child("Destination", |inspector| record_nat_status(inspector, destination));
117            inspector.record_child("Source", |inspector| record_nat_status(inspector, source));
118        });
119    }
120}
121
122/// A weak handle to the address assigned to a device. Allows checking for
123/// validity when using the address for NAT.
124#[derive(Derivative)]
125#[derivative(Debug(bound = "A: Debug"))]
126pub(crate) struct CachedAddr<I: IpExt, A, BT: FilterBindingsTypes> {
127    id: Mutex<Option<A>, BT::Mutex>,
128    _marker: IpVersionMarker<I>,
129}
130
131impl<I: IpExt, A, BT: FilterBindingsTypes> CachedAddr<I, A, BT> {
132    fn new(id: A) -> Self {
133        Self { id: Mutex::new(Some(id)), _marker: IpVersionMarker::new() }
134    }
135}
136
137impl<I: IpExt, A: WeakIpAddressId<I::Addr>, BT: FilterBindingsTypes> CachedAddr<I, A, BT> {
138    /// Check whether the provided IP address is still valid to be used for NAT.
139    ///
140    /// If the address is no longer valid, attempts to acquire a new handle to the
141    /// same address.
142    fn validate_or_replace<CC>(
143        &self,
144        core_ctx: &mut CC,
145        device: &CC::DeviceId,
146        addr: I::Addr,
147    ) -> Verdict<DropPacket>
148    where
149        CC: NatContext<I, BT, WeakAddressId = A>,
150    {
151        let Self { id, _marker } = self;
152
153        // If the address ID is still valid, use the address for NAT.
154        {
155            if id.lock().as_ref().map(|id| id.is_assigned()).unwrap_or(false) {
156                return Verdict::Proceed(Accept);
157            }
158        }
159
160        // Otherwise, try to re-acquire a new handle to the same address in case it has
161        // since been re-added to the device.
162        //
163        // NB: we release the lock around the `Option<WeakIpAddressId>` while we request
164        // a new address ID and then reacquire it to assign it in order to avoid any
165        // possible lock ordering issues. This does mean that there is a potential race
166        // here between two packets in the same conntrack flow updating `id`, but `id`
167        // should be eventually consistent with the state of the device addresses given
168        // each subsequent packet will check for its validity and try to update it if
169        // necessary.
170        match IpDeviceAddr::new(addr).and_then(|addr| core_ctx.get_address_id(device, addr)) {
171            Some(new) => {
172                *id.lock() = Some(new.downgrade());
173                Verdict::Proceed(Accept)
174            }
175            // If either the address we are using for NAT is not a valid `IpDeviceAddr` or
176            // the address is no longer assigned to the device, drop the ID, both to avoid
177            // further futile attempts to upgrade the weak reference and to allow the
178            // backing memory to be deallocated.
179            None => {
180                *id.lock() = None;
181                Verdict::Stop(DropPacket)
182            }
183        }
184    }
185}
186
187/// A type of NAT that is performed on a given conntrack connection.
188#[derive(Debug, Clone, Copy, PartialEq)]
189pub enum NatType {
190    /// Destination NAT is performed.
191    Destination,
192    /// Source NAT is performed.
193    Source,
194}
195
196pub(crate) trait NatHook<I: FilterIpExt> {
197    const NAT_TYPE: NatType;
198
199    /// Evaluate the result of a given routine and returning the resulting control
200    /// flow.
201    fn evaluate_result<P, CC, BC>(
202        core_ctx: &mut CC,
203        bindings_ctx: &mut BC,
204        table: &Table<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
205        conn: &mut ConnectionExclusive<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
206        packet: &P,
207        interfaces: &Interfaces<'_, CC::DeviceId>,
208        result: RoutineResult<I>,
209    ) -> ControlFlow<Verdict<DropPacket, NatConfigurationResult<I, CC::WeakAddressId, BC>>>
210    where
211        P: FilterIpPacket<I>,
212        CC: NatContext<I, BC>,
213        BC: FilterBindingsContext<CC::DeviceId>;
214
215    /// Return the IP address that should be used for Redirect NAT in this NAT hook
216    /// and, if applicable, a weakly-held reference to the address if it is assigned
217    /// to an interface owned by the stack.
218    ///
219    /// # Panics
220    ///
221    /// Panics if called on a hook that does not support DNAT.
222    fn redirect_addr<P, CC, BT>(
223        core_ctx: &mut CC,
224        packet: &P,
225        ingress: Option<&CC::DeviceId>,
226    ) -> Option<(I::Addr, Option<CachedAddr<I, CC::WeakAddressId, BT>>)>
227    where
228        P: IpPacket<I>,
229        CC: NatContext<I, BT>,
230        BT: FilterBindingsTypes;
231
232    /// Extract the relevant interface for this NAT hook from `interfaces`.
233    ///
234    /// # Panics
235    ///
236    /// Panics if the required interface (ingress for ingress hooks and egress for
237    /// egress hooks) is not provided to the NAT hook.
238    fn interface<DeviceId>(interfaces: Interfaces<'_, DeviceId>) -> &DeviceId;
239}
240
241#[derive(Derivative)]
242#[derivative(Debug(bound = "A: Debug"))]
243pub(crate) enum NatConfigurationResult<I: IpExt, A, BT: FilterBindingsTypes> {
244    Result(ShouldNat<I, A, BT>),
245    AdoptExisting(Connection<I, NatConfig<I, A, BT>, BT>),
246}
247
248pub(crate) enum IngressHook {}
249
250impl<I: FilterIpExt> NatHook<I> for IngressHook {
251    const NAT_TYPE: NatType = NatType::Destination;
252
253    fn evaluate_result<P, CC, BC>(
254        core_ctx: &mut CC,
255        bindings_ctx: &mut BC,
256        table: &Table<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
257        conn: &mut ConnectionExclusive<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
258        packet: &P,
259        interfaces: &Interfaces<'_, CC::DeviceId>,
260        result: RoutineResult<I>,
261    ) -> ControlFlow<Verdict<DropPacket, NatConfigurationResult<I, CC::WeakAddressId, BC>>>
262    where
263        P: FilterIpPacket<I>,
264        CC: NatContext<I, BC>,
265        BC: FilterBindingsContext<CC::DeviceId>,
266    {
267        match result {
268            RoutineResult::Accept | RoutineResult::Return => ControlFlow::Continue(()),
269            RoutineResult::Drop => ControlFlow::Break(Verdict::Stop(DropPacket)),
270            RoutineResult::Redirect { dst_port } => {
271                ControlFlow::Break(configure_redirect_nat::<Self, _, _, _, _>(
272                    core_ctx,
273                    bindings_ctx,
274                    table,
275                    conn,
276                    packet,
277                    interfaces,
278                    dst_port,
279                ))
280            }
281            result @ RoutineResult::Masquerade { .. } => {
282                unreachable!("SNAT not supported in INGRESS; got {result:?}")
283            }
284            RoutineResult::Reject(_reject_type) => {
285                unreachable!("REJECT not supported in NAT hooks")
286            }
287            RoutineResult::TransparentLocalDelivery { .. } => {
288                unreachable!("Transparent proxy not supported in NAT hooks")
289            }
290        }
291    }
292
293    fn redirect_addr<P, CC, BT>(
294        core_ctx: &mut CC,
295        packet: &P,
296        ingress: Option<&CC::DeviceId>,
297    ) -> Option<(I::Addr, Option<CachedAddr<I, CC::WeakAddressId, BT>>)>
298    where
299        P: IpPacket<I>,
300        CC: NatContext<I, BT>,
301        BT: FilterBindingsTypes,
302    {
303        let interface = ingress.expect("must have ingress interface in ingress hook");
304        let addr_id = core_ctx
305            .get_local_addr_for_remote(interface, SpecifiedAddr::new(packet.src_addr()))
306            .or_else(|| {
307                warn!(
308                    "cannot redirect because there is no address assigned to the incoming \
309                    interface {interface:?}; dropping packet",
310                );
311                None
312            })?;
313        let addr = addr_id.addr();
314        Some((addr.addr(), Some(CachedAddr::new(addr_id.downgrade()))))
315    }
316
317    fn interface<DeviceId>(interfaces: Interfaces<'_, DeviceId>) -> &DeviceId {
318        let Interfaces { ingress, egress: _ } = interfaces;
319        ingress.expect("ingress interface must be provided to INGRESS hook")
320    }
321}
322
323pub(crate) enum LocalEgressHook {}
324
325impl<I: FilterIpExt> NatHook<I> for LocalEgressHook {
326    const NAT_TYPE: NatType = NatType::Destination;
327
328    fn evaluate_result<P, CC, BC>(
329        core_ctx: &mut CC,
330        bindings_ctx: &mut BC,
331        table: &Table<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
332        conn: &mut ConnectionExclusive<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
333        packet: &P,
334        interfaces: &Interfaces<'_, CC::DeviceId>,
335        result: RoutineResult<I>,
336    ) -> ControlFlow<Verdict<DropPacket, NatConfigurationResult<I, CC::WeakAddressId, BC>>>
337    where
338        P: FilterIpPacket<I>,
339        CC: NatContext<I, BC>,
340        BC: FilterBindingsContext<CC::DeviceId>,
341    {
342        match result {
343            RoutineResult::Accept | RoutineResult::Return => ControlFlow::Continue(()),
344            RoutineResult::Drop => ControlFlow::Break(Verdict::Stop(DropPacket)),
345            result @ RoutineResult::TransparentLocalDelivery { .. } => {
346                unreachable!(
347                    "transparent local delivery is only valid in INGRESS hook; got {result:?}"
348                )
349            }
350            result @ RoutineResult::Masquerade { .. } => {
351                unreachable!("SNAT not supported in LOCAL_EGRESS; got {result:?}")
352            }
353            RoutineResult::Redirect { dst_port } => {
354                ControlFlow::Break(configure_redirect_nat::<Self, _, _, _, _>(
355                    core_ctx,
356                    bindings_ctx,
357                    table,
358                    conn,
359                    packet,
360                    interfaces,
361                    dst_port,
362                ))
363            }
364            RoutineResult::Reject(_) => {
365                unreachable!("REJECT not supported in NAT hooks")
366            }
367        }
368    }
369
370    fn redirect_addr<P, CC, BT>(
371        _: &mut CC,
372        _: &P,
373        _: Option<&CC::DeviceId>,
374    ) -> Option<(I::Addr, Option<CachedAddr<I, CC::WeakAddressId, BT>>)>
375    where
376        P: IpPacket<I>,
377        CC: NatContext<I, BT>,
378        BT: FilterBindingsTypes,
379    {
380        Some((*I::LOOPBACK_ADDRESS, None))
381    }
382
383    fn interface<DeviceId>(interfaces: Interfaces<'_, DeviceId>) -> &DeviceId {
384        let Interfaces { ingress: _, egress } = interfaces;
385        egress.expect("egress interface must be provided to LOCAL_EGRESS hook")
386    }
387}
388
389pub(crate) enum LocalIngressHook {}
390
391impl<I: FilterIpExt> NatHook<I> for LocalIngressHook {
392    const NAT_TYPE: NatType = NatType::Source;
393
394    fn evaluate_result<P, CC, BC>(
395        _core_ctx: &mut CC,
396        _bindings_ctx: &mut BC,
397        _table: &Table<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
398        _conn: &mut ConnectionExclusive<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
399        _packet: &P,
400        _interfaces: &Interfaces<'_, CC::DeviceId>,
401        result: RoutineResult<I>,
402    ) -> ControlFlow<Verdict<DropPacket, NatConfigurationResult<I, CC::WeakAddressId, BC>>>
403    where
404        P: IpPacket<I>,
405        CC: NatContext<I, BC>,
406        BC: FilterBindingsContext<CC::DeviceId>,
407    {
408        match result {
409            RoutineResult::Accept | RoutineResult::Return => ControlFlow::Continue(()),
410            RoutineResult::Drop => ControlFlow::Break(Verdict::Stop(DropPacket)),
411            result @ RoutineResult::Masquerade { .. } => {
412                unreachable!("Masquerade not supported in LOCAL_INGRESS; got {result:?}")
413            }
414            result @ RoutineResult::TransparentLocalDelivery { .. } => {
415                unreachable!(
416                    "transparent local delivery is only valid in INGRESS hook; got {result:?}"
417                )
418            }
419            result @ RoutineResult::Redirect { .. } => {
420                unreachable!("DNAT not supported in LOCAL_INGRESS; got {result:?}")
421            }
422            RoutineResult::Reject(_) => {
423                unreachable!("REJECT not supported in NAT hooks")
424            }
425        }
426    }
427
428    fn redirect_addr<P, CC, BT>(
429        _: &mut CC,
430        _: &P,
431        _: Option<&CC::DeviceId>,
432    ) -> Option<(I::Addr, Option<CachedAddr<I, CC::WeakAddressId, BT>>)>
433    where
434        P: IpPacket<I>,
435        CC: NatContext<I, BT>,
436        BT: FilterBindingsTypes,
437    {
438        unreachable!("DNAT not supported in LOCAL_INGRESS; cannot perform redirect action")
439    }
440
441    fn interface<DeviceId>(interfaces: Interfaces<'_, DeviceId>) -> &DeviceId {
442        let Interfaces { ingress, egress: _ } = interfaces;
443        ingress.expect("ingress interface must be provided to LOCAL_INGRESS hook")
444    }
445}
446
447pub(crate) enum EgressHook {}
448
449impl<I: FilterIpExt> NatHook<I> for EgressHook {
450    const NAT_TYPE: NatType = NatType::Source;
451
452    fn evaluate_result<P, CC, BC>(
453        core_ctx: &mut CC,
454        bindings_ctx: &mut BC,
455        table: &Table<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
456        conn: &mut ConnectionExclusive<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
457        packet: &P,
458        interfaces: &Interfaces<'_, CC::DeviceId>,
459        result: RoutineResult<I>,
460    ) -> ControlFlow<Verdict<DropPacket, NatConfigurationResult<I, CC::WeakAddressId, BC>>>
461    where
462        P: FilterIpPacket<I>,
463        CC: NatContext<I, BC>,
464        BC: FilterBindingsContext<CC::DeviceId>,
465    {
466        match result {
467            RoutineResult::Accept | RoutineResult::Return => ControlFlow::Continue(()),
468            RoutineResult::Drop => ControlFlow::Break(Verdict::Stop(DropPacket)),
469            RoutineResult::Masquerade { src_port } => {
470                ControlFlow::Break(configure_masquerade_nat::<_, _, _, _>(
471                    core_ctx,
472                    bindings_ctx,
473                    table,
474                    conn,
475                    packet,
476                    interfaces,
477                    src_port,
478                ))
479            }
480            result @ RoutineResult::TransparentLocalDelivery { .. } => {
481                unreachable!(
482                    "transparent local delivery is only valid in INGRESS hook; got {result:?}"
483                )
484            }
485            result @ RoutineResult::Redirect { .. } => {
486                unreachable!("DNAT not supported in EGRESS; got {result:?}")
487            }
488            RoutineResult::Reject(_) => {
489                unreachable!("REJECT not supported in NAT hooks")
490            }
491        }
492    }
493
494    fn redirect_addr<P, CC, BT>(
495        _: &mut CC,
496        _: &P,
497        _: Option<&CC::DeviceId>,
498    ) -> Option<(I::Addr, Option<CachedAddr<I, CC::WeakAddressId, BT>>)>
499    where
500        P: IpPacket<I>,
501        CC: NatContext<I, BT>,
502        BT: FilterBindingsTypes,
503    {
504        unreachable!("DNAT not supported in EGRESS; cannot perform redirect action")
505    }
506
507    fn interface<DeviceId>(interfaces: Interfaces<'_, DeviceId>) -> &DeviceId {
508        let Interfaces { ingress: _, egress } = interfaces;
509        egress.expect("egress interface must be provided to EGRESS hook")
510    }
511}
512
513impl<I: IpExt, A, BT: FilterBindingsTypes> Connection<I, NatConfig<I, A, BT>, BT> {
514    fn relevant_config(
515        &self,
516        hook_nat_type: NatType,
517        direction: ConnectionDirection,
518    ) -> (&OnceLock<ShouldNat<I, A, BT>, BT::Once>, NatType) {
519        let NatConfig { source, destination } = self.external_data();
520        match (hook_nat_type, direction) {
521            // If either this is a DNAT hook and we are looking at a packet in the
522            // "original" direction, or this is an SNAT hook and we are looking at a reply
523            // packet, then we want to decide whether to NAT based on whether the connection
524            // has DNAT configured.
525            (NatType::Destination, ConnectionDirection::Original)
526            | (NatType::Source, ConnectionDirection::Reply) => (destination, NatType::Destination),
527            // If either this is an SNAT hook and we are looking at a packet in the
528            // "original" direction, or this is a DNAT hook and we are looking at a reply
529            // packet, then we want to decide whether to NAT based on whether the connection
530            // has SNAT configured.
531            (NatType::Source, ConnectionDirection::Original)
532            | (NatType::Destination, ConnectionDirection::Reply) => (source, NatType::Source),
533        }
534    }
535
536    fn relevant_reply_tuple_addr(&self, nat_type: NatType) -> I::Addr {
537        match nat_type {
538            NatType::Destination => self.reply_tuple().src_addr,
539            NatType::Source => self.reply_tuple().dst_addr,
540        }
541    }
542
543    /// Gets a reference to the appropriate NAT config depending on the NAT hook we
544    /// are in and the direction of the packet with respect to its conntrack
545    /// connection.
546    fn nat_config(
547        &self,
548        hook_nat_type: NatType,
549        direction: ConnectionDirection,
550    ) -> Option<&ShouldNat<I, A, BT>> {
551        let (config, _nat_type) = self.relevant_config(hook_nat_type, direction);
552        config.get()
553    }
554
555    /// Sets the appropriate NAT config to the provided value. Which NAT config is
556    /// appropriate depends on the NAT hook we are in and the direction of the
557    /// packet with respect to its conntrack connection.
558    ///
559    /// Returns a reference to the value that was inserted, if the config had not
560    /// yet been initialized; otherwise, returns the existing value of the config,
561    /// along with the type of NAT it is (for diagnostic purposes).
562    fn set_nat_config(
563        &self,
564        hook_nat_type: NatType,
565        direction: ConnectionDirection,
566        value: ShouldNat<I, A, BT>,
567    ) -> Result<&ShouldNat<I, A, BT>, (ShouldNat<I, A, BT>, NatType)> {
568        let (config, nat_type) = self.relevant_config(hook_nat_type, direction);
569        let mut value = Some(value);
570        let config = config.get_or_init(|| value.take().unwrap());
571        match value {
572            None => Ok(config),
573            Some(value) => Err((value, nat_type)),
574        }
575    }
576}
577
578/// The entry point for NAT logic from an IP layer filtering hook.
579///
580/// This function configures NAT, if it has not yet been configured for the
581/// connection, and performs NAT on the provided packet based on the hook and
582/// the connection's NAT configuration.
583pub(crate) fn perform_nat<N, I, P, M, CC, BC>(
584    core_ctx: &mut CC,
585    bindings_ctx: &mut BC,
586    nat_installed: bool,
587    table: &Table<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
588    conn: &mut Connection<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
589    direction: ConnectionDirection,
590    hook: &Hook<I, BC, ()>,
591    packet: &mut P,
592    interfaces: Interfaces<'_, CC::DeviceId>,
593    metadata: &mut M,
594) -> Verdict<DropPacket>
595where
596    N: NatHook<I>,
597    I: FilterIpExt,
598    P: FilterIpPacket<I>,
599    M: FilterPacketMetadata,
600    CC: NatContext<I, BC>,
601    BC: FilterBindingsContext<CC::DeviceId>,
602{
603    if !nat_installed {
604        return Verdict::Proceed(Accept);
605    }
606
607    let nat_config = if let Some(nat) = conn.nat_config(N::NAT_TYPE, direction) {
608        nat
609    } else {
610        // NAT has not yet been configured for this connection; traverse the installed
611        // NAT routines in order to configure NAT.
612        let (verdict, exclusive) = match (&mut *conn, direction) {
613            (Connection::Exclusive(_), ConnectionDirection::Reply) => {
614                // This is the first packet in the flow (hence the connection being exclusive),
615                // yet the packet is determined to be in the "reply" direction. This means that
616                // this is a self-connected flow. When a connection's original tuple is the same
617                // as its reply tuple, every packet on the connection is considered to be in the
618                // reply direction, which is an implementation quirk that allows self-connected
619                // flows to be considered immediately "established".
620                //
621                // Handle this by just configuring the connection not to be NATed. It does not
622                // make sense to NAT a self-connected flow since the original and reply
623                // directions are indistinguishable.
624                (Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::No)), true)
625            }
626            (Connection::Shared(_), _) => {
627                // In most scenarios, NAT should be configured for every connection before it is
628                // inserted in the conntrack table, at which point it becomes a shared
629                // connection. (This should apply whether or not NAT will actually be performed;
630                // the configuration could be `DoNotNat`.) However, as an optimization, when no
631                // NAT rules have been installed, performing NAT is skipped entirely, which can
632                // result in some connections being finalized without NAT being configured for
633                // them. To handle this, just don't NAT the connection.
634                (Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::No)), false)
635            }
636            (Connection::Exclusive(conn), ConnectionDirection::Original) => {
637                let verdict = configure_nat::<N, _, _, _, _, _>(
638                    core_ctx,
639                    bindings_ctx,
640                    table,
641                    conn,
642                    hook,
643                    packet,
644                    interfaces.clone(),
645                    metadata,
646                );
647                // Configure source port remapping for a connection by default even if its first
648                // packet does not match any NAT rules, in order to ensure that source ports for
649                // locally-generated traffic do not clash with ports used by existing NATed
650                // connections (such as for forwarded masqueraded traffic).
651                let verdict = if matches!(
652                    verdict,
653                    Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::No))
654                ) && N::NAT_TYPE == NatType::Source
655                {
656                    configure_snat_port(
657                        bindings_ctx,
658                        table,
659                        conn,
660                        None, /* src_port_range */
661                        ConflictStrategy::AdoptExisting,
662                    )
663                } else {
664                    verdict
665                };
666                (verdict, true)
667            }
668        };
669
670        let result = match verdict {
671            Verdict::Proceed(result) => result,
672            Verdict::Stop(reason) => return Verdict::Stop(reason),
673        };
674        let new_nat_config = match result {
675            NatConfigurationResult::Result(config) => Some(config),
676            NatConfigurationResult::AdoptExisting(existing) => {
677                *conn = existing;
678                None
679            }
680        };
681        if let Some(config) = new_nat_config {
682            conn.set_nat_config(N::NAT_TYPE, direction, config).unwrap_or_else(
683                |(value, nat_type)| {
684                    // We can only assert that NAT has not been configured yet if we are configuring
685                    // NAT on an exclusive connection. If the connection has already been inserted
686                    // in the table and we are holding a shared reference to it, we could race with
687                    // another thread also configuring NAT for the connection.
688                    if exclusive {
689                        unreachable!(
690                            "{nat_type:?} NAT should not have been configured yet, but found \
691                            {value:?}"
692                        );
693                    }
694                    &ShouldNat::No
695                },
696            )
697        } else {
698            conn.nat_config(N::NAT_TYPE, direction).unwrap_or(&ShouldNat::No)
699        }
700    };
701
702    match nat_config {
703        ShouldNat::No => return Verdict::Proceed(Accept),
704        // If we are NATing this connection, but are not using an IP address that is
705        // dynamically assigned to an interface to do so, continue to rewrite the
706        // packet.
707        ShouldNat::Yes(None) => {}
708        // If we are NATing to an IP address assigned to an interface, ensure that the
709        // address is still valid before performing NAT.
710        ShouldNat::Yes(Some(cached_addr)) => {
711            // Only check the validity of the cached address if we are looking at a packet
712            // in the original direction. Packets in the reply direction are rewritten based
713            // on the original tuple, which is unchanged by NAT and therefore not necessary
714            // to check for validity.
715            if direction == ConnectionDirection::Original {
716                match cached_addr.validate_or_replace(
717                    core_ctx,
718                    N::interface(interfaces),
719                    conn.relevant_reply_tuple_addr(N::NAT_TYPE),
720                ) {
721                    Verdict::Proceed(Accept) => {}
722                    v @ Verdict::Stop(_) => return v,
723                }
724            }
725        }
726    }
727    rewrite_packet(conn, direction, N::NAT_TYPE, packet)
728}
729
730/// Configure NAT by rewriting the provided reply tuple of a connection.
731///
732/// Evaluates the NAT routines at the provided hook and, on finding a rule that
733/// matches the provided packet, configures NAT based on the rule's action. Note
734/// that because NAT routines can contain a superset of the rules filter
735/// routines can, it's possible for this packet to hit a non-NAT action.
736fn configure_nat<N, I, P, M, CC, BC>(
737    core_ctx: &mut CC,
738    bindings_ctx: &mut BC,
739    table: &Table<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
740    conn: &mut ConnectionExclusive<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
741    hook: &Hook<I, BC, ()>,
742    packet: &P,
743    interfaces: Interfaces<'_, CC::DeviceId>,
744    metadata: &mut M,
745) -> Verdict<DropPacket, NatConfigurationResult<I, CC::WeakAddressId, BC>>
746where
747    N: NatHook<I>,
748    I: FilterIpExt,
749    P: FilterIpPacket<I>,
750    M: FilterPacketMetadata,
751    CC: NatContext<I, BC>,
752    BC: FilterBindingsContext<CC::DeviceId>,
753{
754    let Hook { routines } = hook;
755    for routine in routines {
756        let result = super::check_routine(&routine, packet, interfaces, metadata);
757        match N::evaluate_result(core_ctx, bindings_ctx, table, conn, packet, &interfaces, result) {
758            ControlFlow::Break(result) => return result,
759            ControlFlow::Continue(()) => {}
760        }
761    }
762    Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::No))
763}
764
765/// Configure Redirect NAT, a special case of DNAT that redirects the packet to
766/// the local host.
767fn configure_redirect_nat<N, I, P, CC, BC>(
768    core_ctx: &mut CC,
769    bindings_ctx: &mut BC,
770    table: &Table<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
771    conn: &mut ConnectionExclusive<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
772    packet: &P,
773    interfaces: &Interfaces<'_, CC::DeviceId>,
774    dst_port_range: Option<RangeInclusive<NonZeroU16>>,
775) -> Verdict<DropPacket, NatConfigurationResult<I, CC::WeakAddressId, BC>>
776where
777    N: NatHook<I>,
778    I: FilterIpExt,
779    P: FilterIpPacket<I>,
780    CC: NatContext<I, BC>,
781    BC: FilterBindingsContext<CC::DeviceId>,
782{
783    match N::NAT_TYPE {
784        NatType::Source => panic!("DNAT action called from SNAT-only hook"),
785        NatType::Destination => {}
786    }
787
788    // Choose an appropriate new destination address and, optionally, port. Then
789    // rewrite the source address/port of the reply tuple for the connection to use
790    // as the guide for future packet rewriting.
791    //
792    // If we are in INGRESS, use the primary address of the incoming interface; if
793    // we are in LOCAL_EGRESS, use the loopback address.
794    let Some((addr, cached_addr)) = N::redirect_addr(core_ctx, packet, interfaces.ingress) else {
795        return Verdict::Stop(DropPacket);
796    };
797    conn.rewrite_reply_src_addr(addr);
798
799    let Some(range) = dst_port_range else {
800        return Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::Yes(cached_addr)));
801    };
802    match rewrite_reply_tuple_port(
803        bindings_ctx,
804        table,
805        conn,
806        ReplyTuplePort::Source,
807        range,
808        true, /* ensure_port_in_range */
809        ConflictStrategy::RewritePort,
810    ) {
811        // We are already NATing the address, so even if NATing the port is unnecessary,
812        // the connection as a whole still needs to be NATed.
813        Verdict::Proceed(
814            NatConfigurationResult::Result(ShouldNat::Yes(_))
815            | NatConfigurationResult::Result(ShouldNat::No),
816        ) => Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::Yes(cached_addr))),
817        Verdict::Proceed(NatConfigurationResult::AdoptExisting(_)) => {
818            unreachable!("cannot adopt existing connection")
819        }
820        Verdict::Stop(DropPacket) => Verdict::Stop(DropPacket),
821    }
822}
823
824/// Configure Masquerade NAT, a special case of SNAT that rewrites the source IP
825/// address of the packet to an address that is assigned to the outgoing
826/// interface.
827fn configure_masquerade_nat<I, P, CC, BC>(
828    core_ctx: &mut CC,
829    bindings_ctx: &mut BC,
830    table: &Table<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
831    conn: &mut ConnectionExclusive<I, NatConfig<I, CC::WeakAddressId, BC>, BC>,
832    packet: &P,
833    interfaces: &Interfaces<'_, CC::DeviceId>,
834    src_port_range: Option<RangeInclusive<NonZeroU16>>,
835) -> Verdict<DropPacket, NatConfigurationResult<I, CC::WeakAddressId, BC>>
836where
837    I: FilterIpExt,
838    P: FilterIpPacket<I>,
839    CC: NatContext<I, BC>,
840    BC: FilterBindingsContext<CC::DeviceId>,
841{
842    // Choose an appropriate new source address and, optionally, port. Then rewrite
843    // the destination address/port of the reply tuple for the connection to use as
844    // the guide for future packet rewriting.
845    let interface = interfaces.egress.expect(
846        "must have egress interface in EGRESS hook; Masquerade NAT is only valid in EGRESS",
847    );
848    let Some(addr) =
849        core_ctx.get_local_addr_for_remote(interface, SpecifiedAddr::new(packet.dst_addr()))
850    else {
851        // TODO(https://fxbug.dev/372549231): add a counter for this scenario.
852        warn!(
853            "cannot masquerade because there is no address assigned to the outgoing interface \
854            {interface:?}; dropping packet",
855        );
856        return Verdict::Stop(DropPacket);
857    };
858    conn.rewrite_reply_dst_addr(addr.addr().addr());
859
860    // Rewrite the source port if necessary to avoid conflicting with existing
861    // tracked connections.
862    match configure_snat_port(
863        bindings_ctx,
864        table,
865        conn,
866        src_port_range,
867        ConflictStrategy::RewritePort,
868    ) {
869        // We are already NATing the address, so even if NATing the port is unnecessary,
870        // the connection as a whole still needs to be NATed.
871        Verdict::Proceed(
872            NatConfigurationResult::Result(ShouldNat::Yes(_))
873            | NatConfigurationResult::Result(ShouldNat::No),
874        ) => Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::Yes(Some(
875            CachedAddr::new(addr.downgrade()),
876        )))),
877        Verdict::Proceed(NatConfigurationResult::AdoptExisting(_)) => {
878            unreachable!("cannot adopt existing connection")
879        }
880        Verdict::Stop(DropPacket) => Verdict::Stop(DropPacket),
881    }
882}
883
884fn configure_snat_port<I, A, BC, D>(
885    bindings_ctx: &mut BC,
886    table: &Table<I, NatConfig<I, A, BC>, BC>,
887    conn: &mut ConnectionExclusive<I, NatConfig<I, A, BC>, BC>,
888    src_port_range: Option<RangeInclusive<NonZeroU16>>,
889    conflict_strategy: ConflictStrategy,
890) -> Verdict<DropPacket, NatConfigurationResult<I, A, BC>>
891where
892    I: IpExt,
893    BC: FilterBindingsContext<D>,
894    A: PartialEq,
895{
896    // Rewrite the source port if necessary to avoid conflicting with existing
897    // tracked connections. If a source port range was specified, we also ensure the
898    // port is in that range; otherwise, we attempt to rewrite into a "similar"
899    // range to the current value, and only if required to avoid a conflict.
900    let (range, ensure_port_in_range) = if let Some(range) = src_port_range {
901        (range, true)
902    } else {
903        let reply_tuple = conn.reply_tuple();
904        let range = similar_port_or_id_range(reply_tuple.transport, ReplyTuplePort::Destination);
905        (range, false)
906    };
907    rewrite_reply_tuple_port(
908        bindings_ctx,
909        table,
910        conn,
911        ReplyTuplePort::Destination,
912        range,
913        ensure_port_in_range,
914        conflict_strategy,
915    )
916}
917
918/// Choose a range of "similar" values to which transport-layer port or ID can
919/// be rewritten -- that is, a value that is likely to be similar in terms of
920/// privilege, or lack thereof.
921///
922/// The heuristics used in this function are chosen to roughly match those used
923/// by Netstack2/gVisor and Linux.
924fn similar_port_or_id_range(
925    transport: TransportTuple,
926    which_port: ReplyTuplePort,
927) -> RangeInclusive<NonZeroU16> {
928    match transport {
929        TransportTuple::Tcp { src_port, dst_port, .. }
930        | TransportTuple::Udp { src_port, dst_port, .. } => {
931            let port = match which_port {
932                ReplyTuplePort::Source => src_port,
933                ReplyTuplePort::Destination => dst_port,
934            };
935            match port {
936                _ if port < 512 => NonZeroU16::MIN..=NonZeroU16::new(511).unwrap(),
937                _ if port < 1024 => NonZeroU16::MIN..=NonZeroU16::new(1023).unwrap(),
938                _ => NonZeroU16::new(1024).unwrap()..=NonZeroU16::MAX,
939            }
940        }
941        // TODO(https://fxbug.dev/341128580): allow rewriting ICMP echo ID to zero.
942        TransportTuple::IcmpEcho { .. } => NonZeroU16::MIN..=NonZeroU16::MAX,
943    }
944}
945
946#[derive(Clone, Copy)]
947enum ReplyTuplePort {
948    Source,
949    Destination,
950}
951
952enum ConflictStrategy {
953    AdoptExisting,
954    RewritePort,
955}
956
957/// Attempt to rewrite the indicated port of the reply tuple of the provided
958/// connection such that it results in a unique tuple, and, if
959/// `ensure_port_in_range` is `true`, also that it fits in the specified range.
960fn rewrite_reply_tuple_port<I, A, BC, D>(
961    bindings_ctx: &mut BC,
962    table: &Table<I, NatConfig<I, A, BC>, BC>,
963    conn: &mut ConnectionExclusive<I, NatConfig<I, A, BC>, BC>,
964    which_port: ReplyTuplePort,
965    port_range: RangeInclusive<NonZeroU16>,
966    ensure_port_in_range: bool,
967    conflict_strategy: ConflictStrategy,
968) -> Verdict<DropPacket, NatConfigurationResult<I, A, BC>>
969where
970    I: IpExt,
971    A: PartialEq,
972    BC: FilterBindingsContext<D>,
973{
974    // We only need to rewrite the port if the reply tuple of the connection
975    // conflicts with another connection in the table, or if the port must be
976    // rewritten to fall in the specified range.
977    let current_port = match which_port {
978        ReplyTuplePort::Source => conn.reply_tuple().transport.src_port_or_id(),
979        ReplyTuplePort::Destination => conn.reply_tuple().transport.dst_port_or_id(),
980    };
981    let already_in_range = !ensure_port_in_range
982        || NonZeroU16::new(current_port).map(|port| port_range.contains(&port)).unwrap_or(false);
983    if already_in_range {
984        match table.get_shared_connection(conn.reply_tuple()) {
985            None => return Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::No)),
986            Some(conflict) => match conflict_strategy {
987                ConflictStrategy::AdoptExisting => {
988                    // If this connection is identical to the conflicting one that's already in the
989                    // table, including both its original and reply tuple and its NAT configuration,
990                    // simply adopt the existing one rather than attempting port remapping.
991                    if conflict.compatible_with(&*conn) {
992                        return Verdict::Proceed(NatConfigurationResult::AdoptExisting(
993                            Connection::Shared(conflict),
994                        ));
995                    }
996                }
997                ConflictStrategy::RewritePort => {}
998            },
999        }
1000    }
1001
1002    // Attempt to find a new port in the provided range that results in a unique
1003    // tuple. Start by selecting a random offset into the target range, and from
1004    // there increment the candidate port, wrapping around until all ports in
1005    // the range have been checked (or MAX_ATTEMPTS has been exceeded).
1006    //
1007    // As soon as we find a port that would result in a unique tuple, stop and
1008    // accept the packet. If we search the entire range and fail to find a port
1009    // that creates a unique tuple, drop the packet.
1010    const MAX_ATTEMPTS: u16 = 128;
1011    let len = port_range.end().get() - port_range.start().get() + 1;
1012    let mut rng = bindings_ctx.rng();
1013    let start = rng.random_range(port_range.start().get()..=port_range.end().get());
1014    for i in 0..core::cmp::min(MAX_ATTEMPTS, len) {
1015        // `offset` is <= the size of `port_range`, which is a range of `NonZerou16`, so
1016        // `port_range.start()` + `offset` is guaranteed to fit in a `NonZeroU16`.
1017        let offset = (start + i) % len;
1018        let new_port = port_range.start().checked_add(offset).unwrap();
1019        match which_port {
1020            ReplyTuplePort::Source => conn.rewrite_reply_src_port_or_id(new_port.get()),
1021            ReplyTuplePort::Destination => conn.rewrite_reply_dst_port_or_id(new_port.get()),
1022        };
1023        if !table.contains_tuple(conn.reply_tuple()) {
1024            return Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::Yes(None)));
1025        }
1026    }
1027
1028    Verdict::Stop(DropPacket)
1029}
1030
1031fn rewrite_packet_for_dst_nat<I, P>(
1032    packet: &mut P,
1033    new_dst_addr: I::Addr,
1034    new_dst_port: u16,
1035) -> Verdict<DropPacket>
1036where
1037    I: FilterIpExt,
1038    P: IpPacket<I>,
1039{
1040    packet.set_dst_addr(new_dst_addr);
1041    let Some(proto) = packet.protocol() else {
1042        return Verdict::Proceed(Accept);
1043    };
1044    let mut transport = packet.transport_packet_mut();
1045    let Some(mut transport) = transport.transport_packet_mut() else {
1046        return Verdict::Proceed(Accept);
1047    };
1048    let Some(new_dst_port) = NonZeroU16::new(new_dst_port) else {
1049        // TODO(https://fxbug.dev/341128580): allow rewriting port to zero if
1050        // allowed by the transport-layer protocol.
1051        error!("cannot rewrite dst port to unspecified; dropping {proto} packet");
1052        return Verdict::Stop(DropPacket);
1053    };
1054    transport.set_dst_port(new_dst_port);
1055
1056    Verdict::Proceed(Accept)
1057}
1058
1059fn rewrite_packet_for_src_nat<I, P>(
1060    packet: &mut P,
1061    new_src_addr: I::Addr,
1062    new_src_port: u16,
1063) -> Verdict<DropPacket>
1064where
1065    I: FilterIpExt,
1066    P: IpPacket<I>,
1067{
1068    packet.set_src_addr(new_src_addr);
1069    let Some(proto) = packet.protocol() else {
1070        return Verdict::Proceed(Accept);
1071    };
1072    let mut transport = packet.transport_packet_mut();
1073    let Some(mut transport) = transport.transport_packet_mut() else {
1074        return Verdict::Proceed(Accept);
1075    };
1076    let Some(new_src_port) = NonZeroU16::new(new_src_port) else {
1077        // TODO(https://fxbug.dev/341128580): allow rewriting port to zero if
1078        // allowed by the transport-layer protocol.
1079        error!("cannot rewrite src port to unspecified; dropping {proto} packet");
1080        return Verdict::Stop(DropPacket);
1081    };
1082    transport.set_src_port(new_src_port);
1083
1084    Verdict::Proceed(Accept)
1085}
1086
1087fn rewrite_icmp_error_payload<I, E>(
1088    icmp_error: &mut E,
1089    nat: NatType,
1090    tuple: &Tuple<I>,
1091) -> Verdict<DropPacket>
1092where
1093    I: FilterIpExt,
1094    E: IcmpErrorMut<I>,
1095{
1096    // What follows is a justification for how ICMP error NAT decides what
1097    // addresses and ports to use.  We will only consider the address rewriting,
1098    // because ports necessarily must be rewritten in the same way.
1099    //
1100    // When rewriting the IP payload of ICMP errors, we know the following:
1101    //
1102    // 1. The payload was sent in the opposite direction from the error.
1103    // 2. The source of the payload is the same as the destination of the error.
1104    //
1105    // Imagine the following scenario:
1106    //
1107    // A --- R --- B
1108    //
1109    // Where SNAT is configured on R for packets originating at A. When packets
1110    // are sent in the original direction, their source will be rewritten from A
1111    // to R. The conntrack tuples will look like:
1112    //
1113    // Original: {
1114    //   src: A,
1115    //   dst: B,
1116    // }
1117    //
1118    // Reply: {
1119    //   src: B,
1120    //   dst: R,
1121    // }
1122    //
1123    // If B sends an error in response to a packet from A (meaning the reply
1124    // direction), it will look like:
1125    //
1126    //   B -> R | R -> B
1127    //
1128    // When performing SNAT, we need to perform the same rewrite for the
1129    // destination of the outer packet as well as the source of the inner
1130    // packet.
1131    //
1132    // In the opposite direction (original), if A sends an error in response to
1133    // a packet from B, it will look like:
1134    //
1135    //   A -> B | B -> A
1136    //
1137    // When performing SNAT, we need to perform the same rewrite to the source
1138    // of the outer packet and the destination of the inner packet.
1139    //
1140    // Conversely, let's look at DNAT. Imagine the case above was such that
1141    // R has DNAT configured to map traffic originally headed for R to B. The
1142    // tuples would look as follows:
1143    //
1144    // Original: {
1145    //   src: A,
1146    //   dst: R,
1147    // }
1148    //
1149    // Reply: {
1150    //   src: B,
1151    //   dst: A,
1152    // }
1153    //
1154    // An error response from B to A (reply) will look like:
1155    //
1156    // B -> A | A -> B
1157    //
1158    // An error response from A to B (original) will look like:
1159    //
1160    // A -> R | R -> A
1161    //
1162    // Note that we still need to rewrite the inner source the same as the outer
1163    // destination and the inner destination the same as the outer source. This
1164    // means we can use the same source and destination address and port for
1165    // rewriting the inner packet as well as the outer packet, but just need to
1166    // invert whether we're rewriting the source or destination information.
1167    let should_recalculate_checksum = match icmp_error.inner_packet() {
1168        Some(mut inner_packet) => {
1169            let verdict = match nat {
1170                NatType::Destination => rewrite_packet_for_src_nat(
1171                    &mut inner_packet,
1172                    tuple.src_addr,
1173                    tuple.transport.src_port_or_id(),
1174                ),
1175                NatType::Source => rewrite_packet_for_dst_nat(
1176                    &mut inner_packet,
1177                    tuple.dst_addr,
1178                    tuple.transport.dst_port_or_id(),
1179                ),
1180            };
1181
1182            match verdict {
1183                Verdict::Proceed(Accept) => true,
1184                Verdict::Stop(DropPacket) => return Verdict::Stop(DropPacket),
1185            }
1186        }
1187        None => false,
1188    };
1189
1190    if should_recalculate_checksum {
1191        // If updating the checksum fails, the packet will be left with the
1192        // original checksum, which will be incorrect. At the time of writing,
1193        // the only way for this to happen is if the length of an ICMPv6 is
1194        // larger than a u32, which is not possible for NS3 (nor most networks)
1195        // to handle.
1196        if !icmp_error.recalculate_checksum() {
1197            return Verdict::Stop(DropPacket);
1198        }
1199    }
1200
1201    Verdict::Proceed(Accept)
1202}
1203
1204/// Perform NAT on a packet, using its connection in the conntrack table as a
1205/// guide.
1206fn rewrite_packet<I, P, A, BT>(
1207    conn: &Connection<I, NatConfig<I, A, BT>, BT>,
1208    direction: ConnectionDirection,
1209    nat: NatType,
1210    packet: &mut P,
1211) -> Verdict<DropPacket>
1212where
1213    I: FilterIpExt,
1214    P: IpPacket<I>,
1215    BT: FilterBindingsTypes,
1216{
1217    // If this packet is in the "original" direction of the connection, rewrite its
1218    // address and port from the connection's reply tuple. If this is a reply
1219    // packet, rewrite it using the *original* tuple so the traffic is seen to
1220    // originate from or be destined to the expected peer.
1221    //
1222    // The reply tuple functions both as a way to mark what we expect to see coming
1223    // in, *and* a way to stash what the NAT remapping should be.
1224    let tuple = match direction {
1225        ConnectionDirection::Original => conn.reply_tuple(),
1226        ConnectionDirection::Reply => conn.original_tuple(),
1227    };
1228
1229    if let Some(mut icmp_error) = packet.icmp_error_mut().icmp_error_mut() {
1230        match rewrite_icmp_error_payload(&mut icmp_error, nat, tuple) {
1231            Verdict::Proceed(Accept) => (),
1232            Verdict::Stop(DropPacket) => return Verdict::Stop(DropPacket),
1233        }
1234    }
1235
1236    match nat {
1237        NatType::Destination => {
1238            rewrite_packet_for_dst_nat(packet, tuple.src_addr, tuple.transport.src_port_or_id())
1239        }
1240        NatType::Source => {
1241            rewrite_packet_for_src_nat(packet, tuple.dst_addr, tuple.transport.dst_port_or_id())
1242        }
1243    }
1244}
1245
1246#[cfg(test)]
1247mod tests {
1248    use alloc::sync::Arc;
1249    use alloc::vec;
1250    use core::marker::PhantomData;
1251
1252    use assert_matches::assert_matches;
1253    use ip_test_macro::ip_test;
1254    use net_types::ip::{AddrSubnet, Ipv4};
1255    use netstack3_base::testutil::FakeMatcherDeviceId;
1256    use netstack3_base::{
1257        IntoCoreTimerCtx, Mark, MarkDomain, MarkMatcher, MarkMatchers, Marks,
1258        NetworkSerializationContext, PacketType, TimerContext,
1259    };
1260    use packet::{EmptyBuf, NestablePacketBuilder as _, NestableSerializer as _, Serializer};
1261    use packet_formats::ip::{IpPacketBuilder, IpProto};
1262    use packet_formats::udp::UdpPacketBuilder;
1263    use test_case::{test_case, test_matrix};
1264
1265    use super::*;
1266    use crate::MarkAction;
1267    use crate::conntrack::Tuple;
1268    use crate::context::testutil::{
1269        FakeBindingsCtx, FakeNatCtx, FakePrimaryAddressId, FakeWeakAddressId,
1270    };
1271    use crate::matchers::PacketMatcher;
1272    use crate::packets::testutil::internal::{
1273        ArbitraryValue, FakeIpPacket, FakeUdpPacket, IcmpErrorMessage, Icmpv4DestUnreachableError,
1274        Icmpv6DestUnreachableError,
1275    };
1276    use crate::state::testutil::FakePacketMetadata;
1277    use crate::state::{Action, Routine, Rule};
1278    use crate::testutil::TestIpExt;
1279
1280    impl<I: IpExt, A: PartialEq, BT: FilterBindingsTypes> PartialEq
1281        for NatConfigurationResult<I, A, BT>
1282    {
1283        fn eq(&self, other: &Self) -> bool {
1284            match (self, other) {
1285                (Self::Result(lhs), Self::Result(rhs)) => lhs == rhs,
1286                (Self::AdoptExisting(_), Self::AdoptExisting(_)) => {
1287                    panic!("equality check for connections is not supported")
1288                }
1289                _ => false,
1290            }
1291        }
1292    }
1293
1294    impl<I, A, BC> ConnectionExclusive<I, NatConfig<I, A, BC>, BC>
1295    where
1296        BC: FilterBindingsTypes + TimerContext,
1297        I: FilterIpExt,
1298    {
1299        fn from_packet<P: IpPacket<I>>(bindings_ctx: &BC, packet: &P) -> Self {
1300            ConnectionExclusive::from_deconstructed_packet(
1301                bindings_ctx,
1302                &packet.conntrack_packet().unwrap(),
1303            )
1304            .expect("create conntrack entry")
1305        }
1306    }
1307
1308    impl<A, BC> ConnectionExclusive<Ipv4, NatConfig<Ipv4, A, BC>, BC>
1309    where
1310        BC: FilterBindingsTypes + TimerContext,
1311    {
1312        fn with_reply_tuple(bindings_ctx: &BC, which: ReplyTuplePort, port: u16) -> Self {
1313            Self::from_packet(bindings_ctx, &packet_with_port(which, port).reply())
1314        }
1315    }
1316
1317    fn packet_with_port(which: ReplyTuplePort, port: u16) -> FakeIpPacket<Ipv4, FakeUdpPacket> {
1318        let mut packet = FakeIpPacket::<Ipv4, FakeUdpPacket>::arbitrary_value();
1319        match which {
1320            ReplyTuplePort::Source => packet.body.src_port = port,
1321            ReplyTuplePort::Destination => packet.body.dst_port = port,
1322        }
1323        packet
1324    }
1325
1326    fn tuple_with_port(which: ReplyTuplePort, port: u16) -> Tuple<Ipv4> {
1327        packet_with_port(which, port).conntrack_packet().unwrap().tuple()
1328    }
1329
1330    #[test]
1331    fn accept_by_default_if_no_matching_rules_in_hook() {
1332        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
1333        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
1334        let mut core_ctx = FakeNatCtx::default();
1335        let packet = FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value();
1336        let mut conn = ConnectionExclusive::from_packet(&bindings_ctx, &packet);
1337
1338        assert_eq!(
1339            configure_nat::<LocalEgressHook, _, _, _, _, _>(
1340                &mut core_ctx,
1341                &mut bindings_ctx,
1342                &conntrack,
1343                &mut conn,
1344                &Hook::default(),
1345                &packet,
1346                Interfaces { ingress: None, egress: None },
1347                &mut FakePacketMetadata::default(),
1348            ),
1349            Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::No))
1350        );
1351    }
1352
1353    #[test]
1354    fn accept_by_default_if_return_from_routine() {
1355        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
1356        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
1357        let mut core_ctx = FakeNatCtx::default();
1358        let packet = FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value();
1359        let mut conn = ConnectionExclusive::from_packet(&bindings_ctx, &packet);
1360
1361        let hook = Hook {
1362            routines: vec![Routine {
1363                rules: vec![Rule::new(PacketMatcher::default(), Action::Return)],
1364            }],
1365        };
1366        assert_eq!(
1367            configure_nat::<LocalEgressHook, _, _, _, _, _>(
1368                &mut core_ctx,
1369                &mut bindings_ctx,
1370                &conntrack,
1371                &mut conn,
1372                &hook,
1373                &packet,
1374                Interfaces { ingress: None, egress: None },
1375                &mut FakePacketMetadata::default(),
1376            ),
1377            Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::No))
1378        );
1379    }
1380
1381    #[test]
1382    fn accept_terminal_for_installed_routine() {
1383        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
1384        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
1385        let mut core_ctx = FakeNatCtx::default();
1386        let packet = FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value();
1387        let mut conn = ConnectionExclusive::from_packet(&bindings_ctx, &packet);
1388
1389        // The first installed routine should terminate at its `Accept` result.
1390        let routine = Routine {
1391            rules: vec![
1392                // Accept all traffic.
1393                Rule::new(PacketMatcher::default(), Action::Accept),
1394                // Drop all traffic.
1395                Rule::new(PacketMatcher::default(), Action::Drop),
1396            ],
1397        };
1398        assert_eq!(
1399            configure_nat::<LocalEgressHook, _, _, _, _, _>(
1400                &mut core_ctx,
1401                &mut bindings_ctx,
1402                &conntrack,
1403                &mut conn,
1404                &Hook { routines: vec![routine.clone()] },
1405                &packet,
1406                Interfaces { ingress: None, egress: None },
1407                &mut FakePacketMetadata::default(),
1408            ),
1409            Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::No))
1410        );
1411
1412        // The first installed routine should terminate at its `Accept` result, but the
1413        // hook should terminate at the `Drop` result in the second routine.
1414        let hook = Hook {
1415            routines: vec![
1416                routine,
1417                Routine {
1418                    rules: vec![
1419                        // Drop all traffic.
1420                        Rule::new(PacketMatcher::default(), Action::Drop),
1421                    ],
1422                },
1423            ],
1424        };
1425        assert_eq!(
1426            configure_nat::<LocalEgressHook, _, _, _, _, _>(
1427                &mut core_ctx,
1428                &mut bindings_ctx,
1429                &conntrack,
1430                &mut conn,
1431                &hook,
1432                &packet,
1433                Interfaces { ingress: None, egress: None },
1434                &mut FakePacketMetadata::default(),
1435            ),
1436            Verdict::Stop(DropPacket)
1437        );
1438    }
1439
1440    #[test]
1441    fn drop_terminal_for_entire_hook() {
1442        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
1443        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
1444        let mut core_ctx = FakeNatCtx::default();
1445        let packet = FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value();
1446        let mut conn = ConnectionExclusive::from_packet(&bindings_ctx, &packet);
1447
1448        let hook = Hook {
1449            routines: vec![
1450                Routine {
1451                    rules: vec![
1452                        // Drop all traffic.
1453                        Rule::new(PacketMatcher::default(), Action::Drop),
1454                    ],
1455                },
1456                Routine {
1457                    rules: vec![
1458                        // Accept all traffic.
1459                        Rule::new(PacketMatcher::default(), Action::Accept),
1460                    ],
1461                },
1462            ],
1463        };
1464
1465        assert_eq!(
1466            configure_nat::<LocalEgressHook, _, _, _, _, _>(
1467                &mut core_ctx,
1468                &mut bindings_ctx,
1469                &conntrack,
1470                &mut conn,
1471                &hook,
1472                &packet,
1473                Interfaces { ingress: None, egress: None },
1474                &mut FakePacketMetadata::default(),
1475            ),
1476            Verdict::Stop(DropPacket)
1477        );
1478    }
1479
1480    #[test]
1481    fn redirect_terminal_for_entire_hook() {
1482        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
1483        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
1484        let mut core_ctx = FakeNatCtx::default();
1485        let packet = FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value();
1486        let mut conn = ConnectionExclusive::from_packet(&bindings_ctx, &packet);
1487
1488        let hook = Hook {
1489            routines: vec![
1490                Routine {
1491                    rules: vec![
1492                        // Redirect all traffic.
1493                        Rule::new(PacketMatcher::default(), Action::Redirect { dst_port: None }),
1494                    ],
1495                },
1496                Routine {
1497                    rules: vec![
1498                        // Drop all traffic.
1499                        Rule::new(PacketMatcher::default(), Action::Drop),
1500                    ],
1501                },
1502            ],
1503        };
1504
1505        assert_eq!(
1506            configure_nat::<LocalEgressHook, _, _, _, _, _>(
1507                &mut core_ctx,
1508                &mut bindings_ctx,
1509                &conntrack,
1510                &mut conn,
1511                &hook,
1512                &packet,
1513                Interfaces { ingress: None, egress: None },
1514                &mut FakePacketMetadata::default(),
1515            ),
1516            Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::Yes(None)))
1517        );
1518    }
1519
1520    #[ip_test(I)]
1521    fn masquerade_terminal_for_entire_hook<I: TestIpExt>() {
1522        let mut bindings_ctx = FakeBindingsCtx::<I>::new();
1523        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
1524        let assigned_addr = AddrSubnet::new(I::SRC_IP_2, I::SUBNET.prefix()).unwrap();
1525        let mut core_ctx =
1526            FakeNatCtx::new([(FakeMatcherDeviceId::ethernet_interface(), assigned_addr)]);
1527        let packet = FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value();
1528        let mut conn = ConnectionExclusive::from_packet(&bindings_ctx, &packet);
1529
1530        let hook = Hook {
1531            routines: vec![
1532                Routine {
1533                    rules: vec![
1534                        // Masquerade all traffic.
1535                        Rule::new(PacketMatcher::default(), Action::Masquerade { src_port: None }),
1536                    ],
1537                },
1538                Routine {
1539                    rules: vec![
1540                        // Drop all traffic.
1541                        Rule::new(PacketMatcher::default(), Action::Drop),
1542                    ],
1543                },
1544            ],
1545        };
1546
1547        assert_matches!(
1548            configure_nat::<EgressHook, _, _, _, _, _>(
1549                &mut core_ctx,
1550                &mut bindings_ctx,
1551                &conntrack,
1552                &mut conn,
1553                &hook,
1554                &packet,
1555                Interfaces {
1556                    ingress: None,
1557                    egress: Some(&FakeMatcherDeviceId::ethernet_interface())
1558                },
1559                &mut FakePacketMetadata::default(),
1560            ),
1561            Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::Yes(Some(_))))
1562        );
1563    }
1564
1565    #[test]
1566    fn redirect_ingress_drops_packet_if_no_assigned_address() {
1567        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
1568        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
1569        let mut core_ctx = FakeNatCtx::default();
1570        let packet = FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value();
1571        let mut conn = ConnectionExclusive::from_packet(&bindings_ctx, &packet);
1572
1573        let hook = Hook {
1574            routines: vec![Routine {
1575                rules: vec![Rule::new(
1576                    PacketMatcher::default(),
1577                    Action::Redirect { dst_port: None },
1578                )],
1579            }],
1580        };
1581
1582        assert_eq!(
1583            configure_nat::<IngressHook, _, _, _, _, _>(
1584                &mut core_ctx,
1585                &mut bindings_ctx,
1586                &conntrack,
1587                &mut conn,
1588                &hook,
1589                &packet,
1590                Interfaces {
1591                    ingress: Some(&FakeMatcherDeviceId::ethernet_interface()),
1592                    egress: None
1593                },
1594                &mut FakePacketMetadata::default(),
1595            ),
1596            Verdict::Stop(DropPacket)
1597        );
1598    }
1599
1600    #[test]
1601    fn masquerade_egress_drops_packet_if_no_assigned_address() {
1602        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
1603        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
1604        let mut core_ctx = FakeNatCtx::default();
1605        let packet = FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value();
1606        let mut conn = ConnectionExclusive::from_packet(&bindings_ctx, &packet);
1607
1608        let hook = Hook {
1609            routines: vec![Routine {
1610                rules: vec![Rule::new(
1611                    PacketMatcher::default(),
1612                    Action::Masquerade { src_port: None },
1613                )],
1614            }],
1615        };
1616
1617        assert_eq!(
1618            configure_nat::<EgressHook, _, _, _, _, _>(
1619                &mut core_ctx,
1620                &mut bindings_ctx,
1621                &conntrack,
1622                &mut conn,
1623                &hook,
1624                &packet,
1625                Interfaces {
1626                    ingress: None,
1627                    egress: Some(&FakeMatcherDeviceId::ethernet_interface())
1628                },
1629                &mut FakePacketMetadata::default(),
1630            ),
1631            Verdict::Stop(DropPacket)
1632        );
1633    }
1634
1635    #[test]
1636    fn configure_nat_observes_and_updates_packet_metadata() {
1637        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
1638        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
1639        let mut core_ctx = FakeNatCtx::default();
1640        let packet = FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value();
1641        let mut conn = ConnectionExclusive::from_packet(&bindings_ctx, &packet);
1642
1643        let hook = Hook {
1644            routines: vec![Routine {
1645                rules: vec![
1646                    // If Mark1 is 100, set Mark2 to 200.
1647                    Rule::new(
1648                        PacketMatcher {
1649                            mark_matcher: Some(MarkMatchers::new([(
1650                                MarkDomain::Mark1,
1651                                MarkMatcher::Marked {
1652                                    mask: !0,
1653                                    start: 100,
1654                                    end: 100,
1655                                    invert: false,
1656                                },
1657                            )])),
1658                            ..Default::default()
1659                        },
1660                        Action::Mark {
1661                            domain: MarkDomain::Mark2,
1662                            action: MarkAction::SetMark { mark: 200, clearing_mask: 0 },
1663                        },
1664                    ),
1665                    // If Mark2 is 200, redirect.
1666                    Rule::new(
1667                        PacketMatcher {
1668                            mark_matcher: Some(MarkMatchers::new([(
1669                                MarkDomain::Mark2,
1670                                MarkMatcher::Marked {
1671                                    mask: !0,
1672                                    start: 200,
1673                                    end: 200,
1674                                    invert: false,
1675                                },
1676                            )])),
1677                            ..Default::default()
1678                        },
1679                        Action::Redirect { dst_port: None },
1680                    ),
1681                ],
1682            }],
1683        };
1684
1685        let mut metadata =
1686            FakePacketMetadata::new(Marks::new([(MarkDomain::Mark1, 100)]), PacketType::OtherHost);
1687        assert_eq!(
1688            configure_nat::<LocalEgressHook, _, _, _, _, _>(
1689                &mut core_ctx,
1690                &mut bindings_ctx,
1691                &conntrack,
1692                &mut conn,
1693                &hook,
1694                &packet,
1695                Interfaces { ingress: None, egress: None },
1696                &mut metadata,
1697            ),
1698            Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::Yes(None)))
1699        );
1700        assert_eq!(*metadata.marks().get(MarkDomain::Mark2), Mark(Some(200)));
1701    }
1702
1703    trait NatHookExt<I: FilterIpExt>: NatHook<I> {
1704        fn interfaces<'a>(
1705            interface: &'a FakeMatcherDeviceId,
1706        ) -> Interfaces<'a, FakeMatcherDeviceId>;
1707    }
1708
1709    impl<I: FilterIpExt> NatHookExt<I> for IngressHook {
1710        fn interfaces<'a>(
1711            interface: &'a FakeMatcherDeviceId,
1712        ) -> Interfaces<'a, FakeMatcherDeviceId> {
1713            Interfaces { ingress: Some(interface), egress: None }
1714        }
1715    }
1716
1717    impl<I: FilterIpExt> NatHookExt<I> for LocalEgressHook {
1718        fn interfaces<'a>(
1719            interface: &'a FakeMatcherDeviceId,
1720        ) -> Interfaces<'a, FakeMatcherDeviceId> {
1721            Interfaces { ingress: None, egress: Some(interface) }
1722        }
1723    }
1724
1725    impl<I: FilterIpExt> NatHookExt<I> for EgressHook {
1726        fn interfaces<'a>(
1727            interface: &'a FakeMatcherDeviceId,
1728        ) -> Interfaces<'a, FakeMatcherDeviceId> {
1729            Interfaces { ingress: None, egress: Some(interface) }
1730        }
1731    }
1732
1733    const NAT_ENABLED_FOR_TESTS: bool = true;
1734
1735    #[ip_test(I)]
1736    fn nat_disabled_for_self_connected_flows<I: TestIpExt>() {
1737        let mut bindings_ctx = FakeBindingsCtx::<I>::new();
1738        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
1739        let mut core_ctx = FakeNatCtx::default();
1740
1741        let mut packet = FakeIpPacket::<I, _> {
1742            src_ip: I::SRC_IP,
1743            dst_ip: I::SRC_IP,
1744            body: FakeUdpPacket { src_port: 22222, dst_port: 22222 },
1745        };
1746        let (mut conn, direction) = conntrack
1747            .get_connection_for_packet_and_update(
1748                &bindings_ctx,
1749                packet.conntrack_packet().expect("packet should be valid"),
1750            )
1751            .expect("packet should be valid")
1752            .expect("packet should be trackable");
1753
1754        // Even with a Redirect NAT rule in LOCAL_EGRESS, and a Masquerade NAT rule in
1755        // EGRESS, DNAT and SNAT should both be disabled for the connection because it
1756        // is self-connected.
1757        let verdict = perform_nat::<LocalEgressHook, _, _, _, _, _>(
1758            &mut core_ctx,
1759            &mut bindings_ctx,
1760            NAT_ENABLED_FOR_TESTS,
1761            &conntrack,
1762            &mut conn,
1763            direction,
1764            &Hook {
1765                routines: vec![Routine {
1766                    rules: vec![Rule::new(
1767                        PacketMatcher::default(),
1768                        Action::Redirect { dst_port: None },
1769                    )],
1770                }],
1771            },
1772            &mut packet,
1773            <LocalEgressHook as NatHookExt<I>>::interfaces(
1774                &FakeMatcherDeviceId::ethernet_interface(),
1775            ),
1776            &mut FakePacketMetadata::default(),
1777        );
1778        assert_eq!(verdict, Verdict::Proceed(Accept));
1779
1780        let verdict = perform_nat::<EgressHook, _, _, _, _, _>(
1781            &mut core_ctx,
1782            &mut bindings_ctx,
1783            NAT_ENABLED_FOR_TESTS,
1784            &conntrack,
1785            &mut conn,
1786            direction,
1787            &Hook {
1788                routines: vec![Routine {
1789                    rules: vec![Rule::new(
1790                        PacketMatcher::default(),
1791                        Action::Masquerade { src_port: None },
1792                    )],
1793                }],
1794            },
1795            &mut packet,
1796            <EgressHook as NatHookExt<I>>::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
1797            &mut FakePacketMetadata::default(),
1798        );
1799        assert_eq!(verdict, Verdict::Proceed(Accept));
1800
1801        assert_eq!(conn.external_data().destination.get(), Some(&ShouldNat::No));
1802        assert_eq!(conn.external_data().source.get(), Some(&ShouldNat::No));
1803    }
1804
1805    #[ip_test(I)]
1806    fn nat_disabled_if_not_configured_before_connection_finalized<I: TestIpExt>() {
1807        let mut bindings_ctx = FakeBindingsCtx::<I>::new();
1808        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
1809        let mut core_ctx = FakeNatCtx::default();
1810
1811        let mut packet = FakeIpPacket::<I, FakeUdpPacket>::arbitrary_value();
1812        let (mut conn, direction) = conntrack
1813            .get_connection_for_packet_and_update(&bindings_ctx, packet.conntrack_packet().unwrap())
1814            .expect("packet should be valid")
1815            .expect("packet should be trackable");
1816
1817        // Skip NAT so the connection is finalized without DNAT configured for it.
1818        let verdict = perform_nat::<LocalEgressHook, _, _, _, _, _>(
1819            &mut core_ctx,
1820            &mut bindings_ctx,
1821            false, /* nat_installed */
1822            &conntrack,
1823            &mut conn,
1824            direction,
1825            &Hook::default(),
1826            &mut packet,
1827            <LocalEgressHook as NatHookExt<I>>::interfaces(
1828                &FakeMatcherDeviceId::ethernet_interface(),
1829            ),
1830            &mut FakePacketMetadata::default(),
1831        );
1832        assert_eq!(verdict, Verdict::Proceed(Accept));
1833        assert_eq!(conn.external_data().destination.get(), None);
1834        assert_eq!(conn.external_data().source.get(), None);
1835
1836        // Skip NAT so the connection is finalized without SNAT configured for it.
1837        let verdict = perform_nat::<EgressHook, _, _, _, _, _>(
1838            &mut core_ctx,
1839            &mut bindings_ctx,
1840            false, /* nat_installed */
1841            &conntrack,
1842            &mut conn,
1843            direction,
1844            &Hook::default(),
1845            &mut packet,
1846            <EgressHook as NatHookExt<I>>::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
1847            &mut FakePacketMetadata::default(),
1848        );
1849        assert_eq!(verdict, Verdict::Proceed(Accept));
1850        assert_eq!(conn.external_data().destination.get(), None);
1851        assert_eq!(conn.external_data().source.get(), None);
1852
1853        let (inserted, _weak) = conntrack
1854            .finalize_connection(&mut bindings_ctx, conn)
1855            .expect("connection should not conflict");
1856        assert!(inserted);
1857
1858        // Now, when a reply comes in to INGRESS, expect that SNAT will be configured as
1859        // `DoNotNat` given it has not already been configured for the connection.
1860        let mut reply = packet.reply();
1861        let (mut conn, direction) = conntrack
1862            .get_connection_for_packet_and_update(&bindings_ctx, reply.conntrack_packet().unwrap())
1863            .expect("packet should be valid")
1864            .expect("packet should be trackable");
1865        let verdict = perform_nat::<IngressHook, _, _, _, _, _>(
1866            &mut core_ctx,
1867            &mut bindings_ctx,
1868            NAT_ENABLED_FOR_TESTS,
1869            &conntrack,
1870            &mut conn,
1871            direction,
1872            &Hook::default(),
1873            &mut reply,
1874            <IngressHook as NatHookExt<I>>::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
1875            &mut FakePacketMetadata::default(),
1876        );
1877        assert_eq!(verdict, Verdict::Proceed(Accept));
1878        assert_eq!(conn.external_data().destination.get(), None);
1879        assert_eq!(conn.external_data().source.get(), Some(&ShouldNat::No));
1880
1881        // And finally, on LOCAL_INGRESS, DNAT should also be configured as `DoNotNat`.
1882        let verdict = perform_nat::<LocalIngressHook, _, _, _, _, _>(
1883            &mut core_ctx,
1884            &mut bindings_ctx,
1885            NAT_ENABLED_FOR_TESTS,
1886            &conntrack,
1887            &mut conn,
1888            direction,
1889            &Hook::default(),
1890            &mut reply,
1891            <IngressHook as NatHookExt<I>>::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
1892            &mut FakePacketMetadata::default(),
1893        );
1894        assert_eq!(verdict, Verdict::Proceed(Accept));
1895        assert_eq!(conn.external_data().destination.get(), Some(&ShouldNat::No));
1896        assert_eq!(conn.external_data().source.get(), Some(&ShouldNat::No));
1897    }
1898
1899    const LOCAL_PORT: NonZeroU16 = NonZeroU16::new(55555).unwrap();
1900
1901    #[ip_test(I)]
1902    #[test_case(
1903        PhantomData::<IngressHook>, PhantomData::<EgressHook>, None;
1904        "redirect INGRESS"
1905    )]
1906    #[test_case(
1907        PhantomData::<IngressHook>, PhantomData::<EgressHook>, Some(LOCAL_PORT);
1908        "redirect INGRESS to local port"
1909    )]
1910    #[test_case(
1911        PhantomData::<LocalEgressHook>, PhantomData::<EgressHook>, None;
1912        "redirect LOCAL_EGRESS"
1913    )]
1914    #[test_case(
1915        PhantomData::<LocalEgressHook>, PhantomData::<EgressHook>, Some(LOCAL_PORT);
1916        "redirect LOCAL_EGRESS to local port"
1917    )]
1918    fn redirect<I: TestIpExt, Original: NatHookExt<I>, Reply: NatHookExt<I>>(
1919        _original_nat_hook: PhantomData<Original>,
1920        _reply_nat_hook: PhantomData<Reply>,
1921        dst_port: Option<NonZeroU16>,
1922    ) {
1923        let mut bindings_ctx = FakeBindingsCtx::<I>::new();
1924        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
1925        let mut core_ctx = FakeNatCtx::new([(
1926            FakeMatcherDeviceId::ethernet_interface(),
1927            AddrSubnet::new(I::DST_IP_2, I::SUBNET.prefix()).unwrap(),
1928        )]);
1929
1930        // Create a packet and get the corresponding connection from conntrack.
1931        let mut packet = FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value();
1932        let pre_nat_packet = packet.clone();
1933        let (mut conn, direction) = conntrack
1934            .get_connection_for_packet_and_update(&bindings_ctx, packet.conntrack_packet().unwrap())
1935            .expect("packet should be valid")
1936            .expect("packet should be trackable");
1937        let original = conn.original_tuple().clone();
1938
1939        // Perform NAT at the first hook where we'd encounter this packet (either
1940        // INGRESS, if it's an incoming packet, or LOCAL_EGRESS, if it's an outgoing
1941        // packet).
1942        let nat_routines = Hook {
1943            routines: vec![Routine {
1944                rules: vec![Rule::new(
1945                    PacketMatcher::default(),
1946                    Action::Redirect { dst_port: dst_port.map(|port| port..=port) },
1947                )],
1948            }],
1949        };
1950        let verdict = perform_nat::<Original, _, _, _, _, _>(
1951            &mut core_ctx,
1952            &mut bindings_ctx,
1953            NAT_ENABLED_FOR_TESTS,
1954            &conntrack,
1955            &mut conn,
1956            direction,
1957            &nat_routines,
1958            &mut packet,
1959            Original::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
1960            &mut FakePacketMetadata::default(),
1961        );
1962        assert_eq!(verdict, Verdict::Proceed(Accept));
1963
1964        // The packet's destination should be rewritten, and DNAT should be configured
1965        // for the packet; the reply tuple's source should be rewritten to match the new
1966        // destination.
1967        let (redirect_addr, cached_addr) = Original::redirect_addr(
1968            &mut core_ctx,
1969            &packet,
1970            Original::interfaces(&FakeMatcherDeviceId::ethernet_interface()).ingress,
1971        )
1972        .expect("get redirect addr for NAT hook");
1973        let expected = FakeIpPacket::<_, FakeUdpPacket> {
1974            src_ip: packet.src_ip,
1975            dst_ip: redirect_addr,
1976            body: FakeUdpPacket {
1977                src_port: packet.body.src_port,
1978                dst_port: dst_port.map(NonZeroU16::get).unwrap_or(packet.body.dst_port),
1979            },
1980        };
1981        assert_eq!(packet, expected);
1982        assert_eq!(
1983            conn.external_data().destination.get().expect("DNAT should be configured"),
1984            &ShouldNat::Yes(cached_addr)
1985        );
1986        assert_eq!(conn.external_data().source.get(), None, "SNAT should not be configured");
1987        assert_eq!(conn.original_tuple(), &original);
1988        let mut reply = Tuple { src_addr: redirect_addr, ..original.invert() };
1989        if let Some(port) = dst_port {
1990            reply.transport.set_src_port_or_id(port.get());
1991        }
1992        assert_eq!(conn.reply_tuple(), &reply);
1993
1994        // When a reply to the original packet arrives at the corresponding hook, it
1995        // should have reverse DNAT applied, i.e. its source should be rewritten to
1996        // match the original destination of the connection.
1997        let mut reply_packet = packet.reply();
1998        // Install a NAT routine that simply drops all packets. This should have no
1999        // effect, because only the first packet for a given connection traverses NAT
2000        // routines.
2001        let nat_routines = Hook {
2002            routines: vec![Routine {
2003                rules: vec![Rule::new(PacketMatcher::default(), Action::Drop)],
2004            }],
2005        };
2006        let verdict = perform_nat::<Reply, _, _, _, _, _>(
2007            &mut core_ctx,
2008            &mut bindings_ctx,
2009            NAT_ENABLED_FOR_TESTS,
2010            &conntrack,
2011            &mut conn,
2012            ConnectionDirection::Reply,
2013            &nat_routines,
2014            &mut reply_packet,
2015            Reply::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
2016            &mut FakePacketMetadata::default(),
2017        );
2018        assert_eq!(verdict, Verdict::Proceed(Accept));
2019        assert_eq!(reply_packet, pre_nat_packet.reply());
2020    }
2021
2022    #[ip_test(I)]
2023    #[test_case(None; "masquerade")]
2024    #[test_case(Some(LOCAL_PORT); "masquerade to specified port")]
2025    fn masquerade<I: TestIpExt>(src_port: Option<NonZeroU16>) {
2026        let mut bindings_ctx = FakeBindingsCtx::<I>::new();
2027        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
2028        let assigned_addr = AddrSubnet::new(I::SRC_IP_2, I::SUBNET.prefix()).unwrap();
2029        let mut core_ctx =
2030            FakeNatCtx::new([(FakeMatcherDeviceId::ethernet_interface(), assigned_addr)]);
2031
2032        // Create a packet and get the corresponding connection from conntrack.
2033        let mut packet = FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value();
2034        let pre_nat_packet = packet.clone();
2035        let (mut conn, direction) = conntrack
2036            .get_connection_for_packet_and_update(&bindings_ctx, packet.conntrack_packet().unwrap())
2037            .expect("packet should be valid")
2038            .expect("packet should be trackable");
2039        let original = conn.original_tuple().clone();
2040
2041        // Perform Masquerade NAT at EGRESS.
2042        let nat_routines = Hook {
2043            routines: vec![Routine {
2044                rules: vec![Rule::new(
2045                    PacketMatcher::default(),
2046                    Action::Masquerade { src_port: src_port.map(|port| port..=port) },
2047                )],
2048            }],
2049        };
2050        let verdict = perform_nat::<EgressHook, _, _, _, _, _>(
2051            &mut core_ctx,
2052            &mut bindings_ctx,
2053            NAT_ENABLED_FOR_TESTS,
2054            &conntrack,
2055            &mut conn,
2056            direction,
2057            &nat_routines,
2058            &mut packet,
2059            Interfaces { ingress: None, egress: Some(&FakeMatcherDeviceId::ethernet_interface()) },
2060            &mut FakePacketMetadata::default(),
2061        );
2062        assert_eq!(verdict, Verdict::Proceed(Accept));
2063
2064        // The packet's source address should be rewritten, and SNAT should be
2065        // configured for the packet; the reply tuple's destination should be rewritten
2066        // to match the new source.
2067        let expected = FakeIpPacket::<_, FakeUdpPacket> {
2068            src_ip: I::SRC_IP_2,
2069            dst_ip: packet.dst_ip,
2070            body: FakeUdpPacket {
2071                src_port: src_port.map(NonZeroU16::get).unwrap_or(packet.body.src_port),
2072                dst_port: packet.body.dst_port,
2073            },
2074        };
2075        assert_eq!(packet, expected);
2076        assert_matches!(
2077            conn.external_data().source.get().expect("SNAT should be configured"),
2078            &ShouldNat::Yes(Some(_))
2079        );
2080        assert_eq!(conn.external_data().destination.get(), None, "DNAT should not be configured");
2081        assert_eq!(conn.original_tuple(), &original);
2082        let mut reply = Tuple { dst_addr: I::SRC_IP_2, ..original.invert() };
2083        if let Some(port) = src_port {
2084            reply.transport.set_dst_port_or_id(port.get());
2085        }
2086        assert_eq!(conn.reply_tuple(), &reply);
2087
2088        // When a reply to the original packet arrives at INGRESS, it should have
2089        // reverse SNAT applied, i.e. its destination should be rewritten to match the
2090        // original source of the connection.
2091        let mut reply_packet = packet.reply();
2092        // Install a NAT routine that simply drops all packets. This should have no
2093        // effect, because only the first packet for a given connection traverses NAT
2094        // routines.
2095        let nat_routines = Hook {
2096            routines: vec![Routine {
2097                rules: vec![Rule::new(PacketMatcher::default(), Action::Drop)],
2098            }],
2099        };
2100        let verdict = perform_nat::<IngressHook, _, _, _, _, _>(
2101            &mut core_ctx,
2102            &mut bindings_ctx,
2103            NAT_ENABLED_FOR_TESTS,
2104            &conntrack,
2105            &mut conn,
2106            ConnectionDirection::Reply,
2107            &nat_routines,
2108            &mut reply_packet,
2109            Interfaces { ingress: Some(&FakeMatcherDeviceId::ethernet_interface()), egress: None },
2110            &mut FakePacketMetadata::default(),
2111        );
2112        assert_eq!(verdict, Verdict::Proceed(Accept));
2113        assert_eq!(reply_packet, pre_nat_packet.reply());
2114    }
2115
2116    #[ip_test(I)]
2117    #[test_case(22, 1..=511)]
2118    #[test_case(853, 1..=1023)]
2119    #[test_case(11111, 1024..=u16::MAX)]
2120    fn masquerade_reply_tuple_dst_port_rewritten_even_if_target_range_unspecified<I: TestIpExt>(
2121        src_port: u16,
2122        expected_range: RangeInclusive<u16>,
2123    ) {
2124        let mut bindings_ctx = FakeBindingsCtx::<I>::new();
2125        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
2126        let assigned_addr = AddrSubnet::new(I::SRC_IP_2, I::SUBNET.prefix()).unwrap();
2127        let mut core_ctx =
2128            FakeNatCtx::new([(FakeMatcherDeviceId::ethernet_interface(), assigned_addr)]);
2129        let packet = FakeIpPacket {
2130            body: FakeUdpPacket { src_port, ..ArbitraryValue::arbitrary_value() },
2131            ..ArbitraryValue::arbitrary_value()
2132        };
2133
2134        // First, insert a connection in conntrack with the same the source address the
2135        // packet will be masqueraded to, and the same source port, to cause a conflict.
2136        let reply = FakeIpPacket { src_ip: I::SRC_IP_2, ..packet.clone() };
2137        let (conn, _dir) = conntrack
2138            .get_connection_for_packet_and_update(&bindings_ctx, reply.conntrack_packet().unwrap())
2139            .expect("packet should be valid")
2140            .expect("packet should be trackable");
2141        assert_matches!(
2142            conntrack
2143                .finalize_connection(&mut bindings_ctx, conn)
2144                .expect("connection should not conflict"),
2145            (true, Some(_))
2146        );
2147
2148        // Now, configure Masquerade NAT for a new connection that conflicts with the
2149        // existing one, but do not specify a port range to which the source port should
2150        // be rewritten.
2151        let mut conn = ConnectionExclusive::from_packet(&bindings_ctx, &packet);
2152        let verdict = configure_masquerade_nat(
2153            &mut core_ctx,
2154            &mut bindings_ctx,
2155            &conntrack,
2156            &mut conn,
2157            &packet,
2158            &Interfaces { ingress: None, egress: Some(&FakeMatcherDeviceId::ethernet_interface()) },
2159            /* src_port */ None,
2160        );
2161
2162        // The destination address of the reply tuple should have been rewritten to the
2163        // new source address, and the destination port should also have been rewritten
2164        // (to a "similar" value), even though a rewrite range was not specified,
2165        // because otherwise it would conflict with the existing connection in the
2166        // table.
2167        assert_matches!(
2168            verdict,
2169            Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::Yes(Some(_))))
2170        );
2171        let reply_tuple = conn.reply_tuple();
2172        assert_eq!(reply_tuple.dst_addr, I::SRC_IP_2);
2173        assert_ne!(reply_tuple.transport.dst_port_or_id(), src_port);
2174        assert!(expected_range.contains(&reply_tuple.transport.dst_port_or_id()));
2175    }
2176
2177    #[ip_test(I)]
2178    #[test_case(
2179        PhantomData::<IngressHook>, Action::Redirect { dst_port: None };
2180        "redirect in INGRESS"
2181    )]
2182    #[test_case(
2183        PhantomData::<EgressHook>, Action::Masquerade { src_port: None };
2184        "masquerade in EGRESS"
2185    )]
2186    fn assigned_addr_cached_and_validated<I: TestIpExt, N: NatHookExt<I>>(
2187        _nat_hook: PhantomData<N>,
2188        action: Action<I, FakeBindingsCtx<I>, ()>,
2189    ) {
2190        let mut bindings_ctx = FakeBindingsCtx::<I>::new();
2191        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
2192        let assigned_addr = AddrSubnet::new(I::SRC_IP_2, I::SUBNET.prefix()).unwrap();
2193        let mut core_ctx =
2194            FakeNatCtx::new([(FakeMatcherDeviceId::ethernet_interface(), assigned_addr)]);
2195
2196        // Create a packet and get the corresponding connection from conntrack.
2197        let mut packet = FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value();
2198        let (mut conn, direction) = conntrack
2199            .get_connection_for_packet_and_update(&bindings_ctx, packet.conntrack_packet().unwrap())
2200            .expect("packet should be valid")
2201            .expect("packet should be trackable");
2202
2203        // Perform NAT.
2204        let nat_routines = Hook {
2205            routines: vec![Routine { rules: vec![Rule::new(PacketMatcher::default(), action)] }],
2206        };
2207        let verdict = perform_nat::<N, _, _, _, _, _>(
2208            &mut core_ctx,
2209            &mut bindings_ctx,
2210            NAT_ENABLED_FOR_TESTS,
2211            &conntrack,
2212            &mut conn,
2213            direction,
2214            &nat_routines,
2215            &mut packet,
2216            N::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
2217            &mut FakePacketMetadata::default(),
2218        );
2219        assert_eq!(verdict, Verdict::Proceed(Accept));
2220
2221        // A weakly-held reference to the address assigned to the interface should be
2222        // cached in the NAT config.
2223        let (nat, _nat_type) = conn.relevant_config(N::NAT_TYPE, ConnectionDirection::Original);
2224        let nat = nat.get().unwrap_or_else(|| panic!("{:?} NAT should be configured", N::NAT_TYPE));
2225        let id = assert_matches!(nat, ShouldNat::Yes(Some(CachedAddr { id, _marker })) => id);
2226        let id = id
2227            .lock()
2228            .as_ref()
2229            .expect("address ID should be cached in NAT config")
2230            .upgrade()
2231            .expect("address ID should be valid");
2232        assert_eq!(*id, assigned_addr);
2233        drop(id);
2234
2235        // Remove the assigned address; subsequent packets in the original direction on
2236        // the same flow should check the validity of the cached address, see that it's
2237        // invalid, and be dropped.
2238        core_ctx.device_addrs.clear();
2239        let verdict = perform_nat::<N, _, _, _, _, _>(
2240            &mut core_ctx,
2241            &mut bindings_ctx,
2242            NAT_ENABLED_FOR_TESTS,
2243            &conntrack,
2244            &mut conn,
2245            ConnectionDirection::Original,
2246            &nat_routines,
2247            &mut FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value(),
2248            N::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
2249            &mut FakePacketMetadata::default(),
2250        );
2251        assert_eq!(verdict, Verdict::Stop(DropPacket));
2252        let (nat, _nat_type) = conn.relevant_config(N::NAT_TYPE, ConnectionDirection::Original);
2253        let nat = nat.get().unwrap_or_else(|| panic!("{:?} NAT should be configured", N::NAT_TYPE));
2254        let id = assert_matches!(nat, ShouldNat::Yes(Some(CachedAddr { id, _marker })) => id);
2255        assert_eq!(*id.lock(), None, "cached weak address ID should be cleared");
2256
2257        // Reassign the address to the interface, and packet traversal should now
2258        // succeed, with NAT re-acquiring a handle to the address.
2259        assert_matches!(
2260            core_ctx.device_addrs.insert(
2261                FakeMatcherDeviceId::ethernet_interface(),
2262                FakePrimaryAddressId(Arc::new(assigned_addr))
2263            ),
2264            None
2265        );
2266        let verdict = perform_nat::<N, _, _, _, _, _>(
2267            &mut core_ctx,
2268            &mut bindings_ctx,
2269            NAT_ENABLED_FOR_TESTS,
2270            &conntrack,
2271            &mut conn,
2272            ConnectionDirection::Original,
2273            &nat_routines,
2274            &mut FakeIpPacket::<_, FakeUdpPacket>::arbitrary_value(),
2275            N::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
2276            &mut FakePacketMetadata::default(),
2277        );
2278        assert_eq!(verdict, Verdict::Proceed(Accept));
2279        let (nat, _nat_type) = conn.relevant_config(N::NAT_TYPE, ConnectionDirection::Original);
2280        let nat = nat.get().unwrap_or_else(|| panic!("{:?} NAT should be configured", N::NAT_TYPE));
2281        let id = assert_matches!(nat, ShouldNat::Yes(Some(CachedAddr { id, _marker })) => id);
2282        let id = id
2283            .lock()
2284            .as_ref()
2285            .expect("address ID should be cached in NAT config")
2286            .upgrade()
2287            .expect("address Id should be valid");
2288        assert_eq!(*id, assigned_addr);
2289    }
2290
2291    #[test_case(ReplyTuplePort::Source)]
2292    #[test_case(ReplyTuplePort::Destination)]
2293    fn rewrite_port_noop_if_in_range(which: ReplyTuplePort) {
2294        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
2295        let table = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
2296        let mut conn =
2297            ConnectionExclusive::with_reply_tuple(&bindings_ctx, which, LOCAL_PORT.get());
2298
2299        // If the port is already in the specified range, rewriting should succeed and
2300        // be a no-op.
2301        let pre_nat = conn.reply_tuple().clone();
2302        let result = rewrite_reply_tuple_port(
2303            &mut bindings_ctx,
2304            &table,
2305            &mut conn,
2306            which,
2307            LOCAL_PORT..=LOCAL_PORT,
2308            true, /* ensure_port_in_range */
2309            ConflictStrategy::RewritePort,
2310        );
2311        assert_eq!(
2312            result,
2313            Verdict::Proceed(NatConfigurationResult::Result(
2314                ShouldNat::<_, FakeWeakAddressId<Ipv4>, _>::No
2315            ))
2316        );
2317        assert_eq!(conn.reply_tuple(), &pre_nat);
2318    }
2319
2320    #[test_case(ReplyTuplePort::Source)]
2321    #[test_case(ReplyTuplePort::Destination)]
2322    fn rewrite_port_noop_if_no_conflict(which: ReplyTuplePort) {
2323        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
2324        let table = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
2325        let mut conn =
2326            ConnectionExclusive::with_reply_tuple(&bindings_ctx, which, LOCAL_PORT.get());
2327
2328        // If there is no conflicting tuple in the table and we provide `false` for
2329        // `ensure_port_in_range` (as is done for implicit SNAT), then rewriting should
2330        // succeed and be a no-op, even if the port is not in the specified range,
2331        let pre_nat = conn.reply_tuple().clone();
2332        const NEW_PORT: NonZeroU16 = LOCAL_PORT.checked_add(1).unwrap();
2333        let result = rewrite_reply_tuple_port(
2334            &mut bindings_ctx,
2335            &table,
2336            &mut conn,
2337            which,
2338            NEW_PORT..=NEW_PORT,
2339            false, /* ensure_port_in_range */
2340            ConflictStrategy::RewritePort,
2341        );
2342        assert_eq!(
2343            result,
2344            Verdict::Proceed(NatConfigurationResult::Result(
2345                ShouldNat::<_, FakeWeakAddressId<Ipv4>, _>::No
2346            ))
2347        );
2348        assert_eq!(conn.reply_tuple(), &pre_nat);
2349    }
2350
2351    #[test_case(ReplyTuplePort::Source)]
2352    #[test_case(ReplyTuplePort::Destination)]
2353    fn rewrite_port_succeeds_if_available_port_in_range(which: ReplyTuplePort) {
2354        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
2355        let table = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
2356        let mut conn =
2357            ConnectionExclusive::with_reply_tuple(&bindings_ctx, which, LOCAL_PORT.get());
2358
2359        // If the port is not in the specified range, but there is an available port,
2360        // rewriting should succeed.
2361        const NEW_PORT: NonZeroU16 = LOCAL_PORT.checked_add(1).unwrap();
2362        let result = rewrite_reply_tuple_port(
2363            &mut bindings_ctx,
2364            &table,
2365            &mut conn,
2366            which,
2367            NEW_PORT..=NEW_PORT,
2368            true, /* ensure_port_in_range */
2369            ConflictStrategy::RewritePort,
2370        );
2371        assert_eq!(
2372            result,
2373            Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::<
2374                _,
2375                FakeWeakAddressId<Ipv4>,
2376                _,
2377            >::Yes(None)))
2378        );
2379        assert_eq!(conn.reply_tuple(), &tuple_with_port(which, NEW_PORT.get()));
2380    }
2381
2382    #[test_case(ReplyTuplePort::Source)]
2383    #[test_case(ReplyTuplePort::Destination)]
2384    fn rewrite_port_fails_if_no_available_port_in_range(which: ReplyTuplePort) {
2385        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
2386        let table: Table<_, NatConfig<_, FakeWeakAddressId<Ipv4>, _>, _> =
2387            Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
2388
2389        // If there is no port available in the specified range that does not conflict
2390        // with a tuple already in the table, rewriting should fail and the packet
2391        // should be dropped.
2392        let packet = packet_with_port(which, LOCAL_PORT.get());
2393        let (conn, _dir) = table
2394            .get_connection_for_packet_and_update(&bindings_ctx, packet.conntrack_packet().unwrap())
2395            .expect("packet should be valid")
2396            .expect("packet should be trackable");
2397        assert_matches!(
2398            table
2399                .finalize_connection(&mut bindings_ctx, conn)
2400                .expect("connection should not conflict"),
2401            (true, Some(_))
2402        );
2403
2404        let mut conn =
2405            ConnectionExclusive::with_reply_tuple(&bindings_ctx, which, LOCAL_PORT.get());
2406        let result = rewrite_reply_tuple_port(
2407            &mut bindings_ctx,
2408            &table,
2409            &mut conn,
2410            which,
2411            LOCAL_PORT..=LOCAL_PORT,
2412            true, /* ensure_port_in_range */
2413            ConflictStrategy::RewritePort,
2414        );
2415        assert_eq!(result, Verdict::Stop(DropPacket));
2416    }
2417
2418    #[test_case(ReplyTuplePort::Source)]
2419    #[test_case(ReplyTuplePort::Destination)]
2420    fn port_rewritten_to_ensure_unique_tuple_even_if_in_range(which: ReplyTuplePort) {
2421        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
2422        let table = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
2423
2424        // Fill the conntrack table with tuples such that there is only one tuple that
2425        // does not conflict with an existing one and which has a port in the specified
2426        // range.
2427        const MAX_PORT: NonZeroU16 = NonZeroU16::new(LOCAL_PORT.get() + 100).unwrap();
2428        for port in LOCAL_PORT.get()..=MAX_PORT.get() {
2429            let packet = packet_with_port(which, port);
2430            let (conn, _dir) = table
2431                .get_connection_for_packet_and_update(
2432                    &bindings_ctx,
2433                    packet.conntrack_packet().unwrap(),
2434                )
2435                .expect("packet should be valid")
2436                .expect("packet should be trackable");
2437            assert_matches!(
2438                table
2439                    .finalize_connection(&mut bindings_ctx, conn)
2440                    .expect("connection should not conflict"),
2441                (true, Some(_))
2442            );
2443        }
2444
2445        // If the port is in the specified range, but results in a non-unique tuple,
2446        // rewriting should succeed as long as some port exists in the range that
2447        // results in a unique tuple.
2448        let mut conn =
2449            ConnectionExclusive::with_reply_tuple(&bindings_ctx, which, LOCAL_PORT.get());
2450        const MIN_PORT: NonZeroU16 = NonZeroU16::new(LOCAL_PORT.get() - 1).unwrap();
2451        let result = rewrite_reply_tuple_port(
2452            &mut bindings_ctx,
2453            &table,
2454            &mut conn,
2455            which,
2456            MIN_PORT..=MAX_PORT,
2457            true, /* ensure_port_in_range */
2458            ConflictStrategy::RewritePort,
2459        );
2460        assert_eq!(
2461            result,
2462            Verdict::Proceed(NatConfigurationResult::Result(ShouldNat::<
2463                _,
2464                FakeWeakAddressId<Ipv4>,
2465                _,
2466            >::Yes(None)))
2467        );
2468        assert_eq!(conn.reply_tuple(), &tuple_with_port(which, MIN_PORT.get()));
2469    }
2470
2471    #[test_case(ReplyTuplePort::Source)]
2472    #[test_case(ReplyTuplePort::Destination)]
2473    fn rewrite_port_skipped_if_existing_connection_can_be_adopted(which: ReplyTuplePort) {
2474        let mut bindings_ctx = FakeBindingsCtx::<Ipv4>::new();
2475        let table: Table<_, NatConfig<_, FakeWeakAddressId<Ipv4>, _>, _> =
2476            Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
2477
2478        // If there is a conflicting connection already in the table, but the caller
2479        // specifies that existing connections can be adopted if they are identical to
2480        // the one we are NATing, and the one in the table is a match, the existing
2481        // connection should be adopted.
2482        let packet = packet_with_port(which, LOCAL_PORT.get());
2483        let (conn, _dir) = table
2484            .get_connection_for_packet_and_update(&bindings_ctx, packet.conntrack_packet().unwrap())
2485            .expect("packet should be valid")
2486            .expect("packet should be trackable");
2487        let existing = assert_matches!(
2488            table
2489                .finalize_connection(&mut bindings_ctx, conn)
2490                .expect("connection should not conflict"),
2491            (true, Some(conn)) => conn
2492        );
2493
2494        let mut conn = ConnectionExclusive::from_packet(&bindings_ctx, &packet);
2495        let result = rewrite_reply_tuple_port(
2496            &mut bindings_ctx,
2497            &table,
2498            &mut conn,
2499            which,
2500            NonZeroU16::MIN..=NonZeroU16::MAX,
2501            false, /* ensure_port_in_range */
2502            ConflictStrategy::AdoptExisting,
2503        );
2504        let conn = assert_matches!(
2505            result,
2506            Verdict::Proceed(NatConfigurationResult::AdoptExisting(Connection::Shared(conn))) => conn
2507        );
2508        assert!(Arc::ptr_eq(&existing, &conn));
2509    }
2510
2511    trait IcmpErrorTestIpExt: TestIpExt {
2512        const NETSTACK: Self::Addr = Self::DST_IP;
2513        const ULTIMATE_SRC: Self::Addr = Self::SRC_IP;
2514        const ULTIMATE_DST: Self::Addr = Self::DST_IP_3;
2515        const ROUTER_SRC: Self::Addr = Self::SRC_IP_2;
2516        const ROUTER_DST: Self::Addr = Self::DST_IP_2;
2517    }
2518
2519    impl<I> IcmpErrorTestIpExt for I where I: TestIpExt {}
2520
2521    enum IcmpErrorSource {
2522        IntermediateRouter,
2523        EndHost,
2524    }
2525
2526    // The next two test cases (redirect_icmp_error_in_reply_direction and
2527    // redirect_icmp_error_in_original_direction) require some explanation. The
2528    // tests are based on the `redirect` test above, but are validating that
2529    // ICMP error NAT works properly.
2530    //
2531    // The imaginary network used in these tests is set up as follows:
2532    //
2533    // D --- US --- SR --- S
2534    //
2535    // Where:
2536    //
2537    // - US: That's us :-)
2538    // - D:  The ultimate destination
2539    // - S:  The ultimate source
2540    // - SR: A router between us and the source
2541    //
2542    // The IPs that matter are:
2543    //
2544    // - D: ULTIMATE_DST
2545    // - US: NETSTACK
2546    // - S: ULTIMATE_SRC
2547    // - SR: ROUTER_SRC
2548    //
2549    // There is DNAT configured such that packets coming from S to D are
2550    // rewritten to instead go to US. Packets going from US -> S will have their
2551    // source rewritten to replace US with the address of D.
2552    //
2553    // Each test checks that an ICMP error traveling in either the original or
2554    // reply direction are rewritten appropriately.
2555
2556    #[test_case(Icmpv4DestUnreachableError)]
2557    #[test_case(Icmpv6DestUnreachableError)]
2558    fn redirect_icmp_error_in_reply_direction<I: IcmpErrorTestIpExt, IE: IcmpErrorMessage<I>>(
2559        _icmp_error: IE,
2560    ) {
2561        let mut bindings_ctx = FakeBindingsCtx::<I>::new();
2562        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
2563        let mut core_ctx = FakeNatCtx::new([(
2564            FakeMatcherDeviceId::ethernet_interface(),
2565            AddrSubnet::new(I::NETSTACK, I::SUBNET.prefix()).unwrap(),
2566        )]);
2567
2568        // Create a packet and get the corresponding connection from conntrack.
2569        let mut packet = EmptyBuf
2570            .wrap_in(UdpPacketBuilder::new(
2571                I::ULTIMATE_SRC,
2572                I::ULTIMATE_DST,
2573                Some(NonZeroU16::new(11111).unwrap()),
2574                NonZeroU16::new(22222).unwrap(),
2575            ))
2576            .wrap_in(I::PacketBuilder::new(
2577                I::ULTIMATE_SRC,
2578                I::ULTIMATE_DST,
2579                u8::MAX,
2580                IpProto::Udp.into(),
2581            ));
2582        let packet_pre_nat = packet.clone();
2583        let (mut conn, _) = conntrack
2584            .get_connection_for_packet_and_update(&bindings_ctx, packet.conntrack_packet().unwrap())
2585            .expect("packet should be valid")
2586            .expect("packet should be trackable");
2587        let original_tuple = conn.original_tuple().clone();
2588
2589        let nat_routines = Hook {
2590            routines: vec![Routine {
2591                rules: vec![Rule::new(
2592                    PacketMatcher::default(),
2593                    Action::Redirect { dst_port: Some(LOCAL_PORT..=LOCAL_PORT) },
2594                )],
2595            }],
2596        };
2597        let verdict = perform_nat::<IngressHook, _, _, _, _, _>(
2598            &mut core_ctx,
2599            &mut bindings_ctx,
2600            NAT_ENABLED_FOR_TESTS,
2601            &conntrack,
2602            &mut conn,
2603            ConnectionDirection::Original,
2604            &nat_routines,
2605            &mut packet,
2606            <IngressHook as NatHookExt<I>>::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
2607            &mut FakePacketMetadata::default(),
2608        );
2609        assert_eq!(verdict, Verdict::Proceed(Accept));
2610
2611        // The packet's destination should be rewritten and DNAT should be
2612        // configured for the packet; the reply tuple's source should be
2613        // rewritten to match the new destination.
2614        let (redirect_addr, cached_addr) = IngressHook::redirect_addr(
2615            &mut core_ctx,
2616            &packet,
2617            <IngressHook as NatHookExt<I>>::interfaces(&FakeMatcherDeviceId::ethernet_interface())
2618                .ingress,
2619        )
2620        .expect("get redirect addr for NAT hook");
2621
2622        // Since this is in the INGRESS hook, redirect_addr should be the
2623        // address of the receiving interface.
2624        assert_eq!(redirect_addr, I::NETSTACK);
2625
2626        // The destination address and port were updated.
2627        let expected = EmptyBuf
2628            .wrap_in(UdpPacketBuilder::new(
2629                I::ULTIMATE_SRC,
2630                redirect_addr,
2631                packet.inner().outer().src_port(),
2632                LOCAL_PORT,
2633            ))
2634            .wrap_in(I::PacketBuilder::new(
2635                I::ULTIMATE_SRC,
2636                redirect_addr,
2637                u8::MAX,
2638                IpProto::Udp.into(),
2639            ));
2640        assert_eq!(packet, expected);
2641        assert_eq!(
2642            conn.external_data().destination.get().expect("DNAT should be configured"),
2643            &ShouldNat::Yes(cached_addr)
2644        );
2645        assert_eq!(conn.external_data().source.get(), None, "SNAT should not be configured");
2646        assert_eq!(conn.original_tuple(), &original_tuple);
2647
2648        let mut reply_tuple = Tuple { src_addr: redirect_addr, ..original_tuple.invert() };
2649        reply_tuple.transport.set_src_port_or_id(LOCAL_PORT.get());
2650        assert_eq!(conn.reply_tuple(), &reply_tuple);
2651
2652        let mut error_packet = IE::make_serializer(
2653            redirect_addr,
2654            I::ULTIMATE_SRC,
2655            packet
2656                .clone()
2657                .serialize_vec_outer(&mut NetworkSerializationContext::default())
2658                .unwrap()
2659                .unwrap_b()
2660                .into_inner(),
2661        )
2662        .wrap_in(I::PacketBuilder::new(
2663            redirect_addr,
2664            I::ULTIMATE_SRC,
2665            u8::MAX,
2666            IE::proto(),
2667        ));
2668
2669        let verdict = perform_nat::<EgressHook, _, _, _, _, _>(
2670            &mut core_ctx,
2671            &mut bindings_ctx,
2672            NAT_ENABLED_FOR_TESTS,
2673            &conntrack,
2674            &mut conn,
2675            ConnectionDirection::Reply,
2676            &nat_routines,
2677            &mut error_packet,
2678            <EgressHook as NatHookExt<I>>::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
2679            &mut FakePacketMetadata::default(),
2680        );
2681        assert_eq!(verdict, Verdict::Proceed(Accept));
2682
2683        let error_packet_expected = IE::make_serializer(
2684            // We expect this address to be rewritten since `redirect_addr`
2685            // shouldn't end up in the packet destined to the other host.
2686            I::ULTIMATE_DST,
2687            I::ULTIMATE_SRC,
2688            packet_pre_nat
2689                .serialize_vec_outer(&mut NetworkSerializationContext::default())
2690                .unwrap()
2691                .unwrap_b()
2692                .into_inner(),
2693        )
2694        .wrap_in(I::PacketBuilder::new(
2695            I::ULTIMATE_DST,
2696            I::ULTIMATE_SRC,
2697            u8::MAX,
2698            IE::proto(),
2699        ));
2700
2701        assert_eq!(error_packet, error_packet_expected);
2702    }
2703
2704    #[test_matrix(
2705        [
2706            Icmpv4DestUnreachableError,
2707            Icmpv6DestUnreachableError,
2708        ],
2709        [
2710            IcmpErrorSource::IntermediateRouter,
2711            IcmpErrorSource::EndHost,
2712        ]
2713    )]
2714    fn redirect_icmp_error_in_original_direction<I: IcmpErrorTestIpExt, IE: IcmpErrorMessage<I>>(
2715        _icmp_error: IE,
2716        icmp_error_source: IcmpErrorSource,
2717    ) {
2718        let mut bindings_ctx = FakeBindingsCtx::<I>::new();
2719        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
2720        let mut core_ctx = FakeNatCtx::new([(
2721            FakeMatcherDeviceId::ethernet_interface(),
2722            AddrSubnet::new(I::NETSTACK, I::SUBNET.prefix()).unwrap(),
2723        )]);
2724
2725        // Create a packet and get the corresponding connection from conntrack.
2726        let mut packet = EmptyBuf
2727            .wrap_in(UdpPacketBuilder::new(
2728                I::ULTIMATE_SRC,
2729                I::ULTIMATE_DST,
2730                Some(NonZeroU16::new(11111).unwrap()),
2731                NonZeroU16::new(22222).unwrap(),
2732            ))
2733            .wrap_in(I::PacketBuilder::new(
2734                I::ULTIMATE_SRC,
2735                I::ULTIMATE_DST,
2736                u8::MAX,
2737                IpProto::Udp.into(),
2738            ));
2739        let (mut conn, direction) = conntrack
2740            .get_connection_for_packet_and_update(&bindings_ctx, packet.conntrack_packet().unwrap())
2741            .expect("packet should be valid")
2742            .expect("packet should be trackable");
2743        let original_tuple = conn.original_tuple().clone();
2744
2745        // Perform NAT at the first hook where we'd encounter this packet (either
2746        // INGRESS, if it's an incoming packet, or LOCAL_EGRESS, if it's an outgoing
2747        // packet).
2748        let nat_routines = Hook {
2749            routines: vec![Routine {
2750                rules: vec![Rule::new(
2751                    PacketMatcher::default(),
2752                    Action::Redirect { dst_port: Some(LOCAL_PORT..=LOCAL_PORT) },
2753                )],
2754            }],
2755        };
2756        let verdict = perform_nat::<IngressHook, _, _, _, _, _>(
2757            &mut core_ctx,
2758            &mut bindings_ctx,
2759            NAT_ENABLED_FOR_TESTS,
2760            &conntrack,
2761            &mut conn,
2762            direction,
2763            &nat_routines,
2764            &mut packet,
2765            <IngressHook as NatHookExt<I>>::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
2766            &mut FakePacketMetadata::default(),
2767        );
2768        assert_eq!(verdict, Verdict::Proceed(Accept));
2769
2770        // The packet's destination should be rewritten, and DNAT should be configured
2771        // for the packet; the reply tuple's source should be rewritten to match the new
2772        // destination.
2773        let (redirect_addr, cached_addr) = IngressHook::redirect_addr(
2774            &mut core_ctx,
2775            &packet,
2776            <IngressHook as NatHookExt<I>>::interfaces(&FakeMatcherDeviceId::ethernet_interface())
2777                .ingress,
2778        )
2779        .expect("get redirect addr for NAT hook");
2780
2781        // Since this is in the INGRESS hook, redirect_addr should be the
2782        // address of the receiving interface.
2783        assert_eq!(redirect_addr, I::NETSTACK);
2784
2785        // The destination address and port were updated.
2786        let expected = EmptyBuf
2787            .wrap_in(UdpPacketBuilder::new(
2788                I::ULTIMATE_SRC,
2789                redirect_addr,
2790                packet.inner().outer().src_port(),
2791                LOCAL_PORT,
2792            ))
2793            .wrap_in(I::PacketBuilder::new(
2794                I::ULTIMATE_SRC,
2795                redirect_addr,
2796                u8::MAX,
2797                IpProto::Udp.into(),
2798            ));
2799        assert_eq!(packet, expected);
2800        assert_eq!(
2801            conn.external_data().destination.get().expect("DNAT should be configured"),
2802            &ShouldNat::Yes(cached_addr)
2803        );
2804        assert_eq!(conn.external_data().source.get(), None, "SNAT should not be configured");
2805        assert_eq!(conn.original_tuple(), &original_tuple);
2806        let mut reply_tuple = Tuple { src_addr: redirect_addr, ..original_tuple.invert() };
2807        reply_tuple.transport.set_src_port_or_id(LOCAL_PORT.get());
2808        assert_eq!(conn.reply_tuple(), &reply_tuple);
2809
2810        let mut reply_packet = EmptyBuf
2811            .wrap_in(UdpPacketBuilder::new(
2812                reply_tuple.src_addr,
2813                reply_tuple.dst_addr,
2814                Some(NonZeroU16::new(reply_tuple.transport.src_port_or_id()).unwrap()),
2815                NonZeroU16::new(reply_tuple.transport.dst_port_or_id()).unwrap(),
2816            ))
2817            .wrap_in(I::PacketBuilder::new(
2818                reply_tuple.src_addr,
2819                reply_tuple.dst_addr,
2820                u8::MAX,
2821                IpProto::Udp.into(),
2822            ));
2823        let reply_packet_pre_nat = reply_packet.clone();
2824
2825        let verdict = perform_nat::<EgressHook, _, _, _, _, _>(
2826            &mut core_ctx,
2827            &mut bindings_ctx,
2828            NAT_ENABLED_FOR_TESTS,
2829            &conntrack,
2830            &mut conn,
2831            ConnectionDirection::Reply,
2832            &nat_routines,
2833            &mut reply_packet,
2834            <EgressHook as NatHookExt<I>>::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
2835            &mut FakePacketMetadata::default(),
2836        );
2837        assert_eq!(verdict, Verdict::Proceed(Accept));
2838
2839        let reply_packet_expected = EmptyBuf
2840            .wrap_in(UdpPacketBuilder::new(
2841                I::ULTIMATE_DST,
2842                I::ULTIMATE_SRC,
2843                Some(NonZeroU16::new(22222).unwrap()),
2844                NonZeroU16::new(11111).unwrap(),
2845            ))
2846            .wrap_in(I::PacketBuilder::new(
2847                I::ULTIMATE_DST,
2848                I::ULTIMATE_SRC,
2849                u8::MAX,
2850                IpProto::Udp.into(),
2851            ));
2852        assert_eq!(reply_packet, reply_packet_expected);
2853
2854        // The packet sent from D -> S was invalid and triggered an ICMP error
2855        // either from either S or SR.
2856        let error_src_addr = match icmp_error_source {
2857            IcmpErrorSource::IntermediateRouter => I::ROUTER_SRC,
2858            IcmpErrorSource::EndHost => I::ULTIMATE_SRC,
2859        };
2860
2861        let mut error_packet = IE::make_serializer(
2862            error_src_addr,
2863            I::ULTIMATE_DST,
2864            reply_packet
2865                .clone()
2866                .serialize_vec_outer(&mut NetworkSerializationContext::default())
2867                .unwrap()
2868                .unwrap_b()
2869                .into_inner(),
2870        )
2871        .wrap_in(I::PacketBuilder::new(
2872            error_src_addr,
2873            I::ULTIMATE_DST,
2874            u8::MAX,
2875            IE::proto(),
2876        ));
2877
2878        let verdict = perform_nat::<IngressHook, _, _, _, _, _>(
2879            &mut core_ctx,
2880            &mut bindings_ctx,
2881            NAT_ENABLED_FOR_TESTS,
2882            &conntrack,
2883            &mut conn,
2884            direction,
2885            &nat_routines,
2886            &mut error_packet,
2887            <IngressHook as NatHookExt<I>>::interfaces(&FakeMatcherDeviceId::ethernet_interface()),
2888            &mut FakePacketMetadata::default(),
2889        );
2890        assert_eq!(verdict, Verdict::Proceed(Accept));
2891
2892        let error_packet_expected = IE::make_serializer(
2893            // Unlike in the reply case, we shouldn't expect this address to be
2894            // rewritten since it's not one configured for NAT.
2895            error_src_addr,
2896            redirect_addr,
2897            reply_packet_pre_nat
2898                .serialize_vec_outer(&mut NetworkSerializationContext::default())
2899                .unwrap()
2900                .unwrap_b()
2901                .into_inner(),
2902        )
2903        .wrap_in(I::PacketBuilder::new(
2904            error_src_addr,
2905            redirect_addr,
2906            u8::MAX,
2907            IE::proto(),
2908        ));
2909
2910        assert_eq!(error_packet, error_packet_expected);
2911    }
2912
2913    // This is an explanation of masquerade_icmp_error_in_reply_direction and
2914    // masquerade_icmp_error_in_original_direction. There is more background
2915    // information in the equivalent comment of the redirect ICMP error tests.
2916    //
2917    // The imaginary network used in these tests is set up as follows:
2918    //
2919    // S --- SR --- US --- DR --- D
2920    //
2921    // Where:
2922    //
2923    // - US: That's us :-)
2924    // - D:  The ultimate destination
2925    // - S:  The ultimate source
2926    // - DR: A router between us and the destination
2927    // - SR: A router between us and the source
2928    //
2929    // The IPs that matter are:
2930    //
2931    // - D: ULTIMATE_DST
2932    // - DR: ROUTER_DST
2933    // - S: ULTIMAKE_SOURCE
2934    // - SR: ROUTER_SRC
2935    // - US: ULTIMATE_SRC
2936    //
2937    // The network is configured such that any packets traveling from S through
2938    // US are rewritten to have the address of US as their source address.
2939
2940    #[test_matrix(
2941        [
2942            Icmpv4DestUnreachableError,
2943            Icmpv6DestUnreachableError,
2944        ],
2945        [
2946            IcmpErrorSource::IntermediateRouter,
2947            IcmpErrorSource::EndHost,
2948        ]
2949    )]
2950    fn masquerade_icmp_error_in_reply_direction<I: TestIpExt, IE: IcmpErrorMessage<I>>(
2951        _icmp_error: IE,
2952        icmp_error_source: IcmpErrorSource,
2953    ) {
2954        let mut bindings_ctx = FakeBindingsCtx::<I>::new();
2955        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
2956        let assigned_addr = AddrSubnet::new(I::NETSTACK, I::SUBNET.prefix()).unwrap();
2957        let mut core_ctx =
2958            FakeNatCtx::new([(FakeMatcherDeviceId::ethernet_interface(), assigned_addr)]);
2959
2960        // Create a packet and get the corresponding connection from conntrack.
2961        let mut packet = EmptyBuf
2962            .wrap_in(UdpPacketBuilder::new(
2963                I::ULTIMATE_SRC,
2964                I::ULTIMATE_DST,
2965                Some(NonZeroU16::new(11111).unwrap()),
2966                NonZeroU16::new(22222).unwrap(),
2967            ))
2968            .wrap_in(I::PacketBuilder::new(
2969                I::ULTIMATE_SRC,
2970                I::ULTIMATE_DST,
2971                u8::MAX,
2972                IpProto::Udp.into(),
2973            ));
2974        let packet_pre_nat = packet.clone();
2975        let (mut conn, direction) = conntrack
2976            .get_connection_for_packet_and_update(&bindings_ctx, packet.conntrack_packet().unwrap())
2977            .expect("packet should be valid")
2978            .expect("packet should be trackable");
2979        let original_tuple = conn.original_tuple().clone();
2980
2981        // Perform Masquerade NAT at EGRESS.
2982        let nat_routines = Hook {
2983            routines: vec![Routine {
2984                rules: vec![Rule::new(
2985                    PacketMatcher::default(),
2986                    Action::Masquerade { src_port: Some(LOCAL_PORT..=LOCAL_PORT) },
2987                )],
2988            }],
2989        };
2990        let verdict = perform_nat::<EgressHook, _, _, _, _, _>(
2991            &mut core_ctx,
2992            &mut bindings_ctx,
2993            NAT_ENABLED_FOR_TESTS,
2994            &conntrack,
2995            &mut conn,
2996            direction,
2997            &nat_routines,
2998            &mut packet,
2999            Interfaces { ingress: None, egress: Some(&FakeMatcherDeviceId::ethernet_interface()) },
3000            &mut FakePacketMetadata::default(),
3001        );
3002        assert_eq!(verdict, Verdict::Proceed(Accept));
3003
3004        // The packet's source address should be rewritten, and SNAT should be
3005        // configured for the packet; the reply tuple's destination should be rewritten
3006        // to match the new source.
3007        let expected = EmptyBuf
3008            .wrap_in(UdpPacketBuilder::new(
3009                I::NETSTACK,
3010                I::ULTIMATE_DST,
3011                Some(LOCAL_PORT),
3012                packet.inner().outer().dst_port().unwrap(),
3013            ))
3014            .wrap_in(I::PacketBuilder::new(
3015                I::NETSTACK,
3016                I::ULTIMATE_DST,
3017                u8::MAX,
3018                IpProto::Udp.into(),
3019            ));
3020        assert_eq!(packet, expected);
3021        assert_matches!(
3022            conn.external_data().source.get().expect("SNAT should be configured"),
3023            &ShouldNat::Yes(Some(_))
3024        );
3025        assert_eq!(conn.external_data().destination.get(), None, "DNAT should not be configured");
3026        assert_eq!(conn.original_tuple(), &original_tuple);
3027        let mut reply_tuple = Tuple { dst_addr: I::NETSTACK, ..original_tuple.invert() };
3028        reply_tuple.transport.set_dst_port_or_id(LOCAL_PORT.get());
3029        assert_eq!(conn.reply_tuple(), &reply_tuple);
3030
3031        // The packet sent from S -> D was invalid and triggered an ICMP error
3032        // either from D or DR.
3033        let error_src_addr = match icmp_error_source {
3034            IcmpErrorSource::IntermediateRouter => I::ROUTER_DST,
3035            IcmpErrorSource::EndHost => I::ULTIMATE_DST,
3036        };
3037
3038        let mut error_packet = IE::make_serializer(
3039            error_src_addr,
3040            I::NETSTACK,
3041            packet
3042                .clone()
3043                .serialize_vec_outer(&mut NetworkSerializationContext::default())
3044                .unwrap()
3045                .unwrap_b()
3046                .into_inner(),
3047        )
3048        .wrap_in(I::PacketBuilder::new(error_src_addr, I::NETSTACK, u8::MAX, IE::proto()));
3049
3050        let verdict = perform_nat::<IngressHook, _, _, _, _, _>(
3051            &mut core_ctx,
3052            &mut bindings_ctx,
3053            NAT_ENABLED_FOR_TESTS,
3054            &conntrack,
3055            &mut conn,
3056            ConnectionDirection::Reply,
3057            &nat_routines,
3058            &mut error_packet,
3059            Interfaces { ingress: Some(&FakeMatcherDeviceId::ethernet_interface()), egress: None },
3060            &mut FakePacketMetadata::default(),
3061        );
3062        assert_eq!(verdict, Verdict::Proceed(Accept));
3063
3064        let error_packet_expected = IE::make_serializer(
3065            // We expect this address to be rewritten since `redirect_addr`
3066            // shouldn't end up in the packet destined to the other host.
3067            error_src_addr,
3068            I::ULTIMATE_SRC,
3069            packet_pre_nat
3070                .serialize_vec_outer(&mut NetworkSerializationContext::default())
3071                .unwrap()
3072                .unwrap_b()
3073                .into_inner(),
3074        )
3075        .wrap_in(I::PacketBuilder::new(
3076            error_src_addr,
3077            I::ULTIMATE_SRC,
3078            u8::MAX,
3079            IE::proto(),
3080        ));
3081
3082        assert_eq!(error_packet, error_packet_expected);
3083    }
3084
3085    #[test_matrix(
3086        [
3087            Icmpv4DestUnreachableError,
3088            Icmpv6DestUnreachableError,
3089        ],
3090        [
3091            IcmpErrorSource::IntermediateRouter,
3092            IcmpErrorSource::EndHost,
3093        ]
3094    )]
3095    fn masquerade_icmp_error_in_original_direction<I: TestIpExt, IE: IcmpErrorMessage<I>>(
3096        _icmp_error: IE,
3097        icmp_error_source: IcmpErrorSource,
3098    ) {
3099        let mut bindings_ctx = FakeBindingsCtx::<I>::new();
3100        let conntrack = Table::new::<IntoCoreTimerCtx>(&mut bindings_ctx);
3101        let assigned_addr = AddrSubnet::new(I::NETSTACK, I::SUBNET.prefix()).unwrap();
3102        let mut core_ctx =
3103            FakeNatCtx::new([(FakeMatcherDeviceId::ethernet_interface(), assigned_addr)]);
3104
3105        // Create a packet and get the corresponding connection from conntrack.
3106        let mut packet = EmptyBuf
3107            .wrap_in(UdpPacketBuilder::new(
3108                I::ULTIMATE_SRC,
3109                I::ULTIMATE_DST,
3110                Some(NonZeroU16::new(11111).unwrap()),
3111                NonZeroU16::new(22222).unwrap(),
3112            ))
3113            .wrap_in(I::PacketBuilder::new(
3114                I::ULTIMATE_SRC,
3115                I::ULTIMATE_DST,
3116                u8::MAX,
3117                IpProto::Udp.into(),
3118            ));
3119        let (mut conn, direction) = conntrack
3120            .get_connection_for_packet_and_update(&bindings_ctx, packet.conntrack_packet().unwrap())
3121            .expect("packet should be valid")
3122            .expect("packet should be trackable");
3123        let original_tuple = conn.original_tuple().clone();
3124
3125        // Perform Masquerade NAT at EGRESS.
3126        let nat_routines = Hook {
3127            routines: vec![Routine {
3128                rules: vec![Rule::new(
3129                    PacketMatcher::default(),
3130                    Action::Masquerade { src_port: Some(LOCAL_PORT..=LOCAL_PORT) },
3131                )],
3132            }],
3133        };
3134        let verdict = perform_nat::<EgressHook, _, _, _, _, _>(
3135            &mut core_ctx,
3136            &mut bindings_ctx,
3137            NAT_ENABLED_FOR_TESTS,
3138            &conntrack,
3139            &mut conn,
3140            direction,
3141            &nat_routines,
3142            &mut packet,
3143            Interfaces { ingress: None, egress: Some(&FakeMatcherDeviceId::ethernet_interface()) },
3144            &mut FakePacketMetadata::default(),
3145        );
3146        assert_eq!(verdict, Verdict::Proceed(Accept));
3147
3148        // The packet's source address should be rewritten, and SNAT should be
3149        // configured for the packet; the reply tuple's destination should be rewritten
3150        // to match the new source.
3151        let expected = EmptyBuf
3152            .wrap_in(UdpPacketBuilder::new(
3153                I::NETSTACK,
3154                I::ULTIMATE_DST,
3155                Some(LOCAL_PORT),
3156                packet.inner().outer().dst_port().unwrap(),
3157            ))
3158            .wrap_in(I::PacketBuilder::new(
3159                I::NETSTACK,
3160                I::ULTIMATE_DST,
3161                u8::MAX,
3162                IpProto::Udp.into(),
3163            ));
3164        assert_eq!(packet, expected);
3165        assert_matches!(
3166            conn.external_data().source.get().expect("SNAT should be configured"),
3167            &ShouldNat::Yes(Some(_))
3168        );
3169        assert_eq!(conn.external_data().destination.get(), None, "DNAT should not be configured");
3170        assert_eq!(conn.original_tuple(), &original_tuple);
3171        let mut reply_tuple = Tuple { dst_addr: I::NETSTACK, ..original_tuple.invert() };
3172        reply_tuple.transport.set_dst_port_or_id(LOCAL_PORT.get());
3173        assert_eq!(conn.reply_tuple(), &reply_tuple);
3174
3175        // When a reply to the original packet arrives at INGRESS, it should
3176        // have reverse SNAT applied, i.e. its destination should be rewritten
3177        // to match the original source of the connection.
3178        let mut reply_packet = EmptyBuf
3179            .wrap_in(UdpPacketBuilder::new(
3180                reply_tuple.src_addr,
3181                reply_tuple.dst_addr,
3182                Some(NonZeroU16::new(reply_tuple.transport.src_port_or_id()).unwrap()),
3183                NonZeroU16::new(reply_tuple.transport.dst_port_or_id()).unwrap(),
3184            ))
3185            .wrap_in(I::PacketBuilder::new(
3186                reply_tuple.src_addr,
3187                reply_tuple.dst_addr,
3188                u8::MAX,
3189                IpProto::Udp.into(),
3190            ));
3191        let reply_packet_pre_nat = reply_packet.clone();
3192
3193        let verdict = perform_nat::<IngressHook, _, _, _, _, _>(
3194            &mut core_ctx,
3195            &mut bindings_ctx,
3196            NAT_ENABLED_FOR_TESTS,
3197            &conntrack,
3198            &mut conn,
3199            ConnectionDirection::Reply,
3200            &nat_routines,
3201            &mut reply_packet,
3202            Interfaces { ingress: Some(&FakeMatcherDeviceId::ethernet_interface()), egress: None },
3203            &mut FakePacketMetadata::default(),
3204        );
3205        assert_eq!(verdict, Verdict::Proceed(Accept));
3206
3207        let reply_packet_expected = EmptyBuf
3208            .wrap_in(UdpPacketBuilder::new(
3209                I::ULTIMATE_DST,
3210                I::ULTIMATE_SRC,
3211                Some(NonZeroU16::new(22222).unwrap()),
3212                NonZeroU16::new(11111).unwrap(),
3213            ))
3214            .wrap_in(I::PacketBuilder::new(
3215                I::ULTIMATE_DST,
3216                I::ULTIMATE_SRC,
3217                u8::MAX,
3218                IpProto::Udp.into(),
3219            ));
3220        assert_eq!(reply_packet, reply_packet_expected);
3221
3222        let error_src_addr = match icmp_error_source {
3223            IcmpErrorSource::IntermediateRouter => I::ROUTER_SRC,
3224            IcmpErrorSource::EndHost => I::ULTIMATE_SRC,
3225        };
3226
3227        let mut error_packet = IE::make_serializer(
3228            error_src_addr,
3229            I::ULTIMATE_DST,
3230            reply_packet
3231                .clone()
3232                .serialize_vec_outer(&mut NetworkSerializationContext::default())
3233                .unwrap()
3234                .unwrap_b()
3235                .into_inner(),
3236        )
3237        .wrap_in(I::PacketBuilder::new(
3238            error_src_addr,
3239            I::ULTIMATE_DST,
3240            u8::MAX,
3241            IE::proto(),
3242        ));
3243
3244        let verdict = perform_nat::<EgressHook, _, _, _, _, _>(
3245            &mut core_ctx,
3246            &mut bindings_ctx,
3247            NAT_ENABLED_FOR_TESTS,
3248            &conntrack,
3249            &mut conn,
3250            direction,
3251            &nat_routines,
3252            &mut error_packet,
3253            Interfaces { ingress: None, egress: Some(&FakeMatcherDeviceId::ethernet_interface()) },
3254            &mut FakePacketMetadata::default(),
3255        );
3256        assert_eq!(verdict, Verdict::Proceed(Accept));
3257
3258        let error_packet_expected =
3259            I::PacketBuilder::new(I::NETSTACK, I::ULTIMATE_DST, u8::MAX, IE::proto()).wrap_body(
3260                IE::make_serializer(
3261                    // We expect this address to be rewritten since `redirect_addr`
3262                    // shouldn't end up in the packet destined to the other host.
3263                    I::NETSTACK,
3264                    I::ULTIMATE_DST,
3265                    reply_packet_pre_nat
3266                        .serialize_vec_outer(&mut NetworkSerializationContext::default())
3267                        .unwrap()
3268                        .unwrap_b()
3269                        .into_inner(),
3270                ),
3271            );
3272
3273        assert_eq!(error_packet, error_packet_expected);
3274    }
3275}