2

Is there a way to use already obtained cookies from an existing Chrome web session in Powershell for the SessionVariable?

I know the fields for SessionVariable are:

Headers               : {}
Cookies               : System.Net.CookieContainer
UseDefaultCredentials : False
Credentials           : 
Certificates          : 
UserAgent             : Mozilla/5.0 (Windows NT; Windows NT 10.0; en-US) 
                        WindowsPowerShell/5.1.17134.407
Proxy                 : 
MaximumRedirection    : -1

Am I able to do something to set these values initially for a webrequest, such as: ? Would I need specific headers for a session when it could be multiple/different types of requests?

$ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
    $Params = @{
        Headers = $headers 
        Cookies = $cookies 
        UseDefaultCredentials = "False" 
        Credentials = $creds
        UserAgent = $ua
        Proxy = ""
        MaximumRedirection = "-1"
    }

If something like that can be done, I am also a little confused how I would input the cookies. I found this from Getting Cookies using PowerShell :

$webrequest = Invoke-WebRequest -Uri $url -SessionVariable websession 
$cookies = $websession.Cookies.GetCookies($url) 
 
# Here, you can output all of $cookies, or you can go through them one by one. 
 
foreach ($cookie in $cookies) { 
     # You can get cookie specifics, or just use $cookie 
     # This gets each cookie's name and value 
     Write-Host "$($cookie.name) = $($cookie.value)" 
}

I have a JSON format export of cookies from any given site in this format, but I can also cut that down to just "name" = "value" if that is what is needed.

[
  {
    "domain": "",
    "expirationDate": "",
    "hostOnly": "",
    "httpOnly": "",
    "name": "",
    "path": "",
    "sameSite": "",
    "secure": "",
    "session": "",
    "storeId": "",
    "value": "",
    "id": ""
  },
  {
    "domain": "",
    etc...
  }
]

I didn't know how to designate each section as a $cookie in $cookies, nor how to add them in a different manner since it will not be from a URL/WebRequest but instead a JSON.

Thanks for any help!

Community
  • 1
  • 1
  • Each browser has it's own way of storing cookies. Chrome, I just learned, stores cookies in a SQLite db file in yout profile (https://stackoverflow.com/questions/31021764/where-does-chrome-store-cookies) So anyhow you'll have to extract cookie information from there to use in your script. If possible... – Gert Jan Kraaijeveld Dec 24 '18 at 09:00

1 Answers1

0

Here's the solution as PowerShell script using PSSQLite:

# One time setup
    # Download the repository 
        $RepositoryZipUrl = "https://api.github.com/repos/RamblingCookieMonster/PSSQLite/zipball/master"
        Invoke-RestMethod -Uri $RepositoryZipUrl -OutFile "PSSQLite.zip"
    # Unblock the zip
        Unblock-File "PSSQLite.zip"
    # Extract the PSSQLite folder to a module path (e.g. $env:USERPROFILE\Documents\WindowsPowerShell\Modules\)
        Expand-Archive -Path "PSSQLite.zip" -DestinationPath $(Resolve-Path "$env:USERPROFILE\Documents\*PowerShell\Modules" | Select-First 1) -Force -Confirm 
    #Simple alternative, if you have PowerShell 5, or the PowerShellGet module:
        Install-Module PSSQLite

# Import the PSSQlite module
    Import-Module PSSQLite    #Alternatively, Import-Module \\Path\To\PSSQLite
# Specify for which domain you want to retrieve cookies
    $domain = "mavaddat.ca"

# Create a SQLite connection to Cookies
    $cookiesSQL = New-SQLiteConnection -DataSource "$env:APPDATA\Opera Software\Opera Stable\Cookies"

# Investigate the db structure
    $cookiesSQL.GetSchema()

# Investigate tables' structures to formulate a SQL query
    $cookiesSQL.GetSchema("Tables")

# Based on the schema of table `cookies`, form the query
    $query = "SELECT `"_rowid_`",* FROM `"main`".`"cookies`" WHERE `"host_key`" LIKE '%$domain%' ESCAPE '\' LIMIT 0, 49999;"

# Read the cookies from the SQLite
    $cookies = Invoke-SqliteQuery -Query $query -DataSource $cookiesSQL.FileName

# Get Chromium cookie master key
    $cookiesKeyEncBaseSixtyFour = (Get-Content -Path "$env:APPDATA\Opera Software\Opera Stable\Local State" | ConvertFrom-Json).'os_crypt'.'encrypted_key'
    $cookiesKeyEnc = [System.Convert]::FromBase64String($cookiesKeyEncBaseSixtyFour) | Select-Object -Skip 5  # Magic number 5
    $cookiesKey = [System.Security.Cryptography.ProtectedData]::Unprotect($cookiesKeyEnc,$null,[System.Security.Cryptography.DataProtectionScope]::LocalMachine)

# Create a web session object for the IWR work
    $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession

# Stuff the cookies into the session
    foreach($cookie in $cookies){
        $names = $cookie | Get-Member | Where-Object -FilterScript {($_.MemberType) -eq 'NoteProperty'} | Select-Object -Property Name 
        foreach($name in $names)
        {
            $path = if ([string]::IsNullOrEmpty($cookie.'path'))
            {
                '/'
            } 
            else 
            { 
                $cookie.'path'
            }
$cipherStream = [System.IO.MemoryStream]::new($cookie.encrypted_value)
$cipherReader = [System.IO.BinaryReader]::new($cipherStream)
$nonSecretPayload = $cipherReader.ReadBytes(3) # Magic number 3
$nonce = $cipherReader.ReadBytes([System.Security.Cryptography.AesGcm]::NonceByteSizes.MinSize)

            $session.Cookies.Add([System.Net.Cookie]::new(#)
        }
    }

# Now use the session to IWR
    $downloadToPath = "c:\somewhere\on\disk\file.zip"
    $remoteFileLocation = "http://somewhere/on/the/internet"
    Invoke-WebRequest $remoteFileLocation -WebSession $session -TimeoutSec 900 -OutFile $downloadToPath

How I realized the above

The Chromium-based browser uses cookies stored in a binary SQLite database file. See Superuser question on how to find this database for Chrome, "Is there a way to watch cookies and their values live?".

For me (using Opera 74.0.3911.107 on Windows 10), this file is named Cookies and it lives at %appdata%\Opera Software\Opera Stable\Cookies. Using PSSQLite, I can see that the database has two tables with the following schemas:

Cookies table

Name Type Schema
creation_utc INTEGER "creation_utc" INTEGER NOT NULL
host_key TEXT "host_key" TEXT NOT NULL
name TEXT "name" TEXT NOT NULL
value TEXT "value" TEXT NOT NULL
path TEXT "path" TEXT NOT NULL
expires_utc INTEGER "expires_utc" INTEGER NOT NULL
is_secure INTEGER "is_secure" INTEGER NOT NULL
is_httponly INTEGER "is_httponly" INTEGER NOT NULL
last_access_utc INTEGER "last_access_utc" INTEGER NOT NULL
has_expires INTEGER "has_expires" INTEGER NOT NULL DEFAULT 1
is_persistent INTEGER "is_persistent" INTEGER NOT NULL DEFAULT 1
priority INTEGER "priority" INTEGER NOT NULL DEFAULT 1
encrypted_value BLOB "encrypted_value" BLOB DEFAULT ''
samesite INTEGER "samesite" INTEGER NOT NULL DEFAULT -1
source_scheme INTEGER "source_scheme" INTEGER NOT NULL DEFAULT 0
source_port INTEGER "source_port" INTEGER NOT NULL DEFAULT -1
is_same_party INTEGER "is_same_party" INTEGER NOT NULL DEFAULT 0

Meta table

Name Type Schema
key LONGVARCHAR "key" LONGVARCHAR NOT NULL UNIQUE
value LONGVARCHAR "value" LONGVARCHAR

See stackoverflow question "How to read Brave Browser cookie database encrypted values in C# (.NET Core)?" I also followed the PowerShell cookie method of this gist by @lawrencegripper as a template.

Mavaddat Javid
  • 406
  • 4
  • 19