[AndroidWebViewShell] Add MediaStream API layout tests.
[chromium-blink-merge.git] / content / common / sandbox_win.cc
blob110edb8a6812438efa13d1d1549568dfdc6553b0
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 "content/common/sandbox_win.h"
7 #include <string>
9 #include "base/base_switches.h"
10 #include "base/command_line.h"
11 #include "base/debug/profiler.h"
12 #include "base/files/file_util.h"
13 #include "base/hash.h"
14 #include "base/memory/shared_memory.h"
15 #include "base/metrics/sparse_histogram.h"
16 #include "base/path_service.h"
17 #include "base/process/launch.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/trace_event/trace_event.h"
22 #include "base/win/iat_patch_function.h"
23 #include "base/win/scoped_handle.h"
24 #include "base/win/scoped_process_information.h"
25 #include "base/win/windows_version.h"
26 #include "content/common/content_switches_internal.h"
27 #include "content/public/common/content_client.h"
28 #include "content/public/common/content_switches.h"
29 #include "content/public/common/dwrite_font_platform_win.h"
30 #include "content/public/common/sandbox_init.h"
31 #include "content/public/common/sandboxed_process_launcher_delegate.h"
32 #include "sandbox/win/src/process_mitigations.h"
33 #include "sandbox/win/src/sandbox.h"
34 #include "sandbox/win/src/sandbox_nt_util.h"
35 #include "sandbox/win/src/sandbox_policy_base.h"
36 #include "sandbox/win/src/win_utils.h"
37 #include "ui/gfx/win/direct_write.h"
39 static sandbox::BrokerServices* g_broker_services = NULL;
40 static sandbox::TargetServices* g_target_services = NULL;
42 namespace content {
43 namespace {
45 // The DLLs listed here are known (or under strong suspicion) of causing crashes
46 // when they are loaded in the renderer. Note: at runtime we generate short
47 // versions of the dll name only if the dll has an extension.
48 // For more information about how this list is generated, and how to get off
49 // of it, see:
50 // https://sites.google.com/a/chromium.org/dev/Home/third-party-developers
51 const wchar_t* const kTroublesomeDlls[] = {
52 L"adialhk.dll", // Kaspersky Internet Security.
53 L"acpiz.dll", // Unknown.
54 L"airfoilinject3.dll", // Airfoil.
55 L"akinsofthook32.dll", // Akinsoft Software Engineering.
56 L"assistant_x64.dll", // Unknown.
57 L"avcuf64.dll", // Bit Defender Internet Security x64.
58 L"avgrsstx.dll", // AVG 8.
59 L"babylonchromepi.dll", // Babylon translator.
60 L"btkeyind.dll", // Widcomm Bluetooth.
61 L"cmcsyshk.dll", // CMC Internet Security.
62 L"cmsetac.dll", // Unknown (suspected malware).
63 L"cooliris.dll", // CoolIris.
64 L"cplushook.dll", // Unknown (suspected malware).
65 L"dockshellhook.dll", // Stardock Objectdock.
66 L"easyhook32.dll", // GDIPP and others.
67 L"esspd.dll", // Samsung Smart Security ESCORT.
68 L"googledesktopnetwork3.dll", // Google Desktop Search v5.
69 L"fwhook.dll", // PC Tools Firewall Plus.
70 L"hookprocesscreation.dll", // Blumentals Program protector.
71 L"hookterminateapis.dll", // Blumentals and Cyberprinter.
72 L"hookprintapis.dll", // Cyberprinter.
73 L"imon.dll", // NOD32 Antivirus.
74 L"icatcdll.dll", // Samsung Smart Security ESCORT.
75 L"icdcnl.dll", // Samsung Smart Security ESCORT.
76 L"ioloHL.dll", // Iolo (System Mechanic).
77 L"kloehk.dll", // Kaspersky Internet Security.
78 L"lawenforcer.dll", // Spyware-Browser AntiSpyware (Spybro).
79 L"libdivx.dll", // DivX.
80 L"lvprcinj01.dll", // Logitech QuickCam.
81 L"madchook.dll", // Madshi (generic hooking library).
82 L"mdnsnsp.dll", // Bonjour.
83 L"moonsysh.dll", // Moon Secure Antivirus.
84 L"mpk.dll", // KGB Spy.
85 L"npdivx32.dll", // DivX.
86 L"npggNT.des", // GameGuard 2008.
87 L"npggNT.dll", // GameGuard (older).
88 L"oawatch.dll", // Online Armor.
89 L"pastali32.dll", // PastaLeads.
90 L"pavhook.dll", // Panda Internet Security.
91 L"pavlsphook.dll", // Panda Antivirus.
92 L"pavshook.dll", // Panda Antivirus.
93 L"pavshookwow.dll", // Panda Antivirus.
94 L"pctavhook.dll", // PC Tools Antivirus.
95 L"pctgmhk.dll", // PC Tools Spyware Doctor.
96 L"picrmi32.dll", // PicRec.
97 L"picrmi64.dll", // PicRec.
98 L"prntrack.dll", // Pharos Systems.
99 L"protector.dll", // Unknown (suspected malware).
100 L"radhslib.dll", // Radiant Naomi Internet Filter.
101 L"radprlib.dll", // Radiant Naomi Internet Filter.
102 L"rapportnikko.dll", // Trustware Rapport.
103 L"rlhook.dll", // Trustware Bufferzone.
104 L"rooksdol.dll", // Trustware Rapport.
105 L"rndlpepperbrowserrecordhelper.dll", // RealPlayer.
106 L"rpchromebrowserrecordhelper.dll", // RealPlayer.
107 L"r3hook.dll", // Kaspersky Internet Security.
108 L"sahook.dll", // McAfee Site Advisor.
109 L"sbrige.dll", // Unknown.
110 L"sc2hook.dll", // Supercopier 2.
111 L"sdhook32.dll", // Spybot - Search & Destroy Live Protection.
112 L"sguard.dll", // Iolo (System Guard).
113 L"smum32.dll", // Spyware Doctor version 6.
114 L"smumhook.dll", // Spyware Doctor version 5.
115 L"ssldivx.dll", // DivX.
116 L"syncor11.dll", // SynthCore Midi interface.
117 L"systools.dll", // Panda Antivirus.
118 L"tfwah.dll", // Threatfire (PC tools).
119 L"wblind.dll", // Stardock Object desktop.
120 L"wbhelp.dll", // Stardock Object desktop.
121 L"winstylerthemehelper.dll" // Tuneup utilities 2006.
124 #if !defined(NACL_WIN64)
125 // Adds the policy rules for the path and path\ with the semantic |access|.
126 // If |children| is set to true, we need to add the wildcard rules to also
127 // apply the rule to the subfiles and subfolders.
128 bool AddDirectory(int path, const wchar_t* sub_dir, bool children,
129 sandbox::TargetPolicy::Semantics access,
130 sandbox::TargetPolicy* policy) {
131 base::FilePath directory;
132 if (!PathService::Get(path, &directory))
133 return false;
135 if (sub_dir)
136 directory = base::MakeAbsoluteFilePath(directory.Append(sub_dir));
138 sandbox::ResultCode result;
139 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
140 directory.value().c_str());
141 if (result != sandbox::SBOX_ALL_OK)
142 return false;
144 std::wstring directory_str = directory.value() + L"\\";
145 if (children)
146 directory_str += L"*";
147 // Otherwise, add the version of the path that ends with a separator.
149 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
150 directory_str.c_str());
151 if (result != sandbox::SBOX_ALL_OK)
152 return false;
154 return true;
156 #endif // !defined(NACL_WIN64)
158 // Compares the loaded |module| file name matches |module_name|.
159 bool IsExpandedModuleName(HMODULE module, const wchar_t* module_name) {
160 wchar_t path[MAX_PATH];
161 DWORD sz = ::GetModuleFileNameW(module, path, arraysize(path));
162 if ((sz == arraysize(path)) || (sz == 0)) {
163 // XP does not set the last error properly, so we bail out anyway.
164 return false;
166 if (!::GetLongPathName(path, path, arraysize(path)))
167 return false;
168 base::FilePath fname(path);
169 return (fname.BaseName().value() == module_name);
172 // Adds a single dll by |module_name| into the |policy| blacklist.
173 // If |check_in_browser| is true we only add an unload policy only if the dll
174 // is also loaded in this process.
175 void BlacklistAddOneDll(const wchar_t* module_name,
176 bool check_in_browser,
177 sandbox::TargetPolicy* policy) {
178 HMODULE module = check_in_browser ? ::GetModuleHandleW(module_name) : NULL;
179 if (!module) {
180 // The module could have been loaded with a 8.3 short name. We check
181 // the three most common cases: 'thelongname.dll' becomes
182 // 'thelon~1.dll', 'thelon~2.dll' and 'thelon~3.dll'.
183 std::wstring name(module_name);
184 size_t period = name.rfind(L'.');
185 DCHECK_NE(std::string::npos, period);
186 DCHECK_LE(3U, (name.size() - period));
187 if (period <= 8)
188 return;
189 for (wchar_t ix = '1'; ix <= '3'; ++ix) {
190 const wchar_t suffix[] = {'~', ix, 0};
191 std::wstring alt_name = name.substr(0, 6) + suffix;
192 alt_name += name.substr(period, name.size());
193 if (check_in_browser) {
194 module = ::GetModuleHandleW(alt_name.c_str());
195 if (!module)
196 return;
197 // We found it, but because it only has 6 significant letters, we
198 // want to make sure it is the right one.
199 if (!IsExpandedModuleName(module, module_name))
200 return;
202 // Found a match. We add both forms to the policy.
203 policy->AddDllToUnload(alt_name.c_str());
206 policy->AddDllToUnload(module_name);
207 DVLOG(1) << "dll to unload found: " << module_name;
208 return;
211 // Adds policy rules for unloaded the known dlls that cause chrome to crash.
212 // Eviction of injected DLLs is done by the sandbox so that the injected module
213 // does not get a chance to execute any code.
214 void AddGenericDllEvictionPolicy(sandbox::TargetPolicy* policy) {
215 for (int ix = 0; ix != arraysize(kTroublesomeDlls); ++ix)
216 BlacklistAddOneDll(kTroublesomeDlls[ix], true, policy);
219 // Returns the object path prepended with the current logon session.
220 base::string16 PrependWindowsSessionPath(const base::char16* object) {
221 // Cache this because it can't change after process creation.
222 static uintptr_t s_session_id = 0;
223 if (s_session_id == 0) {
224 HANDLE token;
225 DWORD session_id_length;
226 DWORD session_id = 0;
228 CHECK(::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token));
229 CHECK(::GetTokenInformation(token, TokenSessionId, &session_id,
230 sizeof(session_id), &session_id_length));
231 CloseHandle(token);
232 if (session_id)
233 s_session_id = session_id;
236 return base::StringPrintf(L"\\Sessions\\%d%ls", s_session_id, object);
239 // Checks if the sandbox should be let to run without a job object assigned.
240 bool ShouldSetJobLevel(const base::CommandLine& cmd_line) {
241 if (!cmd_line.HasSwitch(switches::kAllowNoSandboxJob))
242 return true;
244 // Windows 8 allows nested jobs so we don't need to check if we are in other
245 // job.
246 if (base::win::GetVersion() >= base::win::VERSION_WIN8)
247 return true;
249 BOOL in_job = true;
250 // Either there is no job yet associated so we must add our job,
251 if (!::IsProcessInJob(::GetCurrentProcess(), NULL, &in_job))
252 NOTREACHED() << "IsProcessInJob failed. " << GetLastError();
253 if (!in_job)
254 return true;
256 // ...or there is a job but the JOB_OBJECT_LIMIT_BREAKAWAY_OK limit is set.
257 JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info = {};
258 if (!::QueryInformationJobObject(NULL,
259 JobObjectExtendedLimitInformation, &job_info,
260 sizeof(job_info), NULL)) {
261 NOTREACHED() << "QueryInformationJobObject failed. " << GetLastError();
262 return true;
264 if (job_info.BasicLimitInformation.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK)
265 return true;
267 return false;
270 // Adds the generic policy rules to a sandbox TargetPolicy.
271 bool AddGenericPolicy(sandbox::TargetPolicy* policy) {
272 sandbox::ResultCode result;
274 // Renderers need to copy sections for plugin DIBs and GPU.
275 // GPU needs to copy sections to renderers.
276 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
277 sandbox::TargetPolicy::HANDLES_DUP_ANY,
278 L"Section");
279 if (result != sandbox::SBOX_ALL_OK)
280 return false;
282 // Add the policy for the client side of a pipe. It is just a file
283 // in the \pipe\ namespace. We restrict it to pipes that start with
284 // "chrome." so the sandboxed process cannot connect to system services.
285 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
286 sandbox::TargetPolicy::FILES_ALLOW_ANY,
287 L"\\??\\pipe\\chrome.*");
288 if (result != sandbox::SBOX_ALL_OK)
289 return false;
291 // Add the policy for the server side of nacl pipe. It is just a file
292 // in the \pipe\ namespace. We restrict it to pipes that start with
293 // "chrome.nacl" so the sandboxed process cannot connect to
294 // system services.
295 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
296 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
297 L"\\\\.\\pipe\\chrome.nacl.*");
298 if (result != sandbox::SBOX_ALL_OK)
299 return false;
301 // Allow the server side of sync sockets, which are pipes that have
302 // the "chrome.sync" namespace and a randomly generated suffix.
303 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
304 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
305 L"\\\\.\\pipe\\chrome.sync.*");
306 if (result != sandbox::SBOX_ALL_OK)
307 return false;
309 // Add the policy for debug message only in debug
310 #ifndef NDEBUG
311 base::FilePath app_dir;
312 if (!PathService::Get(base::DIR_MODULE, &app_dir))
313 return false;
315 wchar_t long_path_buf[MAX_PATH];
316 DWORD long_path_return_value = GetLongPathName(app_dir.value().c_str(),
317 long_path_buf,
318 MAX_PATH);
319 if (long_path_return_value == 0 || long_path_return_value >= MAX_PATH)
320 return false;
322 base::FilePath debug_message(long_path_buf);
323 debug_message = debug_message.AppendASCII("debug_message.exe");
324 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_PROCESS,
325 sandbox::TargetPolicy::PROCESS_MIN_EXEC,
326 debug_message.value().c_str());
327 if (result != sandbox::SBOX_ALL_OK)
328 return false;
329 #endif // NDEBUG
331 // Add the policy for read-only PDB file access for stack traces.
332 #if !defined(OFFICIAL_BUILD)
333 base::FilePath exe;
334 if (!PathService::Get(base::FILE_EXE, &exe))
335 return false;
336 base::FilePath pdb_path = exe.DirName().Append(L"*.pdb");
337 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
338 sandbox::TargetPolicy::FILES_ALLOW_READONLY,
339 pdb_path.value().c_str());
340 if (result != sandbox::SBOX_ALL_OK)
341 return false;
342 #endif
344 #if defined(SANITIZER_COVERAGE)
345 DWORD coverage_dir_size =
346 ::GetEnvironmentVariable(L"SANITIZER_COVERAGE_DIR", NULL, 0);
347 if (coverage_dir_size == 0) {
348 LOG(WARNING) << "SANITIZER_COVERAGE_DIR was not set, coverage won't work.";
349 } else {
350 std::wstring coverage_dir;
351 wchar_t* coverage_dir_str =
352 base::WriteInto(&coverage_dir, coverage_dir_size);
353 coverage_dir_size = ::GetEnvironmentVariable(
354 L"SANITIZER_COVERAGE_DIR", coverage_dir_str, coverage_dir_size);
355 CHECK(coverage_dir.size() == coverage_dir_size);
356 base::FilePath sancov_path =
357 base::FilePath(coverage_dir).Append(L"*.sancov");
358 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
359 sandbox::TargetPolicy::FILES_ALLOW_ANY,
360 sancov_path.value().c_str());
361 if (result != sandbox::SBOX_ALL_OK)
362 return false;
364 #endif
366 AddGenericDllEvictionPolicy(policy);
367 return true;
370 bool AddPolicyForSandboxedProcess(sandbox::TargetPolicy* policy) {
371 sandbox::ResultCode result;
372 // Renderers need to share events with plugins.
373 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
374 sandbox::TargetPolicy::HANDLES_DUP_ANY,
375 L"Event");
376 if (result != sandbox::SBOX_ALL_OK)
377 return false;
379 // Win8+ adds a device DeviceApi that we don't need.
380 if (base::win::GetVersion() > base::win::VERSION_WIN7)
381 result = policy->AddKernelObjectToClose(L"File", L"\\Device\\DeviceApi");
382 if (result != sandbox::SBOX_ALL_OK)
383 return false;
385 // Close the proxy settings on XP.
386 if (base::win::GetVersion() <= base::win::VERSION_SERVER_2003)
387 result = policy->AddKernelObjectToClose(L"Key",
388 L"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\" \
389 L"CurrentVersion\\Internet Settings");
390 if (result != sandbox::SBOX_ALL_OK)
391 return false;
394 sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED;
395 if (base::win::GetVersion() > base::win::VERSION_XP) {
396 // On 2003/Vista the initial token has to be restricted if the main
397 // token is restricted.
398 initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS;
401 policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN);
402 // Prevents the renderers from manipulating low-integrity processes.
403 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
404 policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
406 if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(true)) {
407 DLOG(WARNING) << "Failed to apply desktop security to the renderer";
410 return true;
413 // Updates the command line arguments with debug-related flags. If debug flags
414 // have been used with this process, they will be filtered and added to
415 // command_line as needed.
416 void ProcessDebugFlags(base::CommandLine* command_line) {
417 const base::CommandLine& current_cmd_line =
418 *base::CommandLine::ForCurrentProcess();
419 std::string type = command_line->GetSwitchValueASCII(switches::kProcessType);
420 if (current_cmd_line.HasSwitch(switches::kWaitForDebuggerChildren)) {
421 // Look to pass-on the kWaitForDebugger flag.
422 std::string value = current_cmd_line.GetSwitchValueASCII(
423 switches::kWaitForDebuggerChildren);
424 if (value.empty() || value == type) {
425 command_line->AppendSwitch(switches::kWaitForDebugger);
427 command_line->AppendSwitchASCII(switches::kWaitForDebuggerChildren, value);
431 // This code is test only, and attempts to catch unsafe uses of
432 // DuplicateHandle() that copy privileged handles into sandboxed processes.
433 #ifndef OFFICIAL_BUILD
434 base::win::IATPatchFunction g_iat_patch_duplicate_handle;
436 typedef BOOL (WINAPI *DuplicateHandleFunctionPtr)(HANDLE source_process_handle,
437 HANDLE source_handle,
438 HANDLE target_process_handle,
439 LPHANDLE target_handle,
440 DWORD desired_access,
441 BOOL inherit_handle,
442 DWORD options);
444 DuplicateHandleFunctionPtr g_iat_orig_duplicate_handle;
446 NtQueryObject g_QueryObject = NULL;
448 static const char* kDuplicateHandleWarning =
449 "You are attempting to duplicate a privileged handle into a sandboxed"
450 " process.\n Please use the sandbox::BrokerDuplicateHandle API or"
451 " contact security@chromium.org for assistance.";
453 void CheckDuplicateHandle(HANDLE handle) {
454 // Get the object type (32 characters is safe; current max is 14).
455 BYTE buffer[sizeof(OBJECT_TYPE_INFORMATION) + 32 * sizeof(wchar_t)];
456 OBJECT_TYPE_INFORMATION* type_info =
457 reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer);
458 ULONG size = sizeof(buffer) - sizeof(wchar_t);
459 NTSTATUS error;
460 error = g_QueryObject(handle, ObjectTypeInformation, type_info, size, &size);
461 CHECK(NT_SUCCESS(error));
462 type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
464 // Get the object basic information.
465 OBJECT_BASIC_INFORMATION basic_info;
466 size = sizeof(basic_info);
467 error = g_QueryObject(handle, ObjectBasicInformation, &basic_info, size,
468 &size);
469 CHECK(NT_SUCCESS(error));
471 CHECK(!(basic_info.GrantedAccess & WRITE_DAC)) <<
472 kDuplicateHandleWarning;
474 if (0 == _wcsicmp(type_info->Name.Buffer, L"Process")) {
475 const ACCESS_MASK kDangerousMask =
476 ~static_cast<DWORD>(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE);
477 CHECK(!(basic_info.GrantedAccess & kDangerousMask)) <<
478 kDuplicateHandleWarning;
482 BOOL WINAPI DuplicateHandlePatch(HANDLE source_process_handle,
483 HANDLE source_handle,
484 HANDLE target_process_handle,
485 LPHANDLE target_handle,
486 DWORD desired_access,
487 BOOL inherit_handle,
488 DWORD options) {
489 // Duplicate the handle so we get the final access mask.
490 if (!g_iat_orig_duplicate_handle(source_process_handle, source_handle,
491 target_process_handle, target_handle,
492 desired_access, inherit_handle, options))
493 return FALSE;
495 // We're not worried about broker handles or not crossing process boundaries.
496 if (source_process_handle == target_process_handle ||
497 target_process_handle == ::GetCurrentProcess())
498 return TRUE;
500 // Only sandboxed children are placed in jobs, so just check them.
501 BOOL is_in_job = FALSE;
502 if (!::IsProcessInJob(target_process_handle, NULL, &is_in_job)) {
503 // We need a handle with permission to check the job object.
504 if (ERROR_ACCESS_DENIED == ::GetLastError()) {
505 HANDLE temp_handle;
506 CHECK(g_iat_orig_duplicate_handle(::GetCurrentProcess(),
507 target_process_handle,
508 ::GetCurrentProcess(),
509 &temp_handle,
510 PROCESS_QUERY_INFORMATION,
511 FALSE, 0));
512 base::win::ScopedHandle process(temp_handle);
513 CHECK(::IsProcessInJob(process.Get(), NULL, &is_in_job));
517 if (is_in_job) {
518 // We never allow inheritable child handles.
519 CHECK(!inherit_handle) << kDuplicateHandleWarning;
521 // Duplicate the handle again, to get the final permissions.
522 HANDLE temp_handle;
523 CHECK(g_iat_orig_duplicate_handle(target_process_handle, *target_handle,
524 ::GetCurrentProcess(), &temp_handle,
525 0, FALSE, DUPLICATE_SAME_ACCESS));
526 base::win::ScopedHandle handle(temp_handle);
528 // Callers use CHECK macro to make sure we get the right stack.
529 CheckDuplicateHandle(handle.Get());
532 return TRUE;
534 #endif
536 } // namespace
538 void SetJobLevel(const base::CommandLine& cmd_line,
539 sandbox::JobLevel job_level,
540 uint32 ui_exceptions,
541 sandbox::TargetPolicy* policy) {
542 if (ShouldSetJobLevel(cmd_line)) {
543 #ifdef _WIN64
544 policy->SetJobMemoryLimit(4ULL * 1024 * 1024 * 1024);
545 #endif
546 policy->SetJobLevel(job_level, ui_exceptions);
547 } else {
548 policy->SetJobLevel(sandbox::JOB_NONE, 0);
552 // TODO(jschuh): Need get these restrictions applied to NaCl and Pepper.
553 // Just have to figure out what needs to be warmed up first.
554 void AddBaseHandleClosePolicy(sandbox::TargetPolicy* policy) {
555 // TODO(cpu): Add back the BaseNamedObjects policy.
556 base::string16 object_path = PrependWindowsSessionPath(
557 L"\\BaseNamedObjects\\windows_shell_global_counters");
558 policy->AddKernelObjectToClose(L"Section", object_path.data());
561 void AddAppContainerPolicy(sandbox::TargetPolicy* policy, const wchar_t* sid) {
562 if (base::win::GetVersion() == base::win::VERSION_WIN8 ||
563 base::win::GetVersion() == base::win::VERSION_WIN8_1) {
564 const base::CommandLine& command_line =
565 *base::CommandLine::ForCurrentProcess();
566 if (command_line.HasSwitch(switches::kEnableAppContainer)) {
567 policy->SetLowBox(sid);
572 bool InitBrokerServices(sandbox::BrokerServices* broker_services) {
573 // TODO(abarth): DCHECK(CalledOnValidThread());
574 // See <http://b/1287166>.
575 DCHECK(broker_services);
576 DCHECK(!g_broker_services);
577 sandbox::ResultCode result = broker_services->Init();
578 g_broker_services = broker_services;
580 // In non-official builds warn about dangerous uses of DuplicateHandle.
581 #ifndef OFFICIAL_BUILD
582 BOOL is_in_job = FALSE;
583 CHECK(::IsProcessInJob(::GetCurrentProcess(), NULL, &is_in_job));
584 // In a Syzygy-profiled binary, instrumented for import profiling, this
585 // patch will end in infinite recursion on the attempted delegation to the
586 // original function.
587 if (!base::debug::IsBinaryInstrumented() &&
588 !is_in_job && !g_iat_patch_duplicate_handle.is_patched()) {
589 HMODULE module = NULL;
590 wchar_t module_name[MAX_PATH];
591 CHECK(::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
592 reinterpret_cast<LPCWSTR>(InitBrokerServices),
593 &module));
594 DWORD result = ::GetModuleFileNameW(module, module_name, MAX_PATH);
595 if (result && (result != MAX_PATH)) {
596 ResolveNTFunctionPtr("NtQueryObject", &g_QueryObject);
597 result = g_iat_patch_duplicate_handle.Patch(
598 module_name, "kernel32.dll", "DuplicateHandle",
599 DuplicateHandlePatch);
600 CHECK(result == 0);
601 g_iat_orig_duplicate_handle =
602 reinterpret_cast<DuplicateHandleFunctionPtr>(
603 g_iat_patch_duplicate_handle.original_function());
606 #endif
608 return sandbox::SBOX_ALL_OK == result;
611 bool InitTargetServices(sandbox::TargetServices* target_services) {
612 DCHECK(target_services);
613 DCHECK(!g_target_services);
614 sandbox::ResultCode result = target_services->Init();
615 g_target_services = target_services;
616 return sandbox::SBOX_ALL_OK == result;
619 base::Process StartSandboxedProcess(
620 SandboxedProcessLauncherDelegate* delegate,
621 base::CommandLine* cmd_line) {
622 const base::CommandLine& browser_command_line =
623 *base::CommandLine::ForCurrentProcess();
624 std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
626 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
628 // Propagate the --allow-no-job flag if present.
629 if (browser_command_line.HasSwitch(switches::kAllowNoSandboxJob) &&
630 !cmd_line->HasSwitch(switches::kAllowNoSandboxJob)) {
631 cmd_line->AppendSwitch(switches::kAllowNoSandboxJob);
634 ProcessDebugFlags(cmd_line);
636 // Prefetch hints on windows:
637 // Using a different prefetch profile per process type will allow Windows
638 // to create separate pretetch settings for browser, renderer etc.
639 cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", base::Hash(type_str)));
641 if ((delegate && !delegate->ShouldSandbox()) ||
642 browser_command_line.HasSwitch(switches::kNoSandbox) ||
643 cmd_line->HasSwitch(switches::kNoSandbox)) {
644 base::Process process =
645 base::LaunchProcess(*cmd_line, base::LaunchOptions());
646 // TODO(rvargas) crbug.com/417532: Don't share a raw handle.
647 g_broker_services->AddTargetPeer(process.Handle());
648 return process.Pass();
651 sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
653 sandbox::MitigationFlags mitigations = sandbox::MITIGATION_HEAP_TERMINATE |
654 sandbox::MITIGATION_BOTTOM_UP_ASLR |
655 sandbox::MITIGATION_DEP |
656 sandbox::MITIGATION_DEP_NO_ATL_THUNK |
657 sandbox::MITIGATION_SEHOP;
659 #if !defined(NACL_WIN64)
660 if (type_str == switches::kRendererProcess &&
661 IsWin32kRendererLockdownEnabled()) {
662 if (policy->AddRule(sandbox::TargetPolicy::SUBSYS_WIN32K_LOCKDOWN,
663 sandbox::TargetPolicy::FAKE_USER_GDI_INIT,
664 NULL) != sandbox::SBOX_ALL_OK) {
665 return base::Process();
667 mitigations |= sandbox::MITIGATION_WIN32K_DISABLE;
669 #endif
671 if (policy->SetProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
672 return base::Process();
674 mitigations = sandbox::MITIGATION_STRICT_HANDLE_CHECKS |
675 sandbox::MITIGATION_DLL_SEARCH_ORDER;
677 if (policy->SetDelayedProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
678 return base::Process();
680 SetJobLevel(*cmd_line, sandbox::JOB_LOCKDOWN, 0, policy);
682 bool disable_default_policy = false;
683 base::FilePath exposed_dir;
684 if (delegate)
685 delegate->PreSandbox(&disable_default_policy, &exposed_dir);
687 if (!disable_default_policy && !AddPolicyForSandboxedProcess(policy))
688 return base::Process();
690 if (type_str == switches::kRendererProcess) {
691 #if !defined(NACL_WIN64)
692 if (gfx::win::ShouldUseDirectWrite()) {
693 AddDirectory(base::DIR_WINDOWS_FONTS,
694 NULL,
695 true,
696 sandbox::TargetPolicy::FILES_ALLOW_READONLY,
697 policy);
699 // If DirectWrite is enabled for font rendering then open the font cache
700 // section which is created by the browser and pass the handle to the
701 // renderer process. This is needed because renderer processes on
702 // Windows 8+ may be running in an AppContainer sandbox and hence their
703 // kernel object namespace may be partitioned.
704 std::string name(content::kFontCacheSharedSectionName);
705 name.append(base::UintToString(base::GetCurrentProcId()));
707 base::SharedMemory direct_write_font_cache_section;
708 if (direct_write_font_cache_section.Open(name, true)) {
709 void* shared_handle =
710 policy->AddHandleToShare(direct_write_font_cache_section.handle());
711 cmd_line->AppendSwitchASCII(switches::kFontCacheSharedHandle,
712 base::UintToString(reinterpret_cast<unsigned int>(shared_handle)));
715 #endif
716 } else {
717 // Hack for Google Desktop crash. Trick GD into not injecting its DLL into
718 // this subprocess. See
719 // http://code.google.com/p/chromium/issues/detail?id=25580
720 cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
723 sandbox::ResultCode result;
724 if (!exposed_dir.empty()) {
725 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
726 sandbox::TargetPolicy::FILES_ALLOW_ANY,
727 exposed_dir.value().c_str());
728 if (result != sandbox::SBOX_ALL_OK)
729 return base::Process();
731 base::FilePath exposed_files = exposed_dir.AppendASCII("*");
732 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
733 sandbox::TargetPolicy::FILES_ALLOW_ANY,
734 exposed_files.value().c_str());
735 if (result != sandbox::SBOX_ALL_OK)
736 return base::Process();
739 if (!AddGenericPolicy(policy)) {
740 NOTREACHED();
741 return base::Process();
744 #if !defined(OFFICIAL_BUILD)
745 // If stdout/stderr point to a Windows console, these calls will
746 // have no effect.
747 policy->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE));
748 policy->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE));
749 #endif
751 if (delegate) {
752 bool success = true;
753 delegate->PreSpawnTarget(policy, &success);
754 if (!success)
755 return base::Process();
758 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
760 PROCESS_INFORMATION temp_process_info = {};
761 result = g_broker_services->SpawnTarget(
762 cmd_line->GetProgram().value().c_str(),
763 cmd_line->GetCommandLineString().c_str(),
764 policy, &temp_process_info);
765 DWORD last_error = ::GetLastError();
766 base::win::ScopedProcessInformation target(temp_process_info);
768 TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
770 if (sandbox::SBOX_ALL_OK != result) {
771 if (result == sandbox::SBOX_ERROR_GENERIC)
772 DPLOG(ERROR) << "Failed to launch process";
773 else if (result == sandbox::SBOX_ERROR_CREATE_PROCESS) {
774 // TODO(shrikant): Remove this special case handling after determining
775 // cause for lowbox/createprocess errors.
776 sandbox::PolicyBase* policy_base =
777 static_cast<sandbox::PolicyBase*>(policy);
778 UMA_HISTOGRAM_SPARSE_SLOWLY(policy_base->GetLowBoxSid() ?
779 "Process.Sandbox.Lowbox.Launch.Error" :
780 "Process.Sandbox.Launch.Error",
781 last_error);
782 } else
783 DLOG(ERROR) << "Failed to launch process. Error: " << result;
785 policy->Release();
786 return base::Process();
788 policy->Release();
790 if (delegate)
791 delegate->PostSpawnTarget(target.process_handle());
793 CHECK(ResumeThread(target.thread_handle()) != -1);
794 TRACE_EVENT_END_ETW("StartProcessWithAccess", 0, type_str);
795 return base::Process(target.TakeProcessHandle());
798 bool BrokerDuplicateHandle(HANDLE source_handle,
799 DWORD target_process_id,
800 HANDLE* target_handle,
801 DWORD desired_access,
802 DWORD options) {
803 // If our process is the target just duplicate the handle.
804 if (::GetCurrentProcessId() == target_process_id) {
805 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
806 ::GetCurrentProcess(), target_handle,
807 desired_access, FALSE, options);
811 // Try the broker next
812 if (g_target_services &&
813 g_target_services->DuplicateHandle(source_handle, target_process_id,
814 target_handle, desired_access,
815 options) == sandbox::SBOX_ALL_OK) {
816 return true;
819 // Finally, see if we already have access to the process.
820 base::win::ScopedHandle target_process;
821 target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE,
822 target_process_id));
823 if (target_process.IsValid()) {
824 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
825 target_process.Get(), target_handle,
826 desired_access, FALSE, options);
829 return false;
832 bool BrokerAddTargetPeer(HANDLE peer_process) {
833 return g_broker_services->AddTargetPeer(peer_process) == sandbox::SBOX_ALL_OK;
836 } // namespace content