1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "sandbox/linux/suid/client/setuid_sandbox_client.h"
9 #include <sys/socket.h>
11 #include <sys/types.h>
15 #include "base/command_line.h"
16 #include "base/environment.h"
17 #include "base/files/file_path.h"
18 #include "base/files/file_util.h"
19 #include "base/files/scoped_file.h"
20 #include "base/logging.h"
21 #include "base/macros.h"
22 #include "base/memory/scoped_ptr.h"
23 #include "base/path_service.h"
24 #include "base/posix/eintr_wrapper.h"
25 #include "base/process/launch.h"
26 #include "base/process/process_metrics.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "sandbox/linux/services/init_process_reaper.h"
29 #include "sandbox/linux/suid/common/sandbox.h"
30 #include "sandbox/linux/suid/common/suid_unsafe_environment_variables.h"
34 bool IsFileSystemAccessDenied() {
35 base::ScopedFD
self_exe(HANDLE_EINTR(open(base::kProcSelfExe
, O_RDONLY
)));
36 return !self_exe
.is_valid();
39 // Set an environment variable that reflects the API version we expect from the
40 // setuid sandbox. Old versions of the sandbox will ignore this.
41 void SetSandboxAPIEnvironmentVariable(base::Environment
* env
) {
42 env
->SetVar(sandbox::kSandboxEnvironmentApiRequest
,
43 base::IntToString(sandbox::kSUIDSandboxApiNumber
));
46 // Unset environment variables that are expected to be set by the setuid
47 // sandbox. This is to allow nesting of one instance of the SUID sandbox
49 void UnsetExpectedEnvironmentVariables(base::EnvironmentMap
* env_map
) {
51 const base::NativeEnvironmentString environment_vars
[] = {
52 sandbox::kSandboxDescriptorEnvironmentVarName
,
53 sandbox::kSandboxHelperPidEnvironmentVarName
,
54 sandbox::kSandboxEnvironmentApiProvides
,
55 sandbox::kSandboxPIDNSEnvironmentVarName
,
56 sandbox::kSandboxNETNSEnvironmentVarName
,
59 for (size_t i
= 0; i
< arraysize(environment_vars
); ++i
) {
60 // Setting values in EnvironmentMap to an empty-string will make
61 // sure that they get unset from the environment via AlterEnvironment().
62 (*env_map
)[environment_vars
[i
]] = base::NativeEnvironmentString();
66 // Wrapper around a shared C function.
67 // Returns the "saved" environment variable name corresponding to |envvar|
68 // in a new string or NULL.
69 std::string
* CreateSavedVariableName(const char* env_var
) {
70 char* const saved_env_var
= SandboxSavedEnvironmentVariable(env_var
);
73 std::string
* saved_env_var_copy
= new std::string(saved_env_var
);
74 // SandboxSavedEnvironmentVariable is the C function that we wrap and uses
75 // malloc() to allocate memory.
77 return saved_env_var_copy
;
80 // The ELF loader will clear many environment variables so we save them to
81 // different names here so that the SUID sandbox can resolve them for the
83 void SaveSUIDUnsafeEnvironmentVariables(base::Environment
* env
) {
84 for (unsigned i
= 0; kSUIDUnsafeEnvironmentVariables
[i
]; ++i
) {
85 const char* env_var
= kSUIDUnsafeEnvironmentVariables
[i
];
86 // Get the saved environment variable corresponding to envvar.
87 scoped_ptr
<std::string
> saved_env_var(CreateSavedVariableName(env_var
));
88 if (saved_env_var
== NULL
)
92 if (env
->GetVar(env_var
, &value
))
93 env
->SetVar(saved_env_var
->c_str(), value
);
95 env
->UnSetVar(saved_env_var
->c_str());
99 int GetHelperApi(base::Environment
* env
) {
100 std::string api_string
;
101 int api_number
= 0; // Assume API version 0 if no environment was found.
102 if (env
->GetVar(sandbox::kSandboxEnvironmentApiProvides
, &api_string
) &&
103 !base::StringToInt(api_string
, &api_number
)) {
104 // It's an error if we could not convert the API number.
110 // Convert |var_name| from the environment |env| to an int.
111 // Return -1 if the variable does not exist or the value cannot be converted.
112 int EnvToInt(base::Environment
* env
, const char* var_name
) {
113 std::string var_string
;
115 if (env
->GetVar(var_name
, &var_string
) &&
116 !base::StringToInt(var_string
, &var_value
)) {
122 pid_t
GetHelperPID(base::Environment
* env
) {
123 return EnvToInt(env
, sandbox::kSandboxHelperPidEnvironmentVarName
);
126 // Get the IPC file descriptor used to communicate with the setuid helper.
127 int GetIPCDescriptor(base::Environment
* env
) {
128 return EnvToInt(env
, sandbox::kSandboxDescriptorEnvironmentVarName
);
131 const char* GetDevelSandboxPath() {
132 return getenv("CHROME_DEVEL_SANDBOX");
139 SetuidSandboxClient
* SetuidSandboxClient::Create() {
140 base::Environment
* environment(base::Environment::Create());
141 SetuidSandboxClient
* sandbox_client(new SetuidSandboxClient
);
144 sandbox_client
->env_
= environment
;
145 return sandbox_client
;
148 SetuidSandboxClient::SetuidSandboxClient()
153 SetuidSandboxClient::~SetuidSandboxClient() {
157 void SetuidSandboxClient::CloseDummyFile() {
158 // When we're launched through the setuid sandbox, SetupLaunchOptions
159 // arranges for kZygoteIdFd to be a dummy file descriptor to satisfy an
160 // ancient setuid sandbox ABI requirement. However, the descriptor is no
161 // longer needed, so we can simply close it right away now.
162 CHECK(IsSuidSandboxChild());
164 // Sanity check that kZygoteIdFd refers to a pipe.
166 PCHECK(0 == fstat(kZygoteIdFd
, &st
));
167 CHECK(S_ISFIFO(st
.st_mode
));
169 PCHECK(0 == IGNORE_EINTR(close(kZygoteIdFd
)));
172 bool SetuidSandboxClient::ChrootMe() {
173 int ipc_fd
= GetIPCDescriptor(env_
);
176 LOG(ERROR
) << "Failed to obtain the sandbox IPC descriptor";
180 if (HANDLE_EINTR(write(ipc_fd
, &kMsgChrootMe
, 1)) != 1) {
181 PLOG(ERROR
) << "Failed to write to chroot pipe";
185 // We need to reap the chroot helper process in any event.
186 pid_t helper_pid
= GetHelperPID(env_
);
187 // If helper_pid is -1 we wait for any child.
188 if (HANDLE_EINTR(waitpid(helper_pid
, NULL
, 0)) < 0) {
189 PLOG(ERROR
) << "Failed to wait for setuid helper to die";
194 if (HANDLE_EINTR(read(ipc_fd
, &reply
, 1)) != 1) {
195 PLOG(ERROR
) << "Failed to read from chroot pipe";
199 if (reply
!= kMsgChrootSuccessful
) {
200 LOG(ERROR
) << "Error code reply from chroot helper";
204 // We now consider ourselves "fully sandboxed" as far as the
205 // setuid sandbox is concerned.
206 CHECK(IsFileSystemAccessDenied());
211 bool SetuidSandboxClient::CreateInitProcessReaper(
212 base::Closure
* post_fork_parent_callback
) {
213 return sandbox::CreateInitProcessReaper(post_fork_parent_callback
);
216 bool SetuidSandboxClient::IsSuidSandboxUpToDate() const {
217 return GetHelperApi(env_
) == kSUIDSandboxApiNumber
;
220 bool SetuidSandboxClient::IsSuidSandboxChild() const {
221 return GetIPCDescriptor(env_
) >= 0;
224 bool SetuidSandboxClient::IsInNewPIDNamespace() const {
225 return env_
->HasVar(kSandboxPIDNSEnvironmentVarName
);
228 bool SetuidSandboxClient::IsInNewNETNamespace() const {
229 return env_
->HasVar(kSandboxNETNSEnvironmentVarName
);
232 bool SetuidSandboxClient::IsSandboxed() const {
236 // Check if CHROME_DEVEL_SANDBOX is set but empty. This currently disables
237 // the setuid sandbox. TODO(jln): fix this (crbug.com/245376).
238 bool SetuidSandboxClient::IsDisabledViaEnvironment() {
239 const char* devel_sandbox_path
= GetDevelSandboxPath();
240 if (devel_sandbox_path
&& '\0' == *devel_sandbox_path
) {
246 base::FilePath
SetuidSandboxClient::GetSandboxBinaryPath() {
247 base::FilePath sandbox_binary
;
248 base::FilePath exe_dir
;
249 if (PathService::Get(base::DIR_EXE
, &exe_dir
)) {
250 base::FilePath sandbox_candidate
= exe_dir
.AppendASCII("chrome-sandbox");
251 if (base::PathExists(sandbox_candidate
))
252 sandbox_binary
= sandbox_candidate
;
255 // In user-managed builds, including development builds, an environment
256 // variable is required to enable the sandbox. See
257 // http://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment
259 if (sandbox_binary
.empty() && stat(base::kProcSelfExe
, &st
) == 0 &&
260 st
.st_uid
== getuid()) {
261 const char* devel_sandbox_path
= GetDevelSandboxPath();
262 if (devel_sandbox_path
) {
263 sandbox_binary
= base::FilePath(devel_sandbox_path
);
267 return sandbox_binary
;
270 void SetuidSandboxClient::PrependWrapper(base::CommandLine
* cmd_line
) {
271 std::string
sandbox_binary(GetSandboxBinaryPath().value());
273 if (sandbox_binary
.empty() || stat(sandbox_binary
.c_str(), &st
) != 0) {
274 LOG(FATAL
) << "The SUID sandbox helper binary is missing: "
275 << sandbox_binary
<< " Aborting now. See "
276 "https://code.google.com/p/chromium/wiki/"
277 "LinuxSUIDSandboxDevelopment.";
280 if (access(sandbox_binary
.c_str(), X_OK
) != 0 || (st
.st_uid
!= 0) ||
281 ((st
.st_mode
& S_ISUID
) == 0) || ((st
.st_mode
& S_IXOTH
)) == 0) {
282 LOG(FATAL
) << "The SUID sandbox helper binary was found, but is not "
283 "configured correctly. Rather than run without sandboxing "
284 "I'm aborting now. You need to make sure that "
285 << sandbox_binary
<< " is owned by root and has mode 4755.";
288 cmd_line
->PrependWrapper(sandbox_binary
);
291 void SetuidSandboxClient::SetupLaunchOptions(
292 base::LaunchOptions
* options
,
293 base::FileHandleMappingVector
* fds_to_remap
,
294 base::ScopedFD
* dummy_fd
) {
296 DCHECK(fds_to_remap
);
298 // Launching a setuid binary requires PR_SET_NO_NEW_PRIVS to not be used.
299 options
->allow_new_privs
= true;
300 UnsetExpectedEnvironmentVariables(&options
->environ
);
302 // Set dummy_fd to the reading end of a closed pipe.
304 PCHECK(0 == pipe(pipe_fds
));
305 PCHECK(0 == IGNORE_EINTR(close(pipe_fds
[1])));
306 dummy_fd
->reset(pipe_fds
[0]);
308 // We no longer need a dummy socket for discovering the child's PID,
309 // but the sandbox is still hard-coded to expect a file descriptor at
310 // kZygoteIdFd. Fixing this requires a sandbox API change. :(
311 fds_to_remap
->push_back(std::make_pair(dummy_fd
->get(), kZygoteIdFd
));
314 void SetuidSandboxClient::SetupLaunchEnvironment() {
315 SaveSUIDUnsafeEnvironmentVariables(env_
);
316 SetSandboxAPIEnvironmentVariable(env_
);
319 } // namespace sandbox