TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › Type Confusion in C++ (CWE-843)

Type Confusion in C++ (CWE-843)

Type confusion happens when a program treats an object as a type it isn't. The memory is valid, in bounds and alive, so neither spatial nor temporal checks complain; the bytes are simply interpreted wrongly. In C++ the usual culprit is a static_cast from a base class to the wrong derived class, decided by a type tag that came from input or got out of sync. The fields of the assumed type overlay the fields of the real one: an integer is read as a length, a string's bytes as a pointer, another class's vtable as this class's. Browsers' JavaScript engines and document renderers (PDF, Office, fonts), whose object models have hundreds of node types, have produced many exploited type-confusion bugs. The C++ features involved (inheritance, casts, virtual functions) are taught in C++ Polymorphism and C++ Inheritance.

Definitions

  • Downcast: converting Base* to Derived*. static_cast<Derived*>(b) does it with no run-time check; dynamic_cast<Derived*>(b) checks the object's real type (via RTTI) and returns nullptr if it doesn't match.
  • vptr / vtable: every object of a class with virtual functions starts with a pointer (vptr) to its class's table of virtual functions. The vptr is how the program knows an object's real type at run time, and what an attacker wants to control in a confused object.
  • Tagged union / type tag: a field such as kind that says which type an object is. A tag that can be wrong (read from a file, or not updated when the object changes) is a type-confusion bug waiting to happen.

The bug in a toy program

A document has text nodes and image nodes. render trusts the node kind that the file declares, not the node's real type. The third call passes a Text with a file that says "image". The session builds the same program three ways: with GCC's UBSan, with Clang's control-flow integrity (CFI), and plain:

bash · try it yourself
cat > nodes.cpp <<'SRC'
#include <cstdio>

struct Node  { virtual ~Node() = default; int kind = 0; };
struct Text  : Node { Text()  { kind = 1; } char text[8] = "hello"; };
struct Image : Node { Image() { kind = 2; } int width = 640, height = 480; };

/* The kind comes from a document file and is trusted. */
static void render(Node *n, int kind_from_file) {
    if (kind_from_file == 2) {
        Image *im = static_cast<Image *>(n);        /* BUG: n may not be an Image */
        std::printf("image %dx%d\n", im->width, im->height);
    } else {
        std::printf("text \"%s\"\n", static_cast<Text *>(n)->text);
    }
}

int main() {
    std::setvbuf(stdout, nullptr, _IONBF, 0);
    Image img; Text txt;
    render(&img, 2);
    render(&txt, 1);
    render(&txt, 2);                                /* the file lies about the kind */
    return 0;
}
SRC
echo "== g++ -fsanitize=undefined (includes the vptr check)"
g++ -g -O0 -fsanitize=undefined nodes.cpp -o nodes && ./nodes 2>&1 | grep -E '^image|^text|runtime error|note: object'
echo "exit code: ${PIPESTATUS[0]}"
echo "== clang++ -fsanitize=cfi (needs LTO and hidden visibility)"
clang++ -g -O1 -flto -fvisibility=hidden -fuse-ld=gold -fsanitize=cfi -fno-sanitize-trap=cfi nodes.cpp -o nodes-cfi
./nodes-cfi 2>&1 | grep -E '^image|^text|runtime error|note:'
echo "exit code: ${PIPESTATUS[0]}"
echo "== plain build"
g++ -g -O0 nodes.cpp -o nodes0 && ./nodes0
== g++ -fsanitize=undefined (includes the vptr check)
image 640x480
text "hello"
nodes.cpp:10:21: runtime error: downcast of address 0x7ffd3838d870 which does not point to an object of type 'Image'
0x7ffd3838d870: note: object is of type 'Text'
nodes.cpp:11:53: runtime error: member access within address 0x7ffd3838d870 which does not point to an object of type 'Image'
0x7ffd3838d870: note: object is of type 'Text'
nodes.cpp:11:42: runtime error: member access within address 0x7ffd3838d870 which does not point to an object of type 'Image'
0x7ffd3838d870: note: object is of type 'Text'
image 1819043176x111
exit code: 0
== clang++ -fsanitize=cfi (needs LTO and hidden visibility)
image 640x480
text "hello"
nodes.cpp:10:21: runtime error: control flow integrity check for type 'Image' failed during base-to-derived cast (vtable address 0x5a05c4390cd0)
0x5a05c4390cd0: note: vtable is of type 'Text'
exit code: 1
== plain build
image 640x480
text "hello"
image 1819043176x111

What happened

The plain build printed image 1819043176x111 for a text node. The Image fields width and height sit where Text keeps its characters (offsets 12 to 19, right after the vptr and kind), so width is the four bytes "hell" read as a little-endian int (0x6c6c6568 = 1,819,043,176) and height is "o" plus three NULs (0x6f = 111). Here the result is a silly number. If Image had a pointer or a length where Text has user-controlled characters, the program would now use attacker-chosen bytes as a pointer or a size, and a virtual call through a confused object uses the wrong vtable. That is how type confusion becomes code execution.

The two checks:

  • UBSan's vptr check (on in -fsanitize=undefined for C++ code compiled with RTTI) reads the object's vptr at the cast and at each member access: downcast of address … which does not point to an object of type 'Image', note: object is of type 'Text', at nodes.cpp:10:21 (the static_cast), then once per bad member access on line 11. It reports and continues by default, so the wrong line still prints.
  • Clang CFI (-fsanitize=cfi, which includes cfi-derived-cast) checks that the vtable of the object belongs to Image or a class derived from it: control flow integrity check for type 'Image' failed during base-to-derived cast, vtable is of type 'Text', and the program stops with exit code 1 before the confused object is used. Built normally (without -fno-sanitize-trap), CFI stops with a trap instruction and no message, cheap enough for production; Chrome's official Linux x86-64 builds ship with Clang CFI.

Root cause

The program had two sources of truth about the node's type (the object's real class, and a tag from the file) and trusted the one that an attacker controls. static_cast assumes the programmer already proved the type; nothing here proved it.

The fix

Let the object's real type decide, using a checked cast or a closed set of types:

cpp · try it yourself
#include <cstdio>
#include <variant>

struct Text  { char text[8] = "hello"; };
struct Image { int width = 640, height = 480; };
using Node = std::variant<Text, Image>;            // a closed, checked set of node types

static void render(const Node &n, int kind_from_file) {
    if (kind_from_file == 2) {
        if (const Image *im = std::get_if<Image>(&n))          // checked: nullptr if not an Image
            std::printf("image %dx%d\n", im->width, im->height);
        else
            std::printf("rejected: file says image, node is %s\n", n.index() == 0 ? "text" : "?");
        return;
    }
    std::visit([](const auto &v) {                             // or: dispatch on the real type only
        if constexpr (requires { v.text; }) std::printf("text \"%s\"\n", v.text);
        else std::printf("image %dx%d\n", v.width, v.height);
    }, n);
}

int main() {
    Node img = Image{}, txt = Text{};
    render(img, 2);
    render(txt, 1);
    render(txt, 2);
    return 0;
}
image 640x480
text "hello"
rejected: file says image, node is text

std::variant stores which alternative it holds and std::get_if checks it, so a wrong tag from the file can only cause a rejection. In class hierarchies, dynamic_cast<Image *>(n) plus a nullptr check does the same, at the cost of an RTTI lookup. Better still, make the file's tag only an input to construction: build an Image when the file says image, and never re-interpret an existing object.

How type confusion is detected

  • UBSan vptr in tests and fuzzing (C++ with RTTI).
  • Clang CFI (cfi-derived-cast, cfi-unrelated-cast, cfi-vcall) in tests and, in trapping mode, in production. Windows' Control Flow Guard protects indirect calls but doesn't check casts.
  • Review: every static_cast and C-style cast down a hierarchy, every reinterpret_cast, every union read through a different member than was written, and every place where a type tag is set or trusted. Clang-Tidy's cppcoreguidelines-pro-type-static-cast-downcast flags downcasts.
  • Fuzzing structured formats with grammars that mix node types finds tag mismatches.

The CWE

CWE-843: Access of Resource Using Incompatible Type ('Type Confusion'). In C, the same bug appears with unions and with casting void * to the wrong struct.

Pitfalls

  • C-style casts (Image *)n silently become static_cast or reinterpret_cast; ban them in C++ code (-Wold-style-cast).
  • dynamic_cast with references throws std::bad_cast instead of returning null; catch it or use pointers.
  • Objects that change type: a node that is "converted" in place (by placement new of another type) invalidates every pointer that assumed the old type.

Practice

1. Compute the width the confused read produces if the text is "abcd" instead of "hello".

The bytes 61 62 63 64 read little-endian: 0x64636261 = 1,684,234,849. height would be 0 (the NUL and padding).

2. Why does UBSan's vptr check need RTTI?

It compares the dynamic type, found through the object's vptr and the RTTI records, with the type of the cast. With -fno-rtti there is nothing to compare against, and the check is disabled.

3. Why is a type tag from a file dangerous even with dynamic_cast?

dynamic_cast prevents the memory-safety bug, but code that branches on the file's tag may still take a path meant for another type (logic confusion). Dispatch on the real type, and treat the tag only as a construction hint.

Test yourself

What does static_cast<Image*>(node) check at run time?

  1. That node is an Image
  2. Nothing: it assumes the programmer proved the type
  3. That node is not null
  4. The vtable

Where did the confused width 1819043176 come from?

  1. Random memory
  2. The Text node's characters "hell" read as a little-endian int
  3. The vtable pointer
  4. The Image constructor

Which check stopped the program before the confused object was used?

  1. UBSan vptr (it reported and continued)
  2. Clang CFI's base-to-derived cast check
  3. ASan
  4. The stack canary

Which C++ facility makes the wrong tag impossible to act on?

  1. reinterpret_cast
  2. std::variant with std::get_if (or dynamic_cast with a null check)
  3. A C-style cast
  4. union