summaryrefslogtreecommitdiffstats
path: root/chrome/browser/safe_browsing/incident_reporting/module_integrity_verifier_win_unittest.cc
blob: b991eebb832620a22d1a3720ebe837810fb94c5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// 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/incident_reporting/module_integrity_verifier_win.h"

#include <algorithm>
#include <functional>
#include <map>
#include <vector>

#include "base/files/file_path.h"
#include "base/files/memory_mapped_file.h"
#include "base/native_library.h"
#include "base/scoped_native_library.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/pe_image.h"
#include "chrome/browser/safe_browsing/incident_reporting/module_integrity_unittest_util_win.h"
#include "chrome/common/safe_browsing/csd.pb.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace safe_browsing {

namespace {

// A scoper that makes a modification at a given address when constructed, and
// reverts it upon destruction.
template <size_t ModificationLength>
class ScopedModuleModifier {
 public:
  explicit ScopedModuleModifier(uint8_t* address) : address_(address) {
    uint8_t modification[ModificationLength];
    std::transform(address, address + ModificationLength, &modification[0],
                   std::bind2nd(std::plus<uint8_t>(), 1U));
    SIZE_T bytes_written = 0;
    EXPECT_NE(0, WriteProcessMemory(GetCurrentProcess(),
                                    address,
                                    &modification[0],
                                    ModificationLength,
                                    &bytes_written));
    EXPECT_EQ(ModificationLength, bytes_written);
  }

  ~ScopedModuleModifier() {
    uint8_t modification[ModificationLength];
    std::transform(address_, address_ + ModificationLength, &modification[0],
                   std::bind2nd(std::minus<uint8_t>(), 1U));
    SIZE_T bytes_written = 0;
    EXPECT_NE(0, WriteProcessMemory(GetCurrentProcess(),
                                    address_,
                                    &modification[0],
                                    ModificationLength,
                                    &bytes_written));
    EXPECT_EQ(ModificationLength, bytes_written);
  }

 private:
  uint8_t* address_;

  DISALLOW_COPY_AND_ASSIGN(ScopedModuleModifier);
};

}  // namespace

class SafeBrowsingModuleVerifierWinTest : public testing::Test {
 protected:
  using ModuleState = ClientIncidentReport_EnvironmentData_Process_ModuleState;

  // A mapping of an export name to the sequence of modifications for it.
  using ExportNameToModifications =
      std::map<std::string, std::vector<const ModuleState::Modification*>>;

  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() {
    HMODULE mem_dll_handle =
        LoadNativeLibrary(base::FilePath(kTestDllNames[0]), NULL);
    ASSERT_NE(static_cast<HMODULE>(NULL), mem_dll_handle)
        << "GLE=" << GetLastError();
    mem_dll_handle_.Reset(mem_dll_handle);
    ASSERT_TRUE(mem_dll_handle_.is_valid());
  }

  void GetMemModuleHandle(HMODULE* mem_handle) {
    *mem_handle = GetModuleHandle(kTestDllNames[0]);
    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()));
  }

  // Returns the address of the named function exported by the test dll.
  uint8_t* GetAddressOfExport(const char* export_name) {
    HMODULE mem_handle;
    GetMemModuleHandle(&mem_handle);
    uint8_t* export_addr =
        reinterpret_cast<uint8_t*>(GetProcAddress(mem_handle, export_name));
    EXPECT_NE(nullptr, export_addr);
    return export_addr;
  }

  static void AssertModuleUnmodified(const ModuleState& state,
                                     const wchar_t* module_name) {
    ASSERT_TRUE(state.has_name());
    ASSERT_EQ(base::WideToUTF8(module_name), state.name());
    ASSERT_TRUE(state.has_modified_state());
    ASSERT_EQ(ModuleState::MODULE_STATE_UNMODIFIED, state.modified_state());
    ASSERT_EQ(0, state.modification_size());
  }

  // Replaces the contents of |modification_map| with pointers to those in
  // |state|. |state| must outlive |modification_map|.
  static void BuildModificationMap(
      const ModuleState& state,
      ExportNameToModifications* modification_map) {
    modification_map->clear();
    std::string export_name;
    for (auto& modification : state.modification()) {
      if (!modification.has_export_name())
        export_name.clear();
      else
        export_name = modification.export_name();
      (*modification_map)[export_name].push_back(&modification);
    }
  }

  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_;
};

// Don't run these tests under AddressSanitizer as it patches the modules on
// startup, thus interferes with all these test expectations.
#if !defined(ADDRESS_SANITIZER)
TEST_F(SafeBrowsingModuleVerifierWinTest, VerifyModuleUnmodified) {
  ModuleState state;
  int num_bytes_different = 0;
  // Call VerifyModule before the module has been loaded, should fail.
  ASSERT_FALSE(VerifyModule(kTestDllNames[0], &state, &num_bytes_different));
  ASSERT_TRUE(state.has_name());
  ASSERT_EQ(base::WideToUTF8(kTestDllNames[0]), state.name());
  ASSERT_TRUE(state.has_modified_state());
  ASSERT_EQ(ModuleState::MODULE_STATE_UNKNOWN, state.modified_state());
  ASSERT_EQ(0, num_bytes_different);
  ASSERT_EQ(0, state.modification_size());

  // On loading, the module should be identical (up to relocations) in memory as
  // on disk.
  SetUpTestDllAndPEImages();
  state.Clear();
  num_bytes_different = 0;
  ASSERT_TRUE(VerifyModule(kTestDllNames[0], &state, &num_bytes_different));
  AssertModuleUnmodified(state, kTestDllNames[0]);
  ASSERT_EQ(0, num_bytes_different);
}

TEST_F(SafeBrowsingModuleVerifierWinTest, VerifyModuleModified) {
  int num_bytes_different = 0;
  ModuleState state;

  SetUpTestDllAndPEImages();
  ASSERT_TRUE(VerifyModule(kTestDllNames[0], &state, &num_bytes_different));
  AssertModuleUnmodified(state, kTestDllNames[0]);
  ASSERT_EQ(0, num_bytes_different);

  uint8_t* mem_code_addr = NULL;
  uint8_t* disk_code_addr = NULL;
  uint32_t code_size = 0;
  ASSERT_TRUE(GetCodeAddrsAndSize(*mem_peimage_ptr_,
                                  *disk_peimage_ptr_,
                                  &mem_code_addr,
                                  &disk_code_addr,
                                  &code_size));

  ScopedModuleModifier<1> mod(mem_code_addr);

  size_t modification_offset = code_size - 1;
  ScopedModuleModifier<1> mod2(mem_code_addr + modification_offset);

  state.Clear();
  num_bytes_different = 0;
  ASSERT_TRUE(VerifyModule(kTestDllNames[0], &state, &num_bytes_different));
  ASSERT_TRUE(state.has_name());
  ASSERT_EQ(base::WideToUTF8(kTestDllNames[0]), state.name());
  ASSERT_TRUE(state.has_modified_state());
  ASSERT_EQ(ModuleState::MODULE_STATE_MODIFIED, state.modified_state());
  ASSERT_EQ(2, num_bytes_different);
  ASSERT_EQ(2, state.modification_size());

  size_t expected_file_offset =
      disk_code_addr - reinterpret_cast<uint8_t*>(disk_peimage_ptr_->module());
  EXPECT_EQ(expected_file_offset, state.modification(0).file_offset());
  EXPECT_EQ(1, state.modification(0).byte_count());
  EXPECT_EQ(mem_code_addr[0],
            (uint8_t)state.modification(0).modified_bytes()[0]);

  expected_file_offset = (disk_code_addr + modification_offset) -
      reinterpret_cast<uint8_t*>(disk_peimage_ptr_->module());
  EXPECT_EQ(expected_file_offset, state.modification(1).file_offset());
  EXPECT_EQ(1, state.modification(1).byte_count());
  EXPECT_EQ(mem_code_addr[modification_offset],
            (uint8_t)state.modification(1).modified_bytes()[0]);
}

TEST_F(SafeBrowsingModuleVerifierWinTest, VerifyModuleLongModification) {
  ModuleState state;
  int num_bytes_different = 0;

  SetUpTestDllAndPEImages();
  ASSERT_TRUE(VerifyModule(kTestDllNames[0], &state, &num_bytes_different));
  AssertModuleUnmodified(state, kTestDllNames[0]);
  ASSERT_EQ(0, num_bytes_different);

  uint8_t* mem_code_addr = NULL;
  uint8_t* disk_code_addr = NULL;
  uint32_t code_size = 0;
  ASSERT_TRUE(GetCodeAddrsAndSize(*mem_peimage_ptr_,
                                  *disk_peimage_ptr_,
                                  &mem_code_addr,
                                  &disk_code_addr,
                                  &code_size));

  const size_t kModificationSize = 256;
  // Write the modification at the end so it's not overlapping relocations
  const size_t modification_offset = code_size - kModificationSize;
  ScopedModuleModifier<kModificationSize> mod(
      mem_code_addr + modification_offset);

  state.Clear();
  num_bytes_different = 0;
  ASSERT_TRUE(VerifyModule(kTestDllNames[0], &state, &num_bytes_different));
  ASSERT_TRUE(state.has_name());
  ASSERT_EQ(base::WideToUTF8(kTestDllNames[0]), state.name());
  ASSERT_TRUE(state.has_modified_state());
  ASSERT_EQ(ModuleState::MODULE_STATE_MODIFIED, state.modified_state());
  ASSERT_EQ(kModificationSize, num_bytes_different);
  ASSERT_EQ(1, state.modification_size());

  EXPECT_EQ(kModificationSize, state.modification(0).byte_count());

  size_t expected_file_offset = disk_code_addr + modification_offset -
      reinterpret_cast<uint8_t*>(disk_peimage_ptr_->module());
  EXPECT_EQ(expected_file_offset, state.modification(0).file_offset());

  EXPECT_EQ(
      std::string(mem_code_addr + modification_offset,
                  mem_code_addr + modification_offset + kModificationSize),
      state.modification(0).modified_bytes());
}

TEST_F(SafeBrowsingModuleVerifierWinTest, VerifyModuleRelocOverlap) {
  int num_bytes_different = 0;
  ModuleState state;

  SetUpTestDllAndPEImages();
  ASSERT_TRUE(VerifyModule(kTestDllNames[0], &state, &num_bytes_different));
  AssertModuleUnmodified(state, kTestDllNames[0]);
  ASSERT_EQ(0, num_bytes_different);

  uint8_t* mem_code_addr = NULL;
  uint8_t* disk_code_addr = NULL;
  uint32_t code_size = 0;
  ASSERT_TRUE(GetCodeAddrsAndSize(*mem_peimage_ptr_,
                                  *disk_peimage_ptr_,
                                  &mem_code_addr,
                                  &disk_code_addr,
                                  &code_size));

  // Modify the first hunk of the code, which contains many relocs.
  const size_t kModificationSize = 256;
  ScopedModuleModifier<kModificationSize> mod(mem_code_addr);

  state.Clear();
  num_bytes_different = 0;
  ASSERT_TRUE(VerifyModule(kTestDllNames[0], &state, &num_bytes_different));
  ASSERT_TRUE(state.has_name());
  ASSERT_EQ(base::WideToUTF8(kTestDllNames[0]), state.name());
  ASSERT_TRUE(state.has_modified_state());
  ASSERT_EQ(ModuleState::MODULE_STATE_MODIFIED, state.modified_state());
  ASSERT_EQ(kModificationSize, num_bytes_different);

  // Modifications across the relocs should have been coalesced into one.
  ASSERT_EQ(1, state.modification_size());
  ASSERT_EQ(kModificationSize, state.modification(0).byte_count());
  ASSERT_EQ(kModificationSize, state.modification(0).modified_bytes().size());
  EXPECT_EQ(std::string(mem_code_addr, mem_code_addr + kModificationSize),
            state.modification(0).modified_bytes());
}

TEST_F(SafeBrowsingModuleVerifierWinTest, VerifyModuleExportModified) {
  ModuleState state;
  int num_bytes_different = 0;
  // Confirm the module is identical in memory as on disk before we begin.
  SetUpTestDllAndPEImages();
  ASSERT_TRUE(VerifyModule(kTestDllNames[0], &state, &num_bytes_different));
  AssertModuleUnmodified(state, kTestDllNames[0]);
  ASSERT_EQ(0, num_bytes_different);

  // Edit one exported function. VerifyModule should now return the function
  // name in the modification.
  ScopedModuleModifier<1> mod(GetAddressOfExport(kTestExportName));
  state.Clear();
  num_bytes_different = 0;
  ASSERT_TRUE(VerifyModule(kTestDllNames[0], &state, &num_bytes_different));
  ASSERT_TRUE(state.has_name());
  ASSERT_EQ(base::WideToUTF8(kTestDllNames[0]), state.name());
  ASSERT_TRUE(state.has_modified_state());
  ASSERT_EQ(ModuleState::MODULE_STATE_MODIFIED, state.modified_state());
  ASSERT_EQ(1, state.modification_size());

  // Extract the offset of this modification.
  ExportNameToModifications modification_map;
  BuildModificationMap(state, &modification_map);
  ASSERT_EQ(1U, modification_map[kTestExportName].size());
  uint32_t export_offset = modification_map[kTestExportName][0]->file_offset();

  // Edit another exported function. VerifyModule should now report both. Add
  // one to the address so that this modification and the previous are not
  // coalesced in the event that the first export is only one byte (e.g., ret).
  ScopedModuleModifier<1> mod2(GetAddressOfExport(kTestDllMainExportName) + 1);
  state.Clear();
  num_bytes_different = 0;
  ASSERT_TRUE(VerifyModule(kTestDllNames[0], &state, &num_bytes_different));
  ASSERT_TRUE(state.has_modified_state());
  ASSERT_EQ(ModuleState::MODULE_STATE_MODIFIED, state.modified_state());
  ASSERT_EQ(2, state.modification_size());

  // The first modification should be present and unmodified.
  BuildModificationMap(state, &modification_map);
  ASSERT_EQ(1U, modification_map[kTestExportName].size());
  ASSERT_EQ(export_offset, modification_map[kTestExportName][0]->file_offset());

  // The second modification should be present and different than the first.
  ASSERT_EQ(1U, modification_map[kTestDllMainExportName].size());
  ASSERT_NE(export_offset,
            modification_map[kTestDllMainExportName][0]->file_offset());

  // Now make another edit at the very end of the code section. This should be
  // attributed to the last export.
  uint8_t* mem_code_addr = nullptr;
  uint8_t* disk_code_addr = nullptr;
  uint32_t code_size = 0;
  ASSERT_TRUE(GetCodeAddrsAndSize(*mem_peimage_ptr_,
                                  *disk_peimage_ptr_,
                                  &mem_code_addr,
                                  &disk_code_addr,
                                  &code_size));
  ScopedModuleModifier<1> mod3(mem_code_addr + code_size - 1);

  state.Clear();
  ASSERT_TRUE(VerifyModule(kTestDllNames[0], &state, &num_bytes_different));
  ASSERT_TRUE(state.has_modified_state());
  ASSERT_EQ(ModuleState::MODULE_STATE_MODIFIED, state.modified_state());
  ASSERT_EQ(3, state.modification_size());

  // One of the two exports now has two modifications.
  BuildModificationMap(state, &modification_map);
  ASSERT_EQ(2U, modification_map.size());
  ASSERT_EQ(3U, (modification_map.begin()->second.size() +
                 (++modification_map.begin())->second.size()));
}
#endif  // ADDRESS_SANITIZER

}  // namespace safe_browsing