438 lines · plain
1======================2Control Flow Integrity3======================4 5.. toctree::6 :hidden:7 8 ControlFlowIntegrityDesign9 10.. contents::11 :local:12 13Introduction14============15 16Clang includes an implementation of a number of control flow integrity (CFI)17schemes, which are designed to abort the program upon detecting certain forms18of undefined behavior that can potentially allow attackers to subvert the19program's control flow. These schemes have been optimized for performance,20allowing developers to enable them in release builds.21 22To enable Clang's available CFI schemes, use the flag23``-fsanitize=cfi``. You can also enable a subset of available24:ref:`schemes <cfi-schemes>`. As currently implemented, all schemes25except for ``kcfi`` rely on link-time optimization (LTO); so it is26required to specify ``-flto`` or ``-flto=thin``, and the linker used27must support LTO, for example via the `gold plugin`_.28 29To allow the checks to be implemented efficiently, the program must30be structured such that certain object files are compiled with CFI31enabled, and are statically linked into the program. This may preclude32the use of shared libraries in some cases.33 34The compiler will only produce CFI checks for a class if it can infer hidden35LTO visibility for that class. LTO visibility is a property of a class that36is inferred from flags and attributes. For more details, see the documentation37for :doc:`LTO visibility <LTOVisibility>`.38 39The ``-fsanitize=cfi-{vcall,nvcall,derived-cast,unrelated-cast}`` flags40require that a ``-fvisibility=`` flag also be specified. This is because the41default visibility setting is ``-fvisibility=default``, which would disable42CFI checks for classes without visibility attributes. Most users will want43to specify ``-fvisibility=hidden``, which enables CFI checks for such classes.44 45When using ``-fsanitize=cfi*`` with ``-flto=thin``, it is recommended46to reduce link times by passing `-funique-source-file-names47<UsersManual.html#cmdoption-f-no-unique-source-file-names>`_, provided48that your program is compatible with it.49 50Experimental support for :ref:`cross-DSO control flow integrity51<cfi-cross-dso>` exists that does not require classes to have hidden LTO52visibility. This cross-DSO support has unstable ABI at this time.53 54.. _gold plugin: https://llvm.org/docs/GoldPlugin.html55 56.. _cfi-schemes:57 58Available schemes59=================60 61Available schemes are:62 63 - ``-fsanitize=cfi-cast-strict``: Enables :ref:`strict cast checks64 <cfi-strictness>`.65 - ``-fsanitize=cfi-derived-cast``: Base-to-derived cast to the wrong66 dynamic type.67 - ``-fsanitize=cfi-unrelated-cast``: Cast from ``void*`` or another68 unrelated type to the wrong dynamic type.69 - ``-fsanitize=cfi-nvcall``: Non-virtual call via an object whose vptr is of70 the wrong dynamic type.71 - ``-fsanitize=cfi-vcall``: Virtual call via an object whose vptr is of the72 wrong dynamic type.73 - ``-fsanitize=cfi-icall``: Indirect call of a function with wrong dynamic74 type.75 - ``-fsanitize=cfi-mfcall``: Indirect call via a member function pointer with76 wrong dynamic type.77 78You can use ``-fsanitize=cfi`` to enable all the schemes and use79``-fno-sanitize`` flag to narrow down the set of schemes as desired.80For example, you can build your program with81``-fsanitize=cfi -fno-sanitize=cfi-nvcall,cfi-icall``82to use all schemes except for non-virtual member function call and indirect call83checking.84 85Remember that you have to provide ``-flto`` or ``-flto=thin`` if at86least one CFI scheme is enabled.87 88Trapping and Diagnostics89========================90 91By default, CFI will abort the program immediately upon detecting a control92flow integrity violation. You can use the :ref:`-fno-sanitize-trap=93<controlling-code-generation>` flag to cause CFI to print a diagnostic94similar to the one below before the program aborts.95 96.. code-block:: console97 98 bad-cast.cpp:109:7: runtime error: control flow integrity check for type 'B' failed during base-to-derived cast (vtable address 0x000000425a50)99 0x000000425a50: note: vtable is of type 'A'100 00 00 00 00 f0 f1 41 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 20 5a 42 00101 ^102 103If diagnostics are enabled, you can also configure CFI to continue program104execution instead of aborting by using the :ref:`-fsanitize-recover=105<controlling-code-generation>` flag.106 107Forward-Edge CFI for Virtual Calls108==================================109 110This scheme checks that virtual calls take place using a vptr of the correct111dynamic type; that is, the dynamic type of the called object must be a112derived class of the static type of the object used to make the call.113This CFI scheme can be enabled on its own using ``-fsanitize=cfi-vcall``.114 115For this scheme to work, all translation units containing the definition116of a virtual member function (whether inline or not), other than members117of :ref:`ignored <cfi-ignorelist>` types or types with public :doc:`LTO118visibility <LTOVisibility>`, must be compiled with ``-flto`` or ``-flto=thin``119enabled and be statically linked into the program.120 121Performance122-----------123 124A performance overhead of less than 1% has been measured by running the125Dromaeo benchmark suite against an instrumented version of the Chromium126web browser. Another good performance benchmark for this mechanism is the127virtual-call-heavy SPEC 2006 xalancbmk.128 129Note that this scheme has not yet been optimized for binary size; an increase130of up to 15% has been observed for Chromium.131 132Bad Cast Checking133=================134 135This scheme checks that pointer casts are made to an object of the correct136dynamic type; that is, the dynamic type of the object must be a derived class137of the pointee type of the cast. The checks are currently only introduced138where the class being cast to is a polymorphic class.139 140Bad casts are not in themselves control flow integrity violations, but they141can also create security vulnerabilities, and the implementation uses many142of the same mechanisms.143 144There are two types of bad cast that may be forbidden: bad casts145from a base class to a derived class (which can be checked with146``-fsanitize=cfi-derived-cast``), and bad casts from a pointer of147type ``void*`` or another unrelated type (which can be checked with148``-fsanitize=cfi-unrelated-cast``).149 150The difference between these two types of casts is that the first is defined151by the C++ standard to produce an undefined value, while the second is not152in itself undefined behavior (it is well defined to cast the pointer back153to its original type) unless the object is uninitialized and the cast is a154``static_cast`` (see C++14 [basic.life]p5).155 156If a program as a matter of policy forbids the second type of cast, that157restriction can normally be enforced. However it may in some cases be necessary158for a function to perform a forbidden cast to conform with an external API159(e.g. the ``allocate`` member function of a standard library allocator). Such160functions may be :ref:`ignored <cfi-ignorelist>`.161 162For this scheme to work, all translation units containing the definition163of a virtual member function (whether inline or not), other than members164of :ref:`ignored <cfi-ignorelist>` types or types with public :doc:`LTO165visibility <LTOVisibility>`, must be compiled with ``-flto`` or ``-flto=thin``166enabled and be statically linked into the program.167 168Non-Virtual Member Function Call Checking169=========================================170 171This scheme checks that non-virtual calls take place using an object of172the correct dynamic type; that is, the dynamic type of the called object173must be a derived class of the static type of the object used to make the174call. The checks are currently only introduced where the object is of a175polymorphic class type. This CFI scheme can be enabled on its own using176``-fsanitize=cfi-nvcall``.177 178For this scheme to work, all translation units containing the definition179of a virtual member function (whether inline or not), other than members180of :ref:`ignored <cfi-ignorelist>` types or types with public :doc:`LTO181visibility <LTOVisibility>`, must be compiled with ``-flto`` or ``-flto=thin``182enabled and be statically linked into the program.183 184.. _cfi-strictness:185 186Strictness187----------188 189If a class has a single non-virtual base and does not introduce or override190virtual member functions or fields other than an implicitly defined virtual191destructor, it will have the same layout and virtual function semantics as192its base. By default, casts to such classes are checked as if they were made193to the least derived such class.194 195Casting an instance of a base class to such a derived class is technically196undefined behavior, but it is a relatively common hack for introducing197member functions on class instances with specific properties that works under198most compilers and should not have security implications, so we allow it by199default. It can be disabled with ``-fsanitize=cfi-cast-strict``.200 201Indirect Function Call Checking202===============================203 204This scheme checks that function calls take place using a function of the205correct dynamic type; that is, the dynamic type of the function must match206the static type used at the call. This CFI scheme can be enabled on its own207using ``-fsanitize=cfi-icall``.208 209For this scheme to work, each indirect function call in the program, other210than calls in :ref:`ignored <cfi-ignorelist>` functions, must call a211function which was either compiled with ``-fsanitize=cfi-icall`` enabled,212or whose address was taken by a function in a translation unit compiled with213``-fsanitize=cfi-icall``.214 215If a function in a translation unit compiled with ``-fsanitize=cfi-icall``216takes the address of a function not compiled with ``-fsanitize=cfi-icall``,217that address may differ from the address taken by a function in a translation218unit not compiled with ``-fsanitize=cfi-icall``. This is technically a219violation of the C and C++ standards, but it should not affect most programs.220 221Each translation unit compiled with ``-fsanitize=cfi-icall`` must be222statically linked into the program or shared library, and calls across223shared library boundaries are handled as if the callee was not compiled with224``-fsanitize=cfi-icall``.225 226This scheme is currently supported on a limited set of targets: x86,227x86_64, arm, arch64 and wasm.228 229``-fsanitize-cfi-icall-generalize-pointers``230--------------------------------------------231 232Mismatched pointer types are a common cause of cfi-icall check failures.233Translation units compiled with the ``-fsanitize-cfi-icall-generalize-pointers``234flag relax pointer type checking for call sites in that translation unit,235applied across all functions compiled with ``-fsanitize=cfi-icall``.236 237Specifically, pointers in return and argument types are treated as equivalent as238long as the qualifiers for the type they point to match. For example, ``char*``,239``char**``, and ``int*`` are considered equivalent types. However, ``char*`` and240``const char*`` are considered separate types.241 242``-fsanitize-cfi-icall-generalize-pointers`` is not compatible with243``-fsanitize-cfi-cross-dso``.244 245.. _cfi-icall-experimental-normalize-integers:246 247``-fsanitize-cfi-icall-experimental-normalize-integers``248--------------------------------------------------------249 250This option enables normalizing integer types as vendor extended types for251cross-language LLVM CFI/KCFI support with other languages that can't represent252and encode C/C++ integer types.253 254Specifically, integer types are encoded as their defined representations (e.g.,2558-bit signed integer, 16-bit signed integer, 32-bit signed integer, ...) for256compatibility with languages that define explicitly-sized integer types (e.g.,257i8, i16, i32, ..., in Rust).258 259``-fsanitize-cfi-icall-experimental-normalize-integers`` is compatible with260``-fsanitize-cfi-icall-generalize-pointers``.261 262This option is currently experimental.263 264.. _cfi-canonical-jump-tables:265 266``-fsanitize-cfi-canonical-jump-tables``267----------------------------------------268 269The default behavior of Clang's indirect function call checker will replace270the address of each CFI-checked function in the output file's symbol table271with the address of a jump table entry which will pass CFI checks. We refer272to this as making the jump table `canonical`. This property allows code that273was not compiled with ``-fsanitize=cfi-icall`` to take a CFI-valid address274of a function, but it comes with a couple of caveats that are especially275relevant for users of cross-DSO CFI:276 277- There is a performance and code size overhead associated with each278 exported function, because each such function must have an associated279 jump table entry, which must be emitted even in the common case where the280 function is never address-taken anywhere in the program, and must be used281 even for direct calls between DSOs, in addition to the PLT overhead.282 283- There is no good way to take a CFI-valid address of a function written in284 assembly or a language not supported by Clang. The reason is that the code285 generator would need to insert a jump table in order to form a CFI-valid286 address for assembly functions, but there is no way in general for the287 code generator to determine the language of the function. This may be288 possible with LTO in the intra-DSO case, but in the cross-DSO case the only289 information available is the function declaration. One possible solution290 is to add a C wrapper for each assembly function, but these wrappers can291 present a significant maintenance burden for heavy users of assembly in292 addition to adding runtime overhead.293 294For these reasons, we provide the option of making the jump table non-canonical295with the flag ``-fno-sanitize-cfi-canonical-jump-tables``. When the jump296table is made non-canonical, symbol table entries point directly to the297function body. Any instances of a function's address being taken in C will298be replaced with a jump table address.299 300This scheme does have its own caveats, however. It does end up breaking301function address equality more aggressively than the default behavior,302especially in cross-DSO mode which normally preserves function address303equality entirely.304 305Furthermore, it is occasionally necessary for code not compiled with306``-fsanitize=cfi-icall`` to take a function address that is valid307for CFI. For example, this is necessary when a function's address308is taken by assembly code and then called by CFI-checking C code. The309``__attribute__((cfi_canonical_jump_table))`` attribute may be used to make310the jump table entry of a specific function canonical so that the external311code will end up taking an address for the function that will pass CFI checks.312 313``-fsanitize=cfi-icall`` and ``-fsanitize=function``314----------------------------------------------------315 316This tool is similar to ``-fsanitize=function`` in that both tools check317the types of function calls. However, the two tools occupy different points318on the design space; ``-fsanitize=function`` is a developer tool designed319to find bugs in local development builds, whereas ``-fsanitize=cfi-icall``320is a security hardening mechanism designed to be deployed in release builds.321 322``-fsanitize=function`` has a higher space and time overhead due to a more323complex type check at indirect call sites, which may make it unsuitable for324deployment.325 326On the other hand, ``-fsanitize=function`` conforms more closely with the C++327standard and user expectations around interaction with shared libraries;328the identity of function pointers is maintained, and calls across shared329library boundaries are no different from calls within a single program or330shared library.331 332.. _kcfi:333 334``-fsanitize=kcfi``335-------------------336 337This is an alternative indirect call control-flow integrity scheme designed338for low-level system software, such as operating system kernels. Unlike339``-fsanitize=cfi-icall``, it doesn't require ``-flto``, won't result in340function pointers being replaced with jump table references, and never breaks341cross-DSO function address equality. These properties make KCFI easier to342adopt in low-level software. KCFI is limited to checking only function343pointers, and isn't compatible with executable-only memory.344 345``-fsanitize-kcfi-arity``346-----------------------------347 348For supported targets, this feature extends kCFI by telling the compiler to349record information about each indirect-callable function's arity (i.e., the350number of arguments passed in registers) into the binary. Some kernel CFI351techniques, such as FineIBT, may be able to use this information to provide352enhanced security.353 354Member Function Pointer Call Checking355=====================================356 357This scheme checks that indirect calls via a member function pointer358take place using an object of the correct dynamic type. Specifically, we359check that the dynamic type of the member function referenced by the member360function pointer matches the "function pointer" part of the member function361pointer, and that the member function's class type is related to the base362type of the member function. This CFI scheme can be enabled on its own using363``-fsanitize=cfi-mfcall``.364 365The compiler will only emit a full CFI check if the member function pointer's366base type is complete. This is because the complete definition of the base367type contains information that is necessary to correctly compile the CFI368check. To ensure that the compiler always emits a full CFI check, it is369recommended to also pass the flag ``-fcomplete-member-pointers``, which370enables a non-conforming language extension that requires member pointer371base types to be complete if they may be used for a call.372 373For this scheme to work, all translation units containing the definition374of a virtual member function (whether inline or not), other than members375of :ref:`ignored <cfi-ignorelist>` types or types with public :doc:`LTO376visibility <LTOVisibility>`, must be compiled with ``-flto`` or ``-flto=thin``377enabled and be statically linked into the program.378 379This scheme is currently not compatible with cross-DSO CFI or the380Microsoft ABI.381 382.. _cfi-ignorelist:383 384Ignorelist385==========386 387A :doc:`SanitizerSpecialCaseList` can be used to relax CFI checks for certain388source files, functions and types using the ``src``, ``fun`` and ``type``389entity types. Specific CFI modes can be be specified using ``[section]``390headers.391 392.. code-block:: bash393 394 # Suppress all CFI checking for code in a file.395 src:bad_file.cpp396 src:bad_header.h397 # Ignore all functions with names containing MyFooBar.398 fun:*MyFooBar*399 # Ignore all types in the standard library.400 type:std::*401 # Disable only unrelated cast checks for this function402 [cfi-unrelated-cast]403 fun:*UnrelatedCast*404 # Disable CFI call checks for this function without affecting cast checks405 [cfi-vcall|cfi-nvcall|cfi-icall]406 fun:*BadCall*407 408 409.. _cfi-cross-dso:410 411Shared library support412======================413 414Use **-f[no-]sanitize-cfi-cross-dso** to enable the cross-DSO control415flow integrity mode, which allows all CFI schemes listed above to416apply across DSO boundaries. As in the regular CFI, each DSO must be417built with ``-flto`` or ``-flto=thin``.418 419Normally, CFI checks will only be performed for classes that have hidden LTO420visibility. With this flag enabled, the compiler will emit cross-DSO CFI421checks for all classes, except for those which appear in the CFI ignorelist422or which use a ``no_sanitize`` attribute.423 424Design425======426 427Please refer to the :doc:`design document<ControlFlowIntegrityDesign>`.428 429Publications430============431 432`Control-Flow Integrity: Principles, Implementations, and Applications <https://research.microsoft.com/pubs/64250/ccs05.pdf>`_.433Martin Abadi, Mihai Budiu, Úlfar Erlingsson, Jay Ligatti.434 435`Enforcing Forward-Edge Control-Flow Integrity in GCC & LLVM <https://www.usenix.org/system/files/conference/usenixsecurity14/sec14-paper-tice.pdf>`_.436Caroline Tice, Tom Roeder, Peter Collingbourne, Stephen Checkoway,437Úlfar Erlingsson, Luis Lozano, Geoff Pike.438