13

I'm trying to protect a local database that contains sensitive info (similar to this question, only for delphi 2010)

I'm using DISQLite component, which does support AES encryption, but I still need to protect this password I use to decrypt & read the database.

My initial idea was to generate a random password, store it using something like DPAPI (CryptProtectData and CryptUnprotectData functions found in Crypt32.dll), but I couldn't find any example on that for Delphi

My question is: how can I safely store a randomly generated password? Or, assuming the DPAPI road is secure, how can I implement this DPAPI in Delphi?

Community
  • 1
  • 1
TheDude
  • 3,045
  • 4
  • 46
  • 95
  • 2
    As usually, JEDI library has wrappers for the Windows Cryptography API interface, in `JwaWinCrypt.pas` unit. – TLama Oct 30 '12 at 18:17
  • You can try LockBox, free and easy to use: http://sourceforge.net/projects/tplockbox/ – JustMe Oct 30 '12 at 18:21
  • @TLama: Thanks, yes I just [found it here](http://jedi-apilib.cvs.sourceforge.net/viewvc/jedi-apilib/Win32API/JwaWinCrypt.pas?view=markup), quit a heavy unit with no example...any lighter solution? – TheDude Oct 30 '12 at 18:24
  • @JustMe: Thanks, but it's not clear how does LockBox help in implementing secure password storage, any pointer would be more than welcome! – TheDude Oct 30 '12 at 18:26
  • @TheDude First try http://stackoverflow.com/questions/9449613/how-to-use-aes-256-encryption-in-lockbox-3-using-delphi Anyway it's really easy! – JustMe Oct 30 '12 at 18:33
  • @JustMe: Thanks but I can't/won't bother the user to enter the database password, that's why I'm looking for a secure way to store it somewhere (locally) then read it at runtime – TheDude Oct 30 '12 at 18:40
  • 3
    How will encrypting the password protect anything? Surely an attacker can just read the decrypted password from memory? – David Heffernan Oct 30 '12 at 18:42
  • 1
    @DavidHeffernan So there's no sense to decrypt anything from the application? :-( – JustMe Oct 30 '12 at 18:46
  • @DavidHeffernan: I understand, but I can't just save the password in clear in an ini file! I'm trying to make things as hard as possible for attackers. – TheDude Oct 30 '12 at 18:46
  • 1
    @TheDude Yea, make those stupid script kiddies life harder! :-D – JustMe Oct 30 '12 at 18:48
  • Question: I'd solve the password storage issue by making a hash of it and then storing the hash on disk. Then when it comes time for validation, hashing the entered password and then checking the hash against the stored value. Since people are looking at regular encryption (code/decode), is there a drawback to what I'm suggesting or is there another requirement behind most of these questions? – Glenn1234 Oct 30 '12 at 18:58
  • 1
    @Glenn1234: Unfortunately, I **have to** have the **real password** in order to open the database! A hash won't cut it :( – TheDude Oct 30 '12 at 19:03
  • 1
    You have the real password - the user has just entered it! – Martin James Oct 31 '12 at 10:21

3 Answers3

19

It's better to use Windows' DPAPI. It's much more secure than using other methods:

  • CryptProtectData / CryptProtectMemory
  • CryptUnprotectData / CryptUnprotectMemory

CryptProtectMemory / CryptUnprotectMemory offer more flexibility:

  • CRYPTPROTECTMEMORY_SAME_PROCESS: only your process can decrypt your data
  • CRYPTPROTECTMEMORY_CROSS_PROCESS: any process can dectypt your data
  • CRYPTPROTECTMEMORY_SAME_LOGON: only processes running with the same user and in the same session can decrypt data

Pros:

  1. No need to have a key - Windows do it for you
  2. Granular control: per process / per session / per login / per machine
  3. CryptProtectData exists in Windows 2000 and newer
  4. DPAPI Windows is more secure than using "security" related code written from you, me and the people that believe Random() returns absolutely random number :) In fact Microsoft has decades of experience in the security field, having the most attacked OS ever :o)

Cons:

  1. In the case of CRYPTPROTECTMEMORY_SAME_PROCESS One* can just inject a new thread in your process and this thread can decrypt your data
  2. If someone reset user's password (not change) you will be unable to decrypt your data
  3. In the case of CRYPTPROTECTMEMORY_SAME_LOGON: if the user* run hacked process it can decrypt your data
  4. If you use CRYPTPROTECT_LOCAL_MACHINE - every user* on that machine can decrypt the data. This is why it's not recommended to save passwords in .RDP files
  5. Known issues

Note: "every user" is a user who has tools or skills to use DPAPI

Anyway - you have a choice.

Note that @David-Heffernan is right - anything stored on the computer can be decrypted - reading it from memory, injecting threads in your process etc.

On the other hand ... why don't we make cracker's life harder? :)

Rule of thumb: clear all buffers that contain sensitive data after using them. This doesn't make things super safe, but decreases the possibility your memory to contain sensitive data. Of course this doesn't solve the other major problem: how other Delphi components handle the sensitive data you pass to them :)

Security Library by JEDI has object oriented approach to DPAPI. Also JEDI project contains translated windows headers for DPAPI (JWA IIRC)

UPDATE: Here's sample code that uses DPAPI (using JEDI API):

Uses SysUtils, jwaWinCrypt, jwaWinBase, jwaWinType;

function dpApiProtectData(var fpDataIn: tBytes): tBytes;
var
  dataIn,               // Input buffer (clear-text/data)
  dataOut: DATA_BLOB;   // Output buffer (encrypted)
begin
  // Initializing variables
  dataOut.cbData := 0;
  dataOut.pbData := nil;

  dataIn.cbData := length(fpDataIn); // How much data (in bytes) we want to encrypt
  dataIn.pbData := @fpDataIn[0];     // Pointer to the data itself - the address of the first element of the input byte array

  if not CryptProtectData(@dataIn, nil, nil, nil, nil, 0, @dataOut) then
    RaiseLastOSError; // Bad things happen sometimes

  // Copy the encrypted bytes to RESULT variable
  setLength(result, dataOut.cbData);
  move(dataOut.pbData^, result[0], dataOut.cbData);
  LocalFree(HLOCAL(dataOut.pbData));                  // http://msdn.microsoft.com/en-us/library/windows/desktop/aa380261(v=vs.85).aspx
//  fillChar(fpDataIn[0], length(fpDataIn), #0);  // Eventually erase input buffer i.e. not to leave sensitive data in memory
end;

function dpApiUnprotectData(fpDataIn: tBytes): tBytes;
var
  dataIn,               // Input buffer (clear-text/data)
  dataOut: DATA_BLOB;   // Output buffer (encrypted)
begin
  dataOut.cbData := 0;
  dataOut.pbData := nil;

  dataIn.cbData := length(fpDataIn);
  dataIn.pbData := @fpDataIn[0];

  if not CryptUnprotectData(
    @dataIn,  
    nil, 
    nil, 
    nil, 
    nil, 
    0,         // Possible flags: http://msdn.microsoft.com/en-us/library/windows/desktop/aa380261%28v=vs.85%29.aspx 
               // 0 (zero) means only the user that encrypted the data will be able to decrypt it
    @dataOut
  ) then
    RaiseLastOSError;

  setLength(result, dataOut.cbData);                  // Copy decrypted bytes in the RESULT variable
  move(dataOut.pbData^, result[0], dataOut.cbData);   
  LocalFree(HLOCAL(dataOut.pbData));                  // http://msdn.microsoft.com/en-us/library/windows/desktop/aa380882%28v=vs.85%29.aspx
end;

procedure testDpApi;
var
  bytesClearTextIn,       // Holds input bytes
  bytesClearTextOut,      // Holds output bytes
  bytesEncrypted: tBytes; // Holds the resulting encrypted bytes
  strIn, strOut: string;  // Input / Output strings
begin

  // *** ENCRYPT STRING TO BYTE ARRAY
  strIn := 'Some Secret Data Here';

  // Copy string contents to bytesClearTextIn
  // NB: this works for STRING type only!!! (AnsiString / UnicodeString)
  setLength(bytesClearTextIn, length(strIn) * sizeOf(char));
  move(strIn[1], bytesClearTextIn[0], length(strIn) * sizeOf(char));

  bytesEncrypted := dpApiProtectData(bytesClearTextIn);     // Encrypt data

  // *** DECRYPT BYTE ARRAY TO STRING
  bytesClearTextOut := dpApiUnprotectData(bytesEncrypted);  // Decrypt data

  // Copy decrypted bytes (bytesClearTextOut) to the output string variable
  // NB: this works for STRING type only!!! (AnsiString / UnicodeString)    
  setLength(strOut, length(bytesClearTextOut) div sizeOf(char));
  move(bytesClearTextOut[0], strOut[1], length(bytesClearTextOut));

  assert(strOut = strIn, 'Boom!');  // Boom should never booom :)

end;

Notes:

  • The example is lightweight version of using CryptProtectData / CryptUnprotectData;
  • Encryption is byte oriented so it's easier to use tBytes (tBytes = array of byte);
  • If input and output string are UTF8String, then remove "* sizeOf(char)", because UTF8String's char is 1 byte only
  • The use of CryptProtectMemory / CryptUnProtectMemory is similar
iPath ツ
  • 2,468
  • 20
  • 31
  • 2
    Word of warning: `CryptProtectMemory` is deterministic, meaning it is susceptible to frequency analysis. (i.e. if you have the same data being encrypted in multiple places in memory, they will produce the same ciphertext, so an attacker will be able to tell they are the same thing, which may leak information.) – user541686 Apr 06 '18 at 21:24
  • 1
    be warned, jedi links are linking to pishing site, use https://www.delphi-jedi.org/ instead ! – Jimbot Aug 15 '23 at 14:31
12

If your issue is simply to save the user from having to type a password every time, you should know that Windows already has a password storage system.

If you go to Control Panel -> Credential Manager. From there you are looking for Windows Credentials -> Generic Credentials.

From there you can see that it is the same place that things like Remote Desktop passwords are stored:

enter image description here

The API that exposes this functionality is CredRead, CredWrite, and CredDelete.

I wrapped these up in three functions:

function CredReadGenericCredentials(const Target: UnicodeString; var Username, Password: UnicodeString): Boolean;
function CredWriteGenericCredentials(const Target, Username, Password: UnicodeString): Boolean;
function CredDeleteGenericCredentials(const Target: UnicodeString): Boolean;

The target is the thing to identify the credentails. I usually use the application name.

String target = ExtractFilename(ParamStr(0)); //e.g. 'Contoso.exe'

So then it's simply:

CredWriteGenericCredentials(ExtractFilename(ParamStr(0)), username, password);

You can then see them in the Credential Manager:

enter image description here

When you want to read them back:

CredReadGenericCredentials(ExtractFilename(ParamStr(0)), {var}username, {var}password);

There is the extra piece of UI work where you have to:

  • detect that there were no stored credentials, and prompt the user for credentials
  • detect that the saved username/password didn't work and prompt for new/correct credentials, try connecting, and save the new correct credentials

Reading stored credentials:

function CredReadGenericCredentials(const Target: UnicodeString; var Username, Password: UnicodeString): Boolean;
var
    credential: PCREDENTIALW;
    le: DWORD;
    s: string;
begin
    Result := False;

    credential := nil;
    if not CredReadW(Target, CRED_TYPE_GENERIC, 0, {var}credential) then
    begin
        le := GetLastError;
        s := 'Could not get "'+Target+'" generic credentials: '+SysErrorMessage(le)+' '+IntToStr(le);
        OutputDebugString(PChar(s));
        Exit;
    end;

    try
        username := Credential.UserName;
        password := WideCharToWideString(PWideChar(Credential.CredentialBlob), Credential.CredentialBlobSize div 2); //By convention blobs that contain strings do not have a trailing NULL.
    finally
        CredFree(Credential);
    end;

    Result := True;
end;

Writing stored credentials:

function CredWriteGenericCredentials(const Target, Username, Password: UnicodeString): Boolean;
var
    persistType: DWORD;
    Credentials: CREDENTIALW;
    le: DWORD;
    s: string;
begin
    ZeroMemory(@Credentials, SizeOf(Credentials));
    Credentials.TargetName := PWideChar(Target); //cannot be longer than CRED_MAX_GENERIC_TARGET_NAME_LENGTH (32767) characters. Recommended format "Company_Target"
    Credentials.Type_ := CRED_TYPE_GENERIC;
    Credentials.UserName := PWideChar(Username);
    Credentials.Persist := CRED_PERSIST_LOCAL_MACHINE;
    Credentials.CredentialBlob := PByte(Password);
    Credentials.CredentialBlobSize := 2*(Length(Password)); //By convention no trailing null. Cannot be longer than CRED_MAX_CREDENTIAL_BLOB_SIZE (512) bytes
    Credentials.UserName := PWideChar(Username);
    Result := CredWriteW(Credentials, 0);
    end;
end;

And then delete:

function CredDeleteGenericCredentials(const Target: UnicodeString): Boolean;
begin
    Result := CredDelete(Target, CRED_TYPE_GENERIC);
end;

CredRead is a wrapper around CryptProtectData

It should be noted that CredWrite/CredRead internally uses CryptProtectData.

  • It just also chooses to store the credentials someplace for you
  • It also provides a UI for the user to see, manage, and even manually enter and change the saved credentials

The difference by using CryptProtectData yourself is that you're only given a blob. It's up to you to store it somewhere, and retrieve it later.

Here's nice wrappers around CryptProtectData and CryptUnprotectData when storing passwords:

function EncryptString(const Plaintext: UnicodeString; const AdditionalEntropy: UnicodeString): TBytes;
function DecryptString(const Blob: TBytes; const AdditionalEntropy: UnicodeString): UnicodeString;

which is easy enough to use:

procedure TForm1.TestStringEncryption;
var
    encryptedBlob: TBytes;
    plainText: UnicodeString;
const
    Salt = 'Salt doesn''t have to be secret; just different from the next application';
begin
    encryptedBlob := EncryptString('correct battery horse staple', Salt);

    plainText := DecryptString(encryptedBlob, salt);

    if plainText <> 'correct battery horse staple' then
        raise Exception.Create('String encryption self-test failed');
end;

The actual guts are:

type
    DATA_BLOB = record
            cbData: DWORD;
            pbData: PByte;
    end;
    PDATA_BLOB = ^DATA_BLOB;

const
    CRYPTPROTECT_UI_FORBIDDEN = $1;

function CryptProtectData(const DataIn: DATA_BLOB; szDataDescr: PWideChar; OptionalEntropy: PDATA_BLOB; Reserved: Pointer; PromptStruct: Pointer{PCRYPTPROTECT_PROMPTSTRUCT}; dwFlags: DWORD; var DataOut: DATA_BLOB): BOOL; stdcall; external 'Crypt32.dll' name 'CryptProtectData';
function CryptUnprotectData(const DataIn: DATA_BLOB; szDataDescr: PPWideChar; OptionalEntropy: PDATA_BLOB; Reserved: Pointer; PromptStruct: Pointer{PCRYPTPROTECT_PROMPTSTRUCT}; dwFlags: DWORD; var DataOut: DATA_BLOB): Bool; stdcall; external 'Crypt32.dll' name 'CryptUnprotectData';

function EncryptString(const Plaintext: UnicodeString; const AdditionalEntropy: UnicodeString): TBytes;
var
    blobIn: DATA_BLOB;
    blobOut: DATA_BLOB;
    entropyBlob: DATA_BLOB;
    pEntropy: Pointer;
    bRes: Boolean;
begin
    blobIn.pbData := Pointer(PlainText);
    blobIn.cbData := Length(PlainText)*SizeOf(WideChar);

    if AdditionalEntropy <> '' then
    begin
        entropyBlob.pbData := Pointer(AdditionalEntropy);
        entropyBlob.cbData := Length(AdditionalEntropy)*SizeOf(WideChar);
        pEntropy := @entropyBlob;
    end
    else
        pEntropy := nil;

    bRes := CryptProtectData(
            blobIn,
            nil, //data description (PWideChar)
            pentropy, //optional entropy (PDATA_BLOB)
            nil, //reserved
            nil, //prompt struct
            CRYPTPROTECT_UI_FORBIDDEN, //flags
            {var}blobOut);
    if not bRes then
        RaiseLastOSError;

    //Move output blob into resulting TBytes
    SetLength(Result, blobOut.cbData);
    Move(blobOut.pbData^, Result[0], blobOut.cbData);

    // When you have finished using the DATA_BLOB structure, free its pbData member by calling the LocalFree function
    LocalFree(HLOCAL(blobOut.pbData));
end;

And decrypting:

function DecryptString(const blob: TBytes; const AdditionalEntropy: UnicodeString): UnicodeString;
var
    dataIn: DATA_BLOB;
    entropyBlob: DATA_BLOB;
    pentropy: PDATA_BLOB;
    dataOut: DATA_BLOB;
    bRes: BOOL;
begin
    dataIn.pbData := Pointer(blob);
    dataIn.cbData := Length(blob);

    if AdditionalEntropy <> '' then
    begin
        entropyBlob.pbData := Pointer(AdditionalEntropy);
        entropyBlob.cbData := Length(AdditionalEntropy)*SizeOf(WideChar);
        pentropy := @entropyBlob;
    end
    else
        pentropy := nil;

    bRes := CryptUnprotectData(
            DataIn,
            nil, //data description (PWideChar)
            pentropy, //optional entropy (PDATA_BLOB)
            nil, //reserved
            nil, //prompt struct
            CRYPTPROTECT_UI_FORBIDDEN,
            {var}dataOut);
    if not bRes then
        RaiseLastOSError;

    SetLength(Result, dataOut.cbData div 2);
    Move(dataOut.pbData^, Result[1], dataOut.cbData);
    LocalFree(HLOCAL(DataOut.pbData));
end;
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
  • How do you know that CredWrite/CredRead internally uses CryptProtectData? Can you cite the source of this information? I just used API monitor and on execute CredWrite or CredRead there are no calls to CryptProtectData – Carlos B. Feitoza Filho Feb 11 '23 at 05:17
0

Ok, here's an example using TurboPower Lockbox (version 2)

  uses LbCipher, LbString;

  TaAES = class
  private
    Key: TKey256;
    FPassword: string;
  public
    constructor Create;

    function Code(AString: String): String;
    function Decode(AString: String): String;

    property Password: string read FPassword write FPassword;
  end;

function TaAES.Code(AString: String): String;
begin
  try
    RESULT := RDLEncryptStringCBCEx(AString, Key, SizeOf(Key), False);
  except
    RESULT := '';
  end;
end;

constructor TaAES.Create;
begin
  GenerateLMDKey(Key, SizeOf(Key), Password);
end;

function TaAES.Decode(AString: String): String;
begin
  RESULT := RDLEncryptStringCBCEx(AString, Key, SizeOf(Key), True);
end;

You can save your password as variable in your application. Without save to file example but you can use TFileStream to save encrypted(code) password and then decode it to read it :-)

JustMe
  • 2,329
  • 3
  • 23
  • 43
  • Thanks JustMe, but then I have to hide the key used in encryption, so I'm kind of going back to square one :( – TheDude Oct 30 '12 at 19:04
  • No, you don't. Key is just length of the key encryption - in this example it's 256 bit AES. And have in mind what @DavidHeffernan [points](http://stackoverflow.com/questions/13145112/delphi-application-secure-way-to-store-password-in-windows#comment17880906_13145112) earlier – JustMe Oct 30 '12 at 19:06
  • Thanks JustMe, I'll take a look at LockBox (I'm not sure how they can do it without keys thought...I'll have to study that) – TheDude Oct 30 '12 at 20:05
  • You encrypt string with a password. Password will be your constant in the program. – JustMe Oct 30 '12 at 20:38
  • 1
    @TheDude: LockBox generates the key. See the code in `TaAES.Create` in JustMe's answer above - the line says `GenerateLMDKey` ;-) – Ken White Oct 30 '12 at 20:45
  • I looked into LockBox a year or two ago and although I may be mistaken, I seem to recall that there were some warnings or errors when compiling in more recent Unicode versions of Delphi. I also recall that there was a new version Lockbox (3?) that was a fork in the code, being managed by a different group (or even just one guy?). All this is unsubstantiated and filtered through my poor memory, but the whole situation spooked me a bit, but perhaps I'm mistaken or being over-sensitive - (For example, I'm generally nervous using open-source.) Just a "heads-up" in case there's an issue here. – RobertFrank Oct 31 '12 at 00:30