diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2020-03-11 11:32:04 +0100 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2020-03-18 13:40:17 +0000 |
commit | 31ccca0778db85c159634478b4ec7997f6704860 (patch) | |
tree | 3d33fc3afd9d5ec95541e1bbe074a9cf8da12a0e /chromium/sandbox | |
parent | 248b70b82a40964d5594eb04feca0fa36716185d (diff) | |
download | qtwebengine-chromium-31ccca0778db85c159634478b4ec7997f6704860.tar.gz |
BASELINE: Update Chromium to 80.0.3987.136
Change-Id: I98e1649aafae85ba3a83e67af00bb27ef301db7b
Reviewed-by: Jüri Valdmann <juri.valdmann@qt.io>
Diffstat (limited to 'chromium/sandbox')
107 files changed, 1253 insertions, 859 deletions
diff --git a/chromium/sandbox/linux/seccomp-bpf-helpers/baseline_policy.cc b/chromium/sandbox/linux/seccomp-bpf-helpers/baseline_policy.cc index 806d13c1a84..768025ce192 100644 --- a/chromium/sandbox/linux/seccomp-bpf-helpers/baseline_policy.cc +++ b/chromium/sandbox/linux/seccomp-bpf-helpers/baseline_policy.cc @@ -148,7 +148,7 @@ ResultExpr EvaluateSyscallImpl(int fs_denied_errno, return Allow(); #endif - if (sysno == __NR_clock_gettime) { + if (sysno == __NR_clock_gettime || sysno == __NR_clock_nanosleep) { return RestrictClockID(); } diff --git a/chromium/sandbox/linux/seccomp-bpf-helpers/baseline_policy_unittest.cc b/chromium/sandbox/linux/seccomp-bpf-helpers/baseline_policy_unittest.cc index b56b2944f17..c0a51dad101 100644 --- a/chromium/sandbox/linux/seccomp-bpf-helpers/baseline_policy_unittest.cc +++ b/chromium/sandbox/linux/seccomp-bpf-helpers/baseline_policy_unittest.cc @@ -38,6 +38,7 @@ #include "sandbox/linux/services/thread_helpers.h" #include "sandbox/linux/system_headers/linux_futex.h" #include "sandbox/linux/system_headers/linux_syscalls.h" +#include "sandbox/linux/system_headers/linux_time.h" #include "sandbox/linux/tests/test_utils.h" #include "sandbox/linux/tests/unit_tests.h" @@ -394,7 +395,18 @@ BPF_DEATH_TEST_C(BaselinePolicy, DEATH_SEGV_MESSAGE(GetErrorMessageContentForTests()), BaselinePolicy) { struct timespec ts; - syscall(SYS_clock_gettime, CLOCK_MONOTONIC_RAW, &ts); + syscall(SYS_clock_gettime, (~0) | CLOCKFD, &ts); +} + +BPF_DEATH_TEST_C(BaselinePolicy, + ClockNanosleepWithDisallowedClockCrashes, + DEATH_SEGV_MESSAGE(GetErrorMessageContentForTests()), + BaselinePolicy) { + struct timespec ts; + struct timespec out_ts; + ts.tv_sec = 0; + ts.tv_nsec = 0; + syscall(SYS_clock_nanosleep, (~0) | CLOCKFD, 0, &ts, &out_ts); } #if !defined(GRND_RANDOM) diff --git a/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.cc b/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.cc index 348ab6e8c5e..d9789a7133e 100644 --- a/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.cc +++ b/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.cc @@ -372,11 +372,10 @@ ResultExpr RestrictClockID() { return If((clockid & kIsPidBit) == 0, Switch(clockid).CASES(( -#if defined(OS_ANDROID) CLOCK_BOOTTIME, -#endif CLOCK_MONOTONIC, CLOCK_MONOTONIC_COARSE, + CLOCK_MONOTONIC_RAW, CLOCK_PROCESS_CPUTIME_ID, CLOCK_REALTIME, CLOCK_REALTIME_COARSE, diff --git a/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.h b/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.h index cb563dfc550..15442892bcb 100644 --- a/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.h +++ b/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.h @@ -86,12 +86,13 @@ SANDBOX_EXPORT bpf_dsl::ResultExpr RestrictPrlimit64(pid_t target_pid); // process). SANDBOX_EXPORT bpf_dsl::ResultExpr RestrictGetrusage(); -// Restrict |clk_id| for clock_getres(), clock_gettime() and clock_settime(). -// We allow accessing only CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID, -// CLOCK_REALTIME, and CLOCK_THREAD_CPUTIME_ID. In particular, this disallows -// access to arbitrary per-{process,thread} CPU-time clock IDs (such as those -// returned by {clock,pthread}_getcpuclockid), which can leak information -// about the state of the host OS. +// Restrict |clk_id| for clock_getres(), clock_gettime(), clock_settime(), and +// clock_nanosleep(). We allow accessing only CLOCK_BOOTTIME, +// CLOCK_MONOTONIC{,_RAW,_COARSE}, CLOCK_PROCESS_CPUTIME_ID, +// CLOCK_REALTIME{,_COARSE}, and CLOCK_THREAD_CPUTIME_ID. In particular, on +// non-Android platforms this disallows access to arbitrary per-{process,thread} +// CPU-time clock IDs (such as those returned by {clock,pthread}_getcpuclockid), +// which can leak information about the state of the host OS. SANDBOX_EXPORT bpf_dsl::ResultExpr RestrictClockID(); // Restrict the flags argument to getrandom() to allow only no flags, or diff --git a/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc b/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc index fdd954cc0fd..b6c8c637746 100644 --- a/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc +++ b/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions_unittests.cc @@ -59,6 +59,7 @@ class RestrictClockIdPolicy : public bpf_dsl::Policy { switch (sysno) { case __NR_clock_gettime: case __NR_clock_getres: + case __NR_clock_nanosleep: return RestrictClockID(); default: return Allow(); @@ -85,10 +86,9 @@ BPF_TEST_C(ParameterRestrictions, RestrictClockIdPolicy) { CheckClock(CLOCK_MONOTONIC); CheckClock(CLOCK_MONOTONIC_COARSE); + CheckClock(CLOCK_MONOTONIC_RAW); CheckClock(CLOCK_PROCESS_CPUTIME_ID); -#if defined(OS_ANDROID) CheckClock(CLOCK_BOOTTIME); -#endif CheckClock(CLOCK_REALTIME); CheckClock(CLOCK_REALTIME_COARSE); CheckClock(CLOCK_THREAD_CPUTIME_ID); @@ -99,12 +99,42 @@ BPF_TEST_C(ParameterRestrictions, #endif } +void CheckClockNanosleep(clockid_t clockid) { + struct timespec ts; + struct timespec out_ts; + ts.tv_sec = 0; + ts.tv_nsec = 0; + clock_nanosleep(clockid, 0, &ts, &out_ts); +} + +BPF_TEST_C(ParameterRestrictions, + clock_nanosleep_allowed, + RestrictClockIdPolicy) { + CheckClockNanosleep(CLOCK_MONOTONIC); + CheckClockNanosleep(CLOCK_MONOTONIC_COARSE); + CheckClockNanosleep(CLOCK_MONOTONIC_RAW); + CheckClockNanosleep(CLOCK_BOOTTIME); + CheckClockNanosleep(CLOCK_REALTIME); + CheckClockNanosleep(CLOCK_REALTIME_COARSE); +} + +BPF_DEATH_TEST_C(ParameterRestrictions, + clock_gettime_crash_clock_fd, + DEATH_SEGV_MESSAGE(sandbox::GetErrorMessageContentForTests()), + RestrictClockIdPolicy) { + struct timespec ts; + syscall(SYS_clock_gettime, (~0) | CLOCKFD, &ts); +} + BPF_DEATH_TEST_C(ParameterRestrictions, - clock_gettime_crash_monotonic_raw, + clock_nanosleep_crash_clock_fd, DEATH_SEGV_MESSAGE(sandbox::GetErrorMessageContentForTests()), RestrictClockIdPolicy) { struct timespec ts; - syscall(SYS_clock_gettime, CLOCK_MONOTONIC_RAW, &ts); + struct timespec out_ts; + ts.tv_sec = 0; + ts.tv_nsec = 0; + syscall(SYS_clock_nanosleep, (~0) | CLOCKFD, 0, &ts, &out_ts); } #if !defined(OS_ANDROID) diff --git a/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_sets.cc b/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_sets.cc index 4e0ad046299..d9d18822f67 100644 --- a/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_sets.cc +++ b/chromium/sandbox/linux/seccomp-bpf-helpers/syscall_sets.cc @@ -35,9 +35,10 @@ bool SyscallSets::IsAllowedGettime(int sysno) { return true; case __NR_adjtimex: // Privileged. case __NR_clock_adjtime: // Privileged. - case __NR_clock_getres: // Could be allowed. - case __NR_clock_gettime: - case __NR_clock_nanosleep: // Could be allowed. + case __NR_clock_getres: // Allowed only on Android with parameters + // filtered by RestrictClokID(). + case __NR_clock_gettime: // Parameters filtered by RestrictClockID(). + case __NR_clock_nanosleep: // Parameters filtered by RestrictClockID(). case __NR_clock_settime: // Privileged. #if defined(__i386__) || \ (defined(ARCH_CPU_MIPS_FAMILY) && defined(ARCH_CPU_32_BITS)) diff --git a/chromium/sandbox/linux/services/libc_interceptor.cc b/chromium/sandbox/linux/services/libc_interceptor.cc index d25b5091bb5..cff3ea4a3bb 100644 --- a/chromium/sandbox/linux/services/libc_interceptor.cc +++ b/chromium/sandbox/linux/services/libc_interceptor.cc @@ -20,9 +20,8 @@ #include <set> #include <string> +#include "base/compiler_specific.h" #include "base/lazy_instance.h" -#include "base/memory/protected_memory.h" -#include "base/memory/protected_memory_cfi.h" #include "base/pickle.h" #include "base/posix/eintr_wrapper.h" #include "base/posix/global_descriptors.h" @@ -174,32 +173,24 @@ bool HandleLocalTime(int fd, typedef struct tm* (*LocaltimeFunction)(const time_t* timep); typedef struct tm* (*LocaltimeRFunction)(const time_t* timep, struct tm* result); -struct LibcFunctions { - LocaltimeFunction localtime; - LocaltimeFunction localtime64; - LocaltimeRFunction localtime_r; - LocaltimeRFunction localtime64_r; -}; - -static pthread_once_t g_libc_funcs_guard = PTHREAD_ONCE_INIT; -// The libc function pointers are stored in read-only memory after being -// dynamically resolved as a security mitigation to prevent the pointer from -// being tampered with. See https://crbug.com/771365 for details. -static PROTECTED_MEMORY_SECTION base::ProtectedMemory<LibcFunctions> - g_libc_funcs; + +static pthread_once_t g_libc_localtime_funcs_guard = PTHREAD_ONCE_INIT; +static LocaltimeFunction g_libc_localtime; +static LocaltimeFunction g_libc_localtime64; +static LocaltimeRFunction g_libc_localtime_r; +static LocaltimeRFunction g_libc_localtime64_r; static void InitLibcLocaltimeFunctionsImpl() { - auto writer = base::AutoWritableMemory::Create(g_libc_funcs); - g_libc_funcs->localtime = + g_libc_localtime = reinterpret_cast<LocaltimeFunction>(dlsym(RTLD_NEXT, "localtime")); - g_libc_funcs->localtime64 = + g_libc_localtime64 = reinterpret_cast<LocaltimeFunction>(dlsym(RTLD_NEXT, "localtime64")); - g_libc_funcs->localtime_r = + g_libc_localtime_r = reinterpret_cast<LocaltimeRFunction>(dlsym(RTLD_NEXT, "localtime_r")); - g_libc_funcs->localtime64_r = + g_libc_localtime64_r = reinterpret_cast<LocaltimeRFunction>(dlsym(RTLD_NEXT, "localtime64_r")); - if (!g_libc_funcs->localtime || !g_libc_funcs->localtime_r) { + if (!g_libc_localtime || !g_libc_localtime_r) { // https://bugs.chromium.org/p/chromium/issues/detail?id=16800 // // Nvidia's libGL.so overrides dlsym for an unknown reason and replaces @@ -211,14 +202,14 @@ static void InitLibcLocaltimeFunctionsImpl() { "https://bugs.chromium.org/p/chromium/issues/detail?id=16800"; } - if (!g_libc_funcs->localtime) - g_libc_funcs->localtime = gmtime; - if (!g_libc_funcs->localtime64) - g_libc_funcs->localtime64 = g_libc_funcs->localtime; - if (!g_libc_funcs->localtime_r) - g_libc_funcs->localtime_r = gmtime_r; - if (!g_libc_funcs->localtime64_r) - g_libc_funcs->localtime64_r = g_libc_funcs->localtime_r; + if (!g_libc_localtime) + g_libc_localtime = gmtime; + if (!g_libc_localtime64) + g_libc_localtime64 = g_libc_localtime; + if (!g_libc_localtime_r) + g_libc_localtime_r = gmtime_r; + if (!g_libc_localtime64_r) + g_libc_localtime64_r = g_libc_localtime_r; } // Define localtime_override() function with asm name "localtime", so that all @@ -228,6 +219,7 @@ static void InitLibcLocaltimeFunctionsImpl() { __attribute__((__visibility__("default"))) struct tm* localtime_override( const time_t* timep) __asm__("localtime"); +NO_SANITIZE("cfi-icall") __attribute__((__visibility__("default"))) struct tm* localtime_override( const time_t* timep) { if (g_am_zygote_or_renderer && g_use_localtime_override) { @@ -239,8 +231,7 @@ __attribute__((__visibility__("default"))) struct tm* localtime_override( } InitLibcLocaltimeFunctions(); - struct tm* res = - base::UnsanitizedCfiCall(g_libc_funcs, &LibcFunctions::localtime)(timep); + struct tm* res = g_libc_localtime(timep); #if defined(MEMORY_SANITIZER) if (res) __msan_unpoison(res, sizeof(*res)); @@ -254,6 +245,7 @@ __attribute__((__visibility__("default"))) struct tm* localtime_override( __attribute__((__visibility__("default"))) struct tm* localtime64_override( const time_t* timep) __asm__("localtime64"); +NO_SANITIZE("cfi-icall") __attribute__((__visibility__("default"))) struct tm* localtime64_override( const time_t* timep) { if (g_am_zygote_or_renderer && g_use_localtime_override) { @@ -265,8 +257,7 @@ __attribute__((__visibility__("default"))) struct tm* localtime64_override( } InitLibcLocaltimeFunctions(); - struct tm* res = base::UnsanitizedCfiCall(g_libc_funcs, - &LibcFunctions::localtime64)(timep); + struct tm* res = g_libc_localtime64(timep); #if defined(MEMORY_SANITIZER) if (res) __msan_unpoison(res, sizeof(*res)); @@ -280,6 +271,7 @@ __attribute__((__visibility__("default"))) struct tm* localtime_r_override( const time_t* timep, struct tm* result) __asm__("localtime_r"); +NO_SANITIZE("cfi-icall") __attribute__((__visibility__("default"))) struct tm* localtime_r_override( const time_t* timep, struct tm* result) { @@ -289,8 +281,7 @@ __attribute__((__visibility__("default"))) struct tm* localtime_r_override( } InitLibcLocaltimeFunctions(); - struct tm* res = base::UnsanitizedCfiCall( - g_libc_funcs, &LibcFunctions::localtime_r)(timep, result); + struct tm* res = g_libc_localtime_r(timep, result); #if defined(MEMORY_SANITIZER) if (res) __msan_unpoison(res, sizeof(*res)); @@ -304,6 +295,7 @@ __attribute__((__visibility__("default"))) struct tm* localtime64_r_override( const time_t* timep, struct tm* result) __asm__("localtime64_r"); +NO_SANITIZE("cfi-icall") __attribute__((__visibility__("default"))) struct tm* localtime64_r_override( const time_t* timep, struct tm* result) { @@ -313,8 +305,7 @@ __attribute__((__visibility__("default"))) struct tm* localtime64_r_override( } InitLibcLocaltimeFunctions(); - struct tm* res = base::UnsanitizedCfiCall( - g_libc_funcs, &LibcFunctions::localtime64_r)(timep, result); + struct tm* res = g_libc_localtime64_r(timep, result); #if defined(MEMORY_SANITIZER) if (res) __msan_unpoison(res, sizeof(*res)); @@ -344,8 +335,8 @@ bool HandleInterceptedCall(int kind, } void InitLibcLocaltimeFunctions() { - CHECK_EQ(0, - pthread_once(&g_libc_funcs_guard, InitLibcLocaltimeFunctionsImpl)); + CHECK_EQ(0, pthread_once(&g_libc_localtime_funcs_guard, + InitLibcLocaltimeFunctionsImpl)); } } // namespace sandbox diff --git a/chromium/sandbox/linux/syscall_broker/broker_process.cc b/chromium/sandbox/linux/syscall_broker/broker_process.cc index 800888f9024..19b825a150d 100644 --- a/chromium/sandbox/linux/syscall_broker/broker_process.cc +++ b/chromium/sandbox/linux/syscall_broker/broker_process.cc @@ -73,6 +73,7 @@ bool BrokerProcess::Init( return false; if (child_pid) { + VLOG(3) << "BrokerProcess::Init(), in parent, child is " << child_pid; // We are the parent and we have just forked our broker process. ipc_reader.reset(); broker_pid_ = child_pid; @@ -85,6 +86,7 @@ bool BrokerProcess::Init( // We are the broker process. Make sure to close the writer's end so that // we get notified if the client disappears. + VLOG(3) << "BrokerProcess::Init(), in child"; ipc_writer.reset(); CHECK(std::move(broker_process_init_callback).Run()); BrokerHost broker_host(broker_permission_list_, allowed_command_set_, diff --git a/chromium/sandbox/linux/system_headers/linux_time.h b/chromium/sandbox/linux/system_headers/linux_time.h index 8de1cc100d2..780f24dddd9 100644 --- a/chromium/sandbox/linux/system_headers/linux_time.h +++ b/chromium/sandbox/linux/system_headers/linux_time.h @@ -15,6 +15,10 @@ #define CLOCKFD 3 #endif +#if !defined(CLOCK_MONOTONIC_RAW) +#define CLOCK_MONOTONIC_RAW 4 +#endif + #if !defined(CLOCK_REALTIME_COARSE) #define CLOCK_REALTIME_COARSE 5 #endif @@ -23,4 +27,8 @@ #define CLOCK_MONOTONIC_COARSE 6 #endif +#if !defined(CLOCK_BOOTTIME) +#define CLOCK_BOOTTIME 7 +#endif + #endif // SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_TIME_H_ diff --git a/chromium/sandbox/win/sandbox_poc/main_ui_window.cc b/chromium/sandbox/win/sandbox_poc/main_ui_window.cc index 6bdc171823b..bd6a2b78a47 100644 --- a/chromium/sandbox/win/sandbox_poc/main_ui_window.cc +++ b/chromium/sandbox/win/sandbox_poc/main_ui_window.cc @@ -175,8 +175,8 @@ INT_PTR CALLBACK MainUIWindow::SpawnTargetWndProc(HWND dialog, HWND edit_box_dll_name = ::GetDlgItem(dialog, IDC_DLL_NAME); wchar_t current_dir[MAX_PATH]; if (GetCurrentDirectory(MAX_PATH, current_dir)) { - base::string16 dll_path = base::string16(current_dir) + - base::string16(kDefaultDll_); + std::wstring dll_path = + std::wstring(current_dir) + std::wstring(kDefaultDll_); ::SetWindowText(edit_box_dll_name, dll_path.c_str()); } @@ -205,7 +205,7 @@ INT_PTR CALLBACK MainUIWindow::SpawnTargetWndProc(HWND dialog, return static_cast<INT_PTR>(TRUE); } else if (LOWORD(wparam) == IDC_BROWSE_DLL) { // If the user presses the Browse button to look for a DLL - base::string16 dll_path = host->OnShowBrowseForDllDlg(dialog); + std::wstring dll_path = host->OnShowBrowseForDllDlg(dialog); if (dll_path.length() > 0) { // Initialize the window text for Log File edit box HWND edit_box_dll_path = ::GetDlgItem(dialog, IDC_DLL_NAME); @@ -214,7 +214,7 @@ INT_PTR CALLBACK MainUIWindow::SpawnTargetWndProc(HWND dialog, return static_cast<INT_PTR>(TRUE); } else if (LOWORD(wparam) == IDC_BROWSE_LOG) { // If the user presses the Browse button to look for a log file - base::string16 log_path = host->OnShowBrowseForLogFileDlg(dialog); + std::wstring log_path = host->OnShowBrowseForLogFileDlg(dialog); if (log_path.length() > 0) { // Initialize the window text for Log File edit box HWND edit_box_log_file = ::GetDlgItem(dialog, IDC_LOG_FILE); @@ -350,7 +350,7 @@ bool MainUIWindow::OnLaunchDll(HWND dialog) { } // store these values in the member variables for use in SpawnTarget - log_file_ = base::string16(L"\"") + log_file + base::string16(L"\""); + log_file_ = std::wstring(L"\"") + log_file + std::wstring(L"\""); dll_path_ = dll_path; entry_point_ = entry_point; @@ -519,7 +519,7 @@ bool MainUIWindow::SpawnTarget() { broker_->SpawnTarget(spawn_target_.c_str(), arguments, policy, &warning_result, &last_error, &target_); - policy = NULL; + policy.reset(); bool return_value = false; if (sandbox::SBOX_ALL_OK != result) { @@ -571,7 +571,7 @@ bool MainUIWindow::SpawnTarget() { return return_value; } -base::string16 MainUIWindow::OnShowBrowseForDllDlg(HWND owner) { +std::wstring MainUIWindow::OnShowBrowseForDllDlg(HWND owner) { wchar_t filename[MAX_PATH]; wcscpy_s(filename, MAX_PATH, L""); @@ -591,7 +591,7 @@ base::string16 MainUIWindow::OnShowBrowseForDllDlg(HWND owner) { return L""; } -base::string16 MainUIWindow::OnShowBrowseForLogFileDlg(HWND owner) { +std::wstring MainUIWindow::OnShowBrowseForLogFileDlg(HWND owner) { wchar_t filename[MAX_PATH]; wcscpy_s(filename, MAX_PATH, L""); diff --git a/chromium/sandbox/win/sandbox_poc/main_ui_window.h b/chromium/sandbox/win/sandbox_poc/main_ui_window.h index 5bf98dd4261..29f3b657af1 100644 --- a/chromium/sandbox/win/sandbox_poc/main_ui_window.h +++ b/chromium/sandbox/win/sandbox_poc/main_ui_window.h @@ -10,7 +10,6 @@ #include <string> #include "base/macros.h" -#include "base/strings/string16.h" namespace sandbox { class BrokerServices; @@ -126,11 +125,11 @@ class MainUIWindow { // Shows a standard File Open dialog and returns the DLL filename selected or // blank string if the user cancelled (or an error occurred). - base::string16 OnShowBrowseForDllDlg(HWND owner); + std::wstring OnShowBrowseForDllDlg(HWND owner); // Shows a standard Save As dialog and returns the log filename selected or // blank string if the user cancelled (or an error occurred). - base::string16 OnShowBrowseForLogFileDlg(HWND owner); + std::wstring OnShowBrowseForLogFileDlg(HWND owner); // Formats a message using the supplied format string and prints it in the // listview in the main UI window. Passing a NULL param in 'fmt' results in @@ -166,20 +165,20 @@ class MainUIWindow { // This is essentially a command line to a target executable that the // broker will spawn and ask to load the DLL. - base::string16 spawn_target_; + std::wstring spawn_target_; // A handle to the current instance of the app. Passed in to this class // through CreateMainWindowAndLoop. HINSTANCE instance_handle_; // A path to the DLL that the target should load once it executes. - base::string16 dll_path_; + std::wstring dll_path_; // The name of the entry point the target should call after it loads the DLL. - base::string16 entry_point_; + std::wstring entry_point_; // The name of the log file to use. - base::string16 log_file_; + std::wstring log_file_; // This is a static handle to the list view that fills up the entire main // UI window. The list view is used to display debugging information to the diff --git a/chromium/sandbox/win/sandbox_poc/pocdll/spyware.cc b/chromium/sandbox/win/sandbox_poc/pocdll/spyware.cc index cf0bd4177f9..6130f674cd7 100644 --- a/chromium/sandbox/win/sandbox_poc/pocdll/spyware.cc +++ b/chromium/sandbox/win/sandbox_poc/pocdll/spyware.cc @@ -4,7 +4,6 @@ #include <string> -#include "base/strings/string16.h" #include "sandbox/win/sandbox_poc/pocdll/exports.h" #include "sandbox/win/sandbox_poc/pocdll/utils.h" @@ -25,7 +24,7 @@ void POCDLL_API TestSpyKeys(HANDLE log) { fprintf(output, "[INFO] Logging keystrokes for 15 seconds\r\n"); fflush(output); - base::string16 logged; + std::wstring logged; DWORD tick = ::GetTickCount() + 15000; while (tick > ::GetTickCount()) { for (int i = 0; i < 256; ++i) { diff --git a/chromium/sandbox/win/sandbox_poc/sandbox.cc b/chromium/sandbox/win/sandbox_poc/sandbox.cc index 6d49a803363..aa6cf12e25a 100644 --- a/chromium/sandbox/win/sandbox_poc/sandbox.cc +++ b/chromium/sandbox/win/sandbox_poc/sandbox.cc @@ -18,10 +18,10 @@ // Prototype allowed for functions to be called in the POC typedef void(__cdecl *lpfnInit)(HANDLE); -bool ParseCommandLine(wchar_t * command_line, - std::string * dll_name, - std::string * entry_point, - base::string16 * log_file) { +bool ParseCommandLine(wchar_t* command_line, + std::string* dll_name, + std::string* entry_point, + std::wstring* log_file) { DCHECK(dll_name); DCHECK(entry_point); DCHECK(log_file); @@ -39,8 +39,8 @@ bool ParseCommandLine(wchar_t * command_line, return false; } - base::string16 entry_point_wide = arg_list[1]; - base::string16 dll_name_wide = arg_list[2]; + std::wstring entry_point_wide = arg_list[1]; + std::wstring dll_name_wide = arg_list[2]; *entry_point = std::string(entry_point_wide.begin(), entry_point_wide.end()); *dll_name = std::string(dll_name_wide.begin(), dll_name_wide.end()); *log_file = arg_list[3]; @@ -128,7 +128,7 @@ int APIENTRY _tWinMain(HINSTANCE instance, HINSTANCE, wchar_t* command_line, // Parse the command line to find out what we need to call std::string dll_name, entry_point; - base::string16 log_file; + std::wstring log_file; if (!ParseCommandLine(GetCommandLineW(), &dll_name, &entry_point, diff --git a/chromium/sandbox/win/src/app_container_profile_base.cc b/chromium/sandbox/win/src/app_container_profile_base.cc index 2203b714e75..01ce7f70ce0 100644 --- a/chromium/sandbox/win/src/app_container_profile_base.cc +++ b/chromium/sandbox/win/src/app_container_profile_base.cc @@ -177,7 +177,7 @@ bool AppContainerProfileBase::GetFolderPath(base::FilePath* file_path) { GetModuleHandle(L"userenv"), "GetAppContainerFolderPath")); if (!get_app_container_folder_path) return false; - base::string16 sddl_str; + std::wstring sddl_str; if (!package_sid_.ToSddlString(&sddl_str)) return false; base::win::ScopedCoMem<wchar_t> path_str; @@ -189,7 +189,7 @@ bool AppContainerProfileBase::GetFolderPath(base::FilePath* file_path) { bool AppContainerProfileBase::GetPipePath(const wchar_t* pipe_name, base::FilePath* pipe_path) { - base::string16 sddl_str; + std::wstring sddl_str; if (!package_sid_.ToSddlString(&sddl_str)) return false; *pipe_path = base::FilePath(base::StringPrintf(L"\\\\.\\pipe\\%ls\\%ls", diff --git a/chromium/sandbox/win/src/app_container_unittest.cc b/chromium/sandbox/win/src/app_container_unittest.cc index 4b90b9a4c52..d2689e295f2 100644 --- a/chromium/sandbox/win/src/app_container_unittest.cc +++ b/chromium/sandbox/win/src/app_container_unittest.cc @@ -120,7 +120,7 @@ class SECURITY_ATTRIBUTES_SDDL : public SECURITY_ATTRIBUTES { }; std::wstring CreateSddlWithSid(const Sid& sid) { - base::string16 sddl_string; + std::wstring sddl_string; if (!sid.ToSddlString(&sddl_string)) return L""; std::wstring base_sddl = L"D:(A;;GA;;;WD)(A;;GA;;;"; diff --git a/chromium/sandbox/win/src/broker_services.cc b/chromium/sandbox/win/src/broker_services.cc index bc9da0ce0ca..96c490bad3d 100644 --- a/chromium/sandbox/win/src/broker_services.cc +++ b/chromium/sandbox/win/src/broker_services.cc @@ -245,6 +245,16 @@ DWORD WINAPI BrokerServicesBase::TargetEventsThread(PVOID param) { // that jobs can send and some of them depend on the job attributes set. JobTracker* tracker = reinterpret_cast<JobTracker*>(key); + // Processes may be added to a job after the process count has + // reached zero, leading us to manipulate a freed JobTracker + // object or job handle (as the key is no longer valid). We + // therefore check if the tracker has already been deleted. + if (std::find_if(jobs.begin(), jobs.end(), [&](auto&& p) -> bool { + return p.get() == tracker; + }) == jobs.end()) { + CHECK(false); + } + switch (events) { case JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: { // The job object has signaled that the last process associated @@ -465,7 +475,7 @@ ResultCode BrokerServicesBase::SpawnTarget(const wchar_t* exe_path, std::vector<HANDLE> inherited_handle_list; DWORD child_process_creation = PROCESS_CREATION_CHILD_PROCESS_RESTRICTED; - base::string16 desktop = policy_base->GetAlternateDesktop(); + std::wstring desktop = policy_base->GetAlternateDesktop(); if (!desktop.empty()) { startup_info.startup_info()->lpDesktop = const_cast<wchar_t*>(desktop.c_str()); diff --git a/chromium/sandbox/win/src/crosscall_client.h b/chromium/sandbox/win/src/crosscall_client.h index 98cd65dc55f..84fd090a72a 100644 --- a/chromium/sandbox/win/src/crosscall_client.h +++ b/chromium/sandbox/win/src/crosscall_client.h @@ -42,6 +42,8 @@ // return codes indicate that the IPC transport failed to deliver it. namespace sandbox { +enum class IpcTag; + // this is the assumed channel size. This can be overridden in a given // IPC implementation. const uint32_t kIPCChannelSize = 1024; @@ -272,7 +274,7 @@ class CopyHelper<InOutCountedBuffer> { // CrossCall template with one input parameter template <typename IPCProvider, typename Par1> ResultCode CrossCall(IPCProvider& ipc_provider, - uint32_t tag, + IpcTag tag, const Par1& p1, CrossCallReturn* answer) { XCALL_GEN_PARAMS_OBJ(1, call_params); @@ -291,7 +293,7 @@ ResultCode CrossCall(IPCProvider& ipc_provider, // CrossCall template with two input parameters. template <typename IPCProvider, typename Par1, typename Par2> ResultCode CrossCall(IPCProvider& ipc_provider, - uint32_t tag, + IpcTag tag, const Par1& p1, const Par2& p2, CrossCallReturn* answer) { @@ -312,7 +314,7 @@ ResultCode CrossCall(IPCProvider& ipc_provider, // CrossCall template with three input parameters. template <typename IPCProvider, typename Par1, typename Par2, typename Par3> ResultCode CrossCall(IPCProvider& ipc_provider, - uint32_t tag, + IpcTag tag, const Par1& p1, const Par2& p2, const Par3& p3, @@ -340,7 +342,7 @@ template <typename IPCProvider, typename Par3, typename Par4> ResultCode CrossCall(IPCProvider& ipc_provider, - uint32_t tag, + IpcTag tag, const Par1& p1, const Par2& p2, const Par3& p3, @@ -372,7 +374,7 @@ template <typename IPCProvider, typename Par4, typename Par5> ResultCode CrossCall(IPCProvider& ipc_provider, - uint32_t tag, + IpcTag tag, const Par1& p1, const Par2& p2, const Par3& p3, @@ -408,7 +410,7 @@ template <typename IPCProvider, typename Par5, typename Par6> ResultCode CrossCall(IPCProvider& ipc_provider, - uint32_t tag, + IpcTag tag, const Par1& p1, const Par2& p2, const Par3& p3, @@ -448,7 +450,7 @@ template <typename IPCProvider, typename Par6, typename Par7> ResultCode CrossCall(IPCProvider& ipc_provider, - uint32_t tag, + IpcTag tag, const Par1& p1, const Par2& p2, const Par3& p3, diff --git a/chromium/sandbox/win/src/crosscall_params.h b/chromium/sandbox/win/src/crosscall_params.h index 60a1bb60aa0..eae3f8947b3 100644 --- a/chromium/sandbox/win/src/crosscall_params.h +++ b/chromium/sandbox/win/src/crosscall_params.h @@ -23,6 +23,7 @@ #if !defined(SANDBOX_FUZZ_TARGET) #include "sandbox/win/src/sandbox_nt_types.h" #endif +#include "sandbox/win/src/ipc_tags.h" #include "sandbox/win/src/sandbox_types.h" // This header is part of CrossCall: the sandbox inter-process communication. @@ -128,7 +129,7 @@ struct CrossCallReturn { class CrossCallParams { public: // Returns the tag (ipc unique id) associated with this IPC. - uint32_t GetTag() const { return tag_; } + IpcTag GetTag() const { return tag_; } // Returns the beggining of the buffer where the IPC params can be stored. // prior to an IPC call @@ -153,11 +154,11 @@ class CrossCallParams { protected: // constructs the IPC call params. Called only from the derived classes - CrossCallParams(uint32_t tag, uint32_t params_count) + CrossCallParams(IpcTag tag, uint32_t params_count) : tag_(tag), is_in_out_(0), params_count_(params_count) {} private: - uint32_t tag_; + IpcTag tag_; uint32_t is_in_out_; CrossCallReturn call_return; const uint32_t params_count_; @@ -206,15 +207,14 @@ template <size_t NUMBER_PARAMS, size_t BLOCK_SIZE> class ActualCallParams : public CrossCallParams { public: // constructor. Pass the ipc unique tag as input - explicit ActualCallParams(uint32_t tag) - : CrossCallParams(tag, NUMBER_PARAMS) { + explicit ActualCallParams(IpcTag tag) : CrossCallParams(tag, NUMBER_PARAMS) { param_info_[0].offset_ = static_cast<uint32_t>(parameters_ - reinterpret_cast<char*>(this)); } // Testing-only constructor. Allows setting the |number_params| to a // wrong value. - ActualCallParams(uint32_t tag, uint32_t number_params) + ActualCallParams(IpcTag tag, uint32_t number_params) : CrossCallParams(tag, number_params) { param_info_[0].offset_ = static_cast<uint32_t>(parameters_ - reinterpret_cast<char*>(this)); @@ -285,7 +285,7 @@ class ActualCallParams : public CrossCallParams { uint32_t GetSize() const { return param_info_[NUMBER_PARAMS].offset_; } protected: - ActualCallParams() : CrossCallParams(0, NUMBER_PARAMS) {} + ActualCallParams() : CrossCallParams(IpcTag::UNUSED, NUMBER_PARAMS) {} private: ParamInfo param_info_[NUMBER_PARAMS + 1]; diff --git a/chromium/sandbox/win/src/crosscall_server.cc b/chromium/sandbox/win/src/crosscall_server.cc index 38e94245e81..f32a1583d3e 100644 --- a/chromium/sandbox/win/src/crosscall_server.cc +++ b/chromium/sandbox/win/src/crosscall_server.cc @@ -94,7 +94,7 @@ bool IsSizeWithinRange(uint32_t buffer_size, return true; } -CrossCallParamsEx::CrossCallParamsEx() : CrossCallParams(0, 0) {} +CrossCallParamsEx::CrossCallParamsEx() : CrossCallParams(IpcTag::UNUSED, 0) {} // We override the delete operator because the object's backing memory // is hand allocated in CreateFromBuffer. We don't override the new operator @@ -249,8 +249,7 @@ bool CrossCallParamsEx::GetParameterVoidPtr(uint32_t index, void** param) { // Covers the common case of reading a string. Note that the string is not // scanned for invalid characters. -bool CrossCallParamsEx::GetParameterStr(uint32_t index, - base::string16* string) { +bool CrossCallParamsEx::GetParameterStr(uint32_t index, std::wstring* string) { DCHECK(string->empty()); uint32_t size = 0; ArgType type; @@ -260,14 +259,16 @@ bool CrossCallParamsEx::GetParameterStr(uint32_t index, // Check if this is an empty string. if (size == 0) { - *string = base::WideToUTF16(L""); + *string = std::wstring(); return true; } if (!start || ((size % sizeof(wchar_t)) != 0)) return false; - return base::WideToUTF16(reinterpret_cast<wchar_t*>(start), - size / sizeof(wchar_t), string); + + string->assign(reinterpret_cast<const wchar_t*>(start), + size / sizeof(wchar_t)); + return true; } bool CrossCallParamsEx::GetParameterPtr(uint32_t index, diff --git a/chromium/sandbox/win/src/crosscall_server.h b/chromium/sandbox/win/src/crosscall_server.h index 7e44cafde4b..aed7f99aae2 100644 --- a/chromium/sandbox/win/src/crosscall_server.h +++ b/chromium/sandbox/win/src/crosscall_server.h @@ -12,8 +12,8 @@ #include "base/callback.h" #include "base/macros.h" -#include "base/strings/string16.h" #include "sandbox/win/src/crosscall_params.h" +#include "sandbox/win/src/ipc_tags.h" // This is the IPC server interface for CrossCall: The IPC for the Sandbox // On the server, CrossCall needs two things: @@ -117,7 +117,7 @@ class CrossCallParamsEx : public CrossCallParams { // Gets a parameter that is a string. Returns false if the parameter does not // exist. - bool GetParameterStr(uint32_t index, base::string16* string); + bool GetParameterStr(uint32_t index, std::wstring* string); // Gets a parameter that is an in/out buffer. Returns false is the parameter // does not exist or if the size of the actual parameter is not equal to the @@ -152,14 +152,14 @@ struct ClientInfo { // All IPC-related information to be passed to the IPC handler. struct IPCInfo { - int ipc_tag; + IpcTag ipc_tag; const ClientInfo* client_info; CrossCallReturn return_info; }; // This structure identifies IPC signatures. struct IPCParams { - int ipc_tag; + IpcTag ipc_tag; ArgType args[kMaxIpcParams]; bool Matches(IPCParams* other) const { @@ -240,7 +240,7 @@ class Dispatcher { // Called when a target proces is created, to setup the interceptions related // with the given service (IPC). - virtual bool SetupService(InterceptionManager* manager, int service) = 0; + virtual bool SetupService(InterceptionManager* manager, IpcTag service) = 0; Dispatcher(); virtual ~Dispatcher(); diff --git a/chromium/sandbox/win/src/file_policy_test.cc b/chromium/sandbox/win/src/file_policy_test.cc index c3b006d10bc..4989ab308fc 100644 --- a/chromium/sandbox/win/src/file_policy_test.cc +++ b/chromium/sandbox/win/src/file_policy_test.cc @@ -77,7 +77,7 @@ SBOX_TESTS_COMMAND int File_Win32Create(int argc, wchar_t** argv) { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; } - base::string16 full_path = MakePathToSys(argv[0], false); + std::wstring full_path = MakePathToSys(argv[0], false); if (full_path.empty()) { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; } @@ -110,7 +110,7 @@ SBOX_TESTS_COMMAND int File_CreateSys32(int argc, wchar_t** argv) { if (argc != 1) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; - base::string16 file(argv[0]); + std::wstring file(argv[0]); if (0 != _wcsnicmp(file.c_str(), kNTDevicePrefix, kNTDevicePrefixLen)) file = MakePathToSys(argv[0], true); @@ -148,7 +148,7 @@ SBOX_TESTS_COMMAND int File_OpenSys32(int argc, wchar_t** argv) { if (argc != 1) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; - base::string16 file = MakePathToSys(argv[0], true); + std::wstring file = MakePathToSys(argv[0], true); UNICODE_STRING object_name; RtlInitUnicodeString(&object_name, file.c_str()); @@ -172,7 +172,7 @@ SBOX_TESTS_COMMAND int File_OpenSys32(int argc, wchar_t** argv) { } SBOX_TESTS_COMMAND int File_GetDiskSpace(int argc, wchar_t** argv) { - base::string16 sys_path = MakePathToSys(L"", false); + std::wstring sys_path = MakePathToSys(L"", false); if (sys_path.empty()) { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; } @@ -228,7 +228,7 @@ SBOX_TESTS_COMMAND int File_QueryAttributes(int argc, wchar_t** argv) { bool expect_directory = (L'd' == argv[1][0]); UNICODE_STRING object_name; - base::string16 file = MakePathToSys(argv[0], true); + std::wstring file = MakePathToSys(argv[0], true); RtlInitUnicodeString(&object_name, file.c_str()); OBJECT_ATTRIBUTES obj_attributes = {}; @@ -262,8 +262,8 @@ SBOX_TESTS_COMMAND int File_QueryAttributes(int argc, wchar_t** argv) { // Tries to create a backup of calc.exe in system32 folder. This should fail // with ERROR_ACCESS_DENIED if everything is working as expected. SBOX_TESTS_COMMAND int File_CopyFile(int argc, wchar_t** argv) { - base::string16 calc_path = MakePathToSys(L"calc.exe", false); - base::string16 calc_backup_path = MakePathToSys(L"calc.exe.bak", false); + std::wstring calc_path = MakePathToSys(L"calc.exe", false); + std::wstring calc_backup_path = MakePathToSys(L"calc.exe.bak", false); if (::CopyFile(calc_path.c_str(), calc_backup_path.c_str(), FALSE)) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; @@ -296,8 +296,8 @@ TEST(FilePolicyTest, AllowNtCreateCalc) { } TEST(FilePolicyTest, AllowNtCreateWithNativePath) { - base::string16 calc = MakePathToSys(L"calc.exe", false); - base::string16 nt_path; + std::wstring calc = MakePathToSys(L"calc.exe", false); + std::wstring nt_path; ASSERT_TRUE(GetNtPathFromWin32Path(calc, &nt_path)); TestRunner runner; runner.AddFsRule(TargetPolicy::FILES_ALLOW_READONLY, nt_path.c_str()); @@ -592,9 +592,9 @@ TEST(FilePolicyTest, TestReparsePoint) { ASSERT_TRUE(::CreateDirectory(temp_file_name, nullptr)); // Create a temporary file in the subfolder. - base::string16 subfolder = temp_file_name; - base::string16 temp_file_title = subfolder.substr(subfolder.rfind(L"\\") + 1); - base::string16 temp_file = subfolder + L"\\file_" + temp_file_title; + std::wstring subfolder = temp_file_name; + std::wstring temp_file_title = subfolder.substr(subfolder.rfind(L"\\") + 1); + std::wstring temp_file = subfolder + L"\\file_" + temp_file_title; HANDLE file = ::CreateFile(temp_file.c_str(), FILE_ALL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, @@ -603,8 +603,8 @@ TEST(FilePolicyTest, TestReparsePoint) { ASSERT_TRUE(::CloseHandle(file)); // Create a temporary file in the temp directory. - base::string16 temp_dir = temp_directory; - base::string16 temp_file_in_temp = temp_dir + L"file_" + temp_file_title; + std::wstring temp_dir = temp_directory; + std::wstring temp_file_in_temp = temp_dir + L"file_" + temp_file_title; file = ::CreateFile(temp_file_in_temp.c_str(), FILE_ALL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, 0, nullptr); @@ -612,12 +612,12 @@ TEST(FilePolicyTest, TestReparsePoint) { ASSERT_TRUE(::CloseHandle(file)); // Give write access to the temp directory. - base::string16 temp_dir_wildcard = temp_dir + L"*"; + std::wstring temp_dir_wildcard = temp_dir + L"*"; EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_ANY, temp_dir_wildcard.c_str())); // Prepare the command to execute. - base::string16 command_write; + std::wstring command_write; command_write += L"File_Create Write \""; command_write += temp_file; command_write += L"\""; @@ -632,7 +632,7 @@ TEST(FilePolicyTest, TestReparsePoint) { OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); EXPECT_TRUE(INVALID_HANDLE_VALUE != dir); - base::string16 temp_dir_nt; + std::wstring temp_dir_nt; temp_dir_nt += L"\\??\\"; temp_dir_nt += temp_dir; EXPECT_TRUE(SetReparsePoint(dir, temp_dir_nt.c_str())); @@ -656,25 +656,25 @@ TEST(FilePolicyTest, TestReparsePoint) { } TEST(FilePolicyTest, CheckExistingNTPrefixEscape) { - base::string16 name = L"\\??\\NAME"; + std::wstring name = L"\\??\\NAME"; - base::string16 result = FixNTPrefixForMatch(name); + std::wstring result = FixNTPrefixForMatch(name); EXPECT_STREQ(result.c_str(), L"\\/?/?\\NAME"); } TEST(FilePolicyTest, CheckEscapedNTPrefixNoEscape) { - base::string16 name = L"\\/?/?\\NAME"; + std::wstring name = L"\\/?/?\\NAME"; - base::string16 result = FixNTPrefixForMatch(name); + std::wstring result = FixNTPrefixForMatch(name); EXPECT_STREQ(result.c_str(), name.c_str()); } TEST(FilePolicyTest, CheckMissingNTPrefixEscape) { - base::string16 name = L"C:\\NAME"; + std::wstring name = L"C:\\NAME"; - base::string16 result = FixNTPrefixForMatch(name); + std::wstring result = FixNTPrefixForMatch(name); EXPECT_STREQ(result.c_str(), L"\\/?/?\\C:\\NAME"); } diff --git a/chromium/sandbox/win/src/filesystem_dispatcher.cc b/chromium/sandbox/win/src/filesystem_dispatcher.cc index d039675dec1..ea1c3314ba2 100644 --- a/chromium/sandbox/win/src/filesystem_dispatcher.cc +++ b/chromium/sandbox/win/src/filesystem_dispatcher.cc @@ -22,29 +22,29 @@ namespace sandbox { FilesystemDispatcher::FilesystemDispatcher(PolicyBase* policy_base) : policy_base_(policy_base) { static const IPCCall create_params = { - {IPC_NTCREATEFILE_TAG, + {IpcTag::NTCREATEFILE, {WCHAR_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>(&FilesystemDispatcher::NtCreateFile)}; static const IPCCall open_file = { - {IPC_NTOPENFILE_TAG, + {IpcTag::NTOPENFILE, {WCHAR_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>(&FilesystemDispatcher::NtOpenFile)}; static const IPCCall attribs = { - {IPC_NTQUERYATTRIBUTESFILE_TAG, {WCHAR_TYPE, UINT32_TYPE, INOUTPTR_TYPE}}, + {IpcTag::NTQUERYATTRIBUTESFILE, {WCHAR_TYPE, UINT32_TYPE, INOUTPTR_TYPE}}, reinterpret_cast<CallbackGeneric>( &FilesystemDispatcher::NtQueryAttributesFile)}; static const IPCCall full_attribs = { - {IPC_NTQUERYFULLATTRIBUTESFILE_TAG, + {IpcTag::NTQUERYFULLATTRIBUTESFILE, {WCHAR_TYPE, UINT32_TYPE, INOUTPTR_TYPE}}, reinterpret_cast<CallbackGeneric>( &FilesystemDispatcher::NtQueryFullAttributesFile)}; static const IPCCall set_info = { - {IPC_NTSETINFO_RENAME_TAG, + {IpcTag::NTSETINFO_RENAME, {VOIDPTR_TYPE, INOUTPTR_TYPE, INOUTPTR_TYPE, UINT32_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>( &FilesystemDispatcher::NtSetInformationFile)}; @@ -57,23 +57,23 @@ FilesystemDispatcher::FilesystemDispatcher(PolicyBase* policy_base) } bool FilesystemDispatcher::SetupService(InterceptionManager* manager, - int service) { + IpcTag service) { switch (service) { - case IPC_NTCREATEFILE_TAG: + case IpcTag::NTCREATEFILE: return INTERCEPT_NT(manager, NtCreateFile, CREATE_FILE_ID, 48); - case IPC_NTOPENFILE_TAG: + case IpcTag::NTOPENFILE: return INTERCEPT_NT(manager, NtOpenFile, OPEN_FILE_ID, 28); - case IPC_NTQUERYATTRIBUTESFILE_TAG: + case IpcTag::NTQUERYATTRIBUTESFILE: return INTERCEPT_NT(manager, NtQueryAttributesFile, QUERY_ATTRIB_FILE_ID, 12); - case IPC_NTQUERYFULLATTRIBUTESFILE_TAG: + case IpcTag::NTQUERYFULLATTRIBUTESFILE: return INTERCEPT_NT(manager, NtQueryFullAttributesFile, QUERY_FULL_ATTRIB_FILE_ID, 12); - case IPC_NTSETINFO_RENAME_TAG: + case IpcTag::NTSETINFO_RENAME: return INTERCEPT_NT(manager, NtSetInformationFile, SET_INFO_FILE_ID, 24); default: @@ -82,7 +82,7 @@ bool FilesystemDispatcher::SetupService(InterceptionManager* manager, } bool FilesystemDispatcher::NtCreateFile(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t attributes, uint32_t desired_access, uint32_t file_attributes, @@ -109,7 +109,7 @@ bool FilesystemDispatcher::NtCreateFile(IPCInfo* ipc, // are just middlemen in the operation since is the FileSystemPolicy which // knows what to do. EvalResult result = - policy_base_->EvalPolicy(IPC_NTCREATEFILE_TAG, params.GetBase()); + policy_base_->EvalPolicy(IpcTag::NTCREATEFILE, params.GetBase()); HANDLE handle; ULONG_PTR io_information = 0; NTSTATUS nt_status; @@ -128,7 +128,7 @@ bool FilesystemDispatcher::NtCreateFile(IPCInfo* ipc, } bool FilesystemDispatcher::NtOpenFile(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t attributes, uint32_t desired_access, uint32_t share_access, @@ -154,7 +154,7 @@ bool FilesystemDispatcher::NtOpenFile(IPCInfo* ipc, // are just middlemen in the operation since is the FileSystemPolicy which // knows what to do. EvalResult result = - policy_base_->EvalPolicy(IPC_NTOPENFILE_TAG, params.GetBase()); + policy_base_->EvalPolicy(IpcTag::NTOPENFILE, params.GetBase()); HANDLE handle; ULONG_PTR io_information = 0; NTSTATUS nt_status; @@ -172,7 +172,7 @@ bool FilesystemDispatcher::NtOpenFile(IPCInfo* ipc, } bool FilesystemDispatcher::NtQueryAttributesFile(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t attributes, CountedBuffer* info) { if (sizeof(FILE_BASIC_INFORMATION) != info->Size()) @@ -194,7 +194,7 @@ bool FilesystemDispatcher::NtQueryAttributesFile(IPCInfo* ipc, // are just middlemen in the operation since is the FileSystemPolicy which // knows what to do. EvalResult result = - policy_base_->EvalPolicy(IPC_NTQUERYATTRIBUTESFILE_TAG, params.GetBase()); + policy_base_->EvalPolicy(IpcTag::NTQUERYATTRIBUTESFILE, params.GetBase()); FILE_BASIC_INFORMATION* information = reinterpret_cast<FILE_BASIC_INFORMATION*>(info->Buffer()); @@ -212,7 +212,7 @@ bool FilesystemDispatcher::NtQueryAttributesFile(IPCInfo* ipc, } bool FilesystemDispatcher::NtQueryFullAttributesFile(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t attributes, CountedBuffer* info) { if (sizeof(FILE_NETWORK_OPEN_INFORMATION) != info->Size()) @@ -234,7 +234,7 @@ bool FilesystemDispatcher::NtQueryFullAttributesFile(IPCInfo* ipc, // are just middlemen in the operation since is the FileSystemPolicy which // knows what to do. EvalResult result = policy_base_->EvalPolicy( - IPC_NTQUERYFULLATTRIBUTESFILE_TAG, params.GetBase()); + IpcTag::NTQUERYFULLATTRIBUTESFILE, params.GetBase()); FILE_NETWORK_OPEN_INFORMATION* information = reinterpret_cast<FILE_NETWORK_OPEN_INFORMATION*>(info->Buffer()); @@ -268,7 +268,7 @@ bool FilesystemDispatcher::NtSetInformationFile(IPCInfo* ipc, if (!IsSupportedRenameCall(rename_info, length, info_class)) return false; - base::string16 name; + std::wstring name; name.assign(rename_info->FileName, rename_info->FileNameLength / sizeof(rename_info->FileName[0])); if (!PreProcessName(&name)) { @@ -287,7 +287,7 @@ bool FilesystemDispatcher::NtSetInformationFile(IPCInfo* ipc, // are just middlemen in the operation since is the FileSystemPolicy which // knows what to do. EvalResult result = - policy_base_->EvalPolicy(IPC_NTSETINFO_RENAME_TAG, params.GetBase()); + policy_base_->EvalPolicy(IpcTag::NTSETINFO_RENAME, params.GetBase()); IO_STATUS_BLOCK* io_status = reinterpret_cast<IO_STATUS_BLOCK*>(status->Buffer()); diff --git a/chromium/sandbox/win/src/filesystem_dispatcher.h b/chromium/sandbox/win/src/filesystem_dispatcher.h index 720dc6459bb..5551656e62d 100644 --- a/chromium/sandbox/win/src/filesystem_dispatcher.h +++ b/chromium/sandbox/win/src/filesystem_dispatcher.h @@ -7,9 +7,11 @@ #include <stdint.h> +#include <string> + #include "base/macros.h" -#include "base/strings/string16.h" #include "sandbox/win/src/crosscall_server.h" +#include "sandbox/win/src/ipc_tags.h" #include "sandbox/win/src/sandbox_policy_base.h" namespace sandbox { @@ -21,12 +23,12 @@ class FilesystemDispatcher : public Dispatcher { ~FilesystemDispatcher() override {} // Dispatcher interface. - bool SetupService(InterceptionManager* manager, int service) override; + bool SetupService(InterceptionManager* manager, IpcTag service) override; private: // Processes IPC requests coming from calls to NtCreateFile in the target. bool NtCreateFile(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t attributes, uint32_t desired_access, uint32_t file_attributes, @@ -36,7 +38,7 @@ class FilesystemDispatcher : public Dispatcher { // Processes IPC requests coming from calls to NtOpenFile in the target. bool NtOpenFile(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t attributes, uint32_t desired_access, uint32_t share_access, @@ -45,14 +47,14 @@ class FilesystemDispatcher : public Dispatcher { // Processes IPC requests coming from calls to NtQueryAttributesFile in the // target. bool NtQueryAttributesFile(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t attributes, CountedBuffer* info); // Processes IPC requests coming from calls to NtQueryFullAttributesFile in // the target. bool NtQueryFullAttributesFile(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t attributes, CountedBuffer* info); diff --git a/chromium/sandbox/win/src/filesystem_interception.cc b/chromium/sandbox/win/src/filesystem_interception.cc index d401c038640..59934ebd59a 100644 --- a/chromium/sandbox/win/src/filesystem_interception.cc +++ b/chromium/sandbox/win/src/filesystem_interception.cc @@ -70,7 +70,7 @@ NTSTATUS WINAPI TargetNtCreateFile(NtCreateFileFunction orig_CreateFile, params[OpenFile::OPTIONS] = ParamPickerMake(options_uint32); params[OpenFile::BROKER] = ParamPickerMake(broker); - if (!QueryBroker(IPC_NTCREATEFILE_TAG, params.GetBase())) + if (!QueryBroker(IpcTag::NTCREATEFILE, params.GetBase())) break; SharedMemIPCClient ipc(memory); @@ -78,7 +78,7 @@ NTSTATUS WINAPI TargetNtCreateFile(NtCreateFileFunction orig_CreateFile, // The following call must match in the parameters with // FilesystemDispatcher::ProcessNtCreateFile. ResultCode code = - CrossCall(ipc, IPC_NTCREATEFILE_TAG, name.get(), attributes, + CrossCall(ipc, IpcTag::NTCREATEFILE, name.get(), attributes, desired_access_uint32, file_attributes, sharing, disposition, options_uint32, &answer); if (SBOX_ALL_OK != code) @@ -147,13 +147,13 @@ NTSTATUS WINAPI TargetNtOpenFile(NtOpenFileFunction orig_OpenFile, params[OpenFile::OPTIONS] = ParamPickerMake(options_uint32); params[OpenFile::BROKER] = ParamPickerMake(broker); - if (!QueryBroker(IPC_NTOPENFILE_TAG, params.GetBase())) + if (!QueryBroker(IpcTag::NTOPENFILE, params.GetBase())) break; SharedMemIPCClient ipc(memory); CrossCallReturn answer = {0}; ResultCode code = - CrossCall(ipc, IPC_NTOPENFILE_TAG, name.get(), attributes, + CrossCall(ipc, IpcTag::NTOPENFILE, name.get(), attributes, desired_access_uint32, sharing, options_uint32, &answer); if (SBOX_ALL_OK != code) break; @@ -212,12 +212,12 @@ TargetNtQueryAttributesFile(NtQueryAttributesFileFunction orig_QueryAttributes, params[FileName::NAME] = ParamPickerMake(name_ptr); params[FileName::BROKER] = ParamPickerMake(broker); - if (!QueryBroker(IPC_NTQUERYATTRIBUTESFILE_TAG, params.GetBase())) + if (!QueryBroker(IpcTag::NTQUERYATTRIBUTESFILE, params.GetBase())) break; SharedMemIPCClient ipc(memory); CrossCallReturn answer = {0}; - ResultCode code = CrossCall(ipc, IPC_NTQUERYATTRIBUTESFILE_TAG, name.get(), + ResultCode code = CrossCall(ipc, IpcTag::NTQUERYATTRIBUTESFILE, name.get(), attributes, file_info, &answer); if (SBOX_ALL_OK != code) @@ -269,12 +269,12 @@ NTSTATUS WINAPI TargetNtQueryFullAttributesFile( params[FileName::NAME] = ParamPickerMake(name_ptr); params[FileName::BROKER] = ParamPickerMake(broker); - if (!QueryBroker(IPC_NTQUERYFULLATTRIBUTESFILE_TAG, params.GetBase())) + if (!QueryBroker(IpcTag::NTQUERYFULLATTRIBUTESFILE, params.GetBase())) break; SharedMemIPCClient ipc(memory); CrossCallReturn answer = {0}; - ResultCode code = CrossCall(ipc, IPC_NTQUERYFULLATTRIBUTESFILE_TAG, + ResultCode code = CrossCall(ipc, IpcTag::NTQUERYFULLATTRIBUTESFILE, name.get(), attributes, file_info, &answer); if (SBOX_ALL_OK != code) @@ -345,7 +345,7 @@ TargetNtSetInformationFile(NtSetInformationFileFunction orig_SetInformationFile, params[FileName::NAME] = ParamPickerMake(name_ptr); params[FileName::BROKER] = ParamPickerMake(broker); - if (!QueryBroker(IPC_NTSETINFO_RENAME_TAG, params.GetBase())) + if (!QueryBroker(IpcTag::NTSETINFO_RENAME, params.GetBase())) break; InOutCountedBuffer io_status_buffer(io_status, sizeof(IO_STATUS_BLOCK)); @@ -356,7 +356,7 @@ TargetNtSetInformationFile(NtSetInformationFileFunction orig_SetInformationFile, SharedMemIPCClient ipc(memory); CrossCallReturn answer = {0}; ResultCode code = - CrossCall(ipc, IPC_NTSETINFO_RENAME_TAG, file, io_status_buffer, + CrossCall(ipc, IpcTag::NTSETINFO_RENAME, file, io_status_buffer, file_info_buffer, length, file_info_class, &answer); if (SBOX_ALL_OK != code) diff --git a/chromium/sandbox/win/src/filesystem_policy.cc b/chromium/sandbox/win/src/filesystem_policy.cc index 5f482b641cf..5de82b85354 100644 --- a/chromium/sandbox/win/src/filesystem_policy.cc +++ b/chromium/sandbox/win/src/filesystem_policy.cc @@ -77,7 +77,7 @@ namespace sandbox { bool FileSystemPolicy::GenerateRules(const wchar_t* name, TargetPolicy::Semantics semantics, LowLevelPolicy* policy) { - base::string16 mod_name(name); + std::wstring mod_name(name); if (mod_name.empty()) { return false; } @@ -154,31 +154,31 @@ bool FileSystemPolicy::GenerateRules(const wchar_t* name, if ((rule_to_add & kCallNtCreateFile) && (!create.AddStringMatch(IF, OpenFile::NAME, name, CASE_INSENSITIVE) || - !policy->AddRule(IPC_NTCREATEFILE_TAG, &create))) { + !policy->AddRule(IpcTag::NTCREATEFILE, &create))) { return false; } if ((rule_to_add & kCallNtOpenFile) && (!open.AddStringMatch(IF, OpenFile::NAME, name, CASE_INSENSITIVE) || - !policy->AddRule(IPC_NTOPENFILE_TAG, &open))) { + !policy->AddRule(IpcTag::NTOPENFILE, &open))) { return false; } if ((rule_to_add & kCallNtQueryAttributesFile) && (!query.AddStringMatch(IF, FileName::NAME, name, CASE_INSENSITIVE) || - !policy->AddRule(IPC_NTQUERYATTRIBUTESFILE_TAG, &query))) { + !policy->AddRule(IpcTag::NTQUERYATTRIBUTESFILE, &query))) { return false; } if ((rule_to_add & kCallNtQueryFullAttributesFile) && (!query_full.AddStringMatch(IF, FileName::NAME, name, CASE_INSENSITIVE) || - !policy->AddRule(IPC_NTQUERYFULLATTRIBUTESFILE_TAG, &query_full))) { + !policy->AddRule(IpcTag::NTQUERYFULLATTRIBUTESFILE, &query_full))) { return false; } if ((rule_to_add & kCallNtSetInfoRename) && (!rename.AddStringMatch(IF, FileName::NAME, name, CASE_INSENSITIVE) || - !policy->AddRule(IPC_NTSETINFO_RENAME_TAG, &rename))) { + !policy->AddRule(IpcTag::NTSETINFO_RENAME, &rename))) { return false; } @@ -206,34 +206,34 @@ bool FileSystemPolicy::SetInitialRules(LowLevelPolicy* policy) { rv &= short_name.AddNumberMatch(IF_NOT, FileName::BROKER, BROKER_TRUE, AND); rv &= short_name.AddStringMatch(IF, FileName::NAME, L"*~*", CASE_SENSITIVE); - if (!rv || !policy->AddRule(IPC_NTCREATEFILE_TAG, &format)) + if (!rv || !policy->AddRule(IpcTag::NTCREATEFILE, &format)) return false; - if (!policy->AddRule(IPC_NTCREATEFILE_TAG, &short_name)) + if (!policy->AddRule(IpcTag::NTCREATEFILE, &short_name)) return false; - if (!policy->AddRule(IPC_NTOPENFILE_TAG, &format)) + if (!policy->AddRule(IpcTag::NTOPENFILE, &format)) return false; - if (!policy->AddRule(IPC_NTOPENFILE_TAG, &short_name)) + if (!policy->AddRule(IpcTag::NTOPENFILE, &short_name)) return false; - if (!policy->AddRule(IPC_NTQUERYATTRIBUTESFILE_TAG, &format)) + if (!policy->AddRule(IpcTag::NTQUERYATTRIBUTESFILE, &format)) return false; - if (!policy->AddRule(IPC_NTQUERYATTRIBUTESFILE_TAG, &short_name)) + if (!policy->AddRule(IpcTag::NTQUERYATTRIBUTESFILE, &short_name)) return false; - if (!policy->AddRule(IPC_NTQUERYFULLATTRIBUTESFILE_TAG, &format)) + if (!policy->AddRule(IpcTag::NTQUERYFULLATTRIBUTESFILE, &format)) return false; - if (!policy->AddRule(IPC_NTQUERYFULLATTRIBUTESFILE_TAG, &short_name)) + if (!policy->AddRule(IpcTag::NTQUERYFULLATTRIBUTESFILE, &short_name)) return false; - if (!policy->AddRule(IPC_NTSETINFO_RENAME_TAG, &format)) + if (!policy->AddRule(IpcTag::NTSETINFO_RENAME, &format)) return false; - if (!policy->AddRule(IPC_NTSETINFO_RENAME_TAG, &short_name)) + if (!policy->AddRule(IpcTag::NTSETINFO_RENAME, &short_name)) return false; return true; @@ -241,7 +241,7 @@ bool FileSystemPolicy::SetInitialRules(LowLevelPolicy* policy) { bool FileSystemPolicy::CreateFileAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& file, + const std::wstring& file, uint32_t attributes, uint32_t desired_access, uint32_t file_attributes, @@ -276,7 +276,7 @@ bool FileSystemPolicy::CreateFileAction(EvalResult eval_result, bool FileSystemPolicy::OpenFileAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& file, + const std::wstring& file, uint32_t attributes, uint32_t desired_access, uint32_t share_access, @@ -311,7 +311,7 @@ bool FileSystemPolicy::OpenFileAction(EvalResult eval_result, bool FileSystemPolicy::QueryAttributesFileAction( EvalResult eval_result, const ClientInfo& client_info, - const base::string16& file, + const std::wstring& file, uint32_t attributes, FILE_BASIC_INFORMATION* file_info, NTSTATUS* nt_status) { @@ -339,7 +339,7 @@ bool FileSystemPolicy::QueryAttributesFileAction( bool FileSystemPolicy::QueryFullAttributesFileAction( EvalResult eval_result, const ClientInfo& client_info, - const base::string16& file, + const std::wstring& file, uint32_t attributes, FILE_NETWORK_OPEN_INFORMATION* file_info, NTSTATUS* nt_status) { @@ -400,7 +400,7 @@ bool FileSystemPolicy::SetInformationFileAction(EvalResult eval_result, return true; } -bool PreProcessName(base::string16* path) { +bool PreProcessName(std::wstring* path) { ConvertToLongPath(path); if (ERROR_NOT_A_REPARSE_POINT == IsReparsePoint(*path)) @@ -410,8 +410,8 @@ bool PreProcessName(base::string16* path) { return false; } -base::string16 FixNTPrefixForMatch(const base::string16& name) { - base::string16 mod_name = name; +std::wstring FixNTPrefixForMatch(const std::wstring& name) { + std::wstring mod_name = name; // NT prefix escaped for rule matcher const wchar_t kNTPrefixEscaped[] = L"\\/?/?\\"; diff --git a/chromium/sandbox/win/src/filesystem_policy.h b/chromium/sandbox/win/src/filesystem_policy.h index d860e60b890..81dd1d0d1d0 100644 --- a/chromium/sandbox/win/src/filesystem_policy.h +++ b/chromium/sandbox/win/src/filesystem_policy.h @@ -9,7 +9,6 @@ #include <string> -#include "base/strings/string16.h" #include "sandbox/win/src/crosscall_server.h" #include "sandbox/win/src/nt_internals.h" #include "sandbox/win/src/policy_low_level.h" @@ -41,7 +40,7 @@ class FileSystemPolicy { // 'file' : The target file or directory. static bool CreateFileAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& file, + const std::wstring& file, uint32_t attributes, uint32_t desired_access, uint32_t file_attributes, @@ -59,7 +58,7 @@ class FileSystemPolicy { // 'file' : The target file or directory. static bool OpenFileAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& file, + const std::wstring& file, uint32_t attributes, uint32_t desired_access, uint32_t share_access, @@ -72,7 +71,7 @@ class FileSystemPolicy { // API that is compatible with the IPC-received parameters. static bool QueryAttributesFileAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& file, + const std::wstring& file, uint32_t attributes, FILE_BASIC_INFORMATION* file_info, NTSTATUS* nt_status); @@ -82,7 +81,7 @@ class FileSystemPolicy { static bool QueryFullAttributesFileAction( EvalResult eval_result, const ClientInfo& client_info, - const base::string16& file, + const std::wstring& file, uint32_t attributes, FILE_NETWORK_OPEN_INFORMATION* file_info, NTSTATUS* nt_status); @@ -101,12 +100,12 @@ class FileSystemPolicy { // Expands the path and check if it's a reparse point. Returns false if the path // cannot be trusted. -bool PreProcessName(base::string16* path); +bool PreProcessName(std::wstring* path); // Corrects global paths to have a correctly escaped NT prefix at the // beginning. If the name has no NT prefix (either normal or escaped) // add the escaped form to the string -base::string16 FixNTPrefixForMatch(const base::string16& name); +std::wstring FixNTPrefixForMatch(const std::wstring& name); } // namespace sandbox diff --git a/chromium/sandbox/win/src/handle_closer.cc b/chromium/sandbox/win/src/handle_closer.cc index 23fe0c80b25..6751151dcbc 100644 --- a/chromium/sandbox/win/src/handle_closer.cc +++ b/chromium/sandbox/win/src/handle_closer.cc @@ -42,15 +42,15 @@ HandleCloser::HandleCloser() {} HandleCloser::~HandleCloser() {} -ResultCode HandleCloser::AddHandle(const base::char16* handle_type, - const base::char16* handle_name) { +ResultCode HandleCloser::AddHandle(const wchar_t* handle_type, + const wchar_t* handle_name) { if (!handle_type) return SBOX_ERROR_BAD_PARAMS; - base::string16 resolved_name; + std::wstring resolved_name; if (handle_name) { resolved_name = handle_name; - if (handle_type == base::string16(L"Key")) + if (handle_type == std::wstring(L"Key")) if (!ResolveRegistryName(resolved_name, &resolved_name)) return SBOX_ERROR_BAD_PARAMS; } @@ -77,10 +77,10 @@ size_t HandleCloser::GetBufferSize() { for (HandleMap::iterator i = handles_to_close_.begin(); i != handles_to_close_.end(); ++i) { size_t bytes_entry = offsetof(HandleListEntry, handle_type) + - (i->first.size() + 1) * sizeof(base::char16); + (i->first.size() + 1) * sizeof(wchar_t); for (HandleMap::mapped_type::iterator j = i->second.begin(); j != i->second.end(); ++j) { - bytes_entry += ((*j).size() + 1) * sizeof(base::char16); + bytes_entry += ((*j).size() + 1) * sizeof(wchar_t); } // Round up to the nearest multiple of word size. @@ -123,10 +123,9 @@ bool HandleCloser::SetupHandleList(void* buffer, size_t buffer_bytes) { handle_info->record_bytes = buffer_bytes; handle_info->num_handle_types = handles_to_close_.size(); - base::char16* output = - reinterpret_cast<base::char16*>(&handle_info->handle_entries[0]); - base::char16* end = reinterpret_cast<base::char16*>( - reinterpret_cast<char*>(buffer) + buffer_bytes); + wchar_t* output = reinterpret_cast<wchar_t*>(&handle_info->handle_entries[0]); + wchar_t* end = reinterpret_cast<wchar_t*>(reinterpret_cast<char*>(buffer) + + buffer_bytes); for (HandleMap::iterator i = handles_to_close_.begin(); i != handles_to_close_.end(); ++i) { if (output >= end) @@ -158,7 +157,7 @@ bool HandleCloser::SetupHandleList(void* buffer, size_t buffer_bytes) { return output <= end; } -bool GetHandleName(HANDLE handle, base::string16* handle_name) { +bool GetHandleName(HANDLE handle, std::wstring* handle_name) { static NtQueryObject QueryObject = nullptr; if (!QueryObject) ResolveNTFunctionPtr("NtQueryObject", &QueryObject); diff --git a/chromium/sandbox/win/src/handle_closer.h b/chromium/sandbox/win/src/handle_closer.h index a76095bc095..4f023b27b66 100644 --- a/chromium/sandbox/win/src/handle_closer.h +++ b/chromium/sandbox/win/src/handle_closer.h @@ -10,8 +10,9 @@ #include <map> #include <set> +#include <string> + #include "base/macros.h" -#include "base/strings/string16.h" #include "sandbox/win/src/interception.h" #include "sandbox/win/src/sandbox_types.h" #include "sandbox/win/src/target_process.h" @@ -21,14 +22,14 @@ namespace sandbox { // This is a map of handle-types to names that we need to close in the // target process. A null set means we need to close all handles of the // given type. -typedef std::map<const base::string16, std::set<base::string16>> HandleMap; +typedef std::map<const std::wstring, std::set<std::wstring>> HandleMap; // Type and set of corresponding handle names to close. struct HandleListEntry { size_t record_bytes; // Rounded to sizeof(size_t) bytes. size_t offset_to_names; // Nul terminated strings of name_count names. size_t name_count; - base::char16 handle_type[1]; + wchar_t handle_type[1]; }; // Global parameters and a pointer to the list of entries. @@ -49,8 +50,7 @@ class HandleCloser { // Adds a handle that will be closed in the target process after lockdown. // A nullptr value for handle_name indicates all handles of the specified // type. An empty string for handle_name indicates the handle is unnamed. - ResultCode AddHandle(const base::char16* handle_type, - const base::char16* handle_name); + ResultCode AddHandle(const wchar_t* handle_type, const wchar_t* handle_name); // Serializes and copies the closer table into the target process. bool InitializeTargetHandles(TargetProcess* target); @@ -69,7 +69,7 @@ class HandleCloser { }; // Returns the object manager's name associated with a handle -bool GetHandleName(HANDLE handle, base::string16* handle_name); +bool GetHandleName(HANDLE handle, std::wstring* handle_name); } // namespace sandbox diff --git a/chromium/sandbox/win/src/handle_closer_agent.cc b/chromium/sandbox/win/src/handle_closer_agent.cc index a0f12a52f4f..55fe2d4689b 100644 --- a/chromium/sandbox/win/src/handle_closer_agent.cc +++ b/chromium/sandbox/win/src/handle_closer_agent.cc @@ -54,7 +54,7 @@ HandleCloserAgent::~HandleCloserAgent() {} // generating EXCEPTION_INVALID_HANDLE on shutdown, but nothing else. For now // the only supported |type| is Event or File. bool HandleCloserAgent::AttemptToStuffHandleSlot(HANDLE closed_handle, - const base::string16& type) { + const std::wstring& type) { // Only attempt to stuff Files and Events at the moment. if (type != L"Event" && type != L"File") { return true; @@ -135,13 +135,13 @@ void HandleCloserAgent::InitializeHandlesToClose(bool* is_csrss_connected) { HandleListEntry* entry = g_handles_to_close->handle_entries; for (size_t i = 0; i < g_handles_to_close->num_handle_types; ++i) { // Set the type name. - base::char16* input = entry->handle_type; + wchar_t* input = entry->handle_type; if (!wcscmp(input, L"ALPC Port")) { *is_csrss_connected = false; } HandleMap::mapped_type& handle_names = handles_to_close_[input]; - input = reinterpret_cast<base::char16*>(reinterpret_cast<char*>(entry) + - entry->offset_to_names); + input = reinterpret_cast<wchar_t*>(reinterpret_cast<char*>(entry) + + entry->offset_to_names); // Grab all the handle names. for (size_t j = 0; j < entry->name_count; ++j) { std::pair<HandleMap::mapped_type::iterator, bool> name = @@ -154,9 +154,9 @@ void HandleCloserAgent::InitializeHandlesToClose(bool* is_csrss_connected) { entry = reinterpret_cast<HandleListEntry*>(reinterpret_cast<char*>(entry) + entry->record_bytes); - DCHECK(reinterpret_cast<base::char16*>(entry) >= input); - DCHECK(reinterpret_cast<base::char16*>(entry) - input < - static_cast<ptrdiff_t>(sizeof(size_t) / sizeof(base::char16))); + DCHECK(reinterpret_cast<wchar_t*>(entry) >= input); + DCHECK(reinterpret_cast<wchar_t*>(entry) - input < + static_cast<ptrdiff_t>(sizeof(size_t) / sizeof(wchar_t))); } // Clean up the memory we copied over. @@ -182,7 +182,7 @@ bool HandleCloserAgent::CloseHandles() { 32 * sizeof(wchar_t)); OBJECT_TYPE_INFORMATION* type_info = reinterpret_cast<OBJECT_TYPE_INFORMATION*>(&(type_info_buffer[0])); - base::string16 handle_name; + std::wstring handle_name; HANDLE handle = nullptr; int invalid_count = 0; diff --git a/chromium/sandbox/win/src/handle_closer_agent.h b/chromium/sandbox/win/src/handle_closer_agent.h index 0c7c2904c7c..91f8e74c7ea 100644 --- a/chromium/sandbox/win/src/handle_closer_agent.h +++ b/chromium/sandbox/win/src/handle_closer_agent.h @@ -5,8 +5,9 @@ #ifndef SANDBOX_SRC_HANDLE_CLOSER_AGENT_H_ #define SANDBOX_SRC_HANDLE_CLOSER_AGENT_H_ +#include <string> + #include "base/macros.h" -#include "base/strings/string16.h" #include "base/win/scoped_handle.h" #include "sandbox/win/src/handle_closer.h" #include "sandbox/win/src/sandbox_types.h" @@ -32,8 +33,7 @@ class HandleCloserAgent { private: // Attempt to stuff a closed handle with a dummy Event. - bool AttemptToStuffHandleSlot(HANDLE closed_handle, - const base::string16& type); + bool AttemptToStuffHandleSlot(HANDLE closed_handle, const std::wstring& type); HandleMap handles_to_close_; base::win::ScopedHandle dummy_handle_; diff --git a/chromium/sandbox/win/src/handle_closer_test.cc b/chromium/sandbox/win/src/handle_closer_test.cc index 104ef7fa11c..7406f77592a 100644 --- a/chromium/sandbox/win/src/handle_closer_test.cc +++ b/chromium/sandbox/win/src/handle_closer_test.cc @@ -23,7 +23,7 @@ const wchar_t* kFileExtensions[] = {L".1", L".2", L".3", L".4"}; HANDLE GetMarkerFile(const wchar_t* extension) { wchar_t path_buffer[MAX_PATH + 1]; CHECK(::GetTempPath(MAX_PATH, path_buffer)); - base::string16 marker_path = path_buffer; + std::wstring marker_path = path_buffer; marker_path += L"\\sbox_marker_"; // Generate a unique value from the exe's size and timestamp. @@ -98,7 +98,7 @@ SBOX_TESTS_COMMAND int CheckForFileHandles(int argc, wchar_t** argv) { const size_t kHandleOffset = 4; // Handles are always a multiple of 4. HANDLE handle = nullptr; int invalid_count = 0; - base::string16 handle_name; + std::wstring handle_name; if (!::GetProcessHandleCount(::GetCurrentProcess(), &handle_count)) return SBOX_TEST_FAILED_TO_RUN_TEST; @@ -195,9 +195,9 @@ TEST(HandleCloserTest, CheckForMarkerFiles) { runner.SetTimeout(2000); runner.SetTestState(EVERY_STATE); - base::string16 command = base::string16(L"CheckForFileHandles Y"); + std::wstring command = std::wstring(L"CheckForFileHandles Y"); for (const wchar_t* kExtension : kFileExtensions) { - base::string16 handle_name; + std::wstring handle_name; base::win::ScopedHandle marker(GetMarkerFile(kExtension)); CHECK(marker.IsValid()); CHECK(sandbox::GetHandleName(marker.Get(), &handle_name)); @@ -215,9 +215,9 @@ TEST(HandleCloserTest, CloseMarkerFiles) { runner.SetTestState(EVERY_STATE); sandbox::TargetPolicy* policy = runner.GetPolicy(); - base::string16 command = base::string16(L"CheckForFileHandles N"); + std::wstring command = std::wstring(L"CheckForFileHandles N"); for (const wchar_t* kExtension : kFileExtensions) { - base::string16 handle_name; + std::wstring handle_name; base::win::ScopedHandle marker(GetMarkerFile(kExtension)); CHECK(marker.IsValid()); CHECK(sandbox::GetHandleName(marker.Get(), &handle_name)); @@ -238,7 +238,7 @@ TEST(HandleCloserTest, CheckStuffedHandle) { sandbox::TargetPolicy* policy = runner.GetPolicy(); for (const wchar_t* kExtension : kFileExtensions) { - base::string16 handle_name; + std::wstring handle_name; base::win::ScopedHandle marker(GetMarkerFile(kExtension)); CHECK(marker.IsValid()); CHECK(sandbox::GetHandleName(marker.Get(), &handle_name)); diff --git a/chromium/sandbox/win/src/interception.cc b/chromium/sandbox/win/src/interception.cc index cfe9b0b7ea2..b2c0bc47eaa 100644 --- a/chromium/sandbox/win/src/interception.cc +++ b/chromium/sandbox/win/src/interception.cc @@ -11,10 +11,10 @@ #include <memory> #include <set> +#include <string> #include "base/logging.h" #include "base/scoped_native_library.h" -#include "base/strings/string16.h" #include "base/win/pe_image.h" #include "base/win/windows_version.h" #include "sandbox/win/src/interception_internal.h" @@ -159,7 +159,7 @@ ResultCode InterceptionManager::InitializeInterceptions() { } size_t InterceptionManager::GetBufferSize() const { - std::set<base::string16> dlls; + std::set<std::wstring> dlls; size_t buffer_bytes = 0; for (const auto& interception : interceptions_) { @@ -221,7 +221,7 @@ bool InterceptionManager::SetupConfigBuffer(void* buffer, size_t buffer_bytes) { continue; } - const base::string16 dll = it->dll; + const std::wstring dll = it->dll; if (!SetupDllInfo(*it, &buffer, &buffer_bytes)) return false; @@ -343,7 +343,7 @@ bool InterceptionManager::IsInterceptionPerformedByChild( if (data.type >= INTERCEPTION_LAST) return false; - base::string16 ntdll(kNtdllName); + std::wstring ntdll(kNtdllName); if (ntdll == data.dll) return false; // ntdll has to be intercepted from the parent @@ -464,7 +464,7 @@ ResultCode InterceptionManager::PatchClientFunctions( #endif for (auto interception : interceptions_) { - const base::string16 ntdll(kNtdllName); + const std::wstring ntdll(kNtdllName); if (interception.dll != ntdll) return SBOX_ERROR_BAD_PARAMS; diff --git a/chromium/sandbox/win/src/interception.h b/chromium/sandbox/win/src/interception.h index 1105afbb74f..6b4612fb6c0 100644 --- a/chromium/sandbox/win/src/interception.h +++ b/chromium/sandbox/win/src/interception.h @@ -16,7 +16,6 @@ #include "base/gtest_prod_util.h" #include "base/macros.h" -#include "base/strings/string16.h" #include "sandbox/win/src/interceptors.h" #include "sandbox/win/src/sandbox_types.h" @@ -143,7 +142,7 @@ class InterceptionManager { InterceptionType type; // Interception type. InterceptorId id; // Interceptor id. - base::string16 dll; // Name of dll to intercept. + std::wstring dll; // Name of dll to intercept. std::string function; // Name of function to intercept. std::string interceptor; // Name of interceptor function. const void* interceptor_address; // Interceptor's entry point. diff --git a/chromium/sandbox/win/src/ipc_args.cc b/chromium/sandbox/win/src/ipc_args.cc index 74dc2722b34..c961ad809ed 100644 --- a/chromium/sandbox/win/src/ipc_args.cc +++ b/chromium/sandbox/win/src/ipc_args.cc @@ -16,7 +16,7 @@ void ReleaseArgs(const IPCParams* ipc_params, void* args[kMaxIpcParams]) { for (size_t i = 0; i < kMaxIpcParams; i++) { switch (ipc_params->args[i]) { case WCHAR_TYPE: { - delete reinterpret_cast<base::string16*>(args[i]); + delete reinterpret_cast<std::wstring*>(args[i]); args[i] = nullptr; break; } @@ -46,7 +46,7 @@ bool GetArgs(CrossCallParamsEx* params, ipc_params->args[i] = type; switch (type) { case WCHAR_TYPE: { - std::unique_ptr<base::string16> data(new base::string16); + std::unique_ptr<std::wstring> data(new std::wstring); if (!params->GetParameterStr(i, data.get())) { args[i] = 0; ReleaseArgs(ipc_params, args); diff --git a/chromium/sandbox/win/src/ipc_leak_test.cc b/chromium/sandbox/win/src/ipc_leak_test.cc index 66d0b4daecc..a2ab9c40b9b 100644 --- a/chromium/sandbox/win/src/ipc_leak_test.cc +++ b/chromium/sandbox/win/src/ipc_leak_test.cc @@ -221,10 +221,12 @@ PolicyGlobal* GenerateBlankPolicy() { LowLevelPolicy policy_maker(policy); - for (int i = 0; i < IPC_LAST_TAG; i++) { + for (int i = static_cast<int>(IpcTag::UNUSED); + i < static_cast<int>(IpcTag::LAST); i++) { + IpcTag service = static_cast<IpcTag>(i); PolicyRule ask_broker(ASK_BROKER); ask_broker.Done(); - policy_maker.AddRule(i, &ask_broker); + policy_maker.AddRule(service, &ask_broker); } policy_maker.Done(); @@ -342,7 +344,7 @@ TEST(IPCTest, IPCLeak) { EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY, TargetPolicy::REG_ALLOW_READONLY, L"HKEY_LOCAL_MACHINE\\Software\\*")); - base::string16 command = base::string16(L"IPC_Leak "); + std::wstring command = std::wstring(L"IPC_Leak "); command += std::to_wstring(test.test_id); EXPECT_EQ(test.expected_result, base::win::Uint32ToHandle(runner.RunTest(command.c_str()))) diff --git a/chromium/sandbox/win/src/ipc_tags.h b/chromium/sandbox/win/src/ipc_tags.h index 2d38cdf3657..c2fea44a961 100644 --- a/chromium/sandbox/win/src/ipc_tags.h +++ b/chromium/sandbox/win/src/ipc_tags.h @@ -7,47 +7,51 @@ namespace sandbox { -enum { - IPC_UNUSED_TAG = 0, - IPC_PING1_TAG, // Takes a cookie in parameters and returns the cookie - // multiplied by 2 and the tick_count. Used for testing only. - IPC_PING2_TAG, // Takes an in/out cookie in parameters and modify the cookie - // to be multiplied by 3. Used for testing only. - IPC_NTCREATEFILE_TAG, - IPC_NTOPENFILE_TAG, - IPC_NTQUERYATTRIBUTESFILE_TAG, - IPC_NTQUERYFULLATTRIBUTESFILE_TAG, - IPC_NTSETINFO_RENAME_TAG, - IPC_CREATENAMEDPIPEW_TAG, - IPC_NTOPENTHREAD_TAG, - IPC_NTOPENPROCESS_TAG, - IPC_NTOPENPROCESSTOKEN_TAG, - IPC_NTOPENPROCESSTOKENEX_TAG, - IPC_CREATEPROCESSW_TAG, - IPC_CREATEEVENT_TAG, - IPC_OPENEVENT_TAG, - IPC_NTCREATEKEY_TAG, - IPC_NTOPENKEY_TAG, - IPC_GDI_GDIDLLINITIALIZE_TAG, - IPC_GDI_GETSTOCKOBJECT_TAG, - IPC_USER_REGISTERCLASSW_TAG, - IPC_CREATETHREAD_TAG, - IPC_USER_ENUMDISPLAYMONITORS_TAG, - IPC_USER_ENUMDISPLAYDEVICES_TAG, - IPC_USER_GETMONITORINFO_TAG, - IPC_GDI_CREATEOPMPROTECTEDOUTPUTS_TAG, - IPC_GDI_GETCERTIFICATE_TAG, - IPC_GDI_GETCERTIFICATESIZE_TAG, - IPC_GDI_DESTROYOPMPROTECTEDOUTPUT_TAG, - IPC_GDI_CONFIGUREOPMPROTECTEDOUTPUT_TAG, - IPC_GDI_GETOPMINFORMATION_TAG, - IPC_GDI_GETOPMRANDOMNUMBER_TAG, - IPC_GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE_TAG, - IPC_GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS_TAG, - IPC_NTCREATESECTION_TAG, - IPC_LAST_TAG +enum class IpcTag { + UNUSED = 0, + PING1, // Takes a cookie in parameters and returns the cookie + // multiplied by 2 and the tick_count. Used for testing only. + PING2, // Takes an in/out cookie in parameters and modify the cookie + // to be multiplied by 3. Used for testing only. + NTCREATEFILE, + NTOPENFILE, + NTQUERYATTRIBUTESFILE, + NTQUERYFULLATTRIBUTESFILE, + NTSETINFO_RENAME, + CREATENAMEDPIPEW, + NTOPENTHREAD, + NTOPENPROCESS, + NTOPENPROCESSTOKEN, + NTOPENPROCESSTOKENEX, + CREATEPROCESSW, + CREATEEVENT, + OPENEVENT, + NTCREATEKEY, + NTOPENKEY, + GDI_GDIDLLINITIALIZE, + GDI_GETSTOCKOBJECT, + USER_REGISTERCLASSW, + CREATETHREAD, + USER_ENUMDISPLAYMONITORS, + USER_ENUMDISPLAYDEVICES, + USER_GETMONITORINFO, + GDI_CREATEOPMPROTECTEDOUTPUTS, + GDI_GETCERTIFICATE, + GDI_GETCERTIFICATESIZE, + GDI_DESTROYOPMPROTECTEDOUTPUT, + GDI_CONFIGUREOPMPROTECTEDOUTPUT, + GDI_GETOPMINFORMATION, + GDI_GETOPMRANDOMNUMBER, + GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE, + GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS, + NTCREATESECTION, + LAST }; +constexpr size_t kMaxServiceCount = 64; +constexpr size_t kMaxIpcTag = static_cast<size_t>(IpcTag::LAST); +static_assert(kMaxIpcTag <= kMaxServiceCount, "kMaxServiceCount is too low"); + } // namespace sandbox #endif // SANDBOX_SRC_IPC_TAGS_H__ diff --git a/chromium/sandbox/win/src/ipc_unittest.cc b/chromium/sandbox/win/src/ipc_unittest.cc index 387b744f6aa..71f7aff4cc2 100644 --- a/chromium/sandbox/win/src/ipc_unittest.cc +++ b/chromium/sandbox/win/src/ipc_unittest.cc @@ -159,9 +159,9 @@ TEST(IPCTest, CrossCallStrPacking) { SharedMemIPCClient client(mem); CrossCallReturn answer; - uint32_t tag1 = 666; + IpcTag tag1 = IpcTag::PING1; const wchar_t* text = L"98765 - 43210"; - base::string16 copied_text; + std::wstring copied_text; CrossCallParamsEx* actual_params; CrossCall(client, tag1, text, &answer); @@ -173,7 +173,7 @@ TEST(IPCTest, CrossCallStrPacking) { copied_text.clear(); // Check with an empty string. - uint32_t tag2 = 777; + IpcTag tag2 = IpcTag::PING2; const wchar_t* null_text = nullptr; CrossCall(client, tag2, null_text, &answer); actual_params = reinterpret_cast<CrossCallParamsEx*>(client.GetBuffer()); @@ -188,7 +188,7 @@ TEST(IPCTest, CrossCallStrPacking) { EXPECT_TRUE(actual_params->GetParameterStr(0, &copied_text)); EXPECT_TRUE(copied_text.empty()); - uint32_t tag3 = 888; + IpcTag tag3 = IpcTag::PING1; param_size = 1; copied_text.clear(); @@ -208,7 +208,7 @@ TEST(IPCTest, CrossCallStrPacking) { EXPECT_STREQ(text, copied_text.c_str()); param_size = 1; - base::string16 copied_text_p0, copied_text_p2; + std::wstring copied_text_p0, copied_text_p2; const wchar_t* text2 = L"AeFG"; CrossCall(client, tag1, text2, null_text, text, &answer); @@ -237,8 +237,8 @@ TEST(IPCTest, CrossCallIntPacking) { client_control->server_alive = HANDLE(1); FixChannels(client_control, base_start, kIPCChannelSize, FIX_PONG_READY); - uint32_t tag1 = 999; - uint32_t tag2 = 111; + IpcTag tag1 = IpcTag::PING1; + IpcTag tag2 = IpcTag::PING2; const wchar_t* text = L"godzilla"; CrossCallParamsEx* actual_params; @@ -303,7 +303,7 @@ TEST(IPCTest, CrossCallIntPacking) { TEST(IPCTest, CrossCallValidation) { // First a sanity test with a well formed parameter object. unsigned long value = 124816; - const uint32_t kTag = 33; + IpcTag kTag = IpcTag::PING1; const uint32_t kBufferSize = 256; ActualCallParams<1, kBufferSize> params_1(kTag); params_1.CopyParamIn(0, &value, sizeof(value), false, UINT32_TYPE); @@ -393,7 +393,7 @@ DWORD WINAPI QuickResponseServer(PVOID param) { class CrossCallParamsMock : public CrossCallParams { public: - CrossCallParamsMock(uint32_t tag, uint32_t params_count) + CrossCallParamsMock(IpcTag tag, uint32_t params_count) : CrossCallParams(tag, params_count) {} }; @@ -438,9 +438,9 @@ TEST(IPCTest, ClientFastServer) { EXPECT_EQ(kBusyChannel, client_control->channels[1].state); EXPECT_EQ(kFreeChannel, client_control->channels[2].state); - EXPECT_EQ(0u, client_control->channels[1].ipc_tag); + EXPECT_EQ(IpcTag::UNUSED, client_control->channels[1].ipc_tag); - uint32_t tag = 7654; + IpcTag tag = IpcTag::PING1; CrossCallReturn answer; CrossCallParamsMock* params1 = new (buff1) CrossCallParamsMock(tag, 1); FakeOkAnswerInChannel(buff1); @@ -465,7 +465,7 @@ TEST(IPCTest, ClientFastServer) { events.pong = client_control->channels[0].pong_event; events.state = &client_control->channels[0].state; - tag = 4567; + tag = IpcTag::PING2; CrossCallParamsMock* params2 = new (buff0) CrossCallParamsMock(tag, 1); FakeOkAnswerInChannel(buff0); @@ -542,7 +542,7 @@ TEST(IPCTest, ClientSlowServer) { ::Sleep(1); void* buff0 = client.GetBuffer(); - uint32_t tag = 4321; + IpcTag tag = IpcTag::PING1; CrossCallReturn answer; CrossCallParamsMock* params1 = new (buff0) CrossCallParamsMock(tag, 1); FakeOkAnswerInChannel(buff0); @@ -564,12 +564,10 @@ TEST(IPCTest, ClientSlowServer) { // but only CallOneHandler should be used. class UnitTestIPCDispatcher : public Dispatcher { public: - enum { CALL_ONE_TAG = 78, CALL_TWO_TAG = 87 }; - UnitTestIPCDispatcher(); ~UnitTestIPCDispatcher() override {} - bool SetupService(InterceptionManager* manager, int service) override { + bool SetupService(InterceptionManager* manager, IpcTag service) override { return true; } @@ -584,10 +582,10 @@ class UnitTestIPCDispatcher : public Dispatcher { }; UnitTestIPCDispatcher::UnitTestIPCDispatcher() { - static const IPCCall call_one = {{CALL_ONE_TAG, {VOIDPTR_TYPE, UINT32_TYPE}}, + static const IPCCall call_one = {{IpcTag::PING1, {VOIDPTR_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>( &UnitTestIPCDispatcher::CallOneHandler)}; - static const IPCCall call_two = {{CALL_TWO_TAG, {VOIDPTR_TYPE, UINT32_TYPE}}, + static const IPCCall call_two = {{IpcTag::PING2, {VOIDPTR_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>( &UnitTestIPCDispatcher::CallTwoHandler)}; ipc_calls_.push_back(call_one); @@ -608,7 +606,7 @@ TEST(IPCTest, SharedMemServerTests) { CrossCallReturn answer; HANDLE bar = HANDLE(191919); DWORD foo = 6767676; - CrossCall(client, UnitTestIPCDispatcher::CALL_ONE_TAG, bar, foo, &answer); + CrossCall(client, IpcTag::PING1, bar, foo, &answer); void* buff = client.GetBuffer(); ASSERT_TRUE(buff); diff --git a/chromium/sandbox/win/src/named_pipe_dispatcher.cc b/chromium/sandbox/win/src/named_pipe_dispatcher.cc index 734a71c1a6e..85ffebe6e6b 100644 --- a/chromium/sandbox/win/src/named_pipe_dispatcher.cc +++ b/chromium/sandbox/win/src/named_pipe_dispatcher.cc @@ -7,6 +7,7 @@ #include <stdint.h> #include "base/strings/string_split.h" +#include "base/strings/string_util.h" #include "sandbox/win/src/crosscall_client.h" #include "sandbox/win/src/interception.h" @@ -23,7 +24,7 @@ namespace sandbox { NamedPipeDispatcher::NamedPipeDispatcher(PolicyBase* policy_base) : policy_base_(policy_base) { static const IPCCall create_params = { - {IPC_CREATENAMEDPIPEW_TAG, + {IpcTag::CREATENAMEDPIPEW, {WCHAR_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>(&NamedPipeDispatcher::CreateNamedPipe)}; @@ -32,8 +33,8 @@ NamedPipeDispatcher::NamedPipeDispatcher(PolicyBase* policy_base) } bool NamedPipeDispatcher::SetupService(InterceptionManager* manager, - int service) { - if (IPC_CREATENAMEDPIPEW_TAG == service) + IpcTag service) { + if (IpcTag::CREATENAMEDPIPEW == service) return INTERCEPT_EAT(manager, kKerneldllName, CreateNamedPipeW, CREATE_NAMED_PIPE_ID, 36); @@ -41,7 +42,7 @@ bool NamedPipeDispatcher::SetupService(InterceptionManager* manager, } bool NamedPipeDispatcher::CreateNamedPipe(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t open_mode, uint32_t pipe_mode, uint32_t max_instances, @@ -51,13 +52,13 @@ bool NamedPipeDispatcher::CreateNamedPipe(IPCInfo* ipc, ipc->return_info.win32_result = ERROR_ACCESS_DENIED; ipc->return_info.handle = INVALID_HANDLE_VALUE; - base::StringPiece16 dotdot(L".."); + base::StringPiece16 dotdot(STRING16_LITERAL("..")); - for (const base::StringPiece16& path : - base::SplitStringPiece(*name, base::string16(1, '/'), - base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { + for (const base::StringPiece16& path : base::SplitStringPiece( + base::AsStringPiece16(*name), STRING16_LITERAL("/"), + base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { for (const base::StringPiece16& inner : - base::SplitStringPiece(path, base::string16(1, '\\'), + base::SplitStringPiece(path, STRING16_LITERAL("\\"), base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { if (inner == dotdot) return true; @@ -69,7 +70,7 @@ bool NamedPipeDispatcher::CreateNamedPipe(IPCInfo* ipc, params[NameBased::NAME] = ParamPickerMake(pipe_name); EvalResult eval = - policy_base_->EvalPolicy(IPC_CREATENAMEDPIPEW_TAG, params.GetBase()); + policy_base_->EvalPolicy(IpcTag::CREATENAMEDPIPEW, params.GetBase()); // "For file I/O, the "\\?\" prefix to a path string tells the Windows APIs to // disable all string parsing and to send the string that follows it straight diff --git a/chromium/sandbox/win/src/named_pipe_dispatcher.h b/chromium/sandbox/win/src/named_pipe_dispatcher.h index 83f45e093f4..a14f658506a 100644 --- a/chromium/sandbox/win/src/named_pipe_dispatcher.h +++ b/chromium/sandbox/win/src/named_pipe_dispatcher.h @@ -7,9 +7,11 @@ #include <stdint.h> +#include <string> + #include "base/macros.h" -#include "base/strings/string16.h" #include "sandbox/win/src/crosscall_server.h" +#include "sandbox/win/src/ipc_tags.h" #include "sandbox/win/src/sandbox_policy_base.h" namespace sandbox { @@ -21,13 +23,13 @@ class NamedPipeDispatcher : public Dispatcher { ~NamedPipeDispatcher() override {} // Dispatcher interface. - bool SetupService(InterceptionManager* manager, int service) override; + bool SetupService(InterceptionManager* manager, IpcTag service) override; private: // Processes IPC requests coming from calls to CreateNamedPipeW() in the // target. bool CreateNamedPipe(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t open_mode, uint32_t pipe_mode, uint32_t max_instances, diff --git a/chromium/sandbox/win/src/named_pipe_interception.cc b/chromium/sandbox/win/src/named_pipe_interception.cc index 02adf8f7305..c1ca07a3a52 100644 --- a/chromium/sandbox/win/src/named_pipe_interception.cc +++ b/chromium/sandbox/win/src/named_pipe_interception.cc @@ -49,13 +49,13 @@ TargetCreateNamedPipeW(CreateNamedPipeWFunction orig_CreateNamedPipeW, CountedParameterSet<NameBased> params; params[NameBased::NAME] = ParamPickerMake(pipe_name); - if (!QueryBroker(IPC_CREATENAMEDPIPEW_TAG, params.GetBase())) + if (!QueryBroker(IpcTag::CREATENAMEDPIPEW, params.GetBase())) break; SharedMemIPCClient ipc(memory); CrossCallReturn answer = {0}; ResultCode code = - CrossCall(ipc, IPC_CREATENAMEDPIPEW_TAG, pipe_name, open_mode, + CrossCall(ipc, IpcTag::CREATENAMEDPIPEW, pipe_name, open_mode, pipe_mode, max_instance, out_buffer_size, in_buffer_size, default_timeout, &answer); if (SBOX_ALL_OK != code) diff --git a/chromium/sandbox/win/src/named_pipe_policy.cc b/chromium/sandbox/win/src/named_pipe_policy.cc index 5a409e01d4e..bfad75852d7 100644 --- a/chromium/sandbox/win/src/named_pipe_policy.cc +++ b/chromium/sandbox/win/src/named_pipe_policy.cc @@ -54,7 +54,7 @@ bool NamedPipePolicy::GenerateRules(const wchar_t* name, if (!pipe.AddStringMatch(IF, NameBased::NAME, name, CASE_INSENSITIVE)) { return false; } - if (!policy->AddRule(IPC_CREATENAMEDPIPEW_TAG, &pipe)) { + if (!policy->AddRule(IpcTag::CREATENAMEDPIPEW, &pipe)) { return false; } return true; @@ -62,7 +62,7 @@ bool NamedPipePolicy::GenerateRules(const wchar_t* name, DWORD NamedPipePolicy::CreateNamedPipeAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& name, + const std::wstring& name, DWORD open_mode, DWORD pipe_mode, DWORD max_instances, diff --git a/chromium/sandbox/win/src/named_pipe_policy.h b/chromium/sandbox/win/src/named_pipe_policy.h index f0511a0ab2e..4ad272f16ff 100644 --- a/chromium/sandbox/win/src/named_pipe_policy.h +++ b/chromium/sandbox/win/src/named_pipe_policy.h @@ -7,7 +7,6 @@ #include <string> -#include "base/strings/string16.h" #include "sandbox/win/src/crosscall_server.h" #include "sandbox/win/src/policy_low_level.h" #include "sandbox/win/src/sandbox_policy.h" @@ -29,7 +28,7 @@ class NamedPipePolicy { // Processes a 'CreateNamedPipeW()' request from the target. static DWORD CreateNamedPipeAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& name, + const std::wstring& name, DWORD open_mode, DWORD pipe_mode, DWORD max_instances, diff --git a/chromium/sandbox/win/src/named_pipe_policy_test.cc b/chromium/sandbox/win/src/named_pipe_policy_test.cc index d338be4627e..db532d618d6 100644 --- a/chromium/sandbox/win/src/named_pipe_policy_test.cc +++ b/chromium/sandbox/win/src/named_pipe_policy_test.cc @@ -25,7 +25,7 @@ SBOX_TESTS_COMMAND int NamedPipe_Create(int argc, wchar_t** argv) { // The second parameter allows us to enforce an allowlist for where the // pipe should be in the object namespace after creation. if (argc == 2) { - base::string16 handle_name; + std::wstring handle_name; if (GetHandleName(pipe, &handle_name)) { if (handle_name.compare(0, wcslen(argv[1]), argv[1]) != 0) return SBOX_TEST_FAILED; diff --git a/chromium/sandbox/win/src/policy_engine_opcodes.h b/chromium/sandbox/win/src/policy_engine_opcodes.h index 22d1ee241b8..8e8816df1cb 100644 --- a/chromium/sandbox/win/src/policy_engine_opcodes.h +++ b/chromium/sandbox/win/src/policy_engine_opcodes.h @@ -193,9 +193,10 @@ class PolicyOpcode { uint32_t GetOptions() const { return options_; } // Sets the stored options such as kPolNegateEval. - void SetOptions(uint32_t options) { - options_ = base::checked_cast<uint16_t>(options); - } + void SetOptions(uint32_t options) { options_ = options; } + + // Returns the parameter of the function the opcode concerns. + uint16_t GetParameter() const { return parameter_; } private: static const size_t kArgumentCount = 4; // The number of supported argument. @@ -214,10 +215,7 @@ class PolicyOpcode { MatchContext* match); OpcodeID opcode_id_; int16_t parameter_; - // TODO(cpu): Making |options_| a uint32_t would avoid casting, but causes - // test failures. Somewhere code is relying on the size of this struct. - // http://crbug.com/420296 - uint16_t options_; + uint32_t options_; OpcodeArgument arguments_[PolicyOpcode::kArgumentCount]; }; diff --git a/chromium/sandbox/win/src/policy_low_level.cc b/chromium/sandbox/win/src/policy_low_level.cc index d2c9a6f8564..d987211c8b5 100644 --- a/chromium/sandbox/win/src/policy_low_level.cc +++ b/chromium/sandbox/win/src/policy_low_level.cc @@ -40,7 +40,7 @@ LowLevelPolicy::LowLevelPolicy(PolicyGlobal* policy_store) // Adding a rule is nothing more than pushing it into an stl container. Done() // is called for the rule in case the code that made the rule in the first // place has not done it. -bool LowLevelPolicy::AddRule(int service, PolicyRule* rule) { +bool LowLevelPolicy::AddRule(IpcTag service, PolicyRule* rule) { if (!rule->Done()) { return false; } @@ -69,7 +69,7 @@ LowLevelPolicy::~LowLevelPolicy() { bool LowLevelPolicy::Done() { typedef std::list<RuleNode> RuleNodes; typedef std::list<const PolicyRule*> RuleList; - typedef std::map<uint32_t, RuleList> Mmap; + typedef std::map<IpcTag, RuleList> Mmap; Mmap mmap; for (RuleNodes::iterator it = rules_.begin(); it != rules_.end(); ++it) { @@ -82,11 +82,11 @@ bool LowLevelPolicy::Done() { size_t avail_size = policy_store_->data_size; for (Mmap::iterator it = mmap.begin(); it != mmap.end(); ++it) { - uint32_t service = (*it).first; - if (service >= kMaxServiceCount) { + IpcTag service = (*it).first; + if (static_cast<size_t>(service) >= kMaxServiceCount) { return false; } - policy_store_->entry[service] = current_buffer; + policy_store_->entry[static_cast<size_t>(service)] = current_buffer; RuleList::iterator rules_it = (*it).second.begin(); RuleList::iterator rules_it_end = (*it).second.end(); @@ -113,10 +113,10 @@ bool LowLevelPolicy::Done() { svc_opcode_count += op_count; } - current_buffer->opcode_count += svc_opcode_count; - size_t policy_byte_count = + current_buffer->opcode_count = svc_opcode_count; + size_t policy_buffers_occupied = (svc_opcode_count * sizeof(PolicyOpcode)) / sizeof(current_buffer[0]); - current_buffer = ¤t_buffer[policy_byte_count + 1]; + current_buffer = ¤t_buffer[policy_buffers_occupied + 1]; } return true; @@ -159,7 +159,7 @@ bool PolicyRule::GenStringOpcode(RuleType rule_type, int state, bool last_call, int* skip_count, - base::string16* fragment) { + std::wstring* fragment) { // The last opcode must: // 1) Always clear the context. // 2) Preserve the negation. @@ -231,7 +231,7 @@ bool PolicyRule::AddStringMatch(RuleType rule_type, uint32_t last_char = kLastCharIsNone; int state = PENDING_NONE; int skip_count = 0; // counts how many '?' we have seen in a row. - base::string16 fragment; // accumulates the non-wildcard part. + std::wstring fragment; // accumulates the non-wildcard part. while (L'\0' != *current_char) { switch (*current_char) { diff --git a/chromium/sandbox/win/src/policy_low_level.h b/chromium/sandbox/win/src/policy_low_level.h index ae9bec6e1e5..1586f96af90 100644 --- a/chromium/sandbox/win/src/policy_low_level.h +++ b/chromium/sandbox/win/src/policy_low_level.h @@ -10,14 +10,15 @@ #include <list> +#include <string> + #include "base/macros.h" -#include "base/strings/string16.h" #include "sandbox/win/src/ipc_tags.h" #include "sandbox/win/src/policy_engine_opcodes.h" #include "sandbox/win/src/policy_engine_params.h" // Low level policy classes. -// Built on top of the PolicyOpcode and OpcodeFatory, the low level policy +// Built on top of the PolicyOpcode and OpcodeFactory, the low level policy // provides a way to define rules on strings and numbers but it is unaware // of Windows specific details or how the Interceptions must be set up. // To use these classes you construct one or more rules and add them to the @@ -42,10 +43,6 @@ namespace sandbox { -// TODO(cpu): Move this constant to crosscall_client.h. -const size_t kMaxServiceCount = 64; -static_assert(IPC_LAST_TAG <= kMaxServiceCount, "kMaxServiceCount is too low"); - // Defines the memory layout of the policy. This memory is filled by // LowLevelPolicy object. // For example: @@ -93,7 +90,7 @@ class LowLevelPolicy { // service: The id of the service that this rule is associated with, // for example the 'Open Thread' service or the "Create File" service. // returns false on error. - bool AddRule(int service, PolicyRule* rule); + bool AddRule(IpcTag service, PolicyRule* rule); // Generates all the rules added with AddRule() into the memory area // passed on the constructor. Returns false on error. @@ -102,7 +99,7 @@ class LowLevelPolicy { private: struct RuleNode { const PolicyRule* rule; - int service; + IpcTag service; }; std::list<RuleNode> rules_; PolicyGlobal* policy_store_; @@ -171,7 +168,7 @@ class PolicyRule { int state, bool last_call, int* skip_count, - base::string16* fragment); + std::wstring* fragment); // Loop over all generated opcodes and copy them to increasing memory // addresses from opcode_start and copy the extra data (strings usually) into diff --git a/chromium/sandbox/win/src/policy_low_level_unittest.cc b/chromium/sandbox/win/src/policy_low_level_unittest.cc index 681ec38fe55..84846600961 100644 --- a/chromium/sandbox/win/src/policy_low_level_unittest.cc +++ b/chromium/sandbox/win/src/policy_low_level_unittest.cc @@ -60,7 +60,7 @@ TEST(PolicyEngineTest, SimpleStrMatch) { pr.AddStringMatch(IF, 0, L"z:\\Directory\\domo.txt", CASE_INSENSITIVE)); PolicyGlobal* policy = MakePolicyMemory(); - const uint32_t kFakeService = 2; + const IpcTag kFakeService = IpcTag::PING2; LowLevelPolicy policyGen(policy); EXPECT_TRUE(policyGen.AddRule(kFakeService, &pr)); @@ -73,7 +73,7 @@ TEST(PolicyEngineTest, SimpleStrMatch) { POLPARAMS_END; PolicyResult result; - PolicyProcessor pol_ev(policy->entry[kFakeService]); + PolicyProcessor pol_ev(policy->entry[static_cast<size_t>(kFakeService)]); result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params)); EXPECT_EQ(POLICY_MATCH, result); @@ -92,7 +92,7 @@ TEST(PolicyEngineTest, SimpleIfNotStrMatch) { EXPECT_TRUE(pr.AddStringMatch(IF_NOT, 0, L"c:\\Microsoft\\", CASE_SENSITIVE)); PolicyGlobal* policy = MakePolicyMemory(); - const uint32_t kFakeService = 2; + const IpcTag kFakeService = IpcTag::PING2; LowLevelPolicy policyGen(policy); EXPECT_TRUE(policyGen.AddRule(kFakeService, &pr)); @@ -104,7 +104,7 @@ TEST(PolicyEngineTest, SimpleIfNotStrMatch) { POLPARAMS_END; PolicyResult result; - PolicyProcessor pol_ev(policy->entry[kFakeService]); + PolicyProcessor pol_ev(policy->entry[static_cast<size_t>(kFakeService)]); filename = L"c:\\Microsoft\\"; result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params)); @@ -130,7 +130,7 @@ TEST(PolicyEngineTest, SimpleIfNotStrMatchWild1) { pr.AddStringMatch(IF_NOT, 0, L"c:\\Microsoft\\*", CASE_SENSITIVE)); PolicyGlobal* policy = MakePolicyMemory(); - const uint32_t kFakeService = 3; + const IpcTag kFakeService = IpcTag::NTCREATEFILE; LowLevelPolicy policyGen(policy); EXPECT_TRUE(policyGen.AddRule(kFakeService, &pr)); @@ -142,7 +142,7 @@ TEST(PolicyEngineTest, SimpleIfNotStrMatchWild1) { POLPARAMS_END; PolicyResult result; - PolicyProcessor pol_ev(policy->entry[kFakeService]); + PolicyProcessor pol_ev(policy->entry[static_cast<size_t>(kFakeService)]); filename = L"c:\\Microsoft\\domo.txt"; result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params)); @@ -163,7 +163,7 @@ TEST(PolicyEngineTest, SimpleIfNotStrMatchWild2) { pr.AddStringMatch(IF_NOT, 0, L"c:\\Microsoft\\*.txt", CASE_SENSITIVE)); PolicyGlobal* policy = MakePolicyMemory(); - const uint32_t kFakeService = 3; + const IpcTag kFakeService = IpcTag::NTCREATEFILE; LowLevelPolicy policyGen(policy); EXPECT_TRUE(policyGen.AddRule(kFakeService, &pr)); @@ -175,7 +175,7 @@ TEST(PolicyEngineTest, SimpleIfNotStrMatchWild2) { POLPARAMS_END; PolicyResult result; - PolicyProcessor pol_ev(policy->entry[kFakeService]); + PolicyProcessor pol_ev(policy->entry[static_cast<size_t>(kFakeService)]); filename = L"c:\\Microsoft\\domo.txt"; result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params)); @@ -202,7 +202,7 @@ TEST(PolicyEngineTest, IfNotStrMatchTwoRulesWild1) { EXPECT_TRUE(pr.AddNumberMatch(IF, 1, 24, EQUAL)); PolicyGlobal* policy = MakePolicyMemory(); - const uint32_t kFakeService = 3; + const IpcTag kFakeService = IpcTag::NTCREATEFILE; LowLevelPolicy policyGen(policy); EXPECT_TRUE(policyGen.AddRule(kFakeService, &pr)); @@ -216,7 +216,7 @@ TEST(PolicyEngineTest, IfNotStrMatchTwoRulesWild1) { POLPARAMS_END; PolicyResult result; - PolicyProcessor pol_ev(policy->entry[kFakeService]); + PolicyProcessor pol_ev(policy->entry[static_cast<size_t>(kFakeService)]); filename = L"c:\\Microsoft\\domo.txt"; access = 24; @@ -251,7 +251,7 @@ TEST(PolicyEngineTest, IfNotStrMatchTwoRulesWild2) { EXPECT_TRUE(pr.AddNumberMatch(IF, 2, 66, EQUAL)); PolicyGlobal* policy = MakePolicyMemory(); - const uint32_t kFakeService = 3; + const IpcTag kFakeService = IpcTag::NTCREATEFILE; LowLevelPolicy policyGen(policy); EXPECT_TRUE(policyGen.AddRule(kFakeService, &pr)); @@ -268,7 +268,7 @@ TEST(PolicyEngineTest, IfNotStrMatchTwoRulesWild2) { POLPARAMS_END; PolicyResult result; - PolicyProcessor pol_ev(policy->entry[kFakeService]); + PolicyProcessor pol_ev(policy->entry[static_cast<size_t>(kFakeService)]); filename = L"c:\\GoogleV2\\domo.txt"; access = 24; @@ -324,7 +324,7 @@ TEST(PolicyEngineTest, OneRuleTest) { PolicyGlobal* policy = MakePolicyMemory(); - const uint32_t kNtFakeCreateFile = 7; + const IpcTag kNtFakeCreateFile = IpcTag::NTCREATEFILE; LowLevelPolicy policyGen(policy); EXPECT_TRUE(policyGen.AddRule(kNtFakeCreateFile, &pr)); @@ -343,7 +343,7 @@ TEST(PolicyEngineTest, OneRuleTest) { POLPARAMS_END; PolicyResult result; - PolicyProcessor pol_ev(policy->entry[kNtFakeCreateFile]); + PolicyProcessor pol_ev(policy->entry[static_cast<size_t>(kNtFakeCreateFile)]); result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params)); EXPECT_EQ(POLICY_MATCH, result); @@ -430,9 +430,10 @@ TEST(PolicyEngineTest, ThreeRulesTest) { PolicyGlobal* policy = MakePolicyMemory(); - const uint32_t kNtFakeNone = 4; - const uint32_t kNtFakeCreateFile = 5; - const uint32_t kNtFakeOpenFile = 6; + // These do not match the real tag values. + const IpcTag kNtFakeNone = static_cast<IpcTag>(4); + const IpcTag kNtFakeCreateFile = static_cast<IpcTag>(5); + const IpcTag kNtFakeOpenFile = static_cast<IpcTag>(6); LowLevelPolicy policyGen(policy); EXPECT_TRUE(policyGen.AddRule(kNtFakeCreateFile, &pr_pipe)); @@ -464,9 +465,11 @@ TEST(PolicyEngineTest, ThreeRulesTest) { ++opc4; ++opc5; - size_t tc1 = policy->entry[kNtFakeNone]->opcode_count; - size_t tc2 = policy->entry[kNtFakeCreateFile]->opcode_count; - size_t tc3 = policy->entry[kNtFakeOpenFile]->opcode_count; + size_t tc1 = policy->entry[static_cast<size_t>(kNtFakeNone)]->opcode_count; + size_t tc2 = + policy->entry[static_cast<size_t>(kNtFakeCreateFile)]->opcode_count; + size_t tc3 = + policy->entry[static_cast<size_t>(kNtFakeOpenFile)]->opcode_count; EXPECT_EQ(opc5, tc1); EXPECT_EQ((opc1 + opc2 + opc3), tc2); @@ -474,17 +477,25 @@ TEST(PolicyEngineTest, ThreeRulesTest) { // Check the type of the first and last opcode of each service. - EXPECT_EQ(OP_NUMBER_AND_MATCH, - policy->entry[kNtFakeNone]->opcodes[0].GetID()); - EXPECT_EQ(OP_ACTION, policy->entry[kNtFakeNone]->opcodes[tc1 - 1].GetID()); + EXPECT_EQ( + OP_NUMBER_AND_MATCH, + policy->entry[static_cast<size_t>(kNtFakeNone)]->opcodes[0].GetID()); + EXPECT_EQ(OP_ACTION, policy->entry[static_cast<size_t>(kNtFakeNone)] + ->opcodes[tc1 - 1] + .GetID()); EXPECT_EQ(OP_WSTRING_MATCH, - policy->entry[kNtFakeCreateFile]->opcodes[0].GetID()); - EXPECT_EQ(OP_ACTION, - policy->entry[kNtFakeCreateFile]->opcodes[tc2 - 1].GetID()); - EXPECT_EQ(OP_WSTRING_MATCH, - policy->entry[kNtFakeOpenFile]->opcodes[0].GetID()); - EXPECT_EQ(OP_ACTION, - policy->entry[kNtFakeOpenFile]->opcodes[tc3 - 1].GetID()); + policy->entry[static_cast<size_t>(kNtFakeCreateFile)] + ->opcodes[0] + .GetID()); + EXPECT_EQ(OP_ACTION, policy->entry[static_cast<size_t>(kNtFakeCreateFile)] + ->opcodes[tc2 - 1] + .GetID()); + EXPECT_EQ( + OP_WSTRING_MATCH, + policy->entry[static_cast<size_t>(kNtFakeOpenFile)]->opcodes[0].GetID()); + EXPECT_EQ(OP_ACTION, policy->entry[static_cast<size_t>(kNtFakeOpenFile)] + ->opcodes[tc3 - 1] + .GetID()); // Test the policy evaluation. @@ -501,9 +512,11 @@ TEST(PolicyEngineTest, ThreeRulesTest) { POLPARAMS_END; PolicyResult result; - PolicyProcessor eval_CreateFile(policy->entry[kNtFakeCreateFile]); - PolicyProcessor eval_OpenFile(policy->entry[kNtFakeOpenFile]); - PolicyProcessor eval_None(policy->entry[kNtFakeNone]); + PolicyProcessor eval_CreateFile( + policy->entry[static_cast<size_t>(kNtFakeCreateFile)]); + PolicyProcessor eval_OpenFile( + policy->entry[static_cast<size_t>(kNtFakeOpenFile)]); + PolicyProcessor eval_None(policy->entry[static_cast<size_t>(kNtFakeNone)]); result = eval_CreateFile.Evaluate(kShortEval, params, _countof(params)); EXPECT_EQ(NO_POLICY_MATCH, result); @@ -588,8 +601,8 @@ TEST(PolicyEngineTest, PolicyRuleCopyConstructorTwoStrings) { PolicyGlobal* policy = MakePolicyMemory(); LowLevelPolicy policyGen(policy); - EXPECT_TRUE(policyGen.AddRule(1, &pr_orig)); - EXPECT_TRUE(policyGen.AddRule(2, &pr_copy)); + EXPECT_TRUE(policyGen.AddRule(IpcTag::PING1, &pr_orig)); + EXPECT_TRUE(policyGen.AddRule(IpcTag::PING2, &pr_copy)); EXPECT_TRUE(policyGen.Done()); const wchar_t* name = nullptr; @@ -618,4 +631,54 @@ TEST(PolicyEngineTest, PolicyRuleCopyConstructorTwoStrings) { EXPECT_EQ(POLICY_MATCH, result); EXPECT_EQ(ASK_BROKER, pol_ev_copy.GetAction()); } + +TEST(PolicyEngineTest, PolicyGenDoneCalledTwice) { + SetupNtdllImports(); + // The specific rules here are not important. + PolicyRule pr_orig(ASK_BROKER); + EXPECT_TRUE(pr_orig.AddStringMatch(IF, 0, L"hello.*", CASE_SENSITIVE)); + + PolicyRule pr_copy(pr_orig); + EXPECT_TRUE(pr_orig.AddStringMatch(IF_NOT, 0, L"*.txt", CASE_SENSITIVE)); + EXPECT_TRUE(pr_copy.AddStringMatch(IF_NOT, 0, L"*.txt", CASE_SENSITIVE)); + + PolicyGlobal* policy = MakePolicyMemory(); + LowLevelPolicy policyGen(policy); + const IpcTag tag1 = IpcTag::PING1; + const IpcTag tag2 = IpcTag::PING2; + EXPECT_TRUE(policyGen.AddRule(tag1, &pr_orig)); + EXPECT_TRUE(policyGen.AddRule(tag2, &pr_copy)); + EXPECT_TRUE(policyGen.Done()); + + // Obtain opcode counts. + size_t tc1 = policy->entry[static_cast<size_t>(IpcTag::PING1)]->opcode_count; + size_t tc2 = policy->entry[static_cast<size_t>(IpcTag::PING2)]->opcode_count; + + // Call Done() again. + EXPECT_TRUE(policyGen.Done()); + + // Expect same opcode counts. + EXPECT_EQ(tc1, + policy->entry[static_cast<size_t>(IpcTag::PING1)]->opcode_count); + EXPECT_EQ(tc2, + policy->entry[static_cast<size_t>(IpcTag::PING2)]->opcode_count); + + // Confirm the rules work as before. + const wchar_t* name = nullptr; + POLPARAMS_BEGIN(eval_params) + POLPARAM(name) + POLPARAMS_END; + + PolicyResult result; + PolicyProcessor pol_ev_orig(policy->entry[1]); + name = L"domo.txt"; + result = pol_ev_orig.Evaluate(kShortEval, eval_params, _countof(eval_params)); + EXPECT_EQ(NO_POLICY_MATCH, result); + + name = L"hello.bmp"; + result = pol_ev_orig.Evaluate(kShortEval, eval_params, _countof(eval_params)); + EXPECT_EQ(POLICY_MATCH, result); + EXPECT_EQ(ASK_BROKER, pol_ev_orig.GetAction()); +} + } // namespace sandbox diff --git a/chromium/sandbox/win/src/policy_target.cc b/chromium/sandbox/win/src/policy_target.cc index ac684c78d22..5cf894a4482 100644 --- a/chromium/sandbox/win/src/policy_target.cc +++ b/chromium/sandbox/win/src/policy_target.cc @@ -28,7 +28,7 @@ SANDBOX_INTERCEPT NtExports g_nt; extern void* volatile g_shared_policy_memory; SANDBOX_INTERCEPT size_t g_shared_policy_size; -bool QueryBroker(int ipc_id, CountedParameterSetBase* params) { +bool QueryBroker(IpcTag ipc_id, CountedParameterSetBase* params) { DCHECK_NT(static_cast<size_t>(ipc_id) < kMaxServiceCount); DCHECK_NT(g_shared_policy_memory); DCHECK_NT(g_shared_policy_size > 0); @@ -39,14 +39,16 @@ bool QueryBroker(int ipc_id, CountedParameterSetBase* params) { PolicyGlobal* global_policy = reinterpret_cast<PolicyGlobal*>(g_shared_policy_memory); - if (!global_policy->entry[ipc_id]) + if (!global_policy->entry[static_cast<size_t>(ipc_id)]) return false; PolicyBuffer* policy = reinterpret_cast<PolicyBuffer*>( reinterpret_cast<char*>(g_shared_policy_memory) + - reinterpret_cast<size_t>(global_policy->entry[ipc_id])); + reinterpret_cast<size_t>( + global_policy->entry[static_cast<size_t>(ipc_id)])); - if ((reinterpret_cast<size_t>(global_policy->entry[ipc_id]) > + if ((reinterpret_cast<size_t>( + global_policy->entry[static_cast<size_t>(ipc_id)]) > global_policy->data_size) || (g_shared_policy_size < global_policy->data_size)) { NOTREACHED_NT(); diff --git a/chromium/sandbox/win/src/policy_target.h b/chromium/sandbox/win/src/policy_target.h index 373714e197c..62686aaab23 100644 --- a/chromium/sandbox/win/src/policy_target.h +++ b/chromium/sandbox/win/src/policy_target.h @@ -5,6 +5,7 @@ #ifndef SANDBOX_WIN_SRC_POLICY_TARGET_H_ #define SANDBOX_WIN_SRC_POLICY_TARGET_H_ +#include "sandbox/win/src/ipc_tags.h" #include "sandbox/win/src/nt_internals.h" #include "sandbox/win/src/sandbox_types.h" @@ -14,7 +15,7 @@ struct CountedParameterSetBase; // Performs a policy lookup and returns true if the request should be passed to // the broker process. -bool QueryBroker(int ipc_id, CountedParameterSetBase* params); +bool QueryBroker(IpcTag ipc_id, CountedParameterSetBase* params); extern "C" { diff --git a/chromium/sandbox/win/src/policy_target_test.cc b/chromium/sandbox/win/src/policy_target_test.cc index e69ff4f5898..4ee03e19f61 100644 --- a/chromium/sandbox/win/src/policy_target_test.cc +++ b/chromium/sandbox/win/src/policy_target_test.cc @@ -6,6 +6,7 @@ #include "base/memory/writable_shared_memory_region.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" +#include "base/strings/string_util.h" #include "base/win/scoped_process_information.h" #include "base/win/windows_version.h" #include "sandbox/win/src/sandbox.h" @@ -164,7 +165,7 @@ SBOX_TESTS_COMMAND int PolicyTargetTest_process(int argc, wchar_t** argv) { PROCESS_INFORMATION temp_process_info = {}; // Note: CreateProcessW() can write to its lpCommandLine, don't pass a // raw string literal. - base::string16 writable_cmdline_str(L"foo.exe"); + std::wstring writable_cmdline_str(L"foo.exe"); if (!::CreateProcessW(L"foo.exe", &writable_cmdline_str[0], nullptr, nullptr, false, 0, nullptr, nullptr, &startup_info, &temp_process_info)) @@ -246,7 +247,7 @@ TEST(PolicyTargetTest, DesktopPolicy) { wchar_t prog_name[MAX_PATH]; GetModuleFileNameW(nullptr, prog_name, MAX_PATH); - base::string16 arguments(L"\""); + std::wstring arguments(L"\""); arguments += prog_name; arguments += L"\" -child 0 wait"; // Don't care about the "state" argument. @@ -263,7 +264,7 @@ TEST(PolicyTargetTest, DesktopPolicy) { result = broker->SpawnTarget(prog_name, arguments.c_str(), policy, &warning_result, &last_error, &temp_process_info); - base::string16 desktop_name = policy->GetAlternateDesktop(); + std::wstring desktop_name = policy->GetAlternateDesktop(); policy = nullptr; EXPECT_EQ(SBOX_ALL_OK, result); @@ -313,7 +314,7 @@ TEST(PolicyTargetTest, WinstaPolicy) { wchar_t prog_name[MAX_PATH]; GetModuleFileNameW(nullptr, prog_name, MAX_PATH); - base::string16 arguments(L"\""); + std::wstring arguments(L"\""); arguments += prog_name; arguments += L"\" -child 0 wait"; // Don't care about the "state" argument. @@ -330,7 +331,7 @@ TEST(PolicyTargetTest, WinstaPolicy) { result = broker->SpawnTarget(prog_name, arguments.c_str(), policy, &warning_result, &last_error, &temp_process_info); - base::string16 desktop_name = policy->GetAlternateDesktop(); + std::wstring desktop_name = policy->GetAlternateDesktop(); policy = nullptr; EXPECT_EQ(SBOX_ALL_OK, result); @@ -348,7 +349,7 @@ TEST(PolicyTargetTest, WinstaPolicy) { ASSERT_FALSE(desktop_name.empty()); // Make sure there is a backslash, for the window station name. - EXPECT_NE(desktop_name.find_first_of(L'\\'), base::string16::npos); + EXPECT_NE(desktop_name.find_first_of(L'\\'), std::wstring::npos); // Isolate the desktop name. desktop_name = desktop_name.substr(desktop_name.find_first_of(L'\\') + 1); @@ -383,8 +384,8 @@ TEST(PolicyTargetTest, BothLocalAndAlternateWinstationDesktop) { result = policy3->SetAlternateDesktop(false); EXPECT_EQ(SBOX_ALL_OK, result); - base::string16 policy1_desktop_name = policy1->GetAlternateDesktop(); - base::string16 policy2_desktop_name = policy2->GetAlternateDesktop(); + std::wstring policy1_desktop_name = policy1->GetAlternateDesktop(); + std::wstring policy2_desktop_name = policy2->GetAlternateDesktop(); // Extract only the "desktop name" portion of // "{winstation name}\\{desktop name}" @@ -424,11 +425,11 @@ TEST(PolicyTargetTest, ShareHandleTest) { scoped_refptr<TargetPolicy> policy = broker->CreatePolicy(); policy->AddHandleToShare(read_only_region.GetPlatformHandle()); - base::string16 arguments(L"\""); + std::wstring arguments(L"\""); arguments += prog_name; arguments += L"\" -child 0 shared_memory_handle "; - arguments += base::NumberToString16( - base::win::HandleToUint32(read_only_region.GetPlatformHandle())); + arguments += base::AsWString(base::NumberToString16( + base::win::HandleToUint32(read_only_region.GetPlatformHandle()))); // Launch the app. ResultCode result = SBOX_ALL_OK; diff --git a/chromium/sandbox/win/src/process_mitigations_dyncode_unittest.cc b/chromium/sandbox/win/src/process_mitigations_dyncode_unittest.cc index 59db0b00848..70b20532348 100644 --- a/chromium/sandbox/win/src/process_mitigations_dyncode_unittest.cc +++ b/chromium/sandbox/win/src/process_mitigations_dyncode_unittest.cc @@ -271,7 +271,7 @@ void DynamicCodeTestHarness(sandbox::MitigationFlags which_mitigation, sandbox::SBOX_ALL_OK); } - base::string16 shared = + std::wstring shared = (which_mitigation == sandbox::MITIGATION_DYNAMIC_CODE_DISABLE) ? L"TestWin81DynamicCode " : L"TestWin10DynamicCodeWithOptOut "; @@ -281,7 +281,7 @@ void DynamicCodeTestHarness(sandbox::MitigationFlags which_mitigation, } // Test 1: - base::string16 test = + std::wstring test = base::StringPrintf(L"%ls %u", shared.c_str(), VIRTUALALLOC); EXPECT_EQ((expect_success ? sandbox::SBOX_TEST_SUCCEEDED : ERROR_DYNAMIC_CODE_BLOCKED), @@ -411,7 +411,7 @@ TEST(ProcessMitigationsTest, CheckWin81DynamicCodePolicySuccess) { return; #endif - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(TESTPOLICY_DYNAMICCODE); //--------------------------------- @@ -487,7 +487,7 @@ TEST(ProcessMitigationsTest, CheckWin10DynamicCodeOptOutPolicySuccess) { return; #endif - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(TESTPOLICY_DYNAMICCODEOPTOUT); //--------------------------------- diff --git a/chromium/sandbox/win/src/process_mitigations_extensionpoints_unittest.cc b/chromium/sandbox/win/src/process_mitigations_extensionpoints_unittest.cc index a9da035be55..e2d63555b8f 100644 --- a/chromium/sandbox/win/src/process_mitigations_extensionpoints_unittest.cc +++ b/chromium/sandbox/win/src/process_mitigations_extensionpoints_unittest.cc @@ -61,7 +61,7 @@ bool SpawnWinProc(PROCESS_INFORMATION* pi, bool success_test, HANDLE* event) { } // Command line must be writable. - base::string16 cmd_writeable(hooking_win_proc::g_winproc_file); + std::wstring cmd_writeable(hooking_win_proc::g_winproc_file); if (!::CreateProcessW(nullptr, &cmd_writeable[0], nullptr, nullptr, false, creation_flags, nullptr, nullptr, @@ -236,8 +236,8 @@ void TestWin8ExtensionPointAppInitWrapper(bool is_success_test) { const wchar_t* dlls_value_name = L"AppInit_DLLs"; const wchar_t* enabled_value_name = L"LoadAppInit_DLLs"; const wchar_t* signing_value_name = L"RequireSignedAppInit_DLLs"; - base::string16 orig_dlls; - base::string16 new_dlls; + std::wstring orig_dlls; + std::wstring new_dlls; DWORD orig_enabled_value = 0; DWORD orig_signing_value = 0; base::win::RegKey app_init_key(HKEY_LOCAL_MACHINE, app_init_reg_path, @@ -367,7 +367,7 @@ TEST(ProcessMitigationsTest, CheckWin8ExtensionPointPolicySuccess) { if (base::win::GetVersion() < base::win::Version::WIN8) return; - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(sandbox::TESTPOLICY_EXTENSIONPOINT); //--------------------------------- diff --git a/chromium/sandbox/win/src/process_mitigations_imageload_unittest.cc b/chromium/sandbox/win/src/process_mitigations_imageload_unittest.cc index cece2450cfd..d3e7d6c21a5 100644 --- a/chromium/sandbox/win/src/process_mitigations_imageload_unittest.cc +++ b/chromium/sandbox/win/src/process_mitigations_imageload_unittest.cc @@ -44,7 +44,7 @@ using CheckHijackResultFunction = decltype(&CheckHijackResult); void TestWin10ImageLoadRemote(bool is_success_test) { // ***Insert a manual testing share UNC path here! // E.g.: \\\\hostname\\sharename\\calc.exe - base::string16 unc = L"\"\\\\hostname\\sharename\\calc.exe\""; + std::wstring unc = L"\"\\\\hostname\\sharename\\calc.exe\""; sandbox::TestRunner runner; sandbox::TargetPolicy* policy = runner.GetPolicy(); @@ -61,7 +61,7 @@ void TestWin10ImageLoadRemote(bool is_success_test) { sandbox::SBOX_ALL_OK); } - base::string16 test = L"TestChildProcess "; + std::wstring test = L"TestChildProcess "; test += unc.c_str(); EXPECT_EQ((is_success_test ? sandbox::SBOX_TEST_SUCCEEDED : sandbox::SBOX_TEST_FAILED), @@ -89,7 +89,7 @@ void TestWin10ImageLoadLowLabel(bool is_success_test) { // Test file will be cleaned up by the ScopedTempDir. ASSERT_TRUE(base::CopyFileW(orig_path, new_path)); - base::string16 cmd_line = L"icacls \""; + std::wstring cmd_line = L"icacls \""; cmd_line += new_path.value().c_str(); cmd_line += L"\" /setintegritylevel Low"; @@ -123,7 +123,7 @@ void TestWin10ImageLoadLowLabel(bool is_success_test) { sandbox::SBOX_ALL_OK); } - base::string16 test = L"TestChildProcess \""; + std::wstring test = L"TestChildProcess \""; test += new_path.value().c_str(); test += L"\" false"; @@ -194,7 +194,7 @@ void TestWin10ImageLoadPreferSys32(bool baseline_test, bool expect_sys32_path) { // hijack was successful so the hijack_dll is NOT in system32. // The failure case has the mitigation enabled, so expect the hijack_dll to be // in system32. - base::string16 test = base::StringPrintf( + std::wstring test = base::StringPrintf( L"%ls %ls \"%ls\"", L"TestImageLoadHijack", (!expect_sys32_path) ? L"true" : L"false", shim_dll_path.value().c_str()); @@ -268,7 +268,7 @@ TEST(ProcessMitigationsTest, CheckWin10ImageLoadNoRemotePolicySuccess) { if (base::win::GetVersion() < base::win::Version::WIN10_TH2) return; - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(TESTPOLICY_LOADNOREMOTE); //--------------------------------- @@ -329,7 +329,7 @@ TEST(ProcessMitigationsTest, CheckWin10ImageLoadNoLowLabelPolicySuccess) { if (base::win::GetVersion() < base::win::Version::WIN10_TH2) return; - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(TESTPOLICY_LOADNOLOW); //--------------------------------- @@ -384,7 +384,7 @@ TEST(ProcessMitigationsTest, CheckWin10ImageLoadPreferSys32PolicySuccess) { if (base::win::GetVersion() < base::win::Version::WIN10_RS1) return; - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(TESTPOLICY_LOADPREFERSYS32); //--------------------------------- diff --git a/chromium/sandbox/win/src/process_mitigations_unittest.cc b/chromium/sandbox/win/src/process_mitigations_unittest.cc index a4d404db582..abfb669bdbe 100644 --- a/chromium/sandbox/win/src/process_mitigations_unittest.cc +++ b/chromium/sandbox/win/src/process_mitigations_unittest.cc @@ -62,7 +62,7 @@ void TestWin10NonSystemFont(bool is_success_test) { sandbox::SBOX_ALL_OK); } - base::string16 test_command = L"CheckWin10FontLoad \""; + std::wstring test_command = L"CheckWin10FontLoad \""; test_command += font_path.value().c_str(); test_command += L"\""; @@ -131,7 +131,7 @@ void TestWin10MsSigned(int expected, EXPECT_TRUE(runner.AddFsRule(sandbox::TargetPolicy::FILES_ALLOW_READONLY, dll_path.value().c_str())); // Set up test string. - base::string16 test = L"TestDllLoad \""; + std::wstring test = L"TestDllLoad \""; test += dll_path.value().c_str(); test += L"\""; @@ -425,7 +425,7 @@ SBOX_TESTS_COMMAND int TestDllLoad(int argc, wchar_t** argv) { if (argc < 1 || !argv[0]) return SBOX_TEST_INVALID_PARAMETER; - base::string16 dll = argv[0]; + std::wstring dll = argv[0]; base::ScopedNativeLibrary test_dll((base::FilePath(dll))); if (test_dll.is_valid()) return SBOX_TEST_SUCCEEDED; @@ -512,7 +512,7 @@ SBOX_TESTS_COMMAND int TestChildProcess(int argc, wchar_t** argv) { return SBOX_TEST_INVALID_PARAMETER; bool process_finishes = true; - base::string16 arg2 = argv[1]; + std::wstring arg2 = argv[1]; if (arg2.compare(L"false") == 0) process_finishes = false; @@ -521,7 +521,7 @@ SBOX_TESTS_COMMAND int TestChildProcess(int argc, wchar_t** argv) { desired_exit_code = wcstoul(argv[2], nullptr, 0); } - base::string16 cmd = argv[0]; + std::wstring cmd = argv[0]; base::LaunchOptions options = base::LaunchOptionsForTest(); base::Process setup_proc = base::LaunchProcess(cmd.c_str(), options); @@ -589,7 +589,7 @@ TEST(ProcessMitigationsTest, CheckDepWin8PolicySuccess) { if (base::win::GetVersion() < base::win::Version::WIN8) return; - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(TESTPOLICY_DEP); //--------------------------------- @@ -630,7 +630,7 @@ TEST(ProcessMitigationsTest, CheckWin8AslrPolicySuccess) { if (base::win::GetVersion() < base::win::Version::WIN8) return; - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(TESTPOLICY_ASLR); //--------------------------------------------- @@ -658,7 +658,7 @@ TEST(ProcessMitigationsTest, CheckWin8StrictHandlePolicySuccess) { if (base::win::GetVersion() < base::win::Version::WIN8) return; - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(TESTPOLICY_STRICTHANDLE); //--------------------------------- @@ -685,7 +685,7 @@ TEST(ProcessMitigationsTest, CheckWin10NonSystemFontLockDownPolicySuccess) { if (base::win::GetVersion() < base::win::Version::WIN10) return; - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(TESTPOLICY_NONSYSFONT); //--------------------------------- @@ -742,7 +742,7 @@ TEST(ProcessMitigationsTest, CheckWin10MsSignedPolicySuccessDelayed) { if (base::win::GetVersion() < base::win::Version::WIN10_TH2) return; - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(TESTPOLICY_MSSIGNED); //--------------------------------- @@ -769,7 +769,7 @@ TEST(ProcessMitigationsTest, CheckWin10MsSignedPolicySuccess) { if (base::win::GetVersion() < base::win::Version::WIN10_TH2) return; - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(TESTPOLICY_MSSIGNED); //--------------------------------- @@ -960,7 +960,7 @@ TEST(ProcessMitigationsTest, CheckChildProcessSuccess) { EXPECT_TRUE(base::PathService::Get(base::DIR_SYSTEM, &cmd)); cmd = cmd.Append(L"calc.exe"); - base::string16 test_command = L"TestChildProcess \""; + std::wstring test_command = L"TestChildProcess \""; test_command += cmd.value().c_str(); test_command += L"\" false"; @@ -984,7 +984,7 @@ TEST(ProcessMitigationsTest, CheckChildProcessFailure) { EXPECT_TRUE(base::PathService::Get(base::DIR_SYSTEM, &cmd)); cmd = cmd.Append(L"calc.exe"); - base::string16 test_command = L"TestChildProcess \""; + std::wstring test_command = L"TestChildProcess \""; test_command += cmd.value().c_str(); test_command += L"\" false"; @@ -1010,7 +1010,7 @@ TEST(ProcessMitigationsTest, CheckChildProcessAbnormalExit) { EXPECT_TRUE(base::PathService::Get(base::DIR_SYSTEM, &cmd)); cmd = cmd.Append(L"calc.exe"); - base::string16 test_command = L"TestChildProcess \""; + std::wstring test_command = L"TestChildProcess \""; test_command += cmd.value().c_str(); test_command += L"\" false "; test_command += std::to_wstring(STATUS_ACCESS_VIOLATION); @@ -1032,7 +1032,7 @@ TEST(ProcessMitigationsTest, if (base::win::GetVersion() < base::win::Version::WIN10_RS3) return; - base::string16 test_command = L"CheckPolicy "; + std::wstring test_command = L"CheckPolicy "; test_command += std::to_wstring(TESTPOLICY_RESTRICTINDIRECTBRANCHPREDICTION); //--------------------------------- diff --git a/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.cc b/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.cc index 485c36d0ed1..4d2d94b865e 100644 --- a/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.cc +++ b/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.cc @@ -5,10 +5,10 @@ #include "sandbox/win/src/process_mitigations_win32k_dispatcher.h" #include <algorithm> +#include <string> #include "base/memory/platform_shared_memory_region.h" #include "base/memory/unsafe_shared_memory_region.h" -#include "base/strings/string16.h" #include "base/unguessable_token.h" #include "base/win/windows_version.h" #include "sandbox/win/src/interception.h" @@ -70,51 +70,51 @@ ProcessMitigationsWin32KDispatcher::ProcessMitigationsWin32KDispatcher( PolicyBase* policy_base) : policy_base_(policy_base) { static const IPCCall enum_display_monitors_params = { - {IPC_USER_ENUMDISPLAYMONITORS_TAG, {INOUTPTR_TYPE}}, + {IpcTag::USER_ENUMDISPLAYMONITORS, {INOUTPTR_TYPE}}, reinterpret_cast<CallbackGeneric>( &ProcessMitigationsWin32KDispatcher::EnumDisplayMonitors)}; static const IPCCall get_monitor_info_params = { - {IPC_USER_GETMONITORINFO_TAG, {VOIDPTR_TYPE, INOUTPTR_TYPE}}, + {IpcTag::USER_GETMONITORINFO, {VOIDPTR_TYPE, INOUTPTR_TYPE}}, reinterpret_cast<CallbackGeneric>( &ProcessMitigationsWin32KDispatcher::GetMonitorInfo)}; static const IPCCall get_suggested_output_size_params = { - {IPC_GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE_TAG, {WCHAR_TYPE}}, + {IpcTag::GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE, {WCHAR_TYPE}}, reinterpret_cast<CallbackGeneric>( &ProcessMitigationsWin32KDispatcher:: GetSuggestedOPMProtectedOutputArraySize)}; static const IPCCall create_protected_outputs_params = { - {IPC_GDI_CREATEOPMPROTECTEDOUTPUTS_TAG, {WCHAR_TYPE, INOUTPTR_TYPE}}, + {IpcTag::GDI_CREATEOPMPROTECTEDOUTPUTS, {WCHAR_TYPE, INOUTPTR_TYPE}}, reinterpret_cast<CallbackGeneric>( &ProcessMitigationsWin32KDispatcher::CreateOPMProtectedOutputs)}; static const IPCCall get_cert_size_params = { - {IPC_GDI_GETCERTIFICATESIZE_TAG, {WCHAR_TYPE, VOIDPTR_TYPE}}, + {IpcTag::GDI_GETCERTIFICATESIZE, {WCHAR_TYPE, VOIDPTR_TYPE}}, reinterpret_cast<CallbackGeneric>( &ProcessMitigationsWin32KDispatcher::GetCertificateSize)}; static const IPCCall get_cert_params = { - {IPC_GDI_GETCERTIFICATE_TAG, + {IpcTag::GDI_GETCERTIFICATE, {WCHAR_TYPE, VOIDPTR_TYPE, VOIDPTR_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>( &ProcessMitigationsWin32KDispatcher::GetCertificate)}; static const IPCCall destroy_protected_output_params = { - {IPC_GDI_DESTROYOPMPROTECTEDOUTPUT_TAG, {VOIDPTR_TYPE}}, + {IpcTag::GDI_DESTROYOPMPROTECTEDOUTPUT, {VOIDPTR_TYPE}}, reinterpret_cast<CallbackGeneric>( &ProcessMitigationsWin32KDispatcher::DestroyOPMProtectedOutput)}; static const IPCCall get_random_number_params = { - {IPC_GDI_GETOPMRANDOMNUMBER_TAG, {VOIDPTR_TYPE, INOUTPTR_TYPE}}, + {IpcTag::GDI_GETOPMRANDOMNUMBER, {VOIDPTR_TYPE, INOUTPTR_TYPE}}, reinterpret_cast<CallbackGeneric>( &ProcessMitigationsWin32KDispatcher::GetOPMRandomNumber)}; static const IPCCall set_signing_key_params = { - {IPC_GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS_TAG, + {IpcTag::GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS, {VOIDPTR_TYPE, INOUTPTR_TYPE}}, reinterpret_cast<CallbackGeneric>( &ProcessMitigationsWin32KDispatcher:: SetOPMSigningKeyAndSequenceNumbers)}; static const IPCCall configure_protected_output_params = { - {IPC_GDI_CONFIGUREOPMPROTECTEDOUTPUT_TAG, {VOIDPTR_TYPE, VOIDPTR_TYPE}}, + {IpcTag::GDI_CONFIGUREOPMPROTECTEDOUTPUT, {VOIDPTR_TYPE, VOIDPTR_TYPE}}, reinterpret_cast<CallbackGeneric>( &ProcessMitigationsWin32KDispatcher::ConfigureOPMProtectedOutput)}; static const IPCCall get_information_params = { - {IPC_GDI_GETOPMINFORMATION_TAG, {VOIDPTR_TYPE, VOIDPTR_TYPE}}, + {IpcTag::GDI_GETOPMINFORMATION, {VOIDPTR_TYPE, VOIDPTR_TYPE}}, reinterpret_cast<CallbackGeneric>( &ProcessMitigationsWin32KDispatcher::GetOPMInformation)}; @@ -135,14 +135,14 @@ ProcessMitigationsWin32KDispatcher::~ProcessMitigationsWin32KDispatcher() {} bool ProcessMitigationsWin32KDispatcher::SetupService( InterceptionManager* manager, - int service) { + IpcTag service) { if (!(policy_base_->GetProcessMitigations() & sandbox::MITIGATION_WIN32K_DISABLE)) { return false; } switch (service) { - case IPC_GDI_GDIDLLINITIALIZE_TAG: { + case IpcTag::GDI_GDIDLLINITIALIZE: { if (!INTERCEPT_EAT(manager, L"gdi32.dll", GdiDllInitialize, GDIINITIALIZE_ID, 12)) { return false; @@ -150,7 +150,7 @@ bool ProcessMitigationsWin32KDispatcher::SetupService( return true; } - case IPC_GDI_GETSTOCKOBJECT_TAG: { + case IpcTag::GDI_GETSTOCKOBJECT: { if (!INTERCEPT_EAT(manager, L"gdi32.dll", GetStockObject, GETSTOCKOBJECT_ID, 8)) { return false; @@ -158,7 +158,7 @@ bool ProcessMitigationsWin32KDispatcher::SetupService( return true; } - case IPC_USER_REGISTERCLASSW_TAG: { + case IpcTag::USER_REGISTERCLASSW: { if (!INTERCEPT_EAT(manager, L"user32.dll", RegisterClassW, REGISTERCLASSW_ID, 8)) { return false; @@ -166,7 +166,7 @@ bool ProcessMitigationsWin32KDispatcher::SetupService( return true; } - case IPC_USER_ENUMDISPLAYMONITORS_TAG: { + case IpcTag::USER_ENUMDISPLAYMONITORS: { if (!INTERCEPT_EAT(manager, L"user32.dll", EnumDisplayMonitors, ENUMDISPLAYMONITORS_ID, 20)) { return false; @@ -174,7 +174,7 @@ bool ProcessMitigationsWin32KDispatcher::SetupService( return true; } - case IPC_USER_ENUMDISPLAYDEVICES_TAG: { + case IpcTag::USER_ENUMDISPLAYDEVICES: { if (!INTERCEPT_EAT(manager, L"user32.dll", EnumDisplayDevicesA, ENUMDISPLAYDEVICESA_ID, 20)) { return false; @@ -182,7 +182,7 @@ bool ProcessMitigationsWin32KDispatcher::SetupService( return true; } - case IPC_USER_GETMONITORINFO_TAG: { + case IpcTag::USER_GETMONITORINFO: { if (!INTERCEPT_EAT(manager, L"user32.dll", GetMonitorInfoA, GETMONITORINFOA_ID, 12)) { return false; @@ -195,14 +195,14 @@ bool ProcessMitigationsWin32KDispatcher::SetupService( return true; } - case IPC_GDI_CREATEOPMPROTECTEDOUTPUTS_TAG: + case IpcTag::GDI_CREATEOPMPROTECTEDOUTPUTS: if (!INTERCEPT_EAT(manager, L"gdi32.dll", CreateOPMProtectedOutputs, CREATEOPMPROTECTEDOUTPUTS_ID, 24)) { return false; } return true; - case IPC_GDI_GETCERTIFICATE_TAG: + case IpcTag::GDI_GETCERTIFICATE: if (!INTERCEPT_EAT(manager, L"gdi32.dll", GetCertificate, GETCERTIFICATE_ID, 20)) { return false; @@ -215,7 +215,7 @@ bool ProcessMitigationsWin32KDispatcher::SetupService( } return true; - case IPC_GDI_GETCERTIFICATESIZE_TAG: + case IpcTag::GDI_GETCERTIFICATESIZE: if (!INTERCEPT_EAT(manager, L"gdi32.dll", GetCertificateSize, GETCERTIFICATESIZE_ID, 16)) { return false; @@ -228,35 +228,35 @@ bool ProcessMitigationsWin32KDispatcher::SetupService( } return true; - case IPC_GDI_DESTROYOPMPROTECTEDOUTPUT_TAG: + case IpcTag::GDI_DESTROYOPMPROTECTEDOUTPUT: if (!INTERCEPT_EAT(manager, L"gdi32.dll", DestroyOPMProtectedOutput, DESTROYOPMPROTECTEDOUTPUT_ID, 8)) { return false; } return true; - case IPC_GDI_CONFIGUREOPMPROTECTEDOUTPUT_TAG: + case IpcTag::GDI_CONFIGUREOPMPROTECTEDOUTPUT: if (!INTERCEPT_EAT(manager, L"gdi32.dll", ConfigureOPMProtectedOutput, CONFIGUREOPMPROTECTEDOUTPUT_ID, 20)) { return false; } return true; - case IPC_GDI_GETOPMINFORMATION_TAG: + case IpcTag::GDI_GETOPMINFORMATION: if (!INTERCEPT_EAT(manager, L"gdi32.dll", GetOPMInformation, GETOPMINFORMATION_ID, 16)) { return false; } return true; - case IPC_GDI_GETOPMRANDOMNUMBER_TAG: + case IpcTag::GDI_GETOPMRANDOMNUMBER: if (!INTERCEPT_EAT(manager, L"gdi32.dll", GetOPMRandomNumber, GETOPMRANDOMNUMBER_ID, 12)) { return false; } return true; - case IPC_GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE_TAG: + case IpcTag::GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE: if (!INTERCEPT_EAT(manager, L"gdi32.dll", GetSuggestedOPMProtectedOutputArraySize, GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE_ID, 12)) { @@ -264,7 +264,7 @@ bool ProcessMitigationsWin32KDispatcher::SetupService( } return true; - case IPC_GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS_TAG: + case IpcTag::GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS: if (!INTERCEPT_EAT(manager, L"gdi32.dll", SetOPMSigningKeyAndSequenceNumbers, SETOPMSIGNINGKEYANDSEQUENCENUMBERS_ID, 12)) { @@ -333,7 +333,7 @@ bool ProcessMitigationsWin32KDispatcher::GetMonitorInfo(IPCInfo* ipc, bool ProcessMitigationsWin32KDispatcher:: GetSuggestedOPMProtectedOutputArraySize(IPCInfo* ipc, - base::string16* device_name) { + std::wstring* device_name) { if (!policy_base_->GetEnableOPMRedirection()) { ipc->return_info.nt_status = STATUS_ACCESS_DENIED; return true; @@ -351,7 +351,7 @@ bool ProcessMitigationsWin32KDispatcher:: bool ProcessMitigationsWin32KDispatcher::CreateOPMProtectedOutputs( IPCInfo* ipc, - base::string16* device_name, + std::wstring* device_name, CountedBuffer* protected_outputs) { if (!policy_base_->GetEnableOPMRedirection()) { ipc->return_info.nt_status = STATUS_ACCESS_DENIED; @@ -380,7 +380,7 @@ bool ProcessMitigationsWin32KDispatcher::CreateOPMProtectedOutputs( bool ProcessMitigationsWin32KDispatcher::GetCertificateSize( IPCInfo* ipc, - base::string16* device_name, + std::wstring* device_name, void* protected_output) { if (!policy_base_->GetEnableOPMRedirection()) { ipc->return_info.nt_status = STATUS_ACCESS_DENIED; @@ -410,7 +410,7 @@ bool ProcessMitigationsWin32KDispatcher::GetCertificateSize( bool ProcessMitigationsWin32KDispatcher::GetCertificate( IPCInfo* ipc, - base::string16* device_name, + std::wstring* device_name, void* protected_output, void* shared_buffer_handle, uint32_t shared_buffer_size) { diff --git a/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.h b/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.h index 9408d1c5ac0..0714191fcfe 100644 --- a/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.h +++ b/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.h @@ -6,11 +6,13 @@ #define SANDBOX_SRC_PROCESS_MITIGATIONS_WIN32K_DISPATCHER_H_ #include <map> +#include <string> #include "base/macros.h" #include "base/memory/ref_counted.h" -#include "base/strings/string16.h" #include "base/synchronization/lock.h" +#include "sandbox/win/src/crosscall_server.h" +#include "sandbox/win/src/ipc_tags.h" #include "sandbox/win/src/sandbox_policy_base.h" namespace sandbox { @@ -39,20 +41,20 @@ class ProcessMitigationsWin32KDispatcher : public Dispatcher { ~ProcessMitigationsWin32KDispatcher() override; // Dispatcher interface. - bool SetupService(InterceptionManager* manager, int service) override; + bool SetupService(InterceptionManager* manager, IpcTag service) override; bool EnumDisplayMonitors(IPCInfo* ipc, CountedBuffer* buffer); bool GetMonitorInfo(IPCInfo* ipc, void* monitor, CountedBuffer* buffer); bool GetSuggestedOPMProtectedOutputArraySize(IPCInfo* ipc, - base::string16* device_name); + std::wstring* device_name); bool CreateOPMProtectedOutputs(IPCInfo* ipc, - base::string16* device_name, + std::wstring* device_name, CountedBuffer* protected_outputs); bool GetCertificateSize(IPCInfo* ipc, - base::string16* device_name, + std::wstring* device_name, void* protected_output); bool GetCertificate(IPCInfo* ipc, - base::string16* device_name, + std::wstring* device_name, void* protected_output, void* shared_buffer_handle, uint32_t shared_buffer_size); diff --git a/chromium/sandbox/win/src/process_mitigations_win32k_interception.cc b/chromium/sandbox/win/src/process_mitigations_win32k_interception.cc index ac3522d1364..1a16d85adfc 100644 --- a/chromium/sandbox/win/src/process_mitigations_win32k_interception.cc +++ b/chromium/sandbox/win/src/process_mitigations_win32k_interception.cc @@ -49,8 +49,8 @@ class ScopedSharedMemory { }; void UnicodeStringToString(PUNICODE_STRING unicode_string, - base::string16* result) { - *result = base::string16( + std::wstring* result) { + *result = std::wstring( unicode_string->Buffer, unicode_string->Buffer + (unicode_string->Length / sizeof(unicode_string->Buffer[0]))); @@ -68,7 +68,7 @@ bool CallMonitorInfo(HMONITOR monitor, MONITORINFOEXW* monitor_info_ptr) { CrossCallReturn answer = {}; SharedMemIPCClient ipc(ipc_memory); InOutCountedBuffer buffer(monitor_info_ptr, sizeof(*monitor_info_ptr)); - ResultCode code = CrossCall(ipc, IPC_USER_GETMONITORINFO_TAG, + ResultCode code = CrossCall(ipc, IpcTag::USER_GETMONITORINFO, static_cast<void*>(monitor), buffer, &answer); if (code != SBOX_ALL_OK) @@ -123,7 +123,7 @@ BOOL WINAPI TargetEnumDisplayMonitors(EnumDisplayMonitorsFunction, InOutCountedBuffer result_buffer(&result, sizeof(result)); SharedMemIPCClient ipc(ipc_memory); ResultCode code = - CrossCall(ipc, IPC_USER_ENUMDISPLAYMONITORS_TAG, result_buffer, &answer); + CrossCall(ipc, IpcTag::USER_ENUMDISPLAYMONITORS, result_buffer, &answer); if (code != SBOX_ALL_OK) return false; @@ -218,7 +218,7 @@ static NTSTATUS GetCertificateCommon( ScopedSharedMemory buffer(certificate_size); if (!buffer.IsValid()) return STATUS_INVALID_PARAMETER; - base::string16 device_name_str; + std::wstring device_name_str; void* protected_output_handle = nullptr; if (device_name) { if (device_name->Length == 0) @@ -230,7 +230,7 @@ static NTSTATUS GetCertificateCommon( CrossCallReturn answer = {}; SharedMemIPCClient ipc(ipc_memory); ResultCode code = - CrossCall(ipc, IPC_GDI_GETCERTIFICATE_TAG, device_name_str.c_str(), + CrossCall(ipc, IpcTag::GDI_GETCERTIFICATE, device_name_str.c_str(), protected_output_handle, buffer.handle(), static_cast<uint32_t>(certificate_size), &answer); @@ -270,7 +270,7 @@ static NTSTATUS GetCertificateSizeCommon( CrossCallReturn answer = {}; SharedMemIPCClient ipc(ipc_memory); - base::string16 device_name_str; + std::wstring device_name_str; void* protected_output_handle = nullptr; if (device_name) { UnicodeStringToString(device_name, &device_name_str); @@ -278,7 +278,7 @@ static NTSTATUS GetCertificateSizeCommon( protected_output_handle = protected_output; } ResultCode code = - CrossCall(ipc, IPC_GDI_GETCERTIFICATESIZE_TAG, device_name_str.c_str(), + CrossCall(ipc, IpcTag::GDI_GETCERTIFICATESIZE, device_name_str.c_str(), protected_output_handle, &answer); if (code != SBOX_ALL_OK) { @@ -330,7 +330,7 @@ TargetDestroyOPMProtectedOutput(DestroyOPMProtectedOutputFunction, CrossCallReturn answer = {}; SharedMemIPCClient ipc(ipc_memory); - ResultCode code = CrossCall(ipc, IPC_GDI_DESTROYOPMPROTECTEDOUTPUT_TAG, + ResultCode code = CrossCall(ipc, IpcTag::GDI_DESTROYOPMPROTECTEDOUTPUT, static_cast<void*>(protected_output), &answer); if (code != SBOX_ALL_OK) @@ -362,7 +362,7 @@ NTSTATUS WINAPI TargetConfigureOPMProtectedOutput( CrossCallReturn answer = {}; SharedMemIPCClient ipc(ipc_memory); ResultCode code = - CrossCall(ipc, IPC_GDI_CONFIGUREOPMPROTECTEDOUTPUT_TAG, + CrossCall(ipc, IpcTag::GDI_CONFIGUREOPMPROTECTEDOUTPUT, static_cast<void*>(protected_output), buffer.handle(), &answer); if (code != SBOX_ALL_OK) { @@ -393,7 +393,7 @@ NTSTATUS WINAPI TargetGetOPMInformation( CrossCallReturn answer = {}; SharedMemIPCClient ipc(ipc_memory); ResultCode code = - CrossCall(ipc, IPC_GDI_GETOPMINFORMATION_TAG, + CrossCall(ipc, IpcTag::GDI_GETOPMINFORMATION, static_cast<void*>(protected_output), buffer.handle(), &answer); if (code != SBOX_ALL_OK) @@ -421,7 +421,7 @@ TargetGetOPMRandomNumber(GetOPMRandomNumberFunction, SharedMemIPCClient ipc(ipc_memory); InOutCountedBuffer buffer(random_number, sizeof(*random_number)); ResultCode code = - CrossCall(ipc, IPC_GDI_GETOPMRANDOMNUMBER_TAG, + CrossCall(ipc, IpcTag::GDI_GETOPMRANDOMNUMBER, static_cast<void*>(protected_output), buffer, &answer); if (code != SBOX_ALL_OK) @@ -442,10 +442,10 @@ NTSTATUS WINAPI TargetGetSuggestedOPMProtectedOutputArraySize( CrossCallReturn answer = {}; SharedMemIPCClient ipc(ipc_memory); - base::string16 device_name_str; + std::wstring device_name_str; UnicodeStringToString(device_name, &device_name_str); ResultCode code = - CrossCall(ipc, IPC_GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE_TAG, + CrossCall(ipc, IpcTag::GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE, device_name_str.c_str(), &answer); if (code != SBOX_ALL_OK) @@ -473,7 +473,7 @@ NTSTATUS WINAPI TargetSetOPMSigningKeyAndSequenceNumbers( SharedMemIPCClient ipc(ipc_memory); InOutCountedBuffer buffer(&temp_parameters, sizeof(temp_parameters)); ResultCode code = - CrossCall(ipc, IPC_GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS_TAG, + CrossCall(ipc, IpcTag::GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS, static_cast<void*>(protected_output), buffer, &answer); if (code != SBOX_ALL_OK) @@ -506,9 +506,9 @@ TargetCreateOPMProtectedOutputs(CreateOPMProtectedOutputsFunction, return STATUS_INVALID_PARAMETER; InOutCountedBuffer buffer(outputs_array, array_size.ValueOrDie()); - base::string16 device_name_str; + std::wstring device_name_str; UnicodeStringToString(device_name, &device_name_str); - ResultCode code = CrossCall(ipc, IPC_GDI_CREATEOPMPROTECTEDOUTPUTS_TAG, + ResultCode code = CrossCall(ipc, IpcTag::GDI_CREATEOPMPROTECTEDOUTPUTS, device_name_str.c_str(), buffer, &answer); if (code != SBOX_ALL_OK) diff --git a/chromium/sandbox/win/src/process_mitigations_win32k_policy.cc b/chromium/sandbox/win/src/process_mitigations_win32k_policy.cc index 5649f1ba253..8ab915ec33c 100644 --- a/chromium/sandbox/win/src/process_mitigations_win32k_policy.cc +++ b/chromium/sandbox/win/src/process_mitigations_win32k_policy.cc @@ -40,7 +40,7 @@ const GUID DXGKMDT_OPM_SET_PROTECTION_LEVEL = { {0x9f, 0x00, 0xb4, 0x2b, 0x09, 0x19, 0xc0, 0xda}}; void StringToUnicodeString(PUNICODE_STRING unicode_string, - const base::string16& device_name) { + const std::wstring& device_name) { static RtlInitUnicodeStringFunction RtlInitUnicodeString; if (!RtlInitUnicodeString) { HMODULE ntdll = ::GetModuleHandle(kNtdllName); @@ -88,11 +88,11 @@ T GetExportedFunc(const wchar_t* libname, const char* name) { struct ValidateMonitorParams { HMONITOR monitor; - base::string16 device_name; + std::wstring device_name; bool result; }; -bool GetMonitorDeviceName(HMONITOR monitor, base::string16* device_name) { +bool GetMonitorDeviceName(HMONITOR monitor, std::wstring* device_name) { MONITORINFOEXW monitor_info = {}; monitor_info.cbSize = sizeof(monitor_info); if (!USERFUNC(GetMonitorInfoW)(monitor, &monitor_info)) @@ -109,7 +109,7 @@ BOOL CALLBACK ValidateMonitorEnumProc(HMONITOR monitor, LPARAM data) { ValidateMonitorParams* valid_params = reinterpret_cast<ValidateMonitorParams*>(data); - base::string16 device_name; + std::wstring device_name; bool result = false; if (valid_params->device_name.empty()) { result = monitor == valid_params->monitor; @@ -143,38 +143,38 @@ bool ProcessMitigationsWin32KLockdownPolicy::GenerateRules( TargetPolicy::Semantics semantics, LowLevelPolicy* policy) { PolicyRule rule(FAKE_SUCCESS); - if (!policy->AddRule(IPC_GDI_GDIDLLINITIALIZE_TAG, &rule)) + if (!policy->AddRule(IpcTag::GDI_GDIDLLINITIALIZE, &rule)) return false; - if (!policy->AddRule(IPC_GDI_GETSTOCKOBJECT_TAG, &rule)) + if (!policy->AddRule(IpcTag::GDI_GETSTOCKOBJECT, &rule)) return false; - if (!policy->AddRule(IPC_USER_REGISTERCLASSW_TAG, &rule)) + if (!policy->AddRule(IpcTag::USER_REGISTERCLASSW, &rule)) return false; if (semantics != TargetPolicy::IMPLEMENT_OPM_APIS) return true; - if (!policy->AddRule(IPC_USER_ENUMDISPLAYMONITORS_TAG, &rule)) + if (!policy->AddRule(IpcTag::USER_ENUMDISPLAYMONITORS, &rule)) return false; - if (!policy->AddRule(IPC_USER_ENUMDISPLAYDEVICES_TAG, &rule)) + if (!policy->AddRule(IpcTag::USER_ENUMDISPLAYDEVICES, &rule)) return false; - if (!policy->AddRule(IPC_USER_GETMONITORINFO_TAG, &rule)) + if (!policy->AddRule(IpcTag::USER_GETMONITORINFO, &rule)) return false; - if (!policy->AddRule(IPC_GDI_CREATEOPMPROTECTEDOUTPUTS_TAG, &rule)) + if (!policy->AddRule(IpcTag::GDI_CREATEOPMPROTECTEDOUTPUTS, &rule)) return false; - if (!policy->AddRule(IPC_GDI_GETCERTIFICATE_TAG, &rule)) + if (!policy->AddRule(IpcTag::GDI_GETCERTIFICATE, &rule)) return false; - if (!policy->AddRule(IPC_GDI_GETCERTIFICATESIZE_TAG, &rule)) + if (!policy->AddRule(IpcTag::GDI_GETCERTIFICATESIZE, &rule)) return false; - if (!policy->AddRule(IPC_GDI_DESTROYOPMPROTECTEDOUTPUT_TAG, &rule)) + if (!policy->AddRule(IpcTag::GDI_DESTROYOPMPROTECTEDOUTPUT, &rule)) return false; - if (!policy->AddRule(IPC_GDI_CONFIGUREOPMPROTECTEDOUTPUT_TAG, &rule)) + if (!policy->AddRule(IpcTag::GDI_CONFIGUREOPMPROTECTEDOUTPUT, &rule)) return false; - if (!policy->AddRule(IPC_GDI_GETOPMINFORMATION_TAG, &rule)) + if (!policy->AddRule(IpcTag::GDI_GETOPMINFORMATION, &rule)) return false; - if (!policy->AddRule(IPC_GDI_GETOPMRANDOMNUMBER_TAG, &rule)) + if (!policy->AddRule(IpcTag::GDI_GETOPMRANDOMNUMBER, &rule)) return false; - if (!policy->AddRule(IPC_GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE_TAG, + if (!policy->AddRule(IpcTag::GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE, &rule)) return false; - if (!policy->AddRule(IPC_GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS_TAG, &rule)) + if (!policy->AddRule(IpcTag::GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS, &rule)) return false; return true; } @@ -208,7 +208,7 @@ bool ProcessMitigationsWin32KLockdownPolicy::GetMonitorInfoAction( NTSTATUS ProcessMitigationsWin32KLockdownPolicy:: GetSuggestedOPMProtectedOutputArraySizeAction( const ClientInfo& client_info, - const base::string16& device_name, + const std::wstring& device_name, uint32_t* suggested_array_size) { if (!IsValidMonitorOrDeviceName(nullptr, device_name.c_str())) { return STATUS_ACCESS_DENIED; @@ -226,7 +226,7 @@ NTSTATUS ProcessMitigationsWin32KLockdownPolicy:: NTSTATUS ProcessMitigationsWin32KLockdownPolicy::CreateOPMProtectedOutputsAction( const ClientInfo& client_info, - const base::string16& device_name, + const std::wstring& device_name, HANDLE* protected_outputs, uint32_t array_input_size, uint32_t* array_output_size) { @@ -249,7 +249,7 @@ ProcessMitigationsWin32KLockdownPolicy::CreateOPMProtectedOutputsAction( NTSTATUS ProcessMitigationsWin32KLockdownPolicy::GetCertificateSizeAction( const ClientInfo& client_info, - const base::string16& device_name, + const std::wstring& device_name, uint32_t* cert_size) { if (!IsValidMonitorOrDeviceName(nullptr, device_name.c_str())) { return STATUS_ACCESS_DENIED; @@ -264,7 +264,7 @@ NTSTATUS ProcessMitigationsWin32KLockdownPolicy::GetCertificateSizeAction( NTSTATUS ProcessMitigationsWin32KLockdownPolicy::GetCertificateAction( const ClientInfo& client_info, - const base::string16& device_name, + const std::wstring& device_name, BYTE* cert_data, uint32_t cert_size) { if (!IsValidMonitorOrDeviceName(nullptr, device_name.c_str())) { diff --git a/chromium/sandbox/win/src/process_mitigations_win32k_policy.h b/chromium/sandbox/win/src/process_mitigations_win32k_policy.h index 5f94d6afe44..0c2b2dff953 100644 --- a/chromium/sandbox/win/src/process_mitigations_win32k_policy.h +++ b/chromium/sandbox/win/src/process_mitigations_win32k_policy.h @@ -5,7 +5,8 @@ #ifndef SANDBOX_SRC_PROCESS_MITIGATIONS_WIN32K_POLICY_H_ #define SANDBOX_SRC_PROCESS_MITIGATIONS_WIN32K_POLICY_H_ -#include "base/strings/string16.h" +#include <string> + #include "sandbox/win/src/crosscall_server.h" #include "sandbox/win/src/policy_low_level.h" #include "sandbox/win/src/sandbox_policy.h" @@ -37,21 +38,21 @@ class ProcessMitigationsWin32KLockdownPolicy { static NTSTATUS GetSuggestedOPMProtectedOutputArraySizeAction( const ClientInfo& client_info, - const base::string16& device_name, + const std::wstring& device_name, uint32_t* suggested_array_size); static NTSTATUS CreateOPMProtectedOutputsAction( const ClientInfo& client_info, - const base::string16& device_name, + const std::wstring& device_name, HANDLE* protected_outputs, uint32_t array_input_size, uint32_t* array_output_size); static NTSTATUS GetCertificateSizeAction(const ClientInfo& client_info, - const base::string16& device_name, + const std::wstring& device_name, uint32_t* cert_size); static NTSTATUS GetCertificateAction(const ClientInfo& client_info, - const base::string16& device_name, + const std::wstring& device_name, BYTE* cert_data, uint32_t cert_size); static NTSTATUS GetCertificateSizeByHandleAction( diff --git a/chromium/sandbox/win/src/process_mitigations_win32k_unittest.cc b/chromium/sandbox/win/src/process_mitigations_win32k_unittest.cc index 3cb8daf5bcb..489d815f70f 100644 --- a/chromium/sandbox/win/src/process_mitigations_win32k_unittest.cc +++ b/chromium/sandbox/win/src/process_mitigations_win32k_unittest.cc @@ -29,8 +29,8 @@ BOOL CALLBACK MonitorEnumCallback(HMONITOR monitor, HDC hdc_monitor, LPRECT rect_monitor, LPARAM data) { - std::map<HMONITOR, base::string16>& monitors = - *reinterpret_cast<std::map<HMONITOR, base::string16>*>(data); + std::map<HMONITOR, std::wstring>& monitors = + *reinterpret_cast<std::map<HMONITOR, std::wstring>*>(data); MONITORINFOEXW monitor_info = {}; monitor_info.cbSize = sizeof(monitor_info); @@ -41,8 +41,8 @@ BOOL CALLBACK MonitorEnumCallback(HMONITOR monitor, return true; } -std::map<HMONITOR, base::string16> EnumerateMonitors() { - std::map<HMONITOR, base::string16> result; +std::map<HMONITOR, std::wstring> EnumerateMonitors() { + std::map<HMONITOR, std::wstring> result; ::EnumDisplayMonitors(nullptr, nullptr, MonitorEnumCallback, reinterpret_cast<LPARAM>(&result)); return result; @@ -52,8 +52,8 @@ std::map<HMONITOR, base::string16> EnumerateMonitors() { result[reinterpret_cast<HMONITOR>(monitor)] = \ base::StringPrintf(L"\\\\.\\DISPLAY%X", monitor) -std::map<HMONITOR, base::string16> GetTestMonitors() { - std::map<HMONITOR, base::string16> result; +std::map<HMONITOR, std::wstring> GetTestMonitors() { + std::map<HMONITOR, std::wstring> result; HMONITOR_ENTRY(0x11111111); HMONITOR_ENTRY(0x22222222); @@ -62,15 +62,15 @@ std::map<HMONITOR, base::string16> GetTestMonitors() { return result; } -base::string16 UnicodeStringToString(PUNICODE_STRING name) { - return base::string16( - name->Buffer, name->Buffer + (name->Length / sizeof(name->Buffer[0]))); +std::wstring UnicodeStringToString(PUNICODE_STRING name) { + return std::wstring(name->Buffer, + name->Buffer + (name->Length / sizeof(name->Buffer[0]))); } // Returns an index 1, 2, 4 or 8 depening on the device. 0 on error. DWORD GetTestDeviceMonitorIndex(PUNICODE_STRING device_name) { - base::string16 name = UnicodeStringToString(device_name); - std::map<HMONITOR, base::string16> monitors = GetTestMonitors(); + std::wstring name = UnicodeStringToString(device_name); + std::map<HMONITOR, std::wstring> monitors = GetTestMonitors(); for (const auto& monitor : monitors) { if (name == monitor.second) return static_cast<DWORD>(reinterpret_cast<uintptr_t>(monitor.first)) & @@ -261,7 +261,7 @@ bool WINAPI EnumDisplayMonitorsTest(HDC hdc, } bool WINAPI GetMonitorInfoWTest(HMONITOR monitor, LPMONITORINFO monitor_info) { - std::map<HMONITOR, base::string16> monitors = GetTestMonitors(); + std::map<HMONITOR, std::wstring> monitors = GetTestMonitors(); if (monitor_info->cbSize != sizeof(MONITORINFO) && monitor_info->cbSize != sizeof(MONITORINFOEXW)) return false; @@ -523,8 +523,8 @@ namespace sandbox { //------------------------------------------------------------------------------ SBOX_TESTS_COMMAND int CheckWin8MonitorsRedirection(int argc, wchar_t** argv) { - std::map<HMONITOR, base::string16> monitors = EnumerateMonitors(); - std::map<HMONITOR, base::string16> monitors_to_test = GetTestMonitors(); + std::map<HMONITOR, std::wstring> monitors = EnumerateMonitors(); + std::map<HMONITOR, std::wstring> monitors_to_test = GetTestMonitors(); if (monitors.size() != monitors_to_test.size()) return SBOX_TEST_FIRST_ERROR; @@ -539,12 +539,12 @@ SBOX_TESTS_COMMAND int CheckWin8MonitorsRedirection(int argc, wchar_t** argv) { } SBOX_TESTS_COMMAND int CheckWin8MonitorInfo(int argc, wchar_t** argv) { - std::map<HMONITOR, base::string16> monitors_to_test = GetTestMonitors(); + std::map<HMONITOR, std::wstring> monitors_to_test = GetTestMonitors(); MONITORINFO monitor_info = {}; MONITORINFOEXW monitor_info_exw = {}; MONITORINFOEXA monitor_info_exa = {}; HMONITOR valid_monitor = monitors_to_test.begin()->first; - base::string16 valid_device = monitors_to_test.begin()->second; + std::wstring valid_device = monitors_to_test.begin()->second; monitor_info.cbSize = sizeof(MONITORINFO); if (!::GetMonitorInfoW(valid_monitor, &monitor_info)) return SBOX_TEST_FIRST_ERROR; @@ -560,7 +560,7 @@ SBOX_TESTS_COMMAND int CheckWin8MonitorInfo(int argc, wchar_t** argv) { monitor_info_exa.cbSize = sizeof(MONITORINFOEXA); if (!::GetMonitorInfoA(valid_monitor, reinterpret_cast<MONITORINFO*>(&monitor_info_exa)) || - valid_device != base::ASCIIToUTF16(monitor_info_exa.szDevice)) { + valid_device != base::UTF8ToWide(monitor_info_exa.szDevice)) { return SBOX_TEST_FOURTH_ERROR; } @@ -582,7 +582,7 @@ SBOX_TESTS_COMMAND int CheckWin8MonitorInfo(int argc, wchar_t** argv) { } SBOX_TESTS_COMMAND int CheckWin8OPMApis(int argc, wchar_t** argv) { - std::map<HMONITOR, base::string16> monitors = GetTestMonitors(); + std::map<HMONITOR, std::wstring> monitors = GetTestMonitors(); for (const auto& monitor : monitors) { ULONG output_count = 0; IOPMVideoOutput** outputs = nullptr; @@ -621,7 +621,7 @@ TEST(ProcessMitigationsWin32kTest, CheckWin8LockDownFailure) { if (base::win::GetVersion() < base::win::Version::WIN8) return; - base::string16 test_policy_command = L"CheckPolicy "; + std::wstring test_policy_command = L"CheckPolicy "; test_policy_command += std::to_wstring(TESTPOLICY_WIN32K); TestRunner runner; @@ -641,7 +641,7 @@ TEST(ProcessMitigationsWin32kTest, CheckWin8LockDownSuccess) { if (base::win::GetVersion() < base::win::Version::WIN8) return; - base::string16 test_policy_command = L"CheckPolicy "; + std::wstring test_policy_command = L"CheckPolicy "; test_policy_command += std::to_wstring(TESTPOLICY_WIN32K); TestRunner runner; @@ -668,7 +668,7 @@ TEST(ProcessMitigationsWin32kTest, CheckWin8Redirection) { if (base::win::GetVersion() < base::win::Version::WIN8) return; - base::string16 test_policy_command = L"CheckPolicy "; + std::wstring test_policy_command = L"CheckPolicy "; test_policy_command += std::to_wstring(TESTPOLICY_WIN32K); TestRunner runner; diff --git a/chromium/sandbox/win/src/process_policy_test.cc b/chromium/sandbox/win/src/process_policy_test.cc index 8d5dcbe3fbe..c321c3a0886 100644 --- a/chromium/sandbox/win/src/process_policy_test.cc +++ b/chromium/sandbox/win/src/process_policy_test.cc @@ -6,7 +6,6 @@ #include <string> #include "base/memory/free_deleter.h" -#include "base/strings/string16.h" #include "base/strings/sys_string_conversions.h" #include "base/win/scoped_handle.h" #include "base/win/scoped_process_information.h" @@ -23,8 +22,8 @@ namespace { // Creates a process with the |exe| and |command| parameter using the // unicode and ascii version of the api. -sandbox::SboxTestResult CreateProcessHelper(const base::string16& exe, - const base::string16& command) { +sandbox::SboxTestResult CreateProcessHelper(const std::wstring& exe, + const std::wstring& command) { base::win::ScopedProcessInformation pi; STARTUPINFOW si = {sizeof(si)}; const wchar_t* exe_name = nullptr; @@ -94,10 +93,10 @@ SBOX_TESTS_COMMAND int Process_RunApp1(int argc, wchar_t** argv) { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; if (!argv || !argv[0]) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; - base::string16 path = MakePathToSys(argv[0], false); + std::wstring path = MakePathToSys(argv[0], false); // TEST 1: Try with the path in the app_name. - return CreateProcessHelper(path, base::string16()); + return CreateProcessHelper(path, std::wstring()); } SBOX_TESTS_COMMAND int Process_RunApp2(int argc, wchar_t** argv) { @@ -105,13 +104,13 @@ SBOX_TESTS_COMMAND int Process_RunApp2(int argc, wchar_t** argv) { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; if (!argv || !argv[0]) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; - base::string16 path = MakePathToSys(argv[0], false); + std::wstring path = MakePathToSys(argv[0], false); // TEST 2: Try with the path in the cmd_line. - base::string16 cmd_line = L"\""; + std::wstring cmd_line = L"\""; cmd_line += path; cmd_line += L"\""; - return CreateProcessHelper(base::string16(), cmd_line); + return CreateProcessHelper(std::wstring(), cmd_line); } SBOX_TESTS_COMMAND int Process_RunApp3(int argc, wchar_t** argv) { @@ -120,7 +119,7 @@ SBOX_TESTS_COMMAND int Process_RunApp3(int argc, wchar_t** argv) { if (!argv || !argv[0]) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; // TEST 3: Try file name in the cmd_line. - return CreateProcessHelper(base::string16(), argv[0]); + return CreateProcessHelper(std::wstring(), argv[0]); } SBOX_TESTS_COMMAND int Process_RunApp4(int argc, wchar_t** argv) { @@ -130,7 +129,7 @@ SBOX_TESTS_COMMAND int Process_RunApp4(int argc, wchar_t** argv) { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; // TEST 4: Try file name in the app_name and current directory sets correctly. - base::string16 system32 = MakePathToSys(L"", false); + std::wstring system32 = MakePathToSys(L"", false); wchar_t current_directory[MAX_PATH + 1]; DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory); if (!ret) @@ -143,7 +142,7 @@ SBOX_TESTS_COMMAND int Process_RunApp4(int argc, wchar_t** argv) { if (!::SetCurrentDirectory(system32.c_str())) return SBOX_TEST_SECOND_ERROR; - const int result4 = CreateProcessHelper(argv[0], base::string16()); + const int result4 = CreateProcessHelper(argv[0], std::wstring()); return ::SetCurrentDirectory(current_directory) ? result4 : SBOX_TEST_FAILED; } @@ -152,13 +151,13 @@ SBOX_TESTS_COMMAND int Process_RunApp5(int argc, wchar_t** argv) { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; if (!argv || !argv[0]) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; - base::string16 path = MakePathToSys(argv[0], false); + std::wstring path = MakePathToSys(argv[0], false); // TEST 5: Try with the path in the cmd_line and arguments. - base::string16 cmd_line = L"\""; + std::wstring cmd_line = L"\""; cmd_line += path; cmd_line += L"\" /I"; - return CreateProcessHelper(base::string16(), cmd_line); + return CreateProcessHelper(std::wstring(), cmd_line); } SBOX_TESTS_COMMAND int Process_RunApp6(int argc, wchar_t** argv) { @@ -168,9 +167,9 @@ SBOX_TESTS_COMMAND int Process_RunApp6(int argc, wchar_t** argv) { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; // TEST 6: Try with the file_name in the cmd_line and arguments. - base::string16 cmd_line = argv[0]; + std::wstring cmd_line = argv[0]; cmd_line += L" /I"; - return CreateProcessHelper(base::string16(), cmd_line); + return CreateProcessHelper(std::wstring(), cmd_line); } // Creates a process and checks if it's possible to get a handle to it's token. @@ -181,7 +180,7 @@ SBOX_TESTS_COMMAND int Process_GetChildProcessToken(int argc, wchar_t** argv) { if (!argv || !argv[0]) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; - base::string16 path = MakePathToSys(argv[0], false); + std::wstring path = MakePathToSys(argv[0], false); STARTUPINFOW si = {sizeof(si)}; @@ -222,7 +221,7 @@ SBOX_TESTS_COMMAND int Process_CreateProcessA(int argc, wchar_t** argv) { STARTUPINFOA si = {sizeof(si)}; - base::string16 path = MakePathToSys(argv[0], false); + std::wstring path = MakePathToSys(argv[0], false); PROCESS_INFORMATION temp_process_info = {}; // Create suspended to avoid popping calc. @@ -323,9 +322,9 @@ SBOX_TESTS_COMMAND int Process_CheckExitCode(int argc, wchar_t** argv) { if (!argv || !argv[0] || !argv[1] || !argv[2]) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; - base::string16 path = MakePathToSys(argv[0], false); - base::string16 cmdline = argv[1]; - base::string16 cwd = argv[2]; + std::wstring path = MakePathToSys(argv[0], false); + std::wstring cmdline = argv[1]; + std::wstring cwd = argv[2]; STARTUPINFOW si = {sizeof(si)}; @@ -372,8 +371,8 @@ TEST(ProcessPolicyTest, TestAllAccess) { TEST(ProcessPolicyTest, CreateProcessAW) { TestRunner runner; - base::string16 maybe_virtual_exe_path = MakePathToSys(L"findstr.exe", false); - base::string16 non_virtual_exe_path = MakePathToSys32(L"findstr.exe", false); + std::wstring maybe_virtual_exe_path = MakePathToSys(L"findstr.exe", false); + std::wstring non_virtual_exe_path = MakePathToSys32(L"findstr.exe", false); ASSERT_TRUE(!maybe_virtual_exe_path.empty()); EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS, @@ -434,19 +433,19 @@ TEST(ProcessPolicyTest, MAYBE_CreateProcessCrashy) { TEST(ProcessPolicyTest, CreateProcessWithCWD) { TestRunner runner; - base::string16 sys_path = MakePathToSys(L"", false); + std::wstring sys_path = MakePathToSys(L"", false); while (!sys_path.empty() && sys_path.back() == L'\\') sys_path.erase(sys_path.length() - 1); - base::string16 exe_path = MakePathToSys(L"cmd.exe", false); - base::string16 cmd_line = + std::wstring exe_path = MakePathToSys(L"cmd.exe", false); + std::wstring cmd_line = L"\"/c if \\\"%CD%\\\" NEQ \\\"" + sys_path + L"\\\" exit 1\""; ASSERT_TRUE(!exe_path.empty()); EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS, TargetPolicy::PROCESS_MIN_EXEC, exe_path.c_str())); - base::string16 command = + std::wstring command = L"Process_CheckExitCode cmd.exe " + cmd_line + L" " + sys_path; EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(command.c_str())); } @@ -458,7 +457,7 @@ TEST(ProcessPolicyTest, OpenToken) { TEST(ProcessPolicyTest, TestGetProcessTokenMinAccess) { TestRunner runner; - base::string16 exe_path = MakePathToSys(L"findstr.exe", false); + std::wstring exe_path = MakePathToSys(L"findstr.exe", false); ASSERT_TRUE(!exe_path.empty()); EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS, TargetPolicy::PROCESS_MIN_EXEC, exe_path.c_str())); @@ -469,7 +468,7 @@ TEST(ProcessPolicyTest, TestGetProcessTokenMinAccess) { TEST(ProcessPolicyTest, TestGetProcessTokenMaxAccess) { TestRunner runner(JOB_UNPROTECTED, USER_INTERACTIVE, USER_INTERACTIVE); - base::string16 exe_path = MakePathToSys(L"findstr.exe", false); + std::wstring exe_path = MakePathToSys(L"findstr.exe", false); ASSERT_TRUE(!exe_path.empty()); EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS, TargetPolicy::PROCESS_ALL_EXEC, exe_path.c_str())); @@ -480,7 +479,7 @@ TEST(ProcessPolicyTest, TestGetProcessTokenMaxAccess) { TEST(ProcessPolicyTest, TestGetProcessTokenMinAccessNoJob) { TestRunner runner(JOB_NONE, USER_RESTRICTED_SAME_ACCESS, USER_LOCKDOWN); - base::string16 exe_path = MakePathToSys(L"findstr.exe", false); + std::wstring exe_path = MakePathToSys(L"findstr.exe", false); ASSERT_TRUE(!exe_path.empty()); EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS, TargetPolicy::PROCESS_MIN_EXEC, exe_path.c_str())); @@ -491,7 +490,7 @@ TEST(ProcessPolicyTest, TestGetProcessTokenMinAccessNoJob) { TEST(ProcessPolicyTest, TestGetProcessTokenMaxAccessNoJob) { TestRunner runner(JOB_NONE, USER_INTERACTIVE, USER_INTERACTIVE); - base::string16 exe_path = MakePathToSys(L"findstr.exe", false); + std::wstring exe_path = MakePathToSys(L"findstr.exe", false); ASSERT_TRUE(!exe_path.empty()); EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS, TargetPolicy::PROCESS_ALL_EXEC, exe_path.c_str())); @@ -505,7 +504,7 @@ TEST(ProcessPolicyTest, TestCreateProcessA) { sandbox::TargetPolicy* policy = runner.GetPolicy(); policy->SetJobLevel(JOB_NONE, 0); policy->SetTokenLevel(USER_UNPROTECTED, USER_UNPROTECTED); - base::string16 exe_path = MakePathToSys(L"calc.exe", false); + std::wstring exe_path = MakePathToSys(L"calc.exe", false); ASSERT_TRUE(!exe_path.empty()); EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS, TargetPolicy::PROCESS_ALL_EXEC, exe_path.c_str())); diff --git a/chromium/sandbox/win/src/process_thread_dispatcher.cc b/chromium/sandbox/win/src/process_thread_dispatcher.cc index 9d4db3325e9..7f0b0a6542b 100644 --- a/chromium/sandbox/win/src/process_thread_dispatcher.cc +++ b/chromium/sandbox/win/src/process_thread_dispatcher.cc @@ -31,20 +31,20 @@ namespace { // "c:\program files\test param" will first try to launch c:\program.exe then // c:\program files\test.exe. We don't do that, we stop after at the first // space when there is no quotes. -base::string16 GetPathFromCmdLine(const base::string16& cmd_line) { - base::string16 exe_name; +std::wstring GetPathFromCmdLine(const std::wstring& cmd_line) { + std::wstring exe_name; // Check if it starts with '"'. if (cmd_line[0] == L'\"') { // Find the position of the second '"', this terminates the path. - base::string16::size_type pos = cmd_line.find(L'\"', 1); - if (base::string16::npos == pos) + std::wstring::size_type pos = cmd_line.find(L'\"', 1); + if (std::wstring::npos == pos) return cmd_line; exe_name = cmd_line.substr(1, pos - 1); } else { // There is no '"', that means that the appname is terminated at the // first space. - base::string16::size_type pos = cmd_line.find(L' '); - if (base::string16::npos == pos) { + std::wstring::size_type pos = cmd_line.find(L' '); + if (std::wstring::npos == pos) { // There is no space, the cmd_line contains only the app_name exe_name = cmd_line; } else { @@ -57,7 +57,7 @@ base::string16 GetPathFromCmdLine(const base::string16& cmd_line) { // Returns true is the path in parameter is relative. False if it's // absolute. -bool IsPathRelative(const base::string16& path) { +bool IsPathRelative(const std::wstring& path) { // A path is Relative if it's not a UNC path beginnning with \\ or a // path beginning with a drive. (i.e. X:\) if (path.find(L"\\\\") == 0 || path.find(L":\\") == 1) @@ -66,9 +66,9 @@ bool IsPathRelative(const base::string16& path) { } // Converts a relative path to an absolute path. -bool ConvertToAbsolutePath(const base::string16& child_current_directory, +bool ConvertToAbsolutePath(const std::wstring& child_current_directory, bool use_env_path, - base::string16* path) { + std::wstring* path) { wchar_t file_buffer[MAX_PATH]; wchar_t* file_part = nullptr; @@ -100,27 +100,27 @@ namespace sandbox { ThreadProcessDispatcher::ThreadProcessDispatcher(PolicyBase* policy_base) : policy_base_(policy_base) { static const IPCCall open_thread = { - {IPC_NTOPENTHREAD_TAG, {UINT32_TYPE, UINT32_TYPE}}, + {IpcTag::NTOPENTHREAD, {UINT32_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>( &ThreadProcessDispatcher::NtOpenThread)}; static const IPCCall open_process = { - {IPC_NTOPENPROCESS_TAG, {UINT32_TYPE, UINT32_TYPE}}, + {IpcTag::NTOPENPROCESS, {UINT32_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>( &ThreadProcessDispatcher::NtOpenProcess)}; static const IPCCall process_token = { - {IPC_NTOPENPROCESSTOKEN_TAG, {VOIDPTR_TYPE, UINT32_TYPE}}, + {IpcTag::NTOPENPROCESSTOKEN, {VOIDPTR_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>( &ThreadProcessDispatcher::NtOpenProcessToken)}; static const IPCCall process_tokenex = { - {IPC_NTOPENPROCESSTOKENEX_TAG, {VOIDPTR_TYPE, UINT32_TYPE, UINT32_TYPE}}, + {IpcTag::NTOPENPROCESSTOKENEX, {VOIDPTR_TYPE, UINT32_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>( &ThreadProcessDispatcher::NtOpenProcessTokenEx)}; static const IPCCall create_params = { - {IPC_CREATEPROCESSW_TAG, + {IpcTag::CREATEPROCESSW, {WCHAR_TYPE, WCHAR_TYPE, WCHAR_TYPE, WCHAR_TYPE, INOUTPTR_TYPE}}, reinterpret_cast<CallbackGeneric>( &ThreadProcessDispatcher::CreateProcessW)}; @@ -130,7 +130,7 @@ ThreadProcessDispatcher::ThreadProcessDispatcher(PolicyBase* policy_base) static_assert(sizeof(size_t) == sizeof(void*), "VOIDPTR_TYPE not same size as size_t"); static const IPCCall create_thread_params = { - {IPC_CREATETHREAD_TAG, + {IpcTag::CREATETHREAD, {VOIDPTR_TYPE, VOIDPTR_TYPE, VOIDPTR_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>( &ThreadProcessDispatcher::CreateThread)}; @@ -144,18 +144,18 @@ ThreadProcessDispatcher::ThreadProcessDispatcher(PolicyBase* policy_base) } bool ThreadProcessDispatcher::SetupService(InterceptionManager* manager, - int service) { + IpcTag service) { switch (service) { - case IPC_NTOPENTHREAD_TAG: - case IPC_NTOPENPROCESS_TAG: - case IPC_NTOPENPROCESSTOKEN_TAG: - case IPC_NTOPENPROCESSTOKENEX_TAG: - case IPC_CREATETHREAD_TAG: + case IpcTag::NTOPENTHREAD: + case IpcTag::NTOPENPROCESS: + case IpcTag::NTOPENPROCESSTOKEN: + case IpcTag::NTOPENPROCESSTOKENEX: + case IpcTag::CREATETHREAD: // There is no explicit policy for these services. NOTREACHED(); return false; - case IPC_CREATEPROCESSW_TAG: + case IpcTag::CREATEPROCESSW: return INTERCEPT_EAT(manager, kKerneldllName, CreateProcessW, CREATE_PROCESSW_ID, 44) && INTERCEPT_EAT(manager, L"kernel32.dll", CreateProcessA, @@ -212,16 +212,16 @@ bool ThreadProcessDispatcher::NtOpenProcessTokenEx(IPCInfo* ipc, } bool ThreadProcessDispatcher::CreateProcessW(IPCInfo* ipc, - base::string16* name, - base::string16* cmd_line, - base::string16* cur_dir, - base::string16* target_cur_dir, + std::wstring* name, + std::wstring* cmd_line, + std::wstring* cur_dir, + std::wstring* target_cur_dir, CountedBuffer* info) { if (sizeof(PROCESS_INFORMATION) != info->Size()) return false; // Check if there is an application name. - base::string16 exe_name; + std::wstring exe_name; if (!name->empty()) exe_name = *name; else @@ -240,7 +240,7 @@ bool ThreadProcessDispatcher::CreateProcessW(IPCInfo* ipc, params[NameBased::NAME] = ParamPickerMake(const_exe_name); EvalResult eval = - policy_base_->EvalPolicy(IPC_CREATEPROCESSW_TAG, params.GetBase()); + policy_base_->EvalPolicy(IpcTag::CREATEPROCESSW, params.GetBase()); PROCESS_INFORMATION* proc_info = reinterpret_cast<PROCESS_INFORMATION*>(info->Buffer()); diff --git a/chromium/sandbox/win/src/process_thread_dispatcher.h b/chromium/sandbox/win/src/process_thread_dispatcher.h index da91405f09c..07466c46e2f 100644 --- a/chromium/sandbox/win/src/process_thread_dispatcher.h +++ b/chromium/sandbox/win/src/process_thread_dispatcher.h @@ -7,9 +7,11 @@ #include <stdint.h> +#include <string> + #include "base/macros.h" -#include "base/strings/string16.h" #include "sandbox/win/src/crosscall_server.h" +#include "sandbox/win/src/ipc_tags.h" #include "sandbox/win/src/sandbox_policy_base.h" namespace sandbox { @@ -21,7 +23,7 @@ class ThreadProcessDispatcher : public Dispatcher { ~ThreadProcessDispatcher() override {} // Dispatcher interface. - bool SetupService(InterceptionManager* manager, int service) override; + bool SetupService(InterceptionManager* manager, IpcTag service) override; private: // Processes IPC requests coming from calls to NtOpenThread() in the target. @@ -45,10 +47,10 @@ class ThreadProcessDispatcher : public Dispatcher { // Processes IPC requests coming from calls to CreateProcessW() in the target. bool CreateProcessW(IPCInfo* ipc, - base::string16* name, - base::string16* cmd_line, - base::string16* cur_dir, - base::string16* target_cur_dir, + std::wstring* name, + std::wstring* cmd_line, + std::wstring* cur_dir, + std::wstring* target_cur_dir, CountedBuffer* info); // Processes IPC requests coming from calls to CreateThread() in the target. diff --git a/chromium/sandbox/win/src/process_thread_interception.cc b/chromium/sandbox/win/src/process_thread_interception.cc index f1716835d2d..29d0cada58c 100644 --- a/chromium/sandbox/win/src/process_thread_interception.cc +++ b/chromium/sandbox/win/src/process_thread_interception.cc @@ -73,7 +73,7 @@ NTSTATUS WINAPI TargetNtOpenThread(NtOpenThreadFunction orig_OpenThread, SharedMemIPCClient ipc(memory); CrossCallReturn answer = {0}; - ResultCode code = CrossCall(ipc, IPC_NTOPENTHREAD_TAG, desired_access, + ResultCode code = CrossCall(ipc, IpcTag::NTOPENTHREAD, desired_access, thread_id, &answer); if (SBOX_ALL_OK != code) break; @@ -151,7 +151,7 @@ NTSTATUS WINAPI TargetNtOpenProcess(NtOpenProcessFunction orig_OpenProcess, SharedMemIPCClient ipc(memory); CrossCallReturn answer = {0}; - ResultCode code = CrossCall(ipc, IPC_NTOPENPROCESS_TAG, desired_access, + ResultCode code = CrossCall(ipc, IpcTag::NTOPENPROCESS, desired_access, process_id, &answer); if (SBOX_ALL_OK != code) break; @@ -197,7 +197,7 @@ TargetNtOpenProcessToken(NtOpenProcessTokenFunction orig_OpenProcessToken, SharedMemIPCClient ipc(memory); CrossCallReturn answer = {0}; - ResultCode code = CrossCall(ipc, IPC_NTOPENPROCESSTOKEN_TAG, process, + ResultCode code = CrossCall(ipc, IpcTag::NTOPENPROCESSTOKEN, process, desired_access, &answer); if (SBOX_ALL_OK != code) break; @@ -245,7 +245,7 @@ TargetNtOpenProcessTokenEx(NtOpenProcessTokenExFunction orig_OpenProcessTokenEx, SharedMemIPCClient ipc(memory); CrossCallReturn answer = {0}; - ResultCode code = CrossCall(ipc, IPC_NTOPENPROCESSTOKENEX_TAG, process, + ResultCode code = CrossCall(ipc, IpcTag::NTOPENPROCESSTOKENEX, process, desired_access, handle_attributes, &answer); if (SBOX_ALL_OK != code) break; @@ -316,7 +316,7 @@ BOOL WINAPI TargetCreateProcessW(CreateProcessWFunction orig_CreateProcessW, sizeof(PROCESS_INFORMATION)); ResultCode code = - CrossCall(ipc, IPC_CREATEPROCESSW_TAG, application_name, command_line, + CrossCall(ipc, IpcTag::CREATEPROCESSW, application_name, command_line, cur_dir, current_directory, proc_info, &answer); if (SBOX_ALL_OK != code) break; @@ -411,7 +411,7 @@ BOOL WINAPI TargetCreateProcessA(CreateProcessAFunction orig_CreateProcessA, InOutCountedBuffer proc_info(process_information, sizeof(PROCESS_INFORMATION)); - ResultCode code = CrossCall(ipc, IPC_CREATEPROCESSW_TAG, app_name, cmd_line, + ResultCode code = CrossCall(ipc, IpcTag::CREATEPROCESSW, app_name, cmd_line, cur_dir, cwd, proc_info, &answer); operator delete(cmd_unicode, NT_ALLOC); @@ -480,7 +480,7 @@ HANDLE WINAPI TargetCreateThread(CreateThreadFunction orig_CreateThread, // NOTE: we don't pass the thread_attributes through. This matches the // approach in CreateProcess and in CreateThreadInternal(). - ResultCode code = CrossCall(ipc, IPC_CREATETHREAD_TAG, + ResultCode code = CrossCall(ipc, IpcTag::CREATETHREAD, reinterpret_cast<LPVOID>(stack_size), reinterpret_cast<LPVOID>(start_address), parameter, creation_flags, &answer); diff --git a/chromium/sandbox/win/src/process_thread_policy.cc b/chromium/sandbox/win/src/process_thread_policy.cc index a14ad68113a..20146a83dfc 100644 --- a/chromium/sandbox/win/src/process_thread_policy.cc +++ b/chromium/sandbox/win/src/process_thread_policy.cc @@ -95,7 +95,7 @@ bool ProcessPolicy::GenerateRules(const wchar_t* name, if (!process->AddStringMatch(IF, NameBased::NAME, name, CASE_INSENSITIVE)) { return false; } - if (!policy->AddRule(IPC_CREATEPROCESSW_TAG, process.get())) { + if (!policy->AddRule(IpcTag::CREATEPROCESSW, process.get())) { return false; } return true; @@ -214,9 +214,9 @@ NTSTATUS ProcessPolicy::OpenProcessTokenExAction(const ClientInfo& client_info, DWORD ProcessPolicy::CreateProcessWAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& app_name, - const base::string16& command_line, - const base::string16& current_dir, + const std::wstring& app_name, + const std::wstring& command_line, + const std::wstring& current_dir, PROCESS_INFORMATION* process_info) { // The only action supported is ASK_BROKER which means create the process. if (GIVE_ALLACCESS != eval_result && GIVE_READONLY != eval_result) { diff --git a/chromium/sandbox/win/src/process_thread_policy.h b/chromium/sandbox/win/src/process_thread_policy.h index 018c5b32e7a..f6f96dd0ff9 100644 --- a/chromium/sandbox/win/src/process_thread_policy.h +++ b/chromium/sandbox/win/src/process_thread_policy.h @@ -9,7 +9,6 @@ #include <string> -#include "base/strings/string16.h" #include "sandbox/win/src/crosscall_server.h" #include "sandbox/win/src/policy_low_level.h" #include "sandbox/win/src/sandbox_policy.h" @@ -71,9 +70,9 @@ class ProcessPolicy { // 'current_dir' : The CWD with which to spawn the child process. static DWORD CreateProcessWAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& app_name, - const base::string16& command_line, - const base::string16& current_dir, + const std::wstring& app_name, + const std::wstring& command_line, + const std::wstring& current_dir, PROCESS_INFORMATION* process_info); // Processes a 'CreateThread()' request from the target. diff --git a/chromium/sandbox/win/src/registry_dispatcher.cc b/chromium/sandbox/win/src/registry_dispatcher.cc index 81f9a8743df..26d2bb3ffc6 100644 --- a/chromium/sandbox/win/src/registry_dispatcher.cc +++ b/chromium/sandbox/win/src/registry_dispatcher.cc @@ -23,8 +23,8 @@ namespace { // Builds a path using the root directory and the name. bool GetCompletePath(HANDLE root, - const base::string16& name, - base::string16* complete_name) { + const std::wstring& name, + std::wstring* complete_name) { if (root) { if (!sandbox::GetPathFromHandle(root, complete_name)) return false; @@ -45,13 +45,13 @@ namespace sandbox { RegistryDispatcher::RegistryDispatcher(PolicyBase* policy_base) : policy_base_(policy_base) { static const IPCCall create_params = { - {IPC_NTCREATEKEY_TAG, + {IpcTag::NTCREATEKEY, {WCHAR_TYPE, UINT32_TYPE, VOIDPTR_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>(&RegistryDispatcher::NtCreateKey)}; static const IPCCall open_params = { - {IPC_NTOPENKEY_TAG, {WCHAR_TYPE, UINT32_TYPE, VOIDPTR_TYPE, UINT32_TYPE}}, + {IpcTag::NTOPENKEY, {WCHAR_TYPE, UINT32_TYPE, VOIDPTR_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>(&RegistryDispatcher::NtOpenKey)}; ipc_calls_.push_back(create_params); @@ -59,11 +59,11 @@ RegistryDispatcher::RegistryDispatcher(PolicyBase* policy_base) } bool RegistryDispatcher::SetupService(InterceptionManager* manager, - int service) { - if (IPC_NTCREATEKEY_TAG == service) + IpcTag service) { + if (IpcTag::NTCREATEKEY == service) return INTERCEPT_NT(manager, NtCreateKey, CREATE_KEY_ID, 32); - if (IPC_NTOPENKEY_TAG == service) { + if (IpcTag::NTOPENKEY == service) { bool result = INTERCEPT_NT(manager, NtOpenKey, OPEN_KEY_ID, 16); result &= INTERCEPT_NT(manager, NtOpenKeyEx, OPEN_KEY_EX_ID, 20); return result; @@ -73,14 +73,14 @@ bool RegistryDispatcher::SetupService(InterceptionManager* manager, } bool RegistryDispatcher::NtCreateKey(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t attributes, HANDLE root, uint32_t desired_access, uint32_t title_index, uint32_t create_options) { base::win::ScopedHandle root_handle; - base::string16 real_path = *name; + std::wstring real_path = *name; // If there is a root directory, we need to duplicate the handle to make // it valid in this process. @@ -102,7 +102,7 @@ bool RegistryDispatcher::NtCreateKey(IPCInfo* ipc, params[OpenKey::ACCESS] = ParamPickerMake(desired_access); EvalResult result = - policy_base_->EvalPolicy(IPC_NTCREATEKEY_TAG, params.GetBase()); + policy_base_->EvalPolicy(IpcTag::NTCREATEKEY, params.GetBase()); HANDLE handle; NTSTATUS nt_status; @@ -122,12 +122,12 @@ bool RegistryDispatcher::NtCreateKey(IPCInfo* ipc, } bool RegistryDispatcher::NtOpenKey(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t attributes, HANDLE root, uint32_t desired_access) { base::win::ScopedHandle root_handle; - base::string16 real_path = *name; + std::wstring real_path = *name; // If there is a root directory, we need to duplicate the handle to make // it valid in this process. @@ -148,7 +148,7 @@ bool RegistryDispatcher::NtOpenKey(IPCInfo* ipc, params[OpenKey::ACCESS] = ParamPickerMake(desired_access); EvalResult result = - policy_base_->EvalPolicy(IPC_NTOPENKEY_TAG, params.GetBase()); + policy_base_->EvalPolicy(IpcTag::NTOPENKEY, params.GetBase()); HANDLE handle; NTSTATUS nt_status; if (!RegistryPolicy::OpenKeyAction(result, *ipc->client_info, *name, diff --git a/chromium/sandbox/win/src/registry_dispatcher.h b/chromium/sandbox/win/src/registry_dispatcher.h index cb5af0c3d7c..c23b95098b8 100644 --- a/chromium/sandbox/win/src/registry_dispatcher.h +++ b/chromium/sandbox/win/src/registry_dispatcher.h @@ -7,9 +7,11 @@ #include <stdint.h> +#include <string> + #include "base/macros.h" -#include "base/strings/string16.h" #include "sandbox/win/src/crosscall_server.h" +#include "sandbox/win/src/ipc_tags.h" #include "sandbox/win/src/sandbox_policy_base.h" namespace sandbox { @@ -21,12 +23,12 @@ class RegistryDispatcher : public Dispatcher { ~RegistryDispatcher() override {} // Dispatcher interface. - bool SetupService(InterceptionManager* manager, int service) override; + bool SetupService(InterceptionManager* manager, IpcTag service) override; private: // Processes IPC requests coming from calls to NtCreateKey in the target. bool NtCreateKey(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t attributes, HANDLE root, uint32_t desired_access, @@ -35,7 +37,7 @@ class RegistryDispatcher : public Dispatcher { // Processes IPC requests coming from calls to NtOpenKey in the target. bool NtOpenKey(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t attributes, HANDLE root, uint32_t desired_access); diff --git a/chromium/sandbox/win/src/registry_interception.cc b/chromium/sandbox/win/src/registry_interception.cc index 4d381a948b0..ec09aeb7938 100644 --- a/chromium/sandbox/win/src/registry_interception.cc +++ b/chromium/sandbox/win/src/registry_interception.cc @@ -84,7 +84,7 @@ NTSTATUS WINAPI TargetNtCreateKey(NtCreateKeyFunction orig_CreateKey, params[OpenKey::NAME] = ParamPickerMake(name_ptr); } - query_broker = QueryBroker(IPC_NTCREATEKEY_TAG, params.GetBase()); + query_broker = QueryBroker(IpcTag::NTCREATEKEY, params.GetBase()); } if (!query_broker) @@ -93,7 +93,7 @@ NTSTATUS WINAPI TargetNtCreateKey(NtCreateKeyFunction orig_CreateKey, SharedMemIPCClient ipc(memory); CrossCallReturn answer = {0}; - ResultCode code = CrossCall(ipc, IPC_NTCREATEKEY_TAG, name.get(), + ResultCode code = CrossCall(ipc, IpcTag::NTCREATEKEY, name.get(), attributes, root_directory, desired_access, title_index, create_options, &answer); @@ -169,7 +169,7 @@ NTSTATUS WINAPI CommonNtOpenKey(NTSTATUS status, params[OpenKey::NAME] = ParamPickerMake(name_ptr); } - query_broker = QueryBroker(IPC_NTOPENKEY_TAG, params.GetBase()); + query_broker = QueryBroker(IpcTag::NTOPENKEY, params.GetBase()); } if (!query_broker) @@ -177,7 +177,7 @@ NTSTATUS WINAPI CommonNtOpenKey(NTSTATUS status, SharedMemIPCClient ipc(memory); CrossCallReturn answer = {0}; - ResultCode code = CrossCall(ipc, IPC_NTOPENKEY_TAG, name.get(), attributes, + ResultCode code = CrossCall(ipc, IpcTag::NTOPENKEY, name.get(), attributes, root_directory, desired_access, &answer); if (SBOX_ALL_OK != code) diff --git a/chromium/sandbox/win/src/registry_policy.cc b/chromium/sandbox/win/src/registry_policy.cc index e15baab294f..1379501fb3a 100644 --- a/chromium/sandbox/win/src/registry_policy.cc +++ b/chromium/sandbox/win/src/registry_policy.cc @@ -121,15 +121,15 @@ namespace sandbox { bool RegistryPolicy::GenerateRules(const wchar_t* name, TargetPolicy::Semantics semantics, LowLevelPolicy* policy) { - base::string16 resovled_name(name); - if (resovled_name.empty()) { + std::wstring resolved_name(name); + if (resolved_name.empty()) { return false; } - if (!ResolveRegistryName(resovled_name, &resovled_name)) + if (!ResolveRegistryName(resolved_name, &resolved_name)) return false; - name = resovled_name.c_str(); + name = resolved_name.c_str(); EvalResult result = ASK_BROKER; @@ -156,12 +156,12 @@ bool RegistryPolicy::GenerateRules(const wchar_t* name, } if (!create.AddStringMatch(IF, OpenKey::NAME, name, CASE_INSENSITIVE) || - !policy->AddRule(IPC_NTCREATEKEY_TAG, &create)) { + !policy->AddRule(IpcTag::NTCREATEKEY, &create)) { return false; } if (!open.AddStringMatch(IF, OpenKey::NAME, name, CASE_INSENSITIVE) || - !policy->AddRule(IPC_NTOPENKEY_TAG, &open)) { + !policy->AddRule(IpcTag::NTOPENKEY, &open)) { return false; } @@ -170,7 +170,7 @@ bool RegistryPolicy::GenerateRules(const wchar_t* name, bool RegistryPolicy::CreateKeyAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& key, + const std::wstring& key, uint32_t attributes, HANDLE root_directory, uint32_t desired_access, @@ -204,7 +204,7 @@ bool RegistryPolicy::CreateKeyAction(EvalResult eval_result, bool RegistryPolicy::OpenKeyAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& key, + const std::wstring& key, uint32_t attributes, HANDLE root_directory, uint32_t desired_access, diff --git a/chromium/sandbox/win/src/registry_policy.h b/chromium/sandbox/win/src/registry_policy.h index de4690e3c5c..9a36932869b 100644 --- a/chromium/sandbox/win/src/registry_policy.h +++ b/chromium/sandbox/win/src/registry_policy.h @@ -9,7 +9,6 @@ #include <string> -#include "base/strings/string16.h" #include "sandbox/win/src/crosscall_server.h" #include "sandbox/win/src/nt_internals.h" #include "sandbox/win/src/policy_low_level.h" @@ -30,7 +29,7 @@ class RegistryPolicy { // API that is compatible with the IPC-received parameters. static bool CreateKeyAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& key, + const std::wstring& key, uint32_t attributes, HANDLE root_directory, uint32_t desired_access, @@ -44,7 +43,7 @@ class RegistryPolicy { // API that is compatible with the IPC-received parameters. static bool OpenKeyAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& key, + const std::wstring& key, uint32_t attributes, HANDLE root_directory, uint32_t desired_access, diff --git a/chromium/sandbox/win/src/restricted_token.cc b/chromium/sandbox/win/src/restricted_token.cc index eae0a45e2c2..8e0cb8b30dc 100644 --- a/chromium/sandbox/win/src/restricted_token.cc +++ b/chromium/sandbox/win/src/restricted_token.cc @@ -265,7 +265,7 @@ DWORD RestrictedToken::AddUserSidForDenyOnly() { } DWORD RestrictedToken::DeleteAllPrivileges( - const std::vector<base::string16>* exceptions) { + const std::vector<std::wstring>* exceptions) { DCHECK(init_); if (!init_) return ERROR_NO_TOKEN; diff --git a/chromium/sandbox/win/src/restricted_token.h b/chromium/sandbox/win/src/restricted_token.h index 7b6d9fd0a11..b713f87702b 100644 --- a/chromium/sandbox/win/src/restricted_token.h +++ b/chromium/sandbox/win/src/restricted_token.h @@ -9,8 +9,9 @@ #include <vector> +#include <string> + #include "base/macros.h" -#include "base/strings/string16.h" #include "base/win/scoped_handle.h" #include "sandbox/win/src/restricted_token_utils.h" #include "sandbox/win/src/security_level.h" @@ -113,10 +114,10 @@ class RestrictedToken { // the error. // // Sample usage: - // std::vector<base::string16> privilege_exceptions; + // std::vector<std::wstring> privilege_exceptions; // privilege_exceptions.push_back(SE_CHANGE_NOTIFY_NAME); // restricted_token.DeleteAllPrivileges(&privilege_exceptions); - DWORD DeleteAllPrivileges(const std::vector<base::string16>* exceptions); + DWORD DeleteAllPrivileges(const std::vector<std::wstring>* exceptions); // Adds a privilege to the list of privileges to remove in the restricted // token. diff --git a/chromium/sandbox/win/src/restricted_token_unittest.cc b/chromium/sandbox/win/src/restricted_token_unittest.cc index 88cae12e3d5..1855054a7cd 100644 --- a/chromium/sandbox/win/src/restricted_token_unittest.cc +++ b/chromium/sandbox/win/src/restricted_token_unittest.cc @@ -529,7 +529,7 @@ TEST(RestrictedTokenTest, DeleteAllPrivilegesException) { RestrictedToken token; base::win::ScopedHandle token_handle; - std::vector<base::string16> exceptions; + std::vector<std::wstring> exceptions; exceptions.push_back(SE_CHANGE_NOTIFY_NAME); ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(nullptr)); diff --git a/chromium/sandbox/win/src/restricted_token_utils.cc b/chromium/sandbox/win/src/restricted_token_utils.cc index 496fb37272d..7c18f8481a2 100644 --- a/chromium/sandbox/win/src/restricted_token_utils.cc +++ b/chromium/sandbox/win/src/restricted_token_utils.cc @@ -62,7 +62,7 @@ DWORD CreateRestrictedToken(HANDLE effective_token, if (lockdown_default_dacl) restricted_token.SetLockdownDefaultDacl(); - std::vector<base::string16> privilege_exceptions; + std::vector<std::wstring> privilege_exceptions; std::vector<Sid> sid_exceptions; bool deny_sids = true; @@ -189,7 +189,7 @@ DWORD SetObjectIntegrityLabel(HANDLE handle, const wchar_t* ace_access, const wchar_t* integrity_level_sid) { // Build the SDDL string for the label. - base::string16 sddl = L"S:("; // SDDL for a SACL. + std::wstring sddl = L"S:("; // SDDL for a SACL. sddl += SDDL_MANDATORY_LABEL; // Ace Type is "Mandatory Label". sddl += L";;"; // No Ace Flags. sddl += ace_access; // Add the ACE access. @@ -422,7 +422,7 @@ DWORD CreateLowBoxObjectDirectory(PSID lowbox_sid, return ::GetLastError(); std::unique_ptr<wchar_t, LocalFreeDeleter> sid_string_ptr(sid_string); - base::string16 directory_path = base::StringPrintf( + std::wstring directory_path = base::StringPrintf( L"\\Sessions\\%d\\AppContainerNamedObjects\\%ls", session_id, sid_string); NtCreateDirectoryObjectFunction CreateObjectDirectory = nullptr; diff --git a/chromium/sandbox/win/src/sandbox_constants.cc b/chromium/sandbox/win/src/sandbox_constants.cc index 1d932427d13..5ed326eda7e 100644 --- a/chromium/sandbox/win/src/sandbox_constants.cc +++ b/chromium/sandbox/win/src/sandbox_constants.cc @@ -13,5 +13,6 @@ extern const char kJobLevel[] = "jobLevel"; extern const char kLockdownLevel[] = "lockdownLevel"; extern const char kLowboxSid[] = "lowboxSid"; extern const char kPlatformMitigations[] = "platformMitigations"; +extern const char kPolicyRules[] = "policyRules"; extern const char kProcessIds[] = "processIds"; } // namespace sandbox diff --git a/chromium/sandbox/win/src/sandbox_constants.h b/chromium/sandbox/win/src/sandbox_constants.h index baf9a1e48d4..330a2ae5917 100644 --- a/chromium/sandbox/win/src/sandbox_constants.h +++ b/chromium/sandbox/win/src/sandbox_constants.h @@ -14,8 +14,8 @@ extern const char kJobLevel[]; extern const char kLockdownLevel[]; extern const char kLowboxSid[]; extern const char kPlatformMitigations[]; +extern const char kPolicyRules[]; extern const char kProcessIds[]; - } // namespace sandbox #endif // SANDBOX_WIN_SRC_SANDBOX_CONSTANTS_H_ diff --git a/chromium/sandbox/win/src/sandbox_nt_util_unittest.cc b/chromium/sandbox/win/src/sandbox_nt_util_unittest.cc index a98392fe55d..011f1dbb326 100644 --- a/chromium/sandbox/win/src/sandbox_nt_util_unittest.cc +++ b/chromium/sandbox/win/src/sandbox_nt_util_unittest.cc @@ -253,11 +253,12 @@ TEST(SandboxNtUtil, NtGetPathFromHandle) { // Basic sanity test, the functionality of NtGetPathFromHandle to return // the correct value is already tested from win_utils_unittest.cc. - EXPECT_TRUE(base::EndsWith(path.get(), exe.BaseName().value(), + EXPECT_TRUE(base::EndsWith(base::AsStringPiece16(path.get()), + base::AsStringPiece16(exe.BaseName().value()), base::CompareCase::INSENSITIVE_ASCII)); // Compare to GetNtPathFromWin32Path for extra check. - base::string16 nt_path; + std::wstring nt_path; EXPECT_TRUE(GetNtPathFromWin32Path(exe.value(), &nt_path)); EXPECT_STREQ(path.get(), nt_path.c_str()); } diff --git a/chromium/sandbox/win/src/sandbox_policy.h b/chromium/sandbox/win/src/sandbox_policy.h index 205e9bafbf7..527995586c8 100644 --- a/chromium/sandbox/win/src/sandbox_policy.h +++ b/chromium/sandbox/win/src/sandbox_policy.h @@ -8,8 +8,9 @@ #include <stddef.h> #include <stdint.h> +#include <string> + #include "base/memory/scoped_refptr.h" -#include "base/strings/string16.h" #include "sandbox/win/src/sandbox_types.h" #include "sandbox/win/src/security_level.h" @@ -153,7 +154,7 @@ class TargetPolicy { // Returns the name of the alternate desktop used. If an alternate window // station is specified, the name is prepended by the window station name, // followed by a backslash. - virtual base::string16 GetAlternateDesktop() const = 0; + virtual std::wstring GetAlternateDesktop() const = 0; // Precreates the desktop and window station, if any. virtual ResultCode CreateAlternateDesktop(bool alternate_winstation) = 0; diff --git a/chromium/sandbox/win/src/sandbox_policy_base.cc b/chromium/sandbox/win/src/sandbox_policy_base.cc index ab27faf874f..257eb032374 100644 --- a/chromium/sandbox/win/src/sandbox_policy_base.cc +++ b/chromium/sandbox/win/src/sandbox_policy_base.cc @@ -180,10 +180,10 @@ ResultCode PolicyBase::SetAlternateDesktop(bool alternate_winstation) { return CreateAlternateDesktop(alternate_winstation); } -base::string16 PolicyBase::GetAlternateDesktop() const { +std::wstring PolicyBase::GetAlternateDesktop() const { // No alternate desktop or winstation. Return an empty string. if (!use_alternate_desktop_ && !use_alternate_winstation_) { - return base::string16(); + return std::wstring(); } if (use_alternate_winstation_) { @@ -191,14 +191,14 @@ base::string16 PolicyBase::GetAlternateDesktop() const { // If we hit this scenario, it means that the user ignored the failure // during SetAlternateDesktop, so we ignore it here too. if (!alternate_desktop_handle_ || !alternate_winstation_handle_) - return base::string16(); + return std::wstring(); return GetFullDesktopName(alternate_winstation_handle_, alternate_desktop_handle_); } if (!alternate_desktop_local_winstation_handle_) - return base::string16(); + return std::wstring(); return GetFullDesktopName(nullptr, alternate_desktop_local_winstation_handle_); @@ -368,8 +368,8 @@ ResultCode PolicyBase::AddDllToUnload(const wchar_t* dll_name) { return SBOX_ALL_OK; } -ResultCode PolicyBase::AddKernelObjectToClose(const base::char16* handle_type, - const base::char16* handle_name) { +ResultCode PolicyBase::AddKernelObjectToClose(const wchar_t* handle_type, + const wchar_t* handle_name) { return handle_closer_.AddHandle(handle_type, handle_name); } @@ -578,10 +578,10 @@ ResultCode PolicyBase::SetDisconnectCsrss() { return SBOX_ALL_OK; } -EvalResult PolicyBase::EvalPolicy(int service, +EvalResult PolicyBase::EvalPolicy(IpcTag service, CountedParameterSetBase* params) { if (policy_) { - if (!policy_->entry[service]) { + if (!policy_->entry[static_cast<size_t>(service)]) { // There is no policy for this particular service. This is not a big // deal. return DENY_ACCESS; @@ -592,7 +592,7 @@ EvalResult PolicyBase::EvalPolicy(int service, return SIGNAL_ALARM; } } - PolicyProcessor pol_evaluator(policy_->entry[service]); + PolicyProcessor pol_evaluator(policy_->entry[static_cast<size_t>(service)]); PolicyResult result = pol_evaluator.Evaluate(kShortEval, params->parameters, params->count); if (POLICY_MATCH == result) @@ -674,13 +674,14 @@ ResultCode PolicyBase::SetupAllInterceptions(TargetProcess* target) { InterceptionManager manager(target, relaxed_interceptions_); if (policy_) { - for (int i = 0; i < IPC_LAST_TAG; i++) { - if (policy_->entry[i] && !dispatcher_->SetupService(&manager, i)) + for (size_t i = 0; i < kMaxIpcTag; i++) { + if (policy_->entry[i] && + !dispatcher_->SetupService(&manager, static_cast<IpcTag>(i))) return SBOX_ERROR_SETUP_INTERCEPTION_SERVICE; } } - for (const base::string16& dll : blocklisted_dlls_) + for (const std::wstring& dll : blocklisted_dlls_) manager.AddToUnloadModules(dll.c_str()); if (!SetupBasicInterceptions(&manager, is_csrss_connected_)) diff --git a/chromium/sandbox/win/src/sandbox_policy_base.h b/chromium/sandbox/win/src/sandbox_policy_base.h index 03a8948b789..a2fda7ced0d 100644 --- a/chromium/sandbox/win/src/sandbox_policy_base.h +++ b/chromium/sandbox/win/src/sandbox_policy_base.h @@ -12,13 +12,13 @@ #include <list> #include <memory> +#include <string> #include <vector> #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "base/process/launch.h" -#include "base/strings/string16.h" #include "base/win/scoped_handle.h" #include "sandbox/win/src/app_container_profile_base.h" #include "sandbox/win/src/crosscall_server.h" @@ -50,7 +50,7 @@ class PolicyBase final : public TargetPolicy { JobLevel GetJobLevel() const override; ResultCode SetJobMemoryLimit(size_t memory_limit) override; ResultCode SetAlternateDesktop(bool alternate_winstation) override; - base::string16 GetAlternateDesktop() const override; + std::wstring GetAlternateDesktop() const override; ResultCode CreateAlternateDesktop(bool alternate_winstation) override; void DestroyAlternateDesktop() override; ResultCode SetIntegrityLevel(IntegrityLevel integrity_level) override; @@ -69,8 +69,8 @@ class PolicyBase final : public TargetPolicy { Semantics semantics, const wchar_t* pattern) override; ResultCode AddDllToUnload(const wchar_t* dll_name) override; - ResultCode AddKernelObjectToClose(const base::char16* handle_type, - const base::char16* handle_name) override; + ResultCode AddKernelObjectToClose(const wchar_t* handle_type, + const wchar_t* handle_name) override; void AddHandleToShare(HANDLE handle) override; void SetLockdownDefaultDacl() override; void SetEnableOPMRedirection() override; @@ -105,7 +105,7 @@ class PolicyBase final : public TargetPolicy { // with the job. bool OnJobEmpty(HANDLE job); - EvalResult EvalPolicy(int service, CountedParameterSetBase* params); + EvalResult EvalPolicy(IpcTag service, CountedParameterSetBase* params); HANDLE GetStdoutHandle(); HANDLE GetStderrHandle(); @@ -159,7 +159,7 @@ class PolicyBase final : public TargetPolicy { // Memory structure that stores the low level policy. PolicyGlobal* policy_; // The list of dlls to unload in the target process. - std::vector<base::string16> blocklisted_dlls_; + std::vector<std::wstring> blocklisted_dlls_; // This is a map of handle-types to names that we need to close in the // target process. A null set means we need to close all handles of the // given type. diff --git a/chromium/sandbox/win/src/sandbox_policy_diagnostic.cc b/chromium/sandbox/win/src/sandbox_policy_diagnostic.cc index 190b7296ea0..de4f4a7542c 100644 --- a/chromium/sandbox/win/src/sandbox_policy_diagnostic.cc +++ b/chromium/sandbox/win/src/sandbox_policy_diagnostic.cc @@ -17,6 +17,8 @@ #include "base/numerics/safe_conversions.h" #include "base/strings/stringprintf.h" #include "base/values.h" +#include "sandbox/win/src/ipc_tags.h" +#include "sandbox/win/src/policy_engine_opcodes.h" #include "sandbox/win/src/sandbox_constants.h" #include "sandbox/win/src/sandbox_policy_base.h" #include "sandbox/win/src/target_process.h" @@ -53,7 +55,6 @@ std::string GetTokenLevelInEnglish(TokenLevel token) { case USER_RESTRICTED_NON_ADMIN: return "Restricted Non Admin"; case USER_LAST: - default: DCHECK(false) << "Unknown TokenType"; return "Unknown"; } @@ -73,9 +74,6 @@ std::string GetJobLevelInEnglish(JobLevel job) { return "Unprotected"; case JOB_NONE: return "None"; - default: - DCHECK(false) << "Unknown JobLevel"; - return "Unknown"; } } @@ -97,9 +95,6 @@ std::string GetIntegrityLevelInEnglish(IntegrityLevel integrity) { return "S-1-16-0 Untrusted"; case INTEGRITY_LEVEL_LAST: return "Default"; - default: - DCHECK(false) << "Unknown IntegrityLevel"; - return "Unknown"; } } @@ -128,6 +123,244 @@ std::string GetPlatformMitigationsAsHex(MitigationFlags mitigations) { return base::StringPrintf("%016" PRIx64, platform_flags[0]); } +std::string GetIpcTagAsString(IpcTag service) { + switch (service) { + case IpcTag::UNUSED: + DCHECK(false) << "Unused IpcTag"; + return "Unused"; + case IpcTag::PING1: + return "Ping1"; + case IpcTag::PING2: + return "Ping2"; + case IpcTag::NTCREATEFILE: + return "NtCreateFile"; + case IpcTag::NTOPENFILE: + return "NtOpenFile"; + case IpcTag::NTQUERYATTRIBUTESFILE: + return "NtQueryAttributesFile"; + case IpcTag::NTQUERYFULLATTRIBUTESFILE: + return "NtQueryFullAttributesFile"; + case IpcTag::NTSETINFO_RENAME: + return "NtSetInfoRename"; + case IpcTag::CREATENAMEDPIPEW: + return "CreateNamedPipeW"; + case IpcTag::NTOPENTHREAD: + return "NtOpenThread"; + case IpcTag::NTOPENPROCESS: + return "NtOpenProcess"; + case IpcTag::NTOPENPROCESSTOKEN: + return "NtOpenProcessToken"; + case IpcTag::NTOPENPROCESSTOKENEX: + return "NtOpenProcessTokenEx"; + case IpcTag::CREATEPROCESSW: + return "CreateProcessW"; + case IpcTag::CREATEEVENT: + return "CreateEvent"; + case IpcTag::OPENEVENT: + return "OpenEvent"; + case IpcTag::NTCREATEKEY: + return "NtCreateKey"; + case IpcTag::NTOPENKEY: + return "NtOpenKey"; + case IpcTag::GDI_GDIDLLINITIALIZE: + return "GdiDllInitialize"; + case IpcTag::GDI_GETSTOCKOBJECT: + return "GetStockObject"; + case IpcTag::USER_REGISTERCLASSW: + return "RegisterClassW"; + case IpcTag::CREATETHREAD: + return "CreateThread"; + case IpcTag::USER_ENUMDISPLAYMONITORS: + return "EnumDisplayMonitors"; + case IpcTag::USER_ENUMDISPLAYDEVICES: + return "EnumDisplayDevices"; + case IpcTag::USER_GETMONITORINFO: + return "GetMonitorInfo"; + case IpcTag::GDI_CREATEOPMPROTECTEDOUTPUTS: + return "CreateOPMProtectedOutputs"; + case IpcTag::GDI_GETCERTIFICATE: + return "GetCertificate"; + case IpcTag::GDI_GETCERTIFICATESIZE: + return "GetCertificateSize"; + case IpcTag::GDI_DESTROYOPMPROTECTEDOUTPUT: + return "DestroyOPMProtectedOutput"; + case IpcTag::GDI_CONFIGUREOPMPROTECTEDOUTPUT: + return "ConfigureOPMProtectedOutput"; + case IpcTag::GDI_GETOPMINFORMATION: + return "GetOPMInformation"; + case IpcTag::GDI_GETOPMRANDOMNUMBER: + return "GetOPMRandomNumber"; + case IpcTag::GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE: + return "GetSuggestedOPMProtectedOutputArraySize"; + case IpcTag::GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS: + return "SetOPMSigningKeyAndSequenceNumbers"; + case IpcTag::NTCREATESECTION: + return "NtCreateSection"; + case IpcTag::LAST: + DCHECK(false) << "Unknown IpcTag"; + return "Unknown"; + } +} + +std::string GetOpcodeAction(EvalResult action) { + switch (action) { + case EVAL_TRUE: + return "true"; + case EVAL_FALSE: + return "false"; + case EVAL_ERROR: + return "error"; + case ASK_BROKER: + return "askBroker"; + case DENY_ACCESS: + return "deny"; + case GIVE_READONLY: + return "readonly"; + case GIVE_ALLACCESS: + return "allaccess"; + case GIVE_CACHED: + return "cached"; + case GIVE_FIRST: + return "first"; + case SIGNAL_ALARM: + return "alarm"; + case FAKE_SUCCESS: + return "fakeSuccess"; + case FAKE_ACCESS_DENIED: + return "fakeDenied"; + case TERMINATE_PROCESS: + return "terminate"; + } +} + +std::string GetStringMatchOperation(int pos, uint32_t options) { + if (pos == 0) { + if (options & EXACT_LENGTH) + return "exact"; + else + return "prefix"; + } else if (pos < 0) { + return "scan"; + } else if (pos == kSeekToEnd) { + return "ends"; + } else { + DCHECK(false) << "Invalid pos (" << pos << ")"; + return "unknown"; + } +} + +std::string GetPolicyOpcode(const PolicyOpcode* opcode, bool continuation) { + // See |policy_engine_opcodes.cc|. + uint32_t args[4]; + auto options = opcode->GetOptions(); + auto param = opcode->GetParameter(); + std::string condition; + + if (options & kPolNegateEval) + condition += "!("; + + switch (opcode->GetID()) { + case OP_ALWAYS_FALSE: + condition += "false"; + break; + case OP_ALWAYS_TRUE: + condition += "true"; + break; + case OP_NUMBER_MATCH: + opcode->GetArgument(1, &args[1]); + if (args[1] == UINT32_TYPE) { + opcode->GetArgument(0, &args[0]); + condition += base::StringPrintf("p[%d] == %x", param, args[0]); + } else { + const void* match_ptr = nullptr; + opcode->GetArgument(0, &match_ptr); + condition += base::StringPrintf("p[%d] == %p", param, match_ptr); + } + break; + case OP_NUMBER_MATCH_RANGE: + opcode->GetArgument(0, &args[0]); + opcode->GetArgument(1, &args[1]); + condition += + base::StringPrintf("%x <= p[%d] <= %x", args[0], param, args[1]); + break; + case OP_NUMBER_AND_MATCH: + opcode->GetArgument(0, &args[0]); + condition += base::StringPrintf("p[%d] & %x", param, args[0]); + break; + case OP_WSTRING_MATCH: { + int pos; + opcode->GetArgument(1, &args[1]); // Length. + opcode->GetArgument(2, &pos); // Position. + opcode->GetArgument(3, &args[3]); // Options. + // These are not nul-terminated so we have to wrap them here. + auto match_string = std::wstring(opcode->GetRelativeString(0), 0, + static_cast<size_t>(args[1])); + condition += GetStringMatchOperation(pos, args[3]); + if (args[3] & CASE_INSENSITIVE) + condition += "_i"; + condition += + base::StringPrintf("(p[%d], '%S')", param, match_string.c_str()); + } break; + case OP_ACTION: + opcode->GetArgument(0, &args[0]); + condition += GetOpcodeAction(static_cast<EvalResult>(args[0])); + break; + default: + DCHECK(false) << "Unknown Opcode"; + return "Unknown"; + } + + if (options & kPolNegateEval) + condition += ")"; + // If there is another rule add a joining token. + if (continuation) { + if (options & kPolUseOREval) + condition += " || "; + else + condition += " && "; + } + return condition; +} + +// Uses |service| to index into |policy_rules| returning a list of opcodes. +base::Value GetPolicyOpcodes(const PolicyGlobal* policy_rules, IpcTag service) { + base::Value entry(base::Value::Type::LIST); + PolicyBuffer* policy_buffer = + policy_rules->entry[static_cast<size_t>(service)]; + // Build up rules and emit when we hit an action. + std::string cur_rule; + for (size_t i = 0; i < policy_buffer->opcode_count; i++) { + const PolicyOpcode* opcode = &policy_buffer->opcodes[i]; + if (opcode->GetID() != OP_ACTION) { + DCHECK(i + 1 < policy_buffer->opcode_count) + << "Non-actions should not terminate rules"; + bool peak = policy_buffer->opcodes[i + 1].GetID() != OP_ACTION; + cur_rule += GetPolicyOpcode(opcode, peak); + } else { + cur_rule += " -> "; + cur_rule += GetPolicyOpcode(opcode, false); + entry.GetList().push_back(base::Value(cur_rule)); + cur_rule.clear(); + } + } + return entry; +} + +base::Value GetPolicyRules(const PolicyGlobal* policy_rules) { + DCHECK(policy_rules); + base::Value results(base::Value::Type::DICTIONARY); + + for (size_t i = 0; i < kMaxServiceCount; i++) { + if (!policy_rules->entry[i]) + continue; + IpcTag service = static_cast<IpcTag>(i); + results.SetKey(GetIpcTagAsString(service), + GetPolicyOpcodes(policy_rules, service)); + } + + return results; +} + } // namespace // We are a friend of PolicyBase so that we can steal its private members @@ -158,6 +391,24 @@ PolicyDiagnostic::PolicyDiagnostic(PolicyBase* policy) { std::make_unique<Sid>(policy->app_container_profile_->GetPackageSid()); if (policy->lowbox_sid_) lowbox_sid_ = std::make_unique<Sid>(policy->lowbox_sid_); + + if (policy->policy_) { + size_t policy_mem_size = policy->policy_->data_size + sizeof(PolicyGlobal); + policy_rules_.reset( + static_cast<sandbox::PolicyGlobal*>(::operator new(policy_mem_size))); + memcpy(policy_rules_.get(), policy->policy_, policy_mem_size); + // Fixup pointers (see |PolicyGlobal| in policy_low_level.h). + PolicyBuffer** original_entries = policy->policy_->entry; + PolicyBuffer** copy_base = policy_rules_->entry; + for (size_t i = 0; i < kMaxServiceCount; i++) { + if (policy_rules_->entry[i]) { + policy_rules_->entry[i] = reinterpret_cast<PolicyBuffer*>( + reinterpret_cast<char*>(copy_base) + + (reinterpret_cast<char*>(original_entries[i]) - + reinterpret_cast<char*>(original_entries))); + } + } + } } PolicyDiagnostic::~PolicyDiagnostic() = default; @@ -187,6 +438,9 @@ const char* PolicyDiagnostic::JsonString() { if (lowbox_sid_) value.SetKey(kLowboxSid, base::Value(GetSidAsString(lowbox_sid_.get()))); + if (policy_rules_) + value.SetKey(kPolicyRules, GetPolicyRules(policy_rules_.get())); + auto json_string = std::make_unique<std::string>(); JSONStringValueSerializer to_json(json_string.get()); CHECK(to_json.Serialize(value)); diff --git a/chromium/sandbox/win/src/sandbox_policy_diagnostic.h b/chromium/sandbox/win/src/sandbox_policy_diagnostic.h index 0fb4da7bfd7..a392c7b2d7b 100644 --- a/chromium/sandbox/win/src/sandbox_policy_diagnostic.h +++ b/chromium/sandbox/win/src/sandbox_policy_diagnostic.h @@ -13,6 +13,7 @@ #include "base/macros.h" #include "base/values.h" +#include "sandbox/win/src/policy_low_level.h" #include "sandbox/win/src/process_mitigations.h" #include "sandbox/win/src/sandbox.h" #include "sandbox/win/src/security_level.h" @@ -42,6 +43,7 @@ class PolicyDiagnostic final : public PolicyInfo { MitigationFlags desired_mitigations_ = 0; std::unique_ptr<Sid> app_container_sid_ = nullptr; std::unique_ptr<Sid> lowbox_sid_ = nullptr; + std::unique_ptr<PolicyGlobal> policy_rules_ = nullptr; DISALLOW_COPY_AND_ASSIGN(PolicyDiagnostic); }; diff --git a/chromium/sandbox/win/src/sandbox_utils.cc b/chromium/sandbox/win/src/sandbox_utils.cc index 60933cdb22c..f34daa7d3e2 100644 --- a/chromium/sandbox/win/src/sandbox_utils.cc +++ b/chromium/sandbox/win/src/sandbox_utils.cc @@ -11,7 +11,7 @@ namespace sandbox { -void InitObjectAttribs(const base::string16& name, +void InitObjectAttribs(const std::wstring& name, ULONG attributes, HANDLE root, OBJECT_ATTRIBUTES* obj_attr, diff --git a/chromium/sandbox/win/src/sandbox_utils.h b/chromium/sandbox/win/src/sandbox_utils.h index b1c1f3134da..580d1298f6e 100644 --- a/chromium/sandbox/win/src/sandbox_utils.h +++ b/chromium/sandbox/win/src/sandbox_utils.h @@ -8,12 +8,11 @@ #include <windows.h> #include <string> -#include "base/strings/string16.h" #include "sandbox/win/src/nt_internals.h" namespace sandbox { -void InitObjectAttribs(const base::string16& name, +void InitObjectAttribs(const std::wstring& name, ULONG attributes, HANDLE root, OBJECT_ATTRIBUTES* obj_attr, diff --git a/chromium/sandbox/win/src/sharedmem_ipc_client.h b/chromium/sandbox/win/src/sharedmem_ipc_client.h index a7068fa51e9..73f739dece2 100644 --- a/chromium/sandbox/win/src/sharedmem_ipc_client.h +++ b/chromium/sandbox/win/src/sharedmem_ipc_client.h @@ -9,6 +9,7 @@ #include <stdint.h> #include "sandbox/win/src/crosscall_params.h" +#include "sandbox/win/src/ipc_tags.h" #include "sandbox/win/src/sandbox.h" // IPC transport implementation that uses shared memory. @@ -84,7 +85,7 @@ struct ChannelControl { // the client waits on the pong event for the IPC answer back HANDLE pong_event; // the IPC unique identifier - uint32_t ipc_tag; + IpcTag ipc_tag; }; struct IPCControl { diff --git a/chromium/sandbox/win/src/sharedmem_ipc_server.cc b/chromium/sandbox/win/src/sharedmem_ipc_server.cc index 13ae69b6be4..74e5c171e02 100644 --- a/chromium/sandbox/win/src/sharedmem_ipc_server.cc +++ b/chromium/sandbox/win/src/sharedmem_ipc_server.cc @@ -153,17 +153,15 @@ bool SharedMemIPCServer::InvokeCallback(const ServerControl* service_context, if (!params.get()) return false; - uint32_t tag = params->GetTag(); + IpcTag tag = params->GetTag(); static_assert(0 == INVALID_TYPE, "incorrect type enum"); - IPCParams ipc_params = {0}; - ipc_params.ipc_tag = tag; + IPCParams ipc_params = {tag}; void* args[kMaxIpcParams]; if (!GetArgs(params.get(), &ipc_params, args)) return false; - IPCInfo ipc_info = {0}; - ipc_info.ipc_tag = tag; + IPCInfo ipc_info = {tag}; ipc_info.client_info = &service_context->target_info; Dispatcher* dispatcher = service_context->dispatcher; DCHECK(dispatcher); diff --git a/chromium/sandbox/win/src/sid.cc b/chromium/sandbox/win/src/sid.cc index 3507ad7c346..5f35f3eb6a3 100644 --- a/chromium/sandbox/win/src/sid.cc +++ b/chromium/sandbox/win/src/sid.cc @@ -141,7 +141,7 @@ bool Sid::IsValid() const { } // Converts the SID to an SDDL format string. -bool Sid::ToSddlString(base::string16* sddl_string) const { +bool Sid::ToSddlString(std::wstring* sddl_string) const { LPWSTR sid = nullptr; if (!::ConvertSidToStringSid(GetPSID(), &sid)) return false; diff --git a/chromium/sandbox/win/src/sid.h b/chromium/sandbox/win/src/sid.h index 4ef22e54602..5382160a2ff 100644 --- a/chromium/sandbox/win/src/sid.h +++ b/chromium/sandbox/win/src/sid.h @@ -7,7 +7,7 @@ #include <windows.h> -#include "base/strings/string16.h" +#include <string> namespace sandbox { @@ -60,7 +60,7 @@ class Sid { bool IsValid() const; // Converts the SID to a SDDL format string. - bool ToSddlString(base::string16* sddl_string) const; + bool ToSddlString(std::wstring* sddl_string) const; private: Sid(); diff --git a/chromium/sandbox/win/src/sid_unittest.cc b/chromium/sandbox/win/src/sid_unittest.cc index 3bfa8f3738d..81186cd0bec 100644 --- a/chromium/sandbox/win/src/sid_unittest.cc +++ b/chromium/sandbox/win/src/sid_unittest.cc @@ -159,7 +159,7 @@ TEST(SidTest, NamedCapability) { TEST(SidTest, Sddl) { Sid sid_sddl = Sid::FromSddlString(L"S-1-1-0"); ASSERT_TRUE(sid_sddl.IsValid()); - base::string16 sddl_str; + std::wstring sddl_str; ASSERT_TRUE(sid_sddl.ToSddlString(&sddl_str)); ASSERT_EQ(L"S-1-1-0", sddl_str); } diff --git a/chromium/sandbox/win/src/signed_dispatcher.cc b/chromium/sandbox/win/src/signed_dispatcher.cc index 325a81e4159..49e7cbe946b 100644 --- a/chromium/sandbox/win/src/signed_dispatcher.cc +++ b/chromium/sandbox/win/src/signed_dispatcher.cc @@ -6,7 +6,8 @@ #include <stdint.h> -#include "base/strings/string16.h" +#include <string> + #include "base/strings/string_util.h" #include "base/win/scoped_handle.h" #include "sandbox/win/src/crosscall_client.h" @@ -23,14 +24,15 @@ namespace sandbox { SignedDispatcher::SignedDispatcher(PolicyBase* policy_base) : policy_base_(policy_base) { static const IPCCall create_params = { - {IPC_NTCREATESECTION_TAG, {VOIDPTR_TYPE}}, + {IpcTag::NTCREATESECTION, {VOIDPTR_TYPE}}, reinterpret_cast<CallbackGeneric>(&SignedDispatcher::CreateSection)}; ipc_calls_.push_back(create_params); } -bool SignedDispatcher::SetupService(InterceptionManager* manager, int service) { - if (service == IPC_NTCREATESECTION_TAG) +bool SignedDispatcher::SetupService(InterceptionManager* manager, + IpcTag service) { + if (service == IpcTag::NTCREATESECTION) return INTERCEPT_NT(manager, NtCreateSection, CREATE_SECTION_ID, 32); return false; } @@ -45,7 +47,7 @@ bool SignedDispatcher::CreateSection(IPCInfo* ipc, HANDLE file_handle) { } base::win::ScopedHandle local_handle(local_file_handle); - base::string16 path; + std::wstring path; if (!GetPathFromHandle(local_handle.Get(), &path)) return false; const wchar_t* module_name = path.c_str(); @@ -53,7 +55,7 @@ bool SignedDispatcher::CreateSection(IPCInfo* ipc, HANDLE file_handle) { params[NameBased::NAME] = ParamPickerMake(module_name); EvalResult result = - policy_base_->EvalPolicy(IPC_NTCREATESECTION_TAG, params.GetBase()); + policy_base_->EvalPolicy(IpcTag::NTCREATESECTION, params.GetBase()); // Return operation status on the IPC. HANDLE section_handle = nullptr; diff --git a/chromium/sandbox/win/src/signed_dispatcher.h b/chromium/sandbox/win/src/signed_dispatcher.h index 7abff807ccd..38435481f6a 100644 --- a/chromium/sandbox/win/src/signed_dispatcher.h +++ b/chromium/sandbox/win/src/signed_dispatcher.h @@ -10,6 +10,7 @@ #include "base/macros.h" #include "sandbox/win/src/crosscall_server.h" #include "sandbox/win/src/interception.h" +#include "sandbox/win/src/ipc_tags.h" #include "sandbox/win/src/sandbox_policy_base.h" namespace sandbox { @@ -21,7 +22,7 @@ class SignedDispatcher : public Dispatcher { ~SignedDispatcher() override {} // Dispatcher interface. - bool SetupService(InterceptionManager* manager, int service) override; + bool SetupService(InterceptionManager* manager, IpcTag service) override; private: // Processes IPC requests coming from calls to CreateSection in the target. diff --git a/chromium/sandbox/win/src/signed_interception.cc b/chromium/sandbox/win/src/signed_interception.cc index d9b1bc86b1c..86c4b598aa3 100644 --- a/chromium/sandbox/win/src/signed_interception.cc +++ b/chromium/sandbox/win/src/signed_interception.cc @@ -58,7 +58,7 @@ TargetNtCreateSection(NtCreateSectionFunction orig_CreateSection, params[NameBased::NAME] = ParamPickerMake(const_name); // Check if this will be sent to the broker. - if (!QueryBroker(IPC_NTCREATESECTION_TAG, params.GetBase())) + if (!QueryBroker(IpcTag::NTCREATESECTION, params.GetBase())) break; if (!ValidParameter(section_handle, sizeof(HANDLE), WRITE)) @@ -68,7 +68,7 @@ TargetNtCreateSection(NtCreateSectionFunction orig_CreateSection, answer.nt_status = STATUS_INVALID_IMAGE_HASH; SharedMemIPCClient ipc(memory); ResultCode code = - CrossCall(ipc, IPC_NTCREATESECTION_TAG, file_handle, &answer); + CrossCall(ipc, IpcTag::NTCREATESECTION, file_handle, &answer); if (code != SBOX_ALL_OK) break; diff --git a/chromium/sandbox/win/src/signed_policy.cc b/chromium/sandbox/win/src/signed_policy.cc index 6b7b11f656a..f446fa668be 100644 --- a/chromium/sandbox/win/src/signed_policy.cc +++ b/chromium/sandbox/win/src/signed_policy.cc @@ -25,19 +25,19 @@ bool SignedPolicy::GenerateRules(const wchar_t* name, } base::FilePath file_path(name); - base::string16 nt_path_name; + std::wstring nt_path_name; if (!GetNtPathFromWin32Path(file_path.DirName().value().c_str(), &nt_path_name)) return false; base::FilePath nt_path(nt_path_name); - base::string16 nt_filename = nt_path.Append(file_path.BaseName()).value(); + std::wstring nt_filename = nt_path.Append(file_path.BaseName()).value(); // Create a rule to ASK_BROKER if name matches. PolicyRule signed_policy(ASK_BROKER); if (!signed_policy.AddStringMatch(IF, NameBased::NAME, nt_filename.c_str(), CASE_INSENSITIVE)) { return false; } - if (!policy->AddRule(IPC_NTCREATESECTION_TAG, &signed_policy)) { + if (!policy->AddRule(IpcTag::NTCREATESECTION, &signed_policy)) { return false; } diff --git a/chromium/sandbox/win/src/sync_dispatcher.cc b/chromium/sandbox/win/src/sync_dispatcher.cc index c5e5985cb8c..d728e1d831d 100644 --- a/chromium/sandbox/win/src/sync_dispatcher.cc +++ b/chromium/sandbox/win/src/sync_dispatcher.cc @@ -22,27 +22,28 @@ namespace sandbox { SyncDispatcher::SyncDispatcher(PolicyBase* policy_base) : policy_base_(policy_base) { static const IPCCall create_params = { - {IPC_CREATEEVENT_TAG, {WCHAR_TYPE, UINT32_TYPE, UINT32_TYPE}}, + {IpcTag::CREATEEVENT, {WCHAR_TYPE, UINT32_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>(&SyncDispatcher::CreateEvent)}; static const IPCCall open_params = { - {IPC_OPENEVENT_TAG, {WCHAR_TYPE, UINT32_TYPE}}, + {IpcTag::OPENEVENT, {WCHAR_TYPE, UINT32_TYPE}}, reinterpret_cast<CallbackGeneric>(&SyncDispatcher::OpenEvent)}; ipc_calls_.push_back(create_params); ipc_calls_.push_back(open_params); } -bool SyncDispatcher::SetupService(InterceptionManager* manager, int service) { - if (service == IPC_CREATEEVENT_TAG) { +bool SyncDispatcher::SetupService(InterceptionManager* manager, + IpcTag service) { + if (service == IpcTag::CREATEEVENT) { return INTERCEPT_NT(manager, NtCreateEvent, CREATE_EVENT_ID, 24); } - return (service == IPC_OPENEVENT_TAG) && + return (service == IpcTag::OPENEVENT) && INTERCEPT_NT(manager, NtOpenEvent, OPEN_EVENT_ID, 16); } bool SyncDispatcher::CreateEvent(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t event_type, uint32_t initial_state) { const wchar_t* event_name = name->c_str(); @@ -50,7 +51,7 @@ bool SyncDispatcher::CreateEvent(IPCInfo* ipc, params[NameBased::NAME] = ParamPickerMake(event_name); EvalResult result = - policy_base_->EvalPolicy(IPC_CREATEEVENT_TAG, params.GetBase()); + policy_base_->EvalPolicy(IpcTag::CREATEEVENT, params.GetBase()); HANDLE handle = nullptr; // Return operation status on the IPC. ipc->return_info.nt_status = SyncPolicy::CreateEventAction( @@ -60,7 +61,7 @@ bool SyncDispatcher::CreateEvent(IPCInfo* ipc, } bool SyncDispatcher::OpenEvent(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t desired_access) { const wchar_t* event_name = name->c_str(); @@ -69,7 +70,7 @@ bool SyncDispatcher::OpenEvent(IPCInfo* ipc, params[OpenEventParams::ACCESS] = ParamPickerMake(desired_access); EvalResult result = - policy_base_->EvalPolicy(IPC_OPENEVENT_TAG, params.GetBase()); + policy_base_->EvalPolicy(IpcTag::OPENEVENT, params.GetBase()); HANDLE handle = nullptr; // Return operation status on the IPC. ipc->return_info.nt_status = SyncPolicy::OpenEventAction( diff --git a/chromium/sandbox/win/src/sync_dispatcher.h b/chromium/sandbox/win/src/sync_dispatcher.h index c669ad8a4c3..d4bc025a0b6 100644 --- a/chromium/sandbox/win/src/sync_dispatcher.h +++ b/chromium/sandbox/win/src/sync_dispatcher.h @@ -7,9 +7,11 @@ #include <stdint.h> +#include <string> + #include "base/macros.h" -#include "base/strings/string16.h" #include "sandbox/win/src/crosscall_server.h" +#include "sandbox/win/src/ipc_tags.h" #include "sandbox/win/src/sandbox_policy_base.h" namespace sandbox { @@ -21,17 +23,17 @@ class SyncDispatcher : public Dispatcher { ~SyncDispatcher() override {} // Dispatcher interface. - bool SetupService(InterceptionManager* manager, int service) override; + bool SetupService(InterceptionManager* manager, IpcTag service) override; private: // Processes IPC requests coming from calls to CreateEvent in the target. bool CreateEvent(IPCInfo* ipc, - base::string16* name, + std::wstring* name, uint32_t event_type, uint32_t initial_state); // Processes IPC requests coming from calls to OpenEvent in the target. - bool OpenEvent(IPCInfo* ipc, base::string16* name, uint32_t desired_access); + bool OpenEvent(IPCInfo* ipc, std::wstring* name, uint32_t desired_access); PolicyBase* policy_base_; DISALLOW_COPY_AND_ASSIGN(SyncDispatcher); diff --git a/chromium/sandbox/win/src/sync_interception.cc b/chromium/sandbox/win/src/sync_interception.cc index cbf5cb0af70..d062ecb7b35 100644 --- a/chromium/sandbox/win/src/sync_interception.cc +++ b/chromium/sandbox/win/src/sync_interception.cc @@ -25,11 +25,11 @@ ResultCode ProxyCreateEvent(LPCWSTR name, CountedParameterSet<NameBased> params; params[NameBased::NAME] = ParamPickerMake(name); - if (!QueryBroker(IPC_CREATEEVENT_TAG, params.GetBase())) + if (!QueryBroker(IpcTag::CREATEEVENT, params.GetBase())) return SBOX_ERROR_GENERIC; SharedMemIPCClient ipc(ipc_memory); - ResultCode code = CrossCall(ipc, IPC_CREATEEVENT_TAG, name, event_type, + ResultCode code = CrossCall(ipc, IpcTag::CREATEEVENT, name, event_type, initial_state, answer); return code; } @@ -42,12 +42,12 @@ ResultCode ProxyOpenEvent(LPCWSTR name, params[OpenEventParams::NAME] = ParamPickerMake(name); params[OpenEventParams::ACCESS] = ParamPickerMake(desired_access); - if (!QueryBroker(IPC_OPENEVENT_TAG, params.GetBase())) + if (!QueryBroker(IpcTag::OPENEVENT, params.GetBase())) return SBOX_ERROR_GENERIC; SharedMemIPCClient ipc(ipc_memory); ResultCode code = - CrossCall(ipc, IPC_OPENEVENT_TAG, name, desired_access, answer); + CrossCall(ipc, IpcTag::OPENEVENT, name, desired_access, answer); return code; } diff --git a/chromium/sandbox/win/src/sync_policy.cc b/chromium/sandbox/win/src/sync_policy.cc index 22977fa4c0b..cdc34dd2418 100644 --- a/chromium/sandbox/win/src/sync_policy.cc +++ b/chromium/sandbox/win/src/sync_policy.cc @@ -23,9 +23,9 @@ namespace sandbox { // Provides functionality to resolve a symbolic link within the object // directory passed in. -NTSTATUS ResolveSymbolicLink(const base::string16& directory_name, - const base::string16& name, - base::string16* target) { +NTSTATUS ResolveSymbolicLink(const std::wstring& directory_name, + const std::wstring& name, + std::wstring* target) { NtOpenDirectoryObjectFunction NtOpenDirectoryObject = nullptr; ResolveNTFunctionPtr("NtOpenDirectoryObject", &NtOpenDirectoryObject); @@ -98,7 +98,7 @@ NTSTATUS GetBaseNamedObjectsDirectory(HANDLE* directory) { DWORD session_id = 0; ProcessIdToSessionId(::GetCurrentProcessId(), &session_id); - base::string16 base_named_objects_path; + std::wstring base_named_objects_path; NTSTATUS status = ResolveSymbolicLink(L"\\Sessions\\BNOLINKS", base::StringPrintf(L"%d", session_id), @@ -122,7 +122,7 @@ NTSTATUS GetBaseNamedObjectsDirectory(HANDLE* directory) { bool SyncPolicy::GenerateRules(const wchar_t* name, TargetPolicy::Semantics semantics, LowLevelPolicy* policy) { - base::string16 mod_name(name); + std::wstring mod_name(name); if (mod_name.empty()) { return false; } @@ -149,7 +149,7 @@ bool SyncPolicy::GenerateRules(const wchar_t* name, open.AddNumberMatch(IF_NOT, OpenEventParams::ACCESS, restricted_flags, AND); } - if (!policy->AddRule(IPC_OPENEVENT_TAG, &open)) + if (!policy->AddRule(IpcTag::OPENEVENT, &open)) return false; // If it's not a read only, add the create rule. @@ -158,7 +158,7 @@ bool SyncPolicy::GenerateRules(const wchar_t* name, if (!create.AddStringMatch(IF, NameBased::NAME, name, CASE_INSENSITIVE)) return false; - if (!policy->AddRule(IPC_CREATEEVENT_TAG, &create)) + if (!policy->AddRule(IpcTag::CREATEEVENT, &create)) return false; } @@ -167,7 +167,7 @@ bool SyncPolicy::GenerateRules(const wchar_t* name, NTSTATUS SyncPolicy::CreateEventAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& event_name, + const std::wstring& event_name, uint32_t event_type, uint32_t initial_state, HANDLE* handle) { @@ -206,7 +206,7 @@ NTSTATUS SyncPolicy::CreateEventAction(EvalResult eval_result, NTSTATUS SyncPolicy::OpenEventAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& event_name, + const std::wstring& event_name, uint32_t desired_access, HANDLE* handle) { NtOpenEventFunction NtOpenEvent = nullptr; diff --git a/chromium/sandbox/win/src/sync_policy.h b/chromium/sandbox/win/src/sync_policy.h index 6cb9d830545..2eb4124a823 100644 --- a/chromium/sandbox/win/src/sync_policy.h +++ b/chromium/sandbox/win/src/sync_policy.h @@ -9,7 +9,6 @@ #include <string> -#include "base/strings/string16.h" #include "sandbox/win/src/crosscall_server.h" #include "sandbox/win/src/nt_internals.h" #include "sandbox/win/src/policy_low_level.h" @@ -34,13 +33,13 @@ class SyncPolicy { // eval_result is the desired policy action to accomplish. static NTSTATUS CreateEventAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& event_name, + const std::wstring& event_name, uint32_t event_type, uint32_t initial_state, HANDLE* handle); static NTSTATUS OpenEventAction(EvalResult eval_result, const ClientInfo& client_info, - const base::string16& event_name, + const std::wstring& event_name, uint32_t desired_access, HANDLE* handle); }; diff --git a/chromium/sandbox/win/src/target_services.cc b/chromium/sandbox/win/src/target_services.cc index f35dc39daef..b6b03b34809 100644 --- a/chromium/sandbox/win/src/target_services.cc +++ b/chromium/sandbox/win/src/target_services.cc @@ -164,7 +164,7 @@ TargetServicesBase* TargetServicesBase::GetInstance() { return g_target_services; } -// The broker services a 'test' IPC service with the IPC_PING_TAG tag. +// The broker services a 'test' IPC service with the PING tag. bool TargetServicesBase::TestIPCPing(int version) { void* memory = GetGlobalIPCMemory(); if (!memory) @@ -175,7 +175,7 @@ bool TargetServicesBase::TestIPCPing(int version) { if (1 == version) { uint32_t tick1 = ::GetTickCount(); uint32_t cookie = 717115; - ResultCode code = CrossCall(ipc, IPC_PING1_TAG, cookie, &answer); + ResultCode code = CrossCall(ipc, IpcTag::PING1, cookie, &answer); if (SBOX_ALL_OK != code) { return false; @@ -201,7 +201,7 @@ bool TargetServicesBase::TestIPCPing(int version) { } else if (2 == version) { uint32_t cookie = 717111; InOutCountedBuffer counted_buffer(&cookie, sizeof(cookie)); - ResultCode code = CrossCall(ipc, IPC_PING2_TAG, counted_buffer, &answer); + ResultCode code = CrossCall(ipc, IpcTag::PING2, counted_buffer, &answer); if (SBOX_ALL_OK != code) { return false; diff --git a/chromium/sandbox/win/src/top_level_dispatcher.cc b/chromium/sandbox/win/src/top_level_dispatcher.cc index f245802d64b..8fd610a5af3 100644 --- a/chromium/sandbox/win/src/top_level_dispatcher.cc +++ b/chromium/sandbox/win/src/top_level_dispatcher.cc @@ -29,57 +29,66 @@ TopLevelDispatcher::TopLevelDispatcher(PolicyBase* policy) : policy_(policy) { Dispatcher* dispatcher; dispatcher = new FilesystemDispatcher(policy_); - ipc_targets_[IPC_NTCREATEFILE_TAG] = dispatcher; - ipc_targets_[IPC_NTOPENFILE_TAG] = dispatcher; - ipc_targets_[IPC_NTSETINFO_RENAME_TAG] = dispatcher; - ipc_targets_[IPC_NTQUERYATTRIBUTESFILE_TAG] = dispatcher; - ipc_targets_[IPC_NTQUERYFULLATTRIBUTESFILE_TAG] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::NTCREATEFILE)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::NTOPENFILE)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::NTSETINFO_RENAME)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::NTQUERYATTRIBUTESFILE)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::NTQUERYFULLATTRIBUTESFILE)] = + dispatcher; filesystem_dispatcher_.reset(dispatcher); dispatcher = new NamedPipeDispatcher(policy_); - ipc_targets_[IPC_CREATENAMEDPIPEW_TAG] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::CREATENAMEDPIPEW)] = dispatcher; named_pipe_dispatcher_.reset(dispatcher); dispatcher = new ThreadProcessDispatcher(policy_); - ipc_targets_[IPC_NTOPENTHREAD_TAG] = dispatcher; - ipc_targets_[IPC_NTOPENPROCESS_TAG] = dispatcher; - ipc_targets_[IPC_CREATEPROCESSW_TAG] = dispatcher; - ipc_targets_[IPC_NTOPENPROCESSTOKEN_TAG] = dispatcher; - ipc_targets_[IPC_NTOPENPROCESSTOKENEX_TAG] = dispatcher; - ipc_targets_[IPC_CREATETHREAD_TAG] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::NTOPENTHREAD)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::NTOPENPROCESS)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::CREATEPROCESSW)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::NTOPENPROCESSTOKEN)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::NTOPENPROCESSTOKENEX)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::CREATETHREAD)] = dispatcher; thread_process_dispatcher_.reset(dispatcher); dispatcher = new SyncDispatcher(policy_); - ipc_targets_[IPC_CREATEEVENT_TAG] = dispatcher; - ipc_targets_[IPC_OPENEVENT_TAG] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::CREATEEVENT)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::OPENEVENT)] = dispatcher; sync_dispatcher_.reset(dispatcher); dispatcher = new RegistryDispatcher(policy_); - ipc_targets_[IPC_NTCREATEKEY_TAG] = dispatcher; - ipc_targets_[IPC_NTOPENKEY_TAG] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::NTCREATEKEY)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::NTOPENKEY)] = dispatcher; registry_dispatcher_.reset(dispatcher); dispatcher = new ProcessMitigationsWin32KDispatcher(policy_); - ipc_targets_[IPC_GDI_GDIDLLINITIALIZE_TAG] = dispatcher; - ipc_targets_[IPC_GDI_GETSTOCKOBJECT_TAG] = dispatcher; - ipc_targets_[IPC_USER_REGISTERCLASSW_TAG] = dispatcher; - ipc_targets_[IPC_USER_ENUMDISPLAYMONITORS_TAG] = dispatcher; - ipc_targets_[IPC_USER_ENUMDISPLAYDEVICES_TAG] = dispatcher; - ipc_targets_[IPC_USER_GETMONITORINFO_TAG] = dispatcher; - ipc_targets_[IPC_GDI_CREATEOPMPROTECTEDOUTPUTS_TAG] = dispatcher; - ipc_targets_[IPC_GDI_GETCERTIFICATE_TAG] = dispatcher; - ipc_targets_[IPC_GDI_GETCERTIFICATESIZE_TAG] = dispatcher; - ipc_targets_[IPC_GDI_DESTROYOPMPROTECTEDOUTPUT_TAG] = dispatcher; - ipc_targets_[IPC_GDI_CONFIGUREOPMPROTECTEDOUTPUT_TAG] = dispatcher; - ipc_targets_[IPC_GDI_GETOPMINFORMATION_TAG] = dispatcher; - ipc_targets_[IPC_GDI_GETOPMRANDOMNUMBER_TAG] = dispatcher; - ipc_targets_[IPC_GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE_TAG] = + ipc_targets_[static_cast<size_t>(IpcTag::GDI_GDIDLLINITIALIZE)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::GDI_GETSTOCKOBJECT)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::USER_REGISTERCLASSW)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::USER_ENUMDISPLAYMONITORS)] = + dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::USER_ENUMDISPLAYDEVICES)] = + dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::USER_GETMONITORINFO)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::GDI_CREATEOPMPROTECTEDOUTPUTS)] = + dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::GDI_GETCERTIFICATE)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::GDI_GETCERTIFICATESIZE)] = + dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::GDI_DESTROYOPMPROTECTEDOUTPUT)] = + dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::GDI_CONFIGUREOPMPROTECTEDOUTPUT)] = + dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::GDI_GETOPMINFORMATION)] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::GDI_GETOPMRANDOMNUMBER)] = dispatcher; - ipc_targets_[IPC_GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS_TAG] = dispatcher; + ipc_targets_[static_cast<size_t>( + IpcTag::GDI_GETSUGGESTEDOPMPROTECTEDOUTPUTARRAYSIZE)] = dispatcher; + ipc_targets_[static_cast<size_t>( + IpcTag::GDI_SETOPMSIGNINGKEYANDSEQUENCENUMBERS)] = dispatcher; process_mitigations_win32k_dispatcher_.reset(dispatcher); dispatcher = new SignedDispatcher(policy_); - ipc_targets_[IPC_NTCREATESECTION_TAG] = dispatcher; + ipc_targets_[static_cast<size_t>(IpcTag::NTCREATESECTION)] = dispatcher; signed_dispatcher_.reset(dispatcher); } @@ -91,8 +100,8 @@ TopLevelDispatcher::~TopLevelDispatcher() {} Dispatcher* TopLevelDispatcher::OnMessageReady(IPCParams* ipc, CallbackGeneric* callback) { DCHECK(callback); - static const IPCParams ping1 = {IPC_PING1_TAG, {UINT32_TYPE}}; - static const IPCParams ping2 = {IPC_PING2_TAG, {INOUTPTR_TYPE}}; + static const IPCParams ping1 = {IpcTag::PING1, {UINT32_TYPE}}; + static const IPCParams ping2 = {IpcTag::PING2, {INOUTPTR_TYPE}}; if (ping1.Matches(ipc) || ping2.Matches(ipc)) { *callback = reinterpret_cast<CallbackGeneric>( @@ -110,8 +119,8 @@ Dispatcher* TopLevelDispatcher::OnMessageReady(IPCParams* ipc, // Delegate to the appropriate dispatcher. bool TopLevelDispatcher::SetupService(InterceptionManager* manager, - int service) { - if (IPC_PING1_TAG == service || IPC_PING2_TAG == service) + IpcTag service) { + if (IpcTag::PING1 == service || IpcTag::PING2 == service) return true; Dispatcher* dispatcher = GetDispatcher(service); @@ -122,12 +131,12 @@ bool TopLevelDispatcher::SetupService(InterceptionManager* manager, return dispatcher->SetupService(manager, service); } -// We service IPC_PING_TAG message which is a way to test a round trip of the +// We service PING message which is a way to test a round trip of the // IPC subsystem. We receive a integer cookie and we are expected to return the // cookie times two (or three) and the current tick count. bool TopLevelDispatcher::Ping(IPCInfo* ipc, void* arg1) { switch (ipc->ipc_tag) { - case IPC_PING1_TAG: { + case IpcTag::PING1: { IPCInt ipc_int(arg1); uint32_t cookie = ipc_int.As32Bit(); ipc->return_info.extended_count = 2; @@ -135,7 +144,7 @@ bool TopLevelDispatcher::Ping(IPCInfo* ipc, void* arg1) { ipc->return_info.extended[1].unsigned_int = 2 * cookie; return true; } - case IPC_PING2_TAG: { + case IpcTag::PING2: { CountedBuffer* io_buffer = reinterpret_cast<CountedBuffer*>(arg1); if (sizeof(uint32_t) != io_buffer->Size()) return false; @@ -149,11 +158,11 @@ bool TopLevelDispatcher::Ping(IPCInfo* ipc, void* arg1) { } } -Dispatcher* TopLevelDispatcher::GetDispatcher(int ipc_tag) { - if (ipc_tag >= IPC_LAST_TAG || ipc_tag <= IPC_UNUSED_TAG) +Dispatcher* TopLevelDispatcher::GetDispatcher(IpcTag ipc_tag) { + if (ipc_tag >= IpcTag::LAST || ipc_tag <= IpcTag::UNUSED) return nullptr; - return ipc_targets_[ipc_tag]; + return ipc_targets_[static_cast<size_t>(ipc_tag)]; } } // namespace sandbox diff --git a/chromium/sandbox/win/src/top_level_dispatcher.h b/chromium/sandbox/win/src/top_level_dispatcher.h index 36f71aeb06b..b440d86f1df 100644 --- a/chromium/sandbox/win/src/top_level_dispatcher.h +++ b/chromium/sandbox/win/src/top_level_dispatcher.h @@ -25,14 +25,14 @@ class TopLevelDispatcher : public Dispatcher { Dispatcher* OnMessageReady(IPCParams* ipc, CallbackGeneric* callback) override; - bool SetupService(InterceptionManager* manager, int service) override; + bool SetupService(InterceptionManager* manager, IpcTag service) override; private: // Test IPC provider. bool Ping(IPCInfo* ipc, void* cookie); // Returns a dispatcher from ipc_targets_. - Dispatcher* GetDispatcher(int ipc_tag); + Dispatcher* GetDispatcher(IpcTag ipc_tag); PolicyBase* policy_; std::unique_ptr<Dispatcher> filesystem_dispatcher_; @@ -43,7 +43,7 @@ class TopLevelDispatcher : public Dispatcher { std::unique_ptr<Dispatcher> handle_dispatcher_; std::unique_ptr<Dispatcher> process_mitigations_win32k_dispatcher_; std::unique_ptr<Dispatcher> signed_dispatcher_; - Dispatcher* ipc_targets_[IPC_LAST_TAG]; + Dispatcher* ipc_targets_[kMaxIpcTag]; DISALLOW_COPY_AND_ASSIGN(TopLevelDispatcher); }; diff --git a/chromium/sandbox/win/src/win_utils.cc b/chromium/sandbox/win/src/win_utils.cc index 4b80c6eda77..85be8d16f27 100644 --- a/chromium/sandbox/win/src/win_utils.cc +++ b/chromium/sandbox/win/src/win_utils.cc @@ -10,11 +10,11 @@ #include <map> #include <memory> +#include <string> #include <vector> #include "base/numerics/safe_math.h" #include "base/stl_util.h" -#include "base/strings/string16.h" #include "base/strings/string_util.h" #include "base/win/pe_image.h" #include "sandbox/win/src/internal_types.h" @@ -47,25 +47,25 @@ const KnownReservedKey kKnownKey[] = { {L"HKEY_DYN_DATA", HKEY_DYN_DATA}}; // These functions perform case independent path comparisons. -bool EqualPath(const base::string16& first, const base::string16& second) { +bool EqualPath(const std::wstring& first, const std::wstring& second) { return _wcsicmp(first.c_str(), second.c_str()) == 0; } -bool EqualPath(const base::string16& first, +bool EqualPath(const std::wstring& first, size_t first_offset, - const base::string16& second, + const std::wstring& second, size_t second_offset) { return _wcsicmp(first.c_str() + first_offset, second.c_str() + second_offset) == 0; } -bool EqualPath(const base::string16& first, +bool EqualPath(const std::wstring& first, const wchar_t* second, size_t second_len) { return _wcsnicmp(first.c_str(), second, second_len) == 0; } -bool EqualPath(const base::string16& first, +bool EqualPath(const std::wstring& first, size_t first_offset, const wchar_t* second, size_t second_len) { @@ -74,7 +74,7 @@ bool EqualPath(const base::string16& first, // Returns true if |path| starts with "\??\" and returns a path without that // component. -bool IsNTPath(const base::string16& path, base::string16* trimmed_path) { +bool IsNTPath(const std::wstring& path, std::wstring* trimmed_path) { if ((path.size() < sandbox::kNTPrefixLen) || !EqualPath(path, sandbox::kNTPrefix, sandbox::kNTPrefixLen)) { *trimmed_path = path; @@ -87,7 +87,7 @@ bool IsNTPath(const base::string16& path, base::string16* trimmed_path) { // Returns true if |path| starts with "\Device\" and returns a path without that // component. -bool IsDevicePath(const base::string16& path, base::string16* trimmed_path) { +bool IsDevicePath(const std::wstring& path, std::wstring* trimmed_path) { if ((path.size() < sandbox::kNTDevicePrefixLen) || (!EqualPath(path, sandbox::kNTDevicePrefix, sandbox::kNTDevicePrefixLen))) { @@ -101,13 +101,13 @@ bool IsDevicePath(const base::string16& path, base::string16* trimmed_path) { // Returns the offset to the path seperator following // "\Device\HarddiskVolumeX" in |path|. -size_t PassHarddiskVolume(const base::string16& path) { +size_t PassHarddiskVolume(const std::wstring& path) { static constexpr wchar_t pattern[] = L"\\Device\\HarddiskVolume"; const size_t patternLen = base::size(pattern) - 1; // First, check for |pattern|. if ((path.size() < patternLen) || (!EqualPath(path, pattern, patternLen))) - return base::string16::npos; + return std::wstring::npos; // Find the next path separator, after the pattern match. return path.find_first_of(L'\\', patternLen - 1); @@ -115,11 +115,11 @@ size_t PassHarddiskVolume(const base::string16& path) { // Returns true if |path| starts with "\Device\HarddiskVolumeX\" and returns a // path without that component. |removed| will hold the prefix removed. -bool IsDeviceHarddiskPath(const base::string16& path, - base::string16* trimmed_path, - base::string16* removed) { +bool IsDeviceHarddiskPath(const std::wstring& path, + std::wstring* trimmed_path, + std::wstring* removed) { size_t offset = PassHarddiskVolume(path); - if (offset == base::string16::npos) + if (offset == std::wstring::npos) return false; // Remove up to and including the path separator. @@ -129,7 +129,7 @@ bool IsDeviceHarddiskPath(const base::string16& path, return true; } -bool StartsWithDriveLetter(const base::string16& path) { +bool StartsWithDriveLetter(const std::wstring& path) { if (path.size() < kDriveLetterLen) return false; @@ -140,7 +140,7 @@ bool StartsWithDriveLetter(const base::string16& path) { } // Removes "\\\\.\\" from the path. -void RemoveImpliedDevice(base::string16* path) { +void RemoveImpliedDevice(std::wstring* path) { if (EqualPath(*path, kNTDotPrefix, kNTDotPrefixLen)) *path = path->substr(kNTDotPrefixLen); } @@ -150,7 +150,7 @@ void RemoveImpliedDevice(base::string16* path) { namespace sandbox { // Returns true if the provided path points to a pipe. -bool IsPipe(const base::string16& path) { +bool IsPipe(const std::wstring& path) { size_t start = 0; if (EqualPath(path, sandbox::kNTPrefix, sandbox::kNTPrefixLen)) start = sandbox::kNTPrefixLen; @@ -162,7 +162,7 @@ bool IsPipe(const base::string16& path) { return EqualPath(path, start, kPipe, base::size(kPipe) - 1); } -HKEY GetReservedKeyFromName(const base::string16& name) { +HKEY GetReservedKeyFromName(const std::wstring& name) { for (size_t i = 0; i < base::size(kKnownKey); ++i) { if (name == kKnownKey[i].name) return kKnownKey[i].key; @@ -171,7 +171,7 @@ HKEY GetReservedKeyFromName(const base::string16& name) { return nullptr; } -bool ResolveRegistryName(base::string16 name, base::string16* resolved_name) { +bool ResolveRegistryName(std::wstring name, std::wstring* resolved_name) { for (size_t i = 0; i < base::size(kKnownKey); ++i) { if (name.find(kKnownKey[i].name) == 0) { HKEY key; @@ -199,12 +199,12 @@ bool ResolveRegistryName(base::string16 name, base::string16* resolved_name) { // \??\c:\some\foo\bar // \Device\HarddiskVolume0\some\foo\bar // \??\HarddiskVolume0\some\foo\bar -DWORD IsReparsePoint(const base::string16& full_path) { +DWORD IsReparsePoint(const std::wstring& full_path) { // Check if it's a pipe. We can't query the attributes of a pipe. if (IsPipe(full_path)) return ERROR_NOT_A_REPARSE_POINT; - base::string16 path; + std::wstring path; bool nt_path = IsNTPath(full_path, &path); bool has_drive = StartsWithDriveLetter(path); bool is_device_path = IsDevicePath(path, &path); @@ -214,11 +214,11 @@ DWORD IsReparsePoint(const base::string16& full_path) { bool added_implied_device = false; if (!has_drive) { - path = base::string16(kNTDotPrefix) + path; + path = std::wstring(kNTDotPrefix) + path; added_implied_device = true; } - base::string16::size_type last_pos = base::string16::npos; + std::wstring::size_type last_pos = std::wstring::npos; bool passed_once = false; do { @@ -256,11 +256,11 @@ bool SameObject(HANDLE handle, const wchar_t* full_path) { if (IsPipe(full_path)) return true; - base::string16 actual_path; + std::wstring actual_path; if (!GetPathFromHandle(handle, &actual_path)) return false; - base::string16 path(full_path); + std::wstring path(full_path); DCHECK_NT(!path.empty()); // This may end with a backslash. @@ -276,7 +276,7 @@ bool SameObject(HANDLE handle, const wchar_t* full_path) { bool has_drive = StartsWithDriveLetter(path); if (!has_drive && nt_path) { - base::string16 simple_actual_path; + std::wstring simple_actual_path; if (!IsDevicePath(actual_path, &simple_actual_path)) return false; @@ -317,23 +317,23 @@ bool SameObject(HANDLE handle, const wchar_t* full_path) { // Just make a best effort here. There are lots of corner cases that we're // not expecting - and will fail to make long. -bool ConvertToLongPath(base::string16* native_path, - const base::string16* drive_letter) { +bool ConvertToLongPath(std::wstring* native_path, + const std::wstring* drive_letter) { if (IsPipe(*native_path)) return true; bool is_device_harddisk_path = false; bool is_nt_path = false; bool added_implied_device = false; - base::string16 temp_path; - base::string16 to_restore; + std::wstring temp_path; + std::wstring to_restore; // Process a few prefix types. if (IsNTPath(*native_path, &temp_path)) { // "\??\" if (!StartsWithDriveLetter(temp_path)) { // Prepend with "\\.\". - temp_path = base::string16(kNTDotPrefix) + temp_path; + temp_path = std::wstring(kNTDotPrefix) + temp_path; added_implied_device = true; } is_nt_path = true; @@ -370,12 +370,12 @@ bool ConvertToLongPath(base::string16* native_path, ERROR_PATH_NOT_FOUND == last_error || ERROR_INVALID_NAME == last_error)) { // The file does not exist, but maybe a sub path needs to be expanded. - base::string16::size_type last_slash = temp_path.rfind(L'\\'); - if (base::string16::npos == last_slash) + std::wstring::size_type last_slash = temp_path.rfind(L'\\'); + if (std::wstring::npos == last_slash) return false; - base::string16 begin = temp_path.substr(0, last_slash); - base::string16 end = temp_path.substr(last_slash); + std::wstring begin = temp_path.substr(0, last_slash); + std::wstring end = temp_path.substr(last_slash); if (!ConvertToLongPath(&begin)) return false; @@ -409,7 +409,7 @@ bool ConvertToLongPath(base::string16* native_path, return false; } -bool GetPathFromHandle(HANDLE handle, base::string16* path) { +bool GetPathFromHandle(HANDLE handle, std::wstring* path) { NtQueryObjectFunction NtQueryObject = nullptr; ResolveNTFunctionPtr("NtQueryObject", &NtQueryObject); @@ -439,8 +439,7 @@ bool GetPathFromHandle(HANDLE handle, base::string16* path) { return true; } -bool GetNtPathFromWin32Path(const base::string16& path, - base::string16* nt_path) { +bool GetNtPathFromWin32Path(const std::wstring& path, std::wstring* nt_path) { HANDLE file = ::CreateFileW( path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); diff --git a/chromium/sandbox/win/src/win_utils.h b/chromium/sandbox/win/src/win_utils.h index 28ab11b00a8..2e79eeb78bb 100644 --- a/chromium/sandbox/win/src/win_utils.h +++ b/chromium/sandbox/win/src/win_utils.h @@ -12,7 +12,6 @@ #include "base/macros.h" #include "base/stl_util.h" -#include "base/strings/string16.h" #include "sandbox/win/src/nt_internals.h" namespace sandbox { @@ -80,37 +79,36 @@ struct LocalFreeDeleter { // false and argument is not modified. // - If passing in a short native device path (\Device\HarddiskVolumeX\path~1), // a drive letter string (c:\) must also be provided. -bool ConvertToLongPath(base::string16* path, - const base::string16* drive_letter = nullptr); +bool ConvertToLongPath(std::wstring* path, + const std::wstring* drive_letter = nullptr); // Returns ERROR_SUCCESS if the path contains a reparse point, // ERROR_NOT_A_REPARSE_POINT if there's no reparse point in this path, or an // error code when the function fails. // This function is not smart. It looks for each element in the path and // returns true if any of them is a reparse point. -DWORD IsReparsePoint(const base::string16& full_path); +DWORD IsReparsePoint(const std::wstring& full_path); // Returns true if the handle corresponds to the object pointed by this path. bool SameObject(HANDLE handle, const wchar_t* full_path); // Resolves a handle to an nt path. Returns true if the handle can be resolved. -bool GetPathFromHandle(HANDLE handle, base::string16* path); +bool GetPathFromHandle(HANDLE handle, std::wstring* path); // Resolves a win32 path to an nt path using GetPathFromHandle. The path must // exist. Returs true if the translation was succesful. -bool GetNtPathFromWin32Path(const base::string16& path, - base::string16* nt_path); +bool GetNtPathFromWin32Path(const std::wstring& path, std::wstring* nt_path); // Translates a reserved key name to its handle. // For example "HKEY_LOCAL_MACHINE" returns HKEY_LOCAL_MACHINE. // Returns nullptr if the name does not represent any reserved key name. -HKEY GetReservedKeyFromName(const base::string16& name); +HKEY GetReservedKeyFromName(const std::wstring& name); // Resolves a user-readable registry path to a system-readable registry path. // For example, HKEY_LOCAL_MACHINE\\Software\\microsoft is translated to // \\registry\\machine\\software\\microsoft. Returns false if the path // cannot be resolved. -bool ResolveRegistryName(base::string16 name, base::string16* resolved_name); +bool ResolveRegistryName(std::wstring name, std::wstring* resolved_name); // Writes |length| bytes from the provided |buffer| into the address space of // |child_process|, at the specified |address|, preserving the original write @@ -132,7 +130,7 @@ bool CopyToChildMemory(HANDLE child, void** remote_buffer); // Returns true if the provided path points to a pipe. -bool IsPipe(const base::string16& path); +bool IsPipe(const std::wstring& path); // Converts a NTSTATUS code to a Win32 error code. DWORD GetLastErrorFromNtStatus(NTSTATUS status); diff --git a/chromium/sandbox/win/src/win_utils_unittest.cc b/chromium/sandbox/win/src/win_utils_unittest.cc index 507ceafdd2d..36e7d4dd1e5 100644 --- a/chromium/sandbox/win/src/win_utils_unittest.cc +++ b/chromium/sandbox/win/src/win_utils_unittest.cc @@ -75,11 +75,11 @@ TEST(WinUtils, IsReparsePoint) { EXPECT_EQ(static_cast<DWORD>(ERROR_NOT_A_REPARSE_POINT), IsReparsePoint(my_folder)); - base::string16 not_found = base::string16(my_folder) + L"\\foo\\bar"; + std::wstring not_found = std::wstring(my_folder) + L"\\foo\\bar"; EXPECT_EQ(static_cast<DWORD>(ERROR_NOT_A_REPARSE_POINT), IsReparsePoint(not_found)); - base::string16 new_file = base::string16(my_folder) + L"\\foo"; + std::wstring new_file = std::wstring(my_folder) + L"\\foo"; EXPECT_EQ(static_cast<DWORD>(ERROR_NOT_A_REPARSE_POINT), IsReparsePoint(new_file)); @@ -89,7 +89,7 @@ TEST(WinUtils, IsReparsePoint) { OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); EXPECT_NE(INVALID_HANDLE_VALUE, dir); - base::string16 temp_dir_nt = base::string16(L"\\??\\") + temp_directory; + std::wstring temp_dir_nt = std::wstring(L"\\??\\") + temp_directory; EXPECT_TRUE(SetReparsePoint(dir, temp_dir_nt.c_str())); EXPECT_EQ(static_cast<DWORD>(ERROR_SUCCESS), IsReparsePoint(new_file)); @@ -112,17 +112,16 @@ TEST(WinUtils, SameObject) { ASSERT_TRUE(::DeleteFile(my_folder)); ASSERT_TRUE(::CreateDirectory(my_folder, nullptr)); - base::string16 folder(my_folder); - base::string16 file_name = folder + L"\\foo.txt"; + std::wstring folder(my_folder); + std::wstring file_name = folder + L"\\foo.txt"; const ULONG kSharing = FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE; base::win::ScopedHandle file(CreateFile(file_name.c_str(), GENERIC_WRITE, kSharing, nullptr, CREATE_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, nullptr)); EXPECT_TRUE(file.IsValid()); - base::string16 file_name_nt1 = base::string16(L"\\??\\") + file_name; - base::string16 file_name_nt2 = - base::string16(L"\\??\\") + folder + L"\\FOO.txT"; + std::wstring file_name_nt1 = std::wstring(L"\\??\\") + file_name; + std::wstring file_name_nt2 = std::wstring(L"\\??\\") + folder + L"\\FOO.txT"; EXPECT_TRUE(SameObject(file.Get(), file_name_nt1.c_str())); EXPECT_TRUE(SameObject(file.Get(), file_name_nt2.c_str())); @@ -133,7 +132,7 @@ TEST(WinUtils, SameObject) { TEST(WinUtils, IsPipe) { using sandbox::IsPipe; - base::string16 pipe_name = L"\\??\\pipe\\mypipe"; + std::wstring pipe_name = L"\\??\\pipe\\mypipe"; EXPECT_TRUE(IsPipe(pipe_name)); pipe_name = L"\\??\\PiPe\\mypipe"; @@ -226,26 +225,26 @@ TEST(WinUtils, ConvertToLongPath) { // it was disabled in the filesystem setup. EXPECT_NE(temp_path.value().length(), ::wcslen(short_path)); - base::string16 short_form_native_path; - EXPECT_TRUE(sandbox::GetNtPathFromWin32Path(base::string16(short_path), + std::wstring short_form_native_path; + EXPECT_TRUE(sandbox::GetNtPathFromWin32Path(std::wstring(short_path), &short_form_native_path)); // NT short path: "\Device\HarddiskVolume4\PROGRA~1\TEST_C~1.EXE" // Test 1: convert win32 short path to long: - base::string16 test1(short_path); + std::wstring test1(short_path); EXPECT_TRUE(sandbox::ConvertToLongPath(&test1)); EXPECT_TRUE(::wcsicmp(temp_path.value().c_str(), test1.c_str()) == 0); // Expected result: "c:\Program Files\test_calc.exe" // Test 2: convert native short path to long: - base::string16 drive_letter = temp_path.value().substr(0, 3); - base::string16 test2(short_form_native_path); + std::wstring drive_letter = temp_path.value().substr(0, 3); + std::wstring test2(short_form_native_path); EXPECT_TRUE(sandbox::ConvertToLongPath(&test2, &drive_letter)); size_t index = short_form_native_path.find_first_of( L'\\', ::wcslen(L"\\Device\\HarddiskVolume")); - EXPECT_TRUE(index != base::string16::npos); - base::string16 expected_result = short_form_native_path.substr(0, index + 1); + EXPECT_TRUE(index != std::wstring::npos); + std::wstring expected_result = short_form_native_path.substr(0, index + 1); expected_result.append(temp_path.value().substr(3)); EXPECT_TRUE(::wcsicmp(expected_result.c_str(), test2.c_str()) == 0); // Expected result: "\Device\HarddiskVolumeX\Program Files\test_calc.exe" diff --git a/chromium/sandbox/win/src/window.cc b/chromium/sandbox/win/src/window.cc index 7b387f1a387..27645a90068 100644 --- a/chromium/sandbox/win/src/window.cc +++ b/chromium/sandbox/win/src/window.cc @@ -64,7 +64,7 @@ ResultCode CreateAltWindowStation(HWINSTA* winsta) { } ResultCode CreateAltDesktop(HWINSTA winsta, HDESK* desktop) { - base::string16 desktop_name = L"sbox_alternate_desktop_"; + std::wstring desktop_name = L"sbox_alternate_desktop_"; if (!winsta) { desktop_name += L"local_winstation_"; @@ -128,13 +128,13 @@ ResultCode CreateAltDesktop(HWINSTA winsta, HDESK* desktop) { return SBOX_ERROR_CANNOT_CREATE_DESKTOP; } -base::string16 GetFullDesktopName(HWINSTA winsta, HDESK desktop) { +std::wstring GetFullDesktopName(HWINSTA winsta, HDESK desktop) { if (!desktop) { NOTREACHED(); - return base::string16(); + return std::wstring(); } - base::string16 name; + std::wstring name; if (winsta) { name = base::win::GetWindowObjectName(winsta); name += L'\\'; diff --git a/chromium/sandbox/win/src/window.h b/chromium/sandbox/win/src/window.h index 35c1197def1..1fe5b6cc72c 100644 --- a/chromium/sandbox/win/src/window.h +++ b/chromium/sandbox/win/src/window.h @@ -9,7 +9,6 @@ #include <string> -#include "base/strings/string16.h" #include "sandbox/win/src/sandbox_types.h" namespace sandbox { @@ -31,7 +30,7 @@ ResultCode CreateAltDesktop(HWINSTA winsta, HDESK* desktop); // station is specified, the name is prepended with the window station name, // followed by a backslash. This name can be used as the lpDesktop parameter // to CreateProcess. -base::string16 GetFullDesktopName(HWINSTA winsta, HDESK desktop); +std::wstring GetFullDesktopName(HWINSTA winsta, HDESK desktop); } // namespace sandbox |