--- tags: Sanitizer, --- # Address Sanitizer (ASan) Note # Source https://github.com/google/sanitizers/wiki/AddressSanitizer # What is ASan 1. a LLVM Pass 2. A run-time library that hooked memory operations(malloc/free/memset) # Benefits(mostly compare to Static Analyze) 1. zero false positive . In the meantime,static analyzers that has numerous false positive 2. No CTU problem 3. No de-virtualize calls problem 4. Everything related to pointer are not painful # Algorithm ## LLVM part - Add IsPoisoned and ReportError Functions to every memory access ```c *address = ...; // or: ... = *address; ``` - to ```c if (IsPoisoned(address)) { ReportError(address, kAccessSize, kIsWrite); } *address = ...; // or: ... = *address; ``` - IsPoisoned - 將使用的周圍記憶體mapping改為poisonned - 結束延遲reuse 一段時間後才改為unpoisonned - 如stack 標記整個stack frame - heap 拉出malloc周圍的 - std::container overflow則是可能的capacity 會大於end - ReportError - copy the failure address to %rax - execute ud2 (generates SIGILL) - Encode access type and size in a one-byte instruction which follows ud2 ![](https://i.imgur.com/LMR59SY.png) ## Run-time Lib - malloc: allocates the requested amount of memory with **redzones** around it. The shadow values corresponding to the redzones are **poisoned** and the shadow values for the main memory region are cleared. - free: poisons shadow values for the entire region and puts the chunk of memory into a quarantine queue (such that this chunk will not be returned again by malloc during some period of time) ![](https://i.imgur.com/aZWO1yE.png) ## Divided virtual address 1. Main memory: that is the normal usage of the program 2. **Shadow** memory: shadow values or says metadata. **Poisoning** a byte in the main memory means writing some special value into the corresponding shadow memory. ## Shadow bytes Mapping 1. Every aligned 8-byte word(**qword**) of memory have only 9 values: first k (0<=k<=8) bytes are addressable, the rest are not 2. State of every 8-byte word can be encoded in 1 byte (shadow byte) 3. So the first step to mapping is RHS>>3 ( User_Address >> 3 ) 4. Then we add the offset to shadow region, ( User_Address >> 3 )+ OFFSET ![](https://i.imgur.com/w1mAiAy.png) 5. we can also use -fPIE -pie to avoid the offset, but not always can be use. ![](https://i.imgur.com/UxXQFQO.png) ## Heap Red Zones ![](https://i.imgur.com/9E0kWl2.png) ![](https://i.imgur.com/7DgPsrG.png) ![](https://i.imgur.com/3paP55K.png) ## Stack Red Zones ![](https://i.imgur.com/5EBchUO.png) ![](https://i.imgur.com/QZfHgjl.png) ## ContainerOverflow ![](https://i.imgur.com/pIoVAaH.png) ## The instrumentation ![](https://i.imgur.com/JzmRboQ.png) ## Memory Overhead ![](https://i.imgur.com/UtDAPiW.png)