Read-Chromium.ps1

<#PSScriptInfo
.VERSION 1.0.0
.GUID b2808f1d-4fdd-4002-89fc-21bf38db7b66
.AUTHOR James O'Neill
.COMPANYNAME Mobula Consulting Ltd
.COPYRIGHT (C) James O'Neill 2020
.TAGS passwords secrets chromium chrome edge 'Google-Chrome' 'Microsoft-Edge' AES AesGCcm security key
.LICENSEURI https://opensource.org/licenses/MIT
.EXTERNALMODULEDEPENDENCIES GetSQL
#>


<#
.DESCRIPTION
 Utility to extract and decrypt data from Chromium Browser SQL Lite files, inclduing decoding of the data format used from V80 onwards
#>

<# Copyright James O'Neill 2020.
   Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
   The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #>


#requires -modules getsql -version 7
using namespace "System.Security.Cryptography"
param (
    #Location of the database file replace \Google\Chrome as required
    $DbPath     = (Join-path ([environment]::GetFolderPath('UserProfile')) 'AppData\Local\Google\Chrome\User Data\Default\Login Data'),
    #Location of the State file specify and empty string if nothing is to be decoded.
    $StatePath ,
    #Table to extract from
    $Table    = "logins" ,
    #Properties to return use @{n='Name';e={Unprotect $_.Field}} to decrypt columns
    $Property = @(@{n='User';   e='username_value'}, @{n='Password';e={Unprotect $_.password_value}},
                  @{n='Created';e={([datetime]"1601-01-01").AddMilliseconds(($_.date_created /1000))}},@{n='realm'; e='signon_realm'}),
    #(optional) file path to save the Key to. You must take steps to secure the file
    $KeyPath
)
try   {$sqliteFile   = Copy-Item -PassThru $dbpath -Destination $env:TEMP -ErrorAction Stop } # Delete this file at the end
catch {Write-Warning "Could not make a working copy of $dbpath" ; return }

#region Get the master key and use it to create a AesGCcm object for decoding
if (-not $PSBoundParameters.ContainsKey('StatePath')) {$StatePath = Join-path (Split-path (Split-Path $DbPath)) 'Local State'}
if ($statePath)      {$localStateInfo = Get-Content -Raw $StatePath | ConvertFrom-Json}
if ($localStateInfo) {$encryptedkey   = [convert]::FromBase64String($localStateInfo.os_crypt.encrypted_key)}
if ($encryptedkey -and [string]::new($encryptedkey[0..4]) -eq 'DPAPI') {
    $masterKey       = [ProtectedData]::Unprotect(($encryptedkey | Select-Object -Skip 5),  $null, 'CurrentUser')
    if ($KeyPath)    { [convert]::ToBase64String($masterkey)     | Out-Default $KeyPath  }
    $Script:GCMKey   = [AesGcm]::new($masterKey) # Not present in Windows PowerShell 5, nor in PS Core V6.
}
else {Write-Warning  'Could not get key for new-style encyption. Will try with older Style' }
#endregion
function Unprotect  { # Use GCM decrytpion if ciphertext starts "V10" & GCMKey exists, else try ProtectedData.unprotect
    Param ( $Encrypted )
    $Script:DecodeCount ++
    try {
        if ($Script:GCMKey -and [string]::new($Encrypted[0..2]) -match "v1\d") {
            #Ciphertext bytes run 0-2="V10"; 3-14=12_byte_IV; 15 to len-17=payload; final-16=16_byte_auth_tag
            [byte[]]$output =  1..($Encrypted.length - 31) # same length as payload.
            $Script:GCMKey.Decrypt($Encrypted[3..14]  , $Encrypted[15..($Encrypted.Length-17)],
                                   $Encrypted[-16..-1], $output, $null)
            [string]::new($output)
        }
        else {[string]::new([ProtectedData]::Unprotect($Encrypted,  $null, 'CurrentUser')) }
    }
    catch {Write-Warning "Error decoding item $Script:DecodeCount"}
}

$Script:DecodeCount  = 0 # for reporting where errors are found. If more than 1 decode per row divide by items per row!
$savedRows           = Get-SQL -Lite -Connection $sqliteFile -Table $Table -Close #Storing results instead of piping will release the file sooner.
$savedRows           | Select-Object -Property $Property                          #unprotect is specified in property definitions
try   {Remove-Item   $sqliteFile -ErrorAction Stop}                               #If processing is too quick file may still be locked.
catch {Write-Warning "SQlite was slow to release the data file. Please run del '$sqliteFile'"  }