This source file includes following definitions.
- AddDirectory
- AddKeyAndSubkeys
- IsExpandedModuleName
- BlacklistAddOneDll
- AddGenericDllEvictionPolicy
- PrependWindowsSessionPath
- ShouldSetJobLevel
- AddGenericPolicy
- AddPolicyForSandboxedProcess
- ProcessDebugFlags
- CheckDuplicateHandle
- DuplicateHandlePatch
- SetJobLevel
- AddBaseHandleClosePolicy
- InitBrokerServices
- InitTargetServices
- ShouldUseDirectWrite
- StartSandboxedProcess
- BrokerDuplicateHandle
- BrokerAddTargetPeer
#include "content/common/sandbox_win.h"
#include <string>
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/debug/debugger.h"
#include "base/debug/profiler.h"
#include "base/debug/trace_event.h"
#include "base/file_util.h"
#include "base/hash.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/win/iat_patch_function.h"
#include "base/win/scoped_handle.h"
#include "base/win/scoped_process_information.h"
#include "base/win/windows_version.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/sandbox_init.h"
#include "content/public/common/sandboxed_process_launcher_delegate.h"
#include "ipc/ipc_switches.h"
#include "sandbox/win/src/process_mitigations.h"
#include "sandbox/win/src/sandbox.h"
#include "sandbox/win/src/sandbox_nt_util.h"
#include "sandbox/win/src/win_utils.h"
static sandbox::BrokerServices* g_broker_services = NULL;
static sandbox::TargetServices* g_target_services = NULL;
namespace content {
namespace {
const wchar_t* const kTroublesomeDlls[] = {
L"adialhk.dll",
L"acpiz.dll",
L"akinsofthook32.dll",
L"avgrsstx.dll",
L"babylonchromepi.dll",
L"btkeyind.dll",
L"cmcsyshk.dll",
L"cmsetac.dll",
L"cooliris.dll",
L"dockshellhook.dll",
L"easyhook32.dll",
L"googledesktopnetwork3.dll",
L"fwhook.dll",
L"hookprocesscreation.dll",
L"hookterminateapis.dll",
L"hookprintapis.dll",
L"imon.dll",
L"ioloHL.dll",
L"kloehk.dll",
L"lawenforcer.dll",
L"libdivx.dll",
L"lvprcinj01.dll",
L"madchook.dll",
L"mdnsnsp.dll",
L"moonsysh.dll",
L"mpk.dll",
L"npdivx32.dll",
L"npggNT.des",
L"npggNT.dll",
L"oawatch.dll",
L"pavhook.dll",
L"pavlsphook.dll",
L"pavshook.dll",
L"pavshookwow.dll",
L"pctavhook.dll",
L"pctgmhk.dll",
L"prntrack.dll",
L"protector.dll",
L"radhslib.dll",
L"radprlib.dll",
L"rapportnikko.dll",
L"rlhook.dll",
L"rooksdol.dll",
L"rndlpepperbrowserrecordhelper.dll",
L"rpchromebrowserrecordhelper.dll",
L"r3hook.dll",
L"sahook.dll",
L"sbrige.dll",
L"sc2hook.dll",
L"sdhook32.dll",
L"sguard.dll",
L"smum32.dll",
L"smumhook.dll",
L"ssldivx.dll",
L"syncor11.dll",
L"systools.dll",
L"tfwah.dll",
L"wblind.dll",
L"wbhelp.dll",
L"winstylerthemehelper.dll"
};
bool AddDirectory(int path, const wchar_t* sub_dir, bool children,
sandbox::TargetPolicy::Semantics access,
sandbox::TargetPolicy* policy) {
base::FilePath directory;
if (!PathService::Get(path, &directory))
return false;
if (sub_dir)
directory = base::MakeAbsoluteFilePath(directory.Append(sub_dir));
sandbox::ResultCode result;
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
directory.value().c_str());
if (result != sandbox::SBOX_ALL_OK)
return false;
std::wstring directory_str = directory.value() + L"\\";
if (children)
directory_str += L"*";
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES, access,
directory_str.c_str());
if (result != sandbox::SBOX_ALL_OK)
return false;
return true;
}
bool AddKeyAndSubkeys(std::wstring key,
sandbox::TargetPolicy::Semantics access,
sandbox::TargetPolicy* policy) {
sandbox::ResultCode result;
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
key.c_str());
if (result != sandbox::SBOX_ALL_OK)
return false;
key += L"\\*";
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY, access,
key.c_str());
if (result != sandbox::SBOX_ALL_OK)
return false;
return true;
}
bool IsExpandedModuleName(HMODULE module, const wchar_t* module_name) {
wchar_t path[MAX_PATH];
DWORD sz = ::GetModuleFileNameW(module, path, arraysize(path));
if ((sz == arraysize(path)) || (sz == 0)) {
return false;
}
if (!::GetLongPathName(path, path, arraysize(path)))
return false;
base::FilePath fname(path);
return (fname.BaseName().value() == module_name);
}
void BlacklistAddOneDll(const wchar_t* module_name,
bool check_in_browser,
sandbox::TargetPolicy* policy) {
HMODULE module = check_in_browser ? ::GetModuleHandleW(module_name) : NULL;
if (!module) {
std::wstring name(module_name);
size_t period = name.rfind(L'.');
DCHECK_NE(std::string::npos, period);
DCHECK_LE(3U, (name.size() - period));
if (period <= 8)
return;
for (int ix = 0; ix < 3; ++ix) {
const wchar_t suffix[] = {'~', ('1' + ix), 0};
std::wstring alt_name = name.substr(0, 6) + suffix;
alt_name += name.substr(period, name.size());
if (check_in_browser) {
module = ::GetModuleHandleW(alt_name.c_str());
if (!module)
return;
if (!IsExpandedModuleName(module, module_name))
return;
}
policy->AddDllToUnload(alt_name.c_str());
}
}
policy->AddDllToUnload(module_name);
DVLOG(1) << "dll to unload found: " << module_name;
return;
}
void AddGenericDllEvictionPolicy(sandbox::TargetPolicy* policy) {
for (int ix = 0; ix != arraysize(kTroublesomeDlls); ++ix)
BlacklistAddOneDll(kTroublesomeDlls[ix], true, policy);
}
base::string16 PrependWindowsSessionPath(const base::char16* object) {
static uintptr_t s_session_id = 0;
if (s_session_id == 0) {
HANDLE token;
DWORD session_id_length;
DWORD session_id = 0;
CHECK(::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token));
CHECK(::GetTokenInformation(token, TokenSessionId, &session_id,
sizeof(session_id), &session_id_length));
CloseHandle(token);
if (session_id)
s_session_id = session_id;
}
return base::StringPrintf(L"\\Sessions\\%d%ls", s_session_id, object);
}
bool ShouldSetJobLevel(const CommandLine& cmd_line) {
if (!cmd_line.HasSwitch(switches::kAllowNoSandboxJob))
return true;
if (base::win::GetVersion() >= base::win::VERSION_WIN8)
return true;
BOOL in_job = true;
if (!::IsProcessInJob(::GetCurrentProcess(), NULL, &in_job))
NOTREACHED() << "IsProcessInJob failed. " << GetLastError();
if (!in_job)
return true;
JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info = {0};
if (!::QueryInformationJobObject(NULL,
JobObjectExtendedLimitInformation, &job_info,
sizeof(job_info), NULL)) {
NOTREACHED() << "QueryInformationJobObject failed. " << GetLastError();
return true;
}
if (job_info.BasicLimitInformation.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK)
return true;
return false;
}
bool AddGenericPolicy(sandbox::TargetPolicy* policy) {
sandbox::ResultCode result;
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
sandbox::TargetPolicy::HANDLES_DUP_ANY,
L"Section");
if (result != sandbox::SBOX_ALL_OK)
return false;
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
sandbox::TargetPolicy::FILES_ALLOW_ANY,
L"\\??\\pipe\\chrome.*");
if (result != sandbox::SBOX_ALL_OK)
return false;
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
L"\\\\.\\pipe\\chrome.nacl.*");
if (result != sandbox::SBOX_ALL_OK)
return false;
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
L"\\\\.\\pipe\\chrome.sync.*");
if (result != sandbox::SBOX_ALL_OK)
return false;
#ifndef NDEBUG
base::FilePath app_dir;
if (!PathService::Get(base::DIR_MODULE, &app_dir))
return false;
wchar_t long_path_buf[MAX_PATH];
DWORD long_path_return_value = GetLongPathName(app_dir.value().c_str(),
long_path_buf,
MAX_PATH);
if (long_path_return_value == 0 || long_path_return_value >= MAX_PATH)
return false;
base::FilePath debug_message(long_path_buf);
debug_message = debug_message.AppendASCII("debug_message.exe");
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_PROCESS,
sandbox::TargetPolicy::PROCESS_MIN_EXEC,
debug_message.value().c_str());
if (result != sandbox::SBOX_ALL_OK)
return false;
#endif
AddGenericDllEvictionPolicy(policy);
return true;
}
bool AddPolicyForSandboxedProcess(sandbox::TargetPolicy* policy) {
sandbox::ResultCode result;
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
sandbox::TargetPolicy::HANDLES_DUP_ANY,
L"Event");
if (result != sandbox::SBOX_ALL_OK)
return false;
sandbox::TokenLevel initial_token = sandbox::USER_UNPROTECTED;
if (base::win::GetVersion() > base::win::VERSION_XP) {
initial_token = sandbox::USER_RESTRICTED_SAME_ACCESS;
}
policy->SetTokenLevel(initial_token, sandbox::USER_LOCKDOWN);
policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
bool use_winsta = !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kDisableAltWinstation);
if (sandbox::SBOX_ALL_OK != policy->SetAlternateDesktop(use_winsta)) {
DLOG(WARNING) << "Failed to apply desktop security to the renderer";
}
return true;
}
bool ProcessDebugFlags(CommandLine* command_line, bool is_in_sandbox) {
bool should_help_child = false;
const CommandLine& current_cmd_line = *CommandLine::ForCurrentProcess();
std::string type = command_line->GetSwitchValueASCII(switches::kProcessType);
if (current_cmd_line.HasSwitch(switches::kDebugChildren)) {
std::string value = current_cmd_line.GetSwitchValueASCII(
switches::kDebugChildren);
if (value.empty() || value == type) {
command_line->AppendSwitch(switches::kDebugOnStart);
should_help_child = true;
}
command_line->AppendSwitchASCII(switches::kDebugChildren, value);
} else if (current_cmd_line.HasSwitch(switches::kWaitForDebuggerChildren)) {
std::string value = current_cmd_line.GetSwitchValueASCII(
switches::kWaitForDebuggerChildren);
if (value.empty() || value == type) {
command_line->AppendSwitch(switches::kWaitForDebugger);
}
command_line->AppendSwitchASCII(switches::kWaitForDebuggerChildren, value);
}
return should_help_child;
}
#ifndef OFFICIAL_BUILD
base::win::IATPatchFunction g_iat_patch_duplicate_handle;
typedef BOOL (WINAPI *DuplicateHandleFunctionPtr)(HANDLE source_process_handle,
HANDLE source_handle,
HANDLE target_process_handle,
LPHANDLE target_handle,
DWORD desired_access,
BOOL inherit_handle,
DWORD options);
DuplicateHandleFunctionPtr g_iat_orig_duplicate_handle;
NtQueryObject g_QueryObject = NULL;
static const char* kDuplicateHandleWarning =
"You are attempting to duplicate a privileged handle into a sandboxed"
" process.\n Please use the sandbox::BrokerDuplicateHandle API or"
" contact security@chromium.org for assistance.";
void CheckDuplicateHandle(HANDLE handle) {
BYTE buffer[sizeof(OBJECT_TYPE_INFORMATION) + 32 * sizeof(wchar_t)];
OBJECT_TYPE_INFORMATION* type_info =
reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer);
ULONG size = sizeof(buffer) - sizeof(wchar_t);
NTSTATUS error;
error = g_QueryObject(handle, ObjectTypeInformation, type_info, size, &size);
CHECK(NT_SUCCESS(error));
type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
OBJECT_BASIC_INFORMATION basic_info;
size = sizeof(basic_info);
error = g_QueryObject(handle, ObjectBasicInformation, &basic_info, size,
&size);
CHECK(NT_SUCCESS(error));
CHECK(!(basic_info.GrantedAccess & WRITE_DAC)) <<
kDuplicateHandleWarning;
if (0 == _wcsicmp(type_info->Name.Buffer, L"Process")) {
const ACCESS_MASK kDangerousMask = ~(PROCESS_QUERY_LIMITED_INFORMATION |
SYNCHRONIZE);
CHECK(!(basic_info.GrantedAccess & kDangerousMask)) <<
kDuplicateHandleWarning;
}
}
BOOL WINAPI DuplicateHandlePatch(HANDLE source_process_handle,
HANDLE source_handle,
HANDLE target_process_handle,
LPHANDLE target_handle,
DWORD desired_access,
BOOL inherit_handle,
DWORD options) {
if (!g_iat_orig_duplicate_handle(source_process_handle, source_handle,
target_process_handle, target_handle,
desired_access, inherit_handle, options))
return FALSE;
if (source_process_handle == target_process_handle ||
target_process_handle == ::GetCurrentProcess())
return TRUE;
BOOL is_in_job = FALSE;
if (!::IsProcessInJob(target_process_handle, NULL, &is_in_job)) {
if (ERROR_ACCESS_DENIED == ::GetLastError()) {
HANDLE temp_handle;
CHECK(g_iat_orig_duplicate_handle(::GetCurrentProcess(),
target_process_handle,
::GetCurrentProcess(),
&temp_handle,
PROCESS_QUERY_INFORMATION,
FALSE, 0));
base::win::ScopedHandle process(temp_handle);
CHECK(::IsProcessInJob(process, NULL, &is_in_job));
}
}
if (is_in_job) {
CHECK(!inherit_handle) << kDuplicateHandleWarning;
HANDLE temp_handle;
CHECK(g_iat_orig_duplicate_handle(target_process_handle, *target_handle,
::GetCurrentProcess(), &temp_handle,
0, FALSE, DUPLICATE_SAME_ACCESS));
base::win::ScopedHandle handle(temp_handle);
CheckDuplicateHandle(handle);
}
return TRUE;
}
#endif
}
void SetJobLevel(const CommandLine& cmd_line,
sandbox::JobLevel job_level,
uint32 ui_exceptions,
sandbox::TargetPolicy* policy) {
if (ShouldSetJobLevel(cmd_line))
policy->SetJobLevel(job_level, ui_exceptions);
else
policy->SetJobLevel(sandbox::JOB_NONE, 0);
}
void AddBaseHandleClosePolicy(sandbox::TargetPolicy* policy) {
base::string16 object_path = PrependWindowsSessionPath(
L"\\BaseNamedObjects\\windows_shell_global_counters");
policy->AddKernelObjectToClose(L"Section", object_path.data());
}
bool InitBrokerServices(sandbox::BrokerServices* broker_services) {
DCHECK(broker_services);
DCHECK(!g_broker_services);
sandbox::ResultCode result = broker_services->Init();
g_broker_services = broker_services;
#ifndef OFFICIAL_BUILD
BOOL is_in_job = FALSE;
CHECK(::IsProcessInJob(::GetCurrentProcess(), NULL, &is_in_job));
if (!base::debug::IsBinaryInstrumented() &&
!is_in_job && !g_iat_patch_duplicate_handle.is_patched()) {
HMODULE module = NULL;
wchar_t module_name[MAX_PATH];
CHECK(::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
reinterpret_cast<LPCWSTR>(InitBrokerServices),
&module));
DWORD result = ::GetModuleFileNameW(module, module_name, MAX_PATH);
if (result && (result != MAX_PATH)) {
ResolveNTFunctionPtr("NtQueryObject", &g_QueryObject);
result = g_iat_patch_duplicate_handle.Patch(
module_name, "kernel32.dll", "DuplicateHandle",
DuplicateHandlePatch);
CHECK(result == 0);
g_iat_orig_duplicate_handle =
reinterpret_cast<DuplicateHandleFunctionPtr>(
g_iat_patch_duplicate_handle.original_function());
}
}
#endif
return sandbox::SBOX_ALL_OK == result;
}
bool InitTargetServices(sandbox::TargetServices* target_services) {
DCHECK(target_services);
DCHECK(!g_target_services);
sandbox::ResultCode result = target_services->Init();
g_target_services = target_services;
return sandbox::SBOX_ALL_OK == result;
}
bool ShouldUseDirectWrite() {
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
return command_line.HasSwitch(switches::kEnableDirectWrite) &&
base::win::GetVersion() >= base::win::VERSION_WIN7;
}
base::ProcessHandle StartSandboxedProcess(
SandboxedProcessLauncherDelegate* delegate,
CommandLine* cmd_line) {
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
std::string type_str = cmd_line->GetSwitchValueASCII(switches::kProcessType);
TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess", 0, type_str);
bool in_sandbox = true;
if (delegate)
in_sandbox = delegate->ShouldSandbox();
if (browser_command_line.HasSwitch(switches::kNoSandbox) ||
cmd_line->HasSwitch(switches::kNoSandbox)) {
in_sandbox = false;
}
if (browser_command_line.HasSwitch(switches::kAllowNoSandboxJob) &&
!cmd_line->HasSwitch(switches::kAllowNoSandboxJob)) {
cmd_line->AppendSwitch(switches::kAllowNoSandboxJob);
}
bool child_needs_help = ProcessDebugFlags(cmd_line, in_sandbox);
cmd_line->AppendArg(base::StringPrintf("/prefetch:%d", base::Hash(type_str)));
if (!in_sandbox) {
base::ProcessHandle process = 0;
base::LaunchProcess(*cmd_line, base::LaunchOptions(), &process);
g_broker_services->AddTargetPeer(process);
return process;
}
sandbox::TargetPolicy* policy = g_broker_services->CreatePolicy();
sandbox::MitigationFlags mitigations = sandbox::MITIGATION_HEAP_TERMINATE |
sandbox::MITIGATION_BOTTOM_UP_ASLR |
sandbox::MITIGATION_DEP |
sandbox::MITIGATION_DEP_NO_ATL_THUNK |
sandbox::MITIGATION_SEHOP;
if (policy->SetProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
return 0;
mitigations = sandbox::MITIGATION_STRICT_HANDLE_CHECKS |
sandbox::MITIGATION_DLL_SEARCH_ORDER;
if (policy->SetDelayedProcessMitigations(mitigations) != sandbox::SBOX_ALL_OK)
return 0;
SetJobLevel(*cmd_line, sandbox::JOB_LOCKDOWN, 0, policy);
bool disable_default_policy = false;
base::FilePath exposed_dir;
if (delegate)
delegate->PreSandbox(&disable_default_policy, &exposed_dir);
if (!disable_default_policy && !AddPolicyForSandboxedProcess(policy))
return 0;
if (type_str == switches::kRendererProcess) {
if (ShouldUseDirectWrite()) {
AddDirectory(base::DIR_WINDOWS_FONTS,
NULL,
true,
sandbox::TargetPolicy::FILES_ALLOW_READONLY,
policy);
}
} else {
cmd_line->AppendSwitchASCII("ignored", " --type=renderer ");
}
sandbox::ResultCode result;
if (!exposed_dir.empty()) {
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
sandbox::TargetPolicy::FILES_ALLOW_ANY,
exposed_dir.value().c_str());
if (result != sandbox::SBOX_ALL_OK)
return 0;
base::FilePath exposed_files = exposed_dir.AppendASCII("*");
result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
sandbox::TargetPolicy::FILES_ALLOW_ANY,
exposed_files.value().c_str());
if (result != sandbox::SBOX_ALL_OK)
return 0;
}
if (!AddGenericPolicy(policy)) {
NOTREACHED();
return 0;
}
if (browser_command_line.HasSwitch(switches::kEnableLogging)) {
policy->SetStdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE));
policy->SetStderrHandle(GetStdHandle(STD_ERROR_HANDLE));
}
if (delegate) {
bool success = true;
delegate->PreSpawnTarget(policy, &success);
if (!success)
return 0;
}
TRACE_EVENT_BEGIN_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
PROCESS_INFORMATION temp_process_info = {};
result = g_broker_services->SpawnTarget(
cmd_line->GetProgram().value().c_str(),
cmd_line->GetCommandLineString().c_str(),
policy, &temp_process_info);
policy->Release();
base::win::ScopedProcessInformation target(temp_process_info);
TRACE_EVENT_END_ETW("StartProcessWithAccess::LAUNCHPROCESS", 0, 0);
if (sandbox::SBOX_ALL_OK != result) {
if (result == sandbox::SBOX_ERROR_GENERIC)
DPLOG(ERROR) << "Failed to launch process";
else
DLOG(ERROR) << "Failed to launch process. Error: " << result;
return 0;
}
if (delegate)
delegate->PostSpawnTarget(target.process_handle());
ResumeThread(target.thread_handle());
if (child_needs_help)
base::debug::SpawnDebuggerOnProcess(target.process_id());
return target.TakeProcessHandle();
}
bool BrokerDuplicateHandle(HANDLE source_handle,
DWORD target_process_id,
HANDLE* target_handle,
DWORD desired_access,
DWORD options) {
if (::GetCurrentProcessId() == target_process_id) {
return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
::GetCurrentProcess(), target_handle,
desired_access, FALSE, options);
}
if (g_target_services &&
g_target_services->DuplicateHandle(source_handle, target_process_id,
target_handle, desired_access,
options) == sandbox::SBOX_ALL_OK) {
return true;
}
base::win::ScopedHandle target_process;
target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE,
target_process_id));
if (target_process.IsValid()) {
return !!::DuplicateHandle(::GetCurrentProcess(), source_handle,
target_process, target_handle,
desired_access, FALSE, options);
}
return false;
}
bool BrokerAddTargetPeer(HANDLE peer_process) {
return g_broker_services->AddTargetPeer(peer_process) == sandbox::SBOX_ALL_OK;
}
}