1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <fcntl.h>
6 #include <stddef.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12
13 #include <algorithm>
14 #include <limits>
15 #include <memory>
16
17 #include "base/allocator/buildflags.h"
18 #include "base/files/file_util.h"
19 #include "base/logging.h"
20 #include "base/memory/free_deleter.h"
21 #include "build/build_config.h"
22 #include "testing/gtest/include/gtest/gtest.h"
23
24 #if defined(OS_POSIX)
25 #include <sys/mman.h>
26 #include <unistd.h>
27 #endif
28
29 using std::nothrow;
30 using std::numeric_limits;
31
32 namespace {
33
34 // This function acts as a compiler optimization barrier. We use it to
35 // prevent the compiler from making an expression a compile-time constant.
36 // We also use it so that the compiler doesn't discard certain return values
37 // as something we don't need (see the comment with calloc below).
38 template <typename Type>
HideValueFromCompiler(volatile Type value)39 NOINLINE Type HideValueFromCompiler(volatile Type value) {
40 #if defined(__GNUC__)
41 // In a GCC compatible compiler (GCC or Clang), make this compiler barrier
42 // more robust than merely using "volatile".
43 __asm__ volatile ("" : "+r" (value));
44 #endif // __GNUC__
45 return value;
46 }
47
48 // TCmalloc, currently supported only by Linux/CrOS, supports malloc limits.
49 // - NO_TCMALLOC (should be defined if compiled with use_allocator!="tcmalloc")
50 // - ADDRESS_SANITIZER it has its own memory allocator
51 #if defined(OS_LINUX) && !defined(NO_TCMALLOC) && !defined(ADDRESS_SANITIZER)
52 #define MALLOC_OVERFLOW_TEST(function) function
53 #else
54 #define MALLOC_OVERFLOW_TEST(function) DISABLED_##function
55 #endif
56
57 // There are platforms where these tests are known to fail. We would like to
58 // be able to easily check the status on the bots, but marking tests as
59 // FAILS_ is too clunky.
OverflowTestsSoftExpectTrue(bool overflow_detected)60 void OverflowTestsSoftExpectTrue(bool overflow_detected) {
61 if (!overflow_detected) {
62 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX)
63 // Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't
64 // fail the test, but report.
65 printf("Platform has overflow: %s\n",
66 !overflow_detected ? "yes." : "no.");
67 #else
68 // Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT
69 // aren't).
70 EXPECT_TRUE(overflow_detected);
71 #endif
72 }
73 }
74
75 #if defined(OS_IOS) || defined(OS_FUCHSIA) || defined(ADDRESS_SANITIZER) || \
76 defined(THREAD_SANITIZER) || defined(MEMORY_SANITIZER)
77 #define MAYBE_NewOverflow DISABLED_NewOverflow
78 #else
79 #define MAYBE_NewOverflow NewOverflow
80 #endif
81 // Test array[TooBig][X] and array[X][TooBig] allocations for int overflows.
82 // IOS doesn't honor nothrow, so disable the test there.
83 // TODO(https://crbug.com/828229): Fuchsia SDK exports an incorrect new[] that
84 // gets picked up in Debug/component builds, breaking this test.
85 // Disabled under XSan because asan aborts when new returns nullptr,
86 // https://bugs.chromium.org/p/chromium/issues/detail?id=690271#c15
TEST(SecurityTest,MAYBE_NewOverflow)87 TEST(SecurityTest, MAYBE_NewOverflow) {
88 const size_t kArraySize = 4096;
89 // We want something "dynamic" here, so that the compiler doesn't
90 // immediately reject crazy arrays.
91 const size_t kDynamicArraySize = HideValueFromCompiler(kArraySize);
92 const size_t kMaxSizeT = std::numeric_limits<size_t>::max();
93 const size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
94 const size_t kDynamicArraySize2 = HideValueFromCompiler(kArraySize2);
95 {
96 std::unique_ptr<char[][kArraySize]> array_pointer(
97 new (nothrow) char[kDynamicArraySize2][kArraySize]);
98 // Prevent clang from optimizing away the whole test.
99 char* volatile p = reinterpret_cast<char*>(array_pointer.get());
100 OverflowTestsSoftExpectTrue(!p);
101 }
102 // On windows, the compiler prevents static array sizes of more than
103 // 0x7fffffff (error C2148).
104 #if defined(OS_WIN) && defined(ARCH_CPU_64_BITS)
105 ALLOW_UNUSED_LOCAL(kDynamicArraySize);
106 #else
107 {
108 std::unique_ptr<char[][kArraySize2]> array_pointer(
109 new (nothrow) char[kDynamicArraySize][kArraySize2]);
110 // Prevent clang from optimizing away the whole test.
111 char* volatile p = reinterpret_cast<char*>(array_pointer.get());
112 OverflowTestsSoftExpectTrue(!p);
113 }
114 #endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
115 }
116
117 #if defined(OS_LINUX) && defined(__x86_64__)
118 // Check if ptr1 and ptr2 are separated by less than size chars.
ArePointersToSameArea(void * ptr1,void * ptr2,size_t size)119 bool ArePointersToSameArea(void* ptr1, void* ptr2, size_t size) {
120 ptrdiff_t ptr_diff = reinterpret_cast<char*>(std::max(ptr1, ptr2)) -
121 reinterpret_cast<char*>(std::min(ptr1, ptr2));
122 return static_cast<size_t>(ptr_diff) <= size;
123 }
124
125 // Check if TCMalloc uses an underlying random memory allocator.
TEST(SecurityTest,MALLOC_OVERFLOW_TEST (RandomMemoryAllocations))126 TEST(SecurityTest, MALLOC_OVERFLOW_TEST(RandomMemoryAllocations)) {
127 size_t kPageSize = 4096; // We support x86_64 only.
128 // Check that malloc() returns an address that is neither the kernel's
129 // un-hinted mmap area, nor the current brk() area. The first malloc() may
130 // not be at a random address because TCMalloc will first exhaust any memory
131 // that it has allocated early on, before starting the sophisticated
132 // allocators.
133 void* default_mmap_heap_address =
134 mmap(nullptr, kPageSize, PROT_READ | PROT_WRITE,
135 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
136 ASSERT_NE(default_mmap_heap_address,
137 static_cast<void*>(MAP_FAILED));
138 ASSERT_EQ(munmap(default_mmap_heap_address, kPageSize), 0);
139 void* brk_heap_address = sbrk(0);
140 ASSERT_NE(brk_heap_address, reinterpret_cast<void*>(-1));
141 ASSERT_TRUE(brk_heap_address != nullptr);
142 // 1 MB should get us past what TCMalloc pre-allocated before initializing
143 // the sophisticated allocators.
144 size_t kAllocSize = 1<<20;
145 std::unique_ptr<char, base::FreeDeleter> ptr(
146 static_cast<char*>(malloc(kAllocSize)));
147 ASSERT_TRUE(ptr != nullptr);
148 // If two pointers are separated by less than 512MB, they are considered
149 // to be in the same area.
150 // Our random pointer could be anywhere within 0x3fffffffffff (46bits),
151 // and we are checking that it's not withing 1GB (30 bits) from two
152 // addresses (brk and mmap heap). We have roughly one chance out of
153 // 2^15 to flake.
154 const size_t kAreaRadius = 1<<29;
155 bool in_default_mmap_heap = ArePointersToSameArea(
156 ptr.get(), default_mmap_heap_address, kAreaRadius);
157 EXPECT_FALSE(in_default_mmap_heap);
158
159 bool in_default_brk_heap = ArePointersToSameArea(
160 ptr.get(), brk_heap_address, kAreaRadius);
161 EXPECT_FALSE(in_default_brk_heap);
162
163 // In the implementation, we always mask our random addresses with
164 // kRandomMask, so we use it as an additional detection mechanism.
165 const uintptr_t kRandomMask = 0x3fffffffffffULL;
166 bool impossible_random_address =
167 reinterpret_cast<uintptr_t>(ptr.get()) & ~kRandomMask;
168 EXPECT_FALSE(impossible_random_address);
169 }
170
171 #endif // defined(OS_LINUX) && defined(__x86_64__)
172
173 } // namespace
174