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"
9 #include "base/base_switches.h"
10 #include "base/command_line.h"
11 #include "base/debug/profiler.h"
12 #include "base/files/file_util.h"
13 #include "base/hash.h"
14 #include "base/metrics/sparse_histogram.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/trace_event/trace_event.h"
20 #include "base/win/iat_patch_function.h"
21 #include "base/win/scoped_handle.h"
22 #include "base/win/scoped_process_information.h"
23 #include "base/win/windows_version.h"
24 #include "content/common/content_switches_internal.h"
25 #include "content/public/common/content_client.h"
26 #include "content/public/common/content_switches.h"
27 #include "content/public/common/sandbox_init.h"
28 #include "content/public/common/sandboxed_process_launcher_delegate.h"
29 #include "sandbox/win/src/process_mitigations.h"
30 #include "sandbox/win/src/sandbox.h"
31 #include "sandbox/win/src/sandbox_nt_util.h"
32 #include "sandbox/win/src/sandbox_policy_base.h"
33 #include "sandbox/win/src/win_utils.h"
34 #include "ui/gfx/win/direct_write.h"
36 static sandbox::BrokerServices
* g_broker_services
= NULL
;
37 static sandbox::TargetServices
* g_target_services
= NULL
;
42 // The DLLs listed here are known (or under strong suspicion) of causing crashes
43 // when they are loaded in the renderer. Note: at runtime we generate short
44 // versions of the dll name only if the dll has an extension.
45 // For more information about how this list is generated, and how to get off
47 // https://sites.google.com/a/chromium.org/dev/Home/third-party-developers
48 const wchar_t* const kTroublesomeDlls
[] = {
49 L
"adialhk.dll", // Kaspersky Internet Security.
50 L
"acpiz.dll", // Unknown.
51 L
"airfoilinject3.dll", // Airfoil.
52 L
"akinsofthook32.dll", // Akinsoft Software Engineering.
53 L
"assistant_x64.dll", // Unknown.
54 L
"avcuf64.dll", // Bit Defender Internet Security x64.
55 L
"avgrsstx.dll", // AVG 8.
56 L
"babylonchromepi.dll", // Babylon translator.
57 L
"btkeyind.dll", // Widcomm Bluetooth.
58 L
"cmcsyshk.dll", // CMC Internet Security.
59 L
"cmsetac.dll", // Unknown (suspected malware).
60 L
"cooliris.dll", // CoolIris.
61 L
"dockshellhook.dll", // Stardock Objectdock.
62 L
"easyhook32.dll", // GDIPP and others.
63 L
"esspd.dll", // Samsung Smart Security ESCORT.
64 L
"googledesktopnetwork3.dll", // Google Desktop Search v5.
65 L
"fwhook.dll", // PC Tools Firewall Plus.
66 L
"hookprocesscreation.dll", // Blumentals Program protector.
67 L
"hookterminateapis.dll", // Blumentals and Cyberprinter.
68 L
"hookprintapis.dll", // Cyberprinter.
69 L
"imon.dll", // NOD32 Antivirus.
70 L
"icatcdll.dll", // Samsung Smart Security ESCORT.
71 L
"icdcnl.dll", // Samsung Smart Security ESCORT.
72 L
"ioloHL.dll", // Iolo (System Mechanic).
73 L
"kloehk.dll", // Kaspersky Internet Security.
74 L
"lawenforcer.dll", // Spyware-Browser AntiSpyware (Spybro).
75 L
"libdivx.dll", // DivX.
76 L
"lvprcinj01.dll", // Logitech QuickCam.
77 L
"madchook.dll", // Madshi (generic hooking library).
78 L
"mdnsnsp.dll", // Bonjour.
79 L
"moonsysh.dll", // Moon Secure Antivirus.
80 L
"mpk.dll", // KGB Spy.
81 L
"npdivx32.dll", // DivX.
82 L
"npggNT.des", // GameGuard 2008.
83 L
"npggNT.dll", // GameGuard (older).
84 L
"oawatch.dll", // Online Armor.
85 L
"pastali32.dll", // PastaLeads.
86 L
"pavhook.dll", // Panda Internet Security.
87 L
"pavlsphook.dll", // Panda Antivirus.
88 L
"pavshook.dll", // Panda Antivirus.
89 L
"pavshookwow.dll", // Panda Antivirus.
90 L
"pctavhook.dll", // PC Tools Antivirus.
91 L
"pctgmhk.dll", // PC Tools Spyware Doctor.
92 L
"picrmi32.dll", // PicRec.
93 L
"picrmi64.dll", // PicRec.
94 L
"prntrack.dll", // Pharos Systems.
95 L
"protector.dll", // Unknown (suspected malware).
96 L
"radhslib.dll", // Radiant Naomi Internet Filter.
97 L
"radprlib.dll", // Radiant Naomi Internet Filter.
98 L
"rapportnikko.dll", // Trustware Rapport.
99 L
"rlhook.dll", // Trustware Bufferzone.
100 L
"rooksdol.dll", // Trustware Rapport.
101 L
"rndlpepperbrowserrecordhelper.dll", // RealPlayer.
102 L
"rpchromebrowserrecordhelper.dll", // RealPlayer.
103 L
"r3hook.dll", // Kaspersky Internet Security.
104 L
"sahook.dll", // McAfee Site Advisor.
105 L
"sbrige.dll", // Unknown.
106 L
"sc2hook.dll", // Supercopier 2.
107 L
"sdhook32.dll", // Spybot - Search & Destroy Live Protection.
108 L
"sguard.dll", // Iolo (System Guard).
109 L
"smum32.dll", // Spyware Doctor version 6.
110 L
"smumhook.dll", // Spyware Doctor version 5.
111 L
"ssldivx.dll", // DivX.
112 L
"syncor11.dll", // SynthCore Midi interface.
113 L
"systools.dll", // Panda Antivirus.
114 L
"tfwah.dll", // Threatfire (PC tools).
115 L
"wblind.dll", // Stardock Object desktop.
116 L
"wbhelp.dll", // Stardock Object desktop.
117 L
"winstylerthemehelper.dll" // Tuneup utilities 2006.
120 // Adds the policy rules for the path and path\ with the semantic |access|.
121 // If |children| is set to true, we need to add the wildcard rules to also
122 // apply the rule to the subfiles and subfolders.
123 bool AddDirectory(int path
, const wchar_t* sub_dir
, bool children
,
124 sandbox::TargetPolicy::Semantics access
,
125 sandbox::TargetPolicy
* policy
) {
126 base::FilePath directory
;
127 if (!PathService::Get(path
, &directory
))
131 directory
= base::MakeAbsoluteFilePath(directory
.Append(sub_dir
));
133 sandbox::ResultCode result
;
134 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
, access
,
135 directory
.value().c_str());
136 if (result
!= sandbox::SBOX_ALL_OK
)
139 std::wstring directory_str
= directory
.value() + L
"\\";
141 directory_str
+= L
"*";
142 // Otherwise, add the version of the path that ends with a separator.
144 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
, access
,
145 directory_str
.c_str());
146 if (result
!= sandbox::SBOX_ALL_OK
)
152 // Adds the policy rules for the path and path\* with the semantic |access|.
153 // We need to add the wildcard rules to also apply the rule to the subkeys.
154 bool AddKeyAndSubkeys(std::wstring key
,
155 sandbox::TargetPolicy::Semantics access
,
156 sandbox::TargetPolicy
* policy
) {
157 sandbox::ResultCode result
;
158 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY
, access
,
160 if (result
!= sandbox::SBOX_ALL_OK
)
164 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY
, access
,
166 if (result
!= sandbox::SBOX_ALL_OK
)
172 // Compares the loaded |module| file name matches |module_name|.
173 bool IsExpandedModuleName(HMODULE module
, const wchar_t* module_name
) {
174 wchar_t path
[MAX_PATH
];
175 DWORD sz
= ::GetModuleFileNameW(module
, path
, arraysize(path
));
176 if ((sz
== arraysize(path
)) || (sz
== 0)) {
177 // XP does not set the last error properly, so we bail out anyway.
180 if (!::GetLongPathName(path
, path
, arraysize(path
)))
182 base::FilePath
fname(path
);
183 return (fname
.BaseName().value() == module_name
);
186 // Adds a single dll by |module_name| into the |policy| blacklist.
187 // If |check_in_browser| is true we only add an unload policy only if the dll
188 // is also loaded in this process.
189 void BlacklistAddOneDll(const wchar_t* module_name
,
190 bool check_in_browser
,
191 sandbox::TargetPolicy
* policy
) {
192 HMODULE module
= check_in_browser
? ::GetModuleHandleW(module_name
) : NULL
;
194 // The module could have been loaded with a 8.3 short name. We check
195 // the three most common cases: 'thelongname.dll' becomes
196 // 'thelon~1.dll', 'thelon~2.dll' and 'thelon~3.dll'.
197 std::wstring
name(module_name
);
198 size_t period
= name
.rfind(L
'.');
199 DCHECK_NE(std::string::npos
, period
);
200 DCHECK_LE(3U, (name
.size() - period
));
203 for (wchar_t ix
= '1'; ix
<= '3'; ++ix
) {
204 const wchar_t suffix
[] = {'~', ix
, 0};
205 std::wstring alt_name
= name
.substr(0, 6) + suffix
;
206 alt_name
+= name
.substr(period
, name
.size());
207 if (check_in_browser
) {
208 module
= ::GetModuleHandleW(alt_name
.c_str());
211 // We found it, but because it only has 6 significant letters, we
212 // want to make sure it is the right one.
213 if (!IsExpandedModuleName(module
, module_name
))
216 // Found a match. We add both forms to the policy.
217 policy
->AddDllToUnload(alt_name
.c_str());
220 policy
->AddDllToUnload(module_name
);
221 DVLOG(1) << "dll to unload found: " << module_name
;
225 // Adds policy rules for unloaded the known dlls that cause chrome to crash.
226 // Eviction of injected DLLs is done by the sandbox so that the injected module
227 // does not get a chance to execute any code.
228 void AddGenericDllEvictionPolicy(sandbox::TargetPolicy
* policy
) {
229 for (int ix
= 0; ix
!= arraysize(kTroublesomeDlls
); ++ix
)
230 BlacklistAddOneDll(kTroublesomeDlls
[ix
], true, policy
);
233 // Returns the object path prepended with the current logon session.
234 base::string16
PrependWindowsSessionPath(const base::char16
* object
) {
235 // Cache this because it can't change after process creation.
236 static uintptr_t s_session_id
= 0;
237 if (s_session_id
== 0) {
239 DWORD session_id_length
;
240 DWORD session_id
= 0;
242 CHECK(::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY
, &token
));
243 CHECK(::GetTokenInformation(token
, TokenSessionId
, &session_id
,
244 sizeof(session_id
), &session_id_length
));
247 s_session_id
= session_id
;
250 return base::StringPrintf(L
"\\Sessions\\%d%ls", s_session_id
, object
);
253 // Checks if the sandbox should be let to run without a job object assigned.
254 bool ShouldSetJobLevel(const base::CommandLine
& cmd_line
) {
255 if (!cmd_line
.HasSwitch(switches::kAllowNoSandboxJob
))
258 // Windows 8 allows nested jobs so we don't need to check if we are in other
260 if (base::win::GetVersion() >= base::win::VERSION_WIN8
)
264 // Either there is no job yet associated so we must add our job,
265 if (!::IsProcessInJob(::GetCurrentProcess(), NULL
, &in_job
))
266 NOTREACHED() << "IsProcessInJob failed. " << GetLastError();
270 // ...or there is a job but the JOB_OBJECT_LIMIT_BREAKAWAY_OK limit is set.
271 JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info
= {0};
272 if (!::QueryInformationJobObject(NULL
,
273 JobObjectExtendedLimitInformation
, &job_info
,
274 sizeof(job_info
), NULL
)) {
275 NOTREACHED() << "QueryInformationJobObject failed. " << GetLastError();
278 if (job_info
.BasicLimitInformation
.LimitFlags
& JOB_OBJECT_LIMIT_BREAKAWAY_OK
)
284 // Adds the generic policy rules to a sandbox TargetPolicy.
285 bool AddGenericPolicy(sandbox::TargetPolicy
* policy
) {
286 sandbox::ResultCode result
;
288 // Renderers need to copy sections for plugin DIBs and GPU.
289 // GPU needs to copy sections to renderers.
290 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES
,
291 sandbox::TargetPolicy::HANDLES_DUP_ANY
,
293 if (result
!= sandbox::SBOX_ALL_OK
)
296 // Add the policy for the client side of a pipe. It is just a file
297 // in the \pipe\ namespace. We restrict it to pipes that start with
298 // "chrome." so the sandboxed process cannot connect to system services.
299 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
300 sandbox::TargetPolicy::FILES_ALLOW_ANY
,
301 L
"\\??\\pipe\\chrome.*");
302 if (result
!= sandbox::SBOX_ALL_OK
)
305 // Add the policy for the server side of nacl pipe. It is just a file
306 // in the \pipe\ namespace. We restrict it to pipes that start with
307 // "chrome.nacl" so the sandboxed process cannot connect to
309 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES
,
310 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY
,
311 L
"\\\\.\\pipe\\chrome.nacl.*");
312 if (result
!= sandbox::SBOX_ALL_OK
)
315 // Allow the server side of sync sockets, which are pipes that have
316 // the "chrome.sync" namespace and a randomly generated suffix.
317 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES
,
318 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY
,
319 L
"\\\\.\\pipe\\chrome.sync.*");
320 if (result
!= sandbox::SBOX_ALL_OK
)
323 // Add the policy for debug message only in debug
325 base::FilePath app_dir
;
326 if (!PathService::Get(base::DIR_MODULE
, &app_dir
))
329 wchar_t long_path_buf
[MAX_PATH
];
330 DWORD long_path_return_value
= GetLongPathName(app_dir
.value().c_str(),
333 if (long_path_return_value
== 0 || long_path_return_value
>= MAX_PATH
)
336 base::FilePath
debug_message(long_path_buf
);
337 debug_message
= debug_message
.AppendASCII("debug_message.exe");
338 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_PROCESS
,
339 sandbox::TargetPolicy::PROCESS_MIN_EXEC
,
340 debug_message
.value().c_str());
341 if (result
!= sandbox::SBOX_ALL_OK
)
345 // Add the policy for read-only PDB file access for AddressSanitizer.
346 #if defined(ADDRESS_SANITIZER)
348 if (!PathService::Get(base::FILE_EXE
, &exe
))
350 base::FilePath pdb_path
= exe
.DirName().Append(L
"*.pdb");
351 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
352 sandbox::TargetPolicy::FILES_ALLOW_READONLY
,
353 pdb_path
.value().c_str());
354 if (result
!= sandbox::SBOX_ALL_OK
)
358 AddGenericDllEvictionPolicy(policy
);
362 bool AddPolicyForSandboxedProcess(sandbox::TargetPolicy
* policy
) {
363 sandbox::ResultCode result
;
364 // Renderers need to share events with plugins.
365 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES
,
366 sandbox::TargetPolicy::HANDLES_DUP_ANY
,
368 if (result
!= sandbox::SBOX_ALL_OK
)
371 // Win8+ adds a device DeviceApi that we don't need.
372 if (base::win::GetVersion() > base::win::VERSION_WIN7
)
373 result
= policy
->AddKernelObjectToClose(L
"File", L
"\\Device\\DeviceApi");
374 if (result
!= sandbox::SBOX_ALL_OK
)
377 // Close the proxy settings on XP.
378 if (base::win::GetVersion() <= base::win::VERSION_SERVER_2003
)
379 result
= policy
->AddKernelObjectToClose(L
"Key",
380 L
"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\" \
381 L
"CurrentVersion\\Internet Settings");
382 if (result
!= sandbox::SBOX_ALL_OK
)
386 sandbox::TokenLevel initial_token
= sandbox::USER_UNPROTECTED
;
387 if (base::win::GetVersion() > base::win::VERSION_XP
) {
388 // On 2003/Vista the initial token has to be restricted if the main
389 // token is restricted.
390 initial_token
= sandbox::USER_RESTRICTED_SAME_ACCESS
;
393 policy
->SetTokenLevel(initial_token
, sandbox::USER_LOCKDOWN
);
394 // Prevents the renderers from manipulating low-integrity processes.
395 policy
->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED
);
396 policy
->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
398 if (sandbox::SBOX_ALL_OK
!= policy
->SetAlternateDesktop(true)) {
399 DLOG(WARNING
) << "Failed to apply desktop security to the renderer";
405 // Updates the command line arguments with debug-related flags. If debug flags
406 // have been used with this process, they will be filtered and added to
407 // command_line as needed.
408 void ProcessDebugFlags(base::CommandLine
* command_line
) {
409 const base::CommandLine
& current_cmd_line
=
410 *base::CommandLine::ForCurrentProcess();
411 std::string type
= command_line
->GetSwitchValueASCII(switches::kProcessType
);
412 if (current_cmd_line
.HasSwitch(switches::kWaitForDebuggerChildren
)) {
413 // Look to pass-on the kWaitForDebugger flag.
414 std::string value
= current_cmd_line
.GetSwitchValueASCII(
415 switches::kWaitForDebuggerChildren
);
416 if (value
.empty() || value
== type
) {
417 command_line
->AppendSwitch(switches::kWaitForDebugger
);
419 command_line
->AppendSwitchASCII(switches::kWaitForDebuggerChildren
, value
);
423 // This code is test only, and attempts to catch unsafe uses of
424 // DuplicateHandle() that copy privileged handles into sandboxed processes.
425 #ifndef OFFICIAL_BUILD
426 base::win::IATPatchFunction g_iat_patch_duplicate_handle
;
428 typedef BOOL (WINAPI
*DuplicateHandleFunctionPtr
)(HANDLE source_process_handle
,
429 HANDLE source_handle
,
430 HANDLE target_process_handle
,
431 LPHANDLE target_handle
,
432 DWORD desired_access
,
436 DuplicateHandleFunctionPtr g_iat_orig_duplicate_handle
;
438 NtQueryObject g_QueryObject
= NULL
;
440 static const char* kDuplicateHandleWarning
=
441 "You are attempting to duplicate a privileged handle into a sandboxed"
442 " process.\n Please use the sandbox::BrokerDuplicateHandle API or"
443 " contact security@chromium.org for assistance.";
445 void CheckDuplicateHandle(HANDLE handle
) {
446 // Get the object type (32 characters is safe; current max is 14).
447 BYTE buffer
[sizeof(OBJECT_TYPE_INFORMATION
) + 32 * sizeof(wchar_t)];
448 OBJECT_TYPE_INFORMATION
* type_info
=
449 reinterpret_cast<OBJECT_TYPE_INFORMATION
*>(buffer
);
450 ULONG size
= sizeof(buffer
) - sizeof(wchar_t);
452 error
= g_QueryObject(handle
, ObjectTypeInformation
, type_info
, size
, &size
);
453 CHECK(NT_SUCCESS(error
));
454 type_info
->Name
.Buffer
[type_info
->Name
.Length
/ sizeof(wchar_t)] = L
'\0';
456 // Get the object basic information.
457 OBJECT_BASIC_INFORMATION basic_info
;
458 size
= sizeof(basic_info
);
459 error
= g_QueryObject(handle
, ObjectBasicInformation
, &basic_info
, size
,
461 CHECK(NT_SUCCESS(error
));
463 CHECK(!(basic_info
.GrantedAccess
& WRITE_DAC
)) <<
464 kDuplicateHandleWarning
;
466 if (0 == _wcsicmp(type_info
->Name
.Buffer
, L
"Process")) {
467 const ACCESS_MASK kDangerousMask
=
468 ~static_cast<DWORD
>(PROCESS_QUERY_LIMITED_INFORMATION
| SYNCHRONIZE
);
469 CHECK(!(basic_info
.GrantedAccess
& kDangerousMask
)) <<
470 kDuplicateHandleWarning
;
474 BOOL WINAPI
DuplicateHandlePatch(HANDLE source_process_handle
,
475 HANDLE source_handle
,
476 HANDLE target_process_handle
,
477 LPHANDLE target_handle
,
478 DWORD desired_access
,
481 // Duplicate the handle so we get the final access mask.
482 if (!g_iat_orig_duplicate_handle(source_process_handle
, source_handle
,
483 target_process_handle
, target_handle
,
484 desired_access
, inherit_handle
, options
))
487 // We're not worried about broker handles or not crossing process boundaries.
488 if (source_process_handle
== target_process_handle
||
489 target_process_handle
== ::GetCurrentProcess())
492 // Only sandboxed children are placed in jobs, so just check them.
493 BOOL is_in_job
= FALSE
;
494 if (!::IsProcessInJob(target_process_handle
, NULL
, &is_in_job
)) {
495 // We need a handle with permission to check the job object.
496 if (ERROR_ACCESS_DENIED
== ::GetLastError()) {
498 CHECK(g_iat_orig_duplicate_handle(::GetCurrentProcess(),
499 target_process_handle
,
500 ::GetCurrentProcess(),
502 PROCESS_QUERY_INFORMATION
,
504 base::win::ScopedHandle
process(temp_handle
);
505 CHECK(::IsProcessInJob(process
.Get(), NULL
, &is_in_job
));
510 // We never allow inheritable child handles.
511 CHECK(!inherit_handle
) << kDuplicateHandleWarning
;
513 // Duplicate the handle again, to get the final permissions.
515 CHECK(g_iat_orig_duplicate_handle(target_process_handle
, *target_handle
,
516 ::GetCurrentProcess(), &temp_handle
,
517 0, FALSE
, DUPLICATE_SAME_ACCESS
));
518 base::win::ScopedHandle
handle(temp_handle
);
520 // Callers use CHECK macro to make sure we get the right stack.
521 CheckDuplicateHandle(handle
.Get());
530 void SetJobLevel(const base::CommandLine
& cmd_line
,
531 sandbox::JobLevel job_level
,
532 uint32 ui_exceptions
,
533 sandbox::TargetPolicy
* policy
) {
534 if (ShouldSetJobLevel(cmd_line
)) {
536 policy
->SetJobMemoryLimit(4ULL * 1024 * 1024 * 1024);
538 policy
->SetJobLevel(job_level
, ui_exceptions
);
540 policy
->SetJobLevel(sandbox::JOB_NONE
, 0);
544 // TODO(jschuh): Need get these restrictions applied to NaCl and Pepper.
545 // Just have to figure out what needs to be warmed up first.
546 void AddBaseHandleClosePolicy(sandbox::TargetPolicy
* policy
) {
547 // TODO(cpu): Add back the BaseNamedObjects policy.
548 base::string16 object_path
= PrependWindowsSessionPath(
549 L
"\\BaseNamedObjects\\windows_shell_global_counters");
550 policy
->AddKernelObjectToClose(L
"Section", object_path
.data());
553 bool InitBrokerServices(sandbox::BrokerServices
* broker_services
) {
554 // TODO(abarth): DCHECK(CalledOnValidThread());
555 // See <http://b/1287166>.
556 DCHECK(broker_services
);
557 DCHECK(!g_broker_services
);
558 sandbox::ResultCode result
= broker_services
->Init();
559 g_broker_services
= broker_services
;
561 // In non-official builds warn about dangerous uses of DuplicateHandle.
562 #ifndef OFFICIAL_BUILD
563 BOOL is_in_job
= FALSE
;
564 CHECK(::IsProcessInJob(::GetCurrentProcess(), NULL
, &is_in_job
));
565 // In a Syzygy-profiled binary, instrumented for import profiling, this
566 // patch will end in infinite recursion on the attempted delegation to the
567 // original function.
568 if (!base::debug::IsBinaryInstrumented() &&
569 !is_in_job
&& !g_iat_patch_duplicate_handle
.is_patched()) {
570 HMODULE module
= NULL
;
571 wchar_t module_name
[MAX_PATH
];
572 CHECK(::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
,
573 reinterpret_cast<LPCWSTR
>(InitBrokerServices
),
575 DWORD result
= ::GetModuleFileNameW(module
, module_name
, MAX_PATH
);
576 if (result
&& (result
!= MAX_PATH
)) {
577 ResolveNTFunctionPtr("NtQueryObject", &g_QueryObject
);
578 result
= g_iat_patch_duplicate_handle
.Patch(
579 module_name
, "kernel32.dll", "DuplicateHandle",
580 DuplicateHandlePatch
);
582 g_iat_orig_duplicate_handle
=
583 reinterpret_cast<DuplicateHandleFunctionPtr
>(
584 g_iat_patch_duplicate_handle
.original_function());
589 return sandbox::SBOX_ALL_OK
== result
;
592 bool InitTargetServices(sandbox::TargetServices
* target_services
) {
593 DCHECK(target_services
);
594 DCHECK(!g_target_services
);
595 sandbox::ResultCode result
= target_services
->Init();
596 g_target_services
= target_services
;
597 return sandbox::SBOX_ALL_OK
== result
;
600 base::Process
StartSandboxedProcess(
601 SandboxedProcessLauncherDelegate
* delegate
,
602 base::CommandLine
* cmd_line
) {
603 const base::CommandLine
& browser_command_line
=
604 *base::CommandLine::ForCurrentProcess();
605 std::string type_str
= cmd_line
->GetSwitchValueASCII(switches::kProcessType
);
607 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str
);
609 // Propagate the --allow-no-job flag if present.
610 if (browser_command_line
.HasSwitch(switches::kAllowNoSandboxJob
) &&
611 !cmd_line
->HasSwitch(switches::kAllowNoSandboxJob
)) {
612 cmd_line
->AppendSwitch(switches::kAllowNoSandboxJob
);
615 ProcessDebugFlags(cmd_line
);
617 // Prefetch hints on windows:
618 // Using a different prefetch profile per process type will allow Windows
619 // to create separate pretetch settings for browser, renderer etc.
620 cmd_line
->AppendArg(base::StringPrintf("/prefetch:%d", base::Hash(type_str
)));
622 if ((delegate
&& !delegate
->ShouldSandbox()) ||
623 browser_command_line
.HasSwitch(switches::kNoSandbox
) ||
624 cmd_line
->HasSwitch(switches::kNoSandbox
)) {
625 base::Process process
=
626 base::LaunchProcess(*cmd_line
, base::LaunchOptions());
627 // TODO(rvargas) crbug.com/417532: Don't share a raw handle.
628 g_broker_services
->AddTargetPeer(process
.Handle());
629 return process
.Pass();
632 sandbox::TargetPolicy
* policy
= g_broker_services
->CreatePolicy();
634 sandbox::MitigationFlags mitigations
= sandbox::MITIGATION_HEAP_TERMINATE
|
635 sandbox::MITIGATION_BOTTOM_UP_ASLR
|
636 sandbox::MITIGATION_DEP
|
637 sandbox::MITIGATION_DEP_NO_ATL_THUNK
|
638 sandbox::MITIGATION_SEHOP
;
640 #if !defined(NACL_WIN64)
641 if (type_str
== switches::kRendererProcess
&&
642 IsWin32kRendererLockdownEnabled()) {
643 if (policy
->AddRule(sandbox::TargetPolicy::SUBSYS_WIN32K_LOCKDOWN
,
644 sandbox::TargetPolicy::FAKE_USER_GDI_INIT
,
645 NULL
) != sandbox::SBOX_ALL_OK
) {
646 return base::Process();
648 mitigations
|= sandbox::MITIGATION_WIN32K_DISABLE
;
652 if (policy
->SetProcessMitigations(mitigations
) != sandbox::SBOX_ALL_OK
)
653 return base::Process();
655 mitigations
= sandbox::MITIGATION_STRICT_HANDLE_CHECKS
|
656 sandbox::MITIGATION_DLL_SEARCH_ORDER
;
658 if (policy
->SetDelayedProcessMitigations(mitigations
) != sandbox::SBOX_ALL_OK
)
659 return base::Process();
661 SetJobLevel(*cmd_line
, sandbox::JOB_LOCKDOWN
, 0, policy
);
663 bool disable_default_policy
= false;
664 base::FilePath exposed_dir
;
666 delegate
->PreSandbox(&disable_default_policy
, &exposed_dir
);
668 if (!disable_default_policy
&& !AddPolicyForSandboxedProcess(policy
))
669 return base::Process();
671 if (type_str
== switches::kRendererProcess
) {
672 #if !defined(NACL_WIN64)
673 if (gfx::win::ShouldUseDirectWrite()) {
674 AddDirectory(base::DIR_WINDOWS_FONTS
,
677 sandbox::TargetPolicy::FILES_ALLOW_READONLY
,
682 // Hack for Google Desktop crash. Trick GD into not injecting its DLL into
683 // this subprocess. See
684 // http://code.google.com/p/chromium/issues/detail?id=25580
685 cmd_line
->AppendSwitchASCII("ignored", " --type=renderer ");
688 sandbox::ResultCode result
;
689 if (!exposed_dir
.empty()) {
690 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
691 sandbox::TargetPolicy::FILES_ALLOW_ANY
,
692 exposed_dir
.value().c_str());
693 if (result
!= sandbox::SBOX_ALL_OK
)
694 return base::Process();
696 base::FilePath exposed_files
= exposed_dir
.AppendASCII("*");
697 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
698 sandbox::TargetPolicy::FILES_ALLOW_ANY
,
699 exposed_files
.value().c_str());
700 if (result
!= sandbox::SBOX_ALL_OK
)
701 return base::Process();
704 if (!AddGenericPolicy(policy
)) {
706 return base::Process();
709 if (browser_command_line
.HasSwitch(switches::kEnableLogging
)) {
710 // If stdout/stderr point to a Windows console, these calls will
712 policy
->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE
));
713 policy
->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE
));
718 delegate
->PreSpawnTarget(policy
, &success
);
720 return base::Process();
723 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
725 PROCESS_INFORMATION temp_process_info
= {};
726 result
= g_broker_services
->SpawnTarget(
727 cmd_line
->GetProgram().value().c_str(),
728 cmd_line
->GetCommandLineString().c_str(),
729 policy
, &temp_process_info
);
730 DWORD last_error
= ::GetLastError();
732 base::win::ScopedProcessInformation
target(temp_process_info
);
734 TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
736 if (sandbox::SBOX_ALL_OK
!= result
) {
737 if (result
== sandbox::SBOX_ERROR_GENERIC
)
738 DPLOG(ERROR
) << "Failed to launch process";
739 else if (result
== sandbox::SBOX_ERROR_CREATE_PROCESS
) {
740 // TODO(shrikant): Remove this special case handling after determining
741 // cause for lowbox/createprocess errors.
742 sandbox::PolicyBase
* policy_base
=
743 static_cast<sandbox::PolicyBase
*>(policy
);
744 UMA_HISTOGRAM_SPARSE_SLOWLY(policy_base
->GetLowBoxSid() ?
745 "Process.Sandbox.Lowbox.Launch.Error" :
746 "Process.Sandbox.Launch.Error",
749 DLOG(ERROR
) << "Failed to launch process. Error: " << result
;
750 return base::Process();
754 delegate
->PostSpawnTarget(target
.process_handle());
756 CHECK(ResumeThread(target
.thread_handle()) != -1);
757 TRACE_EVENT_END_ETW("StartProcessWithAccess", 0, type_str
);
758 return base::Process(target
.TakeProcessHandle());
761 bool BrokerDuplicateHandle(HANDLE source_handle
,
762 DWORD target_process_id
,
763 HANDLE
* target_handle
,
764 DWORD desired_access
,
766 // If our process is the target just duplicate the handle.
767 if (::GetCurrentProcessId() == target_process_id
) {
768 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle
,
769 ::GetCurrentProcess(), target_handle
,
770 desired_access
, FALSE
, options
);
774 // Try the broker next
775 if (g_target_services
&&
776 g_target_services
->DuplicateHandle(source_handle
, target_process_id
,
777 target_handle
, desired_access
,
778 options
) == sandbox::SBOX_ALL_OK
) {
782 // Finally, see if we already have access to the process.
783 base::win::ScopedHandle target_process
;
784 target_process
.Set(::OpenProcess(PROCESS_DUP_HANDLE
, FALSE
,
786 if (target_process
.IsValid()) {
787 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle
,
788 target_process
.Get(), target_handle
,
789 desired_access
, FALSE
, options
);
795 bool BrokerAddTargetPeer(HANDLE peer_process
) {
796 return g_broker_services
->AddTargetPeer(peer_process
) == sandbox::SBOX_ALL_OK
;
799 } // namespace content