Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Pascal compilers need SecureZeroMemory function?

Consider the code:

procedure DoSmthSecret;
var
  Seed: array[0..31] of Byte;

begin
// get random seed
  ..
// use the seed to do something secret
  ..
// erase the seed
  FillChar(Seed, SizeOf(Seed), 0);
end;

The problem with the code is: FillChar is a compiler intrinsic, and potentially a compiler can "optimize it out". The problem is known for C/C++ compilers, see SecureZeroMemory. Can modern Pascal compiler (Delphi, FPC) do such optimization, and if they can, do they provide SecureZeroMemory equivalent?

like image 503
kludg Avatar asked Mar 02 '16 09:03

kludg


2 Answers

FPC can't do such optimizations at the moment, and afaik even with C++ they belong into the "uncertain" class. (since the state of the program due to this optimization ignores what the programmer tells it to be)

Solving such problem is a matter of defining which constructs can be optimized out and which not. It doesn't need API/OS assistance per se, any externally linked object file with such function would do (since then global optimization wouldn't touch it)

Note that the article doesn't name the C++ compiler specifically, so I expect it is more a general utility function for when an user of a compiler gets into problems, without hitting the docs too hard, or when it must easily work on multiple (windows-only!) compilers without overly complicating the buildsystem.

Choosing a non inlinable API function might be non optimal in other cases, specially with small, constant sizes to zero, since it won't be inlined, so I would be careful with this function, and make sure there is a hard need

It might be important mainly when an external entity can change memory (DMA, memory mapping etc) of a program, or to erase passwords and other sensitive info from the memory image, even if the program according to the compiler will never read it

like image 70
Marco van de Voort Avatar answered Oct 07 '22 12:10

Marco van de Voort


Even if FreePascal would optimize out writing to memory that is never read again (which I doubt it does atm, regardless of how long you guys discuss it), it does support the absolute type modifier which it guarantees (documented) to never optimize (somewhat similar to volatile in C/C++).

like image 35
tofro Avatar answered Oct 07 '22 13:10

tofro