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 // Unit tests for crc4sandbox example.
16
17 #include <unistd.h>
18
19 #include <string>
20 #include <vector>
21
22 #include "gmock/gmock.h"
23 #include "gtest/gtest.h"
24 #include "absl/log/log.h"
25 #include "sandboxed_api/sandbox2/util.h"
26 #include "sandboxed_api/testing.h"
27 #include "sandboxed_api/util/status_matchers.h"
28
29 namespace sandbox2 {
30 namespace {
31
32 using ::sapi::GetTestSourcePath;
33 using ::testing::Eq;
34 using ::testing::HasSubstr;
35
36 class CRC4Test : public ::testing::Test {
37 protected:
SetUp()38 void SetUp() override {
39 path_ = GetTestSourcePath("sandbox2/examples/crc4/crc4sandbox");
40 env_ = util::CharPtrArray(environ).ToStringVector();
41 }
42
43 std::string path_;
44 std::vector<std::string> env_;
45 };
46
47 // Test that crc4sandbox works.
TEST_F(CRC4Test,TestNormalOperation)48 TEST_F(CRC4Test, TestNormalOperation) {
49 SKIP_SANITIZERS_AND_COVERAGE;
50 std::string output;
51 SAPI_ASSERT_OK_AND_ASSIGN(
52 int exit_code,
53 util::Communicate({path_, "-input", "ABCD"}, env_, &output));
54
55 EXPECT_THAT(output, HasSubstr("0x44434241\n"));
56 EXPECT_THAT(exit_code, Eq(0));
57 }
58
59 // Test that crc4sandbox protects against bugs, because only the sandboxee
60 // will crash and break its communication with executor.
TEST_F(CRC4Test,TestExploitAttempt)61 TEST_F(CRC4Test, TestExploitAttempt) {
62 SKIP_SANITIZERS_AND_COVERAGE;
63
64 std::string output;
65 SAPI_ASSERT_OK_AND_ASSIGN(
66 int exit_code, util::Communicate({path_, "-input", std::string(128, 'A')},
67 env_, &output));
68
69 LOG(INFO) << "Output: " << output;
70 EXPECT_THAT(exit_code, Eq(3));
71 }
72
73 // Test that if sandboxee calls a syscall that is not allowed by the policy,
74 // it triggers a policy violation for the executor.
TEST_F(CRC4Test,TestSyscallViolation)75 TEST_F(CRC4Test, TestSyscallViolation) {
76 SKIP_SANITIZERS_AND_COVERAGE;
77
78 std::string output;
79 SAPI_ASSERT_OK_AND_ASSIGN(
80 int exit_code,
81 util::Communicate({path_, "-input", "x", "-call_syscall_not_allowed"},
82 env_, &output));
83
84 LOG(INFO) << "Output: " << output;
85 EXPECT_THAT(exit_code, Eq(3));
86 }
87
88 } // namespace
89 } // namespace sandbox2
90