Skip to main content

landlock/
net.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3use crate::compat::{private::OptionCompatLevelMut, try_compat_binary};
4use crate::ruleset::QuietRuleCompatibility;
5use crate::{
6    uapi, Access, AddRuleError, AddRulesError, CompatError, CompatLevel, CompatResult, CompatState,
7    Compatible, HandleAccessError, HandleAccessesError, HandledAccess, PrivateHandledAccess,
8    PrivateRule, Rule, Ruleset, RulesetCreated, TailoredCompatLevel, TryCompat, ABI,
9};
10use enumflags2::{bitflags, BitFlags};
11use std::mem::zeroed;
12
13/// Network access right.
14///
15/// Each variant of `AccessNet` is an [access right](https://www.kernel.org/doc/html/latest/userspace-api/landlock.html#access-rights)
16/// for the network.
17/// A set of access rights can be created with [`BitFlags<AccessNet>`](BitFlags).
18///
19/// # Example
20///
21/// ```
22/// use landlock::{ABI, Access, AccessNet, BitFlags, make_bitflags};
23///
24/// let bind = AccessNet::BindTcp;
25///
26/// let bind_set: BitFlags<AccessNet> = bind.into();
27///
28/// let bind_connect = make_bitflags!(AccessNet::{BindTcp | ConnectTcp});
29///
30/// let net_v4 = AccessNet::from_all(ABI::V4);
31///
32/// assert_eq!(bind_connect, net_v4);
33/// ```
34///
35/// # Warning
36///
37/// To avoid unknown restrictions **don't use `BitFlags::<AccessNet>::all()` nor `BitFlags::ALL`**,
38/// but use a version you tested and vetted instead,
39/// for instance [`AccessNet::from_all(ABI::V4)`](Access::from_all).
40/// Direct use of **the [`BitFlags`] API is deprecated**.
41/// See [`ABI`] for the rationale and help to test it.
42#[bitflags]
43#[repr(u64)]
44#[derive(Copy, Clone, Debug, PartialEq, Eq)]
45#[non_exhaustive]
46pub enum AccessNet {
47    /// Bind to a TCP port.
48    BindTcp = uapi::LANDLOCK_ACCESS_NET_BIND_TCP as u64,
49    /// Connect to a TCP port.
50    ConnectTcp = uapi::LANDLOCK_ACCESS_NET_CONNECT_TCP as u64,
51    /// Bind to a UDP port.
52    ///
53    /// This also covers the implicit bind to an ephemeral port performed by the
54    /// kernel when setting the remote peer of a socket or sending a first
55    /// datagram from an unbound socket.  See [`AccessNet::ConnectSendUdp`].
56    BindUdp = uapi::LANDLOCK_ACCESS_NET_BIND_UDP as u64,
57    /// Set the remote port of a UDP socket with `connect(2)`, or send a datagram
58    /// to an explicit remote port with e.g. `sendto(2)` or `sendmsg(2)`,
59    /// ignoring any destination already pre-set on the socket.
60    ///
61    /// Because the kernel auto-binds an unbound UDP socket to an ephemeral local
62    /// port when doing so, a ruleset handling both this right and
63    /// [`AccessNet::BindUdp`] must also allow that bind: either grant [`AccessNet::BindUdp`]
64    /// on port 0 (i.e. any ephemeral port), or grant it on a specific port and
65    /// `bind(2)` that port first, or use a socket bound before the ruleset was
66    /// enforced.
67    ///
68    /// Note that sending a datagram to an `AF_UNSPEC` destination address family
69    /// is not supported for IPv6 UDP sockets; a `NULL` address must be used
70    /// instead.
71    ConnectSendUdp = uapi::LANDLOCK_ACCESS_NET_CONNECT_SEND_UDP as u64,
72}
73
74/// # Warning
75///
76/// If `ABI <= ABI::V3`, `AccessNet::from_all()` returns an empty `BitFlags<AccessNet>`, which
77/// makes `Ruleset::handle_access(AccessNet::from_all(ABI::V3))` return an error.
78impl Access for AccessNet {
79    fn from_all(abi: ABI) -> BitFlags<Self> {
80        match abi {
81            ABI::Unsupported | ABI::V1 | ABI::V2 | ABI::V3 => BitFlags::EMPTY,
82            ABI::V4 | ABI::V5 | ABI::V6 | ABI::V7 | ABI::V8 | ABI::V9 => {
83                AccessNet::BindTcp | AccessNet::ConnectTcp
84            }
85            ABI::V10 => Self::from_all(ABI::V9) | AccessNet::BindUdp | AccessNet::ConnectSendUdp,
86        }
87    }
88}
89
90#[test]
91fn access_net_from_all() {
92    let tcp = AccessNet::BindTcp | AccessNet::ConnectTcp;
93    let udp = AccessNet::BindUdp | AccessNet::ConnectSendUdp;
94
95    assert_eq!(AccessNet::from_all(ABI::V3), BitFlags::EMPTY);
96    assert_eq!(AccessNet::from_all(ABI::V4), tcp);
97    assert_eq!(AccessNet::from_all(ABI::V9), tcp);
98    assert_eq!(AccessNet::from_all(ABI::V10), tcp | udp);
99}
100
101impl HandledAccess for AccessNet {}
102
103impl PrivateHandledAccess for AccessNet {
104    fn ruleset_handle_access(
105        ruleset: &mut Ruleset,
106        access: BitFlags<Self>,
107    ) -> Result<(), HandleAccessesError> {
108        ruleset
109            .net
110            .request(access, &mut ruleset.compat)
111            .map_err(HandleAccessError::Compat)?;
112        Ok(())
113    }
114
115    fn ruleset_quiet_access(
116        ruleset: &mut Ruleset,
117        access: BitFlags<Self>,
118    ) -> Result<(), HandleAccessesError> {
119        ruleset
120            .net
121            .request_quiet(access, &mut ruleset.compat)
122            .map_err(HandleAccessError::Compat)?;
123        Ok(())
124    }
125
126    fn ruleset_has_effective_quiet_access(ruleset: &RulesetCreated, abi: ABI) -> bool {
127        !ruleset.net.resolve(abi).quiet.is_empty()
128    }
129
130    fn into_add_rules_error(error: AddRuleError<Self>) -> AddRulesError {
131        AddRulesError::Net(error)
132    }
133
134    fn into_handle_accesses_error(error: HandleAccessError<Self>) -> HandleAccessesError {
135        HandleAccessesError::Net(error)
136    }
137}
138
139/// Landlock rule for a network port.
140///
141/// # Example
142///
143/// ```
144/// use landlock::{AccessNet, NetPort};
145///
146/// fn bind_http() -> NetPort {
147///     NetPort::new(80, AccessNet::BindTcp)
148/// }
149/// ```
150#[derive(Debug)]
151pub struct NetPort {
152    attr: uapi::landlock_net_port_attr,
153    // Only 16-bit port make sense for now.
154    port: u16,
155    allowed_access: BitFlags<AccessNet>,
156    compat_level: Option<CompatLevel>,
157    quiet: bool,
158    quiet_compatibility: QuietRuleCompatibility,
159}
160
161// If we need support for 32 or 64 ports, we'll add a new_32() or a new_64() method returning a
162// Result with a potential overflow error.
163impl NetPort {
164    /// Creates a new TCP or UDP port rule.
165    ///
166    /// As defined by the Linux ABI, `port` with a value of `0` means that bindings will be
167    /// allowed for a port range defined by `/proc/sys/net/ipv4/ip_local_port_range`.
168    pub fn new<A>(port: u16, access: A) -> Self
169    where
170        A: Into<BitFlags<AccessNet>>,
171    {
172        NetPort {
173            // Invalid access-rights until as_ptr() is called.
174            attr: unsafe { zeroed() },
175            port,
176            allowed_access: access.into(),
177            compat_level: None,
178            quiet: false,
179            quiet_compatibility: QuietRuleCompatibility::Unsupported,
180        }
181    }
182}
183
184impl Rule<AccessNet> for NetPort {}
185
186impl PrivateRule<AccessNet> for NetPort {
187    const TYPE_ID: uapi::landlock_rule_type = uapi::landlock_rule_type_LANDLOCK_RULE_NET_PORT;
188
189    fn as_ptr(&mut self) -> *const libc::c_void {
190        self.attr.port = self.port as u64;
191        self.attr.allowed_access = self.allowed_access.bits();
192        &self.attr as *const _ as _
193    }
194
195    fn check_consistency(&self, ruleset: &RulesetCreated) -> Result<(), AddRulesError> {
196        // Checks that this rule doesn't contain a superset of the access-rights handled by the
197        // ruleset.  This check is about requested but not ABI-resolved access rights.
198        // Indeed, we want to get a deterministic behavior, i.e. not based on the running kernel
199        // (which is handled by Ruleset and RulesetCreated).
200        if !ruleset.net.access.contains(self.allowed_access) {
201            return Err(AddRuleError::UnhandledAccess {
202                access: self.allowed_access,
203                incompatible: self.allowed_access & !ruleset.net.access,
204            }
205            .into());
206        }
207        if self.quiet && ruleset.net.quiet.is_empty() {
208            return Err(AddRuleError::<AccessNet>::MissingQuietAccess.into());
209        }
210        Ok(())
211    }
212
213    fn set_quiet(&mut self, quiet: bool) {
214        self.quiet = quiet;
215    }
216
217    fn set_quiet_compatibility(&mut self, compatibility: QuietRuleCompatibility) {
218        self.quiet_compatibility = compatibility;
219    }
220
221    fn add_rule_flags(&self) -> u32 {
222        if self.quiet {
223            uapi::LANDLOCK_ADD_RULE_QUIET
224        } else {
225            0
226        }
227    }
228}
229
230#[test]
231fn quiet_net_port_compatibility() {
232    use crate::*;
233
234    let mut state = CompatState::Init;
235    let mut rule = NetPort::new(80, BitFlags::<AccessNet>::EMPTY).quiet(true);
236    rule.set_quiet_compatibility(QuietRuleCompatibility::SupportedEffective);
237    let rule = rule
238        .try_compat(ABI::V10, CompatLevel::BestEffort, &mut state)
239        .unwrap()
240        .unwrap();
241    assert_eq!(rule.add_rule_flags(), uapi::LANDLOCK_ADD_RULE_QUIET);
242    assert_eq!(state, CompatState::Full);
243
244    // Models a future access right unsupported by a kernel that supports quiet rules.
245    let mut state = CompatState::Init;
246    let mut rule = NetPort::new(80, AccessNet::BindUdp).quiet(true);
247    rule.set_quiet_compatibility(QuietRuleCompatibility::SupportedEffective);
248    let rule = rule
249        .try_compat(ABI::V9, CompatLevel::BestEffort, &mut state)
250        .unwrap()
251        .unwrap();
252    assert!(rule.allowed_access.is_empty());
253    assert_eq!(rule.add_rule_flags(), uapi::LANDLOCK_ADD_RULE_QUIET);
254    assert_eq!(state, CompatState::Partial);
255
256    // Quiet support is distinct from whether this ruleset has an effective
257    // quiet mask for the rule category.
258    let mut state = CompatState::Partial;
259    let mut rule = NetPort::new(80, BitFlags::<AccessNet>::EMPTY).quiet(true);
260    rule.set_quiet_compatibility(QuietRuleCompatibility::SupportedIneffective);
261    assert!(rule
262        .try_compat(ABI::V10, CompatLevel::HardRequirement, &mut state)
263        .unwrap()
264        .is_none());
265    assert_eq!(state, CompatState::Partial);
266
267    let mut state = CompatState::Partial;
268    let mut rule = NetPort::new(80, AccessNet::BindTcp).quiet(true);
269    rule.set_quiet_compatibility(QuietRuleCompatibility::SupportedIneffective);
270    let rule = rule
271        .try_compat(ABI::V10, CompatLevel::HardRequirement, &mut state)
272        .unwrap()
273        .unwrap();
274    assert_eq!(rule.add_rule_flags(), 0);
275    assert_eq!(state, CompatState::Partial);
276
277    let mut state = CompatState::Dummy;
278    let mut rule = NetPort::new(80, BitFlags::<AccessNet>::EMPTY).quiet(true);
279    rule.set_quiet_compatibility(QuietRuleCompatibility::SupportedIneffective);
280    assert!(rule
281        .try_compat(ABI::V10, CompatLevel::SoftRequirement, &mut state)
282        .unwrap()
283        .is_none());
284    assert_eq!(state, CompatState::Dummy);
285
286    let mut state = CompatState::Init;
287    let mut rule = NetPort::new(80, BitFlags::<AccessNet>::EMPTY).quiet(true);
288    rule.set_quiet_compatibility(QuietRuleCompatibility::Unsupported);
289    assert!(rule
290        .try_compat(ABI::V9, CompatLevel::SoftRequirement, &mut state)
291        .unwrap()
292        .is_none());
293    assert_eq!(state, CompatState::Dummy);
294
295    let mut state = CompatState::Init;
296    let mut rule = NetPort::new(80, AccessNet::BindTcp).quiet(true);
297    rule.set_quiet_compatibility(QuietRuleCompatibility::Unsupported);
298    let rule = rule
299        .try_compat(ABI::V9, CompatLevel::BestEffort, &mut state)
300        .unwrap()
301        .unwrap();
302    assert_eq!(rule.add_rule_flags(), 0);
303    assert_eq!(state, CompatState::Partial);
304
305    let mut state = CompatState::Init;
306    let mut rule = NetPort::new(80, BitFlags::<AccessNet>::EMPTY).quiet(true);
307    rule.set_quiet_compatibility(QuietRuleCompatibility::Unsupported);
308    assert!(matches!(
309        rule.try_compat(ABI::V9, CompatLevel::HardRequirement, &mut state),
310        Err(CompatError::QuietNotSupported)
311    ));
312    assert_eq!(state, CompatState::Full);
313}
314
315#[test]
316fn net_port_check_consistency() {
317    use crate::*;
318
319    let bind = AccessNet::BindTcp;
320    let bind_connect = bind | AccessNet::ConnectTcp;
321
322    assert!(matches!(
323        Ruleset::from(ABI::Unsupported)
324            .handle_access(bind)
325            .unwrap()
326            .create()
327            .unwrap()
328            .add_rule(NetPort::new(1, bind_connect))
329            .unwrap_err(),
330        RulesetError::AddRules(AddRulesError::Net(AddRuleError::UnhandledAccess { access, incompatible }))
331            if access == bind_connect && incompatible == AccessNet::ConnectTcp
332    ));
333}
334
335impl TryCompat<AccessNet> for NetPort {
336    fn try_compat_children<L>(
337        mut self,
338        abi: ABI,
339        parent_level: L,
340        compat_state: &mut CompatState,
341    ) -> Result<Option<Self>, CompatError<AccessNet>>
342    where
343        L: Into<CompatLevel>,
344    {
345        let level = self.tailored_compat_level(parent_level);
346        let requested_quiet = self.quiet;
347        if self.quiet {
348            let (supported, effective) = match self.quiet_compatibility {
349                QuietRuleCompatibility::Unsupported => (false, false),
350                QuietRuleCompatibility::SupportedIneffective => (true, false),
351                QuietRuleCompatibility::SupportedEffective => (true, true),
352            };
353            self.quiet = try_compat_binary(supported, level, compat_state, || {
354                CompatError::<AccessNet>::QuietNotSupported
355            })?;
356            // Quiet may be supported but have no effect after every quiet
357            // access in this rule category has degraded away.  The ruleset
358            // compatibility state already records that degradation.
359            if self.quiet && !effective {
360                self.quiet = false;
361            }
362        }
363        // Empty allowed access is meaningful only while the rule remains quiet.
364        if requested_quiet && self.allowed_access.is_empty() {
365            return Ok(self.quiet.then_some(self));
366        }
367        // Checks with our own compatibility level, if any.
368        self.allowed_access = match self.allowed_access.try_compat(abi, level, compat_state)? {
369            Some(a) => a,
370            None if self.quiet => BitFlags::EMPTY,
371            None => return Ok(None),
372        };
373        Ok(Some(self))
374    }
375
376    fn try_compat_inner(
377        &mut self,
378        _abi: ABI,
379    ) -> Result<CompatResult<AccessNet>, CompatError<AccessNet>> {
380        Ok(CompatResult::Full)
381    }
382}
383
384impl OptionCompatLevelMut for NetPort {
385    fn as_option_compat_level_mut(&mut self) -> &mut Option<CompatLevel> {
386        &mut self.compat_level
387    }
388}
389
390impl OptionCompatLevelMut for &mut NetPort {
391    fn as_option_compat_level_mut(&mut self) -> &mut Option<CompatLevel> {
392        &mut self.compat_level
393    }
394}
395
396impl Compatible for NetPort {}
397
398impl Compatible for &mut NetPort {}