Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Browser enums #62

Merged
merged 25 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,27 +42,29 @@ Alternatively, some users have suggested running Chrome with the
## Usage

```python
from pycookiecheat import chrome_cookies
from pycookiecheat import BrowserType, chrome_cookies
import requests

url = 'http://example.com/fake.html'
url = 'https://n8henrie.com'

# Uses Chrome's default cookies filepath by default
cookies = chrome_cookies(url)
r = requests.get(url, cookies=cookies)

# Using an alternate browser
cookies = chrome_cookies(url, browser=BrowserType.CHROMIUM)
```

Use the `cookie_file` keyword-argument to specify a different filepath for the
cookies-file: `chrome_cookies(url, cookie_file='/abspath/to/cookies')`

Keep in mind that pycookiecheat defaults to looking for cookies for Google
Chrome, not Chromium, so if you're using the latter, you'll need to manually
specify something like `"/home/username/.config/chromium/Default/Cookies"` (for
Linux) as your `cookie_file`.
You may be able to retrieve cookies for alternative Chromium-based browsers by
manually specifying something like
`"/home/username/.config/BrowserName/Default/Cookies"` as your `cookie_file`.

## Features

- Returns decrypted cookies from Google Chrome, Brave, or Slack, on OSX or
- Returns decrypted cookies from Google Chrome, Brave, or Slack, on MacOS or
Linux.
- Optionally outputs cookies to file (thanks to Muntashir Al-Islam!)

Expand Down
25 changes: 21 additions & 4 deletions flake.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 29 additions & 3 deletions flake.nix
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
{
description = "Flake for https://github.com/n8henrie/pycookiecheat";

inputs.nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
inputs = {
# For python3.7
nixpkgs-old.url = "github:nixos/nixpkgs/release-22.11";
nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
};

outputs = {
self,
nixpkgs,
nixpkgs-old,
}: let
inherit (nixpkgs) lib;
systems = ["aarch64-darwin" "x86_64-linux" "aarch64-linux"];
Expand All @@ -18,7 +23,14 @@
in
systemClosure (
system: let
pkgs = import nixpkgs {inherit system;};
pkgs = import nixpkgs {
inherit system;
overlays = [
(_: _: {
inherit (nixpkgs-old.legacyPackages.${system}) python37;
})
];
};
pname = "pycookiecheat";
propagatedBuildInputs = with pkgs.python311Packages; [
cryptography
Expand Down Expand Up @@ -55,7 +67,21 @@
};

devShells.${system}.default = pkgs.mkShell {
buildInputs = [(pkgs.python311.withPackages (_: propagatedBuildInputs))];
buildInputs = with pkgs; [
python37
python38
python39
python310
(python311.withPackages (
ps:
propagatedBuildInputs
++ (with ps; [
mypy
pytest
tox
])
))
];
};
}
);
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ test = [
"flake8-docstrings==1.5.0",
"flake8-import-order==0.18.1",
"flake8==3.8.4",
"mypy==0.991",
"mypy==1.4.1",
"pep8-naming==0.11.1",
"playwright==1.14.1",
"pycodestyle==2.6.0",
Expand Down
2 changes: 2 additions & 0 deletions src/pycookiecheat/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
"""__init__.py :: Exposes chrome_cookies function."""

from pycookiecheat.chrome import chrome_cookies
from pycookiecheat.common import BrowserType
from pycookiecheat.firefox import firefox_cookies

__author__ = "Nathan Henrie"
__email__ = "[email protected]"
__version__ = "v0.6.0"

__all__ = [
"BrowserType",
"chrome_cookies",
"firefox_cookies",
]
138 changes: 72 additions & 66 deletions src/pycookiecheat/chrome.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@
Adapted from my code at http://n8h.me/HufI1w
"""

import pathlib
import sqlite3
import sys
import typing as t
import urllib.error
import urllib.parse
from pathlib import Path

import keyring
from cryptography.hazmat.primitives.ciphers import Cipher
Expand All @@ -25,7 +25,12 @@
from cryptography.hazmat.primitives.hashes import SHA1
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

from pycookiecheat.common import Cookie, generate_host_keys
from pycookiecheat.common import (
BrowserType,
Cookie,
deprecation_warning,
generate_host_keys,
)


def clean(decrypted: bytes) -> str:
Expand Down Expand Up @@ -73,58 +78,57 @@ def chrome_decrypt(
return clean(decrypted)


def get_osx_config(browser: str) -> dict:
"""Get settings for getting Chrome/Chromium cookies on OSX.
def get_macos_config(browser: BrowserType) -> dict:
"""Get settings for getting Chrome/Chromium cookies on MacOS.

Args:
browser: Either "Chrome", "Chromium", "Slack", or "Brave"
browser: Enum variant representing browser of interest
Returns:
Config dictionary for Chrome/Chromium cookie decryption

"""
# Verify supported browser, fail early otherwise. Mind the capitalization,
# which is necessary for the password retrieval.
browser = browser.title()
app_support = Path("/Library/Application Support")
# TODO: Refactor to exhaustive match statement once depending on >= 3.10
try:
app_support = "~/Library/Application Support"
cookie_file = {
"Chrome": f"{app_support}/Google/Chrome/Default/Cookies",
"Chromium": f"{app_support}/Chromium/Default/Cookies",
"Brave": (
f"{app_support}/BraveSoftware/Brave-Browser/Default/Cookies"
),
"Slack": f"{app_support}/Slack/Cookies",
cookies_suffix = {
BrowserType.CHROME: "Google/Chrome/Default/Cookies",
BrowserType.CHROMIUM: "Chromium/Default/Cookies",
BrowserType.BRAVE: "BraveSoftware/Brave-Browser/Default/Cookies",
BrowserType.SLACK: "Slack/Cookies",
}[browser]
except KeyError:
raise ValueError(
"Browser must be either Chrome, Chromium, Slack, or Brave, "
"but found {browser}"
except KeyError as e:
errmsg = (
f"{browser} is not a valid BrowserType for {__name__}"
".get_macos_config"
)
raise ValueError(errmsg) from e
cookie_file = "~" / app_support / cookies_suffix

# Alas, the cookies can be in two places on MacOS (well, one place, but
# possibly via that insane sandboxing of the filesystem that goes on now)
# so we have to hit the filesystem to check. This is the location is Slack
# is installed via direct download.
if (
browser == "Slack"
and not pathlib.Path(cookie_file).expanduser().exists()
):
# Slack cookies can be in two places on MacOS depending on whether it was
# installed from the App Store or direct download.
if browser is BrowserType.SLACK and not cookie_file.exists():
# And this location if Slack is installed from App Store
cookie_file = (
"~/Library/Containers/com.tinyspeck.slackmacgap/Data"
+ cookie_file[1:]
/ app_support
/ cookies_suffix
)

keyring_service_name = f"{browser} Safe Storage"
keyring_username = "Slack Key" if browser == "Slack" else browser
my_pass = keyring.get_password(keyring_service_name, keyring_username)
browser_name = browser.title()
keyring_service_name = f"{browser_name} Safe Storage"

keyring_username = browser_name
if browser is BrowserType.SLACK:
keyring_username = "Slack Key"

my_pass = keyring.get_password(keyring_service_name, keyring_username)
if my_pass is None:
raise ValueError(
errmsg = (
"Could not find a password for the pair "
f"({keyring_service_name}, {keyring_username}). Please manually "
"verify they exist in Keychain Access.app"
"verify they exist in `Keychain Access.app`."
)
raise ValueError(errmsg)

config = {
"my_pass": my_pass,
Expand All @@ -134,31 +138,24 @@ def get_osx_config(browser: str) -> dict:
return config


def get_linux_config(browser: str) -> dict:
def get_linux_config(browser: BrowserType) -> dict:
"""Get the settings for Chrome/Chromium cookies on Linux.

Args:
browser: Either "Chrome", "Chromium", "Slack", or "Brave"
browser: Enum variant representing browser of interest
Returns:
Config dictionary for Chrome/Chromium cookie decryption

"""
# Verify supported browser, fail early otherwise. Mind the capitalization,
# which is necessary for the password retrieval.
browser = browser.title()

try:
cookie_file = {
"Chrome": "~/.config/google-chrome/Default/Cookies",
"Chromium": "~/.config/chromium/Default/Cookies",
"Brave": "~/.config/BraveSoftware/Brave-Browser/Default/Cookies",
"Slack": "~/.config/Slack/Cookies",
cookie_file = (
Path("~/.config")
/ {
BrowserType.CHROME: "google-chrome/Default/Cookies",
BrowserType.CHROMIUM: "chromium/Default/Cookies",
BrowserType.BRAVE: "BraveSoftware/Brave-Browser/Default/Cookies",
BrowserType.SLACK: "Slack/Cookies",
}[browser]
except KeyError:
raise ValueError(
"Browser must be either Chrome, Chromium, Slack, or Brave, "
"but found {browser}"
)
)

# Set the default linux password
config = {
Expand Down Expand Up @@ -227,17 +224,17 @@ def get_linux_config(browser: str) -> dict:

def chrome_cookies(
url: str,
cookie_file: t.Optional[str] = None,
browser: str = "Chrome",
cookie_file: t.Optional[t.Union[str, Path]] = None,
browser: t.Optional[BrowserType] = BrowserType.CHROME,
curl_cookie_file: t.Optional[str] = None,
password: t.Optional[t.Union[bytes, str]] = None,
) -> dict:
"""Retrieve cookies from Chrome/Chromium on OSX or Linux.
"""Retrieve cookies from Chrome/Chromium on MacOS or Linux.

Args:
url: Domain from which to retrieve cookies, starting with http(s)
cookie_file: Path to alternate file to search for cookies
browser: Name of the browser's cookies to read ('Chrome' or 'Chromium')
browser: Enum variant representing browser of interest
curl_cookie_file: Path to save the cookie file to be used with cURL
password: Optional system password
Returns:
Expand All @@ -250,22 +247,29 @@ def chrome_cookies(
else:
raise urllib.error.URLError("You must include a scheme with your URL.")

# If running Chrome on OSX
# TODO: 20231229 remove str support after some deprecation period
if not isinstance(browser, BrowserType):
deprecation_warning(
"Please pass `browser` as a `BrowserType` instead of "
f"`{browser.__class__.__qualname__}`."
)
browser = BrowserType(browser)

# If running Chrome on MacOS
if sys.platform == "darwin":
config = get_osx_config(browser)
config = get_macos_config(browser)
elif sys.platform.startswith("linux"):
config = get_linux_config(browser)
else:
raise OSError("This script only works on OSX or Linux.")
raise OSError("This script only works on MacOS or Linux.")

config.update(
{"init_vector": b" " * 16, "length": 16, "salt": b"saltysalt"}
)

if cookie_file:
cookie_file = str(pathlib.Path(cookie_file).expanduser())
else:
cookie_file = str(pathlib.Path(config["cookie_file"]).expanduser())
if cookie_file is None:
cookie_file = config["cookie_file"]
cookie_file = Path(cookie_file)

if isinstance(password, bytes):
config["my_pass"] = password
Expand All @@ -283,10 +287,12 @@ def chrome_cookies(
enc_key = kdf.derive(config["my_pass"])

try:
conn = sqlite3.connect("file:{}?mode=ro".format(cookie_file), uri=True)
except sqlite3.OperationalError:
print("Unable to connect to cookie_file at: {}\n".format(cookie_file))
raise
conn = sqlite3.connect(
f"file:{cookie_file.expanduser()}?mode=ro", uri=True
)
except sqlite3.OperationalError as e:
print(f"Unable to connect to cookie_file at: {cookie_file}\n")
raise e

conn.row_factory = sqlite3.Row

Expand Down
Loading
Loading