1 /*
2 * Copyright (C) 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "host/commands/process_sandboxer/policies.h"
18
19 #include <linux/filter.h>
20 #include <sys/mman.h>
21
22 #include <string_view>
23 #include <vector>
24
25 #include <sandboxed_api/sandbox2/policybuilder.h>
26 #include <sandboxed_api/sandbox2/util/bpf_helper.h>
27 #include <sandboxed_api/util/path.h>
28
29 namespace cuttlefish::process_sandboxer {
30
31 using sapi::file::JoinPath;
32
BaselinePolicy(const HostInfo & host,std::string_view exe)33 sandbox2::PolicyBuilder BaselinePolicy(const HostInfo& host,
34 std::string_view exe) {
35 return sandbox2::PolicyBuilder()
36 .AddLibrariesForBinary(exe, JoinPath(host.host_artifacts_path, "lib64"))
37 // For dynamic linking and memory allocation
38 .AllowDynamicStartup()
39 .AllowExit()
40 .AllowGetPIDs()
41 .AllowGetRandom()
42 // Observed by `strace` on `socket_vsock_proxy` with x86_64 AOSP `glibc`.
43 .AddPolicyOnMmap([](bpf_labels& labels) -> std::vector<sock_filter> {
44 return {
45 ARG_32(2), // prot
46 JEQ32(PROT_NONE, JUMP(&labels, cf_mmap_prot_none)),
47 JEQ32(PROT_READ, JUMP(&labels, cf_mmap_prot_read)),
48 JEQ32(PROT_READ | PROT_EXEC, JUMP(&labels, cf_mmap_prot_read_exec)),
49 JNE32(PROT_READ | PROT_WRITE, JUMP(&labels, cf_mmap_prot_end)),
50 // PROT_READ | PROT_WRITE
51 ARG_32(3), // flags
52 JEQ32(MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, ALLOW),
53 JUMP(&labels, cf_mmap_prot_end),
54 // PROT_READ | PROT_EXEC
55 LABEL(&labels, cf_mmap_prot_read_exec),
56 ARG_32(3), // flags
57 JEQ32(MAP_PRIVATE | MAP_DENYWRITE, ALLOW),
58 JEQ32(MAP_PRIVATE | MAP_FIXED | MAP_DENYWRITE, ALLOW),
59 JUMP(&labels, cf_mmap_prot_end),
60 // PROT_READ
61 LABEL(&labels, cf_mmap_prot_read),
62 ARG_32(3), // flags
63 JEQ32(MAP_PRIVATE | MAP_ANONYMOUS, ALLOW),
64 JEQ32(MAP_PRIVATE | MAP_DENYWRITE, ALLOW),
65 JEQ32(MAP_PRIVATE | MAP_FIXED | MAP_DENYWRITE, ALLOW),
66 JEQ32(MAP_PRIVATE, ALLOW),
67 JUMP(&labels, cf_mmap_prot_end),
68 // PROT_NONE
69 LABEL(&labels, cf_mmap_prot_none),
70 ARG_32(3), // flags
71 JEQ32(MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, ALLOW),
72 JEQ32(MAP_PRIVATE | MAP_ANONYMOUS, ALLOW),
73
74 LABEL(&labels, cf_mmap_prot_end),
75 };
76 })
77 .AllowReadlink()
78 .AllowRestartableSequences(sandbox2::PolicyBuilder::kAllowSlowFences)
79 .AllowWrite();
80 }
81
82 } // namespace cuttlefish::process_sandboxer
83