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 <sys/prctl.h>
16
17 #include <csignal>
18 #include <cstdlib>
19
20 #include "absl/base/log_severity.h"
21 #include "absl/log/globals.h"
22 #include "absl/status/status.h"
23 #include "sandboxed_api/sandbox2/client.h"
24 #include "sandboxed_api/sandbox2/comms.h"
25 #include "sandboxed_api/sandbox2/forkserver.h"
26 #include "sandboxed_api/sandbox2/sanitizer.h"
27 #include "sandboxed_api/sandbox2/unwind/unwind.h"
28 #include "sandboxed_api/util/raw_logging.h"
29
main()30 int main() {
31 // Make sure the logs go stderr.
32 absl::SetStderrThreshold(absl::LogSeverityAtLeast::kInfo);
33
34 // Close all non-essential FDs to keep newly opened FD numbers consistent.
35 absl::Status status = sandbox2::sanitizer::CloseAllFDsExcept(
36 {0, 1, 2, sandbox2::Comms::kSandbox2ClientCommsFD});
37
38 if (!status.ok()) {
39 SAPI_RAW_LOG(WARNING, "Closing non-essential FDs failed");
40 }
41
42 // Make the process' name easily recognizable with ps/pstree.
43 if (prctl(PR_SET_NAME, "S2-FORK-SERV", 0, 0, 0) != 0) {
44 SAPI_RAW_PLOG(WARNING, "prctl(PR_SET_NAME, 'S2-FORK-SERV')");
45 }
46
47 // Don't react (with stack-tracing) to SIGTERM's sent from other processes
48 // (e.g. from the borglet or SubProcess). This ForkServer should go down if
49 // the parent goes down (or if the GlobalForkServerComms is closed), which is
50 // assured by prctl(PR_SET_PDEATHSIG, SIGKILL) being called in the
51 // ForkServer::Initialize(). We don't want to change behavior of non-global
52 // ForkServers, hence it's called here and not in the
53 // ForkServer::Initialize().
54 struct sigaction sa;
55 sa.sa_handler = SIG_IGN;
56 sa.sa_flags = 0;
57 sigemptyset(&sa.sa_mask);
58 if (sigaction(SIGTERM, &sa, nullptr) == -1) {
59 SAPI_RAW_PLOG(WARNING, "sigaction(SIGTERM, sa_handler=SIG_IGN)");
60 }
61
62 sandbox2::Comms comms(sandbox2::Comms::kDefaultConnection);
63 sandbox2::ForkServer fork_server(&comms);
64 sandbox2::sanitizer::WaitForSanitizer();
65
66 while (!fork_server.IsTerminated()) {
67 pid_t child_pid = fork_server.ServeRequest();
68 if (child_pid == 0) {
69 sandbox2::Client client(&comms);
70 client.SandboxMeHere();
71 return sandbox2::RunLibUnwindAndSymbolizer(&comms) ? EXIT_SUCCESS
72 : EXIT_FAILURE;
73 }
74 }
75 SAPI_RAW_VLOG(1, "ForkServer Comms closed. Exiting");
76 }
77