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 binary which is intended to be sandboxed by the
16 // sandbox2, and which uses a built-in fork-server to spawn new sandboxees
17 // (instead of doing fork/execve via the Fork-Server).
18
19 #include <unistd.h>
20
21 #include <cstdint>
22
23 #include "absl/base/log_severity.h"
24 #include "absl/flags/parse.h"
25 #include "absl/log/globals.h"
26 #include "absl/log/initialize.h"
27 #include "sandboxed_api/sandbox2/comms.h"
28 #include "sandboxed_api/sandbox2/forkingclient.h"
29 #include "sandboxed_api/util/raw_logging.h"
30
31 // Just return the value received over the Comms channel from the parent.
SandboxeeFunction(sandbox2::Comms * comms)32 static int SandboxeeFunction(sandbox2::Comms* comms) {
33 int32_t i;
34 // SAPI_RAW_CHECK() uses smaller set of syscalls than regular CHECK().
35 SAPI_RAW_CHECK(comms->RecvInt32(&i), "Receiving an int32_t");
36
37 // Make sure that we're not the init process in the custom forkserver
38 // child.
39 SAPI_RAW_CHECK(getpid() == 2, "Unexpected PID");
40 return i;
41 }
42
main(int argc,char * argv[])43 int main(int argc, char* argv[]) {
44 absl::ParseCommandLine(argc, argv);
45
46 // Writing to stderr limits the number of invoked syscalls.
47 absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfo);
48 absl::InitializeLog();
49
50 // Instantiate Comms channel with the parent Executor
51 sandbox2::Comms comms(sandbox2::Comms::kDefaultConnection);
52 sandbox2::ForkingClient s2client(&comms);
53
54 for (;;) {
55 // Start a new process, if the sandboxer requests us to do so. No need to
56 // wait for the new process, as the call to sandbox2::Client::Fork will
57 // indirectly call sigaction(SIGCHLD, sa_flags=SA_NOCLDWAIT) in the parent.
58 pid_t pid = s2client.WaitAndFork();
59 if (pid == -1) {
60 SAPI_RAW_CHECK(false, "Could not spawn a new sandboxee");
61 }
62 // Child - return to the main(), to continue with code which is supposed to
63 // be sandboxed. From now on the comms channel (in the child) is set up over
64 // a new file descriptor pair, reachable from a separate Executor in the
65 // sandboxer.
66 if (pid == 0) {
67 break;
68 }
69 }
70
71 // Start sandboxing here
72 s2client.SandboxMeHere();
73
74 // This section of code runs sandboxed
75 return SandboxeeFunction(&comms);
76 }
77