Private/Get-LPKeys.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
<#
.Synopsis
   Generates the encryption keys
.DESCRIPTION
   Retrieves the number of iterations for the user. Uses PBKDF2.NET to create
   the encryption key and the login hex string.
.EXAMPLE
   Get-LPKeys
#>

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

    Begin
    {
        if (!$LPLogin)
        {
            $LPLogin = Get-LPLogin
        }
    }
    Process
    {
        Write-Verbose "Setting up common variables"
        $WebRequestSettings = @{
            "UserAgent" = $LPUserAgent;
            "WebSession" = $LPSession;
            "UseBasicParsing" = $true;
            "ErrorAction" = "Stop";
        }

        if (!$LPIterations)
        {
            Write-Verbose "Getting the number of iterations"
            try
            {
                $IterationsResponse = Invoke-WebRequest -Uri "$LPUrl/iterations.php" -Method Post -Body @{"username"=$LPLogin.UserName.ToLower();} @WebRequestSettings
                Write-Debug $($IterationsResponse | Out-String)
    
                $script:LPIterations = if ([int]$IterationsResponse.Content -eq 1) {100100} else {[int] $IterationsResponse.Content}
                Write-Debug "Using $LPIterations iterations"
            }
            catch
            {
                throw "Failed to get iterations from LastPass API: $_"
            }
        }

        Write-Verbose "Producing the keys"
        try
        {
            $UsernameBytes = $BasicEncoding.GetBytes($LPLogin.UserName.ToLower())
            $PasswordBytes = $BasicEncoding.GetBytes($LPLogin.GetNetworkCredential().Password)

            $KeyPBKDF2 = [System.Security.Cryptography.PBKDF2]::new($PasswordBytes,$UsernameBytes,$LPIterations,"HMACSHA256")
            $KeyBytes = $KeyPBKDF2.GetBytes(32)
            $KeyString = $BasicEncoding.GetString($KeyBytes) | ConvertTo-SecureString -AsPlainText -Force

            $LoginPBKDF2 = [System.Security.Cryptography.PBKDF2]::new($KeyBytes,$PasswordBytes,1,"HMACSHA256")
            $LoginBytes = $LoginPBKDF2.GetBytes(32)
            $LoginString = [System.BitConverter]::ToString($LoginBytes).Replace("-","").ToLower()

            $script:LPKeys = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList @($LoginString,$KeyString)
            $script:LPKeys
        }
        catch
        {
            throw "Failed to generate the login and decryption keys: $_"
        }
    }
}