Home | History | Annotate | Download | only in base
      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 <stdio.h>
      7 #include <stdlib.h>
      8 #include <string.h>
      9 #include <sys/stat.h>
     10 #include <sys/types.h>
     11 
     12 #include <algorithm>
     13 #include <limits>
     14 
     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"
     20 
     21 #if defined(OS_POSIX)
     22 #include <sys/mman.h>
     23 #include <unistd.h>
     24 #endif
     25 
     26 using std::nothrow;
     27 using std::numeric_limits;
     28 
     29 namespace {
     30 
     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;
     43 }
     44 
     45 // - NO_TCMALLOC (should be defined if we compile with linux_use_tcmalloc=0)
     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
     55 
     56 // TODO(jln): switch to std::numeric_limits<int>::max() when we switch to
     57 // C++11.
     58 const size_t kTooBigAllocSize = INT_MAX;
     59 
     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;
     75 }
     76 
     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(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER) || \
     82     defined(THREAD_SANITIZER) || (defined(OS_LINUX) && defined(NO_TCMALLOC))
     83   return true;
     84 #else
     85   return false;
     86 #endif
     87 }
     88 
     89 // Fake test that allow to know the state of TCMalloc by looking at bots.
     90 TEST(SecurityTest, TCMALLOC_TEST(IsTCMallocDynamicallyBypassed)) {
     91   printf("Malloc is dynamically bypassed: %s\n",
     92          IsTcMallocBypassed() ? "yes." : "no.");
     93 }
     94 
     95 // The MemoryAllocationRestrictions* tests test that we can not allocate a
     96 // memory range that cannot be indexed via an int. This is used to mitigate
     97 // vulnerabilities in libraries that use int instead of size_t.  See
     98 // crbug.com/169327.
     99 
    100 TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsMalloc)) {
    101   if (!IsTcMallocBypassed()) {
    102     scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(
    103         HideValueFromCompiler(malloc(kTooBigAllocSize))));
    104     ASSERT_TRUE(!ptr);
    105   }
    106 }
    107 
    108 TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsCalloc)) {
    109   if (!IsTcMallocBypassed()) {
    110     scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(
    111         HideValueFromCompiler(calloc(kTooBigAllocSize, 1))));
    112     ASSERT_TRUE(!ptr);
    113   }
    114 }
    115 
    116 TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsRealloc)) {
    117   if (!IsTcMallocBypassed()) {
    118     char* orig_ptr = static_cast<char*>(malloc(1));
    119     ASSERT_TRUE(orig_ptr);
    120     scoped_ptr<char, base::FreeDeleter> ptr(static_cast<char*>(
    121         HideValueFromCompiler(realloc(orig_ptr, kTooBigAllocSize))));
    122     ASSERT_TRUE(!ptr);
    123     // If realloc() did not succeed, we need to free orig_ptr.
    124     free(orig_ptr);
    125   }
    126 }
    127 
    128 typedef struct {
    129   char large_array[kTooBigAllocSize];
    130 } VeryLargeStruct;
    131 
    132 TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsNew)) {
    133   if (!IsTcMallocBypassed()) {
    134     scoped_ptr<VeryLargeStruct> ptr(
    135         HideValueFromCompiler(new (nothrow) VeryLargeStruct));
    136     ASSERT_TRUE(!ptr);
    137   }
    138 }
    139 
    140 TEST(SecurityTest, TCMALLOC_TEST(MemoryAllocationRestrictionsNewArray)) {
    141   if (!IsTcMallocBypassed()) {
    142     scoped_ptr<char[]> ptr(
    143         HideValueFromCompiler(new (nothrow) char[kTooBigAllocSize]));
    144     ASSERT_TRUE(!ptr);
    145   }
    146 }
    147 
    148 // The tests bellow check for overflows in new[] and calloc().
    149 
    150 #if defined(OS_IOS) || defined(OS_WIN) || defined(THREAD_SANITIZER)
    151   #define DISABLE_ON_IOS_AND_WIN_AND_TSAN(function) DISABLED_##function
    152 #else
    153   #define DISABLE_ON_IOS_AND_WIN_AND_TSAN(function) function
    154 #endif
    155 
    156 // There are platforms where these tests are known to fail. We would like to
    157 // be able to easily check the status on the bots, but marking tests as
    158 // FAILS_ is too clunky.
    159 void OverflowTestsSoftExpectTrue(bool overflow_detected) {
    160   if (!overflow_detected) {
    161 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX)
    162     // Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't
    163     // fail the test, but report.
    164     printf("Platform has overflow: %s\n",
    165            !overflow_detected ? "yes." : "no.");
    166 #else
    167     // Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT
    168     // aren't).
    169     EXPECT_TRUE(overflow_detected);
    170 #endif
    171   }
    172 }
    173 
    174 // Test array[TooBig][X] and array[X][TooBig] allocations for int overflows.
    175 // IOS doesn't honor nothrow, so disable the test there.
    176 // Crashes on Windows Dbg builds, disable there as well.
    177 TEST(SecurityTest, DISABLE_ON_IOS_AND_WIN_AND_TSAN(NewOverflow)) {
    178   const size_t kArraySize = 4096;
    179   // We want something "dynamic" here, so that the compiler doesn't
    180   // immediately reject crazy arrays.
    181   const size_t kDynamicArraySize = HideValueFromCompiler(kArraySize);
    182   // numeric_limits are still not constexpr until we switch to C++11, so we
    183   // use an ugly cast.
    184   const size_t kMaxSizeT = ~static_cast<size_t>(0);
    185   ASSERT_EQ(numeric_limits<size_t>::max(), kMaxSizeT);
    186   const size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
    187   const size_t kDynamicArraySize2 = HideValueFromCompiler(kArraySize2);
    188   {
    189     scoped_ptr<char[][kArraySize]> array_pointer(new (nothrow)
    190         char[kDynamicArraySize2][kArraySize]);
    191     OverflowTestsSoftExpectTrue(!array_pointer);
    192   }
    193   // On windows, the compiler prevents static array sizes of more than
    194   // 0x7fffffff (error C2148).
    195 #if !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
    196   {
    197     scoped_ptr<char[][kArraySize2]> array_pointer(new (nothrow)
    198         char[kDynamicArraySize][kArraySize2]);
    199     OverflowTestsSoftExpectTrue(!array_pointer);
    200   }
    201 #endif  // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
    202 }
    203 
    204 // Call calloc(), eventually free the memory and return whether or not
    205 // calloc() did succeed.
    206 bool CallocReturnsNull(size_t nmemb, size_t size) {
    207   scoped_ptr<char, base::FreeDeleter> array_pointer(
    208       static_cast<char*>(calloc(nmemb, size)));
    209   // We need the call to HideValueFromCompiler(): we have seen LLVM
    210   // optimize away the call to calloc() entirely and assume
    211   // the pointer to not be NULL.
    212   return HideValueFromCompiler(array_pointer.get()) == NULL;
    213 }
    214 
    215 // Test if calloc() can overflow.
    216 TEST(SecurityTest, CallocOverflow) {
    217   const size_t kArraySize = 4096;
    218   const size_t kMaxSizeT = numeric_limits<size_t>::max();
    219   const size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
    220   if (!CallocDiesOnOOM()) {
    221     EXPECT_TRUE(CallocReturnsNull(kArraySize, kArraySize2));
    222     EXPECT_TRUE(CallocReturnsNull(kArraySize2, kArraySize));
    223   } else {
    224     // It's also ok for calloc to just terminate the process.
    225 #if defined(GTEST_HAS_DEATH_TEST)
    226     EXPECT_DEATH(CallocReturnsNull(kArraySize, kArraySize2), "");
    227     EXPECT_DEATH(CallocReturnsNull(kArraySize2, kArraySize), "");
    228 #endif  // GTEST_HAS_DEATH_TEST
    229   }
    230 }
    231 
    232 #if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)
    233 // Check if ptr1 and ptr2 are separated by less than size chars.
    234 bool ArePointersToSameArea(void* ptr1, void* ptr2, size_t size) {
    235   ptrdiff_t ptr_diff = reinterpret_cast<char*>(std::max(ptr1, ptr2)) -
    236                        reinterpret_cast<char*>(std::min(ptr1, ptr2));
    237   return static_cast<size_t>(ptr_diff) <= size;
    238 }
    239 
    240 // Check if TCMalloc uses an underlying random memory allocator.
    241 TEST(SecurityTest, TCMALLOC_TEST(RandomMemoryAllocations)) {
    242   if (IsTcMallocBypassed())
    243     return;
    244   size_t kPageSize = 4096;  // We support x86_64 only.
    245   // Check that malloc() returns an address that is neither the kernel's
    246   // un-hinted mmap area, nor the current brk() area. The first malloc() may
    247   // not be at a random address because TCMalloc will first exhaust any memory
    248   // that it has allocated early on, before starting the sophisticated
    249   // allocators.
    250   void* default_mmap_heap_address =
    251       mmap(0, kPageSize, PROT_READ|PROT_WRITE,
    252            MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
    253   ASSERT_NE(default_mmap_heap_address,
    254             static_cast<void*>(MAP_FAILED));
    255   ASSERT_EQ(munmap(default_mmap_heap_address, kPageSize), 0);
    256   void* brk_heap_address = sbrk(0);
    257   ASSERT_NE(brk_heap_address, reinterpret_cast<void*>(-1));
    258   ASSERT_TRUE(brk_heap_address != NULL);
    259   // 1 MB should get us past what TCMalloc pre-allocated before initializing
    260   // the sophisticated allocators.
    261   size_t kAllocSize = 1<<20;
    262   scoped_ptr<char, base::FreeDeleter> ptr(
    263       static_cast<char*>(malloc(kAllocSize)));
    264   ASSERT_TRUE(ptr != NULL);
    265   // If two pointers are separated by less than 512MB, they are considered
    266   // to be in the same area.
    267   // Our random pointer could be anywhere within 0x3fffffffffff (46bits),
    268   // and we are checking that it's not withing 1GB (30 bits) from two
    269   // addresses (brk and mmap heap). We have roughly one chance out of
    270   // 2^15 to flake.
    271   const size_t kAreaRadius = 1<<29;
    272   bool in_default_mmap_heap = ArePointersToSameArea(
    273       ptr.get(), default_mmap_heap_address, kAreaRadius);
    274   EXPECT_FALSE(in_default_mmap_heap);
    275 
    276   bool in_default_brk_heap = ArePointersToSameArea(
    277       ptr.get(), brk_heap_address, kAreaRadius);
    278   EXPECT_FALSE(in_default_brk_heap);
    279 
    280   // In the implementation, we always mask our random addresses with
    281   // kRandomMask, so we use it as an additional detection mechanism.
    282   const uintptr_t kRandomMask = 0x3fffffffffffULL;
    283   bool impossible_random_address =
    284       reinterpret_cast<uintptr_t>(ptr.get()) & ~kRandomMask;
    285   EXPECT_FALSE(impossible_random_address);
    286 }
    287 
    288 #endif  // (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)
    289 
    290 }  // namespace
    291