syd 3.52.0

rock-solid application kernel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
//
// Syd: rock-solid application kernel
// src/landlock_policy.rs: Landlock policy helper library for Syd
//
// Copyright (c) 2025, 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

// SAFETY: This module has been liberated from unsafe code!
#![forbid(unsafe_code)]

use std::{fmt, sync::LazyLock};

use memchr::arch::all::is_equal;
use nix::{
    errno::Errno,
    fcntl::{OFlag, AT_FDCWD},
};
use serde::{ser::SerializeMap, Serialize, Serializer};

use crate::{
    compat::{openat2, OpenHow, ResolveFlag},
    hash::{SydHashMap, SydHashSet, SydIndexMap},
    landlock::{
        Access, AccessFs, AccessNet, CompatLevel, Compatible, CreateRulesetError, Errata, NetPort,
        PathBeneath, PathFd, RestrictSelfFlags, RestrictionStatus, Ruleset, RulesetAttr,
        RulesetCreatedAttr, RulesetError, Scope, ABI,
    },
    parsers::sandbox::{str2u32, LandlockCmd, LandlockOp, LandlockRule, PathSet},
    path::{XPath, XPathBuf},
    port::PortSet,
    retry::retry_on_eintr,
    sandbox::Sandbox,
};

/// landlock(7) filesystem access rights.
pub static LANDLOCK_ACCESS_FS: LazyLock<SydIndexMap<&str, AccessFs>> = LazyLock::new(|| {
    SydIndexMap::from_iter([
        ("read", AccessFs::ReadFile),
        ("write", AccessFs::WriteFile),
        ("exec", AccessFs::Execute),
        ("ioctl", AccessFs::IoctlDev),
        ("create", AccessFs::MakeReg),
        ("delete", AccessFs::RemoveFile),
        ("rename", AccessFs::Refer),
        ("symlink", AccessFs::MakeSym),
        ("truncate", AccessFs::Truncate),
        ("readdir", AccessFs::ReadDir),
        ("mkdir", AccessFs::MakeDir),
        ("rmdir", AccessFs::RemoveDir),
        ("mkbdev", AccessFs::MakeBlock),
        ("mkcdev", AccessFs::MakeChar),
        ("mkfifo", AccessFs::MakeFifo),
        ("bind", AccessFs::MakeSock),
        // Aliases
        ("all", LandlockPolicy::access_fs_from_set("all")),
        ("all-x", LandlockPolicy::access_fs_from_set("all-x")),
        ("rpath", LandlockPolicy::access_fs_from_set("rpath")),
        ("wpath", LandlockPolicy::access_fs_from_set("wpath")),
        ("cpath", LandlockPolicy::access_fs_from_set("cpath")),
        ("dpath", LandlockPolicy::access_fs_from_set("dpath")),
        ("spath", LandlockPolicy::access_fs_from_set("spath")),
        ("tpath", LandlockPolicy::access_fs_from_set("tpath")),
        ("bnet", LandlockPolicy::access_fs_from_set("bnet")),
    ])
});

/// landlock(7) network access rights.
pub static LANDLOCK_ACCESS_NET: LazyLock<SydIndexMap<&str, AccessNet>> = LazyLock::new(|| {
    SydIndexMap::from_iter([
        ("bind", AccessNet::BindTcp),
        ("connect", AccessNet::ConnectTcp),
        // Aliases
        ("net", LandlockPolicy::access_net_from_set("net")),
        ("inet", LandlockPolicy::access_net_from_set("inet")),
        ("bnet", LandlockPolicy::access_net_from_set("bnet")),
        ("cnet", LandlockPolicy::access_net_from_set("cnet")),
    ])
});

/// Data structure to store the landlock security policy.
#[derive(Clone, Debug, Default)]
pub struct LandlockPolicy {
    /// Set compatibility level to handle unsupported features
    ///
    /// Defaults to `CompatLevel::BestEffort`.
    pub compat_level: Option<CompatLevel>,
    /// Landlock read pathset
    pub read_pathset: Option<PathSet>,
    /// Landlock write pathset
    pub write_pathset: Option<PathSet>,
    /// Landlock execute pathset
    pub exec_pathset: Option<PathSet>,
    /// Landlock ioctl(2) pathset
    pub ioctl_pathset: Option<PathSet>,
    /// Landlock create pathset
    pub create_pathset: Option<PathSet>,
    /// Landlock delete pathset
    pub delete_pathset: Option<PathSet>,
    /// Landlock rename pathset
    pub rename_pathset: Option<PathSet>,
    /// Landlock symlink pathset
    pub symlink_pathset: Option<PathSet>,
    /// Landlock truncate pathset
    pub truncate_pathset: Option<PathSet>,
    /// Landlock readdir pathset
    pub readdir_pathset: Option<PathSet>,
    /// Landlock mkdir pathset
    pub mkdir_pathset: Option<PathSet>,
    /// Landlock rmdir pathset
    pub rmdir_pathset: Option<PathSet>,
    /// Landlock mkbdev pathset
    pub mkbdev_pathset: Option<PathSet>,
    /// Landlock mkcdev pathset
    pub mkcdev_pathset: Option<PathSet>,
    /// Landlock mkfifo pathset
    pub mkfifo_pathset: Option<PathSet>,
    /// Landlock make socket pathset
    pub bind_pathset: Option<PathSet>,
    /// Landlock bind portset
    pub bind_portset: Option<PortSet>,
    /// Landlock connect portset
    pub conn_portset: Option<PortSet>,
    /// Scoped abstract UNIX sockets
    pub scoped_abs: bool,
    /// Scoped UNIX signals
    pub scoped_sig: bool,
    /// Flags for landlock_restrict_self(2)
    pub restrict_self_flags: RestrictSelfFlags,
}

impl LandlockPolicy {
    /// Add or remove landlock(7) rules
    ///
    /// If `sandbox` is given, performs hex decoding,
    /// and environment variable parsing for filesystem rules.
    pub fn edit(&mut self, cmd: LandlockCmd, sandbox: Option<&Sandbox>) -> Result<(), Errno> {
        for rule in cmd.filter {
            match rule {
                LandlockRule::Fs((access_fs, pat)) => {
                    let pat = if let Some(sandbox) = sandbox {
                        // We do not decode hex because:
                        // 1. Mixing hex use with port ranges is confusing.
                        // 2. bind, aka BindTcp+MakeSock, requires absolute paths.
                        sandbox.expand_env(&pat)?
                    } else {
                        pat.into()
                    };
                    let pat = XPath::from_bytes(pat.as_bytes());

                    if cmd.op == LandlockOp::Add {
                        // Add landlock(7) filesystem rule.
                        self.rule_add_fs(access_fs, pat)?;
                    } else {
                        // Remove all matching landlock(7) filesystem rules.
                        //
                        // SAFETY: Prevent removing `/proc` for the following access rights:
                        // - ReadFile
                        // - ReadDir
                        if sandbox.is_some()
                            && access_fs.intersects(AccessFs::ReadFile | AccessFs::ReadDir)
                            && pat.is_equal(b"/proc")
                        {
                            return Err(Errno::EACCES);
                        }

                        // SAFETY: Prevent removing `/dev/null` from access rights:
                        // - ReadFile
                        // - WriteFile
                        // - Truncate
                        if sandbox.is_some()
                            && access_fs.intersects(
                                AccessFs::ReadFile | AccessFs::WriteFile | AccessFs::Truncate,
                            )
                            && pat.is_equal(b"/dev/null")
                        {
                            return Err(Errno::EACCES);
                        }

                        // All checks passed, remove rule.
                        self.rule_del_fs(access_fs, pat)?;
                    }
                }
                LandlockRule::Net((access_net, ref ports)) => {
                    if cmd.op == LandlockOp::Add {
                        // Add landlock(7) network rule.
                        self.rule_add_net(access_net, ports)?;
                    } else {
                        // Remove all matching landlock(7) network rules.
                        self.rule_del_net(access_net, ports)?;
                    }
                }
            }
        }

        Ok(())
    }

    /// Add landlock(7) filesystem rules.
    pub fn rule_add_fs(&mut self, access: AccessFs, pat: &XPath) -> Result<(), Errno> {
        if access.is_empty() {
            return Err(Errno::EINVAL);
        }

        for access in access.iter() {
            let set = self.get_pathset_mut(access);
            if let Some(ref mut set) = set {
                set.insert(pat.to_owned());
            } else {
                let mut new_set = SydHashSet::default();
                new_set.insert(pat.to_owned());
                *set = Some(new_set);
            }
        }

        Ok(())
    }

    /// Remove all matching landlock(7) filesystem rules.
    pub fn rule_del_fs(&mut self, access: AccessFs, pat: &XPath) -> Result<(), Errno> {
        if access.is_empty() {
            return Err(Errno::EINVAL);
        }

        for access in access.iter() {
            let set = self.get_pathset_mut(access);
            if let Some(ref mut set_ref) = set {
                set_ref.remove(pat);
                if set_ref.is_empty() {
                    *set = None;
                }
            }
        }

        Ok(())
    }

    /// Add landlock(7) network rules.
    pub fn rule_add_net(&mut self, access: AccessNet, ports: &PortSet) -> Result<(), Errno> {
        if access.is_empty() {
            return Err(Errno::EINVAL);
        }

        for access in access.iter() {
            let set = self.get_portset_mut(access);
            if let Some(ref mut set_ref) = set {
                set_ref.union_with(ports);
            } else {
                *set = Some(ports.clone());
            }
        }

        Ok(())
    }

    /// Remove all matching landlock(7) network rules.
    pub fn rule_del_net(&mut self, access: AccessNet, ports: &PortSet) -> Result<(), Errno> {
        if access.is_empty() {
            return Err(Errno::EINVAL);
        }

        for access in access.iter() {
            let set = self.get_portset_mut(access);
            if let Some(ref mut set_ref) = set {
                set_ref.difference_with(ports);
                if set_ref.is_clear() {
                    *set = None;
                }
            }
        }

        Ok(())
    }

    /// Parse landlock(7) erratas.
    ///
    /// Flag may be a name or number.
    /// Multiple erratas may be given separated by commas.
    pub fn parse_errata(errata: &[u8]) -> Result<Errata, Errno> {
        let mut e = Errata::empty();
        for fix in errata.split(|b| *b == b',') {
            // Parse as numeric.
            if let Ok(flag) = str2u32(fix).map(Errata::from_bits_retain) {
                e.insert(flag);
                continue;
            }

            // Parse as name.
            if is_equal(fix, b"tcp_socket_identification") {
                e.insert(Errata::TCP_SOCKET_IDENTIFICATION);
            } else if is_equal(fix, b"scoped_signal_same_tgid") {
                e.insert(Errata::SCOPED_SIGNAL_SAME_TGID);
            } else {
                return Err(Errno::EINVAL);
            }
        }

        if !e.is_empty() {
            Ok(e)
        } else {
            Err(Errno::EINVAL)
        }
    }

    /// Parse landlock_restrict_self(2) flags.
    ///
    /// New in ABI 7, older ABIs are NO-OP.
    /// Flag must be a name unless `numeric` when numeric values are permitted too.
    /// Multiple flags may be given separated by commas.
    pub fn parse_restrict_self_flags(
        flags: &[u8],
        numeric: bool,
    ) -> Result<RestrictSelfFlags, Errno> {
        let mut f = RestrictSelfFlags::empty();
        for flag in flags.split(|b| *b == b',') {
            // Parse as number if numeric is set.
            if numeric {
                if let Ok(flag) =
                    str2u32(flag).and_then(|f| RestrictSelfFlags::from_bits(f).ok_or(Errno::EINVAL))
                {
                    f.insert(flag);
                    continue;
                }
            }

            // Parse as name, permit both syd(2) and syd-lock(1) naming.
            const LOG_SAME_EXEC_OFF_NAMES: &[&[u8]] = &[b"same_exec_off", b"log_same_exec_off"];
            const LOG_NEW_EXEC_ON_NAMES: &[&[u8]] = &[b"new_exec_on", b"log_new_exec_on"];
            const LOG_SUBDOMAINS_OFF_NAMES: &[&[u8]] = &[b"subdomains_off", b"log_subdomains_off"];
            if LOG_SAME_EXEC_OFF_NAMES.iter().any(|f| is_equal(flag, f)) {
                f.insert(RestrictSelfFlags::LOG_SAME_EXEC_OFF);
            } else if LOG_NEW_EXEC_ON_NAMES.iter().any(|f| is_equal(flag, f)) {
                f.insert(RestrictSelfFlags::LOG_NEW_EXEC_ON);
            } else if LOG_SUBDOMAINS_OFF_NAMES.iter().any(|f| is_equal(flag, f)) {
                f.insert(RestrictSelfFlags::LOG_SUBDOMAINS_OFF);
            } else {
                return Err(Errno::EINVAL);
            }
        }

        if !f.is_empty() {
            Ok(f)
        } else {
            Err(Errno::EINVAL)
        }
    }

    /// Parse Landlock filesystem and network access rights
    /// from the given comma-delimited string of access rights.
    pub fn access(access_str: &str) -> Result<(AccessFs, AccessNet), Errno> {
        let mut access_fs = AccessFs::EMPTY;
        let mut access_net = AccessNet::EMPTY;

        for access in access_str.split(',') {
            let my_access_fs = LANDLOCK_ACCESS_FS
                .get(access)
                .copied()
                .unwrap_or(AccessFs::EMPTY);
            let my_access_net = LANDLOCK_ACCESS_NET
                .get(access)
                .copied()
                .unwrap_or(AccessNet::EMPTY);

            if my_access_fs.is_empty() && my_access_net.is_empty() {
                return Err(Errno::EINVAL);
            }

            access_fs |= my_access_fs;
            access_net |= my_access_net;
        }

        Ok((access_fs, access_net))
    }

    /// Convert the given alias into a set of filesystem access rights.
    ///
    /// Panics on invalid alias.
    pub fn access_fs_from_set(set: &str) -> AccessFs {
        let s = set.as_bytes();
        if is_equal(s, b"all") {
            AccessFs::all()
        } else if is_equal(s, b"all-x") {
            AccessFs::all() & !AccessFs::Execute
        } else if is_equal(s, b"rpath") {
            AccessFs::ReadFile | AccessFs::ReadDir
        } else if is_equal(s, b"wpath") {
            AccessFs::WriteFile | AccessFs::Truncate
        } else if is_equal(s, b"cpath") {
            AccessFs::MakeReg | AccessFs::RemoveFile | AccessFs::Refer
        } else if is_equal(s, b"dpath") {
            AccessFs::MakeBlock | AccessFs::MakeChar
        } else if is_equal(s, b"spath") {
            AccessFs::MakeFifo | AccessFs::MakeSym
        } else if is_equal(s, b"tpath") {
            AccessFs::MakeDir | AccessFs::RemoveDir
        } else if is_equal(s, b"bnet") {
            AccessFs::MakeSock
        } else {
            unreachable!("BUG: Invalid landlock(7) filesystem access right {set}, report a bug!");
        }
    }

    /// Convert the given alias into a set of network access rights.
    ///
    /// Panics on invalid alias.
    pub fn access_net_from_set(set: &str) -> AccessNet {
        let s = set.as_bytes();
        if is_equal(s, b"all") {
            AccessNet::all()
        } else if is_equal(s, b"bnet") {
            AccessNet::BindTcp
        } else if is_equal(s, b"cnet") {
            AccessNet::ConnectTcp
        } else if is_equal(s, b"net") || is_equal(s, b"inet") {
            AccessNet::BindTcp | AccessNet::ConnectTcp
        } else {
            unreachable!("BUG: Invalid landlock(7) network access right {set}, report a bug!");
        }
    }

    /// A helper function to wrap the operations and reduce duplication.
    #[expect(clippy::cognitive_complexity)]
    pub fn restrict_self(&self, abi: ABI) -> Result<RestrictionStatus, RulesetError> {
        // from_all includes IoctlDev of ABI >= 5 as necessary.
        let mut ruleset = Ruleset::default().handle_access(AccessFs::from_all(abi))?;
        let ruleset_ref = &mut ruleset;

        // Set compatibility level as necessary.
        // For `None` case, use landlock crate default
        // which is `CompatLevel::BestEffort`.
        let level = if let Some(compat_level) = self.compat_level {
            ruleset_ref.set_compatibility(compat_level);
            compat_level
        } else {
            CompatLevel::BestEffort
        };

        // Network is ABI >= 4.
        let mut network_rules_bind = PortSet::empty();
        let mut network_rules_conn = PortSet::empty();
        if abi >= ABI::V4 {
            if let Some(ref port_set) = self.bind_portset {
                network_rules_bind = port_set.clone();
            }

            // We handle BindTcp even if no ports are allowed here,
            // for a default-deny policy.
            if network_rules_bind.is_full() {
                // All ports are allowed, do not handle the access right,
                // rather than allowing each and every port.
                network_rules_bind.clear();
            } else {
                ruleset_ref.handle_access(AccessNet::BindTcp)?;
            }

            if let Some(ref port_set) = self.conn_portset {
                network_rules_conn = port_set.clone();
            }

            // We handle ConnectTcp even if no ports are allowed here,
            // for a default-deny policy.
            if network_rules_conn.is_full() {
                // All ports are allowed, do not handle the access right,
                // rather than allowing each and every port.
                network_rules_conn.clear();
            } else {
                ruleset_ref.handle_access(AccessNet::ConnectTcp)?;
            }
        }

        // Scopes are ABI >= 6.
        if abi >= ABI::V6 {
            if self.scoped_abs {
                ruleset_ref.scope(Scope::AbstractUnixSocket)?;
            }
            if self.scoped_sig {
                ruleset_ref.scope(Scope::Signal)?;
            }
        }

        // Merge path rules based on access rights.
        //
        // Step 1: Accumulate all paths in a single set.
        let mut all_pathset: SydHashSet<XPathBuf> = SydHashSet::default();
        if let Some(ref pathset) = self.read_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.write_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.exec_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.ioctl_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.create_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.delete_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.rename_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.symlink_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.truncate_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.readdir_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.mkdir_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.rmdir_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.mkbdev_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.mkcdev_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.mkfifo_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }
        if let Some(ref pathset) = self.bind_pathset {
            all_pathset.extend(pathset.iter().cloned());
        }

        // Step 2: Accumulate access rights using the `all_pathset`.
        let mut acl: SydHashMap<AccessFs, Vec<XPathBuf>> = SydHashMap::default();
        for path in all_pathset {
            let mut access = AccessFs::EMPTY;

            if self
                .read_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::ReadFile;
            }
            if self
                .write_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::WriteFile;
            }
            if self
                .exec_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::Execute;
            }
            // IoctlDev is ABI >= 5.
            if abi >= ABI::V5
                && self
                    .ioctl_pathset
                    .as_ref()
                    .map(|set| set.contains(&path))
                    .unwrap_or(false)
            {
                access |= AccessFs::IoctlDev;
            }
            if self
                .create_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::MakeReg;
            }
            if self
                .delete_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::RemoveFile;
            }
            // Refer is ABI >= 2.
            if abi >= ABI::V2
                && self
                    .rename_pathset
                    .as_ref()
                    .map(|set| set.contains(&path))
                    .unwrap_or(false)
            {
                access |= AccessFs::Refer;
            }
            if self
                .symlink_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::MakeSym;
            }
            // Truncate is ABI >= 3.
            if abi >= ABI::V3
                && self
                    .truncate_pathset
                    .as_ref()
                    .map(|set| set.contains(&path))
                    .unwrap_or(false)
            {
                access |= AccessFs::Truncate;
            }
            if self
                .readdir_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::ReadDir;
            }
            if self
                .mkdir_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::MakeDir;
            }
            if self
                .rmdir_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::RemoveDir;
            }
            if self
                .mkbdev_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::MakeBlock;
            }
            if self
                .mkcdev_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::MakeChar;
            }
            if self
                .mkfifo_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::MakeFifo;
            }
            if self
                .bind_pathset
                .as_ref()
                .map(|set| set.contains(&path))
                .unwrap_or(false)
            {
                access |= AccessFs::MakeSock;
            }

            if access.is_empty() {
                continue;
            }

            acl.entry(access).or_default().push(path);
        }

        // Step 3: Create ruleset and enter (access, path-set) pairs.
        let mut ruleset = ruleset.create()?;
        for (access, paths) in &acl {
            ruleset = ruleset.add_rules(landlock_path_beneath_rules(level, paths, *access))?;
        }

        #[expect(clippy::cast_possible_truncation)]
        ruleset
            .add_rules(network_rules_bind.ones().map(|port| {
                Ok::<NetPort, RulesetError>(NetPort::new(port as u16, AccessNet::BindTcp))
            }))?
            .add_rules(network_rules_conn.ones().map(|port| {
                Ok::<NetPort, RulesetError>(NetPort::new(port as u16, AccessNet::ConnectTcp))
            }))?
            .restrict_self(self.restrict_self_flags)
    }

    #[inline]
    fn get_pathset_mut(&mut self, access: AccessFs) -> &mut Option<PathSet> {
        match access {
            AccessFs::ReadFile => &mut self.read_pathset,
            AccessFs::WriteFile => &mut self.write_pathset,
            AccessFs::Execute => &mut self.exec_pathset,
            AccessFs::IoctlDev => &mut self.ioctl_pathset,
            AccessFs::MakeReg => &mut self.create_pathset,
            AccessFs::RemoveFile => &mut self.delete_pathset,
            AccessFs::Refer => &mut self.rename_pathset,
            AccessFs::MakeSym => &mut self.symlink_pathset,
            AccessFs::Truncate => &mut self.truncate_pathset,
            AccessFs::ReadDir => &mut self.readdir_pathset,
            AccessFs::MakeDir => &mut self.mkdir_pathset,
            AccessFs::RemoveDir => &mut self.rmdir_pathset,
            AccessFs::MakeBlock => &mut self.mkbdev_pathset,
            AccessFs::MakeChar => &mut self.mkcdev_pathset,
            AccessFs::MakeFifo => &mut self.mkfifo_pathset,
            AccessFs::MakeSock => &mut self.bind_pathset,
            _ => unreachable!("BUG: unhandled Landlock filesystem access right {access:?}!"),
        }
    }

    #[inline]
    fn get_portset_mut(&mut self, access: AccessNet) -> &mut Option<PortSet> {
        match access {
            AccessNet::BindTcp => &mut self.bind_portset,
            AccessNet::ConnectTcp => &mut self.conn_portset,
            _ => unreachable!("BUG: unhandled Landlock network access right {access:?}!"),
        }
    }
}

impl fmt::Display for LandlockPolicy {
    #[expect(clippy::cognitive_complexity)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "  Landlock Policy:")?;

        let level = self.compat_level.unwrap_or(CompatLevel::BestEffort);
        writeln!(f, "    Compat Level: {level:?}")?;

        writeln!(f, "    Scoped Abstract Unix Sockets: {}", self.scoped_abs)?;
        writeln!(f, "    Scoped Signals: {}", self.scoped_sig)?;
        writeln!(f, "    Restrict Self Flags: {:?}", self.restrict_self_flags)?;

        macro_rules! fmt_pathset {
            ($field:ident, $name:expr) => {
                if let Some(ref set) = self.$field {
                    if !set.is_empty() {
                        let mut paths: Vec<_> = set.iter().collect();
                        paths.sort();
                        writeln!(f, "    {}: {paths:?}", $name)?;
                    }
                }
            };
        }

        macro_rules! fmt_portset {
            ($field:ident, $name:expr) => {
                if let Some(ref set) = self.$field {
                    if set.count_ones(..) > 0 {
                        let mut ports: Vec<_> = set.ones().collect();
                        ports.sort();
                        writeln!(f, "    {}: {ports:?}", $name)?;
                    }
                }
            };
        }

        fmt_pathset!(read_pathset, "Read Pathset");
        fmt_pathset!(write_pathset, "Write Pathset");
        fmt_pathset!(exec_pathset, "Exec Pathset");
        fmt_pathset!(ioctl_pathset, "Ioctl Pathset");
        fmt_pathset!(create_pathset, "Create Pathset");
        fmt_pathset!(delete_pathset, "Delete Pathset");
        fmt_pathset!(rename_pathset, "Rename Pathset");
        fmt_pathset!(symlink_pathset, "Symlink Pathset");
        fmt_pathset!(truncate_pathset, "Truncate Pathset");
        fmt_pathset!(readdir_pathset, "Readdir Pathset");
        fmt_pathset!(mkdir_pathset, "Mkdir Pathset");
        fmt_pathset!(rmdir_pathset, "Rmdir Pathset");
        fmt_pathset!(mkbdev_pathset, "Mkbdev Pathset");
        fmt_pathset!(mkcdev_pathset, "Mkcdev Pathset");
        fmt_pathset!(mkfifo_pathset, "Mkfifo Pathset");
        fmt_pathset!(bind_pathset, "Bind Pathset");
        fmt_portset!(bind_portset, "  Bind Portset");
        fmt_portset!(conn_portset, "  Connect Portset");

        Ok(())
    }
}

impl Serialize for LandlockPolicy {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(None)?;

        let level = match self.compat_level.unwrap_or(CompatLevel::BestEffort) {
            CompatLevel::BestEffort => "best-effort",
            CompatLevel::SoftRequirement => "soft-requirement",
            CompatLevel::HardRequirement => "hard-requirement",
        };
        map.serialize_entry("compat_level", level)?;

        map.serialize_entry("scoped_abs", &self.scoped_abs)?;
        map.serialize_entry("scoped_sig", &self.scoped_sig)?;

        let mut flags = Vec::new();
        if self
            .restrict_self_flags
            .contains(RestrictSelfFlags::LOG_SAME_EXEC_OFF)
        {
            flags.push("log-same-exec-off");
        }
        if self
            .restrict_self_flags
            .contains(RestrictSelfFlags::LOG_NEW_EXEC_ON)
        {
            flags.push("log-new-exec-on");
        }
        if self
            .restrict_self_flags
            .contains(RestrictSelfFlags::LOG_SUBDOMAINS_OFF)
        {
            flags.push("log-subdomains-off");
        }
        map.serialize_entry("restrict_self_flags", &flags)?;

        let mut ser_pathset = |name: &str, set: &Option<PathSet>| -> Result<(), S::Error> {
            if let Some(ref set) = set {
                if !set.is_empty() {
                    let mut paths: Vec<_> = set.iter().map(|p| p.to_string()).collect();
                    paths.sort();
                    map.serialize_entry(name, &paths)?;
                }
            }
            Ok(())
        };

        ser_pathset("read_pathset", &self.read_pathset)?;
        ser_pathset("write_pathset", &self.write_pathset)?;
        ser_pathset("exec_pathset", &self.exec_pathset)?;
        ser_pathset("ioctl_pathset", &self.ioctl_pathset)?;
        ser_pathset("create_pathset", &self.create_pathset)?;
        ser_pathset("delete_pathset", &self.delete_pathset)?;
        ser_pathset("rename_pathset", &self.rename_pathset)?;
        ser_pathset("symlink_pathset", &self.symlink_pathset)?;
        ser_pathset("truncate_pathset", &self.truncate_pathset)?;
        ser_pathset("readdir_pathset", &self.readdir_pathset)?;
        ser_pathset("mkdir_pathset", &self.mkdir_pathset)?;
        ser_pathset("rmdir_pathset", &self.rmdir_pathset)?;
        ser_pathset("mkbdev_pathset", &self.mkbdev_pathset)?;
        ser_pathset("mkcdev_pathset", &self.mkcdev_pathset)?;
        ser_pathset("mkfifo_pathset", &self.mkfifo_pathset)?;
        ser_pathset("bind_pathset", &self.bind_pathset)?;

        if let Some(ref set) = self.bind_portset {
            if !set.is_clear() {
                map.serialize_entry("bind_portset", set)?;
            }
        }
        if let Some(ref set) = self.conn_portset {
            if !set.is_clear() {
                map.serialize_entry("conn_portset", set)?;
            }
        }

        map.end()
    }
}

// syd::landlock::path_beneath_rules tailored for Syd use-case.
#[expect(clippy::cognitive_complexity)]
#[expect(clippy::disallowed_methods)]
pub(crate) fn landlock_path_beneath_rules<I, P>(
    level: CompatLevel,
    paths: I,
    access: AccessFs,
) -> impl Iterator<Item = Result<PathBeneath<PathFd>, RulesetError>>
where
    I: IntoIterator<Item = P>,
    P: AsRef<XPath>,
{
    let compat_level = match level {
        CompatLevel::HardRequirement => "hard-requirement",
        CompatLevel::SoftRequirement => "soft-requirement",
        CompatLevel::BestEffort => "best-effort",
    };

    paths.into_iter().filter_map(move |p| {
        let p = p.as_ref();
        if p.has_parent_dot() {
            crate::error!("ctx": "init", "op": "landlock_create_ruleset",
                "path": p, "access": access,
                "cmp": compat_level, "err": Errno::EACCES as i32,
                "msg": format!("open path `{p}' for Landlock failed due to dotdot"),
                "tip": "avoid using `..' components in Landlock rules");
            return Some(Err(RulesetError::CreateRuleset(
                CreateRulesetError::CreateRulesetCall {
                    source: Errno::EACCES.into(),
                },
            )));
        }
        let how = OpenHow::new()
            .flags(OFlag::O_PATH | OFlag::O_CLOEXEC)
            .resolve(ResolveFlag::RESOLVE_NO_MAGICLINKS);
        match retry_on_eintr(|| openat2(AT_FDCWD, p, how)) {
            Ok(fd) => Some(Ok(PathBeneath::new(PathFd { fd }, access))),
            Err(errno @ Errno::ENOENT) if level == CompatLevel::BestEffort => {
                crate::info!("ctx": "init", "op": "landlock_create_ruleset",
                    "path": p, "access": access,
                    "cmp": compat_level, "err": errno as i32,
                    "msg": format!("open path `{p}' for Landlock failed: {errno}"));
                None
            }
            Err(errno) => {
                let tip = if errno == Errno::ENOENT {
                    "use parent dir or set `default/lock:warn' to ignore file-not-found errors for Landlock"
                } else if errno == Errno::ELOOP {
                    "avoid using magiclinks in Landlock rules"
                } else {
                    "avoid using inaccessible paths in Landlock rules"
                };
                crate::error!("ctx": "init", "op": "landlock_create_ruleset",
                    "path": p, "access": access,
                    "cmp": compat_level, "err": errno as i32,
                    "msg": format!("open path `{p}' for Landlock failed: {errno}"),
                    "tip": tip);
                Some(Err(RulesetError::CreateRuleset(
                    CreateRulesetError::CreateRulesetCall {
                        source: errno.into(),
                    },
                )))
            }
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_errata_1() {
        let e = LandlockPolicy::parse_errata(b"tcp_socket_identification").unwrap();
        assert!(e.contains(Errata::TCP_SOCKET_IDENTIFICATION));
    }

    #[test]
    fn test_parse_errata_2() {
        let e = LandlockPolicy::parse_errata(b"scoped_signal_same_tgid").unwrap();
        assert!(e.contains(Errata::SCOPED_SIGNAL_SAME_TGID));
    }

    #[test]
    fn test_parse_errata_3() {
        let e = LandlockPolicy::parse_errata(b"tcp_socket_identification,scoped_signal_same_tgid")
            .unwrap();
        assert!(e.contains(Errata::TCP_SOCKET_IDENTIFICATION));
        assert!(e.contains(Errata::SCOPED_SIGNAL_SAME_TGID));
    }

    #[test]
    fn test_parse_errata_4() {
        let result = LandlockPolicy::parse_errata(b"invalid_errata");
        assert_eq!(result, Err(Errno::EINVAL));
    }

    #[test]
    fn test_parse_errata_5() {
        let result = LandlockPolicy::parse_errata(b"");
        assert_eq!(result, Err(Errno::EINVAL));
    }

    #[test]
    fn test_parse_errata_6() {
        let e = LandlockPolicy::parse_errata(b"1").unwrap();
        assert_eq!(e.bits(), 1);
    }

    #[test]
    fn test_parse_restrict_self_flags_1() {
        let f = LandlockPolicy::parse_restrict_self_flags(b"same_exec_off", false).unwrap();
        assert!(f.contains(RestrictSelfFlags::LOG_SAME_EXEC_OFF));
    }

    #[test]
    fn test_parse_restrict_self_flags_2() {
        let f = LandlockPolicy::parse_restrict_self_flags(b"log_same_exec_off", false).unwrap();
        assert!(f.contains(RestrictSelfFlags::LOG_SAME_EXEC_OFF));
    }

    #[test]
    fn test_parse_restrict_self_flags_3() {
        let f = LandlockPolicy::parse_restrict_self_flags(b"new_exec_on", false).unwrap();
        assert!(f.contains(RestrictSelfFlags::LOG_NEW_EXEC_ON));
    }

    #[test]
    fn test_parse_restrict_self_flags_4() {
        let f = LandlockPolicy::parse_restrict_self_flags(b"subdomains_off", false).unwrap();
        assert!(f.contains(RestrictSelfFlags::LOG_SUBDOMAINS_OFF));
    }

    #[test]
    fn test_parse_restrict_self_flags_5() {
        let result = LandlockPolicy::parse_restrict_self_flags(b"invalid", false);
        assert_eq!(result, Err(Errno::EINVAL));
    }

    #[test]
    fn test_parse_restrict_self_flags_6() {
        let result = LandlockPolicy::parse_restrict_self_flags(b"", false);
        assert_eq!(result, Err(Errno::EINVAL));
    }

    #[test]
    fn test_parse_restrict_self_flags_7() {
        let f =
            LandlockPolicy::parse_restrict_self_flags(b"same_exec_off,new_exec_on", false).unwrap();
        assert!(f.contains(RestrictSelfFlags::LOG_SAME_EXEC_OFF));
        assert!(f.contains(RestrictSelfFlags::LOG_NEW_EXEC_ON));
    }

    #[test]
    fn test_access_1() {
        let (fs, net) = LandlockPolicy::access("exec").unwrap();
        assert!(fs.contains(AccessFs::Execute));
        assert!(net.is_empty());
    }

    #[test]
    fn test_access_2() {
        let (fs, net) = LandlockPolicy::access("bind").unwrap();
        assert!(fs.contains(AccessFs::MakeSock));
        assert!(net.contains(AccessNet::BindTcp));
    }

    #[test]
    fn test_access_3() {
        let (_, net) = LandlockPolicy::access("connect").unwrap();
        assert!(net.contains(AccessNet::ConnectTcp));
    }

    #[test]
    fn test_access_4() {
        let result = LandlockPolicy::access("nonexistent_right");
        assert_eq!(result, Err(Errno::EINVAL));
    }

    #[test]
    fn test_access_5() {
        let (fs, _) = LandlockPolicy::access("read,write").unwrap();
        assert!(fs.contains(AccessFs::ReadFile));
        assert!(fs.contains(AccessFs::WriteFile));
    }

    #[test]
    fn test_access_fs_from_set_1() {
        let fs = LandlockPolicy::access_fs_from_set("all");
        assert_eq!(fs, AccessFs::all());
    }

    #[test]
    fn test_access_fs_from_set_2() {
        let fs = LandlockPolicy::access_fs_from_set("rpath");
        assert!(fs.contains(AccessFs::ReadFile));
        assert!(fs.contains(AccessFs::ReadDir));
    }

    #[test]
    fn test_access_fs_from_set_3() {
        let fs = LandlockPolicy::access_fs_from_set("wpath");
        assert!(fs.contains(AccessFs::WriteFile));
        assert!(fs.contains(AccessFs::Truncate));
    }

    #[test]
    fn test_access_fs_from_set_4() {
        let fs = LandlockPolicy::access_fs_from_set("cpath");
        assert!(fs.contains(AccessFs::MakeReg));
        assert!(fs.contains(AccessFs::RemoveFile));
        assert!(fs.contains(AccessFs::Refer));
    }

    #[test]
    fn test_access_fs_from_set_5() {
        let fs = LandlockPolicy::access_fs_from_set("dpath");
        assert!(fs.contains(AccessFs::MakeBlock));
        assert!(fs.contains(AccessFs::MakeChar));
    }

    #[test]
    fn test_access_fs_from_set_6() {
        let fs = LandlockPolicy::access_fs_from_set("spath");
        assert!(fs.contains(AccessFs::MakeFifo));
        assert!(fs.contains(AccessFs::MakeSym));
    }

    #[test]
    fn test_access_fs_from_set_7() {
        let fs = LandlockPolicy::access_fs_from_set("tpath");
        assert!(fs.contains(AccessFs::MakeDir));
        assert!(fs.contains(AccessFs::RemoveDir));
    }

    #[test]
    fn test_access_fs_from_set_8() {
        let fs = LandlockPolicy::access_fs_from_set("bnet");
        assert!(fs.contains(AccessFs::MakeSock));
    }

    #[test]
    fn test_access_fs_from_set_9() {
        let fs = LandlockPolicy::access_fs_from_set("all-x");
        assert!(!fs.contains(AccessFs::Execute));
    }

    #[test]
    fn test_access_net_from_set_1() {
        let net = LandlockPolicy::access_net_from_set("all");
        assert_eq!(net, AccessNet::all());
    }

    #[test]
    fn test_access_net_from_set_2() {
        let net = LandlockPolicy::access_net_from_set("bnet");
        assert_eq!(net, AccessNet::BindTcp);
    }

    #[test]
    fn test_access_net_from_set_3() {
        let net = LandlockPolicy::access_net_from_set("cnet");
        assert_eq!(net, AccessNet::ConnectTcp);
    }

    #[test]
    fn test_access_net_from_set_4() {
        let net = LandlockPolicy::access_net_from_set("net");
        assert!(net.contains(AccessNet::BindTcp));
        assert!(net.contains(AccessNet::ConnectTcp));
    }

    #[test]
    fn test_access_net_from_set_5() {
        let net = LandlockPolicy::access_net_from_set("inet");
        assert!(net.contains(AccessNet::BindTcp));
        assert!(net.contains(AccessNet::ConnectTcp));
    }
}