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