Update optimize_png_files.sh to work on msysgit bash.
[chromium-blink-merge.git] / content / common / sandbox_win.cc
blob401d68fa56adab4a3f5dade78cea8885de9689db
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 // Win8+ adds a device DeviceApi that we don't need.
347 if (base::win::GetVersion() > base::win::VERSION_WIN7)
348 policy->AddKernelObjectToClose(L"File", L"\\Device\\DeviceApi");
350 sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED;
351 if (base::win::GetVersion() > base::win::VERSION_XP) {
352 // On 2003/Vista the initial token has to be restricted if the main
353 // token is restricted.
354 initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS;
357 policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN);
358 // Prevents the renderers from manipulating low-integrity processes.
359 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
361 bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch(
362 switches::kDisableAltWinstation);
364 if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) {
365 DLOG(WARNING) << "Failed to apply desktop security to the renderer";
368 return true;
371 // Updates the command line arguments with debug-related flags. If debug flags
372 // have been used with this process, they will be filtered and added to
373 // command_line as needed.
374 void ProcessDebugFlags(CommandLine* command_line) {
375 const CommandLine& current_cmd_line = *CommandLine::ForCurrentProcess();
376 std::string type = command_line->GetSwitchValueASCII(switches::kProcessType);
377 if (current_cmd_line.HasSwitch(switches::kWaitForDebuggerChildren)) {
378 // Look to pass-on the kWaitForDebugger flag.
379 std::string value = current_cmd_line.GetSwitchValueASCII(
380 switches::kWaitForDebuggerChildren);
381 if (value.empty() || value == type) {
382 command_line->AppendSwitch(switches::kWaitForDebugger);
384 command_line->AppendSwitchASCII(switches::kWaitForDebuggerChildren, value);
388 // This code is test only, and attempts to catch unsafe uses of
389 // DuplicateHandle() that copy privileged handles into sandboxed processes.
390 #ifndef OFFICIAL_BUILD
391 base::win::IATPatchFunction g_iat_patch_duplicate_handle;
393 typedef BOOL (WINAPI *DuplicateHandleFunctionPtr)(HANDLE source_process_handle,
394 HANDLE source_handle,
395 HANDLE target_process_handle,
396 LPHANDLE target_handle,
397 DWORD desired_access,
398 BOOL inherit_handle,
399 DWORD options);
401 DuplicateHandleFunctionPtr g_iat_orig_duplicate_handle;
403 NtQueryObject g_QueryObject = NULL;
405 static const char* kDuplicateHandleWarning =
406 "You are attempting to duplicate a privileged handle into a sandboxed"
407 " process.\n Please use the sandbox::BrokerDuplicateHandle API or"
408 " contact security@chromium.org for assistance.";
410 void CheckDuplicateHandle(HANDLE handle) {
411 // Get the object type (32 characters is safe; current max is 14).
412 BYTE buffer[sizeof(OBJECT_TYPE_INFORMATION) + 32 * sizeof(wchar_t)];
413 OBJECT_TYPE_INFORMATION* type_info =
414 reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer);
415 ULONG size = sizeof(buffer) - sizeof(wchar_t);
416 NTSTATUS error;
417 error = g_QueryObject(handle, ObjectTypeInformation, type_info, size, &size);
418 CHECK(NT_SUCCESS(error));
419 type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
421 // Get the object basic information.
422 OBJECT_BASIC_INFORMATION basic_info;
423 size = sizeof(basic_info);
424 error = g_QueryObject(handle, ObjectBasicInformation, &basic_info, size,
425 &size);
426 CHECK(NT_SUCCESS(error));
428 CHECK(!(basic_info.GrantedAccess & WRITE_DAC)) <<
429 kDuplicateHandleWarning;
431 if (0 == _wcsicmp(type_info->Name.Buffer, L"Process")) {
432 const ACCESS_MASK kDangerousMask = ~(PROCESS_QUERY_LIMITED_INFORMATION |
433 SYNCHRONIZE);
434 CHECK(!(basic_info.GrantedAccess & kDangerousMask)) <<
435 kDuplicateHandleWarning;
439 BOOL WINAPI DuplicateHandlePatch(HANDLE source_process_handle,
440 HANDLE source_handle,
441 HANDLE target_process_handle,
442 LPHANDLE target_handle,
443 DWORD desired_access,
444 BOOL inherit_handle,
445 DWORD options) {
446 // Duplicate the handle so we get the final access mask.
447 if (!g_iat_orig_duplicate_handle(source_process_handle, source_handle,
448 target_process_handle, target_handle,
449 desired_access, inherit_handle, options))
450 return FALSE;
452 // We're not worried about broker handles or not crossing process boundaries.
453 if (source_process_handle == target_process_handle ||
454 target_process_handle == ::GetCurrentProcess())
455 return TRUE;
457 // Only sandboxed children are placed in jobs, so just check them.
458 BOOL is_in_job = FALSE;
459 if (!::IsProcessInJob(target_process_handle, NULL, &is_in_job)) {
460 // We need a handle with permission to check the job object.
461 if (ERROR_ACCESS_DENIED == ::GetLastError()) {
462 HANDLE temp_handle;
463 CHECK(g_iat_orig_duplicate_handle(::GetCurrentProcess(),
464 target_process_handle,
465 ::GetCurrentProcess(),
466 &temp_handle,
467 PROCESS_QUERY_INFORMATION,
468 FALSE, 0));
469 base::win::ScopedHandle process(temp_handle);
470 CHECK(::IsProcessInJob(process, NULL, &is_in_job));
474 if (is_in_job) {
475 // We never allow inheritable child handles.
476 CHECK(!inherit_handle) << kDuplicateHandleWarning;
478 // Duplicate the handle again, to get the final permissions.
479 HANDLE temp_handle;
480 CHECK(g_iat_orig_duplicate_handle(target_process_handle, *target_handle,
481 ::GetCurrentProcess(), &temp_handle,
482 0, FALSE, DUPLICATE_SAME_ACCESS));
483 base::win::ScopedHandle handle(temp_handle);
485 // Callers use CHECK macro to make sure we get the right stack.
486 CheckDuplicateHandle(handle);
489 return TRUE;
491 #endif
493 } // namespace
495 void SetJobLevel(const CommandLine& cmd_line,
496 sandbox::JobLevel job_level,
497 uint32 ui_exceptions,
498 sandbox::TargetPolicy* policy) {
499 if (ShouldSetJobLevel(cmd_line))
500 policy->SetJobLevel(job_level, ui_exceptions);
501 else
502 policy->SetJobLevel(sandbox::JOB_NONE, 0);
505 // TODO(jschuh): Need get these restrictions applied to NaCl and Pepper.
506 // Just have to figure out what needs to be warmed up first.
507 void AddBaseHandleClosePolicy(sandbox::TargetPolicy* policy) {
508 // TODO(cpu): Add back the BaseNamedObjects policy.
509 base::string16 object_path = PrependWindowsSessionPath(
510 L"\\BaseNamedObjects\\windows_shell_global_counters");
511 policy->AddKernelObjectToClose(L"Section", object_path.data());
514 bool InitBrokerServices(sandbox::BrokerServices* broker_services) {
515 // TODO(abarth): DCHECK(CalledOnValidThread());
516 // See <http://b/1287166>.
517 DCHECK(broker_services);
518 DCHECK(!g_broker_services);
519 sandbox::ResultCode result = broker_services->Init();
520 g_broker_services = broker_services;
522 // In non-official builds warn about dangerous uses of DuplicateHandle.
523 #ifndef OFFICIAL_BUILD
524 BOOL is_in_job = FALSE;
525 CHECK(::IsProcessInJob(::GetCurrentProcess(), NULL, &is_in_job));
526 // In a Syzygy-profiled binary, instrumented for import profiling, this
527 // patch will end in infinite recursion on the attempted delegation to the
528 // original function.
529 if (!base::debug::IsBinaryInstrumented() &&
530 !is_in_job && !g_iat_patch_duplicate_handle.is_patched()) {
531 HMODULE module = NULL;
532 wchar_t module_name[MAX_PATH];
533 CHECK(::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
534 reinterpret_cast<LPCWSTR>(InitBrokerServices),
535 &module));
536 DWORD result = ::GetModuleFileNameW(module, module_name, MAX_PATH);
537 if (result && (result != MAX_PATH)) {
538 ResolveNTFunctionPtr("NtQueryObject", &g_QueryObject);
539 result = g_iat_patch_duplicate_handle.Patch(
540 module_name, "kernel32.dll", "DuplicateHandle",
541 DuplicateHandlePatch);
542 CHECK(result == 0);
543 g_iat_orig_duplicate_handle =
544 reinterpret_cast<DuplicateHandleFunctionPtr>(
545 g_iat_patch_duplicate_handle.original_function());
548 #endif
550 return sandbox::SBOX_ALL_OK == result;
553 bool InitTargetServices(sandbox::TargetServices* target_services) {
554 DCHECK(target_services);
555 DCHECK(!g_target_services);
556 sandbox::ResultCode result = target_services->Init();
557 g_target_services = target_services;
558 return sandbox::SBOX_ALL_OK == result;
561 bool ShouldUseDirectWrite() {
562 // If the flag is currently on, and we're on Win7 or above, we enable
563 // DirectWrite. Skia does not require the additions to DirectWrite in QFE
564 // 2670838, so a Win7 check is sufficient. We do not currently attempt to
565 // support Vista, where SP2 and the Platform Update are required.
566 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
567 return command_line.HasSwitch(switches::kEnableDirectWrite) &&
568 base::win::GetVersion() >= base::win::VERSION_WIN7;
571 base::ProcessHandle StartSandboxedProcess(
572 SandboxedProcessLauncherDelegate* delegate,
573 CommandLine* cmd_line) {
574 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
575 std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
577 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
579 // Propagate the --allow-no-job flag if present.
580 if (browser_command_line.HasSwitch(switches::kAllowNoSandboxJob) &&
581 !cmd_line->HasSwitch(switches::kAllowNoSandboxJob)) {
582 cmd_line->AppendSwitch(switches::kAllowNoSandboxJob);
585 ProcessDebugFlags(cmd_line);
587 // Prefetch hints on windows:
588 // Using a different prefetch profile per process type will allow Windows
589 // to create separate pretetch settings for browser, renderer etc.
590 cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", base::Hash(type_str)));
592 if ((delegate && !delegate->ShouldSandbox()) ||
593 browser_command_line.HasSwitch(switches::kNoSandbox) ||
594 cmd_line->HasSwitch(switches::kNoSandbox)) {
595 base::ProcessHandle process = 0;
596 base::LaunchProcess(*cmd_line, base::LaunchOptions(), &process);
597 g_broker_services->AddTargetPeer(process);
598 return process;
601 sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
603 sandbox::MitigationFlags mitigations = sandbox::MITIGATION_HEAP_TERMINATE |
604 sandbox::MITIGATION_BOTTOM_UP_ASLR |
605 sandbox::MITIGATION_DEP |
606 sandbox::MITIGATION_DEP_NO_ATL_THUNK |
607 sandbox::MITIGATION_SEHOP;
609 if (base::win::GetVersion() >= base::win::VERSION_WIN8 &&
610 type_str == switches::kRendererProcess &&
611 browser_command_line.HasSwitch(
612 switches::kEnableWin32kRendererLockDown)) {
613 mitigations |= sandbox::MITIGATION_WIN32K_DISABLE;
616 if (policy->SetProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
617 return 0;
619 mitigations = sandbox::MITIGATION_STRICT_HANDLE_CHECKS |
620 sandbox::MITIGATION_DLL_SEARCH_ORDER;
622 if (policy->SetDelayedProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
623 return 0;
625 SetJobLevel(*cmd_line, sandbox::JOB_LOCKDOWN, 0, policy);
627 bool disable_default_policy = false;
628 base::FilePath exposed_dir;
629 if (delegate)
630 delegate->PreSandbox(&disable_default_policy, &exposed_dir);
632 if (!disable_default_policy && !AddPolicyForSandboxedProcess(policy))
633 return 0;
635 if (type_str == switches::kRendererProcess) {
636 if (ShouldUseDirectWrite()) {
637 AddDirectory(base::DIR_WINDOWS_FONTS,
638 NULL,
639 true,
640 sandbox::TargetPolicy::FILES_ALLOW_READONLY,
641 policy);
643 } else {
644 // Hack for Google Desktop crash. Trick GD into not injecting its DLL into
645 // this subprocess. See
646 // http://code.google.com/p/chromium/issues/detail?id=25580
647 cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
650 sandbox::ResultCode result;
651 if (!exposed_dir.empty()) {
652 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
653 sandbox::TargetPolicy::FILES_ALLOW_ANY,
654 exposed_dir.value().c_str());
655 if (result != sandbox::SBOX_ALL_OK)
656 return 0;
658 base::FilePath exposed_files = exposed_dir.AppendASCII("*");
659 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
660 sandbox::TargetPolicy::FILES_ALLOW_ANY,
661 exposed_files.value().c_str());
662 if (result != sandbox::SBOX_ALL_OK)
663 return 0;
666 if (!AddGenericPolicy(policy)) {
667 NOTREACHED();
668 return 0;
671 if (browser_command_line.HasSwitch(switches::kEnableLogging)) {
672 // If stdout/stderr point to a Windows console, these calls will
673 // have no effect.
674 policy->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE));
675 policy->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE));
678 if (delegate) {
679 bool success = true;
680 delegate->PreSpawnTarget(policy, &success);
681 if (!success)
682 return 0;
685 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
687 PROCESS_INFORMATION temp_process_info = {};
688 result = g_broker_services->SpawnTarget(
689 cmd_line->GetProgram().value().c_str(),
690 cmd_line->GetCommandLineString().c_str(),
691 policy, &temp_process_info);
692 policy->Release();
693 base::win::ScopedProcessInformation target(temp_process_info);
695 TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
697 if (sandbox::SBOX_ALL_OK != result) {
698 if (result == sandbox::SBOX_ERROR_GENERIC)
699 DPLOG(ERROR) << "Failed to launch process";
700 else
701 DLOG(ERROR) << "Failed to launch process. Error: " << result;
702 return 0;
705 if (delegate)
706 delegate->PostSpawnTarget(target.process_handle());
708 ResumeThread(target.thread_handle());
709 return target.TakeProcessHandle();
712 bool BrokerDuplicateHandle(HANDLE source_handle,
713 DWORD target_process_id,
714 HANDLE* target_handle,
715 DWORD desired_access,
716 DWORD options) {
717 // If our process is the target just duplicate the handle.
718 if (::GetCurrentProcessId() == target_process_id) {
719 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
720 ::GetCurrentProcess(), target_handle,
721 desired_access, FALSE, options);
725 // Try the broker next
726 if (g_target_services &&
727 g_target_services->DuplicateHandle(source_handle, target_process_id,
728 target_handle, desired_access,
729 options) == sandbox::SBOX_ALL_OK) {
730 return true;
733 // Finally, see if we already have access to the process.
734 base::win::ScopedHandle target_process;
735 target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE,
736 target_process_id));
737 if (target_process.IsValid()) {
738 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
739 target_process, target_handle,
740 desired_access, FALSE, options);
743 return false;
746 bool BrokerAddTargetPeer(HANDLE peer_process) {
747 return g_broker_services->AddTargetPeer(peer_process) == sandbox::SBOX_ALL_OK;
750 } // namespace content