exclude GcdPrivateAPITest.AddRemove from browser_tests Dr.Memory bot
[chromium-blink-merge.git] / content / common / sandbox_win.cc
blob68a00dd55908e07826be58616e45858e8d996cdd
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/debug/trace_event.h"
13 #include "base/file_util.h"
14 #include "base/hash.h"
15 #include "base/metrics/field_trial.h"
16 #include "base/path_service.h"
17 #include "base/process/launch.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/win/iat_patch_function.h"
21 #include "base/win/scoped_handle.h"
22 #include "base/win/scoped_process_information.h"
23 #include "base/win/windows_version.h"
24 #include "content/public/common/content_client.h"
25 #include "content/public/common/content_switches.h"
26 #include "content/public/common/sandbox_init.h"
27 #include "content/public/common/sandboxed_process_launcher_delegate.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/gfx/win/dpi.h"
34 static sandbox::BrokerServices* g_broker_services = NULL;
35 static sandbox::TargetServices* g_target_services = NULL;
37 namespace content {
38 namespace {
40 // The DLLs listed here are known (or under strong suspicion) of causing crashes
41 // when they are loaded in the renderer. Note: at runtime we generate short
42 // versions of the dll name only if the dll has an extension.
43 // For more information about how this list is generated, and how to get off
44 // of it, see:
45 // https://sites.google.com/a/chromium.org/dev/Home/third-party-developers
46 // If the size of this list exceeds 64, change kTroublesomeDllsMaxCount.
47 const wchar_t* const kTroublesomeDlls[] = {
48 L"adialhk.dll", // Kaspersky Internet Security.
49 L"acpiz.dll", // Unknown.
50 L"akinsofthook32.dll", // Akinsoft Software Engineering.
51 L"assistant_x64.dll", // Unknown.
52 L"avcuf64.dll", // Bit Defender Internet Security x64.
53 L"avgrsstx.dll", // AVG 8.
54 L"babylonchromepi.dll", // Babylon translator.
55 L"btkeyind.dll", // Widcomm Bluetooth.
56 L"cmcsyshk.dll", // CMC Internet Security.
57 L"cmsetac.dll", // Unknown (suspected malware).
58 L"cooliris.dll", // CoolIris.
59 L"dockshellhook.dll", // Stardock Objectdock.
60 L"easyhook32.dll", // GDIPP and others.
61 L"googledesktopnetwork3.dll", // Google Desktop Search v5.
62 L"fwhook.dll", // PC Tools Firewall Plus.
63 L"hookprocesscreation.dll", // Blumentals Program protector.
64 L"hookterminateapis.dll", // Blumentals and Cyberprinter.
65 L"hookprintapis.dll", // Cyberprinter.
66 L"imon.dll", // NOD32 Antivirus.
67 L"ioloHL.dll", // Iolo (System Mechanic).
68 L"kloehk.dll", // Kaspersky Internet Security.
69 L"lawenforcer.dll", // Spyware-Browser AntiSpyware (Spybro).
70 L"libdivx.dll", // DivX.
71 L"lvprcinj01.dll", // Logitech QuickCam.
72 L"madchook.dll", // Madshi (generic hooking library).
73 L"mdnsnsp.dll", // Bonjour.
74 L"moonsysh.dll", // Moon Secure Antivirus.
75 L"mpk.dll", // KGB Spy.
76 L"npdivx32.dll", // DivX.
77 L"npggNT.des", // GameGuard 2008.
78 L"npggNT.dll", // GameGuard (older).
79 L"oawatch.dll", // Online Armor.
80 L"pavhook.dll", // Panda Internet Security.
81 L"pavlsphook.dll", // Panda Antivirus.
82 L"pavshook.dll", // Panda Antivirus.
83 L"pavshookwow.dll", // Panda Antivirus.
84 L"pctavhook.dll", // PC Tools Antivirus.
85 L"pctgmhk.dll", // PC Tools Spyware Doctor.
86 L"prntrack.dll", // Pharos Systems.
87 L"protector.dll", // Unknown (suspected malware).
88 L"radhslib.dll", // Radiant Naomi Internet Filter.
89 L"radprlib.dll", // Radiant Naomi Internet Filter.
90 L"rapportnikko.dll", // Trustware Rapport.
91 L"rlhook.dll", // Trustware Bufferzone.
92 L"rooksdol.dll", // Trustware Rapport.
93 L"rndlpepperbrowserrecordhelper.dll", // RealPlayer.
94 L"rpchromebrowserrecordhelper.dll", // RealPlayer.
95 L"r3hook.dll", // Kaspersky Internet Security.
96 L"sahook.dll", // McAfee Site Advisor.
97 L"sbrige.dll", // Unknown.
98 L"sc2hook.dll", // Supercopier 2.
99 L"sdhook32.dll", // Spybot - Search & Destroy Live Protection.
100 L"sguard.dll", // Iolo (System Guard).
101 L"smum32.dll", // Spyware Doctor version 6.
102 L"smumhook.dll", // Spyware Doctor version 5.
103 L"ssldivx.dll", // DivX.
104 L"syncor11.dll", // SynthCore Midi interface.
105 L"systools.dll", // Panda Antivirus.
106 L"tfwah.dll", // Threatfire (PC tools).
107 L"wblind.dll", // Stardock Object desktop.
108 L"wbhelp.dll", // Stardock Object desktop.
109 L"winstylerthemehelper.dll" // Tuneup utilities 2006.
112 // Adds the policy rules for the path and path\ with the semantic |access|.
113 // If |children| is set to true, we need to add the wildcard rules to also
114 // apply the rule to the subfiles and subfolders.
115 bool AddDirectory(int path, const wchar_t* sub_dir, bool children,
116 sandbox::TargetPolicy::Semantics access,
117 sandbox::TargetPolicy* policy) {
118 base::FilePath directory;
119 if (!PathService::Get(path, &directory))
120 return false;
122 if (sub_dir)
123 directory = base::MakeAbsoluteFilePath(directory.Append(sub_dir));
125 sandbox::ResultCode result;
126 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
127 directory.value().c_str());
128 if (result != sandbox::SBOX_ALL_OK)
129 return false;
131 std::wstring directory_str = directory.value() + L"\\";
132 if (children)
133 directory_str += L"*";
134 // Otherwise, add the version of the path that ends with a separator.
136 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
137 directory_str.c_str());
138 if (result != sandbox::SBOX_ALL_OK)
139 return false;
141 return true;
144 // Adds the policy rules for the path and path\* with the semantic |access|.
145 // We need to add the wildcard rules to also apply the rule to the subkeys.
146 bool AddKeyAndSubkeys(std::wstring key,
147 sandbox::TargetPolicy::Semantics access,
148 sandbox::TargetPolicy* policy) {
149 sandbox::ResultCode result;
150 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
151 key.c_str());
152 if (result != sandbox::SBOX_ALL_OK)
153 return false;
155 key += L"\\*";
156 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
157 key.c_str());
158 if (result != sandbox::SBOX_ALL_OK)
159 return false;
161 return true;
164 // Compares the loaded |module| file name matches |module_name|.
165 bool IsExpandedModuleName(HMODULE module, const wchar_t* module_name) {
166 wchar_t path[MAX_PATH];
167 DWORD sz = ::GetModuleFileNameW(module, path, arraysize(path));
168 if ((sz == arraysize(path)) || (sz == 0)) {
169 // XP does not set the last error properly, so we bail out anyway.
170 return false;
172 if (!::GetLongPathName(path, path, arraysize(path)))
173 return false;
174 base::FilePath fname(path);
175 return (fname.BaseName().value() == module_name);
178 // Adds a single dll by |module_name| into the |policy| blacklist.
179 // If |check_in_browser| is true we only add an unload policy only if the dll
180 // is also loaded in this process.
181 void BlacklistAddOneDll(const wchar_t* module_name,
182 bool check_in_browser,
183 sandbox::TargetPolicy* policy) {
184 HMODULE module = check_in_browser ? ::GetModuleHandleW(module_name) : NULL;
185 if (!module) {
186 // The module could have been loaded with a 8.3 short name. We check
187 // the three most common cases: 'thelongname.dll' becomes
188 // 'thelon~1.dll', 'thelon~2.dll' and 'thelon~3.dll'.
189 std::wstring name(module_name);
190 size_t period = name.rfind(L'.');
191 DCHECK_NE(std::string::npos, period);
192 DCHECK_LE(3U, (name.size() - period));
193 if (period <= 8)
194 return;
195 for (int ix = 0; ix < 3; ++ix) {
196 const wchar_t suffix[] = {'~', ('1' + ix), 0};
197 std::wstring alt_name = name.substr(0, 6) + suffix;
198 alt_name += name.substr(period, name.size());
199 if (check_in_browser) {
200 module = ::GetModuleHandleW(alt_name.c_str());
201 if (!module)
202 return;
203 // We found it, but because it only has 6 significant letters, we
204 // want to make sure it is the right one.
205 if (!IsExpandedModuleName(module, module_name))
206 return;
208 // Found a match. We add both forms to the policy.
209 policy->AddDllToUnload(alt_name.c_str());
212 policy->AddDllToUnload(module_name);
213 DVLOG(1) << "dll to unload found: " << module_name;
214 return;
217 // Adds policy rules for unloaded the known dlls that cause chrome to crash.
218 // Eviction of injected DLLs is done by the sandbox so that the injected module
219 // does not get a chance to execute any code.
220 void AddGenericDllEvictionPolicy(sandbox::TargetPolicy* policy) {
221 for (int ix = 0; ix != arraysize(kTroublesomeDlls); ++ix)
222 BlacklistAddOneDll(kTroublesomeDlls[ix], true, policy);
225 // Returns the object path prepended with the current logon session.
226 base::string16 PrependWindowsSessionPath(const base::char16* object) {
227 // Cache this because it can't change after process creation.
228 static uintptr_t s_session_id = 0;
229 if (s_session_id == 0) {
230 HANDLE token;
231 DWORD session_id_length;
232 DWORD session_id = 0;
234 CHECK(::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token));
235 CHECK(::GetTokenInformation(token, TokenSessionId, &session_id,
236 sizeof(session_id), &session_id_length));
237 CloseHandle(token);
238 if (session_id)
239 s_session_id = session_id;
242 return base::StringPrintf(L"\\Sessions\\%d%ls", s_session_id, object);
245 // Checks if the sandbox should be let to run without a job object assigned.
246 bool ShouldSetJobLevel(const CommandLine& cmd_line) {
247 if (!cmd_line.HasSwitch(switches::kAllowNoSandboxJob))
248 return true;
250 // Windows 8 allows nested jobs so we don't need to check if we are in other
251 // job.
252 if (base::win::GetVersion() >= base::win::VERSION_WIN8)
253 return true;
255 BOOL in_job = true;
256 // Either there is no job yet associated so we must add our job,
257 if (!::IsProcessInJob(::GetCurrentProcess(), NULL, &in_job))
258 NOTREACHED() << "IsProcessInJob failed. " << GetLastError();
259 if (!in_job)
260 return true;
262 // ...or there is a job but the JOB_OBJECT_LIMIT_BREAKAWAY_OK limit is set.
263 JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info = {0};
264 if (!::QueryInformationJobObject(NULL,
265 JobObjectExtendedLimitInformation, &job_info,
266 sizeof(job_info), NULL)) {
267 NOTREACHED() << "QueryInformationJobObject failed. " << GetLastError();
268 return true;
270 if (job_info.BasicLimitInformation.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK)
271 return true;
273 return false;
276 // Adds the generic policy rules to a sandbox TargetPolicy.
277 bool AddGenericPolicy(sandbox::TargetPolicy* policy) {
278 sandbox::ResultCode result;
280 // Renderers need to copy sections for plugin DIBs and GPU.
281 // GPU needs to copy sections to renderers.
282 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
283 sandbox::TargetPolicy::HANDLES_DUP_ANY,
284 L"Section");
285 if (result != sandbox::SBOX_ALL_OK)
286 return false;
288 // Add the policy for the client side of a pipe. It is just a file
289 // in the \pipe\ namespace. We restrict it to pipes that start with
290 // "chrome." so the sandboxed process cannot connect to system services.
291 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
292 sandbox::TargetPolicy::FILES_ALLOW_ANY,
293 L"\\??\\pipe\\chrome.*");
294 if (result != sandbox::SBOX_ALL_OK)
295 return false;
297 // Add the policy for the server side of nacl pipe. It is just a file
298 // in the \pipe\ namespace. We restrict it to pipes that start with
299 // "chrome.nacl" so the sandboxed process cannot connect to
300 // system services.
301 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
302 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
303 L"\\\\.\\pipe\\chrome.nacl.*");
304 if (result != sandbox::SBOX_ALL_OK)
305 return false;
307 // Allow the server side of sync sockets, which are pipes that have
308 // the "chrome.sync" namespace and a randomly generated suffix.
309 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
310 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
311 L"\\\\.\\pipe\\chrome.sync.*");
312 if (result != sandbox::SBOX_ALL_OK)
313 return false;
315 // Add the policy for debug message only in debug
316 #ifndef NDEBUG
317 base::FilePath app_dir;
318 if (!PathService::Get(base::DIR_MODULE, &app_dir))
319 return false;
321 wchar_t long_path_buf[MAX_PATH];
322 DWORD long_path_return_value = GetLongPathName(app_dir.value().c_str(),
323 long_path_buf,
324 MAX_PATH);
325 if (long_path_return_value == 0 || long_path_return_value >= MAX_PATH)
326 return false;
328 base::FilePath debug_message(long_path_buf);
329 debug_message = debug_message.AppendASCII("debug_message.exe");
330 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_PROCESS,
331 sandbox::TargetPolicy::PROCESS_MIN_EXEC,
332 debug_message.value().c_str());
333 if (result != sandbox::SBOX_ALL_OK)
334 return false;
335 #endif // NDEBUG
337 AddGenericDllEvictionPolicy(policy);
338 return true;
341 bool AddPolicyForSandboxedProcess(sandbox::TargetPolicy* policy) {
342 sandbox::ResultCode result;
343 // Renderers need to share events with plugins.
344 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
345 sandbox::TargetPolicy::HANDLES_DUP_ANY,
346 L"Event");
347 if (result != sandbox::SBOX_ALL_OK)
348 return false;
350 // Win8+ adds a device DeviceApi that we don't need.
351 if (base::win::GetVersion() > base::win::VERSION_WIN7)
352 policy->AddKernelObjectToClose(L"File", L"\\Device\\DeviceApi");
354 sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED;
355 if (base::win::GetVersion() > base::win::VERSION_XP) {
356 // On 2003/Vista the initial token has to be restricted if the main
357 // token is restricted.
358 initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS;
361 policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN);
362 // Prevents the renderers from manipulating low-integrity processes.
363 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
364 policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
366 if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(true)) {
367 DLOG(WARNING) << "Failed to apply desktop security to the renderer";
370 return true;
373 // Updates the command line arguments with debug-related flags. If debug flags
374 // have been used with this process, they will be filtered and added to
375 // command_line as needed.
376 void ProcessDebugFlags(CommandLine* command_line) {
377 const CommandLine& current_cmd_line = *CommandLine::ForCurrentProcess();
378 std::string type = command_line->GetSwitchValueASCII(switches::kProcessType);
379 if (current_cmd_line.HasSwitch(switches::kWaitForDebuggerChildren)) {
380 // Look to pass-on the kWaitForDebugger flag.
381 std::string value = current_cmd_line.GetSwitchValueASCII(
382 switches::kWaitForDebuggerChildren);
383 if (value.empty() || value == type) {
384 command_line->AppendSwitch(switches::kWaitForDebugger);
386 command_line->AppendSwitchASCII(switches::kWaitForDebuggerChildren, value);
390 // This code is test only, and attempts to catch unsafe uses of
391 // DuplicateHandle() that copy privileged handles into sandboxed processes.
392 #ifndef OFFICIAL_BUILD
393 base::win::IATPatchFunction g_iat_patch_duplicate_handle;
395 typedef BOOL (WINAPI *DuplicateHandleFunctionPtr)(HANDLE source_process_handle,
396 HANDLE source_handle,
397 HANDLE target_process_handle,
398 LPHANDLE target_handle,
399 DWORD desired_access,
400 BOOL inherit_handle,
401 DWORD options);
403 DuplicateHandleFunctionPtr g_iat_orig_duplicate_handle;
405 NtQueryObject g_QueryObject = NULL;
407 static const char* kDuplicateHandleWarning =
408 "You are attempting to duplicate a privileged handle into a sandboxed"
409 " process.\n Please use the sandbox::BrokerDuplicateHandle API or"
410 " contact security@chromium.org for assistance.";
412 void CheckDuplicateHandle(HANDLE handle) {
413 // Get the object type (32 characters is safe; current max is 14).
414 BYTE buffer[sizeof(OBJECT_TYPE_INFORMATION) + 32 * sizeof(wchar_t)];
415 OBJECT_TYPE_INFORMATION* type_info =
416 reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer);
417 ULONG size = sizeof(buffer) - sizeof(wchar_t);
418 NTSTATUS error;
419 error = g_QueryObject(handle, ObjectTypeInformation, type_info, size, &size);
420 CHECK(NT_SUCCESS(error));
421 type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
423 // Get the object basic information.
424 OBJECT_BASIC_INFORMATION basic_info;
425 size = sizeof(basic_info);
426 error = g_QueryObject(handle, ObjectBasicInformation, &basic_info, size,
427 &size);
428 CHECK(NT_SUCCESS(error));
430 CHECK(!(basic_info.GrantedAccess & WRITE_DAC)) <<
431 kDuplicateHandleWarning;
433 if (0 == _wcsicmp(type_info->Name.Buffer, L"Process")) {
434 const ACCESS_MASK kDangerousMask = ~(PROCESS_QUERY_LIMITED_INFORMATION |
435 SYNCHRONIZE);
436 CHECK(!(basic_info.GrantedAccess & kDangerousMask)) <<
437 kDuplicateHandleWarning;
441 BOOL WINAPI DuplicateHandlePatch(HANDLE source_process_handle,
442 HANDLE source_handle,
443 HANDLE target_process_handle,
444 LPHANDLE target_handle,
445 DWORD desired_access,
446 BOOL inherit_handle,
447 DWORD options) {
448 // Duplicate the handle so we get the final access mask.
449 if (!g_iat_orig_duplicate_handle(source_process_handle, source_handle,
450 target_process_handle, target_handle,
451 desired_access, inherit_handle, options))
452 return FALSE;
454 // We're not worried about broker handles or not crossing process boundaries.
455 if (source_process_handle == target_process_handle ||
456 target_process_handle == ::GetCurrentProcess())
457 return TRUE;
459 // Only sandboxed children are placed in jobs, so just check them.
460 BOOL is_in_job = FALSE;
461 if (!::IsProcessInJob(target_process_handle, NULL, &is_in_job)) {
462 // We need a handle with permission to check the job object.
463 if (ERROR_ACCESS_DENIED == ::GetLastError()) {
464 HANDLE temp_handle;
465 CHECK(g_iat_orig_duplicate_handle(::GetCurrentProcess(),
466 target_process_handle,
467 ::GetCurrentProcess(),
468 &temp_handle,
469 PROCESS_QUERY_INFORMATION,
470 FALSE, 0));
471 base::win::ScopedHandle process(temp_handle);
472 CHECK(::IsProcessInJob(process, NULL, &is_in_job));
476 if (is_in_job) {
477 // We never allow inheritable child handles.
478 CHECK(!inherit_handle) << kDuplicateHandleWarning;
480 // Duplicate the handle again, to get the final permissions.
481 HANDLE temp_handle;
482 CHECK(g_iat_orig_duplicate_handle(target_process_handle, *target_handle,
483 ::GetCurrentProcess(), &temp_handle,
484 0, FALSE, DUPLICATE_SAME_ACCESS));
485 base::win::ScopedHandle handle(temp_handle);
487 // Callers use CHECK macro to make sure we get the right stack.
488 CheckDuplicateHandle(handle);
491 return TRUE;
493 #endif
495 } // namespace
497 void SetJobLevel(const CommandLine& cmd_line,
498 sandbox::JobLevel job_level,
499 uint32 ui_exceptions,
500 sandbox::TargetPolicy* policy) {
501 if (ShouldSetJobLevel(cmd_line)) {
502 #ifdef _WIN64
503 policy->SetJobMemoryLimit(4ULL * 1024 * 1024 * 1024);
504 #endif
505 policy->SetJobLevel(job_level, ui_exceptions);
506 } else {
507 policy->SetJobLevel(sandbox::JOB_NONE, 0);
511 // TODO(jschuh): Need get these restrictions applied to NaCl and Pepper.
512 // Just have to figure out what needs to be warmed up first.
513 void AddBaseHandleClosePolicy(sandbox::TargetPolicy* policy) {
514 // TODO(cpu): Add back the BaseNamedObjects policy.
515 base::string16 object_path = PrependWindowsSessionPath(
516 L"\\BaseNamedObjects\\windows_shell_global_counters");
517 policy->AddKernelObjectToClose(L"Section", object_path.data());
520 bool InitBrokerServices(sandbox::BrokerServices* broker_services) {
521 // TODO(abarth): DCHECK(CalledOnValidThread());
522 // See <http://b/1287166>.
523 DCHECK(broker_services);
524 DCHECK(!g_broker_services);
525 sandbox::ResultCode result = broker_services->Init();
526 g_broker_services = broker_services;
528 // In non-official builds warn about dangerous uses of DuplicateHandle.
529 #ifndef OFFICIAL_BUILD
530 BOOL is_in_job = FALSE;
531 CHECK(::IsProcessInJob(::GetCurrentProcess(), NULL, &is_in_job));
532 // In a Syzygy-profiled binary, instrumented for import profiling, this
533 // patch will end in infinite recursion on the attempted delegation to the
534 // original function.
535 if (!base::debug::IsBinaryInstrumented() &&
536 !is_in_job && !g_iat_patch_duplicate_handle.is_patched()) {
537 HMODULE module = NULL;
538 wchar_t module_name[MAX_PATH];
539 CHECK(::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
540 reinterpret_cast<LPCWSTR>(InitBrokerServices),
541 &module));
542 DWORD result = ::GetModuleFileNameW(module, module_name, MAX_PATH);
543 if (result && (result != MAX_PATH)) {
544 ResolveNTFunctionPtr("NtQueryObject", &g_QueryObject);
545 result = g_iat_patch_duplicate_handle.Patch(
546 module_name, "kernel32.dll", "DuplicateHandle",
547 DuplicateHandlePatch);
548 CHECK(result == 0);
549 g_iat_orig_duplicate_handle =
550 reinterpret_cast<DuplicateHandleFunctionPtr>(
551 g_iat_patch_duplicate_handle.original_function());
554 #endif
556 return sandbox::SBOX_ALL_OK == result;
559 bool InitTargetServices(sandbox::TargetServices* target_services) {
560 DCHECK(target_services);
561 DCHECK(!g_target_services);
562 sandbox::ResultCode result = target_services->Init();
563 g_target_services = target_services;
564 return sandbox::SBOX_ALL_OK == result;
567 bool ShouldUseDirectWrite() {
568 // If the flag is currently on, and we're on Win7 or above, we enable
569 // DirectWrite. Skia does not require the additions to DirectWrite in QFE
570 // 2670838, but a simple 'better than XP' check is not enough.
571 if (base::win::GetVersion() < base::win::VERSION_WIN7)
572 return false;
574 base::win::OSInfo::VersionNumber os_version =
575 base::win::OSInfo::GetInstance()->version_number();
576 if ((os_version.major == 6) && (os_version.minor == 1)) {
577 // We can't use DirectWrite for pre-release versions of Windows 7.
578 if (os_version.build < 7600)
579 return false;
582 // If forced off, don't use it.
583 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
584 if (command_line.HasSwitch(switches::kDisableDirectWrite))
585 return false;
587 #if !defined(NACL_WIN64)
588 // Can't use GDI on HiDPI.
589 if (gfx::GetDPIScale() > 1.0f)
590 return true;
591 #endif
593 // Otherwise, check the field trial.
594 const std::string group_name =
595 base::FieldTrialList::FindFullName("DirectWrite");
596 return group_name != "Disabled";
599 base::ProcessHandle StartSandboxedProcess(
600 SandboxedProcessLauncherDelegate* delegate,
601 CommandLine* cmd_line) {
602 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
603 std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
605 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
607 // Propagate the --allow-no-job flag if present.
608 if (browser_command_line.HasSwitch(switches::kAllowNoSandboxJob) &&
609 !cmd_line->HasSwitch(switches::kAllowNoSandboxJob)) {
610 cmd_line->AppendSwitch(switches::kAllowNoSandboxJob);
613 ProcessDebugFlags(cmd_line);
615 // Prefetch hints on windows:
616 // Using a different prefetch profile per process type will allow Windows
617 // to create separate pretetch settings for browser, renderer etc.
618 cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", base::Hash(type_str)));
620 if ((delegate && !delegate->ShouldSandbox()) ||
621 browser_command_line.HasSwitch(switches::kNoSandbox) ||
622 cmd_line->HasSwitch(switches::kNoSandbox)) {
623 base::ProcessHandle process = 0;
624 base::LaunchProcess(*cmd_line, base::LaunchOptions(), &process);
625 g_broker_services->AddTargetPeer(process);
626 return process;
629 sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
631 sandbox::MitigationFlags mitigations = sandbox::MITIGATION_HEAP_TERMINATE |
632 sandbox::MITIGATION_BOTTOM_UP_ASLR |
633 sandbox::MITIGATION_DEP |
634 sandbox::MITIGATION_DEP_NO_ATL_THUNK |
635 sandbox::MITIGATION_SEHOP;
637 if (base::win::GetVersion() >= base::win::VERSION_WIN8 &&
638 type_str == switches::kRendererProcess &&
639 browser_command_line.HasSwitch(
640 switches::kEnableWin32kRendererLockDown)) {
641 if (policy->AddRule(sandbox::TargetPolicy::SUBSYS_WIN32K_LOCKDOWN,
642 sandbox::TargetPolicy::FAKE_USER_GDI_INIT,
643 NULL) != sandbox::SBOX_ALL_OK) {
644 return 0;
646 mitigations |= sandbox::MITIGATION_WIN32K_DISABLE;
649 if (policy->SetProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
650 return 0;
652 mitigations = sandbox::MITIGATION_STRICT_HANDLE_CHECKS |
653 sandbox::MITIGATION_DLL_SEARCH_ORDER;
655 if (policy->SetDelayedProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
656 return 0;
658 SetJobLevel(*cmd_line, sandbox::JOB_LOCKDOWN, 0, policy);
660 bool disable_default_policy = false;
661 base::FilePath exposed_dir;
662 if (delegate)
663 delegate->PreSandbox(&disable_default_policy, &exposed_dir);
665 if (!disable_default_policy && !AddPolicyForSandboxedProcess(policy))
666 return 0;
668 if (type_str == switches::kRendererProcess) {
669 if (ShouldUseDirectWrite()) {
670 AddDirectory(base::DIR_WINDOWS_FONTS,
671 NULL,
672 true,
673 sandbox::TargetPolicy::FILES_ALLOW_READONLY,
674 policy);
676 } else {
677 // Hack for Google Desktop crash. Trick GD into not injecting its DLL into
678 // this subprocess. See
679 // http://code.google.com/p/chromium/issues/detail?id=25580
680 cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
683 sandbox::ResultCode result;
684 if (!exposed_dir.empty()) {
685 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
686 sandbox::TargetPolicy::FILES_ALLOW_ANY,
687 exposed_dir.value().c_str());
688 if (result != sandbox::SBOX_ALL_OK)
689 return 0;
691 base::FilePath exposed_files = exposed_dir.AppendASCII("*");
692 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
693 sandbox::TargetPolicy::FILES_ALLOW_ANY,
694 exposed_files.value().c_str());
695 if (result != sandbox::SBOX_ALL_OK)
696 return 0;
699 if (!AddGenericPolicy(policy)) {
700 NOTREACHED();
701 return 0;
704 if (browser_command_line.HasSwitch(switches::kEnableLogging)) {
705 // If stdout/stderr point to a Windows console, these calls will
706 // have no effect.
707 policy->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE));
708 policy->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE));
711 if (delegate) {
712 bool success = true;
713 delegate->PreSpawnTarget(policy, &success);
714 if (!success)
715 return 0;
718 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
720 PROCESS_INFORMATION temp_process_info = {};
721 result = g_broker_services->SpawnTarget(
722 cmd_line->GetProgram().value().c_str(),
723 cmd_line->GetCommandLineString().c_str(),
724 policy, &temp_process_info);
725 policy->Release();
726 base::win::ScopedProcessInformation target(temp_process_info);
728 TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
730 if (sandbox::SBOX_ALL_OK != result) {
731 if (result == sandbox::SBOX_ERROR_GENERIC)
732 DPLOG(ERROR) << "Failed to launch process";
733 else
734 DLOG(ERROR) << "Failed to launch process. Error: " << result;
735 return 0;
738 if (delegate)
739 delegate->PostSpawnTarget(target.process_handle());
741 ResumeThread(target.thread_handle());
742 return target.TakeProcessHandle();
745 bool BrokerDuplicateHandle(HANDLE source_handle,
746 DWORD target_process_id,
747 HANDLE* target_handle,
748 DWORD desired_access,
749 DWORD options) {
750 // If our process is the target just duplicate the handle.
751 if (::GetCurrentProcessId() == target_process_id) {
752 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
753 ::GetCurrentProcess(), target_handle,
754 desired_access, FALSE, options);
758 // Try the broker next
759 if (g_target_services &&
760 g_target_services->DuplicateHandle(source_handle, target_process_id,
761 target_handle, desired_access,
762 options) == sandbox::SBOX_ALL_OK) {
763 return true;
766 // Finally, see if we already have access to the process.
767 base::win::ScopedHandle target_process;
768 target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE,
769 target_process_id));
770 if (target_process.IsValid()) {
771 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
772 target_process, target_handle,
773 desired_access, FALSE, options);
776 return false;
779 bool BrokerAddTargetPeer(HANDLE peer_process) {
780 return g_broker_services->AddTargetPeer(peer_process) == sandbox::SBOX_ALL_OK;
783 } // namespace content