Private/Get-LPVault.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<#
.Synopsis
   Retrieves the LastPass vault
.DESCRIPTION
   Downloads the vault payload from the LastPass API and iterates over the
   VaultItems to create an individual PowerShell object for each.
.EXAMPLE
   Get-LPVault
#>

function Get-LPVault
{
    [CmdletBinding()]
    Param()

    Begin
    {
        if (!$LPSession.Cookies.GetCookies($LPURL)["PHPSESSID"])
        {
            $LPSession = Invoke-LPLogin
        }
    }
    Process
    {
        Write-Verbose "Setting up common variables"
        $WebRequestSettings = @{
            "UserAgent" = $LPUserAgent;
            "WebSession" = $LPSession;
            "UseBasicParsing" = $true;
            "ErrorAction" = "Stop";
        }

        Write-Verbose "Getting the vault"
        try
        {
            $VaultBody = @{
                "mobile" = 1;
                "requestsrc" = "cli";
                "hasplugin" = "1.2.1";
            }

            $VaultResponse = Invoke-WebRequest -Uri "$LPUrl/getaccts.php" -Method Post -Body $VaultBody @WebRequestSettings
        }
        catch
        {
            throw "Failed to get vault from LastPass API: $_"
        }

        Write-Verbose "Converting vault into raw bytes"
        $VaultBytes = $BasicEncoding.GetBytes($VaultResponse.Content)

        $VaultCursor = 0
        $Vault = @()
        Write-Verbose "Iterating through the vault entries"
        while ($VaultCursor -lt $VaultBytes.Count)
        {
            Write-Debug "Cursor is $VaultCursor"
            $ID = $BasicEncoding.GetString($VaultBytes[$VaultCursor..$($VaultCursor+3)])
            Write-Debug "Entry ID is $ID"
            $VaultCursor = $VaultCursor + 4
            $Length = [System.BitConverter]::ToUInt32($VaultBytes[$($VaultCursor+3)..$VaultCursor],0)
            Write-Debug "Entry length is $Length"
            $VaultCursor = $VaultCursor + 4
            $Data = $VaultBytes[$VaultCursor..$($VaultCursor+$Length-1)]
            $VaultCursor = $VaultCursor + $Length

            Write-Verbose "Adding item with ID $ID"
            $VaultItem = @{
                "ID" = $ID;
                "Length" = $Length;
                "Data" = $BasicEncoding.GetString($Data);
            }
            $Vault += New-Object -TypeName PSObject -Property $VaultItem
        }

        $script:LPVault = $Vault
        $Vault
    }
}