3

i am trying to get session from my Chrome browser. i can see 2 cookie files in Developer Tools. but this is inconvenient for the user to get cookie values from browser, i would like to do it in code. so i use this code to get Chrome default profile cookie sqlite DB:

string local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string path = @"Google\Chrome\User Data\Default\Cookies";

path = Path.Combine(local, path);

next i create SQLite connection and request

var cmd = new SQLiteCommand("SELECT encrypted_value, name FROM cookies WHERE host_key = 'my_host_ip'", con);

then i read the results

byte[] encryptedCookie = (byte[])r.GetValue(r.GetOrdinal("encrypted_value"));

and try to decrypt it:

var decodedData = ProtectedData.Unprotect(encryptedCookie, null, DataProtectionScope.CurrentUser);
var plainText = Encoding.ASCII.GetString(decodedData);

and here i got exception

System.Security.Cryptography.CryptographicException

i know that i MUST decrypt cookie contents under the same user account under which the browser was launched (on the same machine), and parameter DataProtectionScope.CurrentUser is used for that

i see 63 bytes in debugger (in encryptedCookie array), i also see this bytes in SQLite DB BLOB field. but Unprotect method throws System.Security.Cryptography.CryptographicException: Invalid data error.

my code works fine at 5 different PC's in my office (win10, win7), but didnt work on my developer PC (win10, vs2019).

i think that the problem is in my Windows Settings or somewhere else, not in my code. so what i am doing wrong?

interesting note - i found PowerShell script that does the same thing (through Add-Type -AssemblyName System.Security) - get cookie and decrypt it. this script also works fine at 5 office PC's, but didnt work at my PC.

my Windows installation is new, i have no AV software. we connected to the same Corporate domain and we have the same security settings.

UPD 1 a little expreriment:

  1. get cookie value from Chrome browser (32 chars, JSESSIONID)
  2. create a simple app that protects this value with CurrentUser protection scope. now i have an array of 178 bytes (result #1)
  3. view Chrome's cookies database with a) https://sqliteonline.com/ and b) DataBase.Net desktop app. this two methods give me the same result: only 63 bytes of encrypted cookie data (result #2). i can also get the same result with my c# application using System.Data.SQLite

so, the results are not equal in length or content result #1 != result #2

looks like Chrome's cookie value protected by different scope (maybe admin account?), but i see my user account name in Task Manager in Chrome's process

P.S. i use .net 4.7.2

UPD 2 i found this method in Chromium sources

bool OSCrypt::DecryptString(const std::string& ciphertext,
                            std::string* plaintext) {
  if (!base::StartsWith(ciphertext, kEncryptionVersionPrefix,
                        base::CompareCase::SENSITIVE))
    return DecryptStringWithDPAPI(ciphertext, plaintext);

  crypto::Aead aead(crypto::Aead::AES_256_GCM);

  auto key = GetEncryptionKeyInternal();
  aead.Init(&key);

  // Obtain the nonce.
  std::string nonce =
      ciphertext.substr(sizeof(kEncryptionVersionPrefix) - 1, kNonceLength);
  // Strip off the versioning prefix before decrypting.
  std::string raw_ciphertext =
      ciphertext.substr(kNonceLength + (sizeof(kEncryptionVersionPrefix) - 1));

  return aead.Open(raw_ciphertext, nonce, std::string(), plaintext);
}

so DPAPI is only used when BLOB NOT starts with v10 chars. but my cookie BLOBs starts with v10 chars, and, according to the code, another crypto-algorithm is used, but i dont understand WHY.

cerberus
  • 378
  • 3
  • 15
  • 1
    I'd start by taking MySQL out of the loop - are you able to encrypt and then decrypt an arbitrary byte array on your computer? Just call Protect then Unprotect with the result. – Jon Skeet Feb 14 '20 at 16:50
  • @JonSkeet yes, i create a simple example where i Protect array of data, then Unprotect it with the same entropy (null) and same key - in one console app. all works fine – cerberus Feb 14 '20 at 16:55
  • 1
    So you need to work out which step of the chain things are failing on. First make sure you can reproduce it entirely reliably - then you can log the bytes (e.g. using base64 to get ASCII) on the way in and out, and see where they change. – Jon Skeet Feb 14 '20 at 17:35
  • There is no .NET 7.2. Perhaps you mean that you're using C# 7.2, which does exist. .NET and C# versions are wholly different at this time. – Damien_The_Unbeliever Feb 17 '20 at 13:18
  • @Damien_The_Unbelieversorry, sorry) i mean 4.7.2 framework – cerberus Feb 17 '20 at 13:27
  • @JonSkeet can this be related to user certificates, installed in system? – cerberus Feb 18 '20 at 16:10
  • 1
    I really don't know - I can't quite follow what steps you're going through, or where the data's coming from. Hopefully someone else will be able to help you more. – Jon Skeet Feb 18 '20 at 16:33
  • @cerberus: I second Jon: it is impossible to follow your description. You need to simplify it to 2 steps: explain how you (1) encrypt data and (2) try to decrypt data. Everything else (Chrome, SQLite, etc) is unnecessary info that does little but confusing the readers. Code samples would be helpful, too. If you keep repeating the convoluted process of your data flow, I doubt you get any helpful responses. – Alek Davis Feb 20 '20 at 17:26
  • @AlekDavis i dont encrypt anything, Chrome did this, i only want to decrypt and my code is already in the question: var decodedData = ProtectedData.Unprotect(encryptedCookie, null, DataProtectionScope.CurrentUser); – cerberus Feb 21 '20 at 07:51
  • DPAPI is working fine and i can encrypt and decrypt data by myself, the problem is only with Google Chrome cookies, so i cant skip this info – cerberus Feb 21 '20 at 08:04
  • #cerbrrus: Whaat made you think that you can decrypt Chrome cookies? Did Google publish details of their encryption algorithm? – Alek Davis Feb 21 '20 at 15:09
  • @AlekDavis from 1) https://stackoverflow.com/questions/22532870/encrypted-cookies-in-chrome 2) i also see DPAPI related code in https://github.com/chromium/chromium (https://github.com/chromium/chromium/blob/ccd149af47315e4c6f2fc45d55be1b271f39062c/components/os_crypt/os_crypt_win.cc) 3) the program works fine on other PC's – cerberus Feb 25 '20 at 06:57
  • Is this not dangerous? Hackers who managed to get access to your computer can easily do this and access sensitive information right? Why should anybody be allowed to decrypt cookie values? – Mike Aug 12 '20 at 16:02

2 Answers2

7

I finally figured it out. according to Chromium sources, two methods are used to decrypt the cookie value.

  1. if the cookie value starts with v10 chars, we use AES_256_GCM
  2. otherwise, DPAPI is used

for the first method we need key and nonce. key is located in Google Chrome files and nonce is located in encrypted cookie value.

it remains unclear for me - what determines which method is used

cerberus
  • 378
  • 3
  • 15
5

For people who are looking for the code, I'm expanding on Cerberus answer. Starting Chrome 80 version, cookies are encrypted using the AES256-GCM algorithm, and the AES encryption key is encrypted with the DPAPI encryption system, and the encrypted key is stored inside the ‘Local State’ file.

byte[] encryptedData=<data stored in cookie file>
string encKey = File.ReadAllText(localAppDataPath + @"\Google\Chrome\User Data\Local State");
encKey = JObject.Parse(encKey)["os_crypt"]["encrypted_key"].ToString();
var decodedKey = System.Security.Cryptography.ProtectedData.Unprotect(Convert.FromBase64String(encKey).Skip(5).ToArray(), null, System.Security.Cryptography.DataProtectionScope.LocalMachine);
_cookie = _decryptWithKey(encryptedData, decodedKey, 3);

Key size is 256 bits. Encypted message format is, pay load('v12')+nonce (12 bytes)+cipherText

private string _decryptWithKey(byte[] message, byte[] key, int nonSecretPayloadLength)
{
    const int KEY_BIT_SIZE = 256;
    const int MAC_BIT_SIZE = 128;
    const int NONCE_BIT_SIZE = 96;

    if (key == null || key.Length != KEY_BIT_SIZE / 8)
        throw new ArgumentException(String.Format("Key needs to be {0} bit!", KEY_BIT_SIZE), "key");
    if (message == null || message.Length == 0)
        throw new ArgumentException("Message required!", "message");

    using (var cipherStream = new MemoryStream(message))
    using (var cipherReader = new BinaryReader(cipherStream))
    {
        var nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);
        var nonce = cipherReader.ReadBytes(NONCE_BIT_SIZE / 8);
        var cipher = new GcmBlockCipher(new AesEngine());
        var parameters = new AeadParameters(new KeyParameter(key), MAC_BIT_SIZE, nonce);
        cipher.Init(false, parameters);
        var cipherText = cipherReader.ReadBytes(message.Length);
        var plainText = new byte[cipher.GetOutputSize(cipherText.Length)];
        try
        {
            var len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
            cipher.DoFinal(plainText, len);
        }
        catch (InvalidCipherTextException)
        {
            return null;
        }
        return Encoding.Default.GetString(plainText);
    }
}

Needed packages

1) Newtonsoft JSON .net

2) Bouncy Castle Crypto package

  • 1
    thank you! i use the same crypto API. for those who want to use this code 1) you need Bouncy Castle Crypto API (github.com/neoeinstein/bouncycastle) 2) you need Newtonsoft JSON.net (https://www.newtonsoft.com/json). and please fix key size is 256 bits, not bytes – cerberus Mar 10 '20 at 07:21