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