Remove const WebMediaPlayer::didLoadingProgress() implementations.
[chromium-blink-merge.git] / content / common / sandbox_win.cc
blob7c3048aadbb477209d5a63b44b2f845bc33378ae
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/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"
32 static sandbox::BrokerServices* g_broker_services = NULL;
33 static sandbox::TargetServices* g_target_services = NULL;
35 namespace content {
36 namespace {
38 // The DLLs listed here are known (or under strong suspicion) of causing crashes
39 // when they are loaded in the renderer. Note: at runtime we generate short
40 // versions of the dll name only if the dll has an extension.
41 // For more information about how this list is generated, and how to get off
42 // of it, see:
43 // https://sites.google.com/a/chromium.org/dev/Home/third-party-developers
44 const wchar_t* const kTroublesomeDlls[] = {
45 L"adialhk.dll", // Kaspersky Internet Security.
46 L"acpiz.dll", // Unknown.
47 L"akinsofthook32.dll", // Akinsoft Software Engineering.
48 L"avgrsstx.dll", // AVG 8.
49 L"babylonchromepi.dll", // Babylon translator.
50 L"btkeyind.dll", // Widcomm Bluetooth.
51 L"cmcsyshk.dll", // CMC Internet Security.
52 L"cmsetac.dll", // Unknown (suspected malware).
53 L"cooliris.dll", // CoolIris.
54 L"dockshellhook.dll", // Stardock Objectdock.
55 L"easyhook32.dll", // GDIPP and others.
56 L"googledesktopnetwork3.dll", // Google Desktop Search v5.
57 L"fwhook.dll", // PC Tools Firewall Plus.
58 L"hookprocesscreation.dll", // Blumentals Program protector.
59 L"hookterminateapis.dll", // Blumentals and Cyberprinter.
60 L"hookprintapis.dll", // Cyberprinter.
61 L"imon.dll", // NOD32 Antivirus.
62 L"ioloHL.dll", // Iolo (System Mechanic).
63 L"kloehk.dll", // Kaspersky Internet Security.
64 L"lawenforcer.dll", // Spyware-Browser AntiSpyware (Spybro).
65 L"libdivx.dll", // DivX.
66 L"lvprcinj01.dll", // Logitech QuickCam.
67 L"madchook.dll", // Madshi (generic hooking library).
68 L"mdnsnsp.dll", // Bonjour.
69 L"moonsysh.dll", // Moon Secure Antivirus.
70 L"mpk.dll", // KGB Spy.
71 L"npdivx32.dll", // DivX.
72 L"npggNT.des", // GameGuard 2008.
73 L"npggNT.dll", // GameGuard (older).
74 L"oawatch.dll", // Online Armor.
75 L"pavhook.dll", // Panda Internet Security.
76 L"pavlsphook.dll", // Panda Antivirus.
77 L"pavshook.dll", // Panda Antivirus.
78 L"pavshookwow.dll", // Panda Antivirus.
79 L"pctavhook.dll", // PC Tools Antivirus.
80 L"pctgmhk.dll", // PC Tools Spyware Doctor.
81 L"prntrack.dll", // Pharos Systems.
82 L"protector.dll", // Unknown (suspected malware).
83 L"radhslib.dll", // Radiant Naomi Internet Filter.
84 L"radprlib.dll", // Radiant Naomi Internet Filter.
85 L"rapportnikko.dll", // Trustware Rapport.
86 L"rlhook.dll", // Trustware Bufferzone.
87 L"rooksdol.dll", // Trustware Rapport.
88 L"rndlpepperbrowserrecordhelper.dll", // RealPlayer.
89 L"rpchromebrowserrecordhelper.dll", // RealPlayer.
90 L"r3hook.dll", // Kaspersky Internet Security.
91 L"sahook.dll", // McAfee Site Advisor.
92 L"sbrige.dll", // Unknown.
93 L"sc2hook.dll", // Supercopier 2.
94 L"sdhook32.dll", // Spybot - Search & Destroy Live Protection.
95 L"sguard.dll", // Iolo (System Guard).
96 L"smum32.dll", // Spyware Doctor version 6.
97 L"smumhook.dll", // Spyware Doctor version 5.
98 L"ssldivx.dll", // DivX.
99 L"syncor11.dll", // SynthCore Midi interface.
100 L"systools.dll", // Panda Antivirus.
101 L"tfwah.dll", // Threatfire (PC tools).
102 L"wblind.dll", // Stardock Object desktop.
103 L"wbhelp.dll", // Stardock Object desktop.
104 L"winstylerthemehelper.dll" // Tuneup utilities 2006.
107 // Adds the policy rules for the path and path\ with the semantic |access|.
108 // If |children| is set to true, we need to add the wildcard rules to also
109 // apply the rule to the subfiles and subfolders.
110 bool AddDirectory(int path, const wchar_t* sub_dir, bool children,
111 sandbox::TargetPolicy::Semantics access,
112 sandbox::TargetPolicy* policy) {
113 base::FilePath directory;
114 if (!PathService::Get(path, &directory))
115 return false;
117 if (sub_dir)
118 directory = base::MakeAbsoluteFilePath(directory.Append(sub_dir));
120 sandbox::ResultCode result;
121 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
122 directory.value().c_str());
123 if (result != sandbox::SBOX_ALL_OK)
124 return false;
126 std::wstring directory_str = directory.value() + L"\\";
127 if (children)
128 directory_str += L"*";
129 // Otherwise, add the version of the path that ends with a separator.
131 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
132 directory_str.c_str());
133 if (result != sandbox::SBOX_ALL_OK)
134 return false;
136 return true;
139 // Adds the policy rules for the path and path\* with the semantic |access|.
140 // We need to add the wildcard rules to also apply the rule to the subkeys.
141 bool AddKeyAndSubkeys(std::wstring key,
142 sandbox::TargetPolicy::Semantics access,
143 sandbox::TargetPolicy* policy) {
144 sandbox::ResultCode result;
145 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
146 key.c_str());
147 if (result != sandbox::SBOX_ALL_OK)
148 return false;
150 key += L"\\*";
151 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
152 key.c_str());
153 if (result != sandbox::SBOX_ALL_OK)
154 return false;
156 return true;
159 // Compares the loaded |module| file name matches |module_name|.
160 bool IsExpandedModuleName(HMODULE module, const wchar_t* module_name) {
161 wchar_t path[MAX_PATH];
162 DWORD sz = ::GetModuleFileNameW(module, path, arraysize(path));
163 if ((sz == arraysize(path)) || (sz == 0)) {
164 // XP does not set the last error properly, so we bail out anyway.
165 return false;
167 if (!::GetLongPathName(path, path, arraysize(path)))
168 return false;
169 base::FilePath fname(path);
170 return (fname.BaseName().value() == module_name);
173 // Adds a single dll by |module_name| into the |policy| blacklist.
174 // If |check_in_browser| is true we only add an unload policy only if the dll
175 // is also loaded in this process.
176 void BlacklistAddOneDll(const wchar_t* module_name,
177 bool check_in_browser,
178 sandbox::TargetPolicy* policy) {
179 HMODULE module = check_in_browser ? ::GetModuleHandleW(module_name) : NULL;
180 if (!module) {
181 // The module could have been loaded with a 8.3 short name. We check
182 // the three most common cases: 'thelongname.dll' becomes
183 // 'thelon~1.dll', 'thelon~2.dll' and 'thelon~3.dll'.
184 std::wstring name(module_name);
185 size_t period = name.rfind(L'.');
186 DCHECK_NE(std::string::npos, period);
187 DCHECK_LE(3U, (name.size() - period));
188 if (period <= 8)
189 return;
190 for (int ix = 0; ix < 3; ++ix) {
191 const wchar_t suffix[] = {'~', ('1' + ix), 0};
192 std::wstring alt_name = name.substr(0, 6) + suffix;
193 alt_name += name.substr(period, name.size());
194 if (check_in_browser) {
195 module = ::GetModuleHandleW(alt_name.c_str());
196 if (!module)
197 return;
198 // We found it, but because it only has 6 significant letters, we
199 // want to make sure it is the right one.
200 if (!IsExpandedModuleName(module, module_name))
201 return;
203 // Found a match. We add both forms to the policy.
204 policy->AddDllToUnload(alt_name.c_str());
207 policy->AddDllToUnload(module_name);
208 DVLOG(1) << "dll to unload found: " << module_name;
209 return;
212 // Adds policy rules for unloaded the known dlls that cause chrome to crash.
213 // Eviction of injected DLLs is done by the sandbox so that the injected module
214 // does not get a chance to execute any code.
215 void AddGenericDllEvictionPolicy(sandbox::TargetPolicy* policy) {
216 for (int ix = 0; ix != arraysize(kTroublesomeDlls); ++ix)
217 BlacklistAddOneDll(kTroublesomeDlls[ix], true, policy);
220 // Returns the object path prepended with the current logon session.
221 base::string16 PrependWindowsSessionPath(const base::char16* object) {
222 // Cache this because it can't change after process creation.
223 static uintptr_t s_session_id = 0;
224 if (s_session_id == 0) {
225 HANDLE token;
226 DWORD session_id_length;
227 DWORD session_id = 0;
229 CHECK(::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token));
230 CHECK(::GetTokenInformation(token, TokenSessionId, &session_id,
231 sizeof(session_id), &session_id_length));
232 CloseHandle(token);
233 if (session_id)
234 s_session_id = session_id;
237 return base::StringPrintf(L"\\Sessions\\%d%ls", s_session_id, object);
240 // Checks if the sandbox should be let to run without a job object assigned.
241 bool ShouldSetJobLevel(const CommandLine& cmd_line) {
242 if (!cmd_line.HasSwitch(switches::kAllowNoSandboxJob))
243 return true;
245 // Windows 8 allows nested jobs so we don't need to check if we are in other
246 // job.
247 if (base::win::GetVersion() >= base::win::VERSION_WIN8)
248 return true;
250 BOOL in_job = true;
251 // Either there is no job yet associated so we must add our job,
252 if (!::IsProcessInJob(::GetCurrentProcess(), NULL, &in_job))
253 NOTREACHED() << "IsProcessInJob failed. " << GetLastError();
254 if (!in_job)
255 return true;
257 // ...or there is a job but the JOB_OBJECT_LIMIT_BREAKAWAY_OK limit is set.
258 JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info = {0};
259 if (!::QueryInformationJobObject(NULL,
260 JobObjectExtendedLimitInformation, &job_info,
261 sizeof(job_info), NULL)) {
262 NOTREACHED() << "QueryInformationJobObject failed. " << GetLastError();
263 return true;
265 if (job_info.BasicLimitInformation.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK)
266 return true;
268 return false;
271 // Adds the generic policy rules to a sandbox TargetPolicy.
272 bool AddGenericPolicy(sandbox::TargetPolicy* policy) {
273 sandbox::ResultCode result;
275 // Renderers need to copy sections for plugin DIBs and GPU.
276 // GPU needs to copy sections to renderers.
277 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
278 sandbox::TargetPolicy::HANDLES_DUP_ANY,
279 L"Section");
280 if (result != sandbox::SBOX_ALL_OK)
281 return false;
283 // Add the policy for the client side of a pipe. It is just a file
284 // in the \pipe\ namespace. We restrict it to pipes that start with
285 // "chrome." so the sandboxed process cannot connect to system services.
286 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
287 sandbox::TargetPolicy::FILES_ALLOW_ANY,
288 L"\\??\\pipe\\chrome.*");
289 if (result != sandbox::SBOX_ALL_OK)
290 return false;
292 // Add the policy for the server side of nacl pipe. It is just a file
293 // in the \pipe\ namespace. We restrict it to pipes that start with
294 // "chrome.nacl" so the sandboxed process cannot connect to
295 // system services.
296 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
297 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
298 L"\\\\.\\pipe\\chrome.nacl.*");
299 if (result != sandbox::SBOX_ALL_OK)
300 return false;
302 // Allow the server side of sync sockets, which are pipes that have
303 // the "chrome.sync" namespace and a randomly generated suffix.
304 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
305 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
306 L"\\\\.\\pipe\\chrome.sync.*");
307 if (result != sandbox::SBOX_ALL_OK)
308 return false;
310 // Add the policy for debug message only in debug
311 #ifndef NDEBUG
312 base::FilePath app_dir;
313 if (!PathService::Get(base::DIR_MODULE, &app_dir))
314 return false;
316 wchar_t long_path_buf[MAX_PATH];
317 DWORD long_path_return_value = GetLongPathName(app_dir.value().c_str(),
318 long_path_buf,
319 MAX_PATH);
320 if (long_path_return_value == 0 || long_path_return_value >= MAX_PATH)
321 return false;
323 base::FilePath debug_message(long_path_buf);
324 debug_message = debug_message.AppendASCII("debug_message.exe");
325 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_PROCESS,
326 sandbox::TargetPolicy::PROCESS_MIN_EXEC,
327 debug_message.value().c_str());
328 if (result != sandbox::SBOX_ALL_OK)
329 return false;
330 #endif // NDEBUG
332 AddGenericDllEvictionPolicy(policy);
334 return true;
337 bool AddPolicyForSandboxedProcess(sandbox::TargetPolicy* policy) {
338 sandbox::ResultCode result;
339 // Renderers need to share events with plugins.
340 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
341 sandbox::TargetPolicy::HANDLES_DUP_ANY,
342 L"Event");
343 if (result != sandbox::SBOX_ALL_OK)
344 return false;
346 sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED;
347 if (base::win::GetVersion() > base::win::VERSION_XP) {
348 // On 2003/Vista the initial token has to be restricted if the main
349 // token is restricted.
350 initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS;
353 policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN);
354 // Prevents the renderers from manipulating low-integrity processes.
355 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
357 bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch(
358 switches::kDisableAltWinstation);
360 if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) {
361 DLOG(WARNING) << "Failed to apply desktop security to the renderer";
364 return true;
367 // Updates the command line arguments with debug-related flags. If debug flags
368 // have been used with this process, they will be filtered and added to
369 // command_line as needed.
370 void ProcessDebugFlags(CommandLine* command_line) {
371 const CommandLine& current_cmd_line = *CommandLine::ForCurrentProcess();
372 std::string type = command_line->GetSwitchValueASCII(switches::kProcessType);
373 if (current_cmd_line.HasSwitch(switches::kWaitForDebuggerChildren)) {
374 // Look to pass-on the kWaitForDebugger flag.
375 std::string value = current_cmd_line.GetSwitchValueASCII(
376 switches::kWaitForDebuggerChildren);
377 if (value.empty() || value == type) {
378 command_line->AppendSwitch(switches::kWaitForDebugger);
380 command_line->AppendSwitchASCII(switches::kWaitForDebuggerChildren, value);
384 // This code is test only, and attempts to catch unsafe uses of
385 // DuplicateHandle() that copy privileged handles into sandboxed processes.
386 #ifndef OFFICIAL_BUILD
387 base::win::IATPatchFunction g_iat_patch_duplicate_handle;
389 typedef BOOL (WINAPI *DuplicateHandleFunctionPtr)(HANDLE source_process_handle,
390 HANDLE source_handle,
391 HANDLE target_process_handle,
392 LPHANDLE target_handle,
393 DWORD desired_access,
394 BOOL inherit_handle,
395 DWORD options);
397 DuplicateHandleFunctionPtr g_iat_orig_duplicate_handle;
399 NtQueryObject g_QueryObject = NULL;
401 static const char* kDuplicateHandleWarning =
402 "You are attempting to duplicate a privileged handle into a sandboxed"
403 " process.\n Please use the sandbox::BrokerDuplicateHandle API or"
404 " contact security@chromium.org for assistance.";
406 void CheckDuplicateHandle(HANDLE handle) {
407 // Get the object type (32 characters is safe; current max is 14).
408 BYTE buffer[sizeof(OBJECT_TYPE_INFORMATION) + 32 * sizeof(wchar_t)];
409 OBJECT_TYPE_INFORMATION* type_info =
410 reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer);
411 ULONG size = sizeof(buffer) - sizeof(wchar_t);
412 NTSTATUS error;
413 error = g_QueryObject(handle, ObjectTypeInformation, type_info, size, &size);
414 CHECK(NT_SUCCESS(error));
415 type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
417 // Get the object basic information.
418 OBJECT_BASIC_INFORMATION basic_info;
419 size = sizeof(basic_info);
420 error = g_QueryObject(handle, ObjectBasicInformation, &basic_info, size,
421 &size);
422 CHECK(NT_SUCCESS(error));
424 CHECK(!(basic_info.GrantedAccess & WRITE_DAC)) <<
425 kDuplicateHandleWarning;
427 if (0 == _wcsicmp(type_info->Name.Buffer, L"Process")) {
428 const ACCESS_MASK kDangerousMask = ~(PROCESS_QUERY_LIMITED_INFORMATION |
429 SYNCHRONIZE);
430 CHECK(!(basic_info.GrantedAccess & kDangerousMask)) <<
431 kDuplicateHandleWarning;
435 BOOL WINAPI DuplicateHandlePatch(HANDLE source_process_handle,
436 HANDLE source_handle,
437 HANDLE target_process_handle,
438 LPHANDLE target_handle,
439 DWORD desired_access,
440 BOOL inherit_handle,
441 DWORD options) {
442 // Duplicate the handle so we get the final access mask.
443 if (!g_iat_orig_duplicate_handle(source_process_handle, source_handle,
444 target_process_handle, target_handle,
445 desired_access, inherit_handle, options))
446 return FALSE;
448 // We're not worried about broker handles or not crossing process boundaries.
449 if (source_process_handle == target_process_handle ||
450 target_process_handle == ::GetCurrentProcess())
451 return TRUE;
453 // Only sandboxed children are placed in jobs, so just check them.
454 BOOL is_in_job = FALSE;
455 if (!::IsProcessInJob(target_process_handle, NULL, &is_in_job)) {
456 // We need a handle with permission to check the job object.
457 if (ERROR_ACCESS_DENIED == ::GetLastError()) {
458 HANDLE temp_handle;
459 CHECK(g_iat_orig_duplicate_handle(::GetCurrentProcess(),
460 target_process_handle,
461 ::GetCurrentProcess(),
462 &temp_handle,
463 PROCESS_QUERY_INFORMATION,
464 FALSE, 0));
465 base::win::ScopedHandle process(temp_handle);
466 CHECK(::IsProcessInJob(process, NULL, &is_in_job));
470 if (is_in_job) {
471 // We never allow inheritable child handles.
472 CHECK(!inherit_handle) << kDuplicateHandleWarning;
474 // Duplicate the handle again, to get the final permissions.
475 HANDLE temp_handle;
476 CHECK(g_iat_orig_duplicate_handle(target_process_handle, *target_handle,
477 ::GetCurrentProcess(), &temp_handle,
478 0, FALSE, DUPLICATE_SAME_ACCESS));
479 base::win::ScopedHandle handle(temp_handle);
481 // Callers use CHECK macro to make sure we get the right stack.
482 CheckDuplicateHandle(handle);
485 return TRUE;
487 #endif
489 } // namespace
491 void SetJobLevel(const CommandLine& cmd_line,
492 sandbox::JobLevel job_level,
493 uint32 ui_exceptions,
494 sandbox::TargetPolicy* policy) {
495 if (ShouldSetJobLevel(cmd_line))
496 policy->SetJobLevel(job_level, ui_exceptions);
497 else
498 policy->SetJobLevel(sandbox::JOB_NONE, 0);
501 // TODO(jschuh): Need get these restrictions applied to NaCl and Pepper.
502 // Just have to figure out what needs to be warmed up first.
503 void AddBaseHandleClosePolicy(sandbox::TargetPolicy* policy) {
504 // TODO(cpu): Add back the BaseNamedObjects policy.
505 base::string16 object_path = PrependWindowsSessionPath(
506 L"\\BaseNamedObjects\\windows_shell_global_counters");
507 policy->AddKernelObjectToClose(L"Section", object_path.data());
510 bool InitBrokerServices(sandbox::BrokerServices* broker_services) {
511 // TODO(abarth): DCHECK(CalledOnValidThread());
512 // See <http://b/1287166>.
513 DCHECK(broker_services);
514 DCHECK(!g_broker_services);
515 sandbox::ResultCode result = broker_services->Init();
516 g_broker_services = broker_services;
518 // In non-official builds warn about dangerous uses of DuplicateHandle.
519 #ifndef OFFICIAL_BUILD
520 BOOL is_in_job = FALSE;
521 CHECK(::IsProcessInJob(::GetCurrentProcess(), NULL, &is_in_job));
522 // In a Syzygy-profiled binary, instrumented for import profiling, this
523 // patch will end in infinite recursion on the attempted delegation to the
524 // original function.
525 if (!base::debug::IsBinaryInstrumented() &&
526 !is_in_job && !g_iat_patch_duplicate_handle.is_patched()) {
527 HMODULE module = NULL;
528 wchar_t module_name[MAX_PATH];
529 CHECK(::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
530 reinterpret_cast<LPCWSTR>(InitBrokerServices),
531 &module));
532 DWORD result = ::GetModuleFileNameW(module, module_name, MAX_PATH);
533 if (result && (result != MAX_PATH)) {
534 ResolveNTFunctionPtr("NtQueryObject", &g_QueryObject);
535 result = g_iat_patch_duplicate_handle.Patch(
536 module_name, "kernel32.dll", "DuplicateHandle",
537 DuplicateHandlePatch);
538 CHECK(result == 0);
539 g_iat_orig_duplicate_handle =
540 reinterpret_cast<DuplicateHandleFunctionPtr>(
541 g_iat_patch_duplicate_handle.original_function());
544 #endif
546 return sandbox::SBOX_ALL_OK == result;
549 bool InitTargetServices(sandbox::TargetServices* target_services) {
550 DCHECK(target_services);
551 DCHECK(!g_target_services);
552 sandbox::ResultCode result = target_services->Init();
553 g_target_services = target_services;
554 return sandbox::SBOX_ALL_OK == result;
557 bool ShouldUseDirectWrite() {
558 // If the flag is currently on, and we're on Win7 or above, we enable
559 // DirectWrite. Skia does not require the additions to DirectWrite in QFE
560 // 2670838, so a Win7 check is sufficient. We do not currently attempt to
561 // support Vista, where SP2 and the Platform Update are required.
562 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
563 return command_line.HasSwitch(switches::kEnableDirectWrite) &&
564 base::win::GetVersion() >= base::win::VERSION_WIN7;
567 base::ProcessHandle StartSandboxedProcess(
568 SandboxedProcessLauncherDelegate* delegate,
569 CommandLine* cmd_line) {
570 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
571 std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
573 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
575 // Propagate the --allow-no-job flag if present.
576 if (browser_command_line.HasSwitch(switches::kAllowNoSandboxJob) &&
577 !cmd_line->HasSwitch(switches::kAllowNoSandboxJob)) {
578 cmd_line->AppendSwitch(switches::kAllowNoSandboxJob);
581 ProcessDebugFlags(cmd_line);
583 // Prefetch hints on windows:
584 // Using a different prefetch profile per process type will allow Windows
585 // to create separate pretetch settings for browser, renderer etc.
586 cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", base::Hash(type_str)));
588 if ((delegate && !delegate->ShouldSandbox()) ||
589 browser_command_line.HasSwitch(switches::kNoSandbox) ||
590 cmd_line->HasSwitch(switches::kNoSandbox)) {
591 base::ProcessHandle process = 0;
592 base::LaunchProcess(*cmd_line, base::LaunchOptions(), &process);
593 g_broker_services->AddTargetPeer(process);
594 return process;
597 sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
599 sandbox::MitigationFlags mitigations = sandbox::MITIGATION_HEAP_TERMINATE |
600 sandbox::MITIGATION_BOTTOM_UP_ASLR |
601 sandbox::MITIGATION_DEP |
602 sandbox::MITIGATION_DEP_NO_ATL_THUNK |
603 sandbox::MITIGATION_SEHOP;
605 if (policy->SetProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
606 return 0;
608 mitigations = sandbox::MITIGATION_STRICT_HANDLE_CHECKS |
609 sandbox::MITIGATION_DLL_SEARCH_ORDER;
611 if (policy->SetDelayedProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
612 return 0;
614 SetJobLevel(*cmd_line, sandbox::JOB_LOCKDOWN, 0, policy);
616 bool disable_default_policy = false;
617 base::FilePath exposed_dir;
618 if (delegate)
619 delegate->PreSandbox(&disable_default_policy, &exposed_dir);
621 if (!disable_default_policy && !AddPolicyForSandboxedProcess(policy))
622 return 0;
624 if (type_str == switches::kRendererProcess) {
625 if (ShouldUseDirectWrite()) {
626 AddDirectory(base::DIR_WINDOWS_FONTS,
627 NULL,
628 true,
629 sandbox::TargetPolicy::FILES_ALLOW_READONLY,
630 policy);
632 } else {
633 // Hack for Google Desktop crash. Trick GD into not injecting its DLL into
634 // this subprocess. See
635 // http://code.google.com/p/chromium/issues/detail?id=25580
636 cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
639 sandbox::ResultCode result;
640 if (!exposed_dir.empty()) {
641 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
642 sandbox::TargetPolicy::FILES_ALLOW_ANY,
643 exposed_dir.value().c_str());
644 if (result != sandbox::SBOX_ALL_OK)
645 return 0;
647 base::FilePath exposed_files = exposed_dir.AppendASCII("*");
648 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
649 sandbox::TargetPolicy::FILES_ALLOW_ANY,
650 exposed_files.value().c_str());
651 if (result != sandbox::SBOX_ALL_OK)
652 return 0;
655 if (!AddGenericPolicy(policy)) {
656 NOTREACHED();
657 return 0;
660 if (browser_command_line.HasSwitch(switches::kEnableLogging)) {
661 // If stdout/stderr point to a Windows console, these calls will
662 // have no effect.
663 policy->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE));
664 policy->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE));
667 if (delegate) {
668 bool success = true;
669 delegate->PreSpawnTarget(policy, &success);
670 if (!success)
671 return 0;
674 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
676 PROCESS_INFORMATION temp_process_info = {};
677 result = g_broker_services->SpawnTarget(
678 cmd_line->GetProgram().value().c_str(),
679 cmd_line->GetCommandLineString().c_str(),
680 policy, &temp_process_info);
681 policy->Release();
682 base::win::ScopedProcessInformation target(temp_process_info);
684 TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
686 if (sandbox::SBOX_ALL_OK != result) {
687 if (result == sandbox::SBOX_ERROR_GENERIC)
688 DPLOG(ERROR) << "Failed to launch process";
689 else
690 DLOG(ERROR) << "Failed to launch process. Error: " << result;
691 return 0;
694 if (delegate)
695 delegate->PostSpawnTarget(target.process_handle());
697 ResumeThread(target.thread_handle());
698 return target.TakeProcessHandle();
701 bool BrokerDuplicateHandle(HANDLE source_handle,
702 DWORD target_process_id,
703 HANDLE* target_handle,
704 DWORD desired_access,
705 DWORD options) {
706 // If our process is the target just duplicate the handle.
707 if (::GetCurrentProcessId() == target_process_id) {
708 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
709 ::GetCurrentProcess(), target_handle,
710 desired_access, FALSE, options);
714 // Try the broker next
715 if (g_target_services &&
716 g_target_services->DuplicateHandle(source_handle, target_process_id,
717 target_handle, desired_access,
718 options) == sandbox::SBOX_ALL_OK) {
719 return true;
722 // Finally, see if we already have access to the process.
723 base::win::ScopedHandle target_process;
724 target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE,
725 target_process_id));
726 if (target_process.IsValid()) {
727 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
728 target_process, target_handle,
729 desired_access, FALSE, options);
732 return false;
735 bool BrokerAddTargetPeer(HANDLE peer_process) {
736 return g_broker_services->AddTargetPeer(peer_process) == sandbox::SBOX_ALL_OK;
739 } // namespace content