Commit 9ca4a5da authored by mef@chromium.org's avatar mef@chromium.org

Revert 288319 "Adding the VerifyModule function (and helpers) to..."

> Adding the VerifyModule function (and helpers) to safe browsing.
> 
> This function allows us to compare a module in memory with 
> its original on disk, and identify any differences (after 
> accounting for relocations).  The state of the module 
> (MODULE_UNKNOWN, MODULE_UNMODIFIED or MODULE_MODIFIED) is 
> returned along with a list of the possibly modified exported 
> functions of the module.
> 
> 
> BUG=401854
> 
> Review URL: https://codereview.chromium.org/406043003

TBR=krstnmnlsn@chromium.org

Review URL: https://codereview.chromium.org/458483003

Cr-Commit-Position: refs/heads/master@{#288356}
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@288356 0039d316-1c4b-4281-b951-d872f2087c98
parent 5f8d96c6
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/module_integrity_verifier_win.h"
#include "base/containers/hash_tables.h"
#include "base/files/file_path.h"
#include "base/files/memory_mapped_file.h"
#include "base/metrics/sparse_histogram.h"
#include "base/scoped_native_library.h"
#include "base/win/pe_image.h"
#include "build/build_config.h"
namespace safe_browsing {
struct ModuleVerificationState {
explicit ModuleVerificationState(HMODULE hModule);
~ModuleVerificationState();
base::win::PEImageAsData disk_peimage;
// The module's preferred base address minus the base address it actually
// loaded at.
intptr_t image_base_delta;
// The location of the disk_peimage module's code section minus that of the
// mem_peimage module's code section.
intptr_t code_section_delta;
// The bytes corrected by relocs.
base::hash_set<uintptr_t> reloc_addr;
// Set true if the relocation table contains a reloc of type that we don't
// currently handle.
bool unknown_reloc_type;
private:
DISALLOW_COPY_AND_ASSIGN(ModuleVerificationState);
};
ModuleVerificationState::ModuleVerificationState(HMODULE hModule)
: disk_peimage(hModule),
image_base_delta(0),
code_section_delta(0),
reloc_addr(),
unknown_reloc_type(false) {
}
ModuleVerificationState::~ModuleVerificationState() {
}
namespace {
struct Export {
Export(void* addr, const std::string& name);
~Export();
bool operator<(const Export& other) const;
void* addr;
std::string name;
};
Export::Export(void* addr, const std::string& name) : addr(addr), name(name) {
}
Export::~Export() {
}
bool Export::operator<(const Export& other) const {
return addr < other.addr;
}
bool ByteAccountedForByReloc(uint8_t* byte_addr,
const ModuleVerificationState& state) {
return ((state.reloc_addr.count(reinterpret_cast<uintptr_t>(byte_addr))) > 0);
}
// Checks each byte in the module's code section again the corresponding byte on
// disk, returning the number of bytes differing between the two. Also adds the
// names of any modfied functions exported by name to |modified_exports|.
// |exports| must be sorted.
int ExamineBytesDiffInMemory(uint8_t* disk_code_start,
uint8_t* mem_code_start,
uint32_t code_size,
const std::vector<Export>& exports,
const ModuleVerificationState& state,
std::set<std::string>* modified_exports) {
int bytes_different = 0;
std::vector<Export>::const_iterator export_it = exports.begin();
for (uint8_t* end = mem_code_start + code_size; mem_code_start != end;
++mem_code_start) {
if ((*disk_code_start++ != *mem_code_start) &&
!ByteAccountedForByReloc(mem_code_start, state)) {
// We get the largest export address still smaller than |addr|. It is
// possible that |addr| belongs to some nonexported function located
// between this export and the following one.
Export addr(reinterpret_cast<void*>(mem_code_start), std::string());
std::vector<Export>::const_iterator modified_export_it =
std::upper_bound(export_it, exports.end(), addr);
if (modified_export_it != exports.begin())
modified_exports->insert((modified_export_it - 1)->name);
++bytes_different;
// No later byte can belong to an earlier export.
export_it = modified_export_it;
}
}
return bytes_different;
}
// Adds to |state->reloc_addr| the bytes of the pointer at |address| that are
// corrected by adding |image_base_delta|.
void AddBytesCorrectedByReloc(uintptr_t address,
ModuleVerificationState* state) {
#if defined(ARCH_CPU_LITTLE_ENDIAN)
# define OFFSET(i) i
#else
# define OFFSET(i) (sizeof(uintptr_t) - i)
#endif
uintptr_t orig_mem_value = *reinterpret_cast<uintptr_t*>(address);
uintptr_t fixed_mem_value = orig_mem_value + state->image_base_delta;
uintptr_t disk_value =
*reinterpret_cast<uintptr_t*>(address + state->code_section_delta);
uintptr_t diff_before = orig_mem_value ^ disk_value;
uintptr_t shared_after = ~(fixed_mem_value ^ disk_value);
int i = 0;
for (uintptr_t fixed = diff_before & shared_after; fixed; fixed >>= 8, ++i) {
if (fixed & 0xFF)
state->reloc_addr.insert(address + OFFSET(i));
}
#undef OFFSET
}
bool AddrIsInCodeSection(void* address,
uint8_t* code_addr,
uint32_t code_size) {
return (code_addr <= address && address < code_addr + code_size);
}
bool EnumRelocsCallback(const base::win::PEImage& mem_peimage,
WORD type,
void* address,
void* cookie) {
ModuleVerificationState* state =
reinterpret_cast<ModuleVerificationState*>(cookie);
uint8_t* mem_code_addr = NULL;
uint8_t* disk_code_addr = NULL;
uint32_t code_size = 0;
if (!GetCodeAddrsAndSize(mem_peimage,
state->disk_peimage,
&mem_code_addr,
&disk_code_addr,
&code_size))
return false;
// If not in the code section return true to continue to the next reloc.
if (!AddrIsInCodeSection(address, mem_code_addr, code_size))
return true;
UMA_HISTOGRAM_SPARSE_SLOWLY("SafeBrowsing.ModuleBaseRelocation", type);
switch (type) {
case IMAGE_REL_BASED_HIGHLOW: {
AddBytesCorrectedByReloc(reinterpret_cast<uintptr_t>(address), state);
break;
}
case IMAGE_REL_BASED_ABSOLUTE:
// Absolute type relocations are a noop, sometimes used to pad a section
// of relocations.
break;
default: {
// TODO(krstnmnlsn): Find a reliable description of the behaviour of the
// remaining types of relocation and handle them.
state->unknown_reloc_type = true;
break;
}
}
return true;
}
bool EnumExportsCallback(const base::win::PEImage& mem_peimage,
DWORD ordinal,
DWORD hint,
LPCSTR name,
PVOID function_addr,
LPCSTR forward,
PVOID cookie) {
std::vector<Export>* exports = reinterpret_cast<std::vector<Export>*>(cookie);
if (name)
exports->push_back(Export(function_addr, std::string(name)));
return true;
}
} // namespace
bool GetCodeAddrsAndSize(const base::win::PEImage& mem_peimage,
const base::win::PEImageAsData& disk_peimage,
uint8_t** mem_code_addr,
uint8_t** disk_code_addr,
uint32_t* code_size) {
DWORD base_of_code = mem_peimage.GetNTHeaders()->OptionalHeader.BaseOfCode;
// Get the address and size of the code section in the loaded module image.
PIMAGE_SECTION_HEADER mem_code_header =
mem_peimage.GetImageSectionFromAddr(mem_peimage.RVAToAddr(base_of_code));
if (mem_code_header == NULL)
return false;
*mem_code_addr = reinterpret_cast<uint8_t*>(
mem_peimage.RVAToAddr(mem_code_header->VirtualAddress));
// If the section is padded with zeros when mapped then |VirtualSize| can be
// larger. Alternatively, |SizeOfRawData| can be rounded up to align
// according to OptionalHeader.FileAlignment.
*code_size = std::min(mem_code_header->Misc.VirtualSize,
mem_code_header->SizeOfRawData);
// Get the address of the code section in the module mapped as data from disk.
DWORD disk_code_offset = 0;
if (!mem_peimage.ImageAddrToOnDiskOffset(
reinterpret_cast<void*>(*mem_code_addr), &disk_code_offset))
return false;
*disk_code_addr =
reinterpret_cast<uint8_t*>(disk_peimage.module()) + disk_code_offset;
return true;
}
ModuleState VerifyModule(const wchar_t* module_name,
std::set<std::string>* modified_exports) {
// Get module handle, load a copy from disk as data and create PEImages.
HMODULE module_handle = NULL;
if (!GetModuleHandleEx(0, module_name, &module_handle))
return MODULE_STATE_UNKNOWN;
base::ScopedNativeLibrary native_library(module_handle);
WCHAR module_path[MAX_PATH] = {};
DWORD length =
GetModuleFileName(module_handle, module_path, arraysize(module_path));
if (!length || length == arraysize(module_path))
return MODULE_STATE_UNKNOWN;
base::MemoryMappedFile mapped_module;
if (!mapped_module.Initialize(base::FilePath(module_path)))
return MODULE_STATE_UNKNOWN;
ModuleVerificationState state(
reinterpret_cast<HMODULE>(const_cast<uint8*>(mapped_module.data())));
base::win::PEImage mem_peimage(module_handle);
if (!mem_peimage.VerifyMagic() || !state.disk_peimage.VerifyMagic())
return MODULE_STATE_UNKNOWN;
// Get the list of exports.
std::vector<Export> exports;
mem_peimage.EnumExports(EnumExportsCallback, &exports);
std::sort(exports.begin(), exports.end());
// Get the addresses of the code sections then calculate |code_section_delta|
// and |image_base_delta|.
uint8_t* mem_code_addr = NULL;
uint8_t* disk_code_addr = NULL;
uint32_t code_size = 0;
if (!GetCodeAddrsAndSize(mem_peimage,
state.disk_peimage,
&mem_code_addr,
&disk_code_addr,
&code_size))
return MODULE_STATE_UNKNOWN;
state.code_section_delta = disk_code_addr - mem_code_addr;
uint8_t* preferred_image_base = reinterpret_cast<uint8_t*>(
state.disk_peimage.GetNTHeaders()->OptionalHeader.ImageBase);
state.image_base_delta =
preferred_image_base - reinterpret_cast<uint8_t*>(mem_peimage.module());
// Get the relocations.
mem_peimage.EnumRelocs(EnumRelocsCallback, &state);
if (state.unknown_reloc_type)
return MODULE_STATE_UNKNOWN;
// Count the modified bytes (after accounting for relocs) and get the set of
// modified functions.
int num_bytes_different = ExamineBytesDiffInMemory(disk_code_addr,
mem_code_addr,
code_size,
exports,
state,
modified_exports);
return num_bytes_different ? MODULE_STATE_MODIFIED : MODULE_STATE_UNMODIFIED;
}
} // namespace safe_browsing
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SAFE_BROWSING_MODULE_INTEGRITY_VERIFIER_WIN_H_
#define CHROME_BROWSER_SAFE_BROWSING_MODULE_INTEGRITY_VERIFIER_WIN_H_
#include <stdint.h>
#include <set>
#include <string>
namespace base {
namespace win {
class PEImage;
class PEImageAsData;
} // namespace win
} // namespace base
namespace safe_browsing {
// This enum defines the possible module states VerifyModule can return.
enum ModuleState {
MODULE_STATE_UNKNOWN,
MODULE_STATE_UNMODIFIED,
MODULE_STATE_MODIFIED,
};
// Helper to grab the addresses and size of the code section of a PEImage.
// Returns two addresses: one for the dll loaded as a library, the other for the
// dll loaded as data.
bool GetCodeAddrsAndSize(const base::win::PEImage& mem_peimage,
const base::win::PEImageAsData& disk_peimage,
uint8_t** mem_code_addr,
uint8_t** disk_code_addr,
uint32_t* code_size);
// Examines the code section of the given module in memory and on disk, looking
// for unexpected differences. Returns a ModuleState and and a set of the
// possibly modified exports.
ModuleState VerifyModule(const wchar_t* module_name,
std::set<std::string>* modified_exports);
} // namespace safe_browsing
#endif // CHROME_BROWSER_SAFE_BROWSING_MODULE_INTEGRITY_VERIFIER_WIN_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/module_integrity_verifier_win.h"
#include "base/files/file_path.h"
#include "base/files/memory_mapped_file.h"
#include "base/native_library.h"
#include "base/path_service.h"
#include "base/scoped_native_library.h"
#include "base/win/pe_image.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace safe_browsing {
namespace {
const wchar_t kTestDllName[] = L"verifier_test_dll.dll";
const char kTestExportName[] = "DummyExport";
} // namespace
class SafeBrowsingModuleVerifierWinTest : public testing::Test {
protected:
void SetUpTestDllAndPEImages() {
LoadModule();
HMODULE mem_handle;
GetMemModuleHandle(&mem_handle);
mem_peimage_ptr_.reset(new base::win::PEImage(mem_handle));
ASSERT_TRUE(mem_peimage_ptr_->VerifyMagic());
LoadDLLAsFile();
HMODULE disk_handle;
GetDiskModuleHandle(&disk_handle);
disk_peimage_ptr_.reset(new base::win::PEImageAsData(disk_handle));
ASSERT_TRUE(disk_peimage_ptr_->VerifyMagic());
}
void LoadModule() {
mem_dll_handle_.Reset(
LoadNativeLibrary(base::FilePath(kTestDllName), NULL));
ASSERT_TRUE(mem_dll_handle_.is_valid());
}
void GetMemModuleHandle(HMODULE* mem_handle) {
*mem_handle = GetModuleHandle(kTestDllName);
ASSERT_NE(static_cast<HMODULE>(NULL), *mem_handle);
}
void LoadDLLAsFile() {
// Use the module handle to find the it on disk, then load as a file.
HMODULE module_handle;
GetMemModuleHandle(&module_handle);
WCHAR module_path[MAX_PATH] = {};
DWORD length =
GetModuleFileName(module_handle, module_path, arraysize(module_path));
ASSERT_NE(arraysize(module_path), length);
ASSERT_TRUE(disk_dll_handle_.Initialize(base::FilePath(module_path)));
}
void GetDiskModuleHandle(HMODULE* disk_handle) {
*disk_handle =
reinterpret_cast<HMODULE>(const_cast<uint8*>(disk_dll_handle_.data()));
}
// Edits the first byte of the single function exported by the test dll.
void EditExport() {
HMODULE mem_handle;
GetMemModuleHandle(&mem_handle);
uint8_t* export_addr =
reinterpret_cast<uint8_t*>(GetProcAddress(mem_handle, kTestExportName));
EXPECT_NE(reinterpret_cast<uint8_t*>(NULL), export_addr);
// Edit the first byte of the function.
uint8_t new_val = (*export_addr) + 1;
SIZE_T bytes_written = 0;
WriteProcessMemory(GetCurrentProcess(),
export_addr,
reinterpret_cast<void*>(&new_val),
1,
&bytes_written);
EXPECT_EQ(1, bytes_written);
}
base::ScopedNativeLibrary mem_dll_handle_;
base::MemoryMappedFile disk_dll_handle_;
scoped_ptr<base::win::PEImageAsData> disk_peimage_ptr_;
scoped_ptr<base::win::PEImage> mem_peimage_ptr_;
};
TEST_F(SafeBrowsingModuleVerifierWinTest, VerifyModuleUnmodified) {
std::set<std::string> modified_exports;
// Call VerifyModule before the module has been loaded, should fail.
EXPECT_EQ(MODULE_STATE_UNKNOWN,
VerifyModule(kTestDllName, &modified_exports));
EXPECT_EQ(0, modified_exports.size());
// On loading, the module should be identical (up to relocations) in memory as
// on disk.
SetUpTestDllAndPEImages();
EXPECT_EQ(MODULE_STATE_UNMODIFIED,
VerifyModule(kTestDllName, &modified_exports));
EXPECT_EQ(0, modified_exports.size());
}
TEST_F(SafeBrowsingModuleVerifierWinTest, VerifyModuleModified) {
std::set<std::string> modified_exports;
// Confirm the module is identical in memory as on disk before we begin.
SetUpTestDllAndPEImages();
EXPECT_EQ(MODULE_STATE_UNMODIFIED,
VerifyModule(kTestDllName, &modified_exports));
uint8_t* mem_code_addr = NULL;
uint8_t* disk_code_addr = NULL;
uint32_t code_size = 0;
EXPECT_TRUE(GetCodeAddrsAndSize(*mem_peimage_ptr_,
*disk_peimage_ptr_,
&mem_code_addr,
&disk_code_addr,
&code_size));
// Edit the first byte of the code section of the module (this may be before
// the address of any export).
uint8_t new_val = (*mem_code_addr) + 1;
SIZE_T bytes_written = 0;
WriteProcessMemory(GetCurrentProcess(),
mem_code_addr,
reinterpret_cast<void*>(&new_val),
1,
&bytes_written);
EXPECT_EQ(1, bytes_written);
// VerifyModule should detect the change.
EXPECT_EQ(MODULE_STATE_MODIFIED,
VerifyModule(kTestDllName, &modified_exports));
}
TEST_F(SafeBrowsingModuleVerifierWinTest, VerifyModuleExportModified) {
std::set<std::string> modified_exports;
// Confirm the module is identical in memory as on disk before we begin.
SetUpTestDllAndPEImages();
EXPECT_EQ(MODULE_STATE_UNMODIFIED,
VerifyModule(kTestDllName, &modified_exports));
modified_exports.clear();
// Edit the exported function, VerifyModule should now return the function
// name in modified_exports.
EditExport();
EXPECT_EQ(MODULE_STATE_MODIFIED,
VerifyModule(kTestDllName, &modified_exports));
EXPECT_EQ(1, modified_exports.size());
EXPECT_EQ(0, std::string(kTestExportName).compare(*modified_exports.begin()));
}
} // namespace safe_browsing
......@@ -2668,8 +2668,6 @@
'browser/safe_browsing/incident_report_uploader_impl.h',
'browser/safe_browsing/last_download_finder.cc',
'browser/safe_browsing/last_download_finder.h',
'browser/safe_browsing/module_integrity_verifier_win.cc',
'browser/safe_browsing/module_integrity_verifier_win.h',
'browser/safe_browsing/path_sanitizer.cc',
'browser/safe_browsing/path_sanitizer.h',
'browser/safe_browsing/pe_image_reader_win.cc',
......
......@@ -1215,7 +1215,6 @@
'browser/safe_browsing/last_download_finder_unittest.cc',
'browser/safe_browsing/local_two_phase_testserver.cc',
'browser/safe_browsing/malware_details_unittest.cc',
'browser/safe_browsing/module_integrity_verifier_win_unittest.cc',
'browser/safe_browsing/path_sanitizer_unittest.cc',
'browser/safe_browsing/pe_image_reader_win_unittest.cc',
'browser/safe_browsing/ping_manager_unittest.cc',
......@@ -2463,7 +2462,6 @@
}],
['OS=="win"', {
'dependencies': [
'browser/safe_browsing/verifier_test/verifier_unittest.gyp:verifier_test_dll',
'chrome_version_resources',
'installer_util_strings',
'../chrome_elf/chrome_elf.gyp:blacklist_test_dll_1',
......
......@@ -25712,15 +25712,6 @@ Therefore, the affected-histogram name has to have at least one dot in it.
</summary>
</histogram>
<histogram name="SafeBrowsing.ModuleBaseRelocation" units="BaseRelocationType">
<owner>csharp@chromium.org</owner>
<owner>krstnmnlsn@chromium.org</owner>
<summary>
A windows only historgram. Records when an unknown base relocation type is
encountered while reading the reloc table of a loaded module.
</summary>
</histogram>
<histogram name="SB.BloomFilter" units="milliseconds">
<obsolete>
Has not been generated for years (7/8/14).
......@@ -36824,20 +36815,6 @@ Therefore, the affected-histogram name has to have at least one dot in it.
<int value="2" label="Failure"/>
</enum>
<enum name="BaseRelocationType" type="int">
<int value="0" label="IMAGE_REL_BASED_ABSOLUTE"/>
<int value="1" label="IMAGE_REL_BASED_HIGH"/>
<int value="2" label="IMAGE_REL_BASED_LOW"/>
<int value="3" label="IMAGE_REL_BASED_HIGHLOW"/>
<int value="4" label="IMAGE_REL_BASED_HIGHADJ"/>
<int value="5" label="IMAGE_REL_BASED_MACHINE_SPECIFIC_5"/>
<int value="6" label="IMAGE_REL_BASED_RESERVED"/>
<int value="7" label="IMAGE_REL_BASED_MACHINE_SPECIFIC_7"/>
<int value="8" label="IMAGE_REL_BASED_MACHINE_SPECIFIC_8"/>
<int value="9" label="IMAGE_REL_BASED_MACHINE_SPECIFIC_9"/>
<int value="10" label="IMAGE_REL_BASED_DIR64"/>
</enum>
<enum name="BatteryInfoSampleResult" type="int">
<int value="0" label="Read"/>
<int value="1" label="Good"/>
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment