Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Broadening compiler checks for buffer overflows in _FORTIFY_SOURCE

April 16, 2021
Siddhesh Poyarekar
Related topics:
C, C#, C++LinuxSecurity
Related products:
Red Hat Enterprise Linux

Share:

    Buffer overruns are by far the most common vulnerability in C or C++ programs, and a number of techniques have come up over the years to detect overruns early and abort execution. The _FORTIFY_SOURCE macro, provided by the GNU C Library, helps mitigate a number of these overruns and is widely deployed in Red Hat Enterprise Linux. This article on the Red Hat Security blog is a good introduction to _FORTIFY_SOURCE.

    In the GNU C Library's 2.33 release, we added a new level for _FORTIFY_SOURCE to improve the protections the macro provides. Here we take a closer look at the internals of _FORTIFY_SOURCE in GCC and explore the need for this new level.

    _FORTIFY_SOURCE under the hood

    The _FORTIFY_SOURCE macro replaces some common functions with fortified wrappers that check whether the size of the destination buffer in those functions is large enough to handle the input data. If the check fails, the program aborts, and the users are saved from what could have been an exploitable buffer overflow. The actual implementation of a fortified wrapper function has a lot of glibc-isms, but it is conceptually a wrapper for wmemcpy that looks like the following:

    extern inline wchar_t *
    __attribute__ ((always_inline))
    wmemcpy (wchar_t *__restrict __s1, const wchar_t *__restrict __s2, size_t __n)
    {
      if (__builtin_object_size (__s1, 0) != (size_t) -1)
        return __wmemcpy_chk (__s1, __s2, __n,
                              __builtin_object_size (__s1, 0) / sizeof (wchar_t));
      return __original_wmemcpy (__s1, __s2, __n);
    }
    

    The GNU C Library implements similar fortified wrappers for a number of functions. Some wrappers look slightly different; for example, the memcpy wrapper unconditionally calls a builtin named __builtin___memcpy_chk. Those built-ins also evaluate to roughly the wrapper function just shown.

    The cornerstone: __builtin_object_size

    As the sample source code shows, the core functionality of _FORTIFY_SOURCE is based around the __builtin_object_size builtin. This builtin evaluates objects that the first argument (which is a pointer) points to and returns an estimate for the size of the object. Based on the second argument to the builtin, the size may be a minimum estimate or a maximum estimate. If the builtin fails to deduce the object size, then it either returns (size_t)0 or (size_t)-1 depending on whether the minimum or maximum estimate is requested.

    The compiler translates the wrapper to either a call to __wmmcpy_chk or to the original wmemcpy, denoted by __original_wmemcpy in the example above. Most importantly, the compiler optimizes away the __builtin_object_size comparison because it is a constant expression: __builtin_object_size always returns a constant. If __builtin_object_size is unable to deduce a constant object size, the compiler falls back to the default implementation wmemcpy.

    Validate before you leap

    The checking variant of wmemcpy—i.e., __wmemcpy_chk—is trivially implemented as follows:

    wchar_t *
    __wmemcpy_chk (wchar_t *s1, const wchar_t *s2, size_t n, size_t ns1)
    {
      if (__glibc_unlikely (ns1 < n))
        __chk_fail ();
      return (wchar_t *) memcpy ((char *) s1, (char *) s2, n * sizeof (wchar_t));
    }
    

    where __chk_fail aborts the program. At first glance, this looks slow because it adds a condition to every call. However, glibc lays out the performance-sensitive functions in a way that the overhead at runtime is constant, and in practice negligible.

    In the very long term, everything is dynamic

    The obvious extension to this functionality is to allow __builtin_object_size to return non-constant results. That idea eventually took the form of a new builtin called __builtin_dynamic_object_size, implemented in LLVM 9. This builtin intends to be a drop-in replacement for __builtin_object_size, although there some differences. Like __builtin_object_size, the new builtin attempts to evaluate the size of the object to a constant. If the object size is not constant, the builtin tries to deduce an expression that evaluates the size of the object. If even that is not possible, it bails out and returns (size_t)-1 or (size_t)0. Overall, this allows more cases where the size of an object can be known well enough to do something useful with it at runtime.

    A third fortification level

    With glibc 2.33, this support materialized into an actual hardening feature in the form of a new fortification level: _FORTIFY_SOURCE=3. This fortification level widens coverage of cases that _FORTIFY_SOURCE can catch. For example, the following function:

    size_t add_size;
    size_t multiplier;
    
    void *
    do_something (void *in, size_t insz, size_t sz)
    {
      void *buf = malloc ((sz + add_size) * multiplier);
    
      memcpy (buf, in, insz);
    
      return buf;
    }
    

    when built with _FORTIFY_SOURCE=2, does not result in a call to the fortified version of memcpy (i.e., __memcpy_chk). As a result, cases where insz may be bigger than the size of buf slip through.

    With _FORTIFY_SOURCE=3, though, __builtin_dynamic_object_size can evaluate to (sz + add_size) * multiplier. With this expression, the compiler can generate a call to __memcpy_chk and allow fortification. This promises to significantly widen fortification coverage to include cases where the compiler can see the non-constant expression for object size. This is a great improvement, but we decided against implementing this at _FORTIFY_SOURCE level 2.

    Runtime overhead in _FORTIFY_SOURCE=3

    Earlier _FORTIFY_SOURCE levels rely on constant object sizes; because of this, the runtime overhead is negligible. _FORTIFY_SOURCE=3, however, changes that because expressions used to compute the object size can be arbitrarily complex. Complex expressions can add arbitrarily more runtime overhead. Further, consider the possibility of do_something in the previous example being called in a loop; the overhead gets magnified. This was a good enough reason to not sneak this new functionality in under the hood. The new level lets developers tinker around with it and decide whether the overhead was acceptable for their use case.

    What's next for _FORTIFY_SOURCE

    GCC support for __builtin_dynamic_object_size or equivalent functionality is in progress. At the moment this is available only when building applications with LLVM. There are some unspecified corner cases with __builtin_dynamic_object_size that may result in avoidable performance overheads. We hope to iron those out with the GCC implementation and feed it back into LLVM, thus making both implementations consistent and performant.

    _FORTIFY_SOURCE=3 begins a shift in design for source fortification as we accept variable performance overheads for the checking. This also adds potential for additional coverage in the future as compilers get smarter at deducing object sizes. This is hopefully just the beginning!

    Last updated: October 14, 2022

    Recent Posts

    • Create and enrich ServiceNow ITSM tickets with Ansible Automation Platform

    • Expand Model-as-a-Service for secure enterprise AI

    • OpenShift LACP bonding performance expectations

    • Build container images in CI/CD with Tekton and Buildpacks

    • How to deploy OpenShift AI & Service Mesh 3 on one cluster

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue