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 #include <fcntl.h>
16
17 #include <cstring>
18 #include <ctime>
19 #include <memory>
20 #include <string>
21 #include <utility>
22
23 #include "absl/base/log_severity.h"
24 #include "absl/base/macros.h"
25 #include "absl/flags/parse.h"
26 #include "absl/log/check.h"
27 #include "absl/log/globals.h"
28 #include "absl/log/initialize.h"
29 #include "absl/log/log.h"
30 #include "absl/status/status.h"
31 #include "absl/status/statusor.h"
32 #include "absl/strings/str_cat.h"
33 #include "sandboxed_api/examples/sum/sum-sapi.sapi.h"
34 #include "sandboxed_api/examples/sum/sum_params.pb.h"
35 #include "sandboxed_api/transaction.h"
36 #include "sandboxed_api/vars.h"
37
38 namespace {
39
40 class SumParams : public sapi::v::Struct<sum_params> {};
41
42 class SumTransaction : public sapi::Transaction {
43 public:
SumTransaction(std::unique_ptr<sapi::Sandbox> sandbox,bool crash,bool violate,bool time_out)44 SumTransaction(std::unique_ptr<sapi::Sandbox> sandbox, bool crash,
45 bool violate, bool time_out)
46 : sapi::Transaction(std::move(sandbox)),
47 crash_(crash),
48 violate_(violate),
49 time_out_(time_out) {
50 sapi::Transaction::SetTimeLimit(kTimeOutVal);
51 }
52
53 private:
54 // Default timeout value for each transaction run.
55 const time_t kTimeOutVal = 2;
56 // Should the sandboxee crash at some point?
57 bool crash_;
58 // Should the sandboxee invoke a disallowed syscall?
59 bool violate_;
60 // Should the sandboxee time_out_?
61 bool time_out_;
62
63 // The main processing function.
64 absl::Status Main() override;
65 };
66
Main()67 absl::Status SumTransaction::Main() {
68 SumApi f(sandbox());
69 SAPI_ASSIGN_OR_RETURN(int v, f.sum(1000, 337));
70 LOG(INFO) << "1000 + 337 = " << v;
71 TRANSACTION_FAIL_IF_NOT(v == 1337, "1000 + 337 != 1337");
72
73 // Sums two int's held in a structure.
74 SumParams params;
75 params.mutable_data()->a = 1111;
76 params.mutable_data()->b = 222;
77 params.mutable_data()->ret = 0;
78 SAPI_RETURN_IF_ERROR(f.sums(params.PtrBoth()));
79 LOG(INFO) << "1111 + 222 = " << params.data().ret;
80 TRANSACTION_FAIL_IF_NOT(params.data().ret == 1333, "1111 + 222 != 1333");
81
82 params.mutable_data()->b = -1000;
83 SAPI_RETURN_IF_ERROR(f.sums(params.PtrBoth()));
84 LOG(INFO) << "1111 - 1000 = " << params.data().ret;
85 TRANSACTION_FAIL_IF_NOT(params.data().ret == 111, "1111 - 1000 != 111");
86
87 // Without the wrapper class for struct.
88 sapi::v::Struct<sum_params> p;
89 p.mutable_data()->a = 1234;
90 p.mutable_data()->b = 5678;
91 p.mutable_data()->ret = 0;
92 SAPI_RETURN_IF_ERROR(f.sums(p.PtrBoth()));
93 LOG(INFO) << "1234 + 5678 = " << p.data().ret;
94 TRANSACTION_FAIL_IF_NOT(p.data().ret == 6912, "1234 + 5678 != 6912");
95
96 // Gets symbol address and prints its value.
97 int* ssaddr;
98 SAPI_RETURN_IF_ERROR(
99 sandbox()->Symbol("sumsymbol", reinterpret_cast<void**>(&ssaddr)));
100 sapi::v::Int sumsymbol;
101 sumsymbol.SetRemote(ssaddr);
102 SAPI_RETURN_IF_ERROR(sandbox()->TransferFromSandboxee(&sumsymbol));
103 LOG(INFO) << "sumsymbol value (exp: 5): " << sumsymbol.GetValue()
104 << ", address: " << ssaddr;
105 TRANSACTION_FAIL_IF_NOT(sumsymbol.GetValue() == 5,
106 "sumsymbol.GetValue() != 5");
107
108 // Sums all int's inside an array.
109 int arr[10];
110 sapi::v::Array<int> iarr(arr, ABSL_ARRAYSIZE(arr));
111 for (size_t i = 0; i < ABSL_ARRAYSIZE(arr); i++) {
112 iarr[i] = i;
113 }
114 SAPI_ASSIGN_OR_RETURN(v, f.sumarr(iarr.PtrBefore(), iarr.GetNElem()));
115 LOG(INFO) << "Sum(iarr, 10 elem, from 0 to 9, exp: 45) = " << v;
116 TRANSACTION_FAIL_IF_NOT(v == 45, "Sum(iarr, 10 elem, from 0 to 9) != 45");
117
118 float a = 0.99999f;
119 double b = 1.5423432l;
120 long double c = 1.1001L;
121 SAPI_ASSIGN_OR_RETURN(long double r, f.addf(a, b, c));
122 LOG(INFO) << "Addf(" << a << ", " << b << ", " << c << ") = " << r;
123 // TODO(szwl): floating point comparison.
124
125 // Prints "Hello World!!!" via puts()
126 const char hwstr[] = "Hello World!!!";
127 LOG(INFO) << "Print: '" << hwstr << "' via puts()";
128 sapi::v::Array<const char> hwarr(hwstr, sizeof(hwstr));
129 sapi::v::Int ret;
130 SAPI_RETURN_IF_ERROR(sandbox()->Call("puts", &ret, hwarr.PtrBefore()));
131 TRANSACTION_FAIL_IF_NOT(ret.GetValue() == 15, "puts('Hello World!!!') != 15");
132
133 sapi::v::Int vp;
134 LOG(INFO) << "Test whether pointer is NOT NULL - new pointers";
135 SAPI_RETURN_IF_ERROR(f.testptr(vp.PtrBefore()));
136 LOG(INFO) << "Test whether pointer is NULL";
137 SAPI_RETURN_IF_ERROR(f.testptr(nullptr));
138
139 // Protobuf test.
140 sumsapi::SumParamsProto proto;
141 proto.set_a(10);
142 proto.set_b(20);
143 proto.set_c(30);
144 auto pp = sapi::v::Proto<sumsapi::SumParamsProto>::FromMessage(proto);
145 if (!pp.ok()) {
146 return pp.status();
147 }
148 SAPI_ASSIGN_OR_RETURN(v, f.sumproto(pp->PtrBefore()));
149 LOG(INFO) << "sumproto(proto {a = 10; b = 20; c = 30}) = " << v;
150 TRANSACTION_FAIL_IF_NOT(v == 60,
151 "sumproto(proto {a = 10; b = 20; c = 30}) != 60");
152
153 // Fd transfer test.
154 int fdesc = open("/proc/self/exe", O_RDONLY);
155 sapi::v::Fd fd(fdesc);
156 SAPI_RETURN_IF_ERROR(sandbox()->TransferToSandboxee(&fd));
157 LOG(INFO) << "remote_fd = " << fd.GetRemoteFd();
158 TRANSACTION_FAIL_IF_NOT(fd.GetRemoteFd() != -1, "remote_fd == -1");
159
160 fdesc = open("/proc/self/comm", O_RDONLY);
161 sapi::v::Fd fd2(fdesc);
162 SAPI_RETURN_IF_ERROR(sandbox()->TransferToSandboxee(&fd2));
163 LOG(INFO) << "remote_fd2 = " << fd2.GetRemoteFd();
164 TRANSACTION_FAIL_IF_NOT(fd2.GetRemoteFd() != -1, "remote_fd2 == -1");
165
166 // Read from fd test.
167 char buffer[1024] = {0};
168 sapi::v::Array<char> buf(buffer, sizeof(buffer));
169 sapi::v::UInt size(128);
170 SAPI_RETURN_IF_ERROR(
171 sandbox()->Call("read", &ret, &fd2, buf.PtrBoth(), &size));
172 LOG(INFO) << "Read from /proc/self/comm = [" << buffer << "]";
173
174 // Close test.
175 SAPI_RETURN_IF_ERROR(fd2.CloseRemoteFd(sandbox()->rpc_channel()));
176 memset(buffer, 0, sizeof(buffer));
177 SAPI_RETURN_IF_ERROR(
178 sandbox()->Call("read", &ret, &fd2, buf.PtrBoth(), &size));
179 LOG(INFO) << "Read from closed /proc/self/comm = [" << buffer << "]";
180
181 // Pass fd as function arg example.
182 fdesc = open("/proc/self/statm", O_RDONLY);
183 sapi::v::Fd fd3(fdesc);
184 SAPI_RETURN_IF_ERROR(sandbox()->TransferToSandboxee(&fd3));
185 SAPI_ASSIGN_OR_RETURN(int r2, f.read_int(fd3.GetRemoteFd()));
186 LOG(INFO) << "statm value (should not be 0) = " << r2;
187
188 if (crash_) {
189 // Crashes the sandboxed part with SIGSEGV
190 LOG(INFO) << "Crash with SIGSEGV";
191 SAPI_RETURN_IF_ERROR(f.crash());
192 }
193
194 if (violate_) {
195 LOG(INFO) << "Cause a sandbox (syscall) violation";
196 SAPI_RETURN_IF_ERROR(f.violate());
197 }
198
199 if (time_out_) {
200 SAPI_RETURN_IF_ERROR(f.sleep_for_sec(kTimeOutVal * 2));
201 }
202 return absl::OkStatus();
203 }
204
test_addition(sapi::Sandbox * sandbox,int a,int b,int c)205 absl::Status test_addition(sapi::Sandbox* sandbox, int a, int b, int c) {
206 SumApi f(sandbox);
207
208 SAPI_ASSIGN_OR_RETURN(int v, f.sum(a, b));
209 TRANSACTION_FAIL_IF_NOT(v == c, absl::StrCat(a, " + ", b, " != ", c));
210 return absl::OkStatus();
211 }
212
213 } // namespace
214
main(int argc,char * argv[])215 int main(int argc, char* argv[]) {
216 absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfo);
217 absl::ParseCommandLine(argc, argv);
218 absl::InitializeLog();
219
220 absl::Status status;
221
222 sapi::BasicTransaction st(std::make_unique<SumSandbox>());
223 // Using the simple transaction (and function pointers):
224 CHECK(st.Run(test_addition, 1, 1, 2).ok());
225 CHECK(st.Run(test_addition, 1336, 1, 1337).ok());
226 CHECK(st.Run(test_addition, 1336, 1, 7).code() ==
227 absl::StatusCode::kFailedPrecondition);
228
229 status = st.Run([](sapi::Sandbox* sandbox) -> absl::Status {
230 SumApi f(sandbox);
231
232 // Sums two int's held in a structure.
233 SumParams params;
234 params.mutable_data()->a = 1111;
235 params.mutable_data()->b = 222;
236 params.mutable_data()->ret = 0;
237 SAPI_RETURN_IF_ERROR(f.sums(params.PtrBoth()));
238 LOG(INFO) << "1111 + 222 = " << params.data().ret;
239 TRANSACTION_FAIL_IF_NOT(params.data().ret == 1333, "1111 + 222 != 1333");
240 return absl::OkStatus();
241 });
242 CHECK(status.ok()) << status.message();
243
244 status = st.Run([](sapi::Sandbox* sandbox) -> absl::Status {
245 SumApi f(sandbox);
246 SumParams params;
247 params.mutable_data()->a = 1111;
248 params.mutable_data()->b = -1000;
249 params.mutable_data()->ret = 0;
250 SAPI_RETURN_IF_ERROR(f.sums(params.PtrBoth()));
251 LOG(INFO) << "1111 - 1000 = " << params.data().ret;
252 TRANSACTION_FAIL_IF_NOT(params.data().ret == 111, "1111 - 1000 != 111");
253
254 // Without the wrapper class for struct.
255 sapi::v::Struct<sum_params> p;
256 p.mutable_data()->a = 1234;
257 p.mutable_data()->b = 5678;
258 p.mutable_data()->ret = 0;
259 SAPI_RETURN_IF_ERROR(f.sums(p.PtrBoth()));
260 LOG(INFO) << "1234 + 5678 = " << p.data().ret;
261 TRANSACTION_FAIL_IF_NOT(p.data().ret == 6912, "1234 + 5678 != 6912");
262 return absl::OkStatus();
263 });
264 CHECK(status.ok()) << status.message();
265
266 // Using overloaded transaction class:
267 SumTransaction sapi_crash{std::make_unique<SumSandbox>(), /*crash=*/true,
268 /*violate=*/false,
269 /*time_out=*/false};
270 status = sapi_crash.Run();
271 LOG(INFO) << "Final run result for crash: " << status;
272 CHECK(status.code() == absl::StatusCode::kUnavailable);
273
274 SumTransaction sapi_violate{std::make_unique<SumSandbox>(),
275 /*crash=*/false,
276 /*violate=*/true,
277 /*time_out=*/false};
278 status = sapi_violate.Run();
279 LOG(INFO) << "Final run result for violate: " << status;
280 CHECK(status.code() == absl::StatusCode::kUnavailable);
281
282 SumTransaction sapi_timeout(std::make_unique<SumSandbox>(),
283 /*crash=*/false,
284 /*violate=*/false,
285 /*time_out=*/true);
286 status = sapi_timeout.Run();
287 LOG(INFO) << "Final run result for timeout: " << status;
288 CHECK(status.code() == absl::StatusCode::kUnavailable);
289
290 SumTransaction sapi{std::make_unique<SumSandbox>(), /*crash=*/false,
291 /*violate=*/false, /*time_out=*/false};
292 for (int i = 0; i < 32; ++i) {
293 status = sapi.Run();
294 LOG(INFO) << "Final run result for not a crash: " << status.message();
295 CHECK(status.ok());
296 }
297 return 0;
298 }
299