xref: /aosp_15_r20/external/sandboxed-api/sandboxed_api/examples/sum/main_sum.cc (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 #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   sapi::v::NullPtr nptr;
135   LOG(INFO) << "Test whether pointer is NOT NULL - new pointers";
136   SAPI_RETURN_IF_ERROR(f.testptr(vp.PtrBefore()));
137   LOG(INFO) << "Test whether pointer is NULL";
138   SAPI_RETURN_IF_ERROR(f.testptr(&nptr));
139 
140   // Protobuf test.
141   sumsapi::SumParamsProto proto;
142   proto.set_a(10);
143   proto.set_b(20);
144   proto.set_c(30);
145   auto pp = sapi::v::Proto<sumsapi::SumParamsProto>::FromMessage(proto);
146   if (!pp.ok()) {
147     return pp.status();
148   }
149   SAPI_ASSIGN_OR_RETURN(v, f.sumproto(pp->PtrBefore()));
150   LOG(INFO) << "sumproto(proto {a = 10; b = 20; c = 30}) = " << v;
151   TRANSACTION_FAIL_IF_NOT(v == 60,
152                           "sumproto(proto {a = 10; b = 20; c = 30}) != 60");
153 
154   // Fd transfer test.
155   int fdesc = open("/proc/self/exe", O_RDONLY);
156   sapi::v::Fd fd(fdesc);
157   SAPI_RETURN_IF_ERROR(sandbox()->TransferToSandboxee(&fd));
158   LOG(INFO) << "remote_fd = " << fd.GetRemoteFd();
159   TRANSACTION_FAIL_IF_NOT(fd.GetRemoteFd() != -1, "remote_fd == -1");
160 
161   fdesc = open("/proc/self/comm", O_RDONLY);
162   sapi::v::Fd fd2(fdesc);
163   SAPI_RETURN_IF_ERROR(sandbox()->TransferToSandboxee(&fd2));
164   LOG(INFO) << "remote_fd2 = " << fd2.GetRemoteFd();
165   TRANSACTION_FAIL_IF_NOT(fd2.GetRemoteFd() != -1, "remote_fd2 == -1");
166 
167   // Read from fd test.
168   char buffer[1024] = {0};
169   sapi::v::Array<char> buf(buffer, sizeof(buffer));
170   sapi::v::UInt size(128);
171   SAPI_RETURN_IF_ERROR(
172       sandbox()->Call("read", &ret, &fd2, buf.PtrBoth(), &size));
173   LOG(INFO) << "Read from /proc/self/comm = [" << buffer << "]";
174 
175   // Close test.
176   SAPI_RETURN_IF_ERROR(fd2.CloseRemoteFd(sandbox()->rpc_channel()));
177   memset(buffer, 0, sizeof(buffer));
178   SAPI_RETURN_IF_ERROR(
179       sandbox()->Call("read", &ret, &fd2, buf.PtrBoth(), &size));
180   LOG(INFO) << "Read from closed /proc/self/comm = [" << buffer << "]";
181 
182   // Pass fd as function arg example.
183   fdesc = open("/proc/self/statm", O_RDONLY);
184   sapi::v::Fd fd3(fdesc);
185   SAPI_RETURN_IF_ERROR(sandbox()->TransferToSandboxee(&fd3));
186   SAPI_ASSIGN_OR_RETURN(int r2, f.read_int(fd3.GetRemoteFd()));
187   LOG(INFO) << "statm value (should not be 0) = " << r2;
188 
189   if (crash_) {
190     // Crashes the sandboxed part with SIGSEGV
191     LOG(INFO) << "Crash with SIGSEGV";
192     SAPI_RETURN_IF_ERROR(f.crash());
193   }
194 
195   if (violate_) {
196     LOG(INFO) << "Cause a sandbox (syscall) violation";
197     SAPI_RETURN_IF_ERROR(f.violate());
198   }
199 
200   if (time_out_) {
201     SAPI_RETURN_IF_ERROR(f.sleep_for_sec(kTimeOutVal * 2));
202   }
203   return absl::OkStatus();
204 }
205 
test_addition(sapi::Sandbox * sandbox,int a,int b,int c)206 absl::Status test_addition(sapi::Sandbox* sandbox, int a, int b, int c) {
207   SumApi f(sandbox);
208 
209   SAPI_ASSIGN_OR_RETURN(int v, f.sum(a, b));
210   TRANSACTION_FAIL_IF_NOT(v == c, absl::StrCat(a, " + ", b, " != ", c));
211   return absl::OkStatus();
212 }
213 
214 }  // namespace
215 
main(int argc,char * argv[])216 int main(int argc, char* argv[]) {
217   absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfo);
218   absl::ParseCommandLine(argc, argv);
219   absl::InitializeLog();
220 
221   absl::Status status;
222 
223   sapi::BasicTransaction st(std::make_unique<SumSandbox>());
224   // Using the simple transaction (and function pointers):
225   CHECK(st.Run(test_addition, 1, 1, 2).ok());
226   CHECK(st.Run(test_addition, 1336, 1, 1337).ok());
227   CHECK(st.Run(test_addition, 1336, 1, 7).code() ==
228         absl::StatusCode::kFailedPrecondition);
229 
230   status = st.Run([](sapi::Sandbox* sandbox) -> absl::Status {
231     SumApi f(sandbox);
232 
233     // Sums two int's held in a structure.
234     SumParams params;
235     params.mutable_data()->a = 1111;
236     params.mutable_data()->b = 222;
237     params.mutable_data()->ret = 0;
238     SAPI_RETURN_IF_ERROR(f.sums(params.PtrBoth()));
239     LOG(INFO) << "1111 + 222 = " << params.data().ret;
240     TRANSACTION_FAIL_IF_NOT(params.data().ret == 1333, "1111 + 222 != 1333");
241     return absl::OkStatus();
242   });
243   CHECK(status.ok()) << status.message();
244 
245   status = st.Run([](sapi::Sandbox* sandbox) -> absl::Status {
246     SumApi f(sandbox);
247     SumParams params;
248     params.mutable_data()->a = 1111;
249     params.mutable_data()->b = -1000;
250     params.mutable_data()->ret = 0;
251     SAPI_RETURN_IF_ERROR(f.sums(params.PtrBoth()));
252     LOG(INFO) << "1111 - 1000 = " << params.data().ret;
253     TRANSACTION_FAIL_IF_NOT(params.data().ret == 111, "1111 - 1000 != 111");
254 
255     // Without the wrapper class for struct.
256     sapi::v::Struct<sum_params> p;
257     p.mutable_data()->a = 1234;
258     p.mutable_data()->b = 5678;
259     p.mutable_data()->ret = 0;
260     SAPI_RETURN_IF_ERROR(f.sums(p.PtrBoth()));
261     LOG(INFO) << "1234 + 5678 = " << p.data().ret;
262     TRANSACTION_FAIL_IF_NOT(p.data().ret == 6912, "1234 + 5678 != 6912");
263     return absl::OkStatus();
264   });
265   CHECK(status.ok()) << status.message();
266 
267   // Using overloaded transaction class:
268   SumTransaction sapi_crash{std::make_unique<SumSandbox>(), /*crash=*/true,
269                             /*violate=*/false,
270                             /*time_out=*/false};
271   status = sapi_crash.Run();
272   LOG(INFO) << "Final run result for crash: " << status;
273   CHECK(status.code() == absl::StatusCode::kUnavailable);
274 
275   SumTransaction sapi_violate{std::make_unique<SumSandbox>(),
276                               /*crash=*/false,
277                               /*violate=*/true,
278                               /*time_out=*/false};
279   status = sapi_violate.Run();
280   LOG(INFO) << "Final run result for violate: " << status;
281   CHECK(status.code() == absl::StatusCode::kUnavailable);
282 
283   SumTransaction sapi_timeout(std::make_unique<SumSandbox>(),
284                               /*crash=*/false,
285                               /*violate=*/false,
286                               /*time_out=*/true);
287   status = sapi_timeout.Run();
288   LOG(INFO) << "Final run result for timeout: " << status;
289   CHECK(status.code() == absl::StatusCode::kUnavailable);
290 
291   SumTransaction sapi{std::make_unique<SumSandbox>(), /*crash=*/false,
292                       /*violate=*/false, /*time_out=*/false};
293   for (int i = 0; i < 32; ++i) {
294     status = sapi.Run();
295     LOG(INFO) << "Final run result for not a crash: " << status.message();
296     CHECK(status.ok());
297   }
298   return 0;
299 }
300