Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(144)

Side by Side Diff: sandbox/linux/services/broker_process.cc

Issue 11557025: Linux sandbox: add a new low-level broker process mechanism. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Add copyright notice Created 8 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
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.
4
5 #include "sandbox/linux/services/broker_process.h"
6
7 #include <fcntl.h>
8 #include <sys/socket.h>
9 #include <sys/stat.h>
10 #include <sys/types.h>
11 #include <unistd.h>
12
13 #include <algorithm>
14 #include <string>
15 #include <vector>
16
17 #include "base/basictypes.h"
18 #include "base/logging.h"
19 #include "base/pickle.h"
20 #include "base/posix/eintr_wrapper.h"
21 #include "base/posix/unix_domain_socket.h"
22
23 namespace {
24
25 static const int kCommandOpen = 'O';
26 static const size_t kMaxMessageLength = 4096;
27
28 // Some flags will need special treatment on the client side and are not
29 // supported for now.
30 int ForCurrentProcessFlagsMask() {
31 return O_CLOEXEC | O_NONBLOCK;
32 }
33
34 // Check whether |requested_filename| is in |allowed_file_names|.
35 // See GetFileNameIfAllowedAccess() for an explaination of |file_to_open|.
36 // async signal safe if |file_to_open| is NULL.
37 // TODO(jln): assert signal safety.
38 bool GetFileNameInWhitelist(const std::vector<std::string>& allowed_file_names,
39 const std::string& requested_filename,
40 const char** file_to_open) {
41 if (file_to_open && *file_to_open) {
42 // Make sure that callers never pass a non-empty string. In case callers
43 // wrongly forget to check the return value and look at the string
44 // instead, this could catch bugs.
45 RAW_LOG(FATAL, "*file_to_open should be NULL");
46 return false;
47 }
48 std::vector<std::string>::const_iterator it;
49 it = std::find(allowed_file_names.begin(), allowed_file_names.end(),
50 requested_filename);
51 if (it < allowed_file_names.end()) { // requested_filename was found?
52 if (file_to_open)
53 *file_to_open = it->c_str();
54 return true;
55 }
56 return false;
57 }
58
59 // We maintain a list of flags that have been reviewed for "sanity" and that
60 // we're ok to allow in the broker.
61 // I.e. here is where we wouldn't add O_RESET_FILE_SYSTEM.
62 bool IsAllowedOpenFlags(int flags) {
63 // First, check the access mode
64 const int access_mode = flags & O_ACCMODE;
65 if (access_mode != O_RDONLY && access_mode != O_WRONLY &&
66 access_mode != O_RDWR) {
67 return false;
68 }
69
70 // Some flags affect the behavior of the current process. We don't support
71 // them and don't allow them for now.
72 if (flags & ForCurrentProcessFlagsMask()) {
73 return false;
74 }
75
76 // Now check that all the flags are known to us.
77 const int creation_and_status_flags = flags & ~O_ACCMODE;
78
79 const int known_flags =
80 O_APPEND | O_ASYNC | O_CLOEXEC | O_CREAT | O_DIRECT |
81 O_DIRECTORY | O_EXCL | O_LARGEFILE | O_NOATIME | O_NOCTTY |
82 O_NOFOLLOW | O_NONBLOCK | O_NDELAY | O_SYNC | O_TRUNC;
83
84 const int unknown_flags = ~known_flags;
85 const bool has_unknown_flags = creation_and_status_flags & unknown_flags;
86 return !has_unknown_flags;
87 }
88
89 } // namespace
90
91 namespace sandbox {
92
93 BrokerProcess::BrokerProcess(const std::vector<std::string>& allowed_r_files,
94 const std::vector<std::string>& allowed_w_files,
95 bool fast_check_in_client,
96 bool quiet_failures_for_tests)
97 : initialized_(false),
98 is_child_(false),
99 fast_check_in_client_(fast_check_in_client),
100 quiet_failures_for_tests_(quiet_failures_for_tests),
101 broker_pid_(-1),
102 allowed_r_files_(allowed_r_files),
103 allowed_w_files_(allowed_w_files),
104 ipc_socketpair_(-1) {
105 }
106
107 BrokerProcess::~BrokerProcess() {
108 if (initialized_ && ipc_socketpair_ != -1) {
109 void (HANDLE_EINTR(close(ipc_socketpair_)));
110 }
111 }
112
113 bool BrokerProcess::Init(void* sandbox_callback) {
114 CHECK(!initialized_);
115 CHECK_EQ(sandbox_callback, (void*) NULL) <<
116 "sandbox_callback is not implemented";
117 int socket_pair[2];
118 // Use SOCK_SEQPACKET, because we need to preserve message boundaries
119 // but we also want to be notified (recvmsg should return and not block)
120 // when the connection has been broken (one of the processes died).
121 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, socket_pair)) {
122 LOG(ERROR) << "Failed to create socketpair";
123 return false;
124 }
125
126 int child_pid = fork();
127 if (child_pid == -1) {
128 (void) HANDLE_EINTR(close(socket_pair[0]));
129 (void) HANDLE_EINTR(close(socket_pair[1]));
130 return false;
131 }
132 if (child_pid) {
133 // We are the parent and we have just forked our broker process.
134 (void) HANDLE_EINTR(close(socket_pair[0]));
135 // We should only be able to write to the IPC channel. We'll always send
136 // a new file descriptor to receive the reply on.
137 shutdown(socket_pair[1], SHUT_RD);
138 ipc_socketpair_ = socket_pair[1];
139 is_child_ = false;
140 broker_pid_ = child_pid;
141 initialized_ = true;
142 return true;
143 } else {
144 // We are the broker.
145 (void) HANDLE_EINTR(close(socket_pair[1]));
146 // We should only be able to read from this IPC channel. We will send our
147 // replies on a new file descriptor attached to the requests.
148 shutdown(socket_pair[0], SHUT_WR);
149 ipc_socketpair_ = socket_pair[0];
150 is_child_ = true;
151 // TODO(jln): activate a sandbox here.
152 initialized_ = true;
153 for (;;) {
154 HandleRequest();
155 }
156 _exit(1);
157 }
158 NOTREACHED();
159 }
160
161 // This function needs to be async signal safe.
162 int BrokerProcess::Open(const char* pathname, int flags) const {
163 RAW_CHECK(initialized_); // async signal safe CHECK().
164 if (!pathname)
165 return -EFAULT;
166 // There is no point in forwarding a request that we know will be denied.
167 // Of course, the real security check needs to be on the other side of the
168 // IPC.
169 if (fast_check_in_client_) {
170 if (!GetFileNameIfAllowedAccess(pathname, flags, NULL))
171 return -EPERM;
172 }
173
174 Pickle write_pickle;
175 write_pickle.WriteInt(kCommandOpen);
176 write_pickle.WriteString(pathname);
177 write_pickle.WriteInt(flags);
178 RAW_CHECK(write_pickle.size() <= kMaxMessageLength);
179
180 int returned_fd = -1;
181 uint8_t reply_buf[kMaxMessageLength];
182 // Send a request (in write_pickle) as well that will include a new
183 // temporary socketpair (created internally by SendRecvMsg()).
184 // Then read the reply on this new socketpair in reply_buf and put an
185 // eventual attached file descriptor in |returned_fd|.
186 // TODO(jln): this API needs some rewriting and documentation.
187 ssize_t msg_len = UnixDomainSocket::SendRecvMsg(ipc_socketpair_,
188 reply_buf,
189 sizeof(reply_buf),
190 &returned_fd,
191 write_pickle);
192 if (msg_len <= 0) {
193 if (!quiet_failures_for_tests_)
194 RAW_LOG(ERROR, "Could not make request to broker process");
195 return -ENOMEM;
196 }
197
198 Pickle read_pickle(reinterpret_cast<char*>(reply_buf), msg_len);
199 PickleIterator iter(read_pickle);
200 int return_value = -1;
201 // Now deserialize the return value and eventually return the file
202 // descriptor.
203 if (read_pickle.ReadInt(&iter, &return_value)) {
204 if (return_value < 0) {
205 RAW_CHECK(returned_fd == -1);
206 return return_value;
207 } else {
208 // We have a real file descriptor to return.
209 RAW_CHECK(returned_fd >= 0);
210 return returned_fd;
211 }
212 } else {
213 RAW_LOG(ERROR, "Could not read pickle");
214 return -1;
215 }
216 }
217
218 // Handle a request on the IPC channel ipc_socketpair_.
219 // A request should have a file descriptor attached on which we will reply and
220 // that we will then close.
221 // A request should start with an int that will be used as the command type.
222 bool BrokerProcess::HandleRequest() const {
223
224 std::vector<int> fds;
225 char buf[kMaxMessageLength];
226 errno = 0;
227 const ssize_t msg_len = UnixDomainSocket::RecvMsg(ipc_socketpair_, buf,
228 sizeof(buf), &fds);
229
230 if (msg_len == 0 || (msg_len == -1 && errno == ECONNRESET)) {
231 // EOF from our parent, or our parent died, we should die.
232 _exit(0);
233 }
234
235 // The parent should send exactly one file descriptor, on which we
236 // will write the reply.
237 if (msg_len < 0 || fds.size() != 1 || fds.at(0) < 0) {
238 PLOG(ERROR) << "Error reading message from the client";
239 return false;
240 }
241
242 const int temporary_ipc = fds.at(0);
243
244 Pickle pickle(buf, msg_len);
245 PickleIterator iter(pickle);
246 int command_type;
247 if (pickle.ReadInt(&iter, &command_type)) {
248 bool r = false;
249 // Go through all the possible IPC messages.
250 switch (command_type) {
251 case kCommandOpen:
252 // We reply on the file descriptor sent to us via the IPC channel.
253 r = HandleOpenRequest(temporary_ipc, pickle, iter);
254 (void) HANDLE_EINTR(close(temporary_ipc));
255 return r;
256 default:
257 NOTREACHED();
258 return false;
259 }
260 }
261
262 LOG(ERROR) << "Error parsing IPC request";
263 return false;
264 }
265
266 // Handle an open request contained in |read_pickle| and send the reply
267 // on |reply_ipc|.
268 bool BrokerProcess::HandleOpenRequest(int reply_ipc,
269 const Pickle& read_pickle,
270 PickleIterator iter) const {
271 std::string requested_filename;
272 int flags = 0;
273 if (!read_pickle.ReadString(&iter, &requested_filename) ||
274 !read_pickle.ReadInt(&iter, &flags)) {
275 return -1;
276 }
277
278 Pickle write_pickle;
279 std::vector<int> opened_files;
280
281 const char* file_to_open = NULL;
282 const bool safe_to_open_file = GetFileNameIfAllowedAccess(
283 requested_filename.c_str(), flags, &file_to_open);
284
285 if (safe_to_open_file) {
286 CHECK(file_to_open);
287 // O_CLOEXEC doesn't hurt (even though we won't execve()), and this
288 // property won't be passed to the client.
289 // We may want to think about O_NONBLOCK as well.
290 int opened_fd = open(file_to_open, flags | O_CLOEXEC);
291 if (opened_fd < 0) {
292 write_pickle.WriteInt(-errno);
293 } else {
294 // Success.
295 opened_files.push_back(opened_fd);
296 write_pickle.WriteInt(0);
297 }
298 } else {
299 write_pickle.WriteInt(-EPERM);
300 }
301
302 CHECK_LE(write_pickle.size(), kMaxMessageLength);
303 ssize_t sent = UnixDomainSocket::SendMsg(reply_ipc, write_pickle.data(),
304 write_pickle.size(), opened_files);
305
306 // Close anything we have opened in this process.
307 for (std::vector<int>::iterator it = opened_files.begin();
308 it < opened_files.end(); ++it) {
309 (void) HANDLE_EINTR(close(*it));
310 }
311
312 if (sent <= 0) {
313 LOG(ERROR) << "Could not send IPC reply";
314 return false;
315 }
316 return true;
317 }
318
319 // For paranoia, if |file_to_open| is not NULL, we will return the matching
320 // string from the white list.
321 // Async signal safe only if |file_to_open| is NULL.
322 // Even if an attacker managed to fool the string comparison mechanism, we
323 // would not open an attacker-controlled file name.
324 // Return true if access should be allowed, false otherwise.
325 bool BrokerProcess::GetFileNameIfAllowedAccess(const char* requested_filename,
326 int requested_flags, const char** file_to_open) const {
327 if (!IsAllowedOpenFlags(requested_flags)) {
328 return false;
329 }
330 switch (requested_flags & O_ACCMODE) {
331 case O_RDONLY:
332 return GetFileNameInWhitelist(allowed_r_files_, requested_filename,
333 file_to_open);
334 case O_WRONLY:
335 return GetFileNameInWhitelist(allowed_w_files_, requested_filename,
336 file_to_open);
337 case O_RDWR:
338 {
339 bool allowed_for_read_and_write =
340 GetFileNameInWhitelist(allowed_r_files_, requested_filename, NULL) &&
341 GetFileNameInWhitelist(allowed_w_files_, requested_filename,
342 file_to_open);
343 return allowed_for_read_and_write;
344 }
345 default:
346 return false;
347 }
348 }
349
350 } // namespace sandbox.
OLDNEW
« no previous file with comments | « sandbox/linux/services/broker_process.h ('k') | sandbox/linux/services/broker_process_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698