summaryrefslogtreecommitdiffstats
path: root/security/sandbox/linux/SandboxFilter.cpp
blob: de4119f4209980af32aef10c6c5842de4e144ead (plain)
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "SandboxFilter.h"
#include "SandboxFilterUtil.h"

#include "Sandbox.h"  // for ContentProcessSandboxParams
#include "SandboxBrokerClient.h"
#include "SandboxInfo.h"
#include "SandboxInternal.h"
#include "SandboxLogging.h"
#ifdef MOZ_GMP_SANDBOX
#include "SandboxOpenedFiles.h"
#endif
#include "mozilla/Move.h"
#include "mozilla/PodOperations.h"
#include "mozilla/TemplateLib.h"
#include "mozilla/UniquePtr.h"
#include "prenv.h"

#include <errno.h>
#include <fcntl.h>
#include <linux/ioctl.h>
#include <linux/ipc.h>
#include <linux/net.h>
#include <linux/prctl.h>
#include <linux/sched.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/un.h>
#include <sys/utsname.h>
#include <time.h>
#include <unistd.h>
#include <vector>
#include <algorithm>

#include "sandbox/linux/bpf_dsl/bpf_dsl.h"
#include "sandbox/linux/system_headers/linux_seccomp.h"
#include "sandbox/linux/system_headers/linux_syscalls.h"

using namespace sandbox::bpf_dsl;
#define CASES SANDBOX_BPF_DSL_CASES

// Fill in defines in case of old headers.
// (Warning: these are wrong on PA-RISC.)
#ifndef MADV_HUGEPAGE
#define MADV_HUGEPAGE 14
#endif
#ifndef MADV_NOHUGEPAGE
#define MADV_NOHUGEPAGE 15
#endif
#ifndef MADV_DONTDUMP
#define MADV_DONTDUMP 16
#endif

// Added in Linux 4.5; see bug 1303813.
#ifndef MADV_FREE
#define MADV_FREE 8
#endif

#ifndef PR_SET_PTRACER
#define PR_SET_PTRACER 0x59616d61
#endif

// The headers define O_LARGEFILE as 0 on x86_64, but we need the
// actual value because it shows up in file flags.
#define O_LARGEFILE_REAL 00100000

// To avoid visual confusion between "ifdef ANDROID" and "ifndef ANDROID":
#ifndef ANDROID
#define DESKTOP
#endif

// This file defines the seccomp-bpf system call filter policies.
// See also SandboxFilterUtil.h, for the CASES_FOR_* macros and
// SandboxFilterBase::Evaluate{Socket,Ipc}Call.
//
// One important difference from how Chromium bpf_dsl filters are
// normally interpreted: returning -ENOSYS from a Trap() handler
// indicates an unexpected system call; SigSysHandler() in Sandbox.cpp
// will detect this, request a crash dump, and terminate the process.
// This does not apply to using Error(ENOSYS) in the policy, so that
// can be used if returning an actual ENOSYS is needed.

namespace mozilla {

// This class whitelists everything used by the sandbox itself, by the
// core IPC code, by the crash reporter, or other core code.
class SandboxPolicyCommon : public SandboxPolicyBase {
 protected:
  typedef const sandbox::arch_seccomp_data& ArgsRef;

  static intptr_t BlockedSyscallTrap(ArgsRef aArgs, void* aux) {
    MOZ_ASSERT(!aux);
    return -ENOSYS;
  }

  // Convert Unix-style "return -1 and set errno" APIs back into the
  // Linux ABI "return -err" style.
  static intptr_t ConvertError(long rv) { return rv < 0 ? -errno : rv; }

  template <typename... Args>
  static intptr_t DoSyscall(long nr, Args... args) {
    static_assert(tl::And<(sizeof(Args) <= sizeof(void*))...>::value,
                  "each syscall arg is at most one word");
    return ConvertError(syscall(nr, args...));
  }

 private:
  // Bug 1093893: Translate tkill to tgkill for pthread_kill; fixed in
  // bionic commit 10c8ce59a (in JB and up; API level 16 = Android 4.1).
  // Bug 1376653: musl also needs this, and security-wise it's harmless.
  static intptr_t TKillCompatTrap(ArgsRef aArgs, void* aux) {
    auto tid = static_cast<pid_t>(aArgs.args[0]);
    auto sig = static_cast<int>(aArgs.args[1]);
    return DoSyscall(__NR_tgkill, getpid(), tid, sig);
  }

  static intptr_t SetNoNewPrivsTrap(ArgsRef& aArgs, void* aux) {
    if (gSetSandboxFilter == nullptr) {
      // Called after BroadcastSetThreadSandbox finished, therefore
      // not our doing and not expected.
      return BlockedSyscallTrap(aArgs, nullptr);
    }
    // Signal that the filter is already in place.
    return -ETXTBSY;
  }

 public:
  ResultExpr InvalidSyscall() const override {
    return Trap(BlockedSyscallTrap, nullptr);
  }

  virtual ResultExpr ClonePolicy(ResultExpr failPolicy) const {
    // Allow use for simple thread creation (pthread_create) only.

    // WARNING: s390 and cris pass the flags in the second arg -- see
    // CLONE_BACKWARDS2 in arch/Kconfig in the kernel source -- but we
    // don't support seccomp-bpf on those archs yet.
    Arg<int> flags(0);

    // The exact flags used can vary.  CLONE_DETACHED is used by musl
    // and by old versions of Android (<= JB 4.2), but it's been
    // ignored by the kernel since the beginning of the Git history.
    //
    // If we ever need to support Android <= KK 4.4 again, SETTLS
    // and the *TID flags will need to be made optional.
    static const int flags_required =
        CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD |
        CLONE_SYSVSEM | CLONE_SETTLS | CLONE_PARENT_SETTID |
        CLONE_CHILD_CLEARTID;
    static const int flags_optional = CLONE_DETACHED;

    return If((flags & ~flags_optional) == flags_required, Allow())
        .Else(failPolicy);
  }

  virtual ResultExpr PrctlPolicy() const {
    // Note: this will probably need PR_SET_VMA if/when it's used on
    // Android without being overridden by an allow-all policy, and
    // the constant will need to be defined locally.
    Arg<int> op(0);
    return Switch(op)
        .CASES((PR_GET_SECCOMP,   // BroadcastSetThreadSandbox, etc.
                PR_SET_NAME,      // Thread creation
                PR_SET_DUMPABLE,  // Crash reporting
                PR_SET_PTRACER),  // Debug-mode crash handling
               Allow())
        .Default(InvalidSyscall());
  }

  Maybe<ResultExpr> EvaluateSocketCall(int aCall,
                                       bool aHasArgs) const override {
    switch (aCall) {
      case SYS_RECVMSG:
      case SYS_SENDMSG:
        return Some(Allow());
      default:
        return Nothing();
    }
  }

  ResultExpr EvaluateSyscall(int sysno) const override {
    switch (sysno) {
        // Timekeeping
      case __NR_clock_gettime: {
        Arg<clockid_t> clk_id(0);
        return If(clk_id == CLOCK_MONOTONIC, Allow())
#ifdef CLOCK_MONOTONIC_COARSE
            // Used by SandboxReporter, among other things.
            .ElseIf(clk_id == CLOCK_MONOTONIC_COARSE, Allow())
#endif
            .ElseIf(clk_id == CLOCK_PROCESS_CPUTIME_ID, Allow())
            .ElseIf(clk_id == CLOCK_REALTIME, Allow())
#ifdef CLOCK_REALTIME_COARSE
            .ElseIf(clk_id == CLOCK_REALTIME_COARSE, Allow())
#endif
            .ElseIf(clk_id == CLOCK_THREAD_CPUTIME_ID, Allow())
            .Else(InvalidSyscall());
      }
      case __NR_gettimeofday:
#ifdef __NR_time
      case __NR_time:
#endif
      case __NR_nanosleep:
        return Allow();

        // Thread synchronization
      case __NR_futex:
        // FIXME: This could be more restrictive....
        return Allow();

        // Asynchronous I/O
      case __NR_epoll_create1:
      case __NR_epoll_create:
      case __NR_epoll_wait:
      case __NR_epoll_pwait:
      case __NR_epoll_ctl:
      case __NR_ppoll:
      case __NR_poll:
        return Allow();

        // Used when requesting a crash dump.
      case __NR_pipe:
        return Allow();

        // Metadata of opened files
      CASES_FOR_fstat:
        return Allow();

        // Simple I/O
      case __NR_write:
      case __NR_read:
      case __NR_readv:
      case __NR_writev:  // see SandboxLogging.cpp
      CASES_FOR_lseek:
        return Allow();

        // Memory mapping
      CASES_FOR_mmap:
      case __NR_munmap:
        return Allow();

        // Signal handling
#if defined(ANDROID) || defined(MOZ_ASAN)
      case __NR_sigaltstack:
#endif
      CASES_FOR_sigreturn:
      CASES_FOR_sigprocmask:
      CASES_FOR_sigaction:
        return Allow();

        // Send signals within the process (raise(), profiling, etc.)
      case __NR_tgkill: {
        Arg<pid_t> tgid(0);
        return If(tgid == getpid(), Allow()).Else(InvalidSyscall());
      }

        // Polyfill with tgkill; see above.
      case __NR_tkill:
        return Trap(TKillCompatTrap, nullptr);

        // Yield
      case __NR_sched_yield:
        return Allow();

        // Thread creation.
      case __NR_clone:
        return ClonePolicy(InvalidSyscall());

        // More thread creation.
#ifdef __NR_set_robust_list
      case __NR_set_robust_list:
        return Allow();
#endif
#ifdef ANDROID
      case __NR_set_tid_address:
        return Allow();
#endif

        // prctl
      case __NR_prctl: {
        if (SandboxInfo::Get().Test(SandboxInfo::kHasSeccompTSync)) {
          return PrctlPolicy();
        }

        Arg<int> option(0);
        return If(option == PR_SET_NO_NEW_PRIVS,
                  Trap(SetNoNewPrivsTrap, nullptr))
            .Else(PrctlPolicy());
      }

        // NSPR can call this when creating a thread, but it will accept a
        // polite "no".
      case __NR_getpriority:
        // But if thread creation races with sandbox startup, that call
        // could succeed, and then we get one of these:
      case __NR_setpriority:
        return Error(EACCES);

        // Stack bounds are obtained via pthread_getattr_np, which calls
        // this but doesn't actually need it:
      case __NR_sched_getaffinity:
        return Error(ENOSYS);

        // Read own pid/tid.
      case __NR_getpid:
      case __NR_gettid:
        return Allow();

        // Discard capabilities
      case __NR_close:
        return Allow();

        // Machine-dependent stuff
#ifdef __arm__
      case __ARM_NR_breakpoint:
      case __ARM_NR_cacheflush:
      case __ARM_NR_usr26:  // FIXME: do we actually need this?
      case __ARM_NR_usr32:
      case __ARM_NR_set_tls:
        return Allow();
#endif

        // Needed when being debugged:
      case __NR_restart_syscall:
        return Allow();

        // Terminate threads or the process
      case __NR_exit:
      case __NR_exit_group:
        return Allow();

      case __NR_getrandom:
        return Allow();

#ifdef MOZ_ASAN
        // ASAN's error reporter wants to know if stderr is a tty.
      case __NR_ioctl: {
        Arg<int> fd(0);
        return If(fd == STDERR_FILENO, Error(ENOTTY)).Else(InvalidSyscall());
      }

        // ...and before compiler-rt r209773, it will call readlink on
        // /proc/self/exe and use the cached value only if that fails:
      case __NR_readlink:
      case __NR_readlinkat:
        return Error(ENOENT);

        // ...and if it found an external symbolizer, it will try to run it:
        // (See also bug 1081242 comment #7.)
      CASES_FOR_stat:
        return Error(ENOENT);
#endif

      default:
        return SandboxPolicyBase::EvaluateSyscall(sysno);
    }
  }
};

// The process-type-specific syscall rules start here:

#ifdef MOZ_CONTENT_SANDBOX
// The seccomp-bpf filter for content processes is not a true sandbox
// on its own; its purpose is attack surface reduction and syscall
// interception in support of a semantic sandboxing layer.  On B2G
// this is the Android process permission model; on desktop,
// namespaces and chroot() will be used.
class ContentSandboxPolicy : public SandboxPolicyCommon {
 private:
  SandboxBrokerClient* mBroker;
  ContentProcessSandboxParams mParams;
  bool mAllowSysV;

  bool BelowLevel(int aLevel) const { return mParams.mLevel < aLevel; }
  ResultExpr AllowBelowLevel(int aLevel, ResultExpr aOrElse) const {
    return BelowLevel(aLevel) ? Allow() : Move(aOrElse);
  }
  ResultExpr AllowBelowLevel(int aLevel) const {
    return AllowBelowLevel(aLevel, InvalidSyscall());
  }

  // Returns true if the running kernel supports separate syscalls for
  // socket operations, or false if it supports only socketcall(2).
  static bool HasSeparateSocketCalls() {
#ifdef __NR_socket
  // If there's no socketcall, then obviously there are separate syscalls.
#ifdef __NR_socketcall
    int fd = syscall(__NR_socket, AF_LOCAL, SOCK_STREAM, 0);
    if (fd < 0) {
      MOZ_DIAGNOSTIC_ASSERT(errno == ENOSYS);
      return false;
    }
    close(fd);
#endif  // __NR_socketcall
    return true;
#else   // ifndef __NR_socket
    return false;
#endif  // __NR_socket
  }

    // Trap handlers for filesystem brokering.
    // (The amount of code duplication here could be improved....)
#ifdef __NR_open
  static intptr_t OpenTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    auto flags = static_cast<int>(aArgs.args[1]);
    return broker->Open(path, flags);
  }
#endif

  static intptr_t OpenAtTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto fd = static_cast<int>(aArgs.args[0]);
    auto path = reinterpret_cast<const char*>(aArgs.args[1]);
    auto flags = static_cast<int>(aArgs.args[2]);
    if (fd != AT_FDCWD && path[0] != '/') {
      SANDBOX_LOG_ERROR("unsupported fd-relative openat(%d, \"%s\", 0%o)", fd,
                        path, flags);
      return BlockedSyscallTrap(aArgs, nullptr);
    }
    return broker->Open(path, flags);
  }

#ifdef __NR_access
  static intptr_t AccessTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    auto mode = static_cast<int>(aArgs.args[1]);
    return broker->Access(path, mode);
  }
#endif

  static intptr_t AccessAtTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto fd = static_cast<int>(aArgs.args[0]);
    auto path = reinterpret_cast<const char*>(aArgs.args[1]);
    auto mode = static_cast<int>(aArgs.args[2]);
    // Linux's faccessat syscall has no "flags" argument.  Attempting
    // to handle the flags != 0 case is left to userspace; this is
    // impossible to do correctly in all cases, but that's not our
    // problem.
    if (fd != AT_FDCWD && path[0] != '/') {
      SANDBOX_LOG_ERROR("unsupported fd-relative faccessat(%d, \"%s\", %d)", fd,
                        path, mode);
      return BlockedSyscallTrap(aArgs, nullptr);
    }
    return broker->Access(path, mode);
  }

  static intptr_t StatTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    auto buf = reinterpret_cast<statstruct*>(aArgs.args[1]);
    return broker->Stat(path, buf);
  }

  static intptr_t LStatTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    auto buf = reinterpret_cast<statstruct*>(aArgs.args[1]);
    return broker->LStat(path, buf);
  }

  static intptr_t StatAtTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto fd = static_cast<int>(aArgs.args[0]);
    auto path = reinterpret_cast<const char*>(aArgs.args[1]);
    auto buf = reinterpret_cast<statstruct*>(aArgs.args[2]);
    auto flags = static_cast<int>(aArgs.args[3]);
    if (fd != AT_FDCWD && path[0] != '/') {
      SANDBOX_LOG_ERROR("unsupported fd-relative fstatat(%d, \"%s\", %p, %d)",
                        fd, path, buf, flags);
      return BlockedSyscallTrap(aArgs, nullptr);
    }
    if ((flags & ~AT_SYMLINK_NOFOLLOW) != 0) {
      SANDBOX_LOG_ERROR("unsupported flags %d in fstatat(%d, \"%s\", %p, %d)",
                        (flags & ~AT_SYMLINK_NOFOLLOW), fd, path, buf, flags);
      return BlockedSyscallTrap(aArgs, nullptr);
    }
    return (flags & AT_SYMLINK_NOFOLLOW) == 0 ? broker->Stat(path, buf)
                                              : broker->LStat(path, buf);
  }

  static intptr_t ChmodTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    auto mode = static_cast<mode_t>(aArgs.args[1]);
    return broker->Chmod(path, mode);
  }

  static intptr_t LinkTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    auto path2 = reinterpret_cast<const char*>(aArgs.args[1]);
    return broker->Link(path, path2);
  }

  static intptr_t SymlinkTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    auto path2 = reinterpret_cast<const char*>(aArgs.args[1]);
    return broker->Symlink(path, path2);
  }

  static intptr_t RenameTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    auto path2 = reinterpret_cast<const char*>(aArgs.args[1]);
    return broker->Rename(path, path2);
  }

  static intptr_t MkdirTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    auto mode = static_cast<mode_t>(aArgs.args[1]);
    return broker->Mkdir(path, mode);
  }

  static intptr_t RmdirTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    return broker->Rmdir(path);
  }

  static intptr_t UnlinkTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    return broker->Unlink(path);
  }

  static intptr_t ReadlinkTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    auto buf = reinterpret_cast<char*>(aArgs.args[1]);
    auto size = static_cast<size_t>(aArgs.args[2]);
    return broker->Readlink(path, buf, size);
  }

  static intptr_t ReadlinkAtTrap(ArgsRef aArgs, void* aux) {
    auto broker = static_cast<SandboxBrokerClient*>(aux);
    auto fd = static_cast<int>(aArgs.args[0]);
    auto path = reinterpret_cast<const char*>(aArgs.args[1]);
    auto buf = reinterpret_cast<char*>(aArgs.args[2]);
    auto size = static_cast<size_t>(aArgs.args[3]);
    if (fd != AT_FDCWD && path[0] != '/') {
      SANDBOX_LOG_ERROR("unsupported fd-relative readlinkat(%d, %s, %p, %u)",
                        fd, path, buf, size);
      return BlockedSyscallTrap(aArgs, nullptr);
    }
    return broker->Readlink(path, buf, size);
  }

  static intptr_t GetPPidTrap(ArgsRef aArgs, void* aux) {
    // In a pid namespace, getppid() will return 0. We will return 0 instead
    // of the real parent pid to see what breaks when we introduce the
    // pid namespace (Bug 1151624).
    return 0;
  }

  static intptr_t SocketpairDatagramTrap(ArgsRef aArgs, void* aux) {
    auto fds = reinterpret_cast<int*>(aArgs.args[3]);
    // Return sequential packet sockets instead of the expected
    // datagram sockets; see bug 1355274 for details.
    return ConvertError(socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds));
  }

  static intptr_t SocketpairUnpackTrap(ArgsRef aArgs, void* aux) {
#ifdef __NR_socketpair
    auto argsPtr = reinterpret_cast<unsigned long*>(aArgs.args[1]);
    return DoSyscall(__NR_socketpair, argsPtr[0], argsPtr[1], argsPtr[2],
                     argsPtr[3]);
#else
    MOZ_CRASH("unreachable?");
    return -ENOSYS;
#endif
  }

  static intptr_t StatFsTrap(ArgsRef aArgs, void* aux) {
    // Warning: the kernel interface is not the C interface.  The
    // structs are different (<asm/statfs.h> vs. <sys/statfs.h>), and
    // the statfs64 version takes an additional size parameter.
    auto path = reinterpret_cast<const char*>(aArgs.args[0]);
    int fd = open(path, O_RDONLY | O_LARGEFILE);
    if (fd < 0) {
      return -errno;
    }

    intptr_t rv;
    switch (aArgs.nr) {
      case __NR_statfs: {
        auto buf = reinterpret_cast<void*>(aArgs.args[1]);
        rv = DoSyscall(__NR_fstatfs, fd, buf);
        break;
      }
#ifdef __NR_statfs64
      case __NR_statfs64: {
        auto sz = static_cast<size_t>(aArgs.args[1]);
        auto buf = reinterpret_cast<void*>(aArgs.args[2]);
        rv = DoSyscall(__NR_fstatfs64, fd, sz, buf);
        break;
      }
#endif
      default:
        MOZ_ASSERT(false);
        rv = -ENOSYS;
    }

    close(fd);
    return rv;
  }

  // This just needs to return something to stand in for the
  // unconnected socket until ConnectTrap, below, and keep track of
  // the socket type somehow.  Half a socketpair *is* a socket, so it
  // should result in minimal confusion in the caller.
  static intptr_t FakeSocketTrapCommon(int domain, int type, int protocol) {
    int fds[2];
    // X11 client libs will still try to getaddrinfo() even for a
    // local connection.  Also, WebRTC still has vestigial network
    // code trying to do things in the content process.  Politely tell
    // them no.
    if (domain != AF_UNIX) {
      return -EAFNOSUPPORT;
    }
    if (socketpair(domain, type, protocol, fds) != 0) {
      return -errno;
    }
    close(fds[1]);
    return fds[0];
  }

  static intptr_t FakeSocketTrap(ArgsRef aArgs, void* aux) {
    return FakeSocketTrapCommon(static_cast<int>(aArgs.args[0]),
                                static_cast<int>(aArgs.args[1]),
                                static_cast<int>(aArgs.args[2]));
  }

  static intptr_t FakeSocketTrapLegacy(ArgsRef aArgs, void* aux) {
    const auto innerArgs = reinterpret_cast<unsigned long*>(aArgs.args[1]);

    return FakeSocketTrapCommon(static_cast<int>(innerArgs[0]),
                                static_cast<int>(innerArgs[1]),
                                static_cast<int>(innerArgs[2]));
  }

  static Maybe<int> DoGetSockOpt(int fd, int optname) {
    int optval;
    socklen_t optlen = sizeof(optval);

    if (getsockopt(fd, SOL_SOCKET, optname, &optval, &optlen) != 0) {
      return Nothing();
    }
    MOZ_RELEASE_ASSERT(static_cast<size_t>(optlen) == sizeof(optval));
    return Some(optval);
  }

  // Substitute the newly connected socket from the broker for the
  // original socket.  This is meant to be used on a fd from
  // FakeSocketTrap, above, but it should also work to simulate
  // re-connect()ing a real connected socket.
  //
  // Warning: This isn't quite right if the socket is dup()ed, because
  // other duplicates will still be the original socket, but hopefully
  // nothing we're dealing with does that.
  static intptr_t ConnectTrapCommon(SandboxBrokerClient* aBroker, int aFd,
                                    const struct sockaddr_un* aAddr,
                                    socklen_t aLen) {
    if (aFd < 0) {
      return -EBADF;
    }
    const auto maybeDomain = DoGetSockOpt(aFd, SO_DOMAIN);
    if (!maybeDomain) {
      return -errno;
    }
    if (*maybeDomain != AF_UNIX) {
      return -EAFNOSUPPORT;
    }
    const auto maybeType = DoGetSockOpt(aFd, SO_TYPE);
    if (!maybeType) {
      return -errno;
    }
    const int oldFlags = fcntl(aFd, F_GETFL);
    if (oldFlags == -1) {
      return -errno;
    }
    const int newFd = aBroker->Connect(aAddr, aLen, *maybeType);
    if (newFd < 0) {
      return newFd;
    }
    // Copy over the nonblocking flag.  The connect() won't be
    // nonblocking in that case, but that shouldn't matter for
    // AF_UNIX.  The other fcntl-settable flags are either irrelevant
    // for sockets (e.g., O_APPEND) or would be blocked by this
    // seccomp-bpf policy, so they're ignored.
    if (fcntl(newFd, F_SETFL, oldFlags & O_NONBLOCK) != 0) {
      close(newFd);
      return -errno;
    }
    if (dup2(newFd, aFd) < 0) {
      close(newFd);
      return -errno;
    }
    close(newFd);
    return 0;
  }

  static intptr_t ConnectTrap(ArgsRef aArgs, void* aux) {
    typedef const struct sockaddr_un* AddrPtr;

    return ConnectTrapCommon(static_cast<SandboxBrokerClient*>(aux),
                             static_cast<int>(aArgs.args[0]),
                             reinterpret_cast<AddrPtr>(aArgs.args[1]),
                             static_cast<socklen_t>(aArgs.args[2]));
  }

  static intptr_t ConnectTrapLegacy(ArgsRef aArgs, void* aux) {
    const auto innerArgs = reinterpret_cast<unsigned long*>(aArgs.args[1]);
    typedef const struct sockaddr_un* AddrPtr;

    return ConnectTrapCommon(static_cast<SandboxBrokerClient*>(aux),
                             static_cast<int>(innerArgs[0]),
                             reinterpret_cast<AddrPtr>(innerArgs[1]),
                             static_cast<socklen_t>(innerArgs[2]));
  }

 public:
  ContentSandboxPolicy(SandboxBrokerClient* aBroker,
                       ContentProcessSandboxParams&& aParams)
      : mBroker(aBroker),
        mParams(Move(aParams)),
        mAllowSysV(PR_GetEnv("MOZ_SANDBOX_ALLOW_SYSV") != nullptr) {}

  ~ContentSandboxPolicy() override = default;

  Maybe<ResultExpr> EvaluateSocketCall(int aCall,
                                       bool aHasArgs) const override {
    switch (aCall) {
      case SYS_RECVFROM:
      case SYS_SENDTO:
      case SYS_SENDMMSG:  // libresolv via libasyncns; see bug 1355274
        return Some(Allow());

      case SYS_SOCKETPAIR: {
        // See bug 1066750.
        if (!aHasArgs) {
          // If this is a socketcall(2) platform, but the kernel also
          // supports separate syscalls (>= 4.2.0), we can unpack the
          // arguments and filter them.
          if (HasSeparateSocketCalls()) {
            return Some(Trap(SocketpairUnpackTrap, nullptr));
          }
          // Otherwise, we can't filter the args if the platform passes
          // them by pointer.
          return Some(Allow());
        }
        Arg<int> domain(0), type(1);
        return Some(
            If(domain == AF_UNIX,
               Switch(type & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
                   .Case(SOCK_STREAM, Allow())
                   .Case(SOCK_SEQPACKET, Allow())
                   .Case(SOCK_DGRAM, Trap(SocketpairDatagramTrap, nullptr))
                   .Default(InvalidSyscall()))
                .Else(InvalidSyscall()));
      }

#ifdef ANDROID
      case SYS_SOCKET:
        return Some(Error(EACCES));
#else  // #ifdef DESKTOP
      case SYS_SOCKET: {
        const auto trapFn = aHasArgs ? FakeSocketTrap : FakeSocketTrapLegacy;
        return Some(AllowBelowLevel(4, Trap(trapFn, nullptr)));
      }
      case SYS_CONNECT: {
        const auto trapFn = aHasArgs ? ConnectTrap : ConnectTrapLegacy;
        return Some(AllowBelowLevel(4, Trap(trapFn, mBroker)));
      }
      case SYS_RECV:
      case SYS_SEND:
      case SYS_GETSOCKOPT:
      case SYS_SETSOCKOPT:
      case SYS_GETSOCKNAME:
      case SYS_GETPEERNAME:
      case SYS_SHUTDOWN:
        return Some(Allow());
#endif
      default:
        return SandboxPolicyCommon::EvaluateSocketCall(aCall, aHasArgs);
    }
  }

#ifdef DESKTOP
  Maybe<ResultExpr> EvaluateIpcCall(int aCall) const override {
    switch (aCall) {
        // These are a problem: SysV IPC follows the Unix "same uid
        // policy" and can't be restricted/brokered like file access.
        // We're not using it directly, but there are some library
        // dependencies that do; see ContentNeedsSysVIPC() in
        // SandboxLaunch.cpp.  Also, Cairo as used by GTK will sometimes
        // try to use MIT-SHM, so shmget() is a non-fatal error.  See
        // also bug 1376910 and bug 1438401.
      case SHMGET:
        return Some(mAllowSysV ? Allow() : Error(EPERM));
      case SHMCTL:
      case SHMAT:
      case SHMDT:
      case SEMGET:
      case SEMCTL:
      case SEMOP:
        if (mAllowSysV) {
          return Some(Allow());
        }
        return SandboxPolicyCommon::EvaluateIpcCall(aCall);
      default:
        return SandboxPolicyCommon::EvaluateIpcCall(aCall);
    }
  }
#endif

#ifdef MOZ_PULSEAUDIO
  ResultExpr PrctlPolicy() const override {
    if (BelowLevel(4)) {
      Arg<int> op(0);
      return If(op == PR_GET_NAME, Allow())
          .Else(SandboxPolicyCommon::PrctlPolicy());
    }
    return SandboxPolicyCommon::PrctlPolicy();
  }
#endif

  ResultExpr EvaluateSyscall(int sysno) const override {
    // Straight allow for anything that got overriden via prefs
    const auto& whitelist = mParams.mSyscallWhitelist;
    if (std::find(whitelist.begin(), whitelist.end(), sysno) !=
        whitelist.end()) {
      if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
        SANDBOX_LOG_ERROR("Allowing syscall nr %d via whitelist", sysno);
      }
      return Allow();
    }
    if (mBroker) {
      // Have broker; route the appropriate syscalls to it.
      switch (sysno) {
        case __NR_open:
          return Trap(OpenTrap, mBroker);
        case __NR_openat:
          return Trap(OpenAtTrap, mBroker);
        case __NR_access:
          return Trap(AccessTrap, mBroker);
        case __NR_faccessat:
          return Trap(AccessAtTrap, mBroker);
        CASES_FOR_stat:
          return Trap(StatTrap, mBroker);
        CASES_FOR_lstat:
          return Trap(LStatTrap, mBroker);
        CASES_FOR_fstatat:
          return Trap(StatAtTrap, mBroker);
        case __NR_chmod:
          return Trap(ChmodTrap, mBroker);
        case __NR_link:
          return Trap(LinkTrap, mBroker);
        case __NR_mkdir:
          return Trap(MkdirTrap, mBroker);
        case __NR_symlink:
          return Trap(SymlinkTrap, mBroker);
        case __NR_rename:
          return Trap(RenameTrap, mBroker);
        case __NR_rmdir:
          return Trap(RmdirTrap, mBroker);
        case __NR_unlink:
          return Trap(UnlinkTrap, mBroker);
        case __NR_readlink:
          return Trap(ReadlinkTrap, mBroker);
        case __NR_readlinkat:
          return Trap(ReadlinkAtTrap, mBroker);
      }
    } else {
      // No broker; allow the syscalls directly.  )-:
      switch (sysno) {
        case __NR_open:
        case __NR_openat:
        case __NR_access:
        case __NR_faccessat:
        CASES_FOR_stat:
        CASES_FOR_lstat:
        CASES_FOR_fstatat:
        case __NR_chmod:
        case __NR_link:
        case __NR_mkdir:
        case __NR_symlink:
        case __NR_rename:
        case __NR_rmdir:
        case __NR_unlink:
        case __NR_readlink:
        case __NR_readlinkat:
          return Allow();
      }
    }

    switch (sysno) {
#ifdef DESKTOP
      case __NR_getppid:
        return Trap(GetPPidTrap, nullptr);

      CASES_FOR_statfs:
        return Trap(StatFsTrap, nullptr);

        // GTK's theme parsing tries to getcwd() while sandboxed, but
        // only during Talos runs.
      case __NR_getcwd:
        return Error(ENOENT);

#ifdef MOZ_PULSEAUDIO
      CASES_FOR_fchown:
      case __NR_fchmod:
        return AllowBelowLevel(4);
#endif
      CASES_FOR_fstatfs:  // fontconfig, pulseaudio, GIO (see also statfs)
      case __NR_flock:    // graphics
        return Allow();

        // Bug 1354731: proprietary GL drivers try to mknod() their devices
#ifdef __NR_mknod
      case __NR_mknod:
#endif
      case __NR_mknodat: {
        Arg<mode_t> mode(sysno == __NR_mknodat ? 2 : 1);
        return If((mode & S_IFMT) == S_IFCHR, Error(EPERM))
            .Else(InvalidSyscall());
      }
        // Bug 1438389: ...and nvidia GL will sometimes try to chown the devices
#ifdef __NR_chown
      case __NR_chown:
#endif
      case __NR_fchownat:
        return Error(EPERM);

        // For ORBit called by GConf (on some systems) to get proxy
        // settings.  Can remove when bug 1325242 happens in some form.
      case __NR_utime:
        return Error(EPERM);
#endif

      CASES_FOR_select:
      case __NR_pselect6:
        return Allow();

      CASES_FOR_getdents:
      CASES_FOR_ftruncate:
      case __NR_writev:
      case __NR_pread64:
#ifdef DESKTOP
      case __NR_pwrite64:
      case __NR_readahead:
#endif
        return Allow();

      case __NR_ioctl: {
#ifdef MOZ_ALSA
        if (BelowLevel(4)) {
          return Allow();
        }
#endif
        static const unsigned long kTypeMask = _IOC_TYPEMASK << _IOC_TYPESHIFT;
        static const unsigned long kTtyIoctls = TIOCSTI & kTypeMask;
        // On some older architectures (but not x86 or ARM), ioctls are
        // assigned type fields differently, and the TIOC/TC/FIO group
        // isn't all the same type.  If/when we support those archs,
        // this would need to be revised (but really this should be a
        // default-deny policy; see below).
        static_assert(kTtyIoctls == (TCSETA & kTypeMask) &&
                          kTtyIoctls == (FIOASYNC & kTypeMask),
                      "tty-related ioctls use the same type");

        Arg<unsigned long> request(1);
        auto shifted_type = request & kTypeMask;

        // Rust's stdlib seems to use FIOCLEX instead of equivalent fcntls.
        return If(request == FIOCLEX, Allow())
            // Rust's stdlib also uses FIONBIO instead of equivalent fcntls.
            .ElseIf(request == FIONBIO, Allow())
            // ffmpeg, and anything else that calls isatty(), will be told
            // that nothing is a typewriter:
            .ElseIf(request == TCGETS, Error(ENOTTY))
            // Allow anything that isn't a tty ioctl, for now; bug 1302711
            // will cover changing this to a default-deny policy.
            .ElseIf(shifted_type != kTtyIoctls, Allow())
            .Else(SandboxPolicyCommon::EvaluateSyscall(sysno));
      }

      CASES_FOR_fcntl : {
        Arg<int> cmd(1);
        Arg<int> flags(2);
        // Typical use of F_SETFL is to modify the flags returned by
        // F_GETFL and write them back, including some flags that
        // F_SETFL ignores.  This is a default-deny policy in case any
        // new SETFL-able flags are added.  (In particular we want to
        // forbid O_ASYNC; see bug 1328896, but also see bug 1408438.)
        static const int ignored_flags =
            O_ACCMODE | O_LARGEFILE_REAL | O_CLOEXEC;
        static const int allowed_flags = ignored_flags | O_APPEND | O_NONBLOCK;
        return Switch(cmd)
            // Close-on-exec is meaningless when execve isn't allowed, but
            // NSPR reads the bit and asserts that it has the expected value.
            .Case(F_GETFD, Allow())
            .Case(
                F_SETFD,
                If((flags & ~FD_CLOEXEC) == 0, Allow()).Else(InvalidSyscall()))
            .Case(F_GETFL, Allow())
            .Case(F_SETFL, If((flags & ~allowed_flags) == 0, Allow())
                               .Else(InvalidSyscall()))
            .Case(F_DUPFD_CLOEXEC, Allow())
            // Nvidia GL and fontconfig (newer versions) use fcntl file locking.
            .Case(F_SETLK, Allow())
#ifdef F_SETLK64
            .Case(F_SETLK64, Allow())
#endif
            // Pulseaudio uses F_SETLKW, as does fontconfig.
            .Case(F_SETLKW, Allow())
#ifdef F_SETLKW64
            .Case(F_SETLKW64, Allow())
#endif
            .Default(SandboxPolicyCommon::EvaluateSyscall(sysno));
      }

      case __NR_mprotect:
      case __NR_brk:
      case __NR_madvise:
        // libc's realloc uses mremap (Bug 1286119); wasm does too (bug
        // 1342385).
      case __NR_mremap:
        return Allow();

      case __NR_sigaltstack:
        return Allow();

#ifdef __NR_set_thread_area
      case __NR_set_thread_area:
        return Allow();
#endif

      case __NR_getrusage:
      case __NR_times:
        return Allow();

      case __NR_dup:
      case __NR_dup2:  // See ConnectTrapCommon
        return Allow();

      CASES_FOR_getuid:
      CASES_FOR_getgid:
      CASES_FOR_geteuid:
      CASES_FOR_getegid:
        return Allow();

      case __NR_fsync:
      case __NR_msync:
        return Allow();

      case __NR_getpriority:
      case __NR_setpriority:
      case __NR_sched_get_priority_min:
      case __NR_sched_get_priority_max:
      case __NR_sched_getscheduler:
      case __NR_sched_setscheduler:
      case __NR_sched_getparam:
      case __NR_sched_setparam:
#ifdef DESKTOP
      case __NR_sched_getaffinity:
#endif
        return Allow();

#ifdef DESKTOP
      case __NR_pipe2:
        return Allow();

      CASES_FOR_getrlimit:
      case __NR_clock_getres:
      CASES_FOR_getresuid:
      CASES_FOR_getresgid:
        return Allow();

      case __NR_prlimit64: {
        // Allow only the getrlimit() use case.  (glibc seems to use
        // only pid 0 to indicate the current process; pid == getpid()
        // is equivalent and could also be allowed if needed.)
        Arg<pid_t> pid(0);
        // This is really a const struct ::rlimit*, but Arg<> doesn't
        // work with pointers, only integer types.
        Arg<uintptr_t> new_limit(2);
        return If(AllOf(pid == 0, new_limit == 0), Allow())
            .Else(InvalidSyscall());
      }

        // PulseAudio calls umask, even though it's unsafe in
        // multithreaded applications.  But, allowing it here doesn't
        // really do anything one way or the other, now that file
        // accesses are brokered to another process.
      case __NR_umask:
        return AllowBelowLevel(4);

      case __NR_kill: {
        if (BelowLevel(4)) {
          Arg<int> sig(1);
          // PulseAudio uses kill(pid, 0) to check if purported owners of
          // shared memory files are still alive; see bug 1397753 for more
          // details.
          return If(sig == 0, Error(EPERM)).Else(InvalidSyscall());
        }
        return InvalidSyscall();
      }

      case __NR_wait4:
#ifdef __NR_waitpid
      case __NR_waitpid:
#endif
        // NSPR will start a thread to wait for child processes even if
        // fork() fails; see bug 227246 and bug 1299581.
        return Error(ECHILD);

      case __NR_eventfd2:
        return Allow();

#ifdef __NR_memfd_create
      case __NR_memfd_create:
        return Allow();
#endif

#ifdef __NR_rt_tgsigqueueinfo
        // Only allow to send signals within the process.
      case __NR_rt_tgsigqueueinfo: {
        Arg<pid_t> tgid(0);
        return If(tgid == getpid(), Allow()).Else(InvalidSyscall());
      }
#endif

      case __NR_mlock:
      case __NR_munlock:
        return Allow();

        // We can't usefully allow fork+exec, even on a temporary basis;
        // the child would inherit the seccomp-bpf policy and almost
        // certainly die from an unexpected SIGSYS.  We also can't have
        // fork() crash, currently, because there are too many system
        // libraries/plugins that try to run commands.  But they can
        // usually do something reasonable on error.
      case __NR_clone:
        return ClonePolicy(Error(EPERM));

#ifdef __NR_fadvise64
      case __NR_fadvise64:
        return Allow();
#endif

#ifdef __NR_fadvise64_64
      case __NR_fadvise64_64:
        return Allow();
#endif

      case __NR_fallocate:
        return Allow();

      case __NR_get_mempolicy:
        return Allow();

#endif  // DESKTOP

#ifdef __NR_getrandom
      case __NR_getrandom:
        return Allow();
#endif

        // nsSystemInfo uses uname (and we cache an instance, so
        // the info remains present even if we block the syscall)
      case __NR_uname:
#ifdef DESKTOP
      case __NR_sysinfo:
#endif
        return Allow();

#ifdef MOZ_JPROF
      case __NR_setitimer:
        return Allow();
#endif  // MOZ_JPROF

      default:
        return SandboxPolicyCommon::EvaluateSyscall(sysno);
    }
  }
};

UniquePtr<sandbox::bpf_dsl::Policy> GetContentSandboxPolicy(
    SandboxBrokerClient* aMaybeBroker, ContentProcessSandboxParams&& aParams) {
  return MakeUnique<ContentSandboxPolicy>(aMaybeBroker, Move(aParams));
}
#endif  // MOZ_CONTENT_SANDBOX

#ifdef MOZ_GMP_SANDBOX
// Unlike for content, the GeckoMediaPlugin seccomp-bpf policy needs
// to be an effective sandbox by itself, because we allow GMP on Linux
// systems where that's the only sandboxing mechanism we can use.
//
// Be especially careful about what this policy allows.
class GMPSandboxPolicy : public SandboxPolicyCommon {
  static intptr_t OpenTrap(const sandbox::arch_seccomp_data& aArgs, void* aux) {
    const auto files = static_cast<const SandboxOpenedFiles*>(aux);
    const char* path;
    int flags;

    switch (aArgs.nr) {
#ifdef __NR_open
      case __NR_open:
        path = reinterpret_cast<const char*>(aArgs.args[0]);
        flags = static_cast<int>(aArgs.args[1]);
        break;
#endif
      case __NR_openat:
        // The path has to be absolute to match the pre-opened file (see
        // assertion in ctor) so the dirfd argument is ignored.
        path = reinterpret_cast<const char*>(aArgs.args[1]);
        flags = static_cast<int>(aArgs.args[2]);
        break;
      default:
        MOZ_CRASH("unexpected syscall number");
    }

    if ((flags & O_ACCMODE) != O_RDONLY) {
      SANDBOX_LOG_ERROR("non-read-only open of file %s attempted (flags=0%o)",
                        path, flags);
      return -EROFS;
    }
    int fd = files->GetDesc(path);
    if (fd < 0) {
      // SandboxOpenedFile::GetDesc already logged about this, if appropriate.
      return -ENOENT;
    }
    return fd;
  }

  static intptr_t SchedTrap(ArgsRef aArgs, void* aux) {
    const pid_t tid = syscall(__NR_gettid);
    if (aArgs.args[0] == static_cast<uint64_t>(tid)) {
      return DoSyscall(aArgs.nr, 0, static_cast<uintptr_t>(aArgs.args[1]),
                       static_cast<uintptr_t>(aArgs.args[2]),
                       static_cast<uintptr_t>(aArgs.args[3]),
                       static_cast<uintptr_t>(aArgs.args[4]),
                       static_cast<uintptr_t>(aArgs.args[5]));
    }
    SANDBOX_LOG_ERROR("unsupported tid in SchedTrap");
    return BlockedSyscallTrap(aArgs, nullptr);
  }

  static intptr_t UnameTrap(const sandbox::arch_seccomp_data& aArgs,
                            void* aux) {
    const auto buf = reinterpret_cast<struct utsname*>(aArgs.args[0]);
    PodZero(buf);
    // The real uname() increases fingerprinting risk for no benefit.
    // This is close enough.
    strcpy(buf->sysname, "Linux");
    strcpy(buf->version, "3");
    return 0;
  };

  static intptr_t FcntlTrap(const sandbox::arch_seccomp_data& aArgs,
                            void* aux) {
    const auto cmd = static_cast<int>(aArgs.args[1]);
    switch (cmd) {
        // This process can't exec, so the actual close-on-exec flag
        // doesn't matter; have it always read as true and ignore writes.
      case F_GETFD:
        return O_CLOEXEC;
      case F_SETFD:
        return 0;
      default:
        return -ENOSYS;
    }
  }

  const SandboxOpenedFiles* mFiles;

 public:
  explicit GMPSandboxPolicy(const SandboxOpenedFiles* aFiles)
      : mFiles(aFiles) {}

  ~GMPSandboxPolicy() override = default;

  ResultExpr EvaluateSyscall(int sysno) const override {
    switch (sysno) {
    // Simulate opening the plugin file.
#ifdef __NR_open
      case __NR_open:
#endif
      case __NR_openat:
        return Trap(OpenTrap, mFiles);

        // ipc::Shmem
      case __NR_mprotect:
        return Allow();
      case __NR_madvise: {
        Arg<int> advice(2);
        return If(advice == MADV_DONTNEED, Allow())
            .ElseIf(advice == MADV_FREE, Allow())
            .ElseIf(advice == MADV_HUGEPAGE, Allow())
            .ElseIf(advice == MADV_NOHUGEPAGE, Allow())
#ifdef MOZ_ASAN
            .ElseIf(advice == MADV_DONTDUMP, Allow())
#endif
            .Else(InvalidSyscall());
      }
      case __NR_brk:
      CASES_FOR_geteuid:
        return Allow();
      case __NR_sched_get_priority_min:
      case __NR_sched_get_priority_max:
        return Allow();
      case __NR_sched_getparam:
      case __NR_sched_getscheduler:
      case __NR_sched_setscheduler: {
        Arg<pid_t> pid(0);
        return If(pid == 0, Allow()).Else(Trap(SchedTrap, nullptr));
      }

      // For clock(3) on older glibcs; bug 1304220.
      case __NR_times:
        return Allow();

      // Bug 1372428
      case __NR_uname:
        return Trap(UnameTrap, nullptr);
      CASES_FOR_fcntl:
        return Trap(FcntlTrap, nullptr);

      case __NR_dup:
        return Allow();

      default:
        return SandboxPolicyCommon::EvaluateSyscall(sysno);
    }
  }
};

UniquePtr<sandbox::bpf_dsl::Policy> GetMediaSandboxPolicy(
    const SandboxOpenedFiles* aFiles) {
  return UniquePtr<sandbox::bpf_dsl::Policy>(new GMPSandboxPolicy(aFiles));
}

#endif  // MOZ_GMP_SANDBOX

}  // namespace mozilla