Remove obsolete Channel ID expiration time from site data viewer.
[chromium-blink-merge.git] / content / common / sandbox_win.cc
blobe86d4335944bb967ae2f524d70a91d1417aa46da
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/debugger.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_util.h"
17 #include "base/string_util.h"
18 #include "base/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 "ipc/ipc_switches.h"
28 #include "sandbox/win/src/process_mitigations.h"
29 #include "sandbox/win/src/sandbox.h"
30 #include "sandbox/win/src/sandbox_nt_util.h"
31 #include "sandbox/win/src/win_utils.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 const wchar_t* const kTroublesomeDlls[] = {
43 L"adialhk.dll", // Kaspersky Internet Security.
44 L"acpiz.dll", // Unknown.
45 L"avgrsstx.dll", // AVG 8.
46 L"babylonchromepi.dll", // Babylon translator.
47 L"btkeyind.dll", // Widcomm Bluetooth.
48 L"cmcsyshk.dll", // CMC Internet Security.
49 L"cmsetac.dll", // Unknown (suspected malware).
50 L"cooliris.dll", // CoolIris.
51 L"dockshellhook.dll", // Stardock Objectdock.
52 L"easyhook32.dll", // GDIPP and others.
53 L"googledesktopnetwork3.dll", // Google Desktop Search v5.
54 L"fwhook.dll", // PC Tools Firewall Plus.
55 L"hookprocesscreation.dll", // Blumentals Program protector.
56 L"hookterminateapis.dll", // Blumentals and Cyberprinter.
57 L"hookprintapis.dll", // Cyberprinter.
58 L"imon.dll", // NOD32 Antivirus.
59 L"ioloHL.dll", // Iolo (System Mechanic).
60 L"kloehk.dll", // Kaspersky Internet Security.
61 L"lawenforcer.dll", // Spyware-Browser AntiSpyware (Spybro).
62 L"libdivx.dll", // DivX.
63 L"lvprcinj01.dll", // Logitech QuickCam.
64 L"madchook.dll", // Madshi (generic hooking library).
65 L"mdnsnsp.dll", // Bonjour.
66 L"moonsysh.dll", // Moon Secure Antivirus.
67 L"mpk.dll", // KGB Spy.
68 L"npdivx32.dll", // DivX.
69 L"npggNT.des", // GameGuard 2008.
70 L"npggNT.dll", // GameGuard (older).
71 L"oawatch.dll", // Online Armor.
72 L"pavhook.dll", // Panda Internet Security.
73 L"pavlsphook.dll", // Panda Antivirus.
74 L"pavshook.dll", // Panda Antivirus.
75 L"pavshookwow.dll", // Panda Antivirus.
76 L"pctavhook.dll", // PC Tools Antivirus.
77 L"pctgmhk.dll", // PC Tools Spyware Doctor.
78 L"prntrack.dll", // Pharos Systems.
79 L"protector.dll", // Unknown (suspected malware).
80 L"radhslib.dll", // Radiant Naomi Internet Filter.
81 L"radprlib.dll", // Radiant Naomi Internet Filter.
82 L"rapportnikko.dll", // Trustware Rapport.
83 L"rlhook.dll", // Trustware Bufferzone.
84 L"rooksdol.dll", // Trustware Rapport.
85 L"rpchromebrowserrecordhelper.dll", // RealPlayer.
86 L"r3hook.dll", // Kaspersky Internet Security.
87 L"sahook.dll", // McAfee Site Advisor.
88 L"sbrige.dll", // Unknown.
89 L"sc2hook.dll", // Supercopier 2.
90 L"sdhook32.dll", // Spybot - Search & Destroy Live Protection.
91 L"sguard.dll", // Iolo (System Guard).
92 L"smum32.dll", // Spyware Doctor version 6.
93 L"smumhook.dll", // Spyware Doctor version 5.
94 L"ssldivx.dll", // DivX.
95 L"syncor11.dll", // SynthCore Midi interface.
96 L"systools.dll", // Panda Antivirus.
97 L"tfwah.dll", // Threatfire (PC tools).
98 L"wblind.dll", // Stardock Object desktop.
99 L"wbhelp.dll", // Stardock Object desktop.
100 L"winstylerthemehelper.dll" // Tuneup utilities 2006.
103 // Adds the policy rules for the path and path\ with the semantic |access|.
104 // If |children| is set to true, we need to add the wildcard rules to also
105 // apply the rule to the subfiles and subfolders.
106 bool AddDirectory(int path, const wchar_t* sub_dir, bool children,
107 sandbox::TargetPolicy::Semantics access,
108 sandbox::TargetPolicy* policy) {
109 base::FilePath directory;
110 if (!PathService::Get(path, &directory))
111 return false;
113 if (sub_dir)
114 directory = base::MakeAbsoluteFilePath(directory.Append(sub_dir));
116 sandbox::ResultCode result;
117 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
118 directory.value().c_str());
119 if (result != sandbox::SBOX_ALL_OK)
120 return false;
122 std::wstring directory_str = directory.value() + L"\\";
123 if (children)
124 directory_str += L"*";
125 // Otherwise, add the version of the path that ends with a separator.
127 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
128 directory_str.c_str());
129 if (result != sandbox::SBOX_ALL_OK)
130 return false;
132 return true;
135 // Adds the policy rules for the path and path\* with the semantic |access|.
136 // We need to add the wildcard rules to also apply the rule to the subkeys.
137 bool AddKeyAndSubkeys(std::wstring key,
138 sandbox::TargetPolicy::Semantics access,
139 sandbox::TargetPolicy* policy) {
140 sandbox::ResultCode result;
141 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
142 key.c_str());
143 if (result != sandbox::SBOX_ALL_OK)
144 return false;
146 key += L"\\*";
147 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
148 key.c_str());
149 if (result != sandbox::SBOX_ALL_OK)
150 return false;
152 return true;
155 // Compares the loaded |module| file name matches |module_name|.
156 bool IsExpandedModuleName(HMODULE module, const wchar_t* module_name) {
157 wchar_t path[MAX_PATH];
158 DWORD sz = ::GetModuleFileNameW(module, path, arraysize(path));
159 if ((sz == arraysize(path)) || (sz == 0)) {
160 // XP does not set the last error properly, so we bail out anyway.
161 return false;
163 if (!::GetLongPathName(path, path, arraysize(path)))
164 return false;
165 base::FilePath fname(path);
166 return (fname.BaseName().value() == module_name);
169 // Adds a single dll by |module_name| into the |policy| blacklist.
170 // If |check_in_browser| is true we only add an unload policy only if the dll
171 // is also loaded in this process.
172 void BlacklistAddOneDll(const wchar_t* module_name,
173 bool check_in_browser,
174 sandbox::TargetPolicy* policy) {
175 HMODULE module = check_in_browser ? ::GetModuleHandleW(module_name) : NULL;
176 if (!module) {
177 // The module could have been loaded with a 8.3 short name. We check
178 // the three most common cases: 'thelongname.dll' becomes
179 // 'thelon~1.dll', 'thelon~2.dll' and 'thelon~3.dll'.
180 std::wstring name(module_name);
181 size_t period = name.rfind(L'.');
182 DCHECK_NE(std::string::npos, period);
183 DCHECK_LE(3U, (name.size() - period));
184 if (period <= 8)
185 return;
186 for (int ix = 0; ix < 3; ++ix) {
187 const wchar_t suffix[] = {'~', ('1' + ix), 0};
188 std::wstring alt_name = name.substr(0, 6) + suffix;
189 alt_name += name.substr(period, name.size());
190 if (check_in_browser) {
191 module = ::GetModuleHandleW(alt_name.c_str());
192 if (!module)
193 return;
194 // We found it, but because it only has 6 significant letters, we
195 // want to make sure it is the right one.
196 if (!IsExpandedModuleName(module, module_name))
197 return;
199 // Found a match. We add both forms to the policy.
200 policy->AddDllToUnload(alt_name.c_str());
203 policy->AddDllToUnload(module_name);
204 DVLOG(1) << "dll to unload found: " << module_name;
205 return;
208 // Adds policy rules for unloaded the known dlls that cause chrome to crash.
209 // Eviction of injected DLLs is done by the sandbox so that the injected module
210 // does not get a chance to execute any code.
211 void AddGenericDllEvictionPolicy(sandbox::TargetPolicy* policy) {
212 for (int ix = 0; ix != arraysize(kTroublesomeDlls); ++ix)
213 BlacklistAddOneDll(kTroublesomeDlls[ix], true, policy);
216 // Returns the object path prepended with the current logon session.
217 string16 PrependWindowsSessionPath(const char16* object) {
218 // Cache this because it can't change after process creation.
219 static uintptr_t s_session_id = 0;
220 if (s_session_id == 0) {
221 HANDLE token;
222 DWORD session_id_length;
223 DWORD session_id = 0;
225 CHECK(::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token));
226 CHECK(::GetTokenInformation(token, TokenSessionId, &session_id,
227 sizeof(session_id), &session_id_length));
228 CloseHandle(token);
229 if (session_id)
230 s_session_id = session_id;
233 return base::StringPrintf(L"\\Sessions\\%d%ls", s_session_id, object);
236 // Checks if the sandbox should be let to run without a job object assigned.
237 bool ShouldSetJobLevel(const CommandLine& cmd_line) {
238 if (!cmd_line.HasSwitch(switches::kAllowNoSandboxJob))
239 return true;
241 // Windows 8 allows nested jobs so we don't need to check if we are in other
242 // job.
243 if (base::win::GetVersion() >= base::win::VERSION_WIN8)
244 return true;
246 BOOL in_job = true;
247 // Either there is no job yet associated so we must add our job,
248 if (!::IsProcessInJob(::GetCurrentProcess(), NULL, &in_job))
249 NOTREACHED() << "IsProcessInJob failed. " << GetLastError();
250 if (!in_job)
251 return true;
253 // ...or there is a job but the JOB_OBJECT_LIMIT_BREAKAWAY_OK limit is set.
254 JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info = {0};
255 if (!::QueryInformationJobObject(NULL,
256 JobObjectExtendedLimitInformation, &job_info,
257 sizeof(job_info), NULL)) {
258 NOTREACHED() << "QueryInformationJobObject failed. " << GetLastError();
259 return true;
261 if (job_info.BasicLimitInformation.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK)
262 return true;
264 return false;
267 // Adds the generic policy rules to a sandbox TargetPolicy.
268 bool AddGenericPolicy(sandbox::TargetPolicy* policy) {
269 sandbox::ResultCode result;
271 // Renderers need to copy sections for plugin DIBs and GPU.
272 // GPU needs to copy sections to renderers.
273 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
274 sandbox::TargetPolicy::HANDLES_DUP_ANY,
275 L"Section");
276 if (result != sandbox::SBOX_ALL_OK)
277 return false;
279 // Add the policy for the client side of a pipe. It is just a file
280 // in the \pipe\ namespace. We restrict it to pipes that start with
281 // "chrome." so the sandboxed process cannot connect to system services.
282 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
283 sandbox::TargetPolicy::FILES_ALLOW_ANY,
284 L"\\??\\pipe\\chrome.*");
285 if (result != sandbox::SBOX_ALL_OK)
286 return false;
288 // Allow the server side of sync sockets, which are pipes that have
289 // the "chrome.sync" namespace and a randomly generated suffix.
290 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
291 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
292 L"\\\\.\\pipe\\chrome.sync.*");
293 if (result != sandbox::SBOX_ALL_OK)
294 return false;
296 // Add the policy for debug message only in debug
297 #ifndef NDEBUG
298 base::FilePath app_dir;
299 if (!PathService::Get(base::DIR_MODULE, &app_dir))
300 return false;
302 wchar_t long_path_buf[MAX_PATH];
303 DWORD long_path_return_value = GetLongPathName(app_dir.value().c_str(),
304 long_path_buf,
305 MAX_PATH);
306 if (long_path_return_value == 0 || long_path_return_value >= MAX_PATH)
307 return false;
309 base::FilePath debug_message(long_path_buf);
310 debug_message = debug_message.AppendASCII("debug_message.exe");
311 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_PROCESS,
312 sandbox::TargetPolicy::PROCESS_MIN_EXEC,
313 debug_message.value().c_str());
314 if (result != sandbox::SBOX_ALL_OK)
315 return false;
316 #endif // NDEBUG
318 AddGenericDllEvictionPolicy(policy);
320 return true;
323 bool AddPolicyForSandboxedProcess(sandbox::TargetPolicy* policy) {
324 sandbox::ResultCode result;
325 // Renderers need to share events with plugins.
326 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
327 sandbox::TargetPolicy::HANDLES_DUP_ANY,
328 L"Event");
329 if (result != sandbox::SBOX_ALL_OK)
330 return false;
332 sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED;
333 if (base::win::GetVersion() > base::win::VERSION_XP) {
334 // On 2003/Vista the initial token has to be restricted if the main
335 // token is restricted.
336 initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS;
339 policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN);
340 // Prevents the renderers from manipulating low-integrity processes.
341 policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
343 bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch(
344 switches::kDisableAltWinstation);
346 if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) {
347 DLOG(WARNING) << "Failed to apply desktop security to the renderer";
350 return true;
353 // Updates the command line arguments with debug-related flags. If debug flags
354 // have been used with this process, they will be filtered and added to
355 // command_line as needed. is_in_sandbox must be true if the child process will
356 // be in a sandbox.
358 // Returns true if the caller should "help" the child process by calling the JIT
359 // debugger on it. It may only happen if is_in_sandbox is true.
360 bool ProcessDebugFlags(CommandLine* command_line, bool is_in_sandbox) {
361 bool should_help_child = false;
362 const CommandLine& current_cmd_line = *CommandLine::ForCurrentProcess();
363 std::string type = command_line->GetSwitchValueASCII(switches::kProcessType);
364 if (current_cmd_line.HasSwitch(switches::kDebugChildren)) {
365 // Look to pass-on the kDebugOnStart flag.
366 std::string value = current_cmd_line.GetSwitchValueASCII(
367 switches::kDebugChildren);
368 if (value.empty() || value == type) {
369 command_line->AppendSwitch(switches::kDebugOnStart);
370 should_help_child = true;
372 command_line->AppendSwitchASCII(switches::kDebugChildren, value);
373 } else 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);
382 return should_help_child;
385 // This code is test only, and attempts to catch unsafe uses of
386 // DuplicateHandle() that copy privileged handles into sandboxed processes.
387 #ifndef OFFICIAL_BUILD
388 base::win::IATPatchFunction g_iat_patch_duplicate_handle;
390 BOOL (WINAPI *g_iat_orig_duplicate_handle)(HANDLE source_process_handle,
391 HANDLE source_handle,
392 HANDLE target_process_handle,
393 LPHANDLE target_handle,
394 DWORD desired_access,
395 BOOL inherit_handle,
396 DWORD options);
398 NtQueryObject g_QueryObject = NULL;
400 static const char* kDuplicateHandleWarning =
401 "You are attempting to duplicate a privileged handle into a sandboxed"
402 " process.\n Please use the sandbox::BrokerDuplicateHandle API or"
403 " contact security@chromium.org for assistance.";
405 void CheckDuplicateHandle(HANDLE handle) {
406 // Get the object type (32 characters is safe; current max is 14).
407 BYTE buffer[sizeof(OBJECT_TYPE_INFORMATION) + 32 * sizeof(wchar_t)];
408 OBJECT_TYPE_INFORMATION* type_info =
409 reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer);
410 ULONG size = sizeof(buffer) - sizeof(wchar_t);
411 NTSTATUS error;
412 error = g_QueryObject(handle, ObjectTypeInformation, type_info, size, &size);
413 CHECK(NT_SUCCESS(error));
414 type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
416 // Get the object basic information.
417 OBJECT_BASIC_INFORMATION basic_info;
418 size = sizeof(basic_info);
419 error = g_QueryObject(handle, ObjectBasicInformation, &basic_info, size,
420 &size);
421 CHECK(NT_SUCCESS(error));
423 if (0 == _wcsicmp(type_info->Name.Buffer, L"Process")) {
424 const ACCESS_MASK kDangerousMask = ~(PROCESS_QUERY_LIMITED_INFORMATION |
425 SYNCHRONIZE);
426 CHECK(!(basic_info.GrantedAccess & kDangerousMask)) <<
427 kDuplicateHandleWarning;
431 BOOL WINAPI DuplicateHandlePatch(HANDLE source_process_handle,
432 HANDLE source_handle,
433 HANDLE target_process_handle,
434 LPHANDLE target_handle,
435 DWORD desired_access,
436 BOOL inherit_handle,
437 DWORD options) {
438 // Duplicate the handle so we get the final access mask.
439 if (!g_iat_orig_duplicate_handle(source_process_handle, source_handle,
440 target_process_handle, target_handle,
441 desired_access, inherit_handle, options))
442 return FALSE;
444 // We're not worried about broker handles or not crossing process boundaries.
445 if (source_process_handle == target_process_handle ||
446 target_process_handle == ::GetCurrentProcess())
447 return TRUE;
449 // Only sandboxed children are placed in jobs, so just check them.
450 BOOL is_in_job = FALSE;
451 if (!::IsProcessInJob(target_process_handle, NULL, &is_in_job)) {
452 // We need a handle with permission to check the job object.
453 if (ERROR_ACCESS_DENIED == ::GetLastError()) {
454 base::win::ScopedHandle process;
455 CHECK(g_iat_orig_duplicate_handle(::GetCurrentProcess(),
456 target_process_handle,
457 ::GetCurrentProcess(),
458 process.Receive(),
459 PROCESS_QUERY_INFORMATION,
460 FALSE, 0));
461 CHECK(::IsProcessInJob(process, NULL, &is_in_job));
465 if (is_in_job) {
466 // We never allow inheritable child handles.
467 CHECK(!inherit_handle) << kDuplicateHandleWarning;
469 // Duplicate the handle again, to get the final permissions.
470 base::win::ScopedHandle handle;
471 CHECK(g_iat_orig_duplicate_handle(target_process_handle, *target_handle,
472 ::GetCurrentProcess(), handle.Receive(),
473 0, FALSE, DUPLICATE_SAME_ACCESS));
475 // Callers use CHECK macro to make sure we get the right stack.
476 CheckDuplicateHandle(handle);
479 return TRUE;
481 #endif
483 } // namespace
485 void SetJobLevel(const CommandLine& cmd_line,
486 sandbox::JobLevel job_level,
487 uint32 ui_exceptions,
488 sandbox::TargetPolicy* policy) {
489 if (ShouldSetJobLevel(cmd_line))
490 policy->SetJobLevel(job_level, ui_exceptions);
491 else
492 policy->SetJobLevel(sandbox::JOB_NONE, 0);
495 // TODO(jschuh): Need get these restrictions applied to NaCl and Pepper.
496 // Just have to figure out what needs to be warmed up first.
497 void AddBaseHandleClosePolicy(sandbox::TargetPolicy* policy) {
498 // Being able to manipulate anything BaseNamedObjects is bad.
499 string16 object_path = PrependWindowsSessionPath(L"\\BaseNamedObjects");
500 policy->AddKernelObjectToClose(L"Directory", object_path.data());
501 object_path = PrependWindowsSessionPath(
502 L"\\BaseNamedObjects\\windows_shell_global_counters");
503 policy->AddKernelObjectToClose(L"Section", object_path.data());
506 bool InitBrokerServices(sandbox::BrokerServices* broker_services) {
507 // TODO(abarth): DCHECK(CalledOnValidThread());
508 // See <http://b/1287166>.
509 DCHECK(broker_services);
510 DCHECK(!g_broker_services);
511 sandbox::ResultCode result = broker_services->Init();
512 g_broker_services = broker_services;
514 // In non-official builds warn about dangerous uses of DuplicateHandle.
515 #ifndef OFFICIAL_BUILD
516 BOOL is_in_job = FALSE;
517 CHECK(::IsProcessInJob(::GetCurrentProcess(), NULL, &is_in_job));
518 if (!is_in_job && !g_iat_patch_duplicate_handle.is_patched()) {
519 HMODULE module = NULL;
520 wchar_t module_name[MAX_PATH];
521 CHECK(::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
522 reinterpret_cast<LPCWSTR>(InitBrokerServices),
523 &module));
524 DWORD result = ::GetModuleFileNameW(module, module_name, MAX_PATH);
525 if (result && (result != MAX_PATH)) {
526 ResolveNTFunctionPtr("NtQueryObject", &g_QueryObject);
527 g_iat_orig_duplicate_handle = ::DuplicateHandle;
528 g_iat_patch_duplicate_handle.Patch(
529 module_name, "kernel32.dll", "DuplicateHandle",
530 DuplicateHandlePatch);
533 #endif
535 return sandbox::SBOX_ALL_OK == result;
538 bool InitTargetServices(sandbox::TargetServices* target_services) {
539 DCHECK(target_services);
540 DCHECK(!g_target_services);
541 sandbox::ResultCode result = target_services->Init();
542 g_target_services = target_services;
543 return sandbox::SBOX_ALL_OK == result;
546 base::ProcessHandle StartSandboxedProcess(
547 SandboxedProcessLauncherDelegate* delegate,
548 CommandLine* cmd_line) {
549 const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
550 std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
552 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
554 bool in_sandbox = true;
555 if (delegate)
556 delegate->ShouldSandbox(&in_sandbox);
558 if (browser_command_line.HasSwitch(switches::kNoSandbox) ||
559 cmd_line->HasSwitch(switches::kNoSandbox)) {
560 // The user or the caller has explicity opted-out from all sandboxing.
561 in_sandbox = false;
565 // Propagate the --allow-no-job flag if present.
566 if (browser_command_line.HasSwitch(switches::kAllowNoSandboxJob) &&
567 !cmd_line->HasSwitch(switches::kAllowNoSandboxJob)) {
568 cmd_line->AppendSwitch(switches::kAllowNoSandboxJob);
571 bool child_needs_help = ProcessDebugFlags(cmd_line, in_sandbox);
573 // Prefetch hints on windows:
574 // Using a different prefetch profile per process type will allow Windows
575 // to create separate pretetch settings for browser, renderer etc.
576 cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", base::Hash(type_str)));
578 if (!in_sandbox) {
579 base::ProcessHandle process = 0;
580 base::LaunchProcess(*cmd_line, base::LaunchOptions(), &process);
581 g_broker_services->AddTargetPeer(process);
582 return process;
585 base::win::ScopedProcessInformation target;
586 sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
588 sandbox::MitigationFlags mitigations = sandbox::MITIGATION_HEAP_TERMINATE |
589 sandbox::MITIGATION_BOTTOM_UP_ASLR |
590 sandbox::MITIGATION_DEP |
591 sandbox::MITIGATION_DEP_NO_ATL_THUNK |
592 sandbox::MITIGATION_SEHOP;
594 if (policy->SetProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
595 return 0;
597 mitigations = sandbox::MITIGATION_STRICT_HANDLE_CHECKS |
598 sandbox::MITIGATION_DLL_SEARCH_ORDER;
600 if (policy->SetDelayedProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
601 return 0;
603 SetJobLevel(*cmd_line, sandbox::JOB_LOCKDOWN, 0, policy);
605 bool disable_default_policy = false;
606 base::FilePath exposed_dir;
607 if (delegate)
608 delegate->PreSandbox(&disable_default_policy, &exposed_dir);
610 if (!disable_default_policy && !AddPolicyForSandboxedProcess(policy))
611 return 0;
613 if (type_str != switches::kRendererProcess) {
614 // Hack for Google Desktop crash. Trick GD into not injecting its DLL into
615 // this subprocess. See
616 // http://code.google.com/p/chromium/issues/detail?id=25580
617 cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
620 sandbox::ResultCode result;
621 if (!exposed_dir.empty()) {
622 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
623 sandbox::TargetPolicy::FILES_ALLOW_ANY,
624 exposed_dir.value().c_str());
625 if (result != sandbox::SBOX_ALL_OK)
626 return 0;
628 base::FilePath exposed_files = exposed_dir.AppendASCII("*");
629 result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
630 sandbox::TargetPolicy::FILES_ALLOW_ANY,
631 exposed_files.value().c_str());
632 if (result != sandbox::SBOX_ALL_OK)
633 return 0;
636 if (!AddGenericPolicy(policy)) {
637 NOTREACHED();
638 return 0;
641 if (browser_command_line.HasSwitch(switches::kEnableLogging)) {
642 // If stdout/stderr point to a Windows console, these calls will
643 // have no effect.
644 policy->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE));
645 policy->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE));
648 if (delegate) {
649 bool success = true;
650 delegate->PreSpawnTarget(policy, &success);
651 if (!success)
652 return 0;
655 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
657 result = g_broker_services->SpawnTarget(
658 cmd_line->GetProgram().value().c_str(),
659 cmd_line->GetCommandLineString().c_str(),
660 policy, target.Receive());
661 policy->Release();
663 TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
665 if (sandbox::SBOX_ALL_OK != result) {
666 DLOG(ERROR) << "Failed to launch process. Error: " << result;
667 return 0;
670 if (delegate)
671 delegate->PostSpawnTarget(target.process_handle());
674 ResumeThread(target.thread_handle());
676 // Help the process a little. It can't start the debugger by itself if
677 // the process is in a sandbox.
678 if (child_needs_help)
679 base::debug::SpawnDebuggerOnProcess(target.process_id());
681 return target.TakeProcessHandle();
684 bool BrokerDuplicateHandle(HANDLE source_handle,
685 DWORD target_process_id,
686 HANDLE* target_handle,
687 DWORD desired_access,
688 DWORD options) {
689 // If our process is the target just duplicate the handle.
690 if (::GetCurrentProcessId() == target_process_id) {
691 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
692 ::GetCurrentProcess(), target_handle,
693 desired_access, FALSE, options);
697 // Try the broker next
698 if (g_target_services &&
699 g_target_services->DuplicateHandle(source_handle, target_process_id,
700 target_handle, desired_access,
701 options) == sandbox::SBOX_ALL_OK) {
702 return true;
705 // Finally, see if we already have access to the process.
706 base::win::ScopedHandle target_process;
707 target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE,
708 target_process_id));
709 if (target_process.IsValid()) {
710 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
711 target_process, target_handle,
712 desired_access, FALSE, options);
715 return false;
718 bool BrokerAddTargetPeer(HANDLE peer_process) {
719 return g_broker_services->AddTargetPeer(peer_process) == sandbox::SBOX_ALL_OK;
722 } // namespace content