ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / content / common / sandbox_win.cc
blob17893ffa6fd399677431f2a16d8019002308ad03
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/path_service.h"
15 #include "base/process/launch.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/trace_event/trace_event.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/content_switches_internal.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/direct_write.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 const wchar_t* const kTroublesomeDlls[] = {
47 L"adialhk.dll", // Kaspersky Internet Security.
48 L"acpiz.dll", // Unknown.
49 L"airfoilinject3.dll", // Airfoil.
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"esspd.dll", // Samsung Smart Security ESCORT.
62 L"googledesktopnetwork3.dll", // Google Desktop Search v5.
63 L"fwhook.dll", // PC Tools Firewall Plus.
64 L"hookprocesscreation.dll", // Blumentals Program protector.
65 L"hookterminateapis.dll", // Blumentals and Cyberprinter.
66 L"hookprintapis.dll", // Cyberprinter.
67 L"imon.dll", // NOD32 Antivirus.
68 L"icatcdll.dll", // Samsung Smart Security ESCORT.
69 L"icdcnl.dll", // Samsung Smart Security ESCORT.
70 L"ioloHL.dll", // Iolo (System Mechanic).
71 L"kloehk.dll", // Kaspersky Internet Security.
72 L"lawenforcer.dll", // Spyware-Browser AntiSpyware (Spybro).
73 L"libdivx.dll", // DivX.
74 L"lvprcinj01.dll", // Logitech QuickCam.
75 L"madchook.dll", // Madshi (generic hooking library).
76 L"mdnsnsp.dll", // Bonjour.
77 L"moonsysh.dll", // Moon Secure Antivirus.
78 L"mpk.dll", // KGB Spy.
79 L"npdivx32.dll", // DivX.
80 L"npggNT.des", // GameGuard 2008.
81 L"npggNT.dll", // GameGuard (older).
82 L"oawatch.dll", // Online Armor.
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"picrmi32.dll", // PicRec.
90 L"picrmi64.dll", // PicRec.
91 L"prntrack.dll", // Pharos Systems.
92 L"protector.dll", // Unknown (suspected malware).
93 L"radhslib.dll", // Radiant Naomi Internet Filter.
94 L"radprlib.dll", // Radiant Naomi Internet Filter.
95 L"rapportnikko.dll", // Trustware Rapport.
96 L"rlhook.dll", // Trustware Bufferzone.
97 L"rooksdol.dll", // Trustware Rapport.
98 L"rndlpepperbrowserrecordhelper.dll", // RealPlayer.
99 L"rpchromebrowserrecordhelper.dll", // RealPlayer.
100 L"r3hook.dll", // Kaspersky Internet Security.
101 L"sahook.dll", // McAfee Site Advisor.
102 L"sbrige.dll", // Unknown.
103 L"sc2hook.dll", // Supercopier 2.
104 L"sdhook32.dll", // Spybot - Search & Destroy Live Protection.
105 L"sguard.dll", // Iolo (System Guard).
106 L"smum32.dll", // Spyware Doctor version 6.
107 L"smumhook.dll", // Spyware Doctor version 5.
108 L"ssldivx.dll", // DivX.
109 L"syncor11.dll", // SynthCore Midi interface.
110 L"systools.dll", // Panda Antivirus.
111 L"tfwah.dll", // Threatfire (PC tools).
112 L"wblind.dll", // Stardock Object desktop.
113 L"wbhelp.dll", // Stardock Object desktop.
114 L"winstylerthemehelper.dll" // Tuneup utilities 2006.
117 // Adds the policy rules for the path and path\ with the semantic |access|.
118 // If |children| is set to true, we need to add the wildcard rules to also
119 // apply the rule to the subfiles and subfolders.
120 bool AddDirectory(int path, const wchar_t* sub_dir, bool children,
121 sandbox::TargetPolicy::Semantics access,
122 sandbox::TargetPolicy* policy) {
123 base::FilePath directory;
124 if (!PathService::Get(path, &directory))
125 return false;
127 if (sub_dir)
128 directory = base::MakeAbsoluteFilePath(directory.Append(sub_dir));
130 sandbox::ResultCode result;
131 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
132 directory.value().c_str());
133 if (result != sandbox::SBOX_ALL_OK)
134 return false;
136 std::wstring directory_str = directory.value() + L"\\";
137 if (children)
138 directory_str += L"*";
139 // Otherwise, add the version of the path that ends with a separator.
141 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
142 directory_str.c_str());
143 if (result != sandbox::SBOX_ALL_OK)
144 return false;
146 return true;
149 // Adds the policy rules for the path and path\* with the semantic |access|.
150 // We need to add the wildcard rules to also apply the rule to the subkeys.
151 bool AddKeyAndSubkeys(std::wstring key,
152 sandbox::TargetPolicy::Semantics access,
153 sandbox::TargetPolicy* policy) {
154 sandbox::ResultCode result;
155 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
156 key.c_str());
157 if (result != sandbox::SBOX_ALL_OK)
158 return false;
160 key += L"\\*";
161 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
162 key.c_str());
163 if (result != sandbox::SBOX_ALL_OK)
164 return false;
166 return true;
169 // Compares the loaded |module| file name matches |module_name|.
170 bool IsExpandedModuleName(HMODULE module, const wchar_t* module_name) {
171 wchar_t path[MAX_PATH];
172 DWORD sz = ::GetModuleFileNameW(module, path, arraysize(path));
173 if ((sz == arraysize(path)) || (sz == 0)) {
174 // XP does not set the last error properly, so we bail out anyway.
175 return false;
177 if (!::GetLongPathName(path, path, arraysize(path)))
178 return false;
179 base::FilePath fname(path);
180 return (fname.BaseName().value() == module_name);
183 // Adds a single dll by |module_name| into the |policy| blacklist.
184 // If |check_in_browser| is true we only add an unload policy only if the dll
185 // is also loaded in this process.
186 void BlacklistAddOneDll(const wchar_t* module_name,
187 bool check_in_browser,
188 sandbox::TargetPolicy* policy) {
189 HMODULE module = check_in_browser ? ::GetModuleHandleW(module_name) : NULL;
190 if (!module) {
191 // The module could have been loaded with a 8.3 short name. We check
192 // the three most common cases: 'thelongname.dll' becomes
193 // 'thelon~1.dll', 'thelon~2.dll' and 'thelon~3.dll'.
194 std::wstring name(module_name);
195 size_t period = name.rfind(L'.');
196 DCHECK_NE(std::string::npos, period);
197 DCHECK_LE(3U, (name.size() - period));
198 if (period <= 8)
199 return;
200 for (wchar_t ix = '1'; ix <= '3'; ++ix) {
201 const wchar_t suffix[] = {'~', ix, 0};
202 std::wstring alt_name = name.substr(0, 6) + suffix;
203 alt_name += name.substr(period, name.size());
204 if (check_in_browser) {
205 module = ::GetModuleHandleW(alt_name.c_str());
206 if (!module)
207 return;
208 // We found it, but because it only has 6 significant letters, we
209 // want to make sure it is the right one.
210 if (!IsExpandedModuleName(module, module_name))
211 return;
213 // Found a match. We add both forms to the policy.
214 policy->AddDllToUnload(alt_name.c_str());
217 policy->AddDllToUnload(module_name);
218 DVLOG(1) << "dll to unload found: " << module_name;
219 return;
222 // Adds policy rules for unloaded the known dlls that cause chrome to crash.
223 // Eviction of injected DLLs is done by the sandbox so that the injected module
224 // does not get a chance to execute any code.
225 void AddGenericDllEvictionPolicy(sandbox::TargetPolicy* policy) {
226 for (int ix = 0; ix != arraysize(kTroublesomeDlls); ++ix)
227 BlacklistAddOneDll(kTroublesomeDlls[ix], true, policy);
230 // Returns the object path prepended with the current logon session.
231 base::string16 PrependWindowsSessionPath(const base::char16* object) {
232 // Cache this because it can't change after process creation.
233 static uintptr_t s_session_id = 0;
234 if (s_session_id == 0) {
235 HANDLE token;
236 DWORD session_id_length;
237 DWORD session_id = 0;
239 CHECK(::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token));
240 CHECK(::GetTokenInformation(token, TokenSessionId, &session_id,
241 sizeof(session_id), &session_id_length));
242 CloseHandle(token);
243 if (session_id)
244 s_session_id = session_id;
247 return base::StringPrintf(L"\\Sessions\\%d%ls", s_session_id, object);
250 // Checks if the sandbox should be let to run without a job object assigned.
251 bool ShouldSetJobLevel(const base::CommandLine& cmd_line) {
252 if (!cmd_line.HasSwitch(switches::kAllowNoSandboxJob))
253 return true;
255 // Windows 8 allows nested jobs so we don't need to check if we are in other
256 // job.
257 if (base::win::GetVersion() >= base::win::VERSION_WIN8)
258 return true;
260 BOOL in_job = true;
261 // Either there is no job yet associated so we must add our job,
262 if (!::IsProcessInJob(::GetCurrentProcess(), NULL, &in_job))
263 NOTREACHED() << "IsProcessInJob failed. " << GetLastError();
264 if (!in_job)
265 return true;
267 // ...or there is a job but the JOB_OBJECT_LIMIT_BREAKAWAY_OK limit is set.
268 JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info = {0};
269 if (!::QueryInformationJobObject(NULL,
270 JobObjectExtendedLimitInformation, &job_info,
271 sizeof(job_info), NULL)) {
272 NOTREACHED() << "QueryInformationJobObject failed. " << GetLastError();
273 return true;
275 if (job_info.BasicLimitInformation.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK)
276 return true;
278 return false;
281 // Adds the generic policy rules to a sandbox TargetPolicy.
282 bool AddGenericPolicy(sandbox::TargetPolicy* policy) {
283 sandbox::ResultCode result;
285 // Renderers need to copy sections for plugin DIBs and GPU.
286 // GPU needs to copy sections to renderers.
287 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
288 sandbox::TargetPolicy::HANDLES_DUP_ANY,
289 L"Section");
290 if (result != sandbox::SBOX_ALL_OK)
291 return false;
293 // Add the policy for the client side of a pipe. It is just a file
294 // in the \pipe\ namespace. We restrict it to pipes that start with
295 // "chrome." so the sandboxed process cannot connect to system services.
296 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
297 sandbox::TargetPolicy::FILES_ALLOW_ANY,
298 L"\\??\\pipe\\chrome.*");
299 if (result != sandbox::SBOX_ALL_OK)
300 return false;
302 // Add the policy for the server side of nacl pipe. It is just a file
303 // in the \pipe\ namespace. We restrict it to pipes that start with
304 // "chrome.nacl" so the sandboxed process cannot connect to
305 // system services.
306 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
307 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
308 L"\\\\.\\pipe\\chrome.nacl.*");
309 if (result != sandbox::SBOX_ALL_OK)
310 return false;
312 // Allow the server side of sync sockets, which are pipes that have
313 // the "chrome.sync" namespace and a randomly generated suffix.
314 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
315 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
316 L"\\\\.\\pipe\\chrome.sync.*");
317 if (result != sandbox::SBOX_ALL_OK)
318 return false;
320 // Add the policy for debug message only in debug
321 #ifndef NDEBUG
322 base::FilePath app_dir;
323 if (!PathService::Get(base::DIR_MODULE, &app_dir))
324 return false;
326 wchar_t long_path_buf[MAX_PATH];
327 DWORD long_path_return_value = GetLongPathName(app_dir.value().c_str(),
328 long_path_buf,
329 MAX_PATH);
330 if (long_path_return_value == 0 || long_path_return_value >= MAX_PATH)
331 return false;
333 base::FilePath debug_message(long_path_buf);
334 debug_message = debug_message.AppendASCII("debug_message.exe");
335 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_PROCESS,
336 sandbox::TargetPolicy::PROCESS_MIN_EXEC,
337 debug_message.value().c_str());
338 if (result != sandbox::SBOX_ALL_OK)
339 return false;
340 #endif // NDEBUG
342 // Add the policy for read-only PDB file access for AddressSanitizer.
343 #if defined(ADDRESS_SANITIZER)
344 base::FilePath exe;
345 if (!PathService::Get(base::FILE_EXE, &exe))
346 return false;
347 base::FilePath pdb_path = exe.DirName().Append(L"*.pdb");
348 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
349 sandbox::TargetPolicy::FILES_ALLOW_READONLY,
350 pdb_path.value().c_str());
351 if (result != sandbox::SBOX_ALL_OK)
352 return false;
353 #endif
355 AddGenericDllEvictionPolicy(policy);
356 return true;
359 bool AddPolicyForSandboxedProcess(sandbox::TargetPolicy* policy) {
360 sandbox::ResultCode result;
361 // Renderers need to share events with plugins.
362 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
363 sandbox::TargetPolicy::HANDLES_DUP_ANY,
364 L"Event");
365 if (result != sandbox::SBOX_ALL_OK)
366 return false;
368 // Win8+ adds a device DeviceApi that we don't need.
369 if (base::win::GetVersion() > base::win::VERSION_WIN7)
370 result = policy->AddKernelObjectToClose(L"File", L"\\Device\\DeviceApi");
371 if (result != sandbox::SBOX_ALL_OK)
372 return false;
374 // Close the proxy settings on XP.
375 if (base::win::GetVersion() <= base::win::VERSION_SERVER_2003)
376 result = policy->AddKernelObjectToClose(L"Key",
377 L"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\" \
378 L"CurrentVersion\\Internet Settings");
379 if (result != sandbox::SBOX_ALL_OK)
380 return false;
383 sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED;
384 if (base::win::GetVersion() > base::win::VERSION_XP) {
385 // On 2003/Vista the initial token has to be restricted if the main
386 // token is restricted.
387 initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS;
390 policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN);
391 // Prevents the renderers from manipulating low-integrity processes.
392 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
393 policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
395 if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(true)) {
396 DLOG(WARNING) << "Failed to apply desktop security to the renderer";
399 return true;
402 // Updates the command line arguments with debug-related flags. If debug flags
403 // have been used with this process, they will be filtered and added to
404 // command_line as needed.
405 void ProcessDebugFlags(base::CommandLine* command_line) {
406 const base::CommandLine& current_cmd_line =
407 *base::CommandLine::ForCurrentProcess();
408 std::string type = command_line->GetSwitchValueASCII(switches::kProcessType);
409 if (current_cmd_line.HasSwitch(switches::kWaitForDebuggerChildren)) {
410 // Look to pass-on the kWaitForDebugger flag.
411 std::string value = current_cmd_line.GetSwitchValueASCII(
412 switches::kWaitForDebuggerChildren);
413 if (value.empty() || value == type) {
414 command_line->AppendSwitch(switches::kWaitForDebugger);
416 command_line->AppendSwitchASCII(switches::kWaitForDebuggerChildren, value);
420 // This code is test only, and attempts to catch unsafe uses of
421 // DuplicateHandle() that copy privileged handles into sandboxed processes.
422 #ifndef OFFICIAL_BUILD
423 base::win::IATPatchFunction g_iat_patch_duplicate_handle;
425 typedef BOOL (WINAPI *DuplicateHandleFunctionPtr)(HANDLE source_process_handle,
426 HANDLE source_handle,
427 HANDLE target_process_handle,
428 LPHANDLE target_handle,
429 DWORD desired_access,
430 BOOL inherit_handle,
431 DWORD options);
433 DuplicateHandleFunctionPtr g_iat_orig_duplicate_handle;
435 NtQueryObject g_QueryObject = NULL;
437 static const char* kDuplicateHandleWarning =
438 "You are attempting to duplicate a privileged handle into a sandboxed"
439 " process.\n Please use the sandbox::BrokerDuplicateHandle API or"
440 " contact security@chromium.org for assistance.";
442 void CheckDuplicateHandle(HANDLE handle) {
443 // Get the object type (32 characters is safe; current max is 14).
444 BYTE buffer[sizeof(OBJECT_TYPE_INFORMATION) + 32 * sizeof(wchar_t)];
445 OBJECT_TYPE_INFORMATION* type_info =
446 reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer);
447 ULONG size = sizeof(buffer) - sizeof(wchar_t);
448 NTSTATUS error;
449 error = g_QueryObject(handle, ObjectTypeInformation, type_info, size, &size);
450 CHECK(NT_SUCCESS(error));
451 type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
453 // Get the object basic information.
454 OBJECT_BASIC_INFORMATION basic_info;
455 size = sizeof(basic_info);
456 error = g_QueryObject(handle, ObjectBasicInformation, &basic_info, size,
457 &size);
458 CHECK(NT_SUCCESS(error));
460 CHECK(!(basic_info.GrantedAccess & WRITE_DAC)) <<
461 kDuplicateHandleWarning;
463 if (0 == _wcsicmp(type_info->Name.Buffer, L"Process")) {
464 const ACCESS_MASK kDangerousMask =
465 ~static_cast<DWORD>(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE);
466 CHECK(!(basic_info.GrantedAccess & kDangerousMask)) <<
467 kDuplicateHandleWarning;
471 BOOL WINAPI DuplicateHandlePatch(HANDLE source_process_handle,
472 HANDLE source_handle,
473 HANDLE target_process_handle,
474 LPHANDLE target_handle,
475 DWORD desired_access,
476 BOOL inherit_handle,
477 DWORD options) {
478 // Duplicate the handle so we get the final access mask.
479 if (!g_iat_orig_duplicate_handle(source_process_handle, source_handle,
480 target_process_handle, target_handle,
481 desired_access, inherit_handle, options))
482 return FALSE;
484 // We're not worried about broker handles or not crossing process boundaries.
485 if (source_process_handle == target_process_handle ||
486 target_process_handle == ::GetCurrentProcess())
487 return TRUE;
489 // Only sandboxed children are placed in jobs, so just check them.
490 BOOL is_in_job = FALSE;
491 if (!::IsProcessInJob(target_process_handle, NULL, &is_in_job)) {
492 // We need a handle with permission to check the job object.
493 if (ERROR_ACCESS_DENIED == ::GetLastError()) {
494 HANDLE temp_handle;
495 CHECK(g_iat_orig_duplicate_handle(::GetCurrentProcess(),
496 target_process_handle,
497 ::GetCurrentProcess(),
498 &temp_handle,
499 PROCESS_QUERY_INFORMATION,
500 FALSE, 0));
501 base::win::ScopedHandle process(temp_handle);
502 CHECK(::IsProcessInJob(process.Get(), NULL, &is_in_job));
506 if (is_in_job) {
507 // We never allow inheritable child handles.
508 CHECK(!inherit_handle) << kDuplicateHandleWarning;
510 // Duplicate the handle again, to get the final permissions.
511 HANDLE temp_handle;
512 CHECK(g_iat_orig_duplicate_handle(target_process_handle, *target_handle,
513 ::GetCurrentProcess(), &temp_handle,
514 0, FALSE, DUPLICATE_SAME_ACCESS));
515 base::win::ScopedHandle handle(temp_handle);
517 // Callers use CHECK macro to make sure we get the right stack.
518 CheckDuplicateHandle(handle.Get());
521 return TRUE;
523 #endif
525 } // namespace
527 void SetJobLevel(const base::CommandLine& cmd_line,
528 sandbox::JobLevel job_level,
529 uint32 ui_exceptions,
530 sandbox::TargetPolicy* policy) {
531 if (ShouldSetJobLevel(cmd_line)) {
532 #ifdef _WIN64
533 policy->SetJobMemoryLimit(4ULL * 1024 * 1024 * 1024);
534 #endif
535 policy->SetJobLevel(job_level, ui_exceptions);
536 } else {
537 policy->SetJobLevel(sandbox::JOB_NONE, 0);
541 // TODO(jschuh): Need get these restrictions applied to NaCl and Pepper.
542 // Just have to figure out what needs to be warmed up first.
543 void AddBaseHandleClosePolicy(sandbox::TargetPolicy* policy) {
544 // TODO(cpu): Add back the BaseNamedObjects policy.
545 base::string16 object_path = PrependWindowsSessionPath(
546 L"\\BaseNamedObjects\\windows_shell_global_counters");
547 policy->AddKernelObjectToClose(L"Section", object_path.data());
550 bool InitBrokerServices(sandbox::BrokerServices* broker_services) {
551 // TODO(abarth): DCHECK(CalledOnValidThread());
552 // See <http://b/1287166>.
553 DCHECK(broker_services);
554 DCHECK(!g_broker_services);
555 sandbox::ResultCode result = broker_services->Init();
556 g_broker_services = broker_services;
558 // In non-official builds warn about dangerous uses of DuplicateHandle.
559 #ifndef OFFICIAL_BUILD
560 BOOL is_in_job = FALSE;
561 CHECK(::IsProcessInJob(::GetCurrentProcess(), NULL, &is_in_job));
562 // In a Syzygy-profiled binary, instrumented for import profiling, this
563 // patch will end in infinite recursion on the attempted delegation to the
564 // original function.
565 if (!base::debug::IsBinaryInstrumented() &&
566 !is_in_job && !g_iat_patch_duplicate_handle.is_patched()) {
567 HMODULE module = NULL;
568 wchar_t module_name[MAX_PATH];
569 CHECK(::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
570 reinterpret_cast<LPCWSTR>(InitBrokerServices),
571 &module));
572 DWORD result = ::GetModuleFileNameW(module, module_name, MAX_PATH);
573 if (result && (result != MAX_PATH)) {
574 ResolveNTFunctionPtr("NtQueryObject", &g_QueryObject);
575 result = g_iat_patch_duplicate_handle.Patch(
576 module_name, "kernel32.dll", "DuplicateHandle",
577 DuplicateHandlePatch);
578 CHECK(result == 0);
579 g_iat_orig_duplicate_handle =
580 reinterpret_cast<DuplicateHandleFunctionPtr>(
581 g_iat_patch_duplicate_handle.original_function());
584 #endif
586 return sandbox::SBOX_ALL_OK == result;
589 bool InitTargetServices(sandbox::TargetServices* target_services) {
590 DCHECK(target_services);
591 DCHECK(!g_target_services);
592 sandbox::ResultCode result = target_services->Init();
593 g_target_services = target_services;
594 return sandbox::SBOX_ALL_OK == result;
597 base::Process StartSandboxedProcess(
598 SandboxedProcessLauncherDelegate* delegate,
599 base::CommandLine* cmd_line) {
600 const base::CommandLine& browser_command_line =
601 *base::CommandLine::ForCurrentProcess();
602 std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
604 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
606 // Propagate the --allow-no-job flag if present.
607 if (browser_command_line.HasSwitch(switches::kAllowNoSandboxJob) &&
608 !cmd_line->HasSwitch(switches::kAllowNoSandboxJob)) {
609 cmd_line->AppendSwitch(switches::kAllowNoSandboxJob);
612 ProcessDebugFlags(cmd_line);
614 // Prefetch hints on windows:
615 // Using a different prefetch profile per process type will allow Windows
616 // to create separate pretetch settings for browser, renderer etc.
617 cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", base::Hash(type_str)));
619 if ((delegate && !delegate->ShouldSandbox()) ||
620 browser_command_line.HasSwitch(switches::kNoSandbox) ||
621 cmd_line->HasSwitch(switches::kNoSandbox)) {
622 base::Process process =
623 base::LaunchProcess(*cmd_line, base::LaunchOptions());
624 // TODO(rvargas) crbug.com/417532: Don't share a raw handle.
625 g_broker_services->AddTargetPeer(process.Handle());
626 return process.Pass();
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 !defined(NACL_WIN64)
638 if (type_str == switches::kRendererProcess &&
639 IsWin32kRendererLockdownEnabled()) {
640 if (policy->AddRule(sandbox::TargetPolicy::SUBSYS_WIN32K_LOCKDOWN,
641 sandbox::TargetPolicy::FAKE_USER_GDI_INIT,
642 NULL) != sandbox::SBOX_ALL_OK) {
643 return base::Process();
645 mitigations |= sandbox::MITIGATION_WIN32K_DISABLE;
647 #endif
649 if (policy->SetProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
650 return base::Process();
652 mitigations = sandbox::MITIGATION_STRICT_HANDLE_CHECKS |
653 sandbox::MITIGATION_DLL_SEARCH_ORDER;
655 if (policy->SetDelayedProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
656 return base::Process();
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 base::Process();
668 if (type_str == switches::kRendererProcess) {
669 #if !defined(NACL_WIN64)
670 if (gfx::win::ShouldUseDirectWrite()) {
671 AddDirectory(base::DIR_WINDOWS_FONTS,
672 NULL,
673 true,
674 sandbox::TargetPolicy::FILES_ALLOW_READONLY,
675 policy);
677 #endif
678 } else {
679 // Hack for Google Desktop crash. Trick GD into not injecting its DLL into
680 // this subprocess. See
681 // http://code.google.com/p/chromium/issues/detail?id=25580
682 cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
685 sandbox::ResultCode result;
686 if (!exposed_dir.empty()) {
687 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
688 sandbox::TargetPolicy::FILES_ALLOW_ANY,
689 exposed_dir.value().c_str());
690 if (result != sandbox::SBOX_ALL_OK)
691 return base::Process();
693 base::FilePath exposed_files = exposed_dir.AppendASCII("*");
694 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
695 sandbox::TargetPolicy::FILES_ALLOW_ANY,
696 exposed_files.value().c_str());
697 if (result != sandbox::SBOX_ALL_OK)
698 return base::Process();
701 if (!AddGenericPolicy(policy)) {
702 NOTREACHED();
703 return base::Process();
706 if (browser_command_line.HasSwitch(switches::kEnableLogging)) {
707 // If stdout/stderr point to a Windows console, these calls will
708 // have no effect.
709 policy->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE));
710 policy->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE));
713 if (delegate) {
714 bool success = true;
715 delegate->PreSpawnTarget(policy, &success);
716 if (!success)
717 return base::Process();
720 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
722 PROCESS_INFORMATION temp_process_info = {};
723 result = g_broker_services->SpawnTarget(
724 cmd_line->GetProgram().value().c_str(),
725 cmd_line->GetCommandLineString().c_str(),
726 policy, &temp_process_info);
727 policy->Release();
728 base::win::ScopedProcessInformation target(temp_process_info);
730 TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
732 if (sandbox::SBOX_ALL_OK != result) {
733 if (result == sandbox::SBOX_ERROR_GENERIC)
734 DPLOG(ERROR) << "Failed to launch process";
735 else
736 DLOG(ERROR) << "Failed to launch process. Error: " << result;
737 return base::Process();
740 if (delegate)
741 delegate->PostSpawnTarget(target.process_handle());
743 CHECK(ResumeThread(target.thread_handle()) != -1);
744 TRACE_EVENT_END_ETW("StartProcessWithAccess", 0, type_str);
745 return base::Process(target.TakeProcessHandle());
748 bool BrokerDuplicateHandle(HANDLE source_handle,
749 DWORD target_process_id,
750 HANDLE* target_handle,
751 DWORD desired_access,
752 DWORD options) {
753 // If our process is the target just duplicate the handle.
754 if (::GetCurrentProcessId() == target_process_id) {
755 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
756 ::GetCurrentProcess(), target_handle,
757 desired_access, FALSE, options);
761 // Try the broker next
762 if (g_target_services &&
763 g_target_services->DuplicateHandle(source_handle, target_process_id,
764 target_handle, desired_access,
765 options) == sandbox::SBOX_ALL_OK) {
766 return true;
769 // Finally, see if we already have access to the process.
770 base::win::ScopedHandle target_process;
771 target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE,
772 target_process_id));
773 if (target_process.IsValid()) {
774 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
775 target_process.Get(), target_handle,
776 desired_access, FALSE, options);
779 return false;
782 bool BrokerAddTargetPeer(HANDLE peer_process) {
783 return g_broker_services->AddTargetPeer(peer_process) == sandbox::SBOX_ALL_OK;
786 } // namespace content