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

Side by Side Diff: content/common/sandbox_policy.cc

Issue 12805004: Remove mention of the nacl process in content. (Closed) Base URL: svn://chrome-svn/chrome/trunk/src/
Patch Set: Created 7 years, 9 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 | « content/common/sandbox_policy.h ('k') | content/common/sandbox_util.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 "content/common/sandbox_policy.h"
6
7 #include <string>
8
9 #include "base/command_line.h"
10 #include "base/debug/debugger.h"
11 #include "base/debug/trace_event.h"
12 #include "base/file_util.h"
13 #include "base/lazy_instance.h"
14 #include "base/logging.h"
15 #include "base/path_service.h"
16 #include "base/process_util.h"
17 #include "base/string_util.h"
18 #include "base/stringprintf.h"
19 #include "base/win/iat_patch_function.h"
20 #include "base/win/scoped_handle.h"
21 #include "base/win/scoped_process_information.h"
22 #include "base/win/windows_version.h"
23 #include "content/common/debug_flags.h"
24 #include "content/public/common/content_client.h"
25 #include "content/public/common/content_switches.h"
26 #include "content/public/common/process_type.h"
27 #include "content/public/common/sandbox_init.h"
28 #include "sandbox/win/src/process_mitigations.h"
29 #include "sandbox/win/src/sandbox.h"
30 #include "sandbox/win/src/sandbox_nt_util.h"
31 #include "sandbox/win/src/win_utils.h"
32 #include "ui/gl/gl_switches.h"
33
34 static sandbox::BrokerServices* g_broker_services = NULL;
35 static sandbox::TargetServices* g_target_services = NULL;
36
37 namespace {
38
39 // The DLLs listed here are known (or under strong suspicion) of causing crashes
40 // when they are loaded in the renderer. Note: at runtime we generate short
41 // versions of the dll name only if the dll has an extension.
42 const wchar_t* const kTroublesomeDlls[] = {
43 L"adialhk.dll", // Kaspersky Internet Security.
44 L"acpiz.dll", // Unknown.
45 L"avgrsstx.dll", // AVG 8.
46 L"babylonchromepi.dll", // Babylon translator.
47 L"btkeyind.dll", // Widcomm Bluetooth.
48 L"cmcsyshk.dll", // CMC Internet Security.
49 L"cmsetac.dll", // Unknown (suspected malware).
50 L"cooliris.dll", // CoolIris.
51 L"dockshellhook.dll", // Stardock Objectdock.
52 L"easyhook32.dll", // GDIPP and others.
53 L"googledesktopnetwork3.dll", // Google Desktop Search v5.
54 L"fwhook.dll", // PC Tools Firewall Plus.
55 L"hookprocesscreation.dll", // Blumentals Program protector.
56 L"hookterminateapis.dll", // Blumentals and Cyberprinter.
57 L"hookprintapis.dll", // Cyberprinter.
58 L"imon.dll", // NOD32 Antivirus.
59 L"ioloHL.dll", // Iolo (System Mechanic).
60 L"kloehk.dll", // Kaspersky Internet Security.
61 L"lawenforcer.dll", // Spyware-Browser AntiSpyware (Spybro).
62 L"libdivx.dll", // DivX.
63 L"lvprcinj01.dll", // Logitech QuickCam.
64 L"madchook.dll", // Madshi (generic hooking library).
65 L"mdnsnsp.dll", // Bonjour.
66 L"moonsysh.dll", // Moon Secure Antivirus.
67 L"mpk.dll", // KGB Spy.
68 L"npdivx32.dll", // DivX.
69 L"npggNT.des", // GameGuard 2008.
70 L"npggNT.dll", // GameGuard (older).
71 L"oawatch.dll", // Online Armor.
72 L"owexplorer-10513.dll", // Overwolf.
73 L"owexplorer-10514.dll", // Overwolf.
74 L"owexplorer-10515.dll", // Overwolf.
75 L"owexplorer-10516.dll", // Overwolf.
76 L"owexplorer-10517.dll", // Overwolf.
77 L"owexplorer-10518.dll", // Overwolf.
78 L"owexplorer-10519.dll", // Overwolf.
79 L"owexplorer-10520.dll", // Overwolf.
80 L"owexplorer-10521.dll", // Overwolf.
81 L"owexplorer-10522.dll", // Overwolf.
82 L"owexplorer-10523.dll", // Overwolf.
83 L"pavhook.dll", // Panda Internet Security.
84 L"pavlsphook.dll", // Panda Antivirus.
85 L"pavshook.dll", // Panda Antivirus.
86 L"pavshookwow.dll", // Panda Antivirus.
87 L"pctavhook.dll", // PC Tools Antivirus.
88 L"pctgmhk.dll", // PC Tools Spyware Doctor.
89 L"prntrack.dll", // Pharos Systems.
90 L"protector.dll", // Unknown (suspected malware).
91 L"radhslib.dll", // Radiant Naomi Internet Filter.
92 L"radprlib.dll", // Radiant Naomi Internet Filter.
93 L"rapportnikko.dll", // Trustware Rapport.
94 L"rlhook.dll", // Trustware Bufferzone.
95 L"rooksdol.dll", // Trustware Rapport.
96 L"rpchromebrowserrecordhelper.dll", // RealPlayer.
97 L"r3hook.dll", // Kaspersky Internet Security.
98 L"sahook.dll", // McAfee Site Advisor.
99 L"sbrige.dll", // Unknown.
100 L"sc2hook.dll", // Supercopier 2.
101 L"sdhook32.dll", // Spybot - Search & Destroy Live Protection.
102 L"sguard.dll", // Iolo (System Guard).
103 L"smum32.dll", // Spyware Doctor version 6.
104 L"smumhook.dll", // Spyware Doctor version 5.
105 L"ssldivx.dll", // DivX.
106 L"syncor11.dll", // SynthCore Midi interface.
107 L"systools.dll", // Panda Antivirus.
108 L"tfwah.dll", // Threatfire (PC tools).
109 L"wblind.dll", // Stardock Object desktop.
110 L"wbhelp.dll", // Stardock Object desktop.
111 L"winstylerthemehelper.dll" // Tuneup utilities 2006.
112 };
113
114 // The DLLs listed here are known (or under strong suspicion) of causing crashes
115 // when they are loaded in the GPU process.
116 const wchar_t* const kTroublesomeGpuDlls[] = {
117 L"cmsetac.dll", // Unknown (suspected malware).
118 };
119
120 // Adds the policy rules for the path and path\ with the semantic |access|.
121 // If |children| is set to true, we need to add the wildcard rules to also
122 // apply the rule to the subfiles and subfolders.
123 bool AddDirectory(int path, const wchar_t* sub_dir, bool children,
124 sandbox::TargetPolicy::Semantics access,
125 sandbox::TargetPolicy* policy) {
126 base::FilePath directory;
127 if (!PathService::Get(path, &directory))
128 return false;
129
130 if (sub_dir) {
131 directory = directory.Append(sub_dir);
132 file_util::AbsolutePath(&directory);
133 }
134
135 sandbox::ResultCode result;
136 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
137 directory.value().c_str());
138 if (result != sandbox::SBOX_ALL_OK)
139 return false;
140
141 std::wstring directory_str = directory.value() + L"\\";
142 if (children)
143 directory_str += L"*";
144 // Otherwise, add the version of the path that ends with a separator.
145
146 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
147 directory_str.c_str());
148 if (result != sandbox::SBOX_ALL_OK)
149 return false;
150
151 return true;
152 }
153
154 // Adds the policy rules for the path and path\* with the semantic |access|.
155 // We need to add the wildcard rules to also apply the rule to the subkeys.
156 bool AddKeyAndSubkeys(std::wstring key,
157 sandbox::TargetPolicy::Semantics access,
158 sandbox::TargetPolicy* policy) {
159 sandbox::ResultCode result;
160 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
161 key.c_str());
162 if (result != sandbox::SBOX_ALL_OK)
163 return false;
164
165 key += L"\\*";
166 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
167 key.c_str());
168 if (result != sandbox::SBOX_ALL_OK)
169 return false;
170
171 return true;
172 }
173
174 // Compares the loaded |module| file name matches |module_name|.
175 bool IsExpandedModuleName(HMODULE module, const wchar_t* module_name) {
176 wchar_t path[MAX_PATH];
177 DWORD sz = ::GetModuleFileNameW(module, path, arraysize(path));
178 if ((sz == arraysize(path)) || (sz == 0)) {
179 // XP does not set the last error properly, so we bail out anyway.
180 return false;
181 }
182 if (!::GetLongPathName(path, path, arraysize(path)))
183 return false;
184 base::FilePath fname(path);
185 return (fname.BaseName().value() == module_name);
186 }
187
188 // Adds a single dll by |module_name| into the |policy| blacklist.
189 // If |check_in_browser| is true we only add an unload policy only if the dll
190 // is also loaded in this process.
191 void BlacklistAddOneDll(const wchar_t* module_name,
192 bool check_in_browser,
193 sandbox::TargetPolicy* policy) {
194 HMODULE module = check_in_browser ? ::GetModuleHandleW(module_name) : NULL;
195 if (!module) {
196 // The module could have been loaded with a 8.3 short name. We check
197 // the three most common cases: 'thelongname.dll' becomes
198 // 'thelon~1.dll', 'thelon~2.dll' and 'thelon~3.dll'.
199 std::wstring name(module_name);
200 size_t period = name.rfind(L'.');
201 DCHECK_NE(std::string::npos, period);
202 DCHECK_LE(3U, (name.size() - period));
203 if (period <= 8)
204 return;
205 for (int ix = 0; ix < 3; ++ix) {
206 const wchar_t suffix[] = {'~', ('1' + ix), 0};
207 std::wstring alt_name = name.substr(0, 6) + suffix;
208 alt_name += name.substr(period, name.size());
209 if (check_in_browser) {
210 module = ::GetModuleHandleW(alt_name.c_str());
211 if (!module)
212 return;
213 // We found it, but because it only has 6 significant letters, we
214 // want to make sure it is the right one.
215 if (!IsExpandedModuleName(module, module_name))
216 return;
217 }
218 // Found a match. We add both forms to the policy.
219 policy->AddDllToUnload(alt_name.c_str());
220 }
221 }
222 policy->AddDllToUnload(module_name);
223 DVLOG(1) << "dll to unload found: " << module_name;
224 return;
225 }
226
227 // Adds policy rules for unloaded the known dlls that cause chrome to crash.
228 // Eviction of injected DLLs is done by the sandbox so that the injected module
229 // does not get a chance to execute any code.
230 void AddGenericDllEvictionPolicy(sandbox::TargetPolicy* policy) {
231 for (int ix = 0; ix != arraysize(kTroublesomeDlls); ++ix)
232 BlacklistAddOneDll(kTroublesomeDlls[ix], true, policy);
233 }
234
235 // Same as AddGenericDllEvictionPolicy but specifically for the GPU process.
236 // In this we add the blacklisted dlls even if they are not loaded in this
237 // process.
238 void AddGpuDllEvictionPolicy(sandbox::TargetPolicy* policy) {
239 for (int ix = 0; ix != arraysize(kTroublesomeGpuDlls); ++ix)
240 BlacklistAddOneDll(kTroublesomeGpuDlls[ix], false, policy);
241 }
242
243 // Returns the object path prepended with the current logon session.
244 string16 PrependWindowsSessionPath(const char16* object) {
245 // Cache this because it can't change after process creation.
246 static uintptr_t s_session_id = 0;
247 if (s_session_id == 0) {
248 HANDLE token;
249 DWORD session_id_length;
250 DWORD session_id = 0;
251
252 CHECK(::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token));
253 CHECK(::GetTokenInformation(token, TokenSessionId, &session_id,
254 sizeof(session_id), &session_id_length));
255 CloseHandle(token);
256 if (session_id)
257 s_session_id = session_id;
258 }
259
260 return base::StringPrintf(L"\\Sessions\\%d%ls", s_session_id, object);
261 }
262
263 // Checks if the sandbox should be let to run without a job object assigned.
264 bool ShouldSetJobLevel(const CommandLine& cmd_line) {
265 if (!cmd_line.HasSwitch(switches::kAllowNoSandboxJob))
266 return true;
267
268 // Windows 8 allows nested jobs so we don't need to check if we are in other
269 // job.
270 if (base::win::GetVersion() >= base::win::VERSION_WIN8)
271 return true;
272
273 BOOL in_job = true;
274 // Either there is no job yet associated so we must add our job,
275 if (!::IsProcessInJob(::GetCurrentProcess(), NULL, &in_job))
276 NOTREACHED() << "IsProcessInJob failed. " << GetLastError();
277 if (!in_job)
278 return true;
279
280 // ...or there is a job but the JOB_OBJECT_LIMIT_BREAKAWAY_OK limit is set.
281 JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info = {0};
282 if (!::QueryInformationJobObject(NULL,
283 JobObjectExtendedLimitInformation, &job_info,
284 sizeof(job_info), NULL)) {
285 NOTREACHED() << "QueryInformationJobObject failed. " << GetLastError();
286 return true;
287 }
288 if (job_info.BasicLimitInformation.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK)
289 return true;
290
291 return false;
292 }
293
294 void SetJobLevel(const CommandLine& cmd_line,
295 sandbox::JobLevel job_level,
296 uint32 ui_exceptions,
297 sandbox::TargetPolicy* policy) {
298 if (ShouldSetJobLevel(cmd_line))
299 policy->SetJobLevel(job_level, ui_exceptions);
300 else
301 policy->SetJobLevel(sandbox::JOB_NONE, 0);
302 }
303
304 // Closes handles that are opened at process creation and initialization.
305 void AddBaseHandleClosePolicy(sandbox::TargetPolicy* policy) {
306 // Being able to manipulate anything BaseNamedObjects is bad.
307 string16 object_path = PrependWindowsSessionPath(L"\\BaseNamedObjects");
308 policy->AddKernelObjectToClose(L"Directory", object_path.data());
309 object_path = PrependWindowsSessionPath(
310 L"\\BaseNamedObjects\\windows_shell_global_counters");
311 policy->AddKernelObjectToClose(L"Section", object_path.data());
312 }
313
314 // Adds the generic policy rules to a sandbox TargetPolicy.
315 bool AddGenericPolicy(sandbox::TargetPolicy* policy) {
316 sandbox::ResultCode result;
317
318 // Add the policy for the client side of a pipe. It is just a file
319 // in the \pipe\ namespace. We restrict it to pipes that start with
320 // "chrome." so the sandboxed process cannot connect to system services.
321 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
322 sandbox::TargetPolicy::FILES_ALLOW_ANY,
323 L"\\??\\pipe\\chrome.*");
324 if (result != sandbox::SBOX_ALL_OK)
325 return false;
326 // Allow the server side of a pipe restricted to the "chrome.nacl."
327 // namespace so that it cannot impersonate other system or other chrome
328 // service pipes.
329 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
330 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
331 L"\\\\.\\pipe\\chrome.nacl.*");
332 if (result != sandbox::SBOX_ALL_OK)
333 return false;
334 // Allow the server side of sync sockets, which are pipes that have
335 // the "chrome.sync" namespace and a randomly generated suffix.
336 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
337 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
338 L"\\\\.\\pipe\\chrome.sync.*");
339 if (result != sandbox::SBOX_ALL_OK)
340 return false;
341
342 // Add the policy for debug message only in debug
343 #ifndef NDEBUG
344 base::FilePath app_dir;
345 if (!PathService::Get(base::DIR_MODULE, &app_dir))
346 return false;
347
348 wchar_t long_path_buf[MAX_PATH];
349 DWORD long_path_return_value = GetLongPathName(app_dir.value().c_str(),
350 long_path_buf,
351 MAX_PATH);
352 if (long_path_return_value == 0 || long_path_return_value >= MAX_PATH)
353 return false;
354
355 base::FilePath debug_message(long_path_buf);
356 debug_message = debug_message.AppendASCII("debug_message.exe");
357 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_PROCESS,
358 sandbox::TargetPolicy::PROCESS_MIN_EXEC,
359 debug_message.value().c_str());
360 if (result != sandbox::SBOX_ALL_OK)
361 return false;
362 #endif // NDEBUG
363 return true;
364 }
365
366 // For the GPU process we gotten as far as USER_LIMITED. The next level
367 // which is USER_RESTRICTED breaks both the DirectX backend and the OpenGL
368 // backend. Note that the GPU process is connected to the interactive
369 // desktop.
370 // TODO(cpu): Lock down the sandbox more if possible.
371 bool AddPolicyForGPU(CommandLine* cmd_line, sandbox::TargetPolicy* policy) {
372 #if !defined(NACL_WIN64) // We don't need this code on win nacl64.
373 if (base::win::GetVersion() > base::win::VERSION_XP) {
374 if (cmd_line->GetSwitchValueASCII(switches::kUseGL) ==
375 gfx::kGLImplementationDesktopName) {
376 // Open GL path.
377 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
378 sandbox::USER_LIMITED);
379 SetJobLevel(*cmd_line, sandbox::JOB_UNPROTECTED, 0, policy);
380 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
381 } else {
382 if (cmd_line->GetSwitchValueASCII(switches::kUseGL) ==
383 gfx::kGLImplementationSwiftShaderName ||
384 cmd_line->HasSwitch(switches::kReduceGpuSandbox) ||
385 cmd_line->HasSwitch(switches::kDisableImageTransportSurface)) {
386 // Swiftshader path.
387 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
388 sandbox::USER_LIMITED);
389 } else {
390 // Angle + DirectX path.
391 policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
392 sandbox::USER_RESTRICTED);
393 // This is a trick to keep the GPU out of low-integrity processes. It
394 // starts at low-integrity for UIPI to work, then drops below
395 // low-integrity after warm-up.
396 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
397 }
398
399 // UI restrictions break when we access Windows from outside our job.
400 // However, we don't want a proxy window in this process because it can
401 // introduce deadlocks where the renderer blocks on the gpu, which in
402 // turn blocks on the browser UI thread. So, instead we forgo a window
403 // message pump entirely and just add job restrictions to prevent child
404 // processes.
405 SetJobLevel(*cmd_line,
406 sandbox::JOB_LIMITED_USER,
407 JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS |
408 JOB_OBJECT_UILIMIT_DESKTOP |
409 JOB_OBJECT_UILIMIT_EXITWINDOWS |
410 JOB_OBJECT_UILIMIT_DISPLAYSETTINGS,
411 policy);
412
413 policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
414 }
415 } else {
416 SetJobLevel(*cmd_line, sandbox::JOB_UNPROTECTED, 0, policy);
417 policy->SetTokenLevel(sandbox::USER_UNPROTECTED,
418 sandbox::USER_LIMITED);
419 }
420
421 // Allow the server side of GPU sockets, which are pipes that have
422 // the "chrome.gpu" namespace and an arbitrary suffix.
423 sandbox::ResultCode result = policy->AddRule(
424 sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
425 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
426 L"\\\\.\\pipe\\chrome.gpu.*");
427 if (result != sandbox::SBOX_ALL_OK)
428 return false;
429
430 // GPU needs to copy sections to renderers.
431 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
432 sandbox::TargetPolicy::HANDLES_DUP_ANY,
433 L"Section");
434 if (result != sandbox::SBOX_ALL_OK)
435 return false;
436
437 #ifdef USE_AURA
438 // GPU also needs to add sections to the browser for aura
439 // TODO(jschuh): refactor the GPU channel to remove this. crbug.com/128786
440 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
441 sandbox::TargetPolicy::HANDLES_DUP_BROKER,
442 L"Section");
443 if (result != sandbox::SBOX_ALL_OK)
444 return false;
445 #endif
446
447 AddGenericDllEvictionPolicy(policy);
448 AddGpuDllEvictionPolicy(policy);
449
450 if (cmd_line->HasSwitch(switches::kEnableLogging)) {
451 string16 log_file_path = logging::GetLogFileFullPath();
452 if (!log_file_path.empty()) {
453 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
454 sandbox::TargetPolicy::FILES_ALLOW_ANY,
455 log_file_path.c_str());
456 if (result != sandbox::SBOX_ALL_OK)
457 return false;
458 }
459 }
460 #endif
461 return true;
462 }
463
464 bool AddPolicyForRenderer(sandbox::TargetPolicy* policy) {
465 // Renderers need to copy sections for plugin DIBs and GPU.
466 sandbox::ResultCode result;
467 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
468 sandbox::TargetPolicy::HANDLES_DUP_ANY,
469 L"Section");
470 if (result != sandbox::SBOX_ALL_OK)
471 return false;
472
473 // Renderers need to share events with plugins.
474 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
475 sandbox::TargetPolicy::HANDLES_DUP_ANY,
476 L"Event");
477 if (result != sandbox::SBOX_ALL_OK)
478 return false;
479
480 // Renderers need to send named pipe handles and shared memory
481 // segment handles to NaCl loader processes.
482 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
483 sandbox::TargetPolicy::HANDLES_DUP_ANY,
484 L"File");
485 if (result != sandbox::SBOX_ALL_OK)
486 return false;
487
488 sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED;
489 if (base::win::GetVersion() > base::win::VERSION_XP) {
490 // On 2003/Vista the initial token has to be restricted if the main
491 // token is restricted.
492 initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS;
493 }
494
495 policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN);
496 // Prevents the renderers from manipulating low-integrity processes.
497 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
498
499 bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch(
500 switches::kDisableAltWinstation);
501
502 if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) {
503 DLOG(WARNING) << "Failed to apply desktop security to the renderer";
504 }
505
506 AddGenericDllEvictionPolicy(policy);
507
508 return true;
509 }
510
511 // The Pepper process as locked-down as a renderer execpt that it can
512 // create the server side of chrome pipes.
513 bool AddPolicyForPepperPlugin(sandbox::TargetPolicy* policy) {
514 sandbox::ResultCode result;
515 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
516 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
517 L"\\\\.\\pipe\\chrome.*");
518 return result == sandbox::SBOX_ALL_OK;
519 }
520
521 // This code is test only, and attempts to catch unsafe uses of
522 // DuplicateHandle() that copy privileged handles into sandboxed processes.
523 #ifndef OFFICIAL_BUILD
524 base::win::IATPatchFunction g_iat_patch_duplicate_handle;
525
526 BOOL (WINAPI *g_iat_orig_duplicate_handle)(HANDLE source_process_handle,
527 HANDLE source_handle,
528 HANDLE target_process_handle,
529 LPHANDLE target_handle,
530 DWORD desired_access,
531 BOOL inherit_handle,
532 DWORD options);
533
534 NtQueryObject g_QueryObject = NULL;
535
536 static const char* kDuplicateHandleWarning =
537 "You are attempting to duplicate a privileged handle into a sandboxed"
538 " process.\n Please use the sandbox::BrokerDuplicateHandle API or"
539 " contact security@chromium.org for assistance.";
540
541 void CheckDuplicateHandle(HANDLE handle) {
542 // Get the object type (32 characters is safe; current max is 14).
543 BYTE buffer[sizeof(OBJECT_TYPE_INFORMATION) + 32 * sizeof(wchar_t)];
544 OBJECT_TYPE_INFORMATION* type_info =
545 reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer);
546 ULONG size = sizeof(buffer) - sizeof(wchar_t);
547 NTSTATUS error;
548 error = g_QueryObject(handle, ObjectTypeInformation, type_info, size, &size);
549 CHECK(NT_SUCCESS(error));
550 type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
551
552 // Get the object basic information.
553 OBJECT_BASIC_INFORMATION basic_info;
554 size = sizeof(basic_info);
555 error = g_QueryObject(handle, ObjectBasicInformation, &basic_info, size,
556 &size);
557 CHECK(NT_SUCCESS(error));
558
559 if (0 == _wcsicmp(type_info->Name.Buffer, L"Process")) {
560 const ACCESS_MASK kDangerousMask = ~(PROCESS_QUERY_LIMITED_INFORMATION |
561 SYNCHRONIZE);
562 CHECK(!(basic_info.GrantedAccess & kDangerousMask)) <<
563 kDuplicateHandleWarning;
564 }
565 }
566
567 BOOL WINAPI DuplicateHandlePatch(HANDLE source_process_handle,
568 HANDLE source_handle,
569 HANDLE target_process_handle,
570 LPHANDLE target_handle,
571 DWORD desired_access,
572 BOOL inherit_handle,
573 DWORD options) {
574 // Duplicate the handle so we get the final access mask.
575 if (!g_iat_orig_duplicate_handle(source_process_handle, source_handle,
576 target_process_handle, target_handle,
577 desired_access, inherit_handle, options))
578 return FALSE;
579
580 // We're not worried about broker handles or not crossing process boundaries.
581 if (source_process_handle == target_process_handle ||
582 target_process_handle == ::GetCurrentProcess())
583 return TRUE;
584
585 // Only sandboxed children are placed in jobs, so just check them.
586 BOOL is_in_job = FALSE;
587 if (!::IsProcessInJob(target_process_handle, NULL, &is_in_job)) {
588 // We need a handle with permission to check the job object.
589 if (ERROR_ACCESS_DENIED == ::GetLastError()) {
590 base::win::ScopedHandle process;
591 CHECK(g_iat_orig_duplicate_handle(::GetCurrentProcess(),
592 target_process_handle,
593 ::GetCurrentProcess(),
594 process.Receive(),
595 PROCESS_QUERY_INFORMATION,
596 FALSE, 0));
597 CHECK(::IsProcessInJob(process, NULL, &is_in_job));
598 }
599 }
600
601 if (is_in_job) {
602 // We never allow inheritable child handles.
603 CHECK(!inherit_handle) << kDuplicateHandleWarning;
604
605 // Duplicate the handle again, to get the final permissions.
606 base::win::ScopedHandle handle;
607 CHECK(g_iat_orig_duplicate_handle(target_process_handle, *target_handle,
608 ::GetCurrentProcess(), handle.Receive(),
609 0, FALSE, DUPLICATE_SAME_ACCESS));
610
611 // Callers use CHECK macro to make sure we get the right stack.
612 CheckDuplicateHandle(handle);
613 }
614
615 return TRUE;
616 }
617 #endif
618
619 } // namespace
620
621 namespace content {
622
623 bool InitBrokerServices(sandbox::BrokerServices* broker_services) {
624 // TODO(abarth): DCHECK(CalledOnValidThread());
625 // See <http://b/1287166>.
626 DCHECK(broker_services);
627 DCHECK(!g_broker_services);
628 sandbox::ResultCode result = broker_services->Init();
629 g_broker_services = broker_services;
630
631 // In non-official builds warn about dangerous uses of DuplicateHandle.
632 BOOL is_in_job = FALSE;
633 #ifdef NACL_WIN64
634 CHECK(::IsProcessInJob(::GetCurrentProcess(), NULL, &is_in_job));
635 #endif
636 #ifndef OFFICIAL_BUILD
637 if (!is_in_job && !g_iat_patch_duplicate_handle.is_patched()) {
638 HMODULE module = NULL;
639 wchar_t module_name[MAX_PATH];
640 CHECK(::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
641 reinterpret_cast<LPCWSTR>(InitBrokerServices),
642 &module));
643 DWORD result = ::GetModuleFileNameW(module, module_name, MAX_PATH);
644 if (result && (result != MAX_PATH)) {
645 ResolveNTFunctionPtr("NtQueryObject", &g_QueryObject);
646 g_iat_orig_duplicate_handle = ::DuplicateHandle;
647 g_iat_patch_duplicate_handle.Patch(
648 module_name, "kernel32.dll", "DuplicateHandle",
649 DuplicateHandlePatch);
650 }
651 }
652 #endif
653
654 return sandbox::SBOX_ALL_OK == result;
655 }
656
657 bool InitTargetServices(sandbox::TargetServices* target_services) {
658 DCHECK(target_services);
659 DCHECK(!g_target_services);
660 sandbox::ResultCode result = target_services->Init();
661 g_target_services = target_services;
662 return sandbox::SBOX_ALL_OK == result;
663 }
664
665 base::ProcessHandle StartProcessWithAccess(CommandLine* cmd_line,
666 const base::FilePath& exposed_dir) {
667 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
668 ProcessType type;
669 std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
670 if (type_str == switches::kRendererProcess) {
671 type = PROCESS_TYPE_RENDERER;
672 } else if (type_str == switches::kPluginProcess) {
673 type = PROCESS_TYPE_PLUGIN;
674 } else if (type_str == switches::kWorkerProcess) {
675 type = PROCESS_TYPE_WORKER;
676 } else if (type_str == switches::kNaClLoaderProcess) {
677 type = PROCESS_TYPE_NACL_LOADER;
678 } else if (type_str == switches::kUtilityProcess) {
679 type = PROCESS_TYPE_UTILITY;
680 } else if (type_str == switches::kNaClBrokerProcess) {
681 type = PROCESS_TYPE_NACL_BROKER;
682 } else if (type_str == switches::kGpuProcess) {
683 type = PROCESS_TYPE_GPU;
684 } else if (type_str == switches::kPpapiPluginProcess) {
685 type = PROCESS_TYPE_PPAPI_PLUGIN;
686 } else if (type_str == switches::kPpapiBrokerProcess) {
687 type = PROCESS_TYPE_PPAPI_BROKER;
688 } else {
689 NOTREACHED();
690 return 0;
691 }
692
693 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
694
695 // To decide if the process is going to be sandboxed we have two cases.
696 // First case: all process types except the nacl broker, and the plugin
697 // process are sandboxed by default.
698 bool in_sandbox =
699 (type != PROCESS_TYPE_NACL_BROKER) &&
700 (type != PROCESS_TYPE_PLUGIN) &&
701 (type != PROCESS_TYPE_PPAPI_BROKER);
702
703 // If it is the GPU process then it can be disabled by a command line flag.
704 if ((type == PROCESS_TYPE_GPU) &&
705 (cmd_line->HasSwitch(switches::kDisableGpuSandbox))) {
706 in_sandbox = false;
707 DVLOG(1) << "GPU sandbox is disabled";
708 }
709
710 if (browser_command_line.HasSwitch(switches::kNoSandbox) ||
711 cmd_line->HasSwitch(switches::kNoSandbox)) {
712 // The user or the caller has explicity opted-out from all sandboxing.
713 in_sandbox = false;
714 }
715
716 #if !defined (GOOGLE_CHROME_BUILD)
717 if (browser_command_line.HasSwitch(switches::kInProcessPlugins)) {
718 // In process plugins won't work if the sandbox is enabled.
719 in_sandbox = false;
720 }
721 #endif
722 if (!browser_command_line.HasSwitch(switches::kDisable3DAPIs) &&
723 !browser_command_line.HasSwitch(switches::kDisableExperimentalWebGL) &&
724 browser_command_line.HasSwitch(switches::kInProcessWebGL)) {
725 // In process WebGL won't work if the sandbox is enabled.
726 in_sandbox = false;
727 }
728
729 // Propagate the Chrome Frame flag to sandboxed processes if present.
730 if (browser_command_line.HasSwitch(switches::kChromeFrame)) {
731 if (!cmd_line->HasSwitch(switches::kChromeFrame)) {
732 cmd_line->AppendSwitch(switches::kChromeFrame);
733 }
734 }
735
736 // Propagate the --allow-no-job flag if present.
737 if (browser_command_line.HasSwitch(switches::kAllowNoSandboxJob) &&
738 !cmd_line->HasSwitch(switches::kAllowNoSandboxJob)) {
739 cmd_line->AppendSwitch(switches::kAllowNoSandboxJob);
740 }
741
742 bool child_needs_help = ProcessDebugFlags(cmd_line, type, in_sandbox);
743
744 // Prefetch hints on windows:
745 // Using a different prefetch profile per process type will allow Windows
746 // to create separate pretetch settings for browser, renderer etc.
747 cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", type));
748
749 if (!in_sandbox) {
750 base::ProcessHandle process = 0;
751 base::LaunchProcess(*cmd_line, base::LaunchOptions(), &process);
752 g_broker_services->AddTargetPeer(process);
753 return process;
754 }
755
756 base::win::ScopedProcessInformation target;
757 sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
758
759 sandbox::MitigationFlags mitigations = sandbox::MITIGATION_HEAP_TERMINATE |
760 sandbox::MITIGATION_BOTTOM_UP_ASLR |
761 sandbox::MITIGATION_DEP |
762 sandbox::MITIGATION_DEP_NO_ATL_THUNK |
763 sandbox::MITIGATION_SEHOP;
764
765 if (policy->SetProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
766 return 0;
767
768 mitigations = sandbox::MITIGATION_STRICT_HANDLE_CHECKS |
769 sandbox::MITIGATION_DLL_SEARCH_ORDER;
770
771 if (policy->SetDelayedProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
772 return 0;
773
774 SetJobLevel(*cmd_line, sandbox::JOB_LOCKDOWN, 0, policy);
775
776 if (type == PROCESS_TYPE_GPU) {
777 if (!AddPolicyForGPU(cmd_line, policy))
778 return 0;
779 } else {
780 if (!AddPolicyForRenderer(policy))
781 return 0;
782 // TODO(jschuh): Need get these restrictions applied to NaCl and Pepper.
783 // Just have to figure out what needs to be warmed up first.
784 if (type == PROCESS_TYPE_RENDERER ||
785 type == PROCESS_TYPE_WORKER) {
786 AddBaseHandleClosePolicy(policy);
787 // Pepper uses the renderer's policy, whith some tweaks.
788 } else if (type == PROCESS_TYPE_PPAPI_PLUGIN) {
789 if (!AddPolicyForPepperPlugin(policy))
790 return 0;
791 }
792
793
794 if (type_str != switches::kRendererProcess) {
795 // Hack for Google Desktop crash. Trick GD into not injecting its DLL into
796 // this subprocess. See
797 // http://code.google.com/p/chromium/issues/detail?id=25580
798 cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
799 }
800 }
801
802 sandbox::ResultCode result;
803 if (!exposed_dir.empty()) {
804 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
805 sandbox::TargetPolicy::FILES_ALLOW_ANY,
806 exposed_dir.value().c_str());
807 if (result != sandbox::SBOX_ALL_OK)
808 return 0;
809
810 base::FilePath exposed_files = exposed_dir.AppendASCII("*");
811 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
812 sandbox::TargetPolicy::FILES_ALLOW_ANY,
813 exposed_files.value().c_str());
814 if (result != sandbox::SBOX_ALL_OK)
815 return 0;
816 }
817
818 if (!AddGenericPolicy(policy)) {
819 NOTREACHED();
820 return 0;
821 }
822
823 if (browser_command_line.HasSwitch(switches::kEnableLogging)) {
824 // If stdout/stderr point to a Windows console, these calls will
825 // have no effect.
826 policy->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE));
827 policy->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE));
828 }
829
830 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
831
832 result = g_broker_services->SpawnTarget(
833 cmd_line->GetProgram().value().c_str(),
834 cmd_line->GetCommandLineString().c_str(),
835 policy, target.Receive());
836 policy->Release();
837
838 TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
839
840 if (sandbox::SBOX_ALL_OK != result) {
841 DLOG(ERROR) << "Failed to launch process. Error: " << result;
842 return 0;
843 }
844
845 #if !defined(NACL_WIN64)
846 // For Native Client sel_ldr processes on 32-bit Windows, reserve 1 GB of
847 // address space to prevent later failure due to address space fragmentation
848 // from .dll loading. The NaCl process will attempt to locate this space by
849 // scanning the address space using VirtualQuery.
850 // TODO(bbudge) Handle the --no-sandbox case.
851 // http://code.google.com/p/nativeclient/issues/detail?id=2131
852 if (type == PROCESS_TYPE_NACL_LOADER) {
853 const SIZE_T kOneGigabyte = 1 << 30;
854 void* nacl_mem = VirtualAllocEx(target.process_handle(),
855 NULL,
856 kOneGigabyte,
857 MEM_RESERVE,
858 PAGE_NOACCESS);
859 if (!nacl_mem) {
860 DLOG(WARNING) << "Failed to reserve address space for Native Client";
861 }
862 }
863 #endif // !defined(NACL_WIN64)
864
865 ResumeThread(target.thread_handle());
866
867 // Help the process a little. It can't start the debugger by itself if
868 // the process is in a sandbox.
869 if (child_needs_help)
870 base::debug::SpawnDebuggerOnProcess(target.process_id());
871
872 return target.TakeProcessHandle();
873 }
874
875 bool BrokerDuplicateHandle(HANDLE source_handle,
876 DWORD target_process_id,
877 HANDLE* target_handle,
878 DWORD desired_access,
879 DWORD options) {
880 // If our process is the target just duplicate the handle.
881 if (::GetCurrentProcessId() == target_process_id) {
882 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
883 ::GetCurrentProcess(), target_handle,
884 desired_access, FALSE, options);
885
886 }
887
888 // Try the broker next
889 if (g_target_services &&
890 g_target_services->DuplicateHandle(source_handle, target_process_id,
891 target_handle, desired_access,
892 options) == sandbox::SBOX_ALL_OK) {
893 return true;
894 }
895
896 // Finally, see if we already have access to the process.
897 base::win::ScopedHandle target_process;
898 target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE,
899 target_process_id));
900 if (target_process.IsValid()) {
901 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
902 target_process, target_handle,
903 desired_access, FALSE, options);
904 }
905
906 return false;
907 }
908
909 bool BrokerAddTargetPeer(HANDLE peer_process) {
910 return g_broker_services->AddTargetPeer(peer_process) == sandbox::SBOX_ALL_OK;
911 }
912
913 } // namespace content
OLDNEW
« no previous file with comments | « content/common/sandbox_policy.h ('k') | content/common/sandbox_util.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698