Blog | G5 Cyber Security

Intel MPX Bounds Checking Guide

TL;DR

This guide shows you how to use Intel’s Memory Protection Extensions (MPX) for bounds checking in C/C++. It covers compilation, linking, and a simple example of protecting an array access. MPX adds hardware support to detect buffer overflows and underflows at runtime.

Prerequisites

1. Compilation Flags

You need to enable MPX during compilation. Use the following flags with GCC or Clang:

gcc -mpopcnt -mbound-checks your_code.c -o your_program

With Intel Compiler, use these flags:

icpc -mpopcnt -qbounds-check your_code.c -o your_program

2. Understanding Bounds Checking

MPX uses a set of registers to store the base address and size of protected memory regions. When you access memory within a protected region, MPX checks if the access is valid. If it’s not, a signal (SIGILL on Linux) is raised.

3. Example: Protecting an Array Access

Let’s protect an array access using MPX:

#include 
#include 

int main() {
  int arr[10];
  int *protected_arr = arr;
  size_t protected_size = sizeof(arr);

  // Use MPX to protect the array access.
  for (int i = 0; i <= 10; ++i) {
    if (i < 10) {
      protected_arr[i] = i;
    } else {
      printf("Accessing out of bounds!");
    }
  }

  for (int i = 0; i < 10; ++i) {
    printf("%d ", arr[i]);
  }
  printf("n");

  return 0;
}

Compile this code with the flags mentioned in step 1:

gcc -mpopcnt -mbound-checks example.c -o example

4. Running the Program

When you run the program, it will likely crash when accessing `protected_arr[10]` because that is outside of the bounds defined by `protected_size`. The operating system will terminate the process with a SIGILL signal.

5. Linking Considerations

Ensure your linker supports MPX. Most modern linkers do, but if you encounter issues, check your linker documentation for specific flags or options related to memory protection features.

6. Limitations

Exit mobile version