Erasing sensitive information from memory

2019-07-07 04:30发布

问题:

After reading this question I'm curious how one would do this in C. When receiving the information from another program, we probably have to assume that the memory is writable.

I have found this stating that a regular memset maybe optimized out and this comment stating that memsets are the wrong way to do it.

回答1:

The example you have provided is not quite valid: the compiler can optimize out a variable setting operation when it can detect that there are no side effects and the value is no longer used.

So, if your code uses some shared buffer, accessible from multiple locations, the memset would work fine. Almost.

Different processors use different caching policies, so you might have to use memory barriers to ensure the data (zero's) have reached memory chip from the cache.

So, if you are not worried about hardware level details, making sure compiler can't optimize out operation is sufficient. For example, memsetting block before releasing it would be executed.

If you want to ensure the data is removed from all hardware items, you need to check how the data caching is implemented on your platform and use appropriate code to force cache flush, which can be non-trivial on multi-core machine.