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/debug/trace_event.h"
13 #include "base/files/file_util.h"
14 #include "base/hash.h"
15 #include "base/metrics/field_trial.h"
16 #include "base/path_service.h"
17 #include "base/process/launch.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.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/public/common/content_client.h"
25 #include "content/public/common/content_switches.h"
26 #include "content/public/common/sandbox_init.h"
27 #include "content/public/common/sandboxed_process_launcher_delegate.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"
32 #include "ui/gfx/win/dpi.h"
34 static sandbox::BrokerServices
* g_broker_services
= NULL
;
35 static sandbox::TargetServices
* g_target_services
= NULL
;
40 // The DLLs listed here are known (or under strong suspicion) of causing crashes
41 // when they are loaded in the renderer. Note: at runtime we generate short
42 // versions of the dll name only if the dll has an extension.
43 // For more information about how this list is generated, and how to get off
45 // https://sites.google.com/a/chromium.org/dev/Home/third-party-developers
46 const wchar_t* const kTroublesomeDlls
[] = {
47 L
"adialhk.dll", // Kaspersky Internet Security.
48 L
"acpiz.dll", // Unknown.
49 L
"airfoilinject3.dll", // Airfoil.
50 L
"akinsofthook32.dll", // Akinsoft Software Engineering.
51 L
"assistant_x64.dll", // Unknown.
52 L
"avcuf64.dll", // Bit Defender Internet Security x64.
53 L
"avgrsstx.dll", // AVG 8.
54 L
"babylonchromepi.dll", // Babylon translator.
55 L
"btkeyind.dll", // Widcomm Bluetooth.
56 L
"cmcsyshk.dll", // CMC Internet Security.
57 L
"cmsetac.dll", // Unknown (suspected malware).
58 L
"cooliris.dll", // CoolIris.
59 L
"dockshellhook.dll", // Stardock Objectdock.
60 L
"easyhook32.dll", // GDIPP and others.
61 L
"googledesktopnetwork3.dll", // Google Desktop Search v5.
62 L
"fwhook.dll", // PC Tools Firewall Plus.
63 L
"hookprocesscreation.dll", // Blumentals Program protector.
64 L
"hookterminateapis.dll", // Blumentals and Cyberprinter.
65 L
"hookprintapis.dll", // Cyberprinter.
66 L
"imon.dll", // NOD32 Antivirus.
67 L
"ioloHL.dll", // Iolo (System Mechanic).
68 L
"kloehk.dll", // Kaspersky Internet Security.
69 L
"lawenforcer.dll", // Spyware-Browser AntiSpyware (Spybro).
70 L
"libdivx.dll", // DivX.
71 L
"lvprcinj01.dll", // Logitech QuickCam.
72 L
"madchook.dll", // Madshi (generic hooking library).
73 L
"mdnsnsp.dll", // Bonjour.
74 L
"moonsysh.dll", // Moon Secure Antivirus.
75 L
"mpk.dll", // KGB Spy.
76 L
"npdivx32.dll", // DivX.
77 L
"npggNT.des", // GameGuard 2008.
78 L
"npggNT.dll", // GameGuard (older).
79 L
"oawatch.dll", // Online Armor.
80 L
"pavhook.dll", // Panda Internet Security.
81 L
"pavlsphook.dll", // Panda Antivirus.
82 L
"pavshook.dll", // Panda Antivirus.
83 L
"pavshookwow.dll", // Panda Antivirus.
84 L
"pctavhook.dll", // PC Tools Antivirus.
85 L
"pctgmhk.dll", // PC Tools Spyware Doctor.
86 L
"prntrack.dll", // Pharos Systems.
87 L
"protector.dll", // Unknown (suspected malware).
88 L
"radhslib.dll", // Radiant Naomi Internet Filter.
89 L
"radprlib.dll", // Radiant Naomi Internet Filter.
90 L
"rapportnikko.dll", // Trustware Rapport.
91 L
"rlhook.dll", // Trustware Bufferzone.
92 L
"rooksdol.dll", // Trustware Rapport.
93 L
"rndlpepperbrowserrecordhelper.dll", // RealPlayer.
94 L
"rpchromebrowserrecordhelper.dll", // RealPlayer.
95 L
"r3hook.dll", // Kaspersky Internet Security.
96 L
"sahook.dll", // McAfee Site Advisor.
97 L
"sbrige.dll", // Unknown.
98 L
"sc2hook.dll", // Supercopier 2.
99 L
"sdhook32.dll", // Spybot - Search & Destroy Live Protection.
100 L
"sguard.dll", // Iolo (System Guard).
101 L
"smum32.dll", // Spyware Doctor version 6.
102 L
"smumhook.dll", // Spyware Doctor version 5.
103 L
"ssldivx.dll", // DivX.
104 L
"syncor11.dll", // SynthCore Midi interface.
105 L
"systools.dll", // Panda Antivirus.
106 L
"tfwah.dll", // Threatfire (PC tools).
107 L
"wblind.dll", // Stardock Object desktop.
108 L
"wbhelp.dll", // Stardock Object desktop.
109 L
"winstylerthemehelper.dll" // Tuneup utilities 2006.
112 // Adds the policy rules for the path and path\ with the semantic |access|.
113 // If |children| is set to true, we need to add the wildcard rules to also
114 // apply the rule to the subfiles and subfolders.
115 bool AddDirectory(int path
, const wchar_t* sub_dir
, bool children
,
116 sandbox::TargetPolicy::Semantics access
,
117 sandbox::TargetPolicy
* policy
) {
118 base::FilePath directory
;
119 if (!PathService::Get(path
, &directory
))
123 directory
= base::MakeAbsoluteFilePath(directory
.Append(sub_dir
));
125 sandbox::ResultCode result
;
126 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
, access
,
127 directory
.value().c_str());
128 if (result
!= sandbox::SBOX_ALL_OK
)
131 std::wstring directory_str
= directory
.value() + L
"\\";
133 directory_str
+= L
"*";
134 // Otherwise, add the version of the path that ends with a separator.
136 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
, access
,
137 directory_str
.c_str());
138 if (result
!= sandbox::SBOX_ALL_OK
)
144 // Adds the policy rules for the path and path\* with the semantic |access|.
145 // We need to add the wildcard rules to also apply the rule to the subkeys.
146 bool AddKeyAndSubkeys(std::wstring key
,
147 sandbox::TargetPolicy::Semantics access
,
148 sandbox::TargetPolicy
* policy
) {
149 sandbox::ResultCode result
;
150 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY
, access
,
152 if (result
!= sandbox::SBOX_ALL_OK
)
156 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY
, access
,
158 if (result
!= sandbox::SBOX_ALL_OK
)
164 // Compares the loaded |module| file name matches |module_name|.
165 bool IsExpandedModuleName(HMODULE module
, const wchar_t* module_name
) {
166 wchar_t path
[MAX_PATH
];
167 DWORD sz
= ::GetModuleFileNameW(module
, path
, arraysize(path
));
168 if ((sz
== arraysize(path
)) || (sz
== 0)) {
169 // XP does not set the last error properly, so we bail out anyway.
172 if (!::GetLongPathName(path
, path
, arraysize(path
)))
174 base::FilePath
fname(path
);
175 return (fname
.BaseName().value() == module_name
);
178 // Adds a single dll by |module_name| into the |policy| blacklist.
179 // If |check_in_browser| is true we only add an unload policy only if the dll
180 // is also loaded in this process.
181 void BlacklistAddOneDll(const wchar_t* module_name
,
182 bool check_in_browser
,
183 sandbox::TargetPolicy
* policy
) {
184 HMODULE module
= check_in_browser
? ::GetModuleHandleW(module_name
) : NULL
;
186 // The module could have been loaded with a 8.3 short name. We check
187 // the three most common cases: 'thelongname.dll' becomes
188 // 'thelon~1.dll', 'thelon~2.dll' and 'thelon~3.dll'.
189 std::wstring
name(module_name
);
190 size_t period
= name
.rfind(L
'.');
191 DCHECK_NE(std::string::npos
, period
);
192 DCHECK_LE(3U, (name
.size() - period
));
195 for (int ix
= 0; ix
< 3; ++ix
) {
196 const wchar_t suffix
[] = {'~', ('1' + ix
), 0};
197 std::wstring alt_name
= name
.substr(0, 6) + suffix
;
198 alt_name
+= name
.substr(period
, name
.size());
199 if (check_in_browser
) {
200 module
= ::GetModuleHandleW(alt_name
.c_str());
203 // We found it, but because it only has 6 significant letters, we
204 // want to make sure it is the right one.
205 if (!IsExpandedModuleName(module
, module_name
))
208 // Found a match. We add both forms to the policy.
209 policy
->AddDllToUnload(alt_name
.c_str());
212 policy
->AddDllToUnload(module_name
);
213 DVLOG(1) << "dll to unload found: " << module_name
;
217 // Adds policy rules for unloaded the known dlls that cause chrome to crash.
218 // Eviction of injected DLLs is done by the sandbox so that the injected module
219 // does not get a chance to execute any code.
220 void AddGenericDllEvictionPolicy(sandbox::TargetPolicy
* policy
) {
221 for (int ix
= 0; ix
!= arraysize(kTroublesomeDlls
); ++ix
)
222 BlacklistAddOneDll(kTroublesomeDlls
[ix
], true, policy
);
225 // Returns the object path prepended with the current logon session.
226 base::string16
PrependWindowsSessionPath(const base::char16
* object
) {
227 // Cache this because it can't change after process creation.
228 static uintptr_t s_session_id
= 0;
229 if (s_session_id
== 0) {
231 DWORD session_id_length
;
232 DWORD session_id
= 0;
234 CHECK(::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY
, &token
));
235 CHECK(::GetTokenInformation(token
, TokenSessionId
, &session_id
,
236 sizeof(session_id
), &session_id_length
));
239 s_session_id
= session_id
;
242 return base::StringPrintf(L
"\\Sessions\\%d%ls", s_session_id
, object
);
245 // Checks if the sandbox should be let to run without a job object assigned.
246 bool ShouldSetJobLevel(const base::CommandLine
& cmd_line
) {
247 if (!cmd_line
.HasSwitch(switches::kAllowNoSandboxJob
))
250 // Windows 8 allows nested jobs so we don't need to check if we are in other
252 if (base::win::GetVersion() >= base::win::VERSION_WIN8
)
256 // Either there is no job yet associated so we must add our job,
257 if (!::IsProcessInJob(::GetCurrentProcess(), NULL
, &in_job
))
258 NOTREACHED() << "IsProcessInJob failed. " << GetLastError();
262 // ...or there is a job but the JOB_OBJECT_LIMIT_BREAKAWAY_OK limit is set.
263 JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info
= {0};
264 if (!::QueryInformationJobObject(NULL
,
265 JobObjectExtendedLimitInformation
, &job_info
,
266 sizeof(job_info
), NULL
)) {
267 NOTREACHED() << "QueryInformationJobObject failed. " << GetLastError();
270 if (job_info
.BasicLimitInformation
.LimitFlags
& JOB_OBJECT_LIMIT_BREAKAWAY_OK
)
276 // Adds the generic policy rules to a sandbox TargetPolicy.
277 bool AddGenericPolicy(sandbox::TargetPolicy
* policy
) {
278 sandbox::ResultCode result
;
280 // Renderers need to copy sections for plugin DIBs and GPU.
281 // GPU needs to copy sections to renderers.
282 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES
,
283 sandbox::TargetPolicy::HANDLES_DUP_ANY
,
285 if (result
!= sandbox::SBOX_ALL_OK
)
288 // Add the policy for the client side of a pipe. It is just a file
289 // in the \pipe\ namespace. We restrict it to pipes that start with
290 // "chrome." so the sandboxed process cannot connect to system services.
291 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
292 sandbox::TargetPolicy::FILES_ALLOW_ANY
,
293 L
"\\??\\pipe\\chrome.*");
294 if (result
!= sandbox::SBOX_ALL_OK
)
297 // Add the policy for the server side of nacl pipe. It is just a file
298 // in the \pipe\ namespace. We restrict it to pipes that start with
299 // "chrome.nacl" so the sandboxed process cannot connect to
301 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES
,
302 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY
,
303 L
"\\\\.\\pipe\\chrome.nacl.*");
304 if (result
!= sandbox::SBOX_ALL_OK
)
307 // Allow the server side of sync sockets, which are pipes that have
308 // the "chrome.sync" namespace and a randomly generated suffix.
309 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES
,
310 sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY
,
311 L
"\\\\.\\pipe\\chrome.sync.*");
312 if (result
!= sandbox::SBOX_ALL_OK
)
315 // Add the policy for debug message only in debug
317 base::FilePath app_dir
;
318 if (!PathService::Get(base::DIR_MODULE
, &app_dir
))
321 wchar_t long_path_buf
[MAX_PATH
];
322 DWORD long_path_return_value
= GetLongPathName(app_dir
.value().c_str(),
325 if (long_path_return_value
== 0 || long_path_return_value
>= MAX_PATH
)
328 base::FilePath
debug_message(long_path_buf
);
329 debug_message
= debug_message
.AppendASCII("debug_message.exe");
330 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_PROCESS
,
331 sandbox::TargetPolicy::PROCESS_MIN_EXEC
,
332 debug_message
.value().c_str());
333 if (result
!= sandbox::SBOX_ALL_OK
)
337 AddGenericDllEvictionPolicy(policy
);
341 bool AddPolicyForSandboxedProcess(sandbox::TargetPolicy
* policy
) {
342 sandbox::ResultCode result
;
343 // Renderers need to share events with plugins.
344 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES
,
345 sandbox::TargetPolicy::HANDLES_DUP_ANY
,
347 if (result
!= sandbox::SBOX_ALL_OK
)
350 // Win8+ adds a device DeviceApi that we don't need.
351 if (base::win::GetVersion() > base::win::VERSION_WIN7
)
352 result
= policy
->AddKernelObjectToClose(L
"File", L
"\\Device\\DeviceApi");
353 if (result
!= sandbox::SBOX_ALL_OK
)
356 // Close the proxy settings on XP.
357 if (base::win::GetVersion() <= base::win::VERSION_SERVER_2003
)
358 result
= policy
->AddKernelObjectToClose(L
"Key",
359 L
"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\" \
360 L
"CurrentVersion\\Internet Settings");
361 if (result
!= sandbox::SBOX_ALL_OK
)
365 sandbox::TokenLevel initial_token
= sandbox::USER_UNPROTECTED
;
366 if (base::win::GetVersion() > base::win::VERSION_XP
) {
367 // On 2003/Vista the initial token has to be restricted if the main
368 // token is restricted.
369 initial_token
= sandbox::USER_RESTRICTED_SAME_ACCESS
;
372 policy
->SetTokenLevel(initial_token
, sandbox::USER_LOCKDOWN
);
373 // Prevents the renderers from manipulating low-integrity processes.
374 policy
->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED
);
375 policy
->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW
);
377 if (sandbox::SBOX_ALL_OK
!= policy
->SetAlternateDesktop(true)) {
378 DLOG(WARNING
) << "Failed to apply desktop security to the renderer";
384 // Updates the command line arguments with debug-related flags. If debug flags
385 // have been used with this process, they will be filtered and added to
386 // command_line as needed.
387 void ProcessDebugFlags(base::CommandLine
* command_line
) {
388 const base::CommandLine
& current_cmd_line
=
389 *base::CommandLine::ForCurrentProcess();
390 std::string type
= command_line
->GetSwitchValueASCII(switches::kProcessType
);
391 if (current_cmd_line
.HasSwitch(switches::kWaitForDebuggerChildren
)) {
392 // Look to pass-on the kWaitForDebugger flag.
393 std::string value
= current_cmd_line
.GetSwitchValueASCII(
394 switches::kWaitForDebuggerChildren
);
395 if (value
.empty() || value
== type
) {
396 command_line
->AppendSwitch(switches::kWaitForDebugger
);
398 command_line
->AppendSwitchASCII(switches::kWaitForDebuggerChildren
, value
);
402 // This code is test only, and attempts to catch unsafe uses of
403 // DuplicateHandle() that copy privileged handles into sandboxed processes.
404 #ifndef OFFICIAL_BUILD
405 base::win::IATPatchFunction g_iat_patch_duplicate_handle
;
407 typedef BOOL (WINAPI
*DuplicateHandleFunctionPtr
)(HANDLE source_process_handle
,
408 HANDLE source_handle
,
409 HANDLE target_process_handle
,
410 LPHANDLE target_handle
,
411 DWORD desired_access
,
415 DuplicateHandleFunctionPtr g_iat_orig_duplicate_handle
;
417 NtQueryObject g_QueryObject
= NULL
;
419 static const char* kDuplicateHandleWarning
=
420 "You are attempting to duplicate a privileged handle into a sandboxed"
421 " process.\n Please use the sandbox::BrokerDuplicateHandle API or"
422 " contact security@chromium.org for assistance.";
424 void CheckDuplicateHandle(HANDLE handle
) {
425 // Get the object type (32 characters is safe; current max is 14).
426 BYTE buffer
[sizeof(OBJECT_TYPE_INFORMATION
) + 32 * sizeof(wchar_t)];
427 OBJECT_TYPE_INFORMATION
* type_info
=
428 reinterpret_cast<OBJECT_TYPE_INFORMATION
*>(buffer
);
429 ULONG size
= sizeof(buffer
) - sizeof(wchar_t);
431 error
= g_QueryObject(handle
, ObjectTypeInformation
, type_info
, size
, &size
);
432 CHECK(NT_SUCCESS(error
));
433 type_info
->Name
.Buffer
[type_info
->Name
.Length
/ sizeof(wchar_t)] = L
'\0';
435 // Get the object basic information.
436 OBJECT_BASIC_INFORMATION basic_info
;
437 size
= sizeof(basic_info
);
438 error
= g_QueryObject(handle
, ObjectBasicInformation
, &basic_info
, size
,
440 CHECK(NT_SUCCESS(error
));
442 CHECK(!(basic_info
.GrantedAccess
& WRITE_DAC
)) <<
443 kDuplicateHandleWarning
;
445 if (0 == _wcsicmp(type_info
->Name
.Buffer
, L
"Process")) {
446 const ACCESS_MASK kDangerousMask
=
447 ~static_cast<DWORD
>(PROCESS_QUERY_LIMITED_INFORMATION
| SYNCHRONIZE
);
448 CHECK(!(basic_info
.GrantedAccess
& kDangerousMask
)) <<
449 kDuplicateHandleWarning
;
453 BOOL WINAPI
DuplicateHandlePatch(HANDLE source_process_handle
,
454 HANDLE source_handle
,
455 HANDLE target_process_handle
,
456 LPHANDLE target_handle
,
457 DWORD desired_access
,
460 // Duplicate the handle so we get the final access mask.
461 if (!g_iat_orig_duplicate_handle(source_process_handle
, source_handle
,
462 target_process_handle
, target_handle
,
463 desired_access
, inherit_handle
, options
))
466 // We're not worried about broker handles or not crossing process boundaries.
467 if (source_process_handle
== target_process_handle
||
468 target_process_handle
== ::GetCurrentProcess())
471 // Only sandboxed children are placed in jobs, so just check them.
472 BOOL is_in_job
= FALSE
;
473 if (!::IsProcessInJob(target_process_handle
, NULL
, &is_in_job
)) {
474 // We need a handle with permission to check the job object.
475 if (ERROR_ACCESS_DENIED
== ::GetLastError()) {
477 CHECK(g_iat_orig_duplicate_handle(::GetCurrentProcess(),
478 target_process_handle
,
479 ::GetCurrentProcess(),
481 PROCESS_QUERY_INFORMATION
,
483 base::win::ScopedHandle
process(temp_handle
);
484 CHECK(::IsProcessInJob(process
, NULL
, &is_in_job
));
489 // We never allow inheritable child handles.
490 CHECK(!inherit_handle
) << kDuplicateHandleWarning
;
492 // Duplicate the handle again, to get the final permissions.
494 CHECK(g_iat_orig_duplicate_handle(target_process_handle
, *target_handle
,
495 ::GetCurrentProcess(), &temp_handle
,
496 0, FALSE
, DUPLICATE_SAME_ACCESS
));
497 base::win::ScopedHandle
handle(temp_handle
);
499 // Callers use CHECK macro to make sure we get the right stack.
500 CheckDuplicateHandle(handle
);
509 void SetJobLevel(const base::CommandLine
& cmd_line
,
510 sandbox::JobLevel job_level
,
511 uint32 ui_exceptions
,
512 sandbox::TargetPolicy
* policy
) {
513 if (ShouldSetJobLevel(cmd_line
)) {
515 policy
->SetJobMemoryLimit(4ULL * 1024 * 1024 * 1024);
517 policy
->SetJobLevel(job_level
, ui_exceptions
);
519 policy
->SetJobLevel(sandbox::JOB_NONE
, 0);
523 // TODO(jschuh): Need get these restrictions applied to NaCl and Pepper.
524 // Just have to figure out what needs to be warmed up first.
525 void AddBaseHandleClosePolicy(sandbox::TargetPolicy
* policy
) {
526 // TODO(cpu): Add back the BaseNamedObjects policy.
527 base::string16 object_path
= PrependWindowsSessionPath(
528 L
"\\BaseNamedObjects\\windows_shell_global_counters");
529 policy
->AddKernelObjectToClose(L
"Section", object_path
.data());
532 bool InitBrokerServices(sandbox::BrokerServices
* broker_services
) {
533 // TODO(abarth): DCHECK(CalledOnValidThread());
534 // See <http://b/1287166>.
535 DCHECK(broker_services
);
536 DCHECK(!g_broker_services
);
537 sandbox::ResultCode result
= broker_services
->Init();
538 g_broker_services
= broker_services
;
540 // In non-official builds warn about dangerous uses of DuplicateHandle.
541 #ifndef OFFICIAL_BUILD
542 BOOL is_in_job
= FALSE
;
543 CHECK(::IsProcessInJob(::GetCurrentProcess(), NULL
, &is_in_job
));
544 // In a Syzygy-profiled binary, instrumented for import profiling, this
545 // patch will end in infinite recursion on the attempted delegation to the
546 // original function.
547 if (!base::debug::IsBinaryInstrumented() &&
548 !is_in_job
&& !g_iat_patch_duplicate_handle
.is_patched()) {
549 HMODULE module
= NULL
;
550 wchar_t module_name
[MAX_PATH
];
551 CHECK(::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
,
552 reinterpret_cast<LPCWSTR
>(InitBrokerServices
),
554 DWORD result
= ::GetModuleFileNameW(module
, module_name
, MAX_PATH
);
555 if (result
&& (result
!= MAX_PATH
)) {
556 ResolveNTFunctionPtr("NtQueryObject", &g_QueryObject
);
557 result
= g_iat_patch_duplicate_handle
.Patch(
558 module_name
, "kernel32.dll", "DuplicateHandle",
559 DuplicateHandlePatch
);
561 g_iat_orig_duplicate_handle
=
562 reinterpret_cast<DuplicateHandleFunctionPtr
>(
563 g_iat_patch_duplicate_handle
.original_function());
568 return sandbox::SBOX_ALL_OK
== result
;
571 bool InitTargetServices(sandbox::TargetServices
* target_services
) {
572 DCHECK(target_services
);
573 DCHECK(!g_target_services
);
574 sandbox::ResultCode result
= target_services
->Init();
575 g_target_services
= target_services
;
576 return sandbox::SBOX_ALL_OK
== result
;
579 bool ShouldUseDirectWrite() {
580 // If the flag is currently on, and we're on Win7 or above, we enable
581 // DirectWrite. Skia does not require the additions to DirectWrite in QFE
582 // 2670838, but a simple 'better than XP' check is not enough.
583 if (base::win::GetVersion() < base::win::VERSION_WIN7
)
586 base::win::OSInfo::VersionNumber os_version
=
587 base::win::OSInfo::GetInstance()->version_number();
588 if ((os_version
.major
== 6) && (os_version
.minor
== 1)) {
589 // We can't use DirectWrite for pre-release versions of Windows 7.
590 if (os_version
.build
< 7600)
594 // If forced off, don't use it.
595 const base::CommandLine
& command_line
=
596 *base::CommandLine::ForCurrentProcess();
597 if (command_line
.HasSwitch(switches::kDisableDirectWrite
))
600 #if !defined(NACL_WIN64)
601 // Can't use GDI on HiDPI.
602 if (gfx::GetDPIScale() > 1.0f
)
606 // Otherwise, check the field trial.
607 const std::string group_name
=
608 base::FieldTrialList::FindFullName("DirectWrite");
609 return group_name
!= "Disabled";
612 base::ProcessHandle
StartSandboxedProcess(
613 SandboxedProcessLauncherDelegate
* delegate
,
614 base::CommandLine
* cmd_line
) {
615 const base::CommandLine
& browser_command_line
=
616 *base::CommandLine::ForCurrentProcess();
617 std::string type_str
= cmd_line
->GetSwitchValueASCII(switches::kProcessType
);
619 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str
);
621 // Propagate the --allow-no-job flag if present.
622 if (browser_command_line
.HasSwitch(switches::kAllowNoSandboxJob
) &&
623 !cmd_line
->HasSwitch(switches::kAllowNoSandboxJob
)) {
624 cmd_line
->AppendSwitch(switches::kAllowNoSandboxJob
);
627 ProcessDebugFlags(cmd_line
);
629 // Prefetch hints on windows:
630 // Using a different prefetch profile per process type will allow Windows
631 // to create separate pretetch settings for browser, renderer etc.
632 cmd_line
->AppendArg(base::StringPrintf("/prefetch:%d", base::Hash(type_str
)));
634 if ((delegate
&& !delegate
->ShouldSandbox()) ||
635 browser_command_line
.HasSwitch(switches::kNoSandbox
) ||
636 cmd_line
->HasSwitch(switches::kNoSandbox
)) {
637 base::ProcessHandle process
= 0;
638 base::LaunchProcess(*cmd_line
, base::LaunchOptions(), &process
);
639 g_broker_services
->AddTargetPeer(process
);
643 sandbox::TargetPolicy
* policy
= g_broker_services
->CreatePolicy();
645 sandbox::MitigationFlags mitigations
= sandbox::MITIGATION_HEAP_TERMINATE
|
646 sandbox::MITIGATION_BOTTOM_UP_ASLR
|
647 sandbox::MITIGATION_DEP
|
648 sandbox::MITIGATION_DEP_NO_ATL_THUNK
|
649 sandbox::MITIGATION_SEHOP
;
651 if (base::win::GetVersion() >= base::win::VERSION_WIN8
&&
652 type_str
== switches::kRendererProcess
&&
653 browser_command_line
.HasSwitch(
654 switches::kEnableWin32kRendererLockDown
)) {
655 if (policy
->AddRule(sandbox::TargetPolicy::SUBSYS_WIN32K_LOCKDOWN
,
656 sandbox::TargetPolicy::FAKE_USER_GDI_INIT
,
657 NULL
) != sandbox::SBOX_ALL_OK
) {
660 mitigations
|= sandbox::MITIGATION_WIN32K_DISABLE
;
663 if (policy
->SetProcessMitigations(mitigations
) != sandbox::SBOX_ALL_OK
)
666 mitigations
= sandbox::MITIGATION_STRICT_HANDLE_CHECKS
|
667 sandbox::MITIGATION_DLL_SEARCH_ORDER
;
669 if (policy
->SetDelayedProcessMitigations(mitigations
) != sandbox::SBOX_ALL_OK
)
672 SetJobLevel(*cmd_line
, sandbox::JOB_LOCKDOWN
, 0, policy
);
674 bool disable_default_policy
= false;
675 base::FilePath exposed_dir
;
677 delegate
->PreSandbox(&disable_default_policy
, &exposed_dir
);
679 if (!disable_default_policy
&& !AddPolicyForSandboxedProcess(policy
))
682 if (type_str
== switches::kRendererProcess
) {
683 if (ShouldUseDirectWrite()) {
684 AddDirectory(base::DIR_WINDOWS_FONTS
,
687 sandbox::TargetPolicy::FILES_ALLOW_READONLY
,
691 // Hack for Google Desktop crash. Trick GD into not injecting its DLL into
692 // this subprocess. See
693 // http://code.google.com/p/chromium/issues/detail?id=25580
694 cmd_line
->AppendSwitchASCII("ignored", " --type=renderer ");
697 sandbox::ResultCode result
;
698 if (!exposed_dir
.empty()) {
699 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
700 sandbox::TargetPolicy::FILES_ALLOW_ANY
,
701 exposed_dir
.value().c_str());
702 if (result
!= sandbox::SBOX_ALL_OK
)
705 base::FilePath exposed_files
= exposed_dir
.AppendASCII("*");
706 result
= policy
->AddRule(sandbox::TargetPolicy::SUBSYS_FILES
,
707 sandbox::TargetPolicy::FILES_ALLOW_ANY
,
708 exposed_files
.value().c_str());
709 if (result
!= sandbox::SBOX_ALL_OK
)
713 if (!AddGenericPolicy(policy
)) {
718 if (browser_command_line
.HasSwitch(switches::kEnableLogging
)) {
719 // If stdout/stderr point to a Windows console, these calls will
721 policy
->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE
));
722 policy
->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE
));
727 delegate
->PreSpawnTarget(policy
, &success
);
732 TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
734 PROCESS_INFORMATION temp_process_info
= {};
735 result
= g_broker_services
->SpawnTarget(
736 cmd_line
->GetProgram().value().c_str(),
737 cmd_line
->GetCommandLineString().c_str(),
738 policy
, &temp_process_info
);
740 base::win::ScopedProcessInformation
target(temp_process_info
);
742 TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
744 if (sandbox::SBOX_ALL_OK
!= result
) {
745 if (result
== sandbox::SBOX_ERROR_GENERIC
)
746 DPLOG(ERROR
) << "Failed to launch process";
748 DLOG(ERROR
) << "Failed to launch process. Error: " << result
;
753 delegate
->PostSpawnTarget(target
.process_handle());
755 ResumeThread(target
.thread_handle());
756 TRACE_EVENT_END_ETW("StartProcessWithAccess", 0, type_str
);
757 return target
.TakeProcessHandle();
760 bool BrokerDuplicateHandle(HANDLE source_handle
,
761 DWORD target_process_id
,
762 HANDLE
* target_handle
,
763 DWORD desired_access
,
765 // If our process is the target just duplicate the handle.
766 if (::GetCurrentProcessId() == target_process_id
) {
767 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle
,
768 ::GetCurrentProcess(), target_handle
,
769 desired_access
, FALSE
, options
);
773 // Try the broker next
774 if (g_target_services
&&
775 g_target_services
->DuplicateHandle(source_handle
, target_process_id
,
776 target_handle
, desired_access
,
777 options
) == sandbox::SBOX_ALL_OK
) {
781 // Finally, see if we already have access to the process.
782 base::win::ScopedHandle target_process
;
783 target_process
.Set(::OpenProcess(PROCESS_DUP_HANDLE
, FALSE
,
785 if (target_process
.IsValid()) {
786 return !!::DuplicateHandle(::GetCurrentProcess(), source_handle
,
787 target_process
, target_handle
,
788 desired_access
, FALSE
, options
);
794 bool BrokerAddTargetPeer(HANDLE peer_process
) {
795 return g_broker_services
->AddTargetPeer(peer_process
) == sandbox::SBOX_ALL_OK
;
798 } // namespace content