2

We have written C++ code which compiles both on Windows and Ubuntu. I want to use secure function memset_s for zeroing out buffers in my app.

Both Windows and Ubuntu 16.04 does not include definition of __STDC_LIB_EXT1__ macro so I am not able to use memset_s provided by C++11.

On windows I have SecureZeroMemory which prevents compiler optimization. On Ubuntu 16.04 (GCC version 5.4 ) I am looking for SecureZeroMemory equivalent library function (which will prevent compiler optimization).

It will be really helpful if you can suggest me library function in linux, end option is manual implemention memset_s for linux platform

Thanks in advance

  • Could use a loop + volatile. – Trass3r Dec 04 '18 at 06:18
  • 2
    Possible duplicate of [Is it possible to guarantee code doing memory writes is not optimized away in C++?](https://stackoverflow.com/questions/13268657/is-it-possible-to-guarantee-code-doing-memory-writes-is-not-optimized-away-in-c) – Retired Ninja Dec 04 '18 at 06:24
  • XY problem? Why are you worried about compiler optimisations? And what does the buzzword *secure* have to do with it? – n. m. could be an AI Dec 04 '18 at 06:32
  • I believe Microsoft implements ISO/IEC TR 24731 (now part of the standard) so you have the safer string functions. glibc is not conforming so it is not part of the standard library. On Linux I think you install a dev library for it. I think it is libbsd, but I don't recall for sure. Also see [Safe String Functions In Mac OS X and Linux](https://stackoverflow.com/q/4570147/608639). – jww Dec 04 '18 at 06:41
  • 2
    There's no `memset_s` in C++11, or in C++17 for that matter. – MSalters Dec 04 '18 at 07:59
  • explicit_bzero is the equivalent of SecureZeroMemory – dmex Jan 17 '19 at 13:07

1 Answers1

2

If you want to be sure the memory is zeroed and that this operation is not optimized out by the compiler (because of the as-if rule), you can put an "optimizer barrier":

void always_memset(void* dest,int ch,size_t count){
     memset(dest,ch,count);
     //Make the compiler believe that you are using memory
     //including memory referenced by dest
     asm volatile("" : : :"memory");//it is possible to be more subtle.

     }

Then memset_s can easily be implemented by a call to this function after the precondition checks.

Oliv
  • 17,610
  • 1
  • 29
  • 72
  • thanks for your response. But I wish to avoid use of memset itself Is there any SecureZeroMemory equivalent function in gcc or third party libraray ?? – Tushar Patil Dec 04 '18 at 08:45
  • @TusharPatil I would be surprised if none of the crypto libraries available on linux did not provide a function to do that. – Oliv Dec 04 '18 at 09:44