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

Side by Side Diff: sandbox/src/broker_services.cc

Issue 10689170: Move the Windows sandbox to sandbox/win (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Rebase on top of tree (properly this time) Created 8 years, 5 months 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
« no previous file with comments | « sandbox/src/broker_services.h ('k') | sandbox/src/crosscall_client.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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/src/broker_services.h"
6
7 #include "base/logging.h"
8 #include "base/memory/scoped_ptr.h"
9 #include "base/threading/platform_thread.h"
10 #include "base/win/scoped_handle.h"
11 #include "base/win/scoped_process_information.h"
12 #include "sandbox/src/sandbox_policy_base.h"
13 #include "sandbox/src/sandbox.h"
14 #include "sandbox/src/target_process.h"
15 #include "sandbox/src/win2k_threadpool.h"
16 #include "sandbox/src/win_utils.h"
17
18 namespace {
19
20 // Utility function to associate a completion port to a job object.
21 bool AssociateCompletionPort(HANDLE job, HANDLE port, void* key) {
22 JOBOBJECT_ASSOCIATE_COMPLETION_PORT job_acp = { key, port };
23 return ::SetInformationJobObject(job,
24 JobObjectAssociateCompletionPortInformation,
25 &job_acp, sizeof(job_acp))? true : false;
26 }
27
28 // Utility function to do the cleanup necessary when something goes wrong
29 // while in SpawnTarget and we must terminate the target process.
30 sandbox::ResultCode SpawnCleanup(sandbox::TargetProcess* target, DWORD error) {
31 if (0 == error)
32 error = ::GetLastError();
33
34 target->Terminate();
35 delete target;
36 ::SetLastError(error);
37 return sandbox::SBOX_ERROR_GENERIC;
38 }
39
40 // the different commands that you can send to the worker thread that
41 // executes TargetEventsThread().
42 enum {
43 THREAD_CTRL_NONE,
44 THREAD_CTRL_REMOVE_PEER,
45 THREAD_CTRL_QUIT,
46 THREAD_CTRL_LAST,
47 };
48
49 // Helper structure that allows the Broker to associate a job notification
50 // with a job object and with a policy.
51 struct JobTracker {
52 HANDLE job;
53 sandbox::PolicyBase* policy;
54 JobTracker(HANDLE cjob, sandbox::PolicyBase* cpolicy)
55 : job(cjob), policy(cpolicy) {
56 }
57 };
58
59 // Helper structure that allows the broker to track peer processes
60 struct PeerTracker {
61 HANDLE wait_object;
62 base::win::ScopedHandle process;
63 DWORD id;
64 HANDLE job_port;
65 PeerTracker(DWORD process_id, HANDLE broker_job_port)
66 : wait_object(NULL), id(process_id), job_port(broker_job_port) {
67 }
68 };
69
70 void DeregisterPeerTracker(PeerTracker* peer) {
71 // Deregistration shouldn't fail, but we leak rather than crash if it does.
72 if (::UnregisterWaitEx(peer->wait_object, INVALID_HANDLE_VALUE)) {
73 delete peer;
74 } else {
75 NOTREACHED();
76 }
77 }
78
79 } // namespace
80
81 namespace sandbox {
82
83 BrokerServicesBase::BrokerServicesBase()
84 : thread_pool_(NULL), job_port_(NULL), no_targets_(NULL),
85 job_thread_(NULL) {
86 }
87
88 // The broker uses a dedicated worker thread that services the job completion
89 // port to perform policy notifications and associated cleanup tasks.
90 ResultCode BrokerServicesBase::Init() {
91 if ((NULL != job_port_) || (NULL != thread_pool_))
92 return SBOX_ERROR_UNEXPECTED_CALL;
93
94 ::InitializeCriticalSection(&lock_);
95
96 job_port_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
97 if (NULL == job_port_)
98 return SBOX_ERROR_GENERIC;
99
100 no_targets_ = ::CreateEventW(NULL, TRUE, FALSE, NULL);
101
102 job_thread_ = ::CreateThread(NULL, 0, // Default security and stack.
103 TargetEventsThread, this, NULL, NULL);
104 if (NULL == job_thread_)
105 return SBOX_ERROR_GENERIC;
106
107 return SBOX_ALL_OK;
108 }
109
110 // The destructor should only be called when the Broker process is terminating.
111 // Since BrokerServicesBase is a singleton, this is called from the CRT
112 // termination handlers, if this code lives on a DLL it is called during
113 // DLL_PROCESS_DETACH in other words, holding the loader lock, so we cannot
114 // wait for threads here.
115 BrokerServicesBase::~BrokerServicesBase() {
116 // If there is no port Init() was never called successfully.
117 if (!job_port_)
118 return;
119
120 // Closing the port causes, that no more Job notifications are delivered to
121 // the worker thread and also causes the thread to exit. This is what we
122 // want to do since we are going to close all outstanding Jobs and notifying
123 // the policy objects ourselves.
124 ::PostQueuedCompletionStatus(job_port_, 0, THREAD_CTRL_QUIT, FALSE);
125 ::CloseHandle(job_port_);
126
127 if (WAIT_TIMEOUT == ::WaitForSingleObject(job_thread_, 1000)) {
128 // Cannot clean broker services.
129 NOTREACHED();
130 return;
131 }
132
133 JobTrackerList::iterator it;
134 for (it = tracker_list_.begin(); it != tracker_list_.end(); ++it) {
135 JobTracker* tracker = (*it);
136 FreeResources(tracker);
137 delete tracker;
138 }
139 ::CloseHandle(job_thread_);
140 delete thread_pool_;
141 ::CloseHandle(no_targets_);
142
143 // Cancel the wait events and delete remaining peer trackers.
144 for (PeerTrackerMap::iterator it = peer_map_.begin();
145 it != peer_map_.end(); ++it) {
146 DeregisterPeerTracker(it->second);
147 }
148
149 // If job_port_ isn't NULL, assumes that the lock has been initialized.
150 if (job_port_)
151 ::DeleteCriticalSection(&lock_);
152 }
153
154 TargetPolicy* BrokerServicesBase::CreatePolicy() {
155 // If you change the type of the object being created here you must also
156 // change the downcast to it in SpawnTarget().
157 return new PolicyBase;
158 }
159
160 void BrokerServicesBase::FreeResources(JobTracker* tracker) {
161 if (NULL != tracker->policy) {
162 BOOL res = ::TerminateJobObject(tracker->job, SBOX_ALL_OK);
163 DCHECK(res);
164 // Closing the job causes the target process to be destroyed so this
165 // needs to happen before calling OnJobEmpty().
166 res = ::CloseHandle(tracker->job);
167 DCHECK(res);
168 // In OnJobEmpty() we don't actually use the job handle directly.
169 tracker->policy->OnJobEmpty(tracker->job);
170 tracker->policy->Release();
171 tracker->policy = NULL;
172 }
173 }
174
175 // The worker thread stays in a loop waiting for asynchronous notifications
176 // from the job objects. Right now we only care about knowing when the last
177 // process on a job terminates, but in general this is the place to tell
178 // the policy about events.
179 DWORD WINAPI BrokerServicesBase::TargetEventsThread(PVOID param) {
180 if (NULL == param)
181 return 1;
182
183 base::PlatformThread::SetName("BrokerEvent");
184
185 BrokerServicesBase* broker = reinterpret_cast<BrokerServicesBase*>(param);
186 HANDLE port = broker->job_port_;
187 HANDLE no_targets = broker->no_targets_;
188
189 int target_counter = 0;
190 ::ResetEvent(no_targets);
191
192 while (true) {
193 DWORD events = 0;
194 ULONG_PTR key = 0;
195 LPOVERLAPPED ovl = NULL;
196
197 if (!::GetQueuedCompletionStatus(port, &events, &key, &ovl, INFINITE))
198 // this call fails if the port has been closed before we have a
199 // chance to service the last packet which is 'exit' anyway so
200 // this is not an error.
201 return 1;
202
203 if (key > THREAD_CTRL_LAST) {
204 // The notification comes from a job object. There are nine notifications
205 // that jobs can send and some of them depend on the job attributes set.
206 JobTracker* tracker = reinterpret_cast<JobTracker*>(key);
207
208 switch (events) {
209 case JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: {
210 // The job object has signaled that the last process associated
211 // with it has terminated. Assuming there is no way for a process
212 // to appear out of thin air in this job, it safe to assume that
213 // we can tell the policy to destroy the target object, and for
214 // us to release our reference to the policy object.
215 FreeResources(tracker);
216 break;
217 }
218
219 case JOB_OBJECT_MSG_NEW_PROCESS: {
220 ++target_counter;
221 if (1 == target_counter) {
222 ::ResetEvent(no_targets);
223 }
224 break;
225 }
226
227 case JOB_OBJECT_MSG_EXIT_PROCESS:
228 case JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS: {
229 {
230 AutoLock lock(&broker->lock_);
231 broker->child_process_ids_.erase(reinterpret_cast<DWORD>(ovl));
232 }
233 --target_counter;
234 if (0 == target_counter)
235 ::SetEvent(no_targets);
236
237 DCHECK(target_counter >= 0);
238 break;
239 }
240
241 case JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT: {
242 break;
243 }
244
245 default: {
246 NOTREACHED();
247 break;
248 }
249 }
250 } else if (THREAD_CTRL_REMOVE_PEER == key) {
251 // Remove a process from our list of peers.
252 AutoLock lock(&broker->lock_);
253 PeerTrackerMap::iterator it =
254 broker->peer_map_.find(reinterpret_cast<DWORD>(ovl));
255 DeregisterPeerTracker(it->second);
256 broker->peer_map_.erase(it);
257 } else if (THREAD_CTRL_QUIT == key) {
258 // The broker object is being destroyed so the thread needs to exit.
259 return 0;
260 } else {
261 // We have not implemented more commands.
262 NOTREACHED();
263 }
264 }
265
266 NOTREACHED();
267 return 0;
268 }
269
270 // SpawnTarget does all the interesting sandbox setup and creates the target
271 // process inside the sandbox.
272 ResultCode BrokerServicesBase::SpawnTarget(const wchar_t* exe_path,
273 const wchar_t* command_line,
274 TargetPolicy* policy,
275 PROCESS_INFORMATION* target_info) {
276 if (!exe_path)
277 return SBOX_ERROR_BAD_PARAMS;
278
279 if (!policy)
280 return SBOX_ERROR_BAD_PARAMS;
281
282 // Even though the resources touched by SpawnTarget can be accessed in
283 // multiple threads, the method itself cannot be called from more than
284 // 1 thread. This is to protect the global variables used while setting up
285 // the child process.
286 static DWORD thread_id = ::GetCurrentThreadId();
287 DCHECK(thread_id == ::GetCurrentThreadId());
288
289 AutoLock lock(&lock_);
290
291 // This downcast is safe as long as we control CreatePolicy()
292 PolicyBase* policy_base = static_cast<PolicyBase*>(policy);
293
294 // Construct the tokens and the job object that we are going to associate
295 // with the soon to be created target process.
296 HANDLE initial_token_temp;
297 HANDLE lockdown_token_temp;
298 DWORD win_result = policy_base->MakeTokens(&initial_token_temp,
299 &lockdown_token_temp);
300 base::win::ScopedHandle initial_token(initial_token_temp);
301 base::win::ScopedHandle lockdown_token(lockdown_token_temp);
302
303 if (ERROR_SUCCESS != win_result)
304 return SBOX_ERROR_GENERIC;
305
306 HANDLE job_temp;
307 win_result = policy_base->MakeJobObject(&job_temp);
308 base::win::ScopedHandle job(job_temp);
309 if (ERROR_SUCCESS != win_result)
310 return SBOX_ERROR_GENERIC;
311
312 if (ERROR_ALREADY_EXISTS == ::GetLastError())
313 return SBOX_ERROR_GENERIC;
314
315 // Construct the thread pool here in case it is expensive.
316 // The thread pool is shared by all the targets
317 if (NULL == thread_pool_)
318 thread_pool_ = new Win2kThreadPool();
319
320 // Create the TargetProces object and spawn the target suspended. Note that
321 // Brokerservices does not own the target object. It is owned by the Policy.
322 base::win::ScopedProcessInformation process_info;
323 TargetProcess* target = new TargetProcess(initial_token.Take(),
324 lockdown_token.Take(),
325 job,
326 thread_pool_);
327
328 std::wstring desktop = policy_base->GetAlternateDesktop();
329
330 win_result = target->Create(exe_path, command_line,
331 desktop.empty() ? NULL : desktop.c_str(),
332 &process_info);
333 if (ERROR_SUCCESS != win_result)
334 return SpawnCleanup(target, win_result);
335
336 // Now the policy is the owner of the target.
337 if (!policy_base->AddTarget(target)) {
338 return SpawnCleanup(target, 0);
339 }
340
341 // We are going to keep a pointer to the policy because we'll call it when
342 // the job object generates notifications using the completion port.
343 policy_base->AddRef();
344 scoped_ptr<JobTracker> tracker(new JobTracker(job.Take(), policy_base));
345 if (!AssociateCompletionPort(tracker->job, job_port_, tracker.get()))
346 return SpawnCleanup(target, 0);
347 // Save the tracker because in cleanup we might need to force closing
348 // the Jobs.
349 tracker_list_.push_back(tracker.release());
350 child_process_ids_.insert(process_info.process_id());
351
352 *target_info = process_info.Take();
353 return SBOX_ALL_OK;
354 }
355
356
357 ResultCode BrokerServicesBase::WaitForAllTargets() {
358 ::WaitForSingleObject(no_targets_, INFINITE);
359 return SBOX_ALL_OK;
360 }
361
362 bool BrokerServicesBase::IsActiveTarget(DWORD process_id) {
363 AutoLock lock(&lock_);
364 return child_process_ids_.find(process_id) != child_process_ids_.end() ||
365 peer_map_.find(process_id) != peer_map_.end();
366 }
367
368 VOID CALLBACK BrokerServicesBase::RemovePeer(PVOID parameter, BOOLEAN timeout) {
369 PeerTracker* peer = reinterpret_cast<PeerTracker*>(parameter);
370 // Don't check the return code because we this may fail (safely) at shutdown.
371 ::PostQueuedCompletionStatus(peer->job_port, 0, THREAD_CTRL_REMOVE_PEER,
372 reinterpret_cast<LPOVERLAPPED>(peer->id));
373 }
374
375 ResultCode BrokerServicesBase::AddTargetPeer(HANDLE peer_process) {
376 scoped_ptr<PeerTracker> peer(new PeerTracker(::GetProcessId(peer_process),
377 job_port_));
378 if (!peer->id)
379 return SBOX_ERROR_GENERIC;
380
381 HANDLE process_handle;
382 if (!::DuplicateHandle(::GetCurrentProcess(), peer_process,
383 ::GetCurrentProcess(), &process_handle,
384 SYNCHRONIZE, FALSE, 0)) {
385 return SBOX_ERROR_GENERIC;
386 }
387 peer->process.Set(process_handle);
388
389 AutoLock lock(&lock_);
390 if (!peer_map_.insert(std::make_pair(peer->id, peer.get())).second)
391 return SBOX_ERROR_BAD_PARAMS;
392
393 if (!::RegisterWaitForSingleObject(
394 &peer->wait_object, peer->process, RemovePeer, peer.get(), INFINITE,
395 WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD)) {
396 peer_map_.erase(peer->id);
397 return SBOX_ERROR_GENERIC;
398 }
399
400 // Release the pointer since it will be cleaned up by the callback.
401 peer.release();
402 return SBOX_ALL_OK;
403 }
404
405 } // namespace sandbox
OLDNEW
« no previous file with comments | « sandbox/src/broker_services.h ('k') | sandbox/src/crosscall_client.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698