Skip to content
Memory corruption Write-up Advanced

Colorful Vulnerabilities

The OpenRazer kernel drivers copied a user-controlled length of RGB data into a fixed 80-byte buffer inside a report structure without validating the length. An unprivileged local user could write to a sysfs attribute and overflow the buffer, crashing the driver (denial of service) and potentially escalating privileges if the kernel was built without FORTIFY_SOURCE.

Tal Lossos Follow

Published on cyberark.com

Our love for gaming alongside finding bugs led us back to the good ol’ question: Is it true that the more RGB colors you have (except for your gaming chair, of course), the more skill and power you’ll have over your opponents? Or could it put you at a disadvantage?

Tal Lossos (@TalLossos), on cyberark.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

Context

OpenRazer is an entirely open source driver and user-space daemon that allows you to manage your Razer peripherals on GNU/Linux. The project ships several kernel modules, among them razerkbd, razermouse, razeraccessory and razerkraken. Because kernel modules are always privileged, every bug in them is essentially a bug in the kernel, and they are far less examined and tested than the core kernel.

The drivers are implemented as USB-HID devices. Each driver exposes its functionality through multiple attribute files in sysfs, created with device_create_file and declared with the DEVICE_ATTR macro, whose fields are:

  • name: the attribute file's name
  • mode: the permissions for the attribute file
  • show: the function for reading from the attribute file
  • store: the function for writing to the attribute file

In razerkbd there are three kinds of attribute files: read-only (0440), write-only (0220) and read-write (0660). The write-only ones are the interesting ones, because the buffer written to the attribute file is normally used directly in the driver's store function.

One of those write-only files is matrix_custom_frame. According to the OpenRazer wiki, it sets the colours of keyboard rows by passing a row index, a column start, a column stop and RGB values for the corresponding keys. For example, this sets the left Ctrl, WinKey and alt keys to blue:

Python
BLUE = '\x00\x00\xff'

with open('matrix_custom_frame', 'wb') as f:
    f.write(b'\x05\x00\x03' + BLUE * 4)

with open('matrix_effect_custom', 'wb') as f:
    f.write('\x01')

Setup

All the work was done on an Ubuntu 20.04 kernel 5.13. OpenRazer can be installed either by following the Download section of the OpenRazer page or by compiling and installing the drivers directly from the GitHub page. After installing, the specific kernel module has to be loaded (check with dmesg).

To confirm the VM recognises the Razer USB device, run lsusb:

From the original on cyberark.com

If the Razer USB device is not visible, make sure the device is connected to the VM (USB and Bluetooth). If it still does not appear, the following can be added to the VM's .vmx file, followed by a restart:

Text
usb.generic.allowHID = "TRUE"
usb.generic.allowLastHID = "TRUE
From the original on cyberark.com

Once the USB device is connected, a new hid device appears under /sys/bus/hid/devices for the connected device, containing all the driver's device files.

For reversing, the kernel module should be compiled with debug symbols. The Makefile can be adjusted by adding EXTRA_CFLAGS="-g -DDEBUG":

Text
# Driver compilation
driver:
        @echo -e "\n::\033[32m Compiling OpenRazer kernel modules\033[0m"
        @echo "========================================"
        $(MAKE) -C $(KERNELDIR) M=$(DRIVERDIR) modules EXTRA_CFLAGS="-g -DDEBUG"

Finding it

The research started from the plain source code, since the drivers are open source. The driver registration shows the HID nature of the modules:

C
static struct hid_driver razer_kbd_driver = {
    .name = "razerkbd",
    .id_table = razer_devices,
    .input_mapping = razer_kbd_input_mapping,
    .probe = razer_kbd_probe,
    .remove = razer_kbd_disconnect,
    .event = razer_event,
    .raw_event = razer_raw_event,
};

module_hid_driver(razer_kbd_driver);

The attribute declarations in razerkbd look like this:

C
static DEVICE_ATTR(game_led_state,          0660, razer_attr_read_mode_game,                  razer_attr_write_mode_game);
static DEVICE_ATTR(macro_led_state,         0660, razer_attr_read_mode_macro,                 razer_attr_write_mode_macro);
...
static DEVICE_ATTR(version,                 0440, razer_attr_read_version,                    NULL);
static DEVICE_ATTR(kbd_layout,              0440, razer_attr_read_kbd_layout,                 NULL);
static DEVICE_ATTR(firmware_version,        0440, razer_attr_read_get_firmware_version,       NULL);
...
static DEVICE_ATTR(device_type,             0440, razer_attr_read_device_type,                NULL);
static DEVICE_ATTR(device_mode,             0660, razer_attr_read_device_mode,                razer_attr_write_device_mode);
static DEVICE_ATTR(device_serial,           0440, razer_attr_read_get_serial,                 NULL);
...
static DEVICE_ATTR(matrix_effect_none,      0220, NULL,                                       razer_attr_write_mode_none);
...
static DEVICE_ATTR(matrix_custom_frame,     0220, NULL,                                       razer_attr_write_matrix_custom_frame);
...

The general flow of writing to matrix_custom_frame is the following:

C
static DEVICE_ATTR(matrix_custom_frame,     0220, NULL, razer_attr_write_matrix_custom_frame);  // 1

...

static ssize_t razer_attr_write_matrix_custom_frame(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
    struct usb_interface *intf = to_usb_interface(dev->parent);
    struct usb_device *usb_dev = interface_to_usbdev(intf);
    struct razer_report report = {0};
    size_t offset = 0;
    unsigned char row_id;
    unsigned char start_col;
    unsigned char stop_col;
    unsigned char row_length;

    while(offset < count) {
        ... row_id = buf[offset++]; // 2
        start_col = buf[offset++];
        stop_col = buf[offset++];
        row_length = ((stop_col+1) - start_col) * 3;
        ...
        switch(usb_dev->descriptor.idProduct) {
        case USB_DEVICE_ID_RAZER_ORNATA:
        ...
        case USB_DEVICE_ID_RAZER_CYNOSA_CHROMA_PRO:
            report = razer_chroma_extended_matrix_set_custom_frame(row_id, start_col, stop_col, (unsigned char*)&buf[offset]);  // 3
            break;
        ...
        razer_send_payload(usb_dev, &report);  // 8

        // *3 as its 3 bytes per col (RGB)
        offset += row_length;
    }

    return count;
}
  1. razer_attr_write_matrix_custom_frame receives the buffer written to matrix_custom_frame as the buf argument.
  2. It assigns row_id, start_col and stop_col from the first, second and third bytes of buf, which are fully controlled by the user.
  3. It passes row_id, start_col, stop_col and the buf buffer starting at the RGB data offset to razer_chroma_extended_matrix_set_custom_frame, which calls [redacted]:
C
struct razer_report razer_chroma_extended_matrix_set_custom_frame(unsigned char row_index, unsigned char start_col, unsigned char stop_col, unsigned char *rgb_data)
{
    return [redacted](row_index, start_col, stop_col, rgb_data, 0x47);
}
C
struct razer_report {
    unsigned char status;
    union transaction_id_union transaction_id;
    unsigned short remaining_packets;
    unsigned char protocol_type;
    unsigned char data_size;
    unsigned char command_class;
    union command_id_union command_id;
    unsigned char arguments[80];
    unsigned char crc;
    unsigned char reserved;
};

struct razer_report [redacted](unsigned char row_index, unsigned char start_col, unsigned char stop_col, unsigned char *rgb_data, size_t packetLength)
{
    const size_t row_length = (size_t) (((stop_col + 1) - start_col) * 3);  // 4
    const size_t data_length = (packetLength != 0) ? packetLength : row_length + 5;
    struct razer_report report = get_razer_report(0x0F, 0x03, data_length);  // 5

    report.transaction_id.id = 0x3F;

    report.arguments[2] = row_index;  // 6
    report.arguments[3] = start_col;
    report.arguments[4] = stop_col;
    memcpy(&report.arguments[5], rgb_data, row_length);  // 7

    return report;
}
  1. row_length for the RGB values is calculated from start_col and stop_col, at three bytes per RGB value.
  2. A new razer_report is created via get_razer_report; one of its members is a char array named arguments with a length of 80.
  3. row_id (as row_index), start_col and stop_col are placed into the arguments buffer.
  4. row_length bytes are copied from buf (rgb_data) into the arguments buffer.
  5. The new razer_report is sent to the USB device.

The problem: row_length is fully controlled and is used as the copy size in the memcpy, with no validation whatsoever. Supplying a size bigger than 80 overflows the arguments buffer, a classic buffer overflow. Both razermouse and razeraccessory implement matrix_custom_frame the same way and suffer from the same bug.

Reversing the compiled module

To understand which code actually runs, the binary has to be reversed, because the compiler can add or change things relative to the source. The module was compiled with debug symbols for easier reversing.

From the original on cyberark.com

After reversing the relevant parts, the decompiled code looked quite similar to the source, but an odd test had been added: it compares row_length with 0x4D and calls fortify_panic if row_length is bigger than 0x4D.

From the original on cyberark.com

What is this test, and what even is 0x4D?

From the original on cyberark.com

0x4D, that is 77, is the space left in the struct razer_report starting from offset 5 in the arguments buffer, which is the destination of the memcpy. Potentially, both the crc and reserved fields could be overwritten. However, the copy size row_length cannot be 76 or 77 bytes long, because neither is a multiple of 3. Therefore the crc and reserved fields of the structure cannot be overwritten.

From the original on cyberark.com

When the drivers are compiled without FORTIFY_SOURCE enabled on the machine, the odd test is not there at all.

Root cause

The driver trusts user input. start_col and stop_col come straight from the buffer written to the sysfs attribute, and row_length is derived from them as ((stop_col+1) - start_col) * 3 without any bounds check before being used as the length of a memcpy into the fixed 80-byte arguments array of struct razer_report. The only thing standing between the user and the overflow is the kernel's FORTIFY_SOURCE mitigation, which is a compile-time and run-time check, not a fix for the logic error.

Fortify Source

The added call to fortify_panic is part of Fortify Source, a feature originally from glibc that provides compile-time and run-time buffer overflow checks for potentially dangerous functions such as memcpy and strcpy. Unlike the glibc version, the Linux kernel implementation also covers buffer reads in addition to writes.

At its core, FORTIFY_SOURCE uses the compiler's __builtin_object_size() to determine the available size at a target address based on the compile-time known structure layout. Two of its modes matter here:

  • Mode 0: checks the outer bounds of the structure.
  • Mode 1: checks the inner bounds of members in the structure.

For example:

C
struct object {
		u16 scalar1;	/* 2 bytes */
		char array[6];	/* 6 bytes */
		u64 scalar2;	/* 8 bytes */
		u32 scalar3;	/* 4 bytes */
		u32 scalar4;	/* 4 bytes */
} instance;

__builtin_object_size(instance.array, 0) == 22, since the remaining size of the enclosing structure starting from the field array is 22 bytes (6 + 8 + 4 + 4). __builtin_object_size(instance.array, 1) == 6, since the remaining size of the specific field array is 6 bytes.

The initial implementation of FORTIFY_SOURCE in kernel v4.13 used __builtin_object_size() with mode 0, because there were many cases of both strcpy and memcpy being used to write (or read) across multiple fields in a structure. That prevented overflows from reaching beyond the end of the structure, but since structures are a continuous area in memory, it did not protect against overwriting neighbouring structure fields.

In kernel v5.11, mode 1 was turned on for the strcpy family of functions, and in kernel v5.18, mode 1 was turned on for the memcpy family of functions. Compiling a kernel module on a machine with FORTIFY_SOURCE enabled (CONFIG_FORTIFY_SOURCE) therefore has this mitigation enabled by default:

C
__FORTIFY_INLINE void *memcpy(void *p, const void *q, __kernel_size_t size)
{
	size_t p_size = __builtin_object_size(p, 0);
	size_t q_size = __builtin_object_size(q, 0);

	if (__builtin_constant_p(size)) {  // The size is known at compile-time
		if (p_size < size)
			__write_overflow();
		if (q_size < size)
			__read_overflow2();
	}
	if (p_size < size || q_size < size)
		fortify_panic(__func__);
	return __underlying_memcpy(p, q, size);
}

Fortify Source checks the code both at compile time and at run time:

From the original on cyberark.com

For instance, in the memcpy check, if the size is known at compile time there is an error right away, which causes compilation failure.

From the original on cyberark.com

Otherwise, if the size is determined at run time, a call to fortify_panic is triggered before the out-of-bounds copy operation:

C
void fortify_panic(const char *name)
{
	pr_emerg("detected buffer overflow in %s\n", name);
	BUG();
}

fortify_panic calls the BUG macro, which calls unreachable and crashes the driver. That is far better than letting an attacker arbitrarily write code in the kernel.

Exploitation

To trigger the vulnerability, a specially constructed buffer must be sent that makes row_length bigger than 80. Setting start_col to 0x00 and stop_col to a value larger than 0x18 makes row_length exceed the size of the arguments buffer and overflow it.

Step 1: write the crafted buffer to the attribute file

Python
file_path = '/sys/bus/hid/devices/0003:1532:021E.0004/matrix_custom_frame'
payload = b'\x00\x00\x19'
payload += b'\x41' * 80

def crash():
    with open(file_path, 'wb') as f:
        f.write(payload)

if __name__ == '__main__':
   crash()

The first three bytes are row_id (0x00), start_col (0x00) and stop_col (0x19), which makes row_length exceed the space available in the arguments array from offset 5. The remaining 80 bytes of 0x41 are the RGB data that gets copied. Running this crashes the driver, causing a denial of service.

Step 2: consider the impact without FORTIFY_SOURCE

The impact may be more severe if the driver was not compiled with FORTIFY_SOURCE enabled. In that case the attacker can chain this vulnerability with an information leak vulnerability, bypassing KASLR and stacking canary mitigations (if present). That leads to kernel control-flow hijack, which results in code execution in kernel space. Even without leveraging an information leak vulnerability, exploiting the bug in the absence of FORTIFY_SOURCE would cause a system crash.

Impact

The buffer overflow causes a denial of service and possibly elevation of privileges. Three CVEs were assigned:

Driver CVE
razerkbd CVE-2022-29021
razeraccessory CVE-2022-29022
razermouse CVE-2022-29023

The severity depends on the build: with FORTIFY_SOURCE enabled, the run-time check turns the overflow into a crash of the driver; without it, kernel code execution becomes possible when combined with an information leak, and a system crash otherwise.

Fix

As part of the disclosure, a patch was submitted for the described vulnerabilities, adding checks before the memcpy to prevent any overflow. It was merged soon after and was part of the new release.

Disclosure timeline:

  • April 3, 2022: bug found
  • April 4, 2022: reported to the OSS maintainer
  • April 8, 2022: PR for fixing the vulnerable code opened
  • April 9, 2022: merged and a new release of OpenRazer published (3.3.0)
  • May 20, 2022: CVEs granted

Variants to test

  • Other OpenRazer drivers exposing matrix_custom_frame: razermouse and razeraccessory were confirmed to share the same implementation. A positive result is the same crash when writing a buffer whose stop_col exceeds 0x18 with start_col at 0x00.
  • Other write-only attribute files in the same drivers: any store function that derives a length from user-controlled bytes and passes it to memcpy into a fixed-size structure is a candidate. A positive result is a fortify_panic message in dmesg or a driver crash.
  • Builds without CONFIG_FORTIFY_SOURCE: the same payload that only crashes the driver on a fortified build may corrupt memory beyond the arguments array. A positive result is memory corruption rather than a clean panic.
  • Other third-party Linux kernel modules that parse user-supplied buffers from sysfs or HID interfaces: look for length fields computed from user input and used as copy sizes. A positive result is an out-of-bounds copy reachable from an unprivileged user.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 23 min read.

What happened, in plain words

A security researcher looked at OpenRazer, a free piece of software that lets people use Razer gaming keyboards, mice and other accessories on Linux. He found a bug in the part of OpenRazer that talks to the operating system's core, the kernel. The bug lets an ordinary user, with no special rights, send a specially crafted message that makes the software write more data into a small fixed-size box than the box can hold. That is called a buffer overflow. In the worst case it can crash the whole computer (a denial of service) and, on builds without FORTIFY_SOURCE and combined with an information leak, it could let an attacker run their own code with the highest privileges on the machine (elevation of privileges). Three official vulnerability identifiers were assigned: CVE-2022-29021, CVE-2022-29022 and CVE-2022-29023.

While working out how to trigger the bug, the researcher ran into a newer Linux kernel safety feature called Fortify Source. It adds automatic checks around copying functions and turns many overflows into a controlled crash instead of silent memory corruption. Understanding that feature is a big part of the story, because it changes what an attacker can achieve.

From the original on cyberark.com

Background: what OpenRazer is and why kernel modules matter

OpenRazer describes itself as "An entirely open source driver and user-space daemon that allows you to manage your Razer peripherals on GNU/Linux". In everyday words: it is the software that makes Razer keyboards and mice work properly on Linux, including their colourful lighting effects.

A few terms first, because they come up constantly:

  • Driver: software that lets the operating system talk to a piece of hardware. Without a driver, the computer does not know how to send commands to the device.
  • Kernel: the core of the operating system. It sits between programs and the hardware and enforces who is allowed to do what. Code running in the kernel has total power over the machine.
  • Kernel module: a piece of code that can be loaded into the kernel while the system is running, usually to support a device. It runs with the same high privileges as the kernel itself.
  • Open source: the human-readable source code is published, so anyone can read it, study it and suggest changes.

OpenRazer ships several kernel modules: razerkbd (keyboards), razermouse (mice), razeraccessory and razerkraken. The researcher's reasoning for looking here is simple and worth spelling out: a kernel module is always privileged, so any bug in it is effectively a bug in the kernel. And because modules are not part of the core kernel, they get far less scrutiny and testing. That combination, high power plus low attention, is exactly where bugs tend to survive.

The drivers are built as USB-HID devices. HID stands for Human Interface Device: the standard way keyboards, mice and similar gadgets describe themselves to a computer. Think of it as a shared language that lets the operating system understand "this is a keyboard with these keys" without needing a custom driver for every model.

Each driver exposes its features through attribute files in a special part of the Linux filesystem called sysfs. Sysfs is a set of files that represent kernel objects. Reading or writing one of these files is how a normal program asks the driver to do something. It is a bit like a control panel made of files: instead of clicking a button, you write bytes into a file.

These attribute files are created by calling device_create_file and declared with the DEVICE_ATTR macro. A macro is a shorthand in the C programming language that expands into a larger piece of code. The DEVICE_ATTR macro takes four fields:

  • name: the attribute file's name
  • mode: the permissions for the attribute file
  • show: the function for reading from the attribute file
  • store: the function for writing to the attribute file

In razerkbd there are three kinds of attribute files: read-only (0440), write-only (0220) and read-write (0660). Those numbers are Unix permission codes: they say who may read and who may write. The researcher focused on the write-only ones, and the reason is practical. When you write into an attribute file, the bytes you supply are normally handed straight to the driver's store function, which then processes them. User input flowing directly into code is where bugs live, so write-only files are the highest-value place to start.

One of those write-only files is matrix_custom_frame. According to the OpenRazer wiki, it sets the colours of keyboard rows by passing a row index, a column start, a column stop and RGB values for the corresponding keys. RGB simply means red, green and blue: three numbers per key that together describe a colour, the same idea as mixing paint.

For example, this sets the left Ctrl, WinKey and alt keys to blue:

Python
BLUE = '\x00\x00\xff'

with open('matrix_custom_frame', 'wb') as f:
    f.write(b'\x05\x00\x03' + BLUE * 4)

with open('matrix_effect_custom', 'wb') as f:
    f.write('\x01')

Line by line:

  1. BLUE = '\x00\x00\xff' defines the colour blue as three bytes: no red, no green, full blue. The \x notation means "the byte with this hexadecimal value".
  2. with open('matrix_custom_frame', 'wb') as f: opens the attribute file for writing in binary mode ('wb'). Opening a file in sysfs is how you talk to the driver.
  3. f.write(b'\x05\x00\x03' + BLUE * 4) writes a message made of two parts. The first three bytes are the instructions: row 5, start column 0, stop column 3. Then BLUE * 4 repeats the blue colour four times, once per key in that range.
  4. The second with open(...) block writes '\x01' into matrix_effect_custom, which tells the keyboard to actually apply the custom colour pattern.

So the whole interaction is: write a small header describing which keys, then write the colours, then switch the effect on.

Setting up a test environment

All the work was done on an Ubuntu 20.04 system running kernel 5.13. Ubuntu is a popular Linux distribution; a kernel version is just the version number of the operating system core.

OpenRazer can be installed either by following the Download section of the OpenRazer page or by compiling and installing the drivers directly from the GitHub page. GitHub is a website where open-source code is hosted and shared. After installing, the specific kernel module has to be loaded, which can be checked with dmesg. dmesg is a command that prints the kernel's log messages, a running diary of what the system has been doing.

To confirm the virtual machine recognises the Razer USB device, run lsusb. A virtual machine (VM) is a computer simulated inside another computer, useful for testing without risking your real machine. lsusb lists the USB devices the system can see.

From the original on cyberark.com

If the Razer USB device is not visible, make sure the device is connected to the VM (USB and Bluetooth). If it still does not appear, the following can be added to the VM's .vmx file, followed by a restart:

Text
usb.generic.allowHID = "TRUE"
usb.generic.allowLastHID = "TRUE

These two lines are configuration settings for the virtual machine software. They tell it to pass HID devices (keyboards, mice) through to the guest system instead of keeping them for the host. Without that, the VM may simply never see the Razer hardware, and none of the testing would work.

From the original on cyberark.com

Once the USB device is connected, a new hid device appears under /sys/bus/hid/devices for the connected device, containing all the driver's device files. That directory is the control panel mentioned earlier: the files inside it are the ones you write to in order to send commands.

For reversing, the kernel module should be compiled with debug symbols. Reversing means taking a compiled program and working backwards to understand what it does, because the compiled form is not human-readable. Debug symbols are extra labels left in the compiled file that make this much easier. The Makefile can be adjusted by adding EXTRA_CFLAGS="-g -DDEBUG". A Makefile is a recipe file that tells the computer how to build software; EXTRA_CFLAGS passes extra options to the compiler, and -g is the option that includes debug information.

Text
# Driver compilation
driver:
        @echo -e "\n::\033[32m Compiling OpenRazer kernel modules\033[0m"
        @echo "========================================"
        $(MAKE) -C $(KERNELDIR) M=$(DRIVERDIR) modules EXTRA_CFLAGS="-g -DDEBUG"

Line by line:

  1. # Driver compilation is a comment, ignored by the build tool.
  2. driver: starts a rule named "driver".
  3. The two @echo lines print coloured status messages to the screen so the person building knows what is happening.
  4. $(MAKE) -C $(KERNELDIR) M=$(DRIVERDIR) modules EXTRA_CFLAGS="-g -DDEBUG" is the actual build command. It runs the build tool inside the kernel source directory (-C $(KERNELDIR)), points it at the driver directory (M=$(DRIVERDIR)), asks for the modules target, and adds the debug flag.
From the original on cyberark.com

Finding the bug

The research started from the plain source code, since the drivers are open source. That is a deliberate choice: reading code is often faster and more reliable than guessing from behaviour. The driver registration shows the HID nature of the modules:

C
static struct hid_driver razer_kbd_driver = {
    .name = "razerkbd",
    .id_table = razer_devices,
    .input_mapping = razer_kbd_input_mapping,
    .probe = razer_kbd_probe,
    .remove = razer_kbd_disconnect,
    .event = razer_event,
    .raw_event = razer_raw_event,
};

module_hid_driver(razer_kbd_driver);

Line by line:

  1. static struct hid_driver razer_kbd_driver = { declares a structure, which in C is a bundle of related values grouped under one name. This one describes a HID driver.
  2. .name = "razerkbd" gives the driver its name.
  3. .id_table = razer_devices points to the list of device identifiers this driver handles, so the kernel knows which hardware to hand to it.
  4. .input_mapping, .probe, .remove, .event and .raw_event are function pointers: they tell the kernel which functions to call when the device is mapped, plugged in, unplugged, or sends an event. Think of them as the driver's contact list.
  5. module_hid_driver(razer_kbd_driver); is a macro that registers the whole thing with the kernel.

The attribute declarations in razerkbd look like this:

C
static DEVICE_ATTR(game_led_state,          0660, razer_attr_read_mode_game,                  razer_attr_write_mode_game);
static DEVICE_ATTR(macro_led_state,         0660, razer_attr_read_mode_macro,                 razer_attr_write_mode_macro);
...
static DEVICE_ATTR(version,                 0440, razer_attr_read_version,                    NULL);
static DEVICE_ATTR(kbd_layout,              0440, razer_attr_read_kbd_layout,                 NULL);
static DEVICE_ATTR(firmware_version,        0440, razer_attr_read_get_firmware_version,       NULL);
...
static DEVICE_ATTR(device_type,             0440, razer_attr_read_device_type,                NULL);
static DEVICE_ATTR(device_mode,             0660, razer_attr_read_device_mode,                razer_attr_write_device_mode);
static DEVICE_ATTR(device_serial,           0440, razer_attr_read_get_serial,                 NULL);
...
static DEVICE_ATTR(matrix_effect_none,      0220, NULL,                                       razer_attr_write_mode_none);
...
static DEVICE_ATTR(matrix_custom_frame,     0220, NULL,                                       razer_attr_write_matrix_custom_frame);
...

Line by line, each line declares one attribute file:

  1. The first argument is the file's name, for example matrix_custom_frame.
  2. The second argument is the permission number: 0660 means read and write, 0440 means read only, 0220 means write only.
  3. The third argument is the function called when someone reads the file, or NULL if reading is not allowed.
  4. The fourth argument is the function called when someone writes to the file, or NULL if writing is not allowed.

The line that matters most is the last one: matrix_custom_frame is write-only, and writing to it calls razer_attr_write_matrix_custom_frame.

The general flow of writing to matrix_custom_frame is the following:

C
static DEVICE_ATTR(matrix_custom_frame,     0220, NULL, razer_attr_write_matrix_custom_frame);  // 1

...

static ssize_t razer_attr_write_matrix_custom_frame(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
    struct usb_interface *intf = to_usb_interface(dev->parent);
    struct usb_device *usb_dev = interface_to_usbdev(intf);
    struct razer_report report = {0};
    size_t offset = 0;
    unsigned char row_id;
    unsigned char start_col;
    unsigned char stop_col;
    unsigned char row_length;

    while(offset < count) {
        ... row_id = buf[offset++]; // 2
        start_col = buf[offset++];
        stop_col = buf[offset++];
        row_length = ((stop_col+1) - start_col) * 3;
        ...
        switch(usb_dev->descriptor.idProduct) {
        case USB_DEVICE_ID_RAZER_ORNATA:
        ...
        case USB_DEVICE_ID_RAZER_CYNOSA_CHROMA_PRO:
            report = razer_chroma_extended_matrix_set_custom_frame(row_id, start_col, stop_col, (unsigned char*)&buf[offset]);  // 3
            break;
        ...
        razer_send_payload(usb_dev, &report);  // 8

        // *3 as its 3 bytes per col (RGB)
        offset += row_length;
    }

    return count;
}

Line by line:

  1. The declaration ties the file to the function, as explained above.
  2. The function signature receives the written bytes as buf and their number as count. Inside, it sets up a report structure, an offset counter, and four small variables: row_id, start_col, stop_col and row_length.
  3. while(offset < count) loops over the written data, handling one row at a time.
  4. row_id = buf[offset++] reads the first byte as the row number and moves the offset forward. The next two lines read the start and stop column the same way. All three come straight from the user, with no checking.
  5. row_length = ((stop_col+1) - start_col) * 3; calculates how many bytes of colour data this row needs. The * 3 is because each key needs three bytes, one each for red, green and blue.
  6. The switch picks the right handling code based on which Razer product is connected.
  7. report = razer_chroma_extended_matrix_set_custom_frame(...) passes the three numbers and a pointer to the colour data into another function, which builds the message.
  8. razer_send_payload(usb_dev, &report); sends the finished message to the device.
  9. offset += row_length; skips past the colour data just processed, so the loop can handle the next row.

That function calls razer_chroma_extended_matrix_set_custom_frame, which calls [redacted]:

C
struct razer_report razer_chroma_extended_matrix_set_custom_frame(unsigned char row_index, unsigned char start_col, unsigned char stop_col, unsigned char *rgb_data)
{
    return [redacted](row_index, start_col, stop_col, rgb_data, 0x47);
}

This is a thin wrapper: it simply forwards the same values to the second function and adds a fixed number, 0x47, as an extra argument. A wrapper like this is common when one function wants to set a default for another.

C
struct razer_report {
    unsigned char status;
    union transaction_id_union transaction_id;
    unsigned short remaining_packets;
    unsigned char protocol_type;
    unsigned char data_size;
    unsigned char command_class;
    union command_id_union command_id;
    unsigned char arguments[80];
    unsigned char crc;
    unsigned char reserved;
};

struct razer_report [redacted](unsigned char row_index, unsigned char start_col, unsigned char stop_col, unsigned char *rgb_data, size_t packetLength)
{
    const size_t row_length = (size_t) (((stop_col + 1) - start_col) * 3);  // 4
    const size_t data_length = (packetLength != 0) ? packetLength : row_length + 5;
    struct razer_report report = get_razer_report(0x0F, 0x03, data_length);  // 5

    report.transaction_id.id = 0x3F;

    report.arguments[2] = row_index;  // 6
    report.arguments[3] = start_col;
    report.arguments[4] = stop_col;
    memcpy(&report.arguments[5], rgb_data, row_length);  // 7

    return report;
}

Line by line:

  1. The struct razer_report definition describes the message format sent to the device. It has several small fields, then arguments[80], a fixed box of exactly 80 bytes, then two more single-byte fields, crc and reserved. A union is a C construct where several types share the same memory; it does not change the overall idea here.
  2. row_length is recalculated from the start and stop columns, again at three bytes per key.
  3. data_length is set to the packet length if one was given, otherwise to row_length + 5.
  4. get_razer_report(...) creates a fresh report with some default values.
  5. report.transaction_id.id = 0x3F; sets one field of the report.
  6. The next three lines store the row number, start column and stop column into positions 2, 3 and 4 of the arguments box.
  7. memcpy(&report.arguments[5], rgb_data, row_length); is the critical line. memcpy means "memory copy": it takes row_length bytes from the user's colour data and copies them into the arguments box, starting at position 5.
  8. Finally the filled-in report is returned, ready to be sent to the device.

The problem is now visible. row_length is fully controlled by the user, because it is calculated from the start and stop columns the user supplied. It is then used as the copy size in the memcpy, with no validation whatsoever. Supplying a size bigger than 80 overflows the arguments box: the copy keeps writing past the end of the box and into whatever comes next in memory. That is a classic buffer overflow. A useful comparison: it is like pouring a litre of water into a 200 ml glass. The glass does not stop the water; the extra simply spills over everything nearby.

Both razermouse and razeraccessory implement matrix_custom_frame the same way and suffer from the same bug. That is why three CVEs were assigned rather than one.

Reversing the compiled module

To understand which code actually runs, the binary has to be reversed, because the compiler can add or change things relative to the source. The compiler is the program that turns human-readable source code into the machine code the computer executes, and it is allowed to optimise, rearrange or insert checks. The module was compiled with debug symbols for easier reversing.

From the original on cyberark.com

After reversing the relevant parts, the decompiled code looked quite similar to the source, but an odd test had been added: it compares row_length with 0x4D and calls fortify_panic if row_length is bigger than 0x4D.

From the original on cyberark.com

What is this test, and what even is 0x4D?

From the original on cyberark.com

0x4D, that is 77, is the space left in the struct razer_report starting from offset 5 in the arguments buffer, which is the destination of the memcpy. In plain terms: 77 is the space left in the structure starting from position 5 of the arguments box, where the copy begins. Potentially, both the crc and reserved fields could be overwritten. However, the copy size row_length cannot be 76 or 77 bytes long, because neither is a multiple of 3. Since every key contributes exactly three bytes, the length always jumps in steps of three. Therefore the crc and reserved fields of the structure cannot be overwritten.

From the original on cyberark.com

When the drivers are compiled without FORTIFY_SOURCE enabled on the machine, the odd test is not there at all. That is the key observation: the check is not part of the driver's own logic, it is added by the build environment.

Root cause

The driver trusts user input. start_col and stop_col come straight from the buffer written to the sysfs attribute, and row_length is derived from them as ((stop_col+1) - start_col) * 3 without any bounds check before being used as the length of a memcpy into the fixed 80-byte arguments array of struct razer_report. The only thing standing between the user and the overflow is the kernel's FORTIFY_SOURCE mitigation, which is a compile-time and run-time check, not a fix for the logic error. A mitigation is a safety net that makes a bug harder to exploit; it does not remove the bug.

Fortify Source

The added call to fortify_panic is part of Fortify Source, a feature originally from glibc that provides compile-time and run-time buffer overflow checks for potentially dangerous functions such as memcpy and strcpy. glibc is the standard C library on Linux, the collection of basic functions almost every program uses. Unlike the glibc version, the Linux kernel implementation also covers buffer reads in addition to writes.

At its core, FORTIFY_SOURCE uses the compiler's __builtin_object_size() to determine the available size at a target address based on the compile-time known structure layout. In everyday terms: the compiler knows how big each box is, so it can ask "how much room is actually left here?" before allowing a copy. Two of its modes matter here:

  • Mode 0: checks the outer bounds of the structure.
  • Mode 1: checks the inner bounds of members in the structure.

The difference is easier with an example:

C
struct object {
		u16 scalar1;	/* 2 bytes */
		char array[6];	/* 6 bytes */
		u64 scalar2;	/* 8 bytes */
		u32 scalar3;	/* 4 bytes */
		u32 scalar4;	/* 4 bytes */
} instance;

Line by line:

  1. struct object { starts the definition of a bundle of fields.
  2. u16 scalar1; is a two-byte number.
  3. char array[6]; is a six-byte array, a row of six slots.
  4. u64 scalar2; is an eight-byte number.
  5. u32 scalar3; and u32 scalar4; are four-byte numbers each.
  6. } instance; creates one actual variable of this type, named instance.

__builtin_object_size(instance.array, 0) == 22, since the remaining size of the enclosing structure starting from the field array is 22 bytes (6 + 8 + 4 + 4). __builtin_object_size(instance.array, 1) == 6, since the remaining size of the specific field array is 6 bytes. Mode 0 asks "how much room until the end of the whole bundle?", mode 1 asks "how much room until the end of this one field?".

The initial implementation of FORTIFY_SOURCE in kernel v4.13 used __builtin_object_size() with mode 0, because there were many cases of both strcpy and memcpy being used to write (or read) across multiple fields in a structure. That prevented overflows from reaching beyond the end of the structure, but since structures are a continuous area in memory, it did not protect against overwriting neighbouring structure fields. Picture a row of houses sharing walls: mode 0 stops you from leaving the block, but not from breaking into the house next door.

In kernel v5.11, mode 1 was turned on for the strcpy family of functions, and in kernel v5.18, mode 1 was turned on for the memcpy family of functions. Compiling a kernel module on a machine with FORTIFY_SOURCE enabled (CONFIG_FORTIFY_SOURCE) therefore has this mitigation enabled by default:

C
__FORTIFY_INLINE void *memcpy(void *p, const void *q, __kernel_size_t size)
{
	size_t p_size = __builtin_object_size(p, 0);
	size_t q_size = __builtin_object_size(q, 0);

	if (__builtin_constant_p(size)) {  // The size is known at compile-time
		if (p_size < size)
			__write_overflow();
		if (q_size < size)
			__read_overflow2();
	}
	if (p_size < size || q_size < size)
		fortify_panic(__func__);
	return __underlying_memcpy(p, q, size);
}

Line by line:

  1. This is a replacement version of memcpy, the function that copies memory. It takes a destination p, a source q and a size.
  2. p_size is how much room the destination has, according to the compiler.
  3. q_size is how much room the source has.
  4. if (__builtin_constant_p(size)) asks whether the size is already known while compiling.
  5. If it is, and the destination is too small, __write_overflow() is called; if the source is too small, __read_overflow2() is called. Both are compile-time errors.
  6. If the size is only known at run time, the check if (p_size < size || q_size < size) runs instead, and calls fortify_panic when the copy would not fit.
  7. If everything fits, the real copy happens via __underlying_memcpy.

Fortify Source checks the code both at compile time and at run time:

From the original on cyberark.com

For instance, in the memcpy check, if the size is known at compile time there is an error right away, which causes compilation failure.

From the original on cyberark.com

Otherwise, if the size is determined at run time, a call to fortify_panic is triggered before the out-of-bounds copy operation:

C
void fortify_panic(const char *name)
{
	pr_emerg("detected buffer overflow in %s\n", name);
	BUG();
}

Line by line:

  1. fortify_panic takes the name of the function that detected the problem.
  2. pr_emerg(...) writes an emergency-level message to the kernel log, saying a buffer overflow was detected and naming the function.
  3. BUG() deliberately crashes the current execution path.

fortify_panic calls the BUG macro, which calls unreachable and crashes the driver. That is far better than letting an attacker arbitrarily write code in the kernel. A controlled crash is a nuisance; silent memory corruption is a security hole.

Exploitation

To trigger the vulnerability, a specially constructed buffer must be sent that makes row_length bigger than 80. Setting start_col to 0x00 and stop_col to a value larger than 0x18 makes row_length exceed the size of the arguments buffer and overflow it. Anything larger spills over.

Step 1: write the crafted buffer to the attribute file

Python
file_path = '/sys/bus/hid/devices/0003:1532:021E.0004/matrix_custom_frame'
payload = b'\x00\x00\x19'
payload += b'\x41' * 80

def crash():
    with open(file_path, 'wb') as f:
        f.write(payload)

if __name__ == '__main__':
   crash()

Line by line:

  1. file_path is the full path of the attribute file for the connected device. The long name in the middle identifies the specific USB device.
  2. payload = b'\x00\x00\x19' builds the first three bytes: row 0, start column 0, stop column 0x19 (25).
  3. payload += b'\x41' * 80 appends 80 bytes of 0x41, which is the letter A. These are the colour data that will be copied.
  4. def crash(): defines a function that performs the write.
  5. with open(file_path, 'wb') as f: opens the attribute file for binary writing.
  6. f.write(payload) sends the bytes to the driver.
  7. The last two lines simply call the function when the script is run.

The first three bytes are row_id (0x00), start_col (0x00) and stop_col (0x19), which makes row_length exceed the space available in the arguments array from offset 5. The remaining 80 bytes of 0x41 are the RGB data that gets copied. Running this crashes the driver, causing a denial of service. A denial of service means making something stop working, without necessarily gaining anything from it.

Step 2: consider the impact without FORTIFY_SOURCE

The impact may be more severe if the driver was not compiled with FORTIFY_SOURCE enabled. In that case the attacker can chain this vulnerability with an information leak vulnerability, bypassing KASLR and stacking canary mitigations (if present). That leads to kernel control-flow hijack, which results in code execution in kernel space. Even without leveraging an information leak vulnerability, exploiting the bug in the absence of FORTIFY_SOURCE would cause a system crash.

Some of those terms deserve a plain explanation:

  • Information leak: a bug that lets an attacker read memory they should not see, for example to learn where things are stored.
  • KASLR: a defence that loads kernel code at a random location each boot, so an attacker cannot know in advance where to jump. An information leak can reveal that location.
  • Canary: a secret value placed next to important data; if an overflow overwrites it, the system notices and stops. "Stacking canary mitigations" means defeating several such protections in turn.
  • Control-flow hijack: making the program jump to code of the attacker's choosing instead of its normal path.
  • Code execution in kernel space: running the attacker's own instructions with the highest privileges on the machine.

Impact

The buffer overflow causes a denial of service and possibly elevation of privileges. Three CVEs were assigned:

Driver CVE
razerkbd CVE-2022-29021
razeraccessory CVE-2022-29022
razermouse CVE-2022-29023

A CVE is a public catalogue number for a known vulnerability, so that everyone can refer to the same issue unambiguously. The severity depends on the build: with FORTIFY_SOURCE enabled, the run-time check turns the overflow into a crash of the driver; without it, kernel code execution becomes possible when combined with an information leak, and a system crash otherwise.

Fix

As part of the disclosure, a patch was submitted for the described vulnerabilities, adding checks before the memcpy to prevent any overflow. It was merged soon after and was part of the new release. A patch is a small change to the source code that fixes a problem; merged means the project accepted it into the official code.

Disclosure timeline:

  • April 3, 2022: bug found
  • April 4, 2022: reported to the OSS maintainer
  • April 8, 2022: PR for fixing the vulnerable code opened
  • April 9, 2022: merged and a new release of OpenRazer published (3.3.0)
  • May 20, 2022: CVEs granted

A PR (pull request) is a proposed change submitted to a project for review. OSS means open-source software.

Variants to test

  • Other OpenRazer drivers exposing matrix_custom_frame: razermouse and razeraccessory were confirmed to share the same implementation. A positive result is the same crash when writing a buffer whose stop_col exceeds 0x18 with start_col at 0x00.
  • Other write-only attribute files in the same drivers: any store function that derives a length from user-controlled bytes and passes it to memcpy into a fixed-size structure is a candidate. A positive result is a fortify_panic message in dmesg or a driver crash.
  • Builds without CONFIG_FORTIFY_SOURCE: the same payload that only crashes the driver on a fortified build may corrupt memory beyond the arguments array. A positive result is memory corruption rather than a clean panic.
  • Other third-party Linux kernel modules that parse user-supplied buffers from sysfs or HID interfaces: look for length fields computed from user input and used as copy sizes. A positive result is an out-of-bounds copy reachable from an unprivileged user.

Glossary

  • Attribute file: a file in sysfs that represents a driver feature; reading or writing it triggers a function in the driver.
  • Buffer: a fixed-size area of memory used to hold data.
  • Buffer overflow: writing more data into a buffer than it can hold, so the extra data spills into neighbouring memory.
  • BUG macro: a kernel macro that deliberately crashes the current execution path when something impossible has happened.
  • Canary: a secret value placed next to important data so that an overflow is detected.
  • Compiler: the program that turns source code into machine code.
  • Control-flow hijack: making a program jump to attacker-chosen code instead of its normal path.
  • CVE: a public catalogue number for a known vulnerability.
  • Debug symbols: extra labels in a compiled program that make reversing easier.
  • Denial of service: making a system or program stop working.
  • DEVICE_ATTR: a C macro that declares a sysfs attribute file with its name, permissions and read/write functions.
  • Elevation of privileges: gaining rights the attacker should not have, up to full control of the machine.
  • FORTIFY_SOURCE: a compile-time and run-time safety feature that checks whether copies fit in their destination.
  • fortify_panic: the function called when Fortify Source detects an overflow at run time; it logs and crashes.
  • glibc: the standard C library on Linux.
  • HID: Human Interface Device, the standard way keyboards, mice and similar devices describe themselves.
  • Information leak: a bug that lets an attacker read memory they should not see.
  • KASLR: a defence that loads kernel code at a random address each boot.
  • Kernel: the core of the operating system, with full control over the hardware.
  • Kernel module: code loaded into the kernel at run time, usually for device support, running with kernel privileges.
  • Macro: a shorthand in C that expands into a larger piece of code.
  • Makefile: a recipe file that tells the computer how to build software.
  • memcpy: a C function that copies a given number of bytes from one place in memory to another.
  • Mitigation: a safety net that makes a bug harder to exploit without removing it.
  • Open source: software whose source code is published for anyone to read and change.
  • Patch: a small change to source code that fixes a problem.
  • PR (pull request): a proposed change submitted to a project for review.
  • Reversing: working backwards from a compiled program to understand what it does.
  • RGB: red, green and blue, the three numbers that describe a colour.
  • struct: a C construct that groups several related values under one name.
  • sysfs: a part of the Linux filesystem that represents kernel objects as files.
  • Union: a C construct where several types share the same memory.
  • USB-HID: a USB device that follows the HID standard, such as a keyboard or mouse.
  • Virtual machine (VM): a computer simulated inside another computer.
  • Wrapper: a small function that forwards a call to another function, often adding a default value.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.