cfi.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. //===-------- cfi.cpp -----------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the runtime support for the cross-DSO CFI.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include <assert.h>
  13. #include <elf.h>
  14. #include "sanitizer_common/sanitizer_common.h"
  15. #if SANITIZER_FREEBSD
  16. #error #include <sys/link_elf.h>
  17. #endif
  18. #include <link.h>
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include <sys/mman.h>
  22. #if SANITIZER_LINUX
  23. typedef ElfW(Phdr) Elf_Phdr;
  24. typedef ElfW(Ehdr) Elf_Ehdr;
  25. typedef ElfW(Addr) Elf_Addr;
  26. typedef ElfW(Sym) Elf_Sym;
  27. typedef ElfW(Dyn) Elf_Dyn;
  28. #elif SANITIZER_FREEBSD
  29. #if SANITIZER_WORDSIZE == 64
  30. #define ElfW64_Dyn Elf_Dyn
  31. #define ElfW64_Sym Elf_Sym
  32. #else
  33. #define ElfW32_Dyn Elf_Dyn
  34. #define ElfW32_Sym Elf_Sym
  35. #endif
  36. #endif
  37. #include "interception/interception.h"
  38. #include "sanitizer_common/sanitizer_flag_parser.h"
  39. #include "ubsan/ubsan_init.h"
  40. #include "ubsan/ubsan_flags.h"
  41. #ifdef CFI_ENABLE_DIAG
  42. #include "ubsan/ubsan_handlers.h"
  43. #endif
  44. using namespace __sanitizer;
  45. namespace __cfi {
  46. #define kCfiShadowLimitsStorageSize 4096 // 1 page
  47. // Lets hope that the data segment is mapped with 4K pages.
  48. // The pointer to the cfi shadow region is stored at the start of this page.
  49. // The rest of the page is unused and re-mapped read-only.
  50. static union {
  51. char space[kCfiShadowLimitsStorageSize];
  52. struct {
  53. uptr start;
  54. uptr size;
  55. } limits;
  56. } cfi_shadow_limits_storage
  57. __attribute__((aligned(kCfiShadowLimitsStorageSize)));
  58. static constexpr uptr kShadowGranularity = 12;
  59. static constexpr uptr kShadowAlign = 1UL << kShadowGranularity; // 4096
  60. static constexpr uint16_t kInvalidShadow = 0;
  61. static constexpr uint16_t kUncheckedShadow = 0xFFFFU;
  62. // Get the start address of the CFI shadow region.
  63. uptr GetShadow() {
  64. return cfi_shadow_limits_storage.limits.start;
  65. }
  66. uptr GetShadowSize() {
  67. return cfi_shadow_limits_storage.limits.size;
  68. }
  69. // This will only work while the shadow is not allocated.
  70. void SetShadowSize(uptr size) {
  71. cfi_shadow_limits_storage.limits.size = size;
  72. }
  73. uptr MemToShadowOffset(uptr x) {
  74. return (x >> kShadowGranularity) << 1;
  75. }
  76. uint16_t *MemToShadow(uptr x, uptr shadow_base) {
  77. return (uint16_t *)(shadow_base + MemToShadowOffset(x));
  78. }
  79. typedef int (*CFICheckFn)(u64, void *, void *);
  80. // This class reads and decodes the shadow contents.
  81. class ShadowValue {
  82. uptr addr;
  83. uint16_t v;
  84. explicit ShadowValue(uptr addr, uint16_t v) : addr(addr), v(v) {}
  85. public:
  86. bool is_invalid() const { return v == kInvalidShadow; }
  87. bool is_unchecked() const { return v == kUncheckedShadow; }
  88. CFICheckFn get_cfi_check() const {
  89. assert(!is_invalid() && !is_unchecked());
  90. uptr aligned_addr = addr & ~(kShadowAlign - 1);
  91. uptr p = aligned_addr - (((uptr)v - 1) << kShadowGranularity);
  92. return reinterpret_cast<CFICheckFn>(p);
  93. }
  94. // Load a shadow value for the given application memory address.
  95. static const ShadowValue load(uptr addr) {
  96. uptr shadow_base = GetShadow();
  97. uptr shadow_offset = MemToShadowOffset(addr);
  98. if (shadow_offset > GetShadowSize())
  99. return ShadowValue(addr, kInvalidShadow);
  100. else
  101. return ShadowValue(
  102. addr, *reinterpret_cast<uint16_t *>(shadow_base + shadow_offset));
  103. }
  104. };
  105. class ShadowBuilder {
  106. uptr shadow_;
  107. public:
  108. // Allocate a new empty shadow (for the entire address space) on the side.
  109. void Start();
  110. // Mark the given address range as unchecked.
  111. // This is used for uninstrumented libraries like libc.
  112. // Any CFI check with a target in that range will pass.
  113. void AddUnchecked(uptr begin, uptr end);
  114. // Mark the given address range as belonging to a library with the given
  115. // cfi_check function.
  116. void Add(uptr begin, uptr end, uptr cfi_check);
  117. // Finish shadow construction. Atomically switch the current active shadow
  118. // region with the newly constructed one and deallocate the former.
  119. void Install();
  120. };
  121. void ShadowBuilder::Start() {
  122. shadow_ = (uptr)MmapNoReserveOrDie(GetShadowSize(), "CFI shadow");
  123. VReport(1, "CFI: shadow at %zx .. %zx\n", shadow_, shadow_ + GetShadowSize());
  124. }
  125. void ShadowBuilder::AddUnchecked(uptr begin, uptr end) {
  126. uint16_t *shadow_begin = MemToShadow(begin, shadow_);
  127. uint16_t *shadow_end = MemToShadow(end - 1, shadow_) + 1;
  128. // memset takes a byte, so our unchecked shadow value requires both bytes to
  129. // be the same. Make sure we're ok during compilation.
  130. static_assert((kUncheckedShadow & 0xff) == ((kUncheckedShadow >> 8) & 0xff),
  131. "Both bytes of the 16-bit value must be the same!");
  132. memset(shadow_begin, kUncheckedShadow & 0xff,
  133. (shadow_end - shadow_begin) * sizeof(*shadow_begin));
  134. }
  135. void ShadowBuilder::Add(uptr begin, uptr end, uptr cfi_check) {
  136. assert((cfi_check & (kShadowAlign - 1)) == 0);
  137. // Don't fill anything below cfi_check. We can not represent those addresses
  138. // in the shadow, and must make sure at codegen to place all valid call
  139. // targets above cfi_check.
  140. begin = Max(begin, cfi_check);
  141. uint16_t *s = MemToShadow(begin, shadow_);
  142. uint16_t *s_end = MemToShadow(end - 1, shadow_) + 1;
  143. uint16_t sv = ((begin - cfi_check) >> kShadowGranularity) + 1;
  144. for (; s < s_end; s++, sv++)
  145. *s = sv;
  146. }
  147. #if SANITIZER_LINUX || SANITIZER_FREEBSD || SANITIZER_NETBSD
  148. void ShadowBuilder::Install() {
  149. MprotectReadOnly(shadow_, GetShadowSize());
  150. uptr main_shadow = GetShadow();
  151. if (main_shadow) {
  152. // Update.
  153. #if SANITIZER_LINUX
  154. void *res = mremap((void *)shadow_, GetShadowSize(), GetShadowSize(),
  155. MREMAP_MAYMOVE | MREMAP_FIXED, (void *)main_shadow);
  156. CHECK(res != MAP_FAILED);
  157. #elif SANITIZER_NETBSD
  158. void *res = mremap((void *)shadow_, GetShadowSize(), (void *)main_shadow,
  159. GetShadowSize(), MAP_FIXED);
  160. CHECK(res != MAP_FAILED);
  161. #else
  162. void *res = MmapFixedOrDie(shadow_, GetShadowSize(), "cfi shadow");
  163. CHECK(res != MAP_FAILED);
  164. ::memcpy(&shadow_, &main_shadow, GetShadowSize());
  165. #endif
  166. } else {
  167. // Initial setup.
  168. CHECK_EQ(kCfiShadowLimitsStorageSize, GetPageSizeCached());
  169. CHECK_EQ(0, GetShadow());
  170. cfi_shadow_limits_storage.limits.start = shadow_;
  171. MprotectReadOnly((uptr)&cfi_shadow_limits_storage,
  172. sizeof(cfi_shadow_limits_storage));
  173. CHECK_EQ(shadow_, GetShadow());
  174. }
  175. }
  176. #else
  177. #error not implemented
  178. #endif
  179. // This is a workaround for a glibc bug:
  180. // https://sourceware.org/bugzilla/show_bug.cgi?id=15199
  181. // Other platforms can, hopefully, just do
  182. // dlopen(RTLD_NOLOAD | RTLD_LAZY)
  183. // dlsym("__cfi_check").
  184. uptr find_cfi_check_in_dso(dl_phdr_info *info) {
  185. const Elf_Dyn *dynamic = nullptr;
  186. for (int i = 0; i < info->dlpi_phnum; ++i) {
  187. if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
  188. dynamic =
  189. (const Elf_Dyn *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
  190. break;
  191. }
  192. }
  193. if (!dynamic) return 0;
  194. uptr strtab = 0, symtab = 0, strsz = 0;
  195. for (const Elf_Dyn *p = dynamic; p->d_tag != PT_NULL; ++p) {
  196. if (p->d_tag == DT_SYMTAB)
  197. symtab = p->d_un.d_ptr;
  198. else if (p->d_tag == DT_STRTAB)
  199. strtab = p->d_un.d_ptr;
  200. else if (p->d_tag == DT_STRSZ)
  201. strsz = p->d_un.d_ptr;
  202. }
  203. if (symtab > strtab) {
  204. VReport(1, "Can not handle: symtab > strtab (%zx > %zx)\n", symtab, strtab);
  205. return 0;
  206. }
  207. // Verify that strtab and symtab are inside of the same LOAD segment.
  208. // This excludes VDSO, which has (very high) bogus strtab and symtab pointers.
  209. int phdr_idx;
  210. for (phdr_idx = 0; phdr_idx < info->dlpi_phnum; phdr_idx++) {
  211. const Elf_Phdr *phdr = &info->dlpi_phdr[phdr_idx];
  212. if (phdr->p_type == PT_LOAD) {
  213. uptr beg = info->dlpi_addr + phdr->p_vaddr;
  214. uptr end = beg + phdr->p_memsz;
  215. if (strtab >= beg && strtab + strsz < end && symtab >= beg &&
  216. symtab < end)
  217. break;
  218. }
  219. }
  220. if (phdr_idx == info->dlpi_phnum) {
  221. // Nope, either different segments or just bogus pointers.
  222. // Can not handle this.
  223. VReport(1, "Can not handle: symtab %zx, strtab %zx\n", symtab, strtab);
  224. return 0;
  225. }
  226. for (const Elf_Sym *p = (const Elf_Sym *)symtab; (Elf_Addr)p < strtab;
  227. ++p) {
  228. // There is no reliable way to find the end of the symbol table. In
  229. // lld-produces files, there are other sections between symtab and strtab.
  230. // Stop looking when the symbol name is not inside strtab.
  231. if (p->st_name >= strsz) break;
  232. char *name = (char*)(strtab + p->st_name);
  233. if (strcmp(name, "__cfi_check") == 0) {
  234. assert(p->st_info == ELF32_ST_INFO(STB_GLOBAL, STT_FUNC) ||
  235. p->st_info == ELF32_ST_INFO(STB_WEAK, STT_FUNC));
  236. uptr addr = info->dlpi_addr + p->st_value;
  237. return addr;
  238. }
  239. }
  240. return 0;
  241. }
  242. int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *data) {
  243. uptr cfi_check = find_cfi_check_in_dso(info);
  244. if (cfi_check)
  245. VReport(1, "Module '%s' __cfi_check %zx\n", info->dlpi_name, cfi_check);
  246. ShadowBuilder *b = reinterpret_cast<ShadowBuilder *>(data);
  247. for (int i = 0; i < info->dlpi_phnum; i++) {
  248. const Elf_Phdr *phdr = &info->dlpi_phdr[i];
  249. if (phdr->p_type == PT_LOAD) {
  250. // Jump tables are in the executable segment.
  251. // VTables are in the non-executable one.
  252. // Need to fill shadow for both.
  253. // FIXME: reject writable if vtables are in the r/o segment. Depend on
  254. // PT_RELRO?
  255. uptr cur_beg = info->dlpi_addr + phdr->p_vaddr;
  256. uptr cur_end = cur_beg + phdr->p_memsz;
  257. if (cfi_check) {
  258. VReport(1, " %zx .. %zx\n", cur_beg, cur_end);
  259. b->Add(cur_beg, cur_end, cfi_check);
  260. } else {
  261. b->AddUnchecked(cur_beg, cur_end);
  262. }
  263. }
  264. }
  265. return 0;
  266. }
  267. // Init or update shadow for the current set of loaded libraries.
  268. void UpdateShadow() {
  269. ShadowBuilder b;
  270. b.Start();
  271. dl_iterate_phdr(dl_iterate_phdr_cb, &b);
  272. b.Install();
  273. }
  274. void InitShadow() {
  275. CHECK_EQ(0, GetShadow());
  276. CHECK_EQ(0, GetShadowSize());
  277. uptr vma = GetMaxUserVirtualAddress();
  278. // Shadow is 2 -> 2**kShadowGranularity.
  279. SetShadowSize((vma >> (kShadowGranularity - 1)) + 1);
  280. VReport(1, "CFI: VMA size %zx, shadow size %zx\n", vma, GetShadowSize());
  281. UpdateShadow();
  282. }
  283. THREADLOCAL int in_loader;
  284. Mutex shadow_update_lock;
  285. void EnterLoader() SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
  286. if (in_loader == 0) {
  287. shadow_update_lock.Lock();
  288. }
  289. ++in_loader;
  290. }
  291. void ExitLoader() SANITIZER_NO_THREAD_SAFETY_ANALYSIS {
  292. CHECK(in_loader > 0);
  293. --in_loader;
  294. UpdateShadow();
  295. if (in_loader == 0) {
  296. shadow_update_lock.Unlock();
  297. }
  298. }
  299. ALWAYS_INLINE void CfiSlowPathCommon(u64 CallSiteTypeId, void *Ptr,
  300. void *DiagData) {
  301. uptr Addr = (uptr)Ptr;
  302. VReport(3, "__cfi_slowpath: %llx, %p\n", CallSiteTypeId, Ptr);
  303. ShadowValue sv = ShadowValue::load(Addr);
  304. if (sv.is_invalid()) {
  305. VReport(1, "CFI: invalid memory region for a check target: %p\n", Ptr);
  306. #ifdef CFI_ENABLE_DIAG
  307. if (DiagData) {
  308. __ubsan_handle_cfi_check_fail(
  309. reinterpret_cast<__ubsan::CFICheckFailData *>(DiagData), Addr, false);
  310. return;
  311. }
  312. #endif
  313. Trap();
  314. }
  315. if (sv.is_unchecked()) {
  316. VReport(2, "CFI: unchecked call (shadow=FFFF): %p\n", Ptr);
  317. return;
  318. }
  319. CFICheckFn cfi_check = sv.get_cfi_check();
  320. VReport(2, "__cfi_check at %p\n", (void *)cfi_check);
  321. cfi_check(CallSiteTypeId, Ptr, DiagData);
  322. }
  323. void InitializeFlags() {
  324. SetCommonFlagsDefaults();
  325. #ifdef CFI_ENABLE_DIAG
  326. __ubsan::Flags *uf = __ubsan::flags();
  327. uf->SetDefaults();
  328. #endif
  329. FlagParser cfi_parser;
  330. RegisterCommonFlags(&cfi_parser);
  331. cfi_parser.ParseStringFromEnv("CFI_OPTIONS");
  332. #ifdef CFI_ENABLE_DIAG
  333. FlagParser ubsan_parser;
  334. __ubsan::RegisterUbsanFlags(&ubsan_parser, uf);
  335. RegisterCommonFlags(&ubsan_parser);
  336. const char *ubsan_default_options = __ubsan_default_options();
  337. ubsan_parser.ParseString(ubsan_default_options);
  338. ubsan_parser.ParseStringFromEnv("UBSAN_OPTIONS");
  339. #endif
  340. InitializeCommonFlags();
  341. if (Verbosity())
  342. ReportUnrecognizedFlags();
  343. if (common_flags()->help) {
  344. cfi_parser.PrintFlagDescriptions();
  345. }
  346. }
  347. } // namespace __cfi
  348. using namespace __cfi;
  349. extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
  350. __cfi_slowpath(u64 CallSiteTypeId, void *Ptr) {
  351. CfiSlowPathCommon(CallSiteTypeId, Ptr, nullptr);
  352. }
  353. #ifdef CFI_ENABLE_DIAG
  354. extern "C" SANITIZER_INTERFACE_ATTRIBUTE void
  355. __cfi_slowpath_diag(u64 CallSiteTypeId, void *Ptr, void *DiagData) {
  356. CfiSlowPathCommon(CallSiteTypeId, Ptr, DiagData);
  357. }
  358. #endif
  359. static void EnsureInterceptorsInitialized();
  360. // Setup shadow for dlopen()ed libraries.
  361. // The actual shadow setup happens after dlopen() returns, which means that
  362. // a library can not be a target of any CFI checks while its constructors are
  363. // running. It's unclear how to fix this without some extra help from libc.
  364. // In glibc, mmap inside dlopen is not interceptable.
  365. // Maybe a seccomp-bpf filter?
  366. // We could insert a high-priority constructor into the library, but that would
  367. // not help with the uninstrumented libraries.
  368. INTERCEPTOR(void*, dlopen, const char *filename, int flag) {
  369. EnsureInterceptorsInitialized();
  370. EnterLoader();
  371. void *handle = REAL(dlopen)(filename, flag);
  372. ExitLoader();
  373. return handle;
  374. }
  375. INTERCEPTOR(int, dlclose, void *handle) {
  376. EnsureInterceptorsInitialized();
  377. EnterLoader();
  378. int res = REAL(dlclose)(handle);
  379. ExitLoader();
  380. return res;
  381. }
  382. static Mutex interceptor_init_lock;
  383. static bool interceptors_inited = false;
  384. static void EnsureInterceptorsInitialized() {
  385. Lock lock(&interceptor_init_lock);
  386. if (interceptors_inited)
  387. return;
  388. INTERCEPT_FUNCTION(dlopen);
  389. INTERCEPT_FUNCTION(dlclose);
  390. interceptors_inited = true;
  391. }
  392. extern "C" SANITIZER_INTERFACE_ATTRIBUTE
  393. #if !SANITIZER_CAN_USE_PREINIT_ARRAY
  394. // On ELF platforms, the constructor is invoked using .preinit_array (see below)
  395. __attribute__((constructor(0)))
  396. #endif
  397. void __cfi_init() {
  398. SanitizerToolName = "CFI";
  399. InitializeFlags();
  400. InitShadow();
  401. #ifdef CFI_ENABLE_DIAG
  402. __ubsan::InitAsPlugin();
  403. #endif
  404. }
  405. #if SANITIZER_CAN_USE_PREINIT_ARRAY
  406. // On ELF platforms, run cfi initialization before any other constructors.
  407. // On other platforms we use the constructor attribute to arrange to run our
  408. // initialization early.
  409. extern "C" {
  410. __attribute__((section(".preinit_array"),
  411. used)) void (*__cfi_preinit)(void) = __cfi_init;
  412. }
  413. #endif