xref: /aosp_15_r20/external/sandboxed-api/sandboxed_api/sandbox2/policybuilder.h (revision ec63e07ab9515d95e79c211197c445ef84cefa6a)
1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef SANDBOXED_API_SANDBOX2_POLICYBUILDER_H_
16 #define SANDBOXED_API_SANDBOX2_POLICYBUILDER_H_
17 
18 #include <linux/filter.h>
19 
20 #include <cstddef>
21 #include <cstdint>
22 #include <functional>
23 #include <memory>
24 #include <string>
25 #include <utility>
26 #include <vector>
27 
28 #include "absl/base/attributes.h"
29 #include "absl/base/macros.h"
30 #include "absl/container/flat_hash_set.h"
31 #include "absl/log/check.h"
32 #include "absl/status/status.h"
33 #include "absl/status/statusor.h"
34 #include "absl/strings/string_view.h"
35 #include "absl/types/optional.h"
36 #include "absl/types/span.h"
37 #include "sandboxed_api/sandbox2/mounts.h"
38 #include "sandboxed_api/sandbox2/network_proxy/filtering.h"
39 #include "sandboxed_api/sandbox2/policy.h"
40 
41 struct bpf_labels;
42 
43 namespace sandbox2 {
44 
45 class AllowAllSyscalls;
46 class TraceAllSyscalls;
47 class UnrestrictedNetworking;
48 
49 // PolicyBuilder is a helper class to simplify creation of policies. The builder
50 // uses fluent interface for convenience and increased readability of policies.
51 //
52 // To build a policy you simply create a new builder object, call methods on it
53 // specifying what you want and finally call BuildOrDie() to generate you
54 // policy.
55 //
56 // For instance this would generate a simple policy suitable for binaries doing
57 // only computations:
58 //
59 // std::unique_ptr<Policy> policy =
60 //     PolicyBuilder()
61 //       .AllowRead()
62 //       .AllowWrite()
63 //       .AllowExit()
64 //       .AllowSystemMalloc()
65 //       .BuildOrDie();
66 //
67 // Note that operations are executed in the order they are dictated, though in
68 // most cases this has no influence since the operations themselves commute.
69 //
70 // For instance these two policies are equivalent:
71 //
72 // auto policy = PolicyBuilder.AllowRead().AllowWrite().BuildOrDie();
73 // auto policy = PolicyBuilder.AllowWrite().AllowRead().BuildOrDie();
74 //
75 // While these two are not:
76 //
77 // auto policy = PolicyBuilder.AllowRead().BlockSyscallWithErrno(__NR_read, EIO)
78 //                            .BuildOrDie();
79 // auto policy = PolicyBuilder.BlockSyscallWithErrno(__NR_read, EIO).AllowRead()
80 //                            .BuildOrDie();
81 //
82 // In fact the first one is equivalent to:
83 //
84 // auto policy = PolicyBuilder.AllowRead().BuildOrDie();
85 //
86 // If you dislike the chained style, it is also possible to write the first
87 // example as this:
88 //
89 // PolicyBuilder builder;
90 // builder.AllowRead();
91 // builder.AllowWrite();
92 // builder.AllowExit();
93 // builder.AllowSystemMalloc();
94 // auto policy = builder.BuildOrDie();
95 //
96 // For a more complicated example, see examples/persistent/persistent_sandbox.cc
97 class PolicyBuilder final {
98  public:
99   // Possible CPU fence modes for `AllowRestartableSequences()`
100   enum CpuFenceMode {
101     // Allow only fast fences for restartable sequences.
102     kRequireFastFences,
103 
104     // Allow fast fences as well as slow fences if fast fences are unavailable.
105     kAllowSlowFences,
106   };
107 
108   static constexpr absl::string_view kDefaultHostname = "sandbox2";
109   // Seccomp takes a 16-bit filter length, so the limit would be 64k.
110   // We set it lower so that there is for sure some room for the default policy.
111   static constexpr size_t kMaxUserPolicyLength = 30000;
112 
113   using BpfFunc = const std::function<std::vector<sock_filter>(bpf_labels&)>&;
114 
115   // Appends code to allow visibility restricted policy functionality.
116   //
117   // For example:
118   // Allow(sandbox2::UnrestrictedNetworking);
119   // This allows unrestricted network access by not creating a network
120   // namespace.
121   //
122   // Each type T is defined in an individual library and individually visibility
123   // restricted.
124   template <typename... T>
Allow(T...tags)125   PolicyBuilder& Allow(T... tags) {
126     return (Allow(tags), ...);
127   }
128 
129   // Allows unrestricted access to the network by *not* creating a network
130   // namespace. Note that this only disables the network namespace. To
131   // actually allow networking, you would also need to allow networking
132   // syscalls. Calling this function will enable use of namespaces
133   PolicyBuilder& Allow(UnrestrictedNetworking tag);
134 
135   // Appends code to allow a specific syscall
136   PolicyBuilder& AllowSyscall(uint32_t num);
137 
138   // Appends code to allow a number of syscalls
139   PolicyBuilder& AllowSyscalls(absl::Span<const uint32_t> nums);
140 
141   // Appends code to block a syscalls while setting errno to the error given.
142   PolicyBuilder& BlockSyscallsWithErrno(absl::Span<const uint32_t> nums,
143                                         int error);
144 
145   // Appends code to block a specific syscall and setting errno.
146   PolicyBuilder& BlockSyscallWithErrno(uint32_t num, int error);
147 
148   // Appends code to allow waiting for events on epoll file descriptors.
149   // Allows these syscalls:
150   // - epoll_wait
151   // - epoll_pwait
152   // - epoll_pwait2
153   PolicyBuilder& AllowEpollWait();
154 
155   // Appends code to allow using epoll.
156   // Allows these syscalls:
157   // - epoll_create
158   // - epoll_create1
159   // - epoll_ctl
160   // - epoll_wait
161   // - epoll_pwait
162   // - epoll_pwait2
163   PolicyBuilder& AllowEpoll();
164 
165   // Appends code to allow initializing an inotify instance.
166   // Allows these syscalls:
167   // - inotify_init
168   // - inotify_init1
169   PolicyBuilder& AllowInotifyInit();
170 
171   // Appends code to allow synchronous I/O multiplexing.
172   // Allows these syscalls:
173   // - pselect6
174   // - select
175   PolicyBuilder& AllowSelect();
176 
177   // Appends code to allow exiting.
178   // Allows these syscalls:
179   // - exit
180   // - exit_group
181   PolicyBuilder& AllowExit();
182 
183   // Appends code to allow restartable sequences and necessary /proc files.
184   // Allows these syscalls:
185   // - rseq
186   // - mmap(..., PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, ...)
187   // - getcpu
188   // - membarrier
189   // - futex(WAIT)
190   // - futex(WAKE)
191   // - rt_sigprocmask(SIG_SETMASK)
192   // Allows these files:
193   // - "/proc/cpuinfo"
194   // - "/proc/stat"
195   // And this directory (including subdirs/files):
196   // - "/sys/devices/system/cpu/"
197   //
198   // If `cpu_fence_mode` is `kAllowSlowFences`, also permits slow CPU fences.
199   // Allows these syscalls:
200   // - sched_getaffinity
201   // - sched_setaffinity
202   // Allows these files:
203   // - "/proc/self/cpuset"
204   //
205   // If `cpu_fence_mode` is `kRequireFastFences`, RSEQ functionality may not
206   // be enabled if fast CPU fences are not available.
207   PolicyBuilder& AllowRestartableSequences(CpuFenceMode cpu_fence_mode);
208   ABSL_DEPRECATED("Use AllowRestartableSequences() instead")
AllowRestartableSequencesWithProcFiles(CpuFenceMode cpu_fence_mode)209   PolicyBuilder& AllowRestartableSequencesWithProcFiles(
210       CpuFenceMode cpu_fence_mode) {
211     return this->AllowRestartableSequences(cpu_fence_mode);
212   }
213 
214   // Appends code to allow the scudo version of malloc, free and
215   // friends. This should be used in conjunction with namespaces. If scudo
216   // options are passed to the sandboxee through an environment variable, access
217   // to "/proc/self/environ" will have to be allowed by the policy.
218   //
219   // Note: This function is tuned towards the secure scudo allocator. If you are
220   //       using another implementation, this function might not be the most
221   //       suitable.
222   PolicyBuilder& AllowScudoMalloc();
223 
224   // Appends code to allow the system-allocator version of malloc, free and
225   // friends.
226   //
227   // Note: This function is tuned towards the malloc implementation in glibc. If
228   //       you are using another implementation, this function might not be the
229   //       most suitable.
230   PolicyBuilder& AllowSystemMalloc();
231 
232   // Appends code to allow the tcmalloc version of malloc, free and
233   // friends.
234   PolicyBuilder& AllowTcMalloc();
235 
236   // Allows system calls typically used by the LLVM sanitizers (address
237   // sanitizer, memory sanitizer, and thread sanitizer). This method is
238   // intended as a best effort for adding system calls that are common to many
239   // binaries. It may not be fully inclusive of all potential system calls for
240   // all binaries.
241   PolicyBuilder& AllowLlvmSanitizers();
242 
243   // Allows system calls typically used by the LLVM coverage.
244   // This method is intended as a best effort.
245   PolicyBuilder& AllowLlvmCoverage();
246 
247   // Appends code to allow mmap. Specifically this allows mmap and mmap2 syscall
248   // on architectures where this syscalls exist.
249   // Prefer using AllowMmapWithoutExec as allowing mapping executable pages
250   // makes exploitation easier.
251   PolicyBuilder& AllowMmap();
252 
253   // Appends code to allow mmap calls that don't specify PROT_EXEC.
254   PolicyBuilder& AllowMmapWithoutExec();
255 
256   // Appends code to allow calling futex with the given operation.
257   PolicyBuilder& AllowFutexOp(int op);
258 
259   // Appends code to allow opening and possibly creating files or directories.
260   // Allows these syscalls:
261   // - creat
262   // - open
263   // - openat
264   PolicyBuilder& AllowOpen();
265 
266   // Appends code to allow calling stat, fstat and lstat.
267   // Allows these syscalls:
268   // - fstat
269   // - fstat64
270   // - fstatat
271   // - fstatat64
272   // - fstatfs
273   // - fstatfs64
274   // - lstat
275   // - lstat64
276   // - newfstatat
277   // - oldfstat
278   // - oldlstat
279   // - oldstat
280   // - stat
281   // - stat64
282   // - statfs
283   // - statfs64
284   // - ustat
285   PolicyBuilder& AllowStat();
286 
287   // Appends code to allow checking file permissions.
288   // Allows these syscalls:
289   // - access
290   // - faccessat
291   PolicyBuilder& AllowAccess();
292 
293   // Appends code to allow duplicating file descriptors.
294   // Allows these syscalls:
295   // - dup
296   // - dup2
297   // - dup3
298   PolicyBuilder& AllowDup();
299 
300   // Appends code to allow creating pipes.
301   // Allows these syscalls:
302   // - pipe
303   // - pipe2
304   PolicyBuilder& AllowPipe();
305 
306   // Appends code to allow changing file permissions.
307   // Allows these syscalls:
308   // - chmod
309   // - fchmod
310   // - fchmodat
311   PolicyBuilder& AllowChmod();
312 
313   // Appends code to allow changing file ownership.
314   // Allows these syscalls:
315   // - chown
316   // - lchown
317   // - fchown
318   // - fchownat
319   PolicyBuilder& AllowChown();
320 
321   // Appends code to the policy to allow reading from file descriptors.
322   // Allows these syscalls:
323   // - read
324   // - readv
325   // - preadv
326   // - pread64
327   PolicyBuilder& AllowRead();
328 
329   // Appends code to the policy to allow writing to file descriptors.
330   // Allows these syscalls:
331   // - write
332   // - writev
333   // - pwritev
334   // - pwrite64
335   PolicyBuilder& AllowWrite();
336 
337   // Appends code to allow reading directories.
338   // Allows these syscalls:
339   // - getdents
340   // - getdents64
341   PolicyBuilder& AllowReaddir();
342 
343   // Appends code to allow reading symbolic links.
344   // Allows these syscalls:
345   // - readlink
346   // - readlinkat
347   PolicyBuilder& AllowReadlink();
348 
349   // Appends code to allow creating links.
350   // Allows these syscalls:
351   // - link
352   // - linkat
353   PolicyBuilder& AllowLink();
354 
355   // Appends code to allow creating symbolic links.
356   // Allows these syscalls:
357   // - symlink
358   // - symlinkat
359   PolicyBuilder& AllowSymlink();
360 
361   // Appends code to allow creating directories.
362   // Allows these syscalls:
363   // - mkdir
364   // - mkdirat
365   PolicyBuilder& AllowMkdir();
366 
367   // Appends code to allow changing file timestamps.
368   // Allows these syscalls:
369   // - futimens
370   // - utime
371   // - utimensat
372   // - utimes
373   PolicyBuilder& AllowUtime();
374 
375   // Appends code to allow safe calls to fcntl.
376   // Allows these syscalls:
377   // - fcntl
378   // - fcntl64 (on architectures where it exists)
379   //
380   // The above are only allowed when the cmd is one of:
381   // F_GETFD, F_SETFD, F_GETFL, F_SETFL, F_GETLK, F_SETLKW, F_SETLK,
382   // F_DUPFD, F_DUPFD_CLOEXEC
383   PolicyBuilder& AllowSafeFcntl();
384 
385   // Appends code to allow creating new processes.
386   // Allows these syscalls:
387   // - fork
388   // - vfork
389   // - clone
390   //
391   // Note: while this function allows the calls, the default policy is run first
392   // and it has checks for dangerous flags which can create a violation. See
393   // sandbox2/policy.cc for more details.
394   PolicyBuilder& AllowFork();
395 
396   // Appends code to allow waiting for processes.
397   // Allows these syscalls:
398   // - waitpid (on architectures where it exists)
399   // - wait4
400   PolicyBuilder& AllowWait();
401 
402   // Appends code to allow setting alarms / interval timers.
403   // Allows these syscalls:
404   // - alarm (on architectures where it exists)
405   // - setitimer
406   PolicyBuilder& AllowAlarm();
407 
408   // Appends code to allow setting up signal handlers, returning from them, etc.
409   // Allows these syscalls:
410   // - rt_sigaction
411   // - rt_sigreturn
412   // - rt_procmask
413   // - signal (on architectures where it exists)
414   // - sigaction (on architectures where it exists)
415   // - sigreturn (on architectures where it exists)
416   // - sigprocmask (on architectures where it exists)
417   PolicyBuilder& AllowHandleSignals();
418 
419   // Appends code to allow doing the TCGETS ioctl.
420   // Allows these syscalls:
421   // - ioctl (when the first argument is TCGETS)
422   PolicyBuilder& AllowTCGETS();
423 
424   // Appends code to allow to getting the current time.
425   // Allows these syscalls:
426   // - time
427   // - gettimeofday
428   // - clock_gettime
429   PolicyBuilder& AllowTime();
430 
431   // Appends code to allow sleeping in the current thread.
432   // Allow these syscalls:
433   // - clock_nanosleep
434   // - nanosleep
435   PolicyBuilder& AllowSleep();
436 
437   // Appends code to allow getting the uid, euid, gid, etc.
438   // - getuid + geteuid + getresuid
439   // - getgid + getegid + getresgid
440   // - getuid32 + geteuid32 + getresuid32 (on architectures where they exist)
441   // - getgid32 + getegid32 + getresgid32 (on architectures where they exist)
442   // - getgroups
443   PolicyBuilder& AllowGetIDs();
444 
445   // Appends code to allow getting the pid, ppid and tid.
446   // Allows these syscalls:
447   // - getpid
448   // - getppid
449   // - gettid
450   PolicyBuilder& AllowGetPIDs();
451 
452   // Appends code to allow getting process groups.
453   // Allows these syscalls:
454   // - getpgid
455   // - getpgrp
456   PolicyBuilder& AllowGetPGIDs();
457 
458   // Appends code to allow getting the rlimits.
459   // Allows these syscalls:
460   // - getrlimit
461   // - ugetrlimit (on architectures where it exist)
462   PolicyBuilder& AllowGetRlimit();
463 
464   // Appends code to allow setting the rlimits.
465   // Allows these syscalls:
466   // - setrlimit
467   // - usetrlimit (on architectures where it exist)
468   PolicyBuilder& AllowSetRlimit();
469 
470   // Appends code to allow reading random bytes.
471   // Allows these syscalls:
472   // - getrandom (with no flags or GRND_NONBLOCK)
473   //
474   PolicyBuilder& AllowGetRandom();
475 
476   // Appends code to allow configuring wipe-on-fork memory
477   // Allows these syscalls:
478   // - madvise (with advice equal to -1 or MADV_WIPEONFORK).
479   PolicyBuilder& AllowWipeOnFork();
480 
481   // Enables syscalls required to use the logging support enabled via
482   // Client::SendLogsToSupervisor()
483   // Allows the following:
484   // - Writes
485   // - kill(0, SIGABRT) (for LOG(FATAL))
486   // - clock_gettime
487   // - gettid
488   // - close
489   PolicyBuilder& AllowLogForwarding();
490 
491   // Appends code to allow deleting files and directories.
492   // Allows these syscalls:
493   // - rmdir (if available)
494   // - unlink (if available)
495   // - unlinkat
496   PolicyBuilder& AllowUnlink();
497 
498   // Appends code to allow renaming files
499   // Allows these syscalls:
500   // - rename (if available)
501   // - renameat
502   // - renameat2
503   PolicyBuilder& AllowRename();
504 
505   // Appends code to allow creating event notification file descriptors.
506   // Allows these syscalls:
507   // - eventfd (if available)
508   // - eventfd2
509   PolicyBuilder& AllowEventFd();
510 
511   // Appends code to allow polling files.
512   // Allows these syscalls:
513   // - poll (if available)
514   // - ppoll
515   PolicyBuilder& AllowPoll();
516 
517   // Appends code to allow setting the name of a thread
518   // Allows the following
519   // - prctl(PR_SET_NAME, ...)
520   PolicyBuilder& AllowPrctlSetName();
521 
522   // Appends code to allow setting a name for an anonymous memory region.
523   // Allows the following
524   // - prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, ...)
525   PolicyBuilder& AllowPrctlSetVma();
526 
527   // Enables the syscalls necessary to start a statically linked binary
528   //
529   // NOTE: This will call BlockSyscallWithErrno(__NR_readlink, ENOENT). If you
530   // do not want readlink blocked, put a different call before this call.
531   //
532   // The current list of allowed syscalls are below. However you should *not*
533   // depend on the specifics, as these will change whenever the startup code
534   // changes.
535   //
536   // - uname,
537   // - brk,
538   // - set_tid_address,
539   // - set_robust_list,
540   // - futex(FUTEX_WAIT_BITSET, ...)
541   // - rt_sigaction(0x20, ...)
542   // - rt_sigaction(0x21, ...)
543   // - rt_sigprocmask(SIG_UNBLOCK, ...)
544   // - arch_prctl(ARCH_SET_FS)
545   //
546   // Additionally it will block calls to readlink.
547   PolicyBuilder& AllowStaticStartup();
548 
549   // In addition to syscalls allowed by AllowStaticStartup, also allow reading,
550   // seeking, mmapping and closing files. It does not allow opening them, as
551   // the mechanism for doing so depends on whether GetFs-checks are used or not.
552   PolicyBuilder& AllowDynamicStartup();
553 
554   // Appends a policy, which will be run on the specified syscall.
555   // This policy must be written without labels. If you need labels, use
556   // the overloaded function passing a BpfFunc object instead of the
557   // sock_filter.
558   PolicyBuilder& AddPolicyOnSyscall(uint32_t num,
559                                     absl::Span<const sock_filter> policy);
560 
561   // Appends a policy, which will be run on the specified syscall.
562   // This policy may use labels.
563   // Example of how to use it:
564   //  builder.AddPolicyOnSyscall(
565   //      __NR_socket, [](bpf_labels& labels) -> std::vector<sock_filter> {
566   //        return {
567   //            ARG(0),  // domain is first argument of socket
568   //            JEQ(AF_UNIX, JUMP(&labels, af_unix)),
569   //            JEQ(AF_NETLINK, JUMP(&labels, af_netlink)),
570   //            KILL,
571   //
572   //            LABEL(&labels, af_unix),
573   //            ARG(1),
574   //            JEQ(SOCK_STREAM | SOCK_NONBLOCK, ALLOW),
575   //            KILL,
576   //
577   //            LABEL(&labels, af_netlink),
578   //            ARG(2),
579   //            JEQ(NETLINK_ROUTE, ALLOW),
580   //        };
581   //      });
582   PolicyBuilder& AddPolicyOnSyscall(uint32_t num, BpfFunc f);
583 
584   // Appends a policy, which will be run on the specified syscalls.
585   // This policy must be written without labels.
586   PolicyBuilder& AddPolicyOnSyscalls(absl::Span<const uint32_t> nums,
587                                      absl::Span<const sock_filter> policy);
588 
589   // Appends a policy, which will be run on the specified syscalls.
590   // This policy may use labels.
591   PolicyBuilder& AddPolicyOnSyscalls(absl::Span<const uint32_t> nums,
592                                      BpfFunc f);
593 
594   // Equivalent to AddPolicyOnSyscalls(mmap_syscalls, policy), where
595   // mmap_syscalls is a subset of {__NR_mmap, __NR_mmap2}, which exists on the
596   // target architecture.
597   PolicyBuilder& AddPolicyOnMmap(absl::Span<const sock_filter> policy);
598 
599   // Equivalent to AddPolicyOnSyscalls(mmap_syscalls, f), where mmap_syscalls
600   // is a subset of {__NR_mmap, __NR_mmap2}, which exists on the target
601   // architecture.
602   PolicyBuilder& AddPolicyOnMmap(BpfFunc f);
603 
604   // Builds the policy returning a unique_ptr to it. This should only be
605   // called once.
606   absl::StatusOr<std::unique_ptr<Policy>> TryBuild();
607 
608   // Builds the policy returning a unique_ptr to it. This should only be
609   // called once. This function will abort if an error happened in any of the
610   // PolicyBuilder methods.
BuildOrDie()611   std::unique_ptr<Policy> BuildOrDie() { return TryBuild().value(); }
612 
613   // Adds a bind-mount for a file from outside the namespace to inside. This
614   // will also create parent directories inside the namespace if needed.
615   //
616   // Calling these function will enable use of namespaces.
617   PolicyBuilder& AddFile(absl::string_view path, bool is_ro = true);
618   PolicyBuilder& AddFileAt(absl::string_view outside, absl::string_view inside,
619                            bool is_ro = true);
620 
621   // Best-effort function that adds the libraries and linker required by a
622   // binary.
623   //
624   // This does not add the binary itself, only the libraries it depends on.
625   //
626   // This function should work correctly for most binaries, but you might need
627   // to tweak it in some cases.
628   //
629   // This function is safe even for untrusted/potentially malicious binaries.
630   // It adds libraries only from standard library dirs and ld_library_path.
631   //
632   // run `ldd` yourself and use AddFile or AddDirectory.
633   PolicyBuilder& AddLibrariesForBinary(absl::string_view path,
634                                        absl::string_view ld_library_path = {});
635 
636   // Similar to AddLibrariesForBinary, but binary is specified with an open
637   // fd.
638   PolicyBuilder& AddLibrariesForBinary(int fd,
639                                        absl::string_view ld_library_path = {});
640 
641   // Adds a bind-mount for a directory from outside the namespace to
642   // inside.  This will also create parent directories inside the namespace if
643   // needed.
644   //
645   // Calling these function will enable use of namespaces.
646   PolicyBuilder& AddDirectory(absl::string_view path, bool is_ro = true);
647   PolicyBuilder& AddDirectoryAt(absl::string_view outside,
648                                 absl::string_view inside, bool is_ro = true);
649 
650   // Adds a tmpfs inside the namespace. This will also create parent
651   // directories inside the namespace if needed.
652   //
653   // Calling this function will enable use of namespaces.
654   PolicyBuilder& AddTmpfs(absl::string_view inside, size_t size);
655 
656   // Allows unrestricted access to the network by *not* creating a network
657   // namespace. Note that this only disables the network namespace. To
658   // actually allow networking, you would also need to allow networking
659   // syscalls. Calling this function will enable use of namespaces.
660   PolicyBuilder& AllowUnrestrictedNetworking();
661 
662   // Enables the use of namespaces.
663   //
664   // Namespaces are enabled by default.
665   // This is a no-op.
666   ABSL_DEPRECATED("Namespaces are enabled by default; no need to call this")
EnableNamespaces()667   PolicyBuilder& EnableNamespaces() {
668     CHECK(use_namespaces_) << "Namespaces cannot be both disabled and enabled";
669     requires_namespaces_ = true;
670     return *this;
671   }
672 
673   // Disables the use of namespaces.
674   //
675   // Call in order to use Sandbox2 without namespaces.
676   // This is not recommended.
DisableNamespaces()677   PolicyBuilder& DisableNamespaces() {
678     CHECK(!requires_namespaces_)
679         << "Namespaces cannot be both disabled and enabled. You're probably "
680            "using features that implicitly enable namespaces (SetHostname, "
681            "AddFile, AddDirectory, AddDataDependency, AddLibrariesForBinary "
682            "or similar)";
683     use_namespaces_ = false;
684     return *this;
685   }
686 
687   // Set hostname in the network namespace instead of default "sandbox2".
688   //
689   // Calling this function will enable use of namespaces.
690   // It is an error to also call AllowUnrestrictedNetworking.
691   PolicyBuilder& SetHostname(absl::string_view hostname);
692 
693   // Enables/disables stack trace collection on violations.
694   PolicyBuilder& CollectStacktracesOnViolation(bool enable);
695 
696   // Enables/disables stack trace collection on signals (e.g. crashes / killed
697   // from a signal).
698   PolicyBuilder& CollectStacktracesOnSignal(bool enable);
699 
700   // Enables/disables stack trace collection on hitting a timeout.
701   PolicyBuilder& CollectStacktracesOnTimeout(bool enable);
702 
703   // Enables/disables stack trace collection on getting killed by the sandbox
704   // monitor / the user.
705   PolicyBuilder& CollectStacktracesOnKill(bool enable);
706 
707   // Enables/disables stack trace collection on normal process exit.
708   PolicyBuilder& CollectStacktracesOnExit(bool enable);
709 
710   // Changes the default action to ALLOW.
711   // All syscalls not handled explicitly by the policy will thus be allowed.
712   // Do not use in environment with untrusted code and/or data, ask
713   // sandbox-team@ first if unsure.
714   PolicyBuilder& DefaultAction(AllowAllSyscalls);
715 
716   // Changes the default action to SANDBOX2_TRACE.
717   // All syscalls not handled explicitly by the policy will be passed off to
718   // the `sandbox2::Notify` implementation given to the `sandbox2::Sandbox2`
719   // instance.
720   PolicyBuilder& DefaultAction(TraceAllSyscalls);
721 
722   ABSL_DEPRECATED("Use DefaultAction(sandbox2::AllowAllSyscalls()) instead")
723   PolicyBuilder& DangerDefaultAllowAll();
724 
725   // Allows syscalls that are necessary for the NetworkProxyClient
726   PolicyBuilder& AddNetworkProxyPolicy();
727 
728   // Allows syscalls that are necessary for the NetworkProxyClient and
729   // the NetworkProxyHandler
730   PolicyBuilder& AddNetworkProxyHandlerPolicy();
731 
732   // Makes root of the filesystem writeable
733   // Not recommended
734   PolicyBuilder& SetRootWritable();
735 
736   // Changes mounts propagation from MS_PRIVATE to MS_SLAVE.
DangerAllowMountPropagation()737   PolicyBuilder& DangerAllowMountPropagation() {
738     allow_mount_propagation_ = true;
739     return *this;
740   }
741 
742   // Allows connections to this IP.
743   PolicyBuilder& AllowIPv4(const std::string& ip_and_mask, uint32_t port = 0);
744   PolicyBuilder& AllowIPv6(const std::string& ip_and_mask, uint32_t port = 0);
745 
746  private:
747   friend class PolicyBuilderPeer;  // For testing
748   friend class StackTracePeer;
749 
750   static absl::StatusOr<std::string> ValidateAbsolutePath(
751       absl::string_view path);
752   static absl::StatusOr<std::string> ValidatePath(absl::string_view path);
753 
754   // Similar to AddFile(At)/AddDirectory(At) but it won't force use of
755   // namespaces - files will only be added to the namespace if it is not
756   // disabled by the time of TryBuild().
757   PolicyBuilder& AddFileIfNamespaced(absl::string_view path, bool is_ro = true);
758   PolicyBuilder& AddFileAtIfNamespaced(absl::string_view outside,
759                                        absl::string_view inside,
760                                        bool is_ro = true);
761   PolicyBuilder& AddDirectoryIfNamespaced(absl::string_view path,
762                                           bool is_ro = true);
763   PolicyBuilder& AddDirectoryAtIfNamespaced(absl::string_view outside,
764                                             absl::string_view inside,
765                                             bool is_ro = true);
766 
767   // Allows a limited version of madvise
768   PolicyBuilder& AllowLimitedMadvise();
769 
770   // Traps instead of denying ptrace.
771   PolicyBuilder& TrapPtrace();
772 
773   // Appends code to block a specific syscall and setting errno at the end of
774   // the policy - decision taken by user policy take precedence.
775   PolicyBuilder& OverridableBlockSyscallWithErrno(uint32_t num, int error);
776 
SetMounts(Mounts mounts)777   PolicyBuilder& SetMounts(Mounts mounts) {
778     mounts_ = std::move(mounts);
779     return *this;
780   }
781 
782   std::vector<sock_filter> ResolveBpfFunc(BpfFunc f);
783 
784   void StoreDescription(PolicyBuilderDescription* pb_description);
785 
786   // This function returns a PolicyBuilder so that we can use it in the status
787   // macros
788   PolicyBuilder& SetError(const absl::Status& status);
789 
790   Mounts mounts_;
791   bool use_namespaces_ = true;
792   bool requires_namespaces_ = false;
793   bool allow_unrestricted_networking_ = false;
794   bool allow_mount_propagation_ = false;
795   std::string hostname_ = std::string(kDefaultHostname);
796 
797   bool collect_stacktrace_on_violation_ = true;
798   bool collect_stacktrace_on_signal_ = true;
799   bool collect_stacktrace_on_timeout_ = true;
800   bool collect_stacktrace_on_kill_ = false;
801   bool collect_stacktrace_on_exit_ = false;
802 
803   // Seccomp fields
804   std::vector<sock_filter> user_policy_;
805   std::vector<sock_filter> overridable_policy_;
806   std::optional<sock_filter> default_action_;
807   bool user_policy_handles_bpf_ = false;
808   bool user_policy_handles_ptrace_ = false;
809   absl::flat_hash_set<uint32_t> handled_syscalls_;
810 
811   // Error handling
812   absl::Status last_status_;
813   bool already_built_ = false;
814 
815   // Contains list of allowed hosts.
816   absl::optional<AllowedHosts> allowed_hosts_;
817 };
818 
819 }  // namespace sandbox2
820 
821 #endif  // SANDBOXED_API_SANDBOX2_POLICYBUILDER_H_
822