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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
//
// Syd: rock-solid application kernel
// src/kernel/open.rs: creat(2), open(2), openat(2), and openat2(2) handlers
//
// Copyright (c) 2023, 2024, 2025, 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

use std::{
    borrow::Cow,
    env,
    ffi::CStr,
    io::{BufWriter, Seek, Write},
    os::{
        fd::{AsRawFd, IntoRawFd, RawFd},
        unix::ffi::OsStrExt,
    },
};

use libseccomp::ScmpNotifResp;
use nix::{
    errno::Errno,
    fcntl::OFlag,
    sys::stat::Mode,
    unistd::{Pid, Uid},
    NixPath,
};

use crate::{
    compat::{fstatx, FsType, OpenHow, ResolveFlag, O_LARGEFILE, STATX_MODE, STATX_UID},
    config::{
        ENV_ID, ESYD_SH, MAGIC_PREFIX, PINK_FLOYD, SAFE_MFD_FLAGS, SEE_EMILY_PLAY, SYD_EL,
        THE_PIPER,
    },
    confine::EIDRM,
    cookie::{safe_ftruncate64, safe_memfd_create, safe_openat2, safe_umask, safe_uname},
    debug,
    err::err2no,
    error,
    fd::{is_dev_kfd, seal_memfd_all, SafeOwnedFd, NULL_FD, PROC_FILE},
    fs::{format_oflags, oflag_accmode, oflag_nonblock},
    hash::aes_ctr_tmp,
    log_enabled,
    lookup::{
        safe_open_how_msym, safe_open_msym, CanonicalPath, FileInfo, FileType, FsFlags, MaybeFd,
    },
    mask::mask_proc_pid_status,
    ofd::{lock_fd, unlock_fd},
    path::{XPath, XPathBuf},
    proc::{proc_tty, proc_umask},
    req::{SysArg, SysFlags, UNotifyEventRequest},
    retry::retry_on_eintr,
    sandbox::{Action, Capability, Sandbox},
    syslog::LogLevel,
    warn,
    workers::aes::{AesMod, AesVal},
};

// Raw O_TMPFILE bit without O_DIRECTORY
const __O_TMPFILE: OFlag = OFlag::O_TMPFILE.difference(OFlag::O_DIRECTORY);

// Valid flags with O_PATH.
// openat2(2) validates these, open(2) and openat(2) strip them.
const O_PATH_VALID: OFlag =
    OFlag::from_bits_retain(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_PATH | libc::O_CLOEXEC);

// `OpenSyscall` represents possible open family system calls.
//
//  The list of open family system calls are: creat(2), open(2),
//  openat(2), and openat2(2).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum OpenSyscall {
    Creat,
    Open,
    Openat,
    Openat2,
}

pub(crate) fn sys_creat(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;

    // Here we omit MUST_PATH in fsflags as path may not exist yet.
    let arg = SysArg {
        path: Some(0),
        flags: SysFlags::OPENER_CALL,
        fsflags: FsFlags::empty(),
        ..Default::default()
    };
    let flags = OFlag::O_CREAT | OFlag::O_WRONLY | OFlag::O_TRUNC;

    // Truncate undefined/invalid mode.
    let mode = crate::kernel::to_mode(req.data.args[1]);

    // Path pointer will be validated by open handler after further flag validation.
    syscall_open_handler(request, OpenSyscall::Creat, arg, flags, mode)
}

pub(crate) fn sys_open(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;

    // Truncate undefined/invalid flags.
    let flags = match to_oflag(req.data.args[1], true) {
        Ok(flags) => flags,
        Err(errno) => return request.fail_syscall(errno),
    };

    // Reject undefined/invalid mode.
    // Ignore mode if no creation flags are passed.
    let mode = match to_mode(req.data.args[2], flags, true) {
        Ok(mode) => mode,
        Err(errno) => return request.fail_syscall(errno),
    };

    // Path pointer will be validated by open handler
    // after further flag validation.
    let arg = SysArg::open(flags, false, ResolveFlag::empty());
    syscall_open_handler(request, OpenSyscall::Open, arg, flags, mode)
}

pub(crate) fn sys_openat(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;

    // Truncate undefined/invalid flags.
    let flags = match to_oflag(req.data.args[2], true) {
        Ok(flags) => flags,
        Err(errno) => return request.fail_syscall(errno),
    };

    // Reject undefined/invalid mode.
    // Ignore mode if no creation flags are passed.
    let mode = match to_mode(req.data.args[3], flags, true) {
        Ok(mode) => mode,
        Err(errno) => return request.fail_syscall(errno),
    };

    // Path pointer will be validated by open handler after further flag validation.
    let arg = SysArg::open(flags, true, ResolveFlag::empty());
    syscall_open_handler(request, OpenSyscall::Openat, arg, flags, mode)
}

pub(crate) fn sys_openat2(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;

    // remote_ohow validates address and size.
    let open_how = match request.remote_ohow(req.data.args[2], req.data.args[3]) {
        Ok(open_how) => open_how,
        Err(errno) => {
            return request.fail_syscall(errno);
        }
    };

    // Reject undefined and invalid flags.
    let flags = match to_oflag(open_how.flags, false) {
        Ok(flags) => flags,
        Err(errno) => return request.fail_syscall(errno),
    };

    // Return EINVAL for invalid resolve flags or combinations.
    let rflags = match ResolveFlag::from_bits(open_how.resolve) {
        Some(rflags)
            if rflags.contains(ResolveFlag::RESOLVE_BENEATH | ResolveFlag::RESOLVE_IN_ROOT) =>
        {
            return request.fail_syscall(Errno::EINVAL);
        }
        Some(rflags) => rflags,
        None => return request.fail_syscall(Errno::EINVAL),
    };

    // Reject undefined/invalid mode.
    // Reject non-zero mode if no creation flags are passed.
    let mode = match to_mode(open_how.mode, flags, false) {
        Ok(mode) => mode,
        Err(errno) => return request.fail_syscall(errno),
    };

    // Path pointer will be validated by open handler
    // after further flag validation.
    let arg = SysArg::open(flags, true, rflags);
    syscall_open_handler(request, OpenSyscall::Openat2, arg, flags, mode)
}

#[expect(clippy::cognitive_complexity)]
fn syscall_open_handler(
    request: UNotifyEventRequest,
    syscall: OpenSyscall,
    arg: SysArg,
    flags: OFlag,
    mode: Mode,
) -> ScmpNotifResp {
    syscall_handler!(request, |request: UNotifyEventRequest| {
        // When emulating the open call we always open the file
        // descriptor with O_CLOEXEC flag for safety. Here, we mark the
        // state of the O_CLOEXEC flag to use it in seccomp_addfd call.
        // Mutability:
        //   1. o_cloexec is mutable because trace/open_force_cloexec:1
        //      may change its value for O_CLOEXEC.
        //   2. flags is mutable because trace/allow_unsafe_open:0
        //      may change its value for O_PATH.
        //   3. flags is mutable because trace/allow_unsafe_create:0
        //      may insert O_NOFOLLOW when O_CREAT is set but O_EXCL
        //      is not set.
        let mut o_cloexec = flags.contains(OFlag::O_CLOEXEC);
        let mut flags = flags | OFlag::O_CLOEXEC;

        // Determine capabilities based on access mode:
        //
        // TODO: Confine O_PATH file descriptors with Stat category,
        // rather than Read category when they can be properly emulated.
        // See: https://bugzilla.kernel.org/show_bug.cgi?id=218501
        let (mut caps, o_path, o_rdwr) = match oflag_accmode(flags) {
            OFlag::O_RDONLY => (Capability::CAP_READ, false, false),
            OFlag::O_WRONLY => (Capability::CAP_WRITE, false, false),
            OFlag::O_RDWR => (Capability::CAP_READ | Capability::CAP_WRITE, false, true),
            OFlag::O_PATH => (Capability::CAP_READ, true, false),
            _ => return Err(Errno::EINVAL), // Invalid access mode.
        };

        let o_creat = flags.contains(OFlag::O_CREAT);
        let o_dir = flags.contains(OFlag::O_DIRECTORY);
        let o_tmpfl = flags.contains(OFlag::O_TMPFILE);
        let o_trunc = flags.contains(OFlag::O_TRUNC);
        let __o_tmpfl = flags.contains(__O_TMPFILE);
        let mut o_mask = o_creat || o_tmpfl;

        // The following flag combinations are invalid:
        // - O_PATH | O_CREAT
        // - O_PATH | O_TMPFILE
        // - O_CREAT | O_TMPFILE
        // - O_CREAT | O_DIRECTORY
        // - __O_TMPFILE without O_DIRECTORY
        if (o_path && o_mask) || (o_creat && (o_dir || o_tmpfl)) || (__o_tmpfl && !o_tmpfl) {
            return Err(Errno::EINVAL);
        }

        // O_TMPFILE must be combined with O_WRONLY or O_RDWR.
        if o_tmpfl && !caps.contains(Capability::CAP_WRITE) {
            return Err(Errno::EINVAL);
        }

        // Return EAGAIN for RESOLVE_CACHED combined with creation or truncation.
        if arg.flags.contains(SysFlags::CACHED_CALL) && (o_creat || o_trunc || o_tmpfl) {
            return Err(Errno::EAGAIN);
        }

        let req = request.scmpreq;
        let sandbox = request.get_sandbox();

        // Check for chroot.
        if sandbox.is_chroot() {
            return Err(Errno::ENOENT);
        }

        // We use exactly one of Mktemp, Create, Truncate sandboxing
        // categories to improve usability, ie the priority is
        // O_TMPFILE > O_CREAT > O_TRUNC.
        if o_tmpfl {
            caps.insert(Capability::CAP_MKTEMP);
        } else if o_creat {
            caps.insert(Capability::CAP_CREATE);
        } else if o_trunc {
            caps.insert(Capability::CAP_TRUNCATE);
        }

        let can_write = caps.can_write();
        if can_write && sandbox.flags.force_ro_open() {
            // Deny write/truncate attempt with trace/force_ro_open:1.
            return Err(Errno::EPERM);
        }

        if sandbox.log_scmp() {
            debug!("ctx": "open", "op": "init",
                "cap": caps,
                "sbc": *sandbox.state,
                "arg": format!("{arg:?}"),
                "flg": format!("{flags:?}"),
                "mod": format!("{mode:?}"),
                "req": &request);
        } else {
            debug!("ctx": "open", "op": "init",
                "cap": caps,
                "sbc": *sandbox.state,
                "arg": format!("{arg:?}"),
                "flg": format!("{flags:?}"),
                "mod": format!("{mode:?}"),
                "pid": request.scmpreq.pid);
        }

        let mut arg = arg;
        if sandbox.flags.deny_dotdot() {
            // Apply deny_dotdot for open family with trace/deny_dotdot:1.
            arg.fsflags.insert(FsFlags::NO_RESOLVE_DOTDOT);
        }

        // Prevent file creation through dangling symlinks.
        let restrict_create = !sandbox.flags.allow_unsafe_create();
        if o_creat && restrict_create && !flags.contains(OFlag::O_EXCL) {
            flags.insert(OFlag::O_NOFOLLOW);
            arg.fsflags.insert(FsFlags::NO_FOLLOW_LAST);
        }

        // Read the remote path and check for magic path.
        arg.flags.insert(SysFlags::CHECK_MAGIC);
        let (mut path, magic, _) = request.read_path(&sandbox, arg)?;

        // Restrict opening/creating SUID/SGID files as necessary.
        let restrict_suid = !sandbox.flags.allow_unsafe_open_suid();

        if sandbox.log_scmp() {
            debug!("ctx": "open", "op": "read_path",
                "path": &path, "magic": magic,
                "req": &request);
        } else {
            debug!("ctx": "open", "op": "read_path",
                "path": &path, "magic": magic,
                "pid": request.scmpreq.pid().as_raw());
        }

        // Handle the special /dev/syd paths.
        if magic {
            // Check sandbox lock for Read access.
            //
            // a. LockState::Set allows no access.
            // b. LockState::Read allows open(2) based read-only access.
            //
            // `locked_read_for` returns true for LockState::Set, and
            // false for LockState::Read.
            if sandbox.locked_read_for(req.pid()) {
                return Err(Errno::ENOENT);
            }
            if o_path {
                return Err(Errno::EINVAL);
            }

            let fd = if caps.contains(Capability::CAP_READ) {
                let mut fd = safe_memfd_create(c"syd/box", *SAFE_MFD_FLAGS)?;

                const FLEN: usize = MAGIC_PREFIX.len() + 3; /* .{el,sh} */
                let fack = path.abs().len() == FLEN;
                let fext = path.abs().extension();
                let data = if path.abs().is_equal(MAGIC_PREFIX) {
                    Cow::Owned(serde_json::to_string_pretty(&*sandbox).or(Err(Errno::EINVAL))?)
                } else if fack && fext.map(|ext| ext.is_equal(b"el")).unwrap_or(false) {
                    Cow::Borrowed(SYD_EL)
                } else if fack && fext.map(|ext| ext.is_equal(b"sh")).unwrap_or(false) {
                    Cow::Borrowed(ESYD_SH)
                } else if path.abs().is_equal(b"/dev/syd/pink") {
                    Cow::Borrowed(PINK_FLOYD)
                } else if path.abs().is_equal(b"/dev/syd/pipe") {
                    Cow::Borrowed(THE_PIPER)
                } else if path.abs().is_equal(b"/dev/syd/play") {
                    Cow::Borrowed(SEE_EMILY_PLAY)
                } else {
                    return Err(Errno::EINVAL);
                };
                drop(sandbox); // release the read-lock.

                fd.write_all(data.as_bytes()).or(Err(Errno::EACCES))?;
                fd.rewind().or(Err(Errno::EACCES))?;

                // Deny further writes to the file descriptor.
                seal_memfd_all(&fd)?;

                MaybeFd::Owned(fd.into())
            } else {
                MaybeFd::RawFd(NULL_FD())
            };

            // Send the file descriptor to the process and return the fd no.
            // Randomize FD to make reuse harder.
            return request.send_fd(fd, true, true);
        }

        // Validate file flags based on file type information.
        //
        // is_dir: Used for mask to determine directory override.
        // may_crypt: Used by Crypt sandboxing.
        let (is_dir, may_crypt) = if let Some(ref file_type) = path.typ {
            if o_creat {
                // Creating open with existing file:
                // Remove Create from capabilities, and add back
                // Truncate capability as necessary to improve
                // usability.
                caps.remove(Capability::CAP_CREATE);
                if o_trunc {
                    caps.insert(Capability::CAP_TRUNCATE);
                }
            }

            match *file_type {
                FileType::Reg => {
                    // We only ever attempt to encrypt regular files.
                    (false, true)
                }
                FileType::Dir => {
                    // We know it's a directory, so let's assert it.
                    // Unless path ends with a slash, in that case we
                    // don't want to break expectations.
                    if path.abs().last() != Some(b'/') {
                        flags.insert(OFlag::O_DIRECTORY);
                    }

                    // Change capability from Read to Readdir.
                    caps.remove(Capability::CAP_READ);
                    caps.insert(Capability::CAP_READDIR);

                    (true, false)
                }
                FileType::Mfd | FileType::MfdSec => {
                    // We do not encrypt memory fds.
                    (false, false)
                }
                FileType::MagicLnk(_) => {
                    if file_type.is_magic_dir() {
                        // Change capability from Read to Readdir.
                        caps.remove(Capability::CAP_READ);
                        caps.insert(Capability::CAP_READDIR);
                    }

                    (false, false)
                }
                FileType::Lnk | FileType::Chr | FileType::Fifo | FileType::Sock => (false, false),
                FileType::Blk => {
                    // Do not allow access to block devices.
                    // Restriction may be relaxed with trace/allow_unsafe_mkbdev:1.
                    // Deny with ENOENT for stealth.
                    if !sandbox.options.allow_unsafe_mkbdev() {
                        return Err(Errno::ENOENT);
                    }

                    (false, false)
                }
                FileType::Unk => {
                    // Do not allow access to files with unknown types.
                    // Deny with ENOENT for stealth.
                    return Err(Errno::ENOENT);
                }
            }
        } else if !o_creat {
            // Non-creating open on non-existing file.
            return Err(Errno::ENOENT);
        } else {
            // Creating open on non-existing file.
            //
            // Note, adding O_EXCL to flags here to assert file creation
            // may result in a race condition where a fellow Syd thread
            // can race with this one in creating the same file, making
            // the thread losing the race return a confusing EEXIST error.
            // Therefore we avoid doing that, see:
            // https://gitlab.exherbo.org/sydbox/sydbox/-/issues/211
            //
            // flags.insert(OFlag::O_EXCL);

            // Non-existing files are not directories.
            // Non-existing files may be encrypted from scratch.
            (false, true)
        };

        // We must provide safe access to sandbox process' controlling
        // terminal. Both the virtual "/dev/console" or "/dev/tty" and
        // the replacing tty path are checked for access.
        let pid = req.pid();
        let mut path_tty = None;
        if path.is_char_device() {
            const TTY: &[&[u8]] = &[b"/dev/tty", b"/dev/console"];
            for p in TTY {
                if !path.abs().is_equal(p) {
                    continue;
                }

                let real_tty = proc_tty(pid)?;
                if !request.is_valid() {
                    return Err(Errno::ESRCH);
                }
                path = CanonicalPath::new_tty(real_tty)?;
                path_tty = Some(Cow::Borrowed(XPath::from_bytes(p)));
                break;
            }
        }

        let has_tty = path_tty.is_some();
        let log_scmp = sandbox.log_scmp();
        if has_tty {
            if log_scmp {
                debug!("ctx": "open", "op": "flip_tty",
                    "path": &path, "tty": &path_tty,
                    "req": &request);
            } else {
                debug!("ctx": "open", "op": "flip_tty",
                    "path": &path, "tty": &path_tty,
                    "pid": request.scmpreq.pid);
            }
        }

        // Ensure the sandbox process cannot acquire a new controlling
        // terminal other than what they already have. O_NOCTTY is
        // invalid with O_PATH, but we don't care for now since we'll
        // change it to O_RDONLY later as a mitigation due to our
        // inability to emulate them.
        // See: https://bugzilla.kernel.org/show_bug.cgi?id=218501
        flags.insert(OFlag::O_NOCTTY);

        // Sandboxing.
        let orig_caps = caps;
        let caps = sandbox.getcaps(orig_caps); // Get enabled caps.
        let mut action = Action::Allow;

        // Convert /proc/$pid to /proc/self as necessary.
        let mut path_check = path.abs().replace_proc_self(pid);

        if !caps.is_empty() {
            // If open is a TTY both the virtual and real path are checked for access.
            // The more critical action wins.
            let mut flip_tty = false;
            for (idx, path) in [Some(&path_check), path_tty.as_ref()]
                .iter()
                .flatten()
                .enumerate()
            {
                for cap in caps {
                    let new_action = sandbox.check_path(cap, path);
                    if new_action >= action {
                        action = new_action;
                        if idx > 0 && new_action > Action::Allow {
                            flip_tty = true;
                        }
                    }
                }
            }
            #[expect(clippy::disallowed_methods)]
            if flip_tty {
                path_check = path_tty.unwrap()
            }
        }

        let (hidden, mut crypted) = if action.is_denying() {
            // No need to check for mask when denying.
            // No need to check for encryption when denying.
            (sandbox.is_hidden(&path_check), false)
        } else {
            // No need for hidden check if we're allowing:
            // 1. Check for encrypted path and mark for later.
            // 2. Check for masked path and change path to /dev/null.
            // 3. Check for append-only path and deny.
            // We perform these check only if we're allowing.
            let crypted = if let Some(mask) = sandbox.is_masked(&path_check) {
                let mask = if let Some(mask_dir) = &mask.mask_dir {
                    // Override mask for directories as necessary.
                    if is_dir {
                        Some(mask_dir)
                    } else {
                        mask.mask_all.as_ref()
                    }
                } else {
                    mask.mask_all.as_ref()
                };
                match mask {
                    None => path = CanonicalPath::new_null(),
                    Some(mask) => path = CanonicalPath::new_mask(mask, &path_check)?,
                };
                // Mask path is not subject to sandbox check!
                // `path_check' is only used for logging and points to
                // the original path.
                path_check = Cow::Borrowed(path.abs());
                false // masked path is not encrypted.
            } else if sandbox.enabled(Capability::CAP_CRYPT) {
                may_crypt && sandbox.is_crypt(&path_check)
            } else {
                false // encryption not enabled for path.
            };

            // Check for append-only path and deny.
            // Temporary files can not be made append-only.
            if (o_trunc || (can_write && !flags.contains(OFlag::O_APPEND)))
                && sandbox.is_append(&path_check)
            {
                return Err(Errno::EPERM);
            }

            (false, crypted)
        };

        // Check for Filesystem sandboxing as necessary.
        let mut maybe_fs_type = None;
        if action.is_allowing() && sandbox.has_fs() {
            let fs_type = FsType::get(path.dir())?;
            let action = sandbox.check_fs(fs_type);
            if action.is_logging() {
                if log_scmp {
                    warn!("ctx": "access", "cap": Capability::CAP_FS, "act": action,
                        "sys": request.syscall, "fs": fs_type, "path": &path_check,
                        "mode": mode.bits(),
                        "oflags": format_oflags(flags), "rflags": arg.fsflags,
                        "type": path.typ,
                        "tip": format!("configure `allow/fs+{fs_type}'"),
                        "req": &request);
                } else {
                    warn!("ctx": "access", "cap": Capability::CAP_FS, "act": action,
                        "sys": request.syscall, "fs": fs_type, "path": &path_check,
                        "mode": mode.bits(),
                        "oflags": format_oflags(flags), "rflags": arg.fsflags,
                        "type": path.typ,
                        "tip": format!("configure `allow/fs+{fs_type}'"),
                        "pid": request.scmpreq.pid);
                }
            }

            match action {
                Action::Allow | Action::Warn => {}
                Action::Deny | Action::Filter if hidden => return Err(Errno::ENOENT),
                Action::Deny | Action::Filter => return Err(Errno::EACCES),
                Action::Panic => panic!(),
                Action::Exit => std::process::exit(libc::EACCES),
                action => {
                    // Stop|Kill
                    let _ = request.kill(action);
                    return Err(Errno::EACCES);
                }
            }
            maybe_fs_type = Some(fs_type);
        }

        let force_umask = sandbox.umask;
        let unsafe_open_kfd = sandbox.flags.allow_unsafe_open_kfd();
        let unsafe_open_path = sandbox.flags.allow_unsafe_open_path();
        let filter_machine_id = !sandbox.flags.allow_unsafe_machine_id();
        let filter_proc_status = !sandbox.flags.allow_unsafe_proc_pid_status();
        let filter_uname = !sandbox.options.allow_unsafe_uname();
        if sandbox.flags.force_cloexec() {
            o_cloexec = true;
        } else if cfg!(feature = "kcov") && path.abs().is_kcov() {
            o_cloexec = false;
        }
        let o_rand_fd = sandbox.flags.force_rand_fd();
        let setup_fds = sandbox.crypt_setup();
        let crypt_tmp = if crypted { sandbox.crypt_tmp } else { None };
        drop(sandbox); // release the read-lock.

        // Perform action: allow->emulate, deny->log.
        if action.is_logging() && log_enabled!(LogLevel::Warn) {
            let fs_type = if let Some(fs_type) = maybe_fs_type {
                fs_type
            } else {
                FsType::get(path.dir())?
            };
            let grp = caps.to_string().to_ascii_lowercase();
            if log_scmp {
                warn!("ctx": "access", "cap": caps, "act": action,
                    "sys": request.syscall, "fs": fs_type, "path": &path_check,
                    "mode": mode.bits(),
                    "oflags": format_oflags(flags), "rflags": arg.fsflags,
                    "type": path.typ,
                    "tip": format!("configure `allow/{grp}+{path_check}'"),
                    "req": &request);
            } else {
                warn!("ctx": "access", "cap": caps, "act": action,
                    "sys": request.syscall, "fs": fs_type, "path": &path_check,
                    "mode": mode.bits(),
                    "oflags": format_oflags(flags), "rflags": arg.fsflags,
                    "type": path.typ,
                    "tip": format!("configure `allow/{grp}+{path_check}'"),
                    "pid": request.scmpreq.pid);
            }
        }

        // Access check is done, now it is safe to:
        // 1. Return ENOENT if path is hidden.
        // 2. Return EEXIST if options include MISS_LAST.
        // 3. Return ENOTDIR for non-directories with trailing slash.
        // 4. Return EISDIR for write opens on directories.
        // 5. Return ELOOP for symlinks unless O_NOFOLLOW was passed.

        // We check for the actions Deny|Filter here as other actions
        // such as Panic, Stop, Kill are handled afterwards as necessary.
        if hidden && matches!(action, Action::Deny | Action::Filter) {
            return Err(Errno::ENOENT);
        }

        if arg.fsflags.missing() && path.typ.is_some() {
            // Exclusive open for existing file.
            return Err(Errno::EEXIST);
        }

        if let Some(file_type) = &path.typ {
            if !matches!(file_type, FileType::Dir | FileType::MagicLnk(_))
                && path.abs().last() == Some(b'/')
            {
                return Err(Errno::ENOTDIR);
            }
        }

        if let Some(FileType::Dir) = &path.typ {
            if !o_tmpfl && orig_caps.can_write() {
                // Open for write on directory.
                return Err(Errno::EISDIR);
            }
        } else if o_tmpfl {
            // O_TMPFILE open on non-directory.
            return Err(Errno::ENOTDIR);
        }

        // Return EPERM for {/dev,/proc}/kmsg, so dmesg(1) falls back to
        // syslog(2) which we provide. EPERM is fine as we do this after
        // the access check so path hiding was already done as
        // necessary.
        if !has_tty && path.is_char_device() && path.abs().is_equal(b"/dev/kmsg") {
            return Err(Errno::EPERM);
        }
        if !has_tty && path.is_file() && path.abs().is_equal(b"/proc/kmsg") {
            return Err(Errno::EPERM);
        }

        // Do not follow (magic) symlinks after canonicalization.
        // Exception: Last component is allowed with O_NOFOLLOW.
        if path.is_symlink() && !flags.contains(OFlag::O_NOFOLLOW) {
            return Err(Errno::ELOOP);
        }

        // Restrictions a la protected_{fifos,regular} and
        // CONFIG_GRKERNSEC_FIFO. Here, though, we take a stricter
        // approach and block creates on non-owned files or fifos
        // regardless of the owned directory.
        //
        // This is done after O_CREAT|O_EXCL -> EEXIST check.
        let mut file_mode = None;
        if restrict_create && o_creat && matches!(path.typ, Some(FileType::Reg | FileType::Fifo)) {
            // We use MUST_PATH, dir refers to the file.
            assert!(path.base().is_empty()); // MUST_PATH!
            let fd = path.dir();

            let statx = fstatx(fd, STATX_MODE | STATX_UID)?;
            let mode = libc::mode_t::from(statx.stx_mode);
            file_mode = Some(Mode::from_bits_retain(mode));

            // Return EACCES if:
            // 1. File is group or world-writable.
            // 2. File is not owned by caller.
            let mut err = None;
            if mode & libc::S_IWOTH != 0 {
                // File is world-writable.
                err = Some("file is world writable");
            } else if mode & libc::S_IWGRP != 0 {
                // File is group-writable.
                err = Some("file is group writable");
            } else if statx.stx_uid != Uid::effective().as_raw() {
                // File is not owned by caller.
                err = Some("file is not owned by caller");
            }

            if let Some(msg) = err {
                if log_scmp {
                    error!("ctx": "trusted_file_creation", "cap": caps,
                        "sys": request.syscall, "path": &path_check,
                        "mode": mode, "oflags": format_oflags(flags), "rflags": arg.fsflags,
                        "msg": format!("create for untrusted path blocked: {msg}"),
                        "tip": "fix path permissions or use `trace/allow_unsafe_create:1'",
                        "req": &request);
                } else {
                    error!("ctx": "trusted_file_creation", "cap": caps,
                        "sys": request.syscall, "path": &path_check,
                        "mode": mode, "oflags": format_oflags(flags), "rflags": arg.fsflags,
                        "msg": format!("create for untrusted path blocked: {msg}"),
                        "tip": "fix path permissions or use `trace/allow_unsafe_create:1'",
                        "pid": request.scmpreq.pid);
                }
                return Err(Errno::EACCES);
            }
        }

        // Check for SUID/SGID files if mitigation is enabled.
        if restrict_suid
            && (matches!(path.typ, Some(FileType::Reg)) || (o_creat && path.typ.is_none()))
        {
            // Get file mode to check for SUID/SGID bits.
            let mode = if o_creat && path.typ.is_none() {
                mode // Mode argument of O_CREAT
            } else if let Some(mode) = file_mode {
                mode // File mode of non-creating open
            } else {
                fstatx(path.dir(), STATX_MODE)
                    .map(|statx| libc::mode_t::from(statx.stx_mode))
                    .map(Mode::from_bits_retain)?
            };

            // Reject SUID and SGID files with EACCES.
            if mode.intersects(Mode::S_ISUID | Mode::S_ISGID) {
                if log_scmp {
                    error!("ctx": "trusted_file_open", "cap": caps,
                        "sys": request.syscall, "path": &path_check,
                        "mode": mode.bits(), "oflags": format_oflags(flags), "rflags": arg.fsflags,
                        "msg": "open for SUID/SGID path blocked",
                        "tip": "fix path permissions or use `trace/allow_unsafe_open_suid:1'",
                        "req": &request);
                } else {
                    error!("ctx": "trusted_file_open", "cap": caps,
                        "sys": request.syscall, "path": &path_check,
                        "mode": mode.bits(), "oflags": format_oflags(flags), "rflags": arg.fsflags,
                        "msg": "open for SUID/SGID path blocked",
                        "tip": "fix path permissions or use `trace/allow_unsafe_open_suid:1'",
                        "pid": request.scmpreq.pid);
                }
                return Err(Errno::EACCES);
            }
        }

        match action {
            Action::Allow | Action::Warn => {
                // The system call is allowed.
                //
                // To prevent TOCTOU, we open the file ourselves, and
                // put the file descriptor to the process' address space
                // with SECCOMP_IOCTL_NOTIF_ADDFD.
                if o_path {
                    if unsafe_open_path {
                        // SAFETY:
                        // seccomp addfd operation returns EBADF for O_PATH file
                        // descriptors so there's no TOCTOU-free way to emulate
                        // this as of yet. However we did our best by
                        // delaying continue up to this point, thereby
                        // including the open request to the sandbox access
                        // check.
                        return unsafe { Ok(request.continue_syscall()) };
                    }
                    // Turn O_PATH flag to O_RDONLY for successful emulation.
                    // Add O_NONBLOCK to reduce potential side effects.
                    flags.remove(OFlag::O_PATH);
                    flags.insert(OFlag::O_RDONLY | OFlag::O_NONBLOCK);
                } else if unsafe_open_kfd
                    && o_rdwr
                    && !o_creat
                    && !o_trunc
                    && !o_tmpfl
                    && path.base().is_empty()
                    && is_dev_kfd(path.dir()).unwrap_or(false)
                {
                    // SAFETY:
                    //
                    // trace/allow_unsafe_kfd:true
                    //
                    // 1. AMD KFD character devices require per-application access
                    //    to the GPU device, therefore opening the device in the
                    //    Syd emulator thread and then continuing the subsequent ioctl(2)
                    //    system calls in the sandbox process is going to return EBADF.
                    //    Until, Syd has a way to fully emulate the ioctl(2) request space
                    //    and is able to call ioctl(2) directly from Syd emulator threads,
                    //    this option may be used to access such character devices.
                    //    Setting this option opens a TOCTOU attack vector, whereby the
                    //    sandbox process can open an arbitrary file instead of the character
                    //    device in question!
                    // 2. Syd does not CONTINUE the system call if at least one of the flags
                    //    O_CREAT|O_TRUNC|O_TMPFILE is set in flags argument to limit the scope
                    //    of the TOCTOU attack vector.
                    //  3. Syd CONTINUEs the system call if and only if O_RDWR is set in the flags
                    //     argument to limit the scope of the TOCTOU attack vector.
                    //  4. Syd returns ENOSYS for openat2(2) rather than CONTINUE'ing the system call
                    //     to prevent the "struct open_how" pointer indirection to bypass the restrictions
                    //     applied to the flags argument.
                    //  5. This option may be changed at runtime, and it is highly recommended to unset
                    //     this option right after the respective character device is open using the syd(2)
                    //     API to close the TOCTOU attack vector.
                    return if syscall != OpenSyscall::Openat2 {
                        // SAFETY: See above, stupid clippy.
                        unsafe { Ok(request.continue_syscall()) }
                    } else {
                        Err(Errno::ENOSYS)
                    };
                }

                // We have already resolved the symbolic links in the
                // path as necessary, to prevent a time-of-check to
                // time-of-use vector:
                // 1. Add O_NOFOLLOW to flags.
                // 2. Add RESOLVE_BENEATH to flags.
                // 3. Add RESOLVE_NO_MAGICLINKS | RESOLVE_NO_SYMLINKS to flags.
                // 4. Mode must be 0 if O_CREAT or O_TMPFILE is not in flags.
                // Note, magic symbolic links are an exception here.
                if matches!(path.typ, Some(FileType::MagicLnk(_))) {
                    if !path.base().is_empty() || flags.contains(OFlag::O_NOFOLLOW) {
                        // Magic symlink O_PATH fds were continued as
                        // necessary if relevant unsafe options were
                        // set. After this point, we have to ELOOP.
                        return Err(Errno::ELOOP);
                    }

                    // Ensure no encryption or file creation attempts
                    // can ever happen for magic symlinks.
                    o_mask = false;
                    crypted = false;
                    flags.remove(OFlag::O_CREAT);
                    flags.remove(OFlag::O_TMPFILE);
                }

                // We use RESOLVE_NO_SYMLINKS to prevent symlinks as
                // needed, and don't want to leak O_NOFOLLOW into
                // F_GETFL(2const). See Linux kernel's openat2 tests
                // for more information.
                //  flags.insert(OFlag::O_NOFOLLOW);

                let fd: SafeOwnedFd = if crypted {
                    // Handle Encryption.
                    let opts = CryptOpts {
                        o_cloexec,
                        o_rand_fd,
                        force_umask,
                        setup_fds,
                        tmpdir: crypt_tmp,
                    };
                    if let Some(fd) = handle_crypt(&request, &path, flags, mode, opts)? {
                        // read-only encryption.
                        fd
                    } else {
                        // read-write encryption.
                        //
                        // We do not need to send a response,
                        // send a dummy response to the caller
                        // can skip it gracefully.
                        return Ok(ScmpNotifResp::new(0, 0, EIDRM, 0));
                    }
                } else if path.base().is_empty() && !o_tmpfl {
                    if let Some(fd) = do_open_pre(&request, &path, filter_machine_id, filter_uname)?
                    {
                        // pre-open hook intercepted, no need to open.
                        fd
                    } else {
                        // Existing path: Construct path to proc(5) magic symlink,
                        // or pre-open file descriptor.
                        let fd = do_open(&request, &path, flags)?;
                        do_open_post(fd, request.scmpreq.pid(), path, filter_proc_status)?
                    }
                } else if o_mask {
                    // Cannot be O_PATH or encrypted fd!
                    //
                    // If we're creating the file, we need to change
                    // per-thread umask and still honour POSIX ACLs.
                    do_creat(&request, &path, flags, mode, force_umask)?
                } else {
                    unreachable!("BUG: MUST_PATH returned a directory for open, report a bug!");
                };

                // File opened successfully, return to caller at one go.
                request.send_fd(fd, o_cloexec, o_rand_fd)
            }
            Action::Deny | Action::Filter if hidden => Err(Errno::ENOENT),
            Action::Deny | Action::Filter => Err(Errno::EACCES),
            Action::Panic => panic!(),
            Action::Exit => std::process::exit(libc::EACCES),
            action => {
                // Stop|Kill
                let _ = request.kill(action);
                Err(Errno::EACCES)
            }
        }
    })
}

/// Options for `handle_crypt` function.
#[derive(Copy, Clone, Debug)]
struct CryptOpts {
    o_cloexec: bool,
    o_rand_fd: bool,
    force_umask: Option<Mode>,
    tmpdir: Option<RawFd>,
    setup_fds: Result<(RawFd, RawFd), Errno>,
}

/// Handle open() calls for encrypted files.
fn handle_crypt(
    request: &UNotifyEventRequest,
    path: &CanonicalPath,
    safe_flags: OFlag,
    mode: Mode,
    opts: CryptOpts,
) -> Result<Option<SafeOwnedFd>, Errno> {
    #[expect(clippy::disallowed_methods)]
    let files = request.cache.crypt_map.as_ref().unwrap();
    let my_mode = AesMod::from(safe_flags);

    // Check for concurrent read access to the same crypt fd.
    if my_mode == AesMod::Read {
        // Lock the mutex and attempt to reopen the crypt fd.
        // Concurrent access is only allowed if both modes are Read.
        //
        // proc(5) reopen must happen while holding the lock to prevent
        // syd_aes thread from closing crypt_fd, and the kernel from
        // recycling the fd number.
        let crypt_res = {
            let files = files.0.lock().unwrap_or_else(|err| err.into_inner());
            match files
                .get(path.abs())
                .filter(|&entry| entry.mode == AesMod::Read)
                .map(|aes_val| aes_val.crypt_fd)
            {
                Some(crypt_fd) => {
                    let mut flags = safe_flags;
                    flags.remove(OFlag::O_NOFOLLOW);

                    let pfd = XPathBuf::from_self_fd(crypt_fd)?;
                    match safe_open_msym(PROC_FILE(), &pfd, flags, ResolveFlag::empty()) {
                        Ok(fd) if retry_on_eintr(|| lock_fd(&fd, false, false)).is_ok() => {
                            // OFD read lock acquired under mutex.
                            Some(Ok(fd))
                        }
                        Ok(fd) => {
                            // syd_aes thread already holds the write lock.
                            drop(fd);
                            None
                        }
                        Err(Errno::ENOENT) => {
                            // syd_aes thread already closed the crypt fd.
                            None
                        }
                        Err(errno) => Some(Err(errno)),
                    }
                }
                None => None,
            }
        }; // Lock is released here.

        match crypt_res {
            Some(Ok(fd)) => return Ok(Some(fd)),
            Some(Err(errno)) => return Err(errno),
            None => { /* fall through */ }
        }
    }

    // Promote O_WRONLY to O_RDWR and drop O_APPEND.
    // This fd is not exposed to sandbox process.
    let mut flags = safe_flags;
    flags.remove(OFlag::O_WRONLY);
    flags.insert(OFlag::O_RDWR);
    flags.remove(OFlag::O_APPEND);

    // Strip O_ASYNC|O_NDELAY|O_NONBLOCK.
    // We want blocking writes to the underlying fd.
    flags.remove(OFlag::O_ASYNC | OFlag::O_NDELAY | OFlag::O_NONBLOCK);

    // Defer O_TRUNC until after the OFD lock is acquired.
    // Truncating before the lock corrupts in-flight AES writes.
    let o_trunc = flags.contains(OFlag::O_TRUNC);
    flags.remove(OFlag::O_TRUNC);

    // Open or create the file as read-write.
    //
    // Note, if `path.base().is_empty()` we have an existing file
    // which do_open_crypt is going to reopen using proc(5) magic
    // symlink.
    let create = if path.base().is_empty() {
        // Strip O_CREAT when NOT creating.
        flags.remove(OFlag::O_CREAT);
        // O_TMPFILE is valid if base is empty, when
        // we create a temporary file under parent-fd.
        flags.contains(OFlag::O_TMPFILE)
    } else {
        assert!(
            !flags.contains(OFlag::O_TMPFILE),
            "BUG: O_CREAT|O_TMPFILE flags are invalid, report a bug!"
        );
        flags.contains(OFlag::O_CREAT)
    };
    let enc_fd = if create {
        do_creat(request, path, flags, mode, opts.force_umask)
    } else {
        do_open_crypt(request, path, flags)
    }?;

    // Hold a write-lock to ensure no concurrent Syd aes writes.
    //
    // Block until we can acquire the lock to ensure safe concurrent
    // access _unless_ the open was a non-blocking open in which case we
    // happily return EAGAIN so the caller can retry.
    //
    // Similarly, `aes_ctr_tmp` respects non-blocking opens too,
    // and returns a non-blocking fd as necessary.
    let wait = !oflag_nonblock(safe_flags);
    retry_on_eintr(|| lock_fd(&enc_fd, true, create || wait))?;

    // Acquire encryption sockets.
    let setup_fds = opts.setup_fds?;

    // Perform deferred truncation with the lock held.
    // This ensures no in-flight AES writes are corrupted.
    if o_trunc {
        safe_ftruncate64(&enc_fd, 0)?;
    }

    // Map decrypted version to memory/temporary FD.
    //
    // This does not read plaintext into memory because we use
    // zero-copy. enc_fd is an SafeOwnedFd so in the event of an
    // aes_ctr_tmp error it'll be closed and the lock will be released.
    let (fd, iv) = if let Some((fd, iv)) = aes_ctr_tmp(setup_fds, &enc_fd, safe_flags, opts.tmpdir)?
    {
        (fd, iv)
    } else {
        // 1. This is not a new file.
        // 2. This is not a Syd encrypted file.
        // Unlock and open as-is.
        unlock_fd(&enc_fd)?;
        return Ok(Some(enc_fd));
    };

    // Reopen a new instance to pass to the sandbox process.
    // This instance points to a different open file description!
    let pfd = XPathBuf::from_self_fd(fd.as_raw_fd())?;

    let mut flags = safe_flags;
    flags.remove(
        OFlag::O_WRONLY | OFlag::O_ASYNC | OFlag::O_CREAT | OFlag::O_EXCL | OFlag::O_NOFOLLOW,
    );
    flags.insert(OFlag::O_RDWR);

    let aes_fd = safe_open_msym(PROC_FILE(), &pfd, flags, ResolveFlag::empty())?;

    // Record the file information, so we can answer reliably on fstat(2).
    let info = FileInfo::from_fd(&aes_fd)?;

    // No need to wait on this lock, as we've just opened the file.
    retry_on_eintr(|| lock_fd(&aes_fd, false, false))?;

    // Lock AES map before sending the fd.
    let (aes_map, cvar) = &**files;
    let mut aes_map = aes_map.lock().unwrap_or_else(|e| e.into_inner());

    // Now send the fd to the tracee, unblocking it.
    // Close the send fd to get rid off our copy of the lock.
    request.send_fd(aes_fd, opts.o_cloexec, opts.o_rand_fd)?;

    // Record encryption process information.
    aes_map.insert(
        path.abs().to_owned(),
        AesVal {
            info,
            iv: Some(iv),
            enc_fd: enc_fd.into_raw_fd(),
            crypt_fd: fd.into_raw_fd(),
            mode: my_mode,
        },
    );

    // Unlock and notify syd_aes thread.
    drop(aes_map);
    cvar.notify_one();

    Ok(None)
}

/// Handle open(2) calls that can potentially create files.
fn do_creat(
    request: &UNotifyEventRequest,
    path: &CanonicalPath,
    safe_flags: OFlag,
    mut mode: Mode,
    force_umask: Option<Mode>,
) -> Result<SafeOwnedFd, Errno> {
    // trace/force_umask overrides POSIX ACLs.
    if let Some(mask) = force_umask {
        mode &= !mask;
    }

    let how = OpenHow::new().flags(safe_flags).mode(mode).resolve(
        ResolveFlag::RESOLVE_BENEATH
            | ResolveFlag::RESOLVE_NO_MAGICLINKS
            | ResolveFlag::RESOLVE_NO_SYMLINKS,
    );

    // Determine process umask to apply in the thread.
    let req = request.scmpreq;
    let mask = proc_umask(req.pid())?;

    // `path.base()` may be empty for O_TMPFILE.
    let base = if !path.base().is_empty() {
        path.base()
    } else {
        XPath::from_bytes(b".")
    };

    // Set umask which is per-thread here.
    safe_umask(mask);

    // Record blocking call so it can get invalidated.
    let is_blocking = !oflag_nonblock(safe_flags);
    if is_blocking {
        request.cache.add_sys_block(req, false)?;
    }

    // All set, make the openat2(2) call.
    let result = safe_openat2(path.dir(), base, how);

    // Remove invalidation record.
    if is_blocking {
        request.cache.del_sys_block(req.id)?;
    }

    result
}

fn to_oflag(arg: u64, truncate: bool) -> Result<OFlag, Errno> {
    // Reject undefined flags.
    #[expect(clippy::cast_possible_truncation)]
    let flags = if truncate {
        // open(2), openat(2) truncates undefined flags.
        arg as libc::c_int
    } else {
        // openat2(2) validates undefined flags.
        arg.try_into().or(Err(Errno::EINVAL))?
    };

    // Keep O_LARGEFILE for old ABI.
    const KEEP_OFLAG: OFlag = O_LARGEFILE;

    let mut flags = OFlag::from_bits_retain(flags);
    let preserved = flags & KEEP_OFLAG;
    flags.remove(KEEP_OFLAG);

    if truncate {
        // open(2), openat(2):
        // 1. Truncates invalid flags.
        // 2. O_PATH truncates invalid O_PATH flags.
        let mut flags = (flags & OFlag::all()) | preserved;
        if flags.contains(OFlag::O_PATH) {
            flags &= O_PATH_VALID;
        }
        return Ok(flags);
    }

    // openat2(2) validates invalid flags.
    if flags.difference(OFlag::all()).bits() != 0 {
        return Err(Errno::EINVAL);
    }

    // openat2(2) validates O_PATH. open(2) and openat(2) strip.
    if flags.contains(OFlag::O_PATH) && !O_PATH_VALID.contains(flags | preserved) {
        return Err(Errno::EINVAL);
    }

    Ok(flags | preserved)
}

// Handle open(2) calls for Crypt sandboxing for existing paths.
//
// This function has no internal encryption logic,
// and it's only used by Crypt sandboxing when opening existing paths
// using proc(5) magic symlink, otherwise do_creat() is used.
fn do_open_crypt(
    request: &UNotifyEventRequest,
    path: &CanonicalPath,
    mut safe_flags: OFlag,
) -> Result<SafeOwnedFd, Errno> {
    assert!(
        path.base().is_empty(),
        "BUG: non-canonical path passed to do_open_crypt, report a bug!"
    );
    assert!(
        !safe_flags.contains(OFlag::O_CREAT),
        "BUG: O_CREAT passed to do_open_crypt, report a bug!"
    );
    assert!(
        !safe_flags.contains(OFlag::O_TMPFILE),
        "BUG: O_TMPFILE passed to do_open_crypt, report a bug!"
    );
    safe_flags.remove(OFlag::O_NOFOLLOW);

    // Construct path to proc(5) magic symlink.
    let pfd = XPathBuf::from_self_fd(path.dir().as_raw_fd())?;

    // Record blocking call so it can get invalidated.
    let req = request.scmpreq;
    let is_blocking = !oflag_nonblock(safe_flags);
    if is_blocking {
        request.cache.add_sys_block(req, false)?;
    }

    // Reopen the `O_PATH` path fd with the requested flags.
    let result = safe_open_msym(PROC_FILE(), &pfd, safe_flags, ResolveFlag::empty());

    // Remove invalidation record.
    if is_blocking {
        request.cache.del_sys_block(req.id)?;
    }

    result
}

// Existing path: Construct path to proc(5) magic symlink, or pre-open file descriptor.
fn do_open(
    request: &UNotifyEventRequest,
    path: &CanonicalPath,
    mut flags: OFlag,
) -> Result<SafeOwnedFd, Errno> {
    assert!(path.base().is_empty());

    // Path may be borrowed here, ie it can be a fd to the preopen `/`,
    // `/proc`, or `/dev/null` fds. In these cases, we still want to reopen, because the
    // fd we're going to send will share the same open file description and we don't want
    // to mess up file offsets for everyone.
    let fd = path.dir().as_raw_fd();
    let pfd = XPathBuf::from_self_fd(fd)?;

    // Reopen the `O_PATH` path fd with the requested flags.
    flags.remove(OFlag::O_CREAT);
    flags.remove(OFlag::O_NOFOLLOW);
    let how = safe_open_how_msym(flags, ResolveFlag::empty());

    // Record blocking call so it can get invalidated.
    let req = request.scmpreq;
    let is_blocking = !oflag_nonblock(flags);
    if is_blocking {
        request.cache.add_sys_block(req, false)?;
    }

    let result = safe_openat2(PROC_FILE(), &pfd, how);

    // Remove invalidation record.
    if is_blocking {
        request.cache.del_sys_block(req.id)?;
    }

    result
}

fn do_open_pre(
    request: &UNotifyEventRequest,
    path: &CanonicalPath,
    filter_machine_id: bool,
    filter_uname: bool,
) -> Result<Option<SafeOwnedFd>, Errno> {
    // Substitute machine-id(5) with per-Syd random boot-id.
    if filter_machine_id && path.abs().is_machine_id() {
        return Ok(Some(do_open_machine_id()?));
    }

    // Provide identical data to uname(2) for /proc/version.
    if filter_uname && path.abs().is_proc_version() {
        return Ok(Some(do_open_proc_version(request)?));
    }

    // Provide identical data to uname(2) for /proc/sys/kernel/osrelease.
    if filter_uname && path.abs().is_proc_osrelease() {
        return Ok(Some(do_open_proc_osrelease()?));
    }

    Ok(None)
}

fn do_open_post(
    mut fd: SafeOwnedFd,
    pid: Pid,
    path: CanonicalPath,
    filter_proc_status: bool,
) -> Result<SafeOwnedFd, Errno> {
    // Filter security-sensitive proc_pid_status(5) contents.
    if filter_proc_status && path.abs().is_proc_status() {
        fd = do_mask_proc_pid_status(fd, pid, path)?;
    }

    Ok(fd)
}

fn do_open_machine_id() -> Result<SafeOwnedFd, Errno> {
    // Open a memory fd to be sealed for write.
    let mut mfd = do_open_memfd(c"syd/etc/machine-id").map(BufWriter::new)?;

    // Generate machine-id(5) contents.
    #[expect(clippy::disallowed_methods)]
    let mut machine_id = env::var(ENV_ID).expect("BUG: SYD_ID environment variable isn't set!");
    machine_id.truncate(32);
    machine_id.push('\n');

    // Write file contents, retrying on interrupts.
    mfd.write_all(machine_id.as_bytes())
        .map_err(|err| err2no(&err))?;
    // into_inner fails on flush errors.
    let mut mfd = mfd.into_inner().or(Err(Errno::EIO))?;

    // Rewind file offset and seal to deny further writes.
    mfd.rewind().or(Err(Errno::EIO))?;
    seal_memfd_all(&mfd)?;

    Ok(mfd)
}

fn do_open_proc_version(request: &UNotifyEventRequest) -> Result<SafeOwnedFd, Errno> {
    // Open a memory fd to be sealed for write.
    let mut mfd = do_open_memfd(c"syd/proc/version").map(BufWriter::new)?;

    // Read UtsName using uname(2) syscall.
    //
    // Syscall is confined with syscall argument cookies.
    let mut utsname = safe_uname()?;

    // Mask utsname using the sandbox.
    let sandbox = request.get_sandbox();
    sandbox.mask_uname(&mut utsname);
    drop(sandbox); // release the read-lock.

    // Write the utsname's Display into file, retry on interrupts.
    let utsname = utsname.to_string();
    mfd.write_all(utsname.as_bytes())
        .map_err(|err| err2no(&err))?;
    // into_inner fails on flush errors.
    let mut mfd = mfd.into_inner().or(Err(Errno::EIO))?;

    // Rewind file offset and seal to deny further writes.
    mfd.rewind().or(Err(Errno::EIO))?;
    seal_memfd_all(&mfd)?;

    Ok(mfd)
}

fn do_open_proc_osrelease() -> Result<SafeOwnedFd, Errno> {
    // Open a memory fd to be sealed for write.
    let mut mfd = do_open_memfd(c"syd/proc/sys/kernel/osrelease").map(BufWriter::new)?;

    // Read static release string.
    let release = Sandbox::os_release();

    // Write release string avoiding interrupts.
    // End it with a newline.
    mfd.write_all(release.as_bytes())
        .map_err(|err| err2no(&err))?;
    mfd.write_all(b"\n").map_err(|err| err2no(&err))?;
    // into_inner fails on flush errors.
    let mut mfd = mfd.into_inner().or(Err(Errno::EIO))?;

    // Rewind file offset and seal to deny further writes.
    mfd.rewind().or(Err(Errno::EIO))?;
    seal_memfd_all(&mfd)?;

    Ok(mfd)
}

fn do_mask_proc_pid_status(
    fd: SafeOwnedFd,
    pid: Pid,
    path: CanonicalPath,
) -> Result<SafeOwnedFd, Errno> {
    // Prepare the name of the memfd for identification.
    // Undo /proc/self -> /proc/$pid.
    let mut path = path.take();
    if path.starts_with(b"/proc/self/") {
        let mut pfd = XPathBuf::from("/proc");
        pfd.push_pid(pid);
        path.replace_prefix(b"/proc/self", pfd.as_bytes())?;
    }
    path.replace_prefix(b"/", b"syd/")?;

    // Open a memory fd to be sealed for write.
    let mut mfd = path.with_nix_path(do_open_memfd)??;

    // Filter proc_pid_status(5) into the memory fd.
    mask_proc_pid_status(fd, &mfd)?;

    // Rewind file offset and seal to deny further writes.
    mfd.rewind().or(Err(Errno::EIO))?;
    seal_memfd_all(&mfd)?;

    Ok(mfd)
}

// Open a memory fd to be sealed for write.
// Memory fd is exec-sealed on Linux>=6.3.
fn do_open_memfd(name: &CStr) -> Result<SafeOwnedFd, Errno> {
    safe_memfd_create(name, *SAFE_MFD_FLAGS)
}

fn to_mode(arg: u64, flags: OFlag, ignore: bool) -> Result<Mode, Errno> {
    if flags.contains(OFlag::O_CREAT) || flags.contains(OFlag::O_TMPFILE) {
        if ignore {
            // Strip undefined/invalid mode.
            // Used by open, openat, and creat.
            Ok(crate::kernel::to_mode(arg))
        } else {
            // Reject undefined/invalid mode.
            // Used by openat2.
            crate::kernel::to_mode2(arg)
        }
    } else if !ignore && arg != 0 {
        // mode argument must be zero without creation flags for openat2.
        Err(Errno::EINVAL)
    } else {
        // mode argument is ignored without creation flags.
        // glibc sets it to 0, musl does not. Both are valid behaviour.
        Ok(Mode::empty())
    }
}

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

    #[test]
    fn test_to_oflag_0() {
        let flags = to_oflag(libc::O_RDONLY as u64, true).unwrap();
        assert!(flags.contains(OFlag::O_RDONLY));
    }

    #[test]
    fn test_to_oflag_1() {
        let flags = to_oflag(libc::O_WRONLY as u64, true).unwrap();
        assert!(flags.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_to_oflag_2() {
        let flags = to_oflag(libc::O_RDWR as u64, true).unwrap();
        assert!(flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_to_oflag_3() {
        let flags = to_oflag((libc::O_CREAT | libc::O_WRONLY) as u64, true).unwrap();
        assert!(flags.contains(OFlag::O_CREAT));
        assert!(flags.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_to_oflag_4() {
        let flags = to_oflag((libc::O_CREAT | libc::O_EXCL | libc::O_WRONLY) as u64, true).unwrap();
        assert!(flags.contains(OFlag::O_CREAT));
        assert!(flags.contains(OFlag::O_EXCL));
        assert!(flags.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_to_oflag_5() {
        let flags = to_oflag(
            (libc::O_CREAT | libc::O_TRUNC | libc::O_WRONLY) as u64,
            true,
        )
        .unwrap();
        assert!(flags.contains(OFlag::O_CREAT));
        assert!(flags.contains(OFlag::O_TRUNC));
        assert!(flags.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_to_oflag_6() {
        let flags = to_oflag(libc::O_PATH as u64, true).unwrap();
        assert!(flags.contains(OFlag::O_PATH));
    }

    #[test]
    fn test_to_oflag_7() {
        let flags = to_oflag(
            (libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW) as u64,
            true,
        )
        .unwrap();
        assert!(flags.contains(OFlag::O_PATH));
        assert!(flags.contains(OFlag::O_DIRECTORY));
        assert!(flags.contains(OFlag::O_NOFOLLOW));
    }

    #[test]
    fn test_to_oflag_8() {
        let flags = to_oflag((libc::O_PATH | libc::O_RDWR) as u64, true).unwrap();
        assert!(flags.contains(OFlag::O_PATH));
        assert!(!flags.contains(OFlag::O_RDWR));
    }

    #[test]
    fn test_to_oflag_9() {
        let flags = to_oflag((libc::O_PATH | libc::O_CLOEXEC) as u64, false).unwrap();
        assert!(flags.contains(OFlag::O_PATH));
        assert!(flags.contains(OFlag::O_CLOEXEC));
    }

    #[test]
    fn test_to_oflag_10() {
        let err = to_oflag((libc::O_PATH | libc::O_RDWR) as u64, false).unwrap_err();
        assert_eq!(err, Errno::EINVAL);
    }

    #[test]
    fn test_to_oflag_11() {
        let err = to_oflag((libc::O_PATH | libc::O_CREAT) as u64, false).unwrap_err();
        assert_eq!(err, Errno::EINVAL);
    }

    #[test]
    fn test_to_oflag_12() {
        let flags = to_oflag((libc::O_CREAT | libc::O_WRONLY) as u64, false).unwrap();
        assert!(flags.contains(OFlag::O_CREAT));
        assert!(flags.contains(OFlag::O_WRONLY));
    }

    #[test]
    fn test_to_oflag_13() {
        let huge: u64 = 1u64 << 40;
        let err = to_oflag(huge, false).unwrap_err();
        assert_eq!(err, Errno::EINVAL);
    }

    #[test]
    fn test_to_oflag_14() {
        let huge: u64 = 1u64 << 40;
        let flags = to_oflag(huge, true).unwrap();
        assert_eq!(flags & OFlag::all(), OFlag::empty());
    }

    #[test]
    fn test_to_oflag_15() {
        let flags = to_oflag(libc::O_RDONLY as u64, false).unwrap();
        assert!(flags.contains(OFlag::O_RDONLY));
    }

    #[test]
    fn test_to_oflag_16() {
        let bogus = 1 << 30;
        let err = to_oflag(bogus as u64, false).unwrap_err();
        assert_eq!(err, Errno::EINVAL);
    }

    #[test]
    fn test_to_oflag_17() {
        let bogus = 1 << 30;
        let flags = to_oflag(bogus as u64, true).unwrap();
        assert_eq!(flags & OFlag::from_bits_retain(bogus), OFlag::empty());
    }

    #[test]
    fn test_to_oflag_18() {
        let arg = (libc::O_PATH as u64) | (O_LARGEFILE.bits() as u64);
        assert_eq!(to_oflag(arg, false), Err(Errno::EINVAL));
    }

    #[test]
    fn test_to_oflag_19() {
        let arg = (libc::O_PATH as u64) | (O_LARGEFILE.bits() as u64);
        let flags = to_oflag(arg, true).unwrap();
        assert!(flags.contains(OFlag::O_PATH));
        assert!(!flags.intersects(O_LARGEFILE));
    }

    #[test]
    fn test_to_mode_0() {
        let mode = to_mode(0o644, OFlag::O_CREAT, true).unwrap();
        assert_eq!(mode, Mode::from_bits(0o644).unwrap());
    }

    #[test]
    fn test_to_mode_1() {
        let mode = to_mode(0o644, OFlag::O_CREAT, false).unwrap();
        assert_eq!(mode, Mode::from_bits(0o644).unwrap());
    }

    #[test]
    fn test_to_mode_2() {
        let mode = to_mode(0o777, OFlag::O_RDONLY, true).unwrap();
        assert_eq!(mode, Mode::empty());
    }

    #[test]
    fn test_to_mode_3() {
        let err = to_mode(0o777, OFlag::O_RDONLY, false).unwrap_err();
        assert_eq!(err, Errno::EINVAL);
    }

    #[test]
    fn test_to_mode_4() {
        let mode = to_mode(0, OFlag::O_RDONLY, false).unwrap();
        assert_eq!(mode, Mode::empty());
    }

    #[test]
    fn test_to_mode_5() {
        let mode = to_mode(0o755, OFlag::O_TMPFILE, true).unwrap();
        assert_eq!(mode, Mode::from_bits(0o755).unwrap());
    }

    #[test]
    fn test_to_mode_6() {
        let mode = to_mode(0o755, OFlag::O_TMPFILE, false).unwrap();
        assert_eq!(mode, Mode::from_bits(0o755).unwrap());
    }

    #[test]
    fn test_to_mode_7() {
        let err = to_mode(u64::MAX, OFlag::O_CREAT, false).unwrap_err();
        assert_eq!(err, Errno::EINVAL);
    }

    #[test]
    fn test_to_mode_8() {
        let mode = to_mode(u64::MAX, OFlag::O_CREAT, true).unwrap();
        assert!(mode.bits() <= 0o7777);
    }

    #[test]
    fn test_to_mode_9() {
        let mode = to_mode(0, OFlag::O_CREAT, true).unwrap();
        assert_eq!(mode, Mode::empty());
    }

    #[test]
    fn test_to_mode_10() {
        let mode = to_mode(0, OFlag::O_CREAT, false).unwrap();
        assert_eq!(mode, Mode::empty());
    }
}