Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / common / sandbox_win.cc
blobf6d9cf258729da3ece34b36fbde8386427e94da7
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 = {};
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 =
370 base::WriteInto(&coverage_dir, coverage_dir_size);
371 coverage_dir_size = ::GetEnvironmentVariable(
372 L"SANITIZER_COVERAGE_DIR", coverage_dir_str, coverage_dir_size);
373 CHECK(coverage_dir.size() == coverage_dir_size);
374 base::FilePath sancov_path =
375 base::FilePath(coverage_dir).Append(L"*.sancov");
376 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
377 sandbox::TargetPolicy::FILES_ALLOW_ANY,
378 sancov_path.value().c_str());
379 if (result != sandbox::SBOX_ALL_OK)
380 return false;
382 #endif
384 AddGenericDllEvictionPolicy(policy);
385 return true;
388 bool AddPolicyForSandboxedProcess(sandbox::TargetPolicy* policy) {
389 sandbox::ResultCode result;
390 // Renderers need to share events with plugins.
391 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
392 sandbox::TargetPolicy::HANDLES_DUP_ANY,
393 L"Event");
394 if (result != sandbox::SBOX_ALL_OK)
395 return false;
397 // Win8+ adds a device DeviceApi that we don't need.
398 if (base::win::GetVersion() > base::win::VERSION_WIN7)
399 result = policy->AddKernelObjectToClose(L"File", L"\\Device\\DeviceApi");
400 if (result != sandbox::SBOX_ALL_OK)
401 return false;
403 // Close the proxy settings on XP.
404 if (base::win::GetVersion() <= base::win::VERSION_SERVER_2003)
405 result = policy->AddKernelObjectToClose(L"Key",
406 L"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\" \
407 L"CurrentVersion\\Internet Settings");
408 if (result != sandbox::SBOX_ALL_OK)
409 return false;
412 sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED;
413 if (base::win::GetVersion() > base::win::VERSION_XP) {
414 // On 2003/Vista the initial token has to be restricted if the main
415 // token is restricted.
416 initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS;
419 policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN);
420 // Prevents the renderers from manipulating low-integrity processes.
421 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
422 policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
424 if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(true)) {
425 DLOG(WARNING) << "Failed to apply desktop security to the renderer";
428 return true;
431 // Updates the command line arguments with debug-related flags. If debug flags
432 // have been used with this process, they will be filtered and added to
433 // command_line as needed.
434 void ProcessDebugFlags(base::CommandLine* command_line) {
435 const base::CommandLine& current_cmd_line =
436 *base::CommandLine::ForCurrentProcess();
437 std::string type = command_line->GetSwitchValueASCII(switches::kProcessType);
438 if (current_cmd_line.HasSwitch(switches::kWaitForDebuggerChildren)) {
439 // Look to pass-on the kWaitForDebugger flag.
440 std::string value = current_cmd_line.GetSwitchValueASCII(
441 switches::kWaitForDebuggerChildren);
442 if (value.empty() || value == type) {
443 command_line->AppendSwitch(switches::kWaitForDebugger);
445 command_line->AppendSwitchASCII(switches::kWaitForDebuggerChildren, value);
449 // This code is test only, and attempts to catch unsafe uses of
450 // DuplicateHandle() that copy privileged handles into sandboxed processes.
451 #ifndef OFFICIAL_BUILD
452 base::win::IATPatchFunction g_iat_patch_duplicate_handle;
454 typedef BOOL (WINAPI *DuplicateHandleFunctionPtr)(HANDLE source_process_handle,
455 HANDLE source_handle,
456 HANDLE target_process_handle,
457 LPHANDLE target_handle,
458 DWORD desired_access,
459 BOOL inherit_handle,
460 DWORD options);
462 DuplicateHandleFunctionPtr g_iat_orig_duplicate_handle;
464 NtQueryObject g_QueryObject = NULL;
466 static const char* kDuplicateHandleWarning =
467 "You are attempting to duplicate a privileged handle into a sandboxed"
468 " process.\n Please use the sandbox::BrokerDuplicateHandle API or"
469 " contact security@chromium.org for assistance.";
471 void CheckDuplicateHandle(HANDLE handle) {
472 // Get the object type (32 characters is safe; current max is 14).
473 BYTE buffer[sizeof(OBJECT_TYPE_INFORMATION) + 32 * sizeof(wchar_t)];
474 OBJECT_TYPE_INFORMATION* type_info =
475 reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer);
476 ULONG size = sizeof(buffer) - sizeof(wchar_t);
477 NTSTATUS error;
478 error = g_QueryObject(handle, ObjectTypeInformation, type_info, size, &size);
479 CHECK(NT_SUCCESS(error));
480 type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
482 // Get the object basic information.
483 OBJECT_BASIC_INFORMATION basic_info;
484 size = sizeof(basic_info);
485 error = g_QueryObject(handle, ObjectBasicInformation, &basic_info, size,
486 &size);
487 CHECK(NT_SUCCESS(error));
489 CHECK(!(basic_info.GrantedAccess & WRITE_DAC)) <<
490 kDuplicateHandleWarning;
492 if (0 == _wcsicmp(type_info->Name.Buffer, L"Process")) {
493 const ACCESS_MASK kDangerousMask =
494 ~static_cast<DWORD>(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE);
495 CHECK(!(basic_info.GrantedAccess & kDangerousMask)) <<
496 kDuplicateHandleWarning;
500 BOOL WINAPI DuplicateHandlePatch(HANDLE source_process_handle,
501 HANDLE source_handle,
502 HANDLE target_process_handle,
503 LPHANDLE target_handle,
504 DWORD desired_access,
505 BOOL inherit_handle,
506 DWORD options) {
507 // Duplicate the handle so we get the final access mask.
508 if (!g_iat_orig_duplicate_handle(source_process_handle, source_handle,
509 target_process_handle, target_handle,
510 desired_access, inherit_handle, options))
511 return FALSE;
513 // We're not worried about broker handles or not crossing process boundaries.
514 if (source_process_handle == target_process_handle ||
515 target_process_handle == ::GetCurrentProcess())
516 return TRUE;
518 // Only sandboxed children are placed in jobs, so just check them.
519 BOOL is_in_job = FALSE;
520 if (!::IsProcessInJob(target_process_handle, NULL, &is_in_job)) {
521 // We need a handle with permission to check the job object.
522 if (ERROR_ACCESS_DENIED == ::GetLastError()) {
523 HANDLE temp_handle;
524 CHECK(g_iat_orig_duplicate_handle(::GetCurrentProcess(),
525 target_process_handle,
526 ::GetCurrentProcess(),
527 &temp_handle,
528 PROCESS_QUERY_INFORMATION,
529 FALSE, 0));
530 base::win::ScopedHandle process(temp_handle);
531 CHECK(::IsProcessInJob(process.Get(), NULL, &is_in_job));
535 if (is_in_job) {
536 // We never allow inheritable child handles.
537 CHECK(!inherit_handle) << kDuplicateHandleWarning;
539 // Duplicate the handle again, to get the final permissions.
540 HANDLE temp_handle;
541 CHECK(g_iat_orig_duplicate_handle(target_process_handle, *target_handle,
542 ::GetCurrentProcess(), &temp_handle,
543 0, FALSE, DUPLICATE_SAME_ACCESS));
544 base::win::ScopedHandle handle(temp_handle);
546 // Callers use CHECK macro to make sure we get the right stack.
547 CheckDuplicateHandle(handle.Get());
550 return TRUE;
552 #endif
554 } // namespace
556 void SetJobLevel(const base::CommandLine& cmd_line,
557 sandbox::JobLevel job_level,
558 uint32 ui_exceptions,
559 sandbox::TargetPolicy* policy) {
560 if (ShouldSetJobLevel(cmd_line)) {
561 #ifdef _WIN64
562 policy->SetJobMemoryLimit(4ULL * 1024 * 1024 * 1024);
563 #endif
564 policy->SetJobLevel(job_level, ui_exceptions);
565 } else {
566 policy->SetJobLevel(sandbox::JOB_NONE, 0);
570 // TODO(jschuh): Need get these restrictions applied to NaCl and Pepper.
571 // Just have to figure out what needs to be warmed up first.
572 void AddBaseHandleClosePolicy(sandbox::TargetPolicy* policy) {
573 // TODO(cpu): Add back the BaseNamedObjects policy.
574 base::string16 object_path = PrependWindowsSessionPath(
575 L"\\BaseNamedObjects\\windows_shell_global_counters");
576 policy->AddKernelObjectToClose(L"Section", object_path.data());
579 void AddAppContainerPolicy(sandbox::TargetPolicy* policy, const wchar_t* sid) {
580 if (base::win::GetVersion() == base::win::VERSION_WIN8 ||
581 base::win::GetVersion() == base::win::VERSION_WIN8_1) {
582 const base::CommandLine& command_line =
583 *base::CommandLine::ForCurrentProcess();
584 if (!command_line.HasSwitch(switches::kDisableAppContainer)) {
585 policy->SetLowBox(sid);
590 bool InitBrokerServices(sandbox::BrokerServices* broker_services) {
591 // TODO(abarth): DCHECK(CalledOnValidThread());
592 // See <http://b/1287166>.
593 DCHECK(broker_services);
594 DCHECK(!g_broker_services);
595 sandbox::ResultCode result = broker_services->Init();
596 g_broker_services = broker_services;
598 // In non-official builds warn about dangerous uses of DuplicateHandle.
599 #ifndef OFFICIAL_BUILD
600 BOOL is_in_job = FALSE;
601 CHECK(::IsProcessInJob(::GetCurrentProcess(), NULL, &is_in_job));
602 // In a Syzygy-profiled binary, instrumented for import profiling, this
603 // patch will end in infinite recursion on the attempted delegation to the
604 // original function.
605 if (!base::debug::IsBinaryInstrumented() &&
606 !is_in_job && !g_iat_patch_duplicate_handle.is_patched()) {
607 HMODULE module = NULL;
608 wchar_t module_name[MAX_PATH];
609 CHECK(::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
610 reinterpret_cast<LPCWSTR>(InitBrokerServices),
611 &module));
612 DWORD result = ::GetModuleFileNameW(module, module_name, MAX_PATH);
613 if (result && (result != MAX_PATH)) {
614 ResolveNTFunctionPtr("NtQueryObject", &g_QueryObject);
615 result = g_iat_patch_duplicate_handle.Patch(
616 module_name, "kernel32.dll", "DuplicateHandle",
617 DuplicateHandlePatch);
618 CHECK(result == 0);
619 g_iat_orig_duplicate_handle =
620 reinterpret_cast<DuplicateHandleFunctionPtr>(
621 g_iat_patch_duplicate_handle.original_function());
624 #endif
626 return sandbox::SBOX_ALL_OK == result;
629 bool InitTargetServices(sandbox::TargetServices* target_services) {
630 DCHECK(target_services);
631 DCHECK(!g_target_services);
632 sandbox::ResultCode result = target_services->Init();
633 g_target_services = target_services;
634 return sandbox::SBOX_ALL_OK == result;
637 base::Process StartSandboxedProcess(
638 SandboxedProcessLauncherDelegate* delegate,
639 base::CommandLine* cmd_line) {
640 const base::CommandLine& browser_command_line =
641 *base::CommandLine::ForCurrentProcess();
642 std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
644 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
646 // Propagate the --allow-no-job flag if present.
647 if (browser_command_line.HasSwitch(switches::kAllowNoSandboxJob) &&
648 !cmd_line->HasSwitch(switches::kAllowNoSandboxJob)) {
649 cmd_line->AppendSwitch(switches::kAllowNoSandboxJob);
652 ProcessDebugFlags(cmd_line);
654 // Prefetch hints on windows:
655 // Using a different prefetch profile per process type will allow Windows
656 // to create separate pretetch settings for browser, renderer etc.
657 cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", base::Hash(type_str)));
659 if ((delegate && !delegate->ShouldSandbox()) ||
660 browser_command_line.HasSwitch(switches::kNoSandbox) ||
661 cmd_line->HasSwitch(switches::kNoSandbox)) {
662 base::Process process =
663 base::LaunchProcess(*cmd_line, base::LaunchOptions());
664 // TODO(rvargas) crbug.com/417532: Don't share a raw handle.
665 g_broker_services->AddTargetPeer(process.Handle());
666 return process.Pass();
669 sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
671 sandbox::MitigationFlags mitigations = sandbox::MITIGATION_HEAP_TERMINATE |
672 sandbox::MITIGATION_BOTTOM_UP_ASLR |
673 sandbox::MITIGATION_DEP |
674 sandbox::MITIGATION_DEP_NO_ATL_THUNK |
675 sandbox::MITIGATION_SEHOP;
677 #if !defined(NACL_WIN64)
678 if (type_str == switches::kRendererProcess &&
679 IsWin32kRendererLockdownEnabled()) {
680 if (policy->AddRule(sandbox::TargetPolicy::SUBSYS_WIN32K_LOCKDOWN,
681 sandbox::TargetPolicy::FAKE_USER_GDI_INIT,
682 NULL) != sandbox::SBOX_ALL_OK) {
683 return base::Process();
685 mitigations |= sandbox::MITIGATION_WIN32K_DISABLE;
687 #endif
689 if (policy->SetProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
690 return base::Process();
692 mitigations = sandbox::MITIGATION_STRICT_HANDLE_CHECKS |
693 sandbox::MITIGATION_DLL_SEARCH_ORDER;
695 if (policy->SetDelayedProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
696 return base::Process();
698 SetJobLevel(*cmd_line, sandbox::JOB_LOCKDOWN, 0, policy);
700 bool disable_default_policy = false;
701 base::FilePath exposed_dir;
702 if (delegate)
703 delegate->PreSandbox(&disable_default_policy, &exposed_dir);
705 if (!disable_default_policy && !AddPolicyForSandboxedProcess(policy))
706 return base::Process();
708 if (type_str == switches::kRendererProcess) {
709 #if !defined(NACL_WIN64)
710 if (gfx::win::ShouldUseDirectWrite()) {
711 AddDirectory(base::DIR_WINDOWS_FONTS,
712 NULL,
713 true,
714 sandbox::TargetPolicy::FILES_ALLOW_READONLY,
715 policy);
717 // If DirectWrite is enabled for font rendering then open the font cache
718 // section which is created by the browser and pass the handle to the
719 // renderer process. This is needed because renderer processes on
720 // Windows 8+ may be running in an AppContainer sandbox and hence their
721 // kernel object namespace may be partitioned.
722 std::string name(content::kFontCacheSharedSectionName);
723 name.append(base::UintToString(base::GetCurrentProcId()));
725 base::SharedMemory direct_write_font_cache_section;
726 if (direct_write_font_cache_section.Open(name, true)) {
727 void* shared_handle =
728 policy->AddHandleToShare(direct_write_font_cache_section.handle());
729 cmd_line->AppendSwitchASCII(switches::kFontCacheSharedHandle,
730 base::UintToString(reinterpret_cast<unsigned int>(shared_handle)));
733 #endif
734 } else {
735 // Hack for Google Desktop crash. Trick GD into not injecting its DLL into
736 // this subprocess. See
737 // http://code.google.com/p/chromium/issues/detail?id=25580
738 cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
741 sandbox::ResultCode result;
742 if (!exposed_dir.empty()) {
743 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
744 sandbox::TargetPolicy::FILES_ALLOW_ANY,
745 exposed_dir.value().c_str());
746 if (result != sandbox::SBOX_ALL_OK)
747 return base::Process();
749 base::FilePath exposed_files = exposed_dir.AppendASCII("*");
750 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
751 sandbox::TargetPolicy::FILES_ALLOW_ANY,
752 exposed_files.value().c_str());
753 if (result != sandbox::SBOX_ALL_OK)
754 return base::Process();
757 if (!AddGenericPolicy(policy)) {
758 NOTREACHED();
759 return base::Process();
762 if (browser_command_line.HasSwitch(switches::kEnableLogging)) {
763 // If stdout/stderr point to a Windows console, these calls will
764 // have no effect.
765 policy->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE));
766 policy->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE));
769 if (delegate) {
770 bool success = true;
771 delegate->PreSpawnTarget(policy, &success);
772 if (!success)
773 return base::Process();
776 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
778 PROCESS_INFORMATION temp_process_info = {};
779 result = g_broker_services->SpawnTarget(
780 cmd_line->GetProgram().value().c_str(),
781 cmd_line->GetCommandLineString().c_str(),
782 policy, &temp_process_info);
783 DWORD last_error = ::GetLastError();
784 base::win::ScopedProcessInformation target(temp_process_info);
786 TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
788 if (sandbox::SBOX_ALL_OK != result) {
789 if (result == sandbox::SBOX_ERROR_GENERIC)
790 DPLOG(ERROR) << "Failed to launch process";
791 else if (result == sandbox::SBOX_ERROR_CREATE_PROCESS) {
792 // TODO(shrikant): Remove this special case handling after determining
793 // cause for lowbox/createprocess errors.
794 sandbox::PolicyBase* policy_base =
795 static_cast<sandbox::PolicyBase*>(policy);
796 UMA_HISTOGRAM_SPARSE_SLOWLY(policy_base->GetLowBoxSid() ?
797 "Process.Sandbox.Lowbox.Launch.Error" :
798 "Process.Sandbox.Launch.Error",
799 last_error);
800 } else
801 DLOG(ERROR) << "Failed to launch process. Error: " << result;
803 policy->Release();
804 return base::Process();
806 policy->Release();
808 if (delegate)
809 delegate->PostSpawnTarget(target.process_handle());
811 CHECK(ResumeThread(target.thread_handle()) != -1);
812 TRACE_EVENT_END_ETW("StartProcessWithAccess", 0, type_str);
813 return base::Process(target.TakeProcessHandle());
816 bool BrokerDuplicateHandle(HANDLE source_handle,
817 DWORD target_process_id,
818 HANDLE* target_handle,
819 DWORD desired_access,
820 DWORD options) {
821 // If our process is the target just duplicate the handle.
822 if (::GetCurrentProcessId() == target_process_id) {
823 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
824 ::GetCurrentProcess(), target_handle,
825 desired_access, FALSE, options);
829 // Try the broker next
830 if (g_target_services &&
831 g_target_services->DuplicateHandle(source_handle, target_process_id,
832 target_handle, desired_access,
833 options) == sandbox::SBOX_ALL_OK) {
834 return true;
837 // Finally, see if we already have access to the process.
838 base::win::ScopedHandle target_process;
839 target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE,
840 target_process_id));
841 if (target_process.IsValid()) {
842 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
843 target_process.Get(), target_handle,
844 desired_access, FALSE, options);
847 return false;
850 bool BrokerAddTargetPeer(HANDLE peer_process) {
851 return g_broker_services->AddTargetPeer(peer_process) == sandbox::SBOX_ALL_OK;
854 } // namespace content