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 // This file is an example of a computational-centric binary which is intended
16 // to be sandboxed by the sandbox2.
17
18 #include <syscall.h>
19
20 #include <cstdint>
21 #include <cstring>
22 #include <functional>
23 #include <vector>
24
25 #include "absl/flags/flag.h"
26 #include "absl/flags/parse.h"
27 #include "absl/strings/string_view.h"
28 #include "sandboxed_api/sandbox2/client.h"
29 #include "sandboxed_api/sandbox2/comms.h"
30 #include "sandboxed_api/sandbox2/util.h"
31
32 ABSL_FLAG(bool, call_syscall_not_allowed, false,
33 "Call a syscall that is not allowed by policy.");
34
35 // This function is insecure (i.e. can be crashed and exploited) to demonstrate
36 // how sandboxing can be helpful in defending against bugs.
37 // We need to make sure that this function is not inlined, so that we don't
38 // optimize the bug away.
ComputeCRC4Impl(const uint8_t * ptr,uint64_t len)39 static uint32_t ComputeCRC4Impl(const uint8_t* ptr, uint64_t len) {
40 uint8_t buf[8] = {0};
41
42 memcpy(buf, ptr, len); // buffer overflow!
43
44 uint32_t crc4 = 0;
45 for (uint64_t i = 0; i < len; i++) {
46 crc4 ^= (buf[i] << (i % 4) * 8);
47 }
48 return crc4;
49 }
50
main(int argc,char * argv[])51 int main(int argc, char* argv[]) {
52 absl::ParseCommandLine(argc, argv);
53
54 // Set-up the sandbox2::Client object, using a file descriptor (1023).
55 sandbox2::Comms comms(sandbox2::Comms::kDefaultConnection);
56 sandbox2::Client sandbox2_client(&comms);
57 // Enable sandboxing from here.
58 sandbox2_client.SandboxMeHere();
59
60 // A syscall not allowed in policy, should cause a violation.
61 if (absl::GetFlag(FLAGS_call_syscall_not_allowed)) {
62 sandbox2::util::Syscall(__NR_sendfile, 0, 0, 0, 0, 0, 0);
63 }
64
65 // Receive data to be processed, process it, and return results.
66 std::vector<uint8_t> buffer;
67 if (!comms.RecvBytes(&buffer)) {
68 return 1;
69 }
70
71 // Make sure we don't inline the function. See the comment in
72 // ComputeCRC4Impl() for more details.
73 std::function<uint32_t(const uint8_t*, uint64_t)> ComputeCRC4 =
74 ComputeCRC4Impl;
75
76 uint32_t crc4 = ComputeCRC4(buffer.data(), buffer.size());
77
78 if (!comms.SendUint32(crc4)) {
79 return 2;
80 }
81 return 0;
82 }
83