Alex Rivera | Logout

How-to ensure that compiler optimizations don't introduce a security risk?

Asked 2010-09-24T08:23:38.470
41

I have to write a Windows service that handles at some point confidential data (such as PIN codes, passwords, and so on). Those informations are needed for a very short amount of time: usually they are sent almost immediately to a smart card reader.

Lets consider this piece of code:

{
  std::string password = getPassword(); // Get the password from the user

  writePasswordToSmartCard(password);

  // Okay, here we don't need password anymore.
  // We set it all to '\0' so it doesn't stay in memory.
  std::fill(password.begin(), password.end(), '\0');
}

Now my concern is about compiler optimizations. Here the compiler might detect that password is about to be deleted and that changing its value at this point is useless and just remove the call.

I don't expect my compiler to care about the value of future-unreferenced memory.

Are my concerns legitimate ? How can I be sure that such a piece of code won't be optimized-out ?

Edit
Report

1 Answer

9

Don't use std::string for passwords, as it doesn't zero out it's memory when doing reallocations or destruction - design your own ConfidentialString class instead. When designing that class, you might want to take advantage of CryptProtectMemory... and be very, very careful when you need to use the decrypted version, especially when calling external code.

answered 2010-09-24T09:24:25.263

Your Answer