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