GWP-ASan

Introduction

GWP-ASan is a sampled allocator framework that assists in finding use-after-freeand heap-buffer-overflow bugs in production environments. It informally is arecursive acronym, “GWP-ASan Will Provide AllocationSANity”.

GWP-ASan is based on the classicElectric Fence Malloc Debugger, with akey adaptation. Notably, we only choose a very small percentage of allocationsto sample, and apply guard pages to these sampled allocations only. The samplingis small enough to allow us to have very low performance overhead.

There is a small, tunable memory overhead that is fixed for the lifetime of theprocess. This is approximately ~40KiB per process using the default settings,depending on the average size of your allocations.

GWP-ASan vs. ASan

Unlike AddressSanitizer,GWP-ASan does not induce a significant performance overhead. ASan often requiresthe use of dedicated canaries to be viable in production environments, and assuch is often impractical.

GWP-ASan is only capable of finding a subset of the memory issues detected byASan. Furthermore, GWP-ASan’s bug detection capabilities are only probabilistic.As such, we recommend using ASan over GWP-ASan in testing, as well as anywhereelse that guaranteed error detection is more valuable than the 2x executionslowdown/binary size bloat. For the majority of production environments, thisimpact is too high, and GWP-ASan proves extremely useful.

Design

Please note: The implementation of GWP-ASan is largely in-flux, and thesedetails are subject to change. There are currently other implementations ofGWP-ASan, such as the implementation featured inChromium. Thelong-term support goal is to ensure feature-parity where reasonable, and tosupport compiler-rt as the reference implementation.

Allocator Support

GWP-ASan is not a replacement for a traditional allocator. Instead, it works byinserting stubs into a supporting allocator to redirect allocations to GWP-ASanwhen they’re chosen to be sampled. These stubs are generally implemented in theimplementation of malloc(), free() and realloc(). The stubs areextremely small, which makes using GWP-ASan in most allocators fairly trivial.The stubs follow the same general pattern (example malloc() pseudocodebelow):

  1. #ifdef INSTALL_GWP_ASAN_STUBS
  2. gwp_asan::GuardedPoolAllocator GWPASanAllocator;
  3. #endif
  4.  
  5. void* YourAllocator::malloc(..) {
  6. #ifdef INSTALL_GWP_ASAN_STUBS
  7. if (GWPASanAllocator.shouldSample(..))
  8. return GWPASanAllocator.allocate(..);
  9. #endif
  10.  
  11. // ... the rest of your allocator code here.
  12. }

Then, all the supporting allocator needs to do is compile with-DINSTALL_GWP_ASAN_STUBS and link against the GWP-ASan library! Forperformance reasons, we strongly recommend static linkage of the GWP-ASanlibrary.

Guarded Allocation Pool

The core of GWP-ASan is the guarded allocation pool. Each sampled allocation isbacked using its own guarded slot, which may consist of one or more accessiblepages. Each guarded slot is surrounded by two guard pages, which are mapped asinaccessible. The collection of all guarded slots makes up the guardedallocation pool.

Buffer Underflow/Overflow Detection

We gain buffer-overflow and buffer-underflow detection through these guardpages. When a memory access overruns the allocated buffer, it will touch theinaccessible guard page, causing memory exception. This exception is caught andhandled by the internal crash handler. Because each allocation is recorded withmetadata about where (and by what thread) it was allocated and deallocated, wecan provide information that will help identify the root cause of the bug.

Allocations are randomly selected to be either left- or right-aligned to provideequal detection of both underflows and overflows.

Use after Free Detection

The guarded allocation pool also provides use-after-free detection. Whenever asampled allocation is deallocated, we map its guarded slot as inaccessible. Anymemory accesses after deallocation will thus trigger the crash handler, and wecan provide useful information about the source of the error.

Please note that the use-after-free detection for a sampled allocation istransient. To keep memory overhead fixed while still detecting bugs, deallocatedslots are randomly reused to guard future allocations.

Usage

GWP-ASan already ships by default in theScudo Hardened Allocator,so building with -fsanitize=scudo is the quickest and easiest way to try outGWP-ASan.

Options

GWP-ASan’s configuration is managed by the supporting allocator. We provide ageneric configuration management library that is used by Scudo. It allowsseveral aspects of GWP-ASan to be configured through the following methods:

  • When the GWP-ASan library is compiled, by setting-DGWP_ASAN_DEFAULT_OPTIONS to the options string you want set by default.If you’re building GWP-ASan as part of a compiler-rt/LLVM build, add it duringcmake configure time (e.g. cmake … -DGWP_ASAN_DEFAULT_OPTIONS="…"). Ifyou’re building GWP-ASan outside of compiler-rt, simply ensure that youspecify -DGWP_ASAN_DEFAULT_OPTIONS="…" when buildingoptional/options_parser.cpp).
  • By defining a gwp_asan_default_options function in one’s program thatreturns the options string to be parsed. Said function must have the followingprototype: extern "C" const char* gwp_asan_default_options(void), with adefault visibility. This will override the compile time define;
  • Depending on allocator support (Scudo has support for this mechanism): Throughthe environment variable GWP_ASAN_OPTIONS, containing the options stringto be parsed. Options defined this way will override any definition madethrough __gwp_asan_default_options.

The options string follows a syntax similar to ASan, where distinct optionscan be assigned in the same string, separated by colons.

For example, using the environment variable:

  1. GWP_ASAN_OPTIONS="MaxSimultaneousAllocations=16:SampleRate=5000" ./a.out

Or using the function:

  1. extern "C" const char *__gwp_asan_default_options() {
  2. return "MaxSimultaneousAllocations=16:SampleRate=5000";
  3. }

The following options are available:

OptionDefaultDescription
EnabledtrueIs GWP-ASan enabled?
PerfectlyRightAlignfalseWhen allocations are right-aligned, should we perfectly align them up to thepage boundary? By default (false), we round up allocation size to the nearestpower of two (2, 4, 8, 16) up to a maximum of 16-byte alignment forperformance reasons. Setting this to true can find single bytebuffer-overflows at the cost of performance, and may be incompatible withsome architectures.
MaxSimultaneousAllocations16Number of simultaneously-guarded allocations available in the pool.
SampleRate5000The probability (1 / SampleRate) that a page is selected for GWP-ASansampling. Sample rates up to (2^31 - 1) are supported.
InstallSignalHandlerstrueInstall GWP-ASan signal handlers for SIGSEGV during dynamic loading. Thisallows better error reports by providing stack traces for allocation anddeallocation when reporting a memory error. GWP-ASan’s signal handler willforward the signal to any previously-installed handler, and user programsthat install further signal handlers should make sure they do the same. Note,if the previously installed SIGSEGV handler is SIG_IGN, we terminate theprocess after dumping the error report.

Example

The below code has a use-after-free bug, where the string_view is created asa reference to the temporary result of the string+ operator. Theuse-after-free occurs when sv is dereferenced on line 8.

  1. 1: #include <iostream>
  2. 2: #include <string>
  3. 3: #include <string_view>
  4. 4:
  5. 5: int main() {
  6. 6: std::string s = "Hellooooooooooooooo ";
  7. 7: std::string_view sv = s + "World\n";
  8. 8: std::cout << sv;
  9. 9: }

Compiling this code with Scudo+GWP-ASan will probabilistically catch this bugand provide us a detailed error report:

  1. $ clang++ -fsanitize=scudo -std=c++17 -g buggy_code.cpp
  2. $ for i in `seq 1 200`; do
  3. GWP_ASAN_OPTIONS="SampleRate=100" ./a.out > /dev/null;
  4. done
  5. |
  6. | *** GWP-ASan detected a memory error ***
  7. | Use after free at 0x7feccab26000 (0 bytes into a 41-byte allocation at 0x7feccab26000) by thread 31027 here:
  8. | ...
  9. | #9 ./a.out(_ZStlsIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_St17basic_string_viewIS3_S4_E+0x45) [0x55585c0afa55]
  10. | #10 ./a.out(main+0x9f) [0x55585c0af7cf]
  11. | #11 /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xeb) [0x7fecc966952b]
  12. | #12 ./a.out(_start+0x2a) [0x55585c0867ba]
  13. |
  14. | 0x7feccab26000 was deallocated by thread 31027 here:
  15. | ...
  16. | #7 ./a.out(main+0x83) [0x55585c0af7b3]
  17. | #8 /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xeb) [0x7fecc966952b]
  18. | #9 ./a.out(_start+0x2a) [0x55585c0867ba]
  19. |
  20. | 0x7feccab26000 was allocated by thread 31027 here:
  21. | ...
  22. | #12 ./a.out(main+0x57) [0x55585c0af787]
  23. | #13 /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xeb) [0x7fecc966952b]
  24. | #14 ./a.out(_start+0x2a) [0x55585c0867ba]
  25. |
  26. | *** End GWP-ASan report ***
  27. | Segmentation fault

To symbolize these stack traces, some care has to be taken. Scudo currently usesGNU’s backtrace_symbols() from <execinfo.h> to unwind. The unwinderprovides human-readable stack traces in function+offset form, rather thanthe normal binary+offset form. In order to use addr2line or similar tools torecover the exact line number, we must convert the function+offset tobinary+offset. A helper script is available atcompiler-rt/lib/gwp_asan/scripts/symbolize.sh. Using this script willattempt to symbolize each possible line, falling back to the previous output ifanything fails. This results in the following output:

  1. $ cat my_gwp_asan_error.txt | symbolize.sh
  2. |
  3. | *** GWP-ASan detected a memory error ***
  4. | Use after free at 0x7feccab26000 (0 bytes into a 41-byte allocation at 0x7feccab26000) by thread 31027 here:
  5. | ...
  6. | #9 /usr/lib/gcc/x86_64-linux-gnu/8.0.1/../../../../include/c++/8.0.1/string_view:547
  7. | #10 /tmp/buggy_code.cpp:8
  8. |
  9. | 0x7feccab26000 was deallocated by thread 31027 here:
  10. | ...
  11. | #7 /tmp/buggy_code.cpp:8
  12. | #8 /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xeb) [0x7fecc966952b]
  13. | #9 ./a.out(_start+0x2a) [0x55585c0867ba]
  14. |
  15. | 0x7feccab26000 was allocated by thread 31027 here:
  16. | ...
  17. | #12 /tmp/buggy_code.cpp:7
  18. | #13 /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xeb) [0x7fecc966952b]
  19. | #14 ./a.out(_start+0x2a) [0x55585c0867ba]
  20. |
  21. | *** End GWP-ASan report ***
  22. | Segmentation fault