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