llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

Increasing the Hamming distance for defense programming may be optimized by the compiler.

Open zhou-shan opened this issue 2 years ago • 2 comments

  1. The code that caused the error is as follows:(test.c)
enum {
  TEST_XXX_ENABLED = 0x5AA55AA5,
  TEST_XXX_DISABLED = 0xA55AA55A,
};
static unsigned int g_test_xxx_flag = TEST_XXX_DISABLED;

bool test_xxx_is_enable(void)
{
  return g_test_xxx_flag == TEST_XXX_ENABLED;
}

vold test_xxx_enable(void)
{
  g_test_xxx_flag = TEST_XXX_ENABLED;
}
  1. The optimization level is Os.
  2. Problem Description: image The function works normally, but the secure programming design (increasing the Hamming distance) is optimized by the compiler. In the final generated executable program:
  • The size of g_test_xxx_flag is reduced from 4 bytes to 1 byte.
  • The operations of assigning and comparing g_test_xxx_flag are both replaced with 0/1.

We expect to generate the following assembly instruction sequence: image

zhou-shan avatar Dec 20 '23 02:12 zhou-shan

Currently, we add "volatile" when defining variables to prevent optimization.

zhou-shan avatar Dec 20 '23 02:12 zhou-shan

It's a legal optimization. If you want to prevent it, make the value observable (e.g. via volatile as you did, or by making it non-static assuming you don't use LTO.)

nikic avatar Dec 20 '23 08:12 nikic