Revert 258482 "Use cryptohome --action=is_mounted instead of man..."
[chromium-blink-merge.git] / base / security_unittest.cc
blobd613f34c5097d2299b88226d9547d2372e2aa1e4
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.
5 #include <fcntl.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/stat.h>
10 #include <sys/types.h>
12 #include <algorithm>
13 #include <limits>
15 #include "base/file_util.h"
16 #include "base/logging.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "build/build_config.h"
19 #include "testing/gtest/include/gtest/gtest.h"
21 #if defined(OS_POSIX)
22 #include <sys/mman.h>
23 #include <unistd.h>
24 #endif
26 using std::nothrow;
27 using std::numeric_limits;
29 namespace {
31 // This function acts as a compiler optimization barrier. We use it to
32 // prevent the compiler from making an expression a compile-time constant.
33 // We also use it so that the compiler doesn't discard certain return values
34 // as something we don't need (see the comment with calloc below).
35 template <typename Type>
36 Type HideValueFromCompiler(volatile Type value) {
37 #if defined(__GNUC__)
38 // In a GCC compatible compiler (GCC or Clang), make this compiler barrier
39 // more robust than merely using "volatile".
40 __asm__ volatile ("" : "+r" (value));
41 #endif // __GNUC__
42 return value;
45 // - NO_TCMALLOC (should be defined if compiled with use_allocator!="tcmalloc")
46 // - ADDRESS_SANITIZER because it has its own memory allocator
47 // - IOS does not use tcmalloc
48 // - OS_MACOSX does not use tcmalloc
49 #if !defined(NO_TCMALLOC) && !defined(ADDRESS_SANITIZER) && \
50 !defined(OS_IOS) && !defined(OS_MACOSX)
51 #define TCMALLOC_TEST(function) function
52 #else
53 #define TCMALLOC_TEST(function) DISABLED_##function
54 #endif
56 // TODO(jln): switch to std::numeric_limits<int>::max() when we switch to
57 // C++11.
58 const size_t kTooBigAllocSize = INT_MAX;
60 // Detect runtime TCMalloc bypasses.
61 bool IsTcMallocBypassed() {
62 #if defined(OS_LINUX) || defined(OS_CHROMEOS)
63 // This should detect a TCMalloc bypass from Valgrind.
64 char* g_slice = getenv("G_SLICE");
65 if (g_slice && !strcmp(g_slice, "always-malloc"))
66 return true;
67 #elif defined(OS_WIN)
68 // This should detect a TCMalloc bypass from setting
69 // the CHROME_ALLOCATOR environment variable.
70 char* allocator = getenv("CHROME_ALLOCATOR");
71 if (allocator && strcmp(allocator, "tcmalloc"))
72 return true;
73 #endif
74 return false;
77 bool CallocDiesOnOOM() {
78 // The sanitizers' calloc dies on OOM instead of returning NULL.
79 // The wrapper function in base/process_util_linux.cc that is used when we
80 // compile without TCMalloc will just die on OOM instead of returning NULL.
81 #if !defined(OS_WIN) && (defined(ADDRESS_SANITIZER) || \
82 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
83 (defined(OS_LINUX) && defined(NO_TCMALLOC)))
84 return true;
85 #else
86 return false;
87 #endif
90 // Fake test that allow to know the state of TCMalloc by looking at bots.
91 TEST(SecurityTest, TCMALLOC_TEST(IsTCMallocDynamicallyBypassed)) {
92 printf("Malloc is dynamically bypassed: %s\n",
93 IsTcMallocBypassed() ? "yes." : "no.");
96 // The MemoryAllocationRestrictions* tests test that we can not allocate a
97 // memory range that cannot be indexed via an int. This is used to mitigate
98 // vulnerabilities in libraries that use int instead of size_t. See
99 // crbug.com/169327.
101 TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsMalloc)) {
102 if (!IsTcMallocBypassed()) {
103 scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(
104 HideValueFromCompiler(malloc(kTooBigAllocSize))));
105 ASSERT_TRUE(!ptr);
109 TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsCalloc)) {
110 if (!IsTcMallocBypassed()) {
111 scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(
112 HideValueFromCompiler(calloc(kTooBigAllocSize, 1))));
113 ASSERT_TRUE(!ptr);
117 TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsRealloc)) {
118 if (!IsTcMallocBypassed()) {
119 char* orig_ptr = static_cast<char*>(malloc(1));
120 ASSERT_TRUE(orig_ptr);
121 scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(
122 HideValueFromCompiler(realloc(orig_ptr, kTooBigAllocSize))));
123 ASSERT_TRUE(!ptr);
124 // If realloc() did not succeed, we need to free orig_ptr.
125 free(orig_ptr);
129 typedef struct {
130 char large_array[kTooBigAllocSize];
131 } VeryLargeStruct;
133 TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsNew)) {
134 if (!IsTcMallocBypassed()) {
135 scoped_ptr<VeryLargeStruct> ptr(
136 HideValueFromCompiler(new (nothrow) VeryLargeStruct));
137 ASSERT_TRUE(!ptr);
141 TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsNewArray)) {
142 if (!IsTcMallocBypassed()) {
143 scoped_ptr<char[]> ptr(
144 HideValueFromCompiler(new (nothrow) char[kTooBigAllocSize]));
145 ASSERT_TRUE(!ptr);
149 // The tests bellow check for overflows in new[] and calloc().
151 #if defined(OS_IOS) || defined(OS_WIN) || defined(THREAD_SANITIZER)
152 #define DISABLE_ON_IOS_AND_WIN_AND_TSAN(function) DISABLED_##function
153 #else
154 #define DISABLE_ON_IOS_AND_WIN_AND_TSAN(function) function
155 #endif
157 // There are platforms where these tests are known to fail. We would like to
158 // be able to easily check the status on the bots, but marking tests as
159 // FAILS_ is too clunky.
160 void OverflowTestsSoftExpectTrue(bool overflow_detected) {
161 if (!overflow_detected) {
162 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX)
163 // Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't
164 // fail the test, but report.
165 printf("Platform has overflow: %s\n",
166 !overflow_detected ? "yes." : "no.");
167 #else
168 // Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT
169 // aren't).
170 EXPECT_TRUE(overflow_detected);
171 #endif
175 // Test array[TooBig][X] and array[X][TooBig] allocations for int overflows.
176 // IOS doesn't honor nothrow, so disable the test there.
177 // Crashes on Windows Dbg builds, disable there as well.
178 TEST(SecurityTest, DISABLE_ON_IOS_AND_WIN_AND_TSAN(NewOverflow)) {
179 const size_t kArraySize = 4096;
180 // We want something "dynamic" here, so that the compiler doesn't
181 // immediately reject crazy arrays.
182 const size_t kDynamicArraySize = HideValueFromCompiler(kArraySize);
183 // numeric_limits are still not constexpr until we switch to C++11, so we
184 // use an ugly cast.
185 const size_t kMaxSizeT = ~static_cast<size_t>(0);
186 ASSERT_EQ(numeric_limits<size_t>::max(), kMaxSizeT);
187 const size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
188 const size_t kDynamicArraySize2 = HideValueFromCompiler(kArraySize2);
190 scoped_ptr<char[][kArraySize]> array_pointer(new (nothrow)
191 char[kDynamicArraySize2][kArraySize]);
192 OverflowTestsSoftExpectTrue(!array_pointer);
194 // On windows, the compiler prevents static array sizes of more than
195 // 0x7fffffff (error C2148).
196 #if !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
198 scoped_ptr<char[][kArraySize2]> array_pointer(new (nothrow)
199 char[kDynamicArraySize][kArraySize2]);
200 OverflowTestsSoftExpectTrue(!array_pointer);
202 #endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
205 // Call calloc(), eventually free the memory and return whether or not
206 // calloc() did succeed.
207 bool CallocReturnsNull(size_t nmemb, size_t size) {
208 scoped_ptr<char, base::FreeDeleter> array_pointer(
209 static_cast<char*>(calloc(nmemb, size)));
210 // We need the call to HideValueFromCompiler(): we have seen LLVM
211 // optimize away the call to calloc() entirely and assume
212 // the pointer to not be NULL.
213 return HideValueFromCompiler(array_pointer.get()) == NULL;
216 // Test if calloc() can overflow.
217 TEST(SecurityTest, CallocOverflow) {
218 const size_t kArraySize = 4096;
219 const size_t kMaxSizeT = numeric_limits<size_t>::max();
220 const size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
221 if (!CallocDiesOnOOM()) {
222 EXPECT_TRUE(CallocReturnsNull(kArraySize, kArraySize2));
223 EXPECT_TRUE(CallocReturnsNull(kArraySize2, kArraySize));
224 } else {
225 // It's also ok for calloc to just terminate the process.
226 #if defined(GTEST_HAS_DEATH_TEST)
227 EXPECT_DEATH(CallocReturnsNull(kArraySize, kArraySize2), "");
228 EXPECT_DEATH(CallocReturnsNull(kArraySize2, kArraySize), "");
229 #endif // GTEST_HAS_DEATH_TEST
233 #if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)
234 // Check if ptr1 and ptr2 are separated by less than size chars.
235 bool ArePointersToSameArea(void* ptr1, void* ptr2, size_t size) {
236 ptrdiff_t ptr_diff = reinterpret_cast<char*>(std::max(ptr1, ptr2)) -
237 reinterpret_cast<char*>(std::min(ptr1, ptr2));
238 return static_cast<size_t>(ptr_diff) <= size;
241 // Check if TCMalloc uses an underlying random memory allocator.
242 TEST(SecurityTest, TCMALLOC_TEST(RandomMemoryAllocations)) {
243 if (IsTcMallocBypassed())
244 return;
245 size_t kPageSize = 4096; // We support x86_64 only.
246 // Check that malloc() returns an address that is neither the kernel's
247 // un-hinted mmap area, nor the current brk() area. The first malloc() may
248 // not be at a random address because TCMalloc will first exhaust any memory
249 // that it has allocated early on, before starting the sophisticated
250 // allocators.
251 void* default_mmap_heap_address =
252 mmap(0, kPageSize, PROT_READ|PROT_WRITE,
253 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
254 ASSERT_NE(default_mmap_heap_address,
255 static_cast<void*>(MAP_FAILED));
256 ASSERT_EQ(munmap(default_mmap_heap_address, kPageSize), 0);
257 void* brk_heap_address = sbrk(0);
258 ASSERT_NE(brk_heap_address, reinterpret_cast<void*>(-1));
259 ASSERT_TRUE(brk_heap_address != NULL);
260 // 1 MB should get us past what TCMalloc pre-allocated before initializing
261 // the sophisticated allocators.
262 size_t kAllocSize = 1<<20;
263 scoped_ptr<char, base::FreeDeleter> ptr(
264 static_cast<char*>(malloc(kAllocSize)));
265 ASSERT_TRUE(ptr != NULL);
266 // If two pointers are separated by less than 512MB, they are considered
267 // to be in the same area.
268 // Our random pointer could be anywhere within 0x3fffffffffff (46bits),
269 // and we are checking that it's not withing 1GB (30 bits) from two
270 // addresses (brk and mmap heap). We have roughly one chance out of
271 // 2^15 to flake.
272 const size_t kAreaRadius = 1<<29;
273 bool in_default_mmap_heap = ArePointersToSameArea(
274 ptr.get(), default_mmap_heap_address, kAreaRadius);
275 EXPECT_FALSE(in_default_mmap_heap);
277 bool in_default_brk_heap = ArePointersToSameArea(
278 ptr.get(), brk_heap_address, kAreaRadius);
279 EXPECT_FALSE(in_default_brk_heap);
281 // In the implementation, we always mask our random addresses with
282 // kRandomMask, so we use it as an additional detection mechanism.
283 const uintptr_t kRandomMask = 0x3fffffffffffULL;
284 bool impossible_random_address =
285 reinterpret_cast<uintptr_t>(ptr.get()) & ~kRandomMask;
286 EXPECT_FALSE(impossible_random_address);
289 #endif // (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)
291 } // namespace