Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi : how to completely remove String from the memory [duplicate]

Var
S1:String;
S2:String;
begin
   S1:='Sensitive Data';
   S2:=Crypt(S1,'encryption key');
   S1:='';
   FreeAndNil(S1);
end;

now when i search on my process memory using programs like "WinHex" i can easly find the un-crypted String ! even i tried to make new form to encrypt this string then unload the form but it still exist

is there any way to completely remove it

thanks in advance

like image 447
Somebody Avatar asked Dec 06 '13 15:12

Somebody


2 Answers

You need to overwrite the string with zeros when you are done with it. Like this:

ZeroMemory(Pointer(s), Length(s)*SizeOf(Char));

If you are paranoid that the compiler will optimise away the ZeroMemory then you could use SecureZeroMemory. However, the Delphi compiler will not optimise away ZeroMemory so this is somewhat moot.

If you just write:

s := '';

then the memory will be returned as is to the memory manager. You then have no control over when, if ever, the memory manager re-uses or returns the memory.

Obviously you'd need to do that to all copies of the string, and so the only sane approach is not to make copies of sensitive data.

None of this will help with the code as per your question because your sensitive data is a string literal and so is stored in the executable. This approach can only be applied meaningfully for dynamic data. I presume that your real program does not put sensitive data in literals.

Oh, and don't ever pass a string to FreeAndNil. You can only pass object variables to FreeAndNil, but the procedure uses an untyped var parameter so the compiler cannot save you from your mistake.

like image 107
David Heffernan Avatar answered Oct 13 '22 23:10

David Heffernan


Var
  S1:String;
  S2:String;
begin
   S1:='Sensitive Data';
   S2:=Crypt(S1,'encryption key');
   UniqueString(S1); // <-- if reference count of S1 is not 1
   ZeroMemory(Pointer(S1), Length(S1)*SizeOf(Char));
   // or better: SecureZeroMemory(Pointer(S1), Length(S1)*SizeOf(Char));
   S1:='';
end;
like image 45
Remy Lebeau Avatar answered Oct 13 '22 22:10

Remy Lebeau