Decrypt Chrome Cookies File Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
crocodile
Posts: 98
Joined: 28 Dec 2020, 13:41

Decrypt Chrome Cookies File

21 Oct 2021, 06:22

Sorry this may be an excessive request for help.
I want to extract cookies from Chrome Cookies File, I searched for information and found a python script.
But I don't know python at all, can someone help me to convert it to AHK code? Thanks!

https://gist.github.com/GramThanos/ff2c42bb961b68e7cc197d6685e06f10

Code: Select all

# Based on:
# 	https://gist.github.com/DakuTree/98c8362fb424351b803e
# 	https://gist.github.com/jordan-wright/5770442
# 	https://gist.github.com/DakuTree/428e5b737306937628f2944fbfdc4ffc
# 	https://stackoverflow.com/questions/60416350/chrome-80-how-to-decode-cookies
# 	https://stackoverflow.com/questions/43987779/python-module-crypto-cipher-aes-has-no-attribute-mode-ccm-even-though-pycry

import os
import json
import base64
import sqlite3
from shutil import copyfile

# python.exe -m pip install pypiwin32
import win32crypt
# python.exe -m pip install pycryptodomex
from Cryptodome.Cipher import AES

# Copy Cookies and Local State to current folder
copyfile(os.getenv("APPDATA") + "/../Local/Google/Chrome/User Data/Default/Cookies", './Cookies')

# Load encryption key
encrypted_key = None
with open(os.getenv("APPDATA") + "/../Local/Google/Chrome/User Data/Local State", 'r') as file:
	encrypted_key = json.loads(file.read())['os_crypt']['encrypted_key']
encrypted_key = base64.b64decode(encrypted_key)
encrypted_key = encrypted_key[5:]
decrypted_key = win32crypt.CryptUnprotectData(encrypted_key, None, None, None, 0)[1]


# Connect to the Database
conn = sqlite3.connect('./Cookies')
cursor = conn.cursor()

# Get the results
cursor.execute('SELECT host_key, name, value, encrypted_value FROM cookies')
for host_key, name, value, encrypted_value in cursor.fetchall():
	# Decrypt the encrypted_value
	try:
		# Try to decrypt as AES (2020 method)
		cipher = AES.new(decrypted_key, AES.MODE_GCM, nonce=encrypted_value[3:3+12])
		decrypted_value = cipher.decrypt_and_verify(encrypted_value[3+12:-16], encrypted_value[-16:])
	except:
		# If failed try with the old method
		decrypted_value = win32crypt.CryptUnprotectData(encrypted_value, None, None, None, 0)[1].decode('utf-8') or value or 0

	# Update the cookies with the decrypted value
	# This also makes all session cookies persistent
	cursor.execute('\
		UPDATE cookies SET value = ?, has_expires = 1, expires_utc = 99999999999999999, is_persistent = 1, is_secure = 0\
		WHERE host_key = ?\
		AND name = ?',
		(decrypted_value, host_key, name));

conn.commit()
conn.close()
teadrinker
Posts: 4325
Joined: 29 Mar 2015, 09:41
Contact:

Re: Decrypt Chrome Cookies File

21 Oct 2021, 06:45

This script is deprecated and not valid at this time.
malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

Re: Decrypt Chrome Cookies File

21 Oct 2021, 12:57

For me this script works, as it should chrome 94.
crocodile , You need install python, run this script, understand algorithm how it works and do the same on autohotkey.
I am sure We have all the functions to do it, but I am too lazy to convert it.
If it is too hard for You, why just not to use python?
AHK_user
Posts: 515
Joined: 04 Dec 2015, 14:52
Location: Belgium

Re: Decrypt Chrome Cookies File

21 Oct 2021, 13:16

Cookies can be extracted with pages with the javascript "document.cookie;"

You could use chrome.ahk and a line like:
strCookie := page.Evaluate("document.cookie;").value
teadrinker
Posts: 4325
Joined: 29 Mar 2015, 09:41
Contact:

Re: Decrypt Chrome Cookies File

21 Oct 2021, 14:14

malcev wrote: For me this script works
Does it work for you as it is? For me it returns the error:
Traceback (most recent call last):
File "C:\Users\User\Desktop\cookie\cookie.py", line 36, in <module>
cursor.execute('SELECT host_key, name, value, encrypted_value FROM cookies')

sqlite3.OperationalError: Could not decode to UTF-8 column 'encrypted_value' wit
k??B?bk?♦Y:4??I⌂????!>???????K??W??◄h??▲?L!??Y.?????k♣#?"??♦.??{????rYK? ♠▼?→♂$
Last edited by teadrinker on 21 Oct 2021, 14:18, edited 1 time in total.
malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

Re: Decrypt Chrome Cookies File

21 Oct 2021, 14:18

I do not have any errors.
But I dont have folder \Google\Chrome\User Data\Default
and change path to: \Google\Chrome\User Data\Profile 6.
teadrinker
Posts: 4325
Joined: 29 Mar 2015, 09:41
Contact:

Re: Decrypt Chrome Cookies File

21 Oct 2021, 14:20

Do you see decrypted values in the Cookies file?
malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

Re: Decrypt Chrome Cookies File

21 Oct 2021, 14:25

Yes, of course.
But I use print(decrypted_value) for testing.
teadrinker
Posts: 4325
Joined: 29 Mar 2015, 09:41
Contact:

Re: Decrypt Chrome Cookies File

21 Oct 2021, 14:35

For me it started working after adding conn.text_factory = bytes.
Looks like it's not difficult to translate to AHK, but sqlite3.dll is needed.
crocodile
Posts: 98
Joined: 28 Dec 2020, 13:41

Re: Decrypt Chrome Cookies File

21 Oct 2021, 15:04

Thank you all.

@teadrinker
I have used sqlite.ahk to read out the data correctly. Can you convert the decryption function to AHK code? Assuming the data is stored in a buffer() object. Thanks!

@malcev
Since I've never used python, I'm having trouble determining how AutoHotkey gets the data returned from python even if it works properly.
malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

Re: Decrypt Chrome Cookies File

21 Oct 2021, 15:37

crocodile, then it is good opportunity start to learn python ;)
You dont need to run python from ahk.
You need to understand what python functions do and translate them to ahk using winapi.
teadrinker
Posts: 4325
Joined: 29 Mar 2015, 09:41
Contact:

Re: Decrypt Chrome Cookies File  Topic is solved

21 Oct 2021, 15:57

Something like this:

Code: Select all

DecryptEncryptedValue(addr, size, encrypted_key) { ; addr — encrypted data pointer
   static szKey, keyBuff
   if !szKey
      try szKey := KeyBase64ToBuff(encrypted_key, keyBuff)
   if szKey
      outSize := DecryptAesGcm( {p: &keyBuff        , s: szKey}       ; master key
                              , {p: addr + 3        , s: 12}          ; nonce
                              , {p: addr + 15       , s: size - 31}   ; encrypted text
                              , {p: addr + size - 16, s: 16}          ; tag
                              , outData )
   if !outSize {
      try outSize := CryptProtectData(addr, size, outData)
      catch
         Return
   }
   decrypted := StrGet(&outData, outSize, "UTF-8")
   VarSetCapacity(outData, 0)
   Return decrypted
}

KeyBase64ToBuff(key, ByRef outData) {
   size := CryptStringToBinary(key, data) - 5
   try outDataSize := CryptProtectData(&data + 5, size, outData)
   Return outDataSize
}

CryptStringToBinary(string, ByRef outData, formatName := "CRYPT_STRING_BASE64")
{
   static formats := { CRYPT_STRING_BASE64: 0x1
                     , CRYPT_STRING_HEX:    0x4
                     , CRYPT_STRING_HEXRAW: 0xC }
   fmt := formats[formatName]
   chars := StrLen(string)
   if !DllCall("Crypt32\CryptStringToBinary", "Ptr", &string, "UInt", chars, "UInt", fmt
                                            , "Ptr", 0, "UIntP", bytes, "UIntP", 0, "UIntP", 0)
      throw "CryptStringToBinary failed. LastError: " . A_LastError
   VarSetCapacity(outData, bytes)
   DllCall("Crypt32\CryptStringToBinary", "Ptr", &string, "UInt", chars, "UInt", fmt
                                        , "Str", outData, "UIntP", bytes, "UIntP", 0, "UIntP", 0)
   Return bytes
}

CryptProtectData(pData, size, ByRef outData, crypt := false, pEntropy := 0, entropySize := 0) ; crypt = false ? decrypt : encrypt
{
   VarSetCapacity( inBuff, A_PtrSize*2, 0)
   VarSetCapacity(outBuff, A_PtrSize*2, 0)
   NumPut(size, inBuff)
   NumPut(pData, inBuff, A_PtrSize)
   pEntropyBuff := 0
   if pEntropy {
      VarSetCapacity(entropyBuff, A_PtrSize*2, 0)
      NumPut(entropySize, entropyBuff)
      NumPut(pEntropy, entropyBuff, A_PtrSize)
      pEntropyBuff := &entropyBuff
   }
   cryptFunc := crypt ? "CryptProtectData" : "CryptUnprotectData"
   if !DllCall("Crypt32\" . cryptFunc, "Ptr", &inBuff, "Ptr", 0, "Ptr", pEntropyBuff, "Ptr", 0, "Ptr", 0, "UInt", 0, "Ptr", &outBuff)
      throw cryptFunc . " failed. LastError: " . A_LastError
   outSize := NumGet(outBuff, "UInt")
   pOutData := NumGet(outBuff, A_PtrSize)
   VarSetCapacity(outData, outSize, 0)
   DllCall("RtlMoveMemory", "Ptr", &outData, "Ptr", pOutData, "Ptr", outSize)
   DllCall("LocalFree", "Ptr", pOutData)
   Return outSize
}

DecryptAesGcm(key, nonce, cipher, tag, ByRef outBuff) {
   DllCall("Bcrypt\BCryptOpenAlgorithmProvider", "PtrP", hAlgorithm, "WStr", "AES", "Ptr", 0, "UInt", 0)
   mode := "ChainingModeGCM"
   DllCall("Bcrypt\BCryptSetProperty", "Ptr", hAlgorithm, "WStr", "ChainingMode", "WStr", mode, "UInt", StrLen(mode)*2, "UInt", 0)
   DllCall("Bcrypt\BCryptGenerateSymmetricKey", "Ptr", hAlgorithm, "PtrP", hKey, "Ptr", 0, "UInt", 0, "Ptr", key.p, "UInt", key.s, "UInt", 0)
   VarSetCapacity(BACMI, sz := 4*4 + A_PtrSize*8 + 16, 0) ; BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO
   NumPut(sz     , BACMI, 0, "UInt")
   NumPut(1      , BACMI, 4, "UInt") ; BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO_VERSION = 1
   NumPut(nonce.p, BACMI, 8)
   NumPut(nonce.s, BACMI, 8 + A_PtrSize)
   NumPut(tag.p  , BACMI, 8 + A_PtrSize*4)
   NumPut(tag.s  , BACMI, 8 + A_PtrSize*5)
   DllCall("Bcrypt\BCryptDecrypt", "Ptr", hKey, "Ptr", cipher.p, "UInt", cipher.s, "Ptr", &BACMI
                                 , "Ptr", 0, "UInt", 0, "Ptr", 0, "UInt", 0, "UIntP", size, "UInt", 0)
   VarSetCapacity(outBuff, size, 0)
   res := DllCall("Bcrypt\BCryptDecrypt", "Ptr", hKey, "Ptr", cipher.p, "UInt", cipher.s, "Ptr", &BACMI
                                 , "Ptr", 0, "UInt", 0, "Ptr", &outBuff, "UInt", size, "UIntP", size, "UInt", 0)
   DllCall("Bcrypt\BCryptDestroyKey", "Ptr", hKey)
   DllCall("Bcrypt\BCryptCloseAlgorithmProvider", "Ptr", hAlgorithm, "UInt", 0)
   Return res ? 0 : size
}
I've already used such a code to decrypt passwords.
crocodile
Posts: 98
Joined: 28 Dec 2020, 13:41

Re: Decrypt Chrome Cookies File

21 Oct 2021, 19:26

@teadrinker
I managed to decrypt the data. Thank you so much!

@malcev
Yes, python is a language worth learning.
But I didn't want to interrupt my current AutoHotkey work to learn it. But now thanks to everyone's help, the problem is smoothly solved and I can finish my script. :D

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: mamo691, MrDoge and 234 guests