SecretManagement.LastPass.Extension/SecretManagement.LastPass.Extension.psm1

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
using namespace Microsoft.PowerShell.SecretManagement

#region constants

# The capture groups are:
# 1. The date and time that the secret was stored
# 2. The ls short output (just the name & id)
# 3. The name of the secret
# 4. The username of the secret
$lsLongOutput = "(\d\d\d\d-\d\d-\d\d \d\d:\d\d)? *((.*) \[id: \d*\]) \[username: (.*)\]"

# Custom notes in lpass CLI are a bit of a mess.
# For default types
# Get operation will return the value
# Set operation will only accept the key
# This is to convert value obtained from Get when doing a Set.
$DefaultNoteTypeMap = @{
    'Address'           = 'address'
    # 'amex' = '' # Possibly deprecated
    'Bank Account'      = 'bank'
    'Credit Card'       = 'credit-card'
    'Database'          = 'database'
    "Driver's License"  = 'drivers-license'
    'Email Account'     = 'email'
    'Health Insurance'  = 'health-insurance'
    'Instant Messenger' = 'im'
    'Insurance'         = 'insurance'
    #'mastercard' = '' # Possibly deprecated
    'Membership'        = 'membership'
    'Passport'          = 'passport'
    'Server'            = 'server'
    'Software License'  = 'software-license'
    'SSH Key'           = 'ssh-key'
    'Social Security'   = 'ssn'
    #'visa' = '' # Possibly deprecated
    'Wi-Fi Password'    = 'wifi'
} 

$lpassMessage = @{
    AccountNotFound = 'Error: Could not find specified account(s).'
    # Need to use wildcard since the path of lpass could be different
    LoggedOut = 'Error: Could not find decryption key. Perhaps you need to login with*'
    MultipleMatches = 'Multiple matches found.'
}

# These fields need special consideration when working with secrets.
# Language / NoteType are fields that are part of any custom notes and always appear last (before Notes)
#Notes field can appear in any secrets and is always the last field. It is also the only multiline field.
$SpecialKeys = @('Language', 'NoteType', 'Notes')

#endregion

# Internal wrapper around the actual call. Reserved for Invoke-lpass. Use Invoke-lpass instead.
function Invoke-lpassInternal {
    [CmdletBinding()]
    Param(
        [Parameter(ValueFromPipeline)]
        [object]$InputObject,
        [Switch]$UseNative,
        [String]$lpassPath,
        [string[]]$Arguments
    )

    if ($UseNative) {
        if ($InputObject) { return $InputObject | & $lpassPath @Arguments }
        return & $lpassPath @Arguments
    }
    # WSL
    if ($InputObject) { return $InputObject | & wsl $lpassPath @Arguments }
    return & wsl $lpassPath @Arguments
}


<#
.SYNOPSIS
Manage calls to lastpass.

.DESCRIPTION
Manage calls to lastpass. show & login command are special and requires us to not redirect streams
to get the prompt. Everything else have its error stream redirect to success (2>&1)

.PARAMETER Arguments
Arguments to pass to lpass CLI

.PARAMETER InputObject
Used by some of the non-interactive commands such as lpass add / lpass edit

.PARAMETER VaultParams
This should never be populated from the extension. It is only for the main module, which have
no awareness of the vault parameters and need to have them fed to it. If this parameter is provided,
it overrides $AdditionalParameters
#>

function Invoke-lpass {
    [CmdletBinding()]
    param (
        [Parameter()]
        [string[]]$Arguments,
        [Parameter(ValueFromPipeline)]
        [object]$InputObject,
        #Only for root module functions
        [hashtable]$VaultParams
    )
     # Command from the root module do not contain $AdditionalParameters
    if ($null -ne $VaultParams) { $AdditionalParameters = $VaultParams }
    
    $UseWSL = $AdditionalParameters.wsl -eq $true
    $lpassPath = if ($null -ne $AdditionalParameters.lpassPath) { "`"$($AdditionalParameters.lpassPath)`"" } else { 'lpass' }
    $UseNative = -not $UseWSL

    if (($UseNative -and -not (Get-Command $lpassPath -EA 0)) -or 
        ($UseWSL -and (& wsl $lpassPath --version ) -notlike 'LastPass CLI*')) {
        throw "lpass executable not found or installed."
    }

    $Params = @{
        InputObject = $InputObject
        UseNative   = $UseNative
        lpassPath   = $lpassPath
        Arguments   = $Arguments
    }

    # If we do redirect on the command themselves, it doesn't work.
    # Doing redirect on the commands wrapped in a function work.
    
    if ($Arguments.Count -gt 0) {
        switch ($Arguments[0]) {
            'login' {  
                # We want the prompt always, so no redirect
                $result = Invoke-lpassInternal @Params
            }
            {$_ -in 'show','ls','rm'} {
                # We might want the prompt, but are not sure yet.
                $result = Invoke-lpassInternal @Params 2>&1
                # If we get the message stating we might be logged out, we reissue the command without redirect (for Prompt)
                if ($result -is [System.Management.Automation.ErrorRecord] -and [String]$result -like $lpassMessage.LoggedOut) {
                    $result2 = Invoke-lpassInternal @Params
                    # If $result2 -eq $null, something will have been printed in the console (because we disabled the redirect)
                    # We therefore want to keep the original $result "Logged out" so it is thrown later on
                    # If not $null, we want to evaluate $result2 instead and discard $result
                    if ($null -ne $result2 -or $Arguments[0] -eq 'rm') { $result = $result2 }
                }
            }
            Default {
                # By default, we always redirect streams
                $result = Invoke-lpassInternal @Params 2>&1
            }
        }
    }

    if ($result -is [System.Management.Automation.ErrorRecord]) {
        switch -Wildcard ([string] $result) {
            $lpassMessage.LoggedOut { throw [PasswordRequiredException] "$($lpassMessage.LoggedOut.TrimEnd("*")) Connect-LastPass" }
            $lpassMessage.AccountNotFound { break }
            $lpassMessage.MultipleMatches { break }
            # We leave handling exceptions to SecretManagement
            default {
                # We do a Write-Error so it's more discoverable to the user
                # (but it will exist in the inner exception of the throw)
                Write-Error -ErrorRecord $result
                throw $result
            }
        }
    }

    # This should be a string or a collection of strings
    return $result
}

function Get-Secret
{
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipelineByPropertyName)]
        [string] $Name,
        [Parameter(ValueFromPipelineByPropertyName)]
        [string] $VaultName,
        [Parameter(ValueFromPipelineByPropertyName)]
        [hashtable] $AdditionalParameters
    )

    # TODO error handling

    if ($AdditionalParameters.Verbose) {
        $VerbosePreference = "Continue"
    }

    if ($Name -match ".* \(id: (\d*)\)") {
        $Name = $Matches[1]
    }

    $res = Invoke-lpass 'show', '--name', $Name, '--all'

    # We use ToString() here to turn the ErrorRecord into a string if we got an ErrorRecord
    if ($null -eq $res -or $res.ToString() -eq $lpassMessage.AccountNotFound) {
        # Will produce "Get-Secret : The secret $Name was not found." error.
        return
    }

    if ($res[0] -eq $lpassMessage.MultipleMatches) {
        Write-Warning "Multiple matches found with the name $Name. `nThe first matching result will be returned."
        $Id = [regex]::Match($res[1], '\[id: (.*)\]').Groups[1].value
        $res = Invoke-lpass 'show', '--name', $Id, '--all'

    }

    #The first line contains the secret name and ID. We do not have any use for it.
    $Raw = ($res | Select-Object -Skip 1) -join "`n"

    if ([String]::IsNullOrEmpty($Raw)) {
        return ""
    }

    # Custom type cannot have the same case-sensitive name but Username / uSERname work.
    # That's why we don't parse it directly to a hashtable.
    $MyMatches = @([regex]::Matches($raw, '(?<key>.*?)\: (?<value>.*?)(?:\n|$)')  | ForEach-Object {
            [PSCustomObject]@{
                key        = $_.Groups.Item('key').value
                value      = $_.Groups.Item('value').value 
                valueIndex = $_.Groups.Item('value').index
            }
        })

    # Notes is always the last item (lpass wise). This is also the only field that can be multiline.
    # Any matching items after the first "Notes" key need to be discarded as it is not an item,
    # but rather just part of the notes.
    $HasNote = $MyMatches.key -ccontains 'Notes' 
    if ($HasNote) {
        $start = $MyMatches.Where({$_.Key -ceq 'Notes'},'First')[0].valueIndex
        $Note = $raw.Substring($start)
        $MyMatches = $MyMatches.Where({$_.ValueIndex -lt $start})
    }
    $IsCustomType = $AdditionalParameters.outputType -eq 'Detailed' -or $MyMatches.key.Contains('NoteType')
    If ($IsCustomType) {
        $Output = Get-ComplexSecret -Fields $MyMatches -Note $Note 
    }
    else {
        $Output = Get-SimpleSecret -Fields $MyMatches -Note $Note 
    }
    
    return $Output
}

function Set-Secret
{
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipelineByPropertyName)]
        [string] $Name,
        [Parameter(ValueFromPipelineByPropertyName)]
        [object] $Secret,
        [Parameter(ValueFromPipelineByPropertyName)]
        [string] $VaultName,
        [Parameter(ValueFromPipelineByPropertyName)]
        [hashtable] $AdditionalParameters
    )
    if ($AdditionalParameters.Verbose) {
        $VerbosePreference = "Continue"
    }
    $sb = [System.Text.StringBuilder]::new()
    
    
    if ($Secret -is [string] -or $Secret -is [securestring]) {
        $Secret = @{
            URL = ' http://sn'
            Notes = $Secret
        }
    } elseif ($Secret -is [pscredential]) {
        $Secret = @{
            Username = $Secret.Username
            Password = $Secret.GetNetworkCredential().password
        }
    }

    if ($Secret -is [System.Collections.IDictionary]) {
        if ($Secret.Keys.count -eq 1 -and $null -ne $Secret.Notes) {
            $Secret.URL = 'http://sn'
        }

        $Keys = $Secret.Keys.Where({$_ -notin $SpecialKeys })
        foreach ($k in $Keys) {
            if ($Secret.$k -is [securestring]) {
                $Secret.$k = [System.Net.NetworkCredential]::new("", $Secret.$k).Password
            }
            $sb.AppendLine("$($k): $($Secret.$k)") | Out-Null
        }

        # Notes need to be on a new line
        if ($null -ne $Secret.Notes) {
            if ($Secret.Notes -is [securestring]) {
                $Secret.Notes = [System.Net.NetworkCredential]::new("", $Secret.Notes).Password
            }
            $sb.AppendLine("Notes: `n$($Secret.Notes)") | Out-Null
        }
    } 
    
    $res = Invoke-lpass 'show', '--sync=now', '--name', $Name

    # We use ToString() here to turn the ErrorRecord into a string if we got an ErrorRecord
    $SecretExists = switch -Wildcard ($res) {
        # This should never ever happen...
        "" {
            Write-Warning "Querying the secret $Name produced an unexpected result of `$Null"
            $false
            break
        }
        $lpassMessage.AccountNotFound {
            $false
            break
        }
        default {
            $true
            break
        }
    }

    if ($SecretExists) {
        Write-Verbose "Editing secret"
        $sb.ToString() | Invoke-lpass 'edit', '--non-interactive', $Name
    } else {
        Write-Verbose "Adding new secret"
        $NoteTypeArgs = @()
        if ($null -ne $Secret.NoteType) {
            if ($Secret.NoteType -is [securestring]) { 
                $Secret.NoteType = [System.Net.NetworkCredential]::new("", $Secret.NoteType).Password
            }
            $NoteTypeArgs += "--note-type=$($Secret.NoteType)"
        }
        $sb.ToString() | Invoke-lpass 'add', $Name, '--non-interactive', $NoteTypeArgs
    }

    # Explicit sync so calling set again does not duplicate the secret (add --sync=now not fast enough)
    Invoke-lpass 'sync'

    return $true
}

function Remove-Secret
{
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipelineByPropertyName)]
        [string] $Name,
        [Parameter(ValueFromPipelineByPropertyName)]
        [string] $VaultName,
        [Parameter(ValueFromPipelineByPropertyName)]
        [hashtable] $AdditionalParameters
    )

    # Grab the id because that's more exact
    if ($Name -match ".* \(id: (\d*)\)") {
        $Name = $Matches[1]
    }

    Invoke-lpass 'rm', $Name
    return $?
}

function Get-SecretInfo
{
    [CmdletBinding()]
    param (
        [string] $Filter,
        [string] $VaultName,
        [hashtable] $AdditionalParameters
    )
    if ($AdditionalParameters.Verbose) {
        $VerbosePreference = "Continue"
    }

    $Filter = "*$Filter"
    $pattern = [WildcardPattern]::new($Filter,[System.Management.Automation.WildcardOptions]::IgnoreCase)
    Invoke-lpass 'ls','-l' |
        Where-Object { 
            $IsMatch = $_ -match $lsLongOutput 
            if (-not $IsMatch ) { Write-Verbose -Message "No match for: $_ `nThis record will be ignored." }
            $IsMatch -and $pattern.IsMatch($Matches[3])
        } |
        ForEach-Object {
            $type = if ($AdditionalParameters.outputType -eq 'Detailed') {
                [SecretType]::Hashtable
            }
            elseif ($Matches[4]) {
                [SecretType]::PSCredential
            }
            else {
                [SecretType]::Unknown
            }

            [SecretInformation]::new(
                ($Matches[2] -replace '\[(id: \d*?)\]$', '($1)'), 
                $type,
                $VaultName)
        }
}

function Test-SecretVault
{
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipelineByPropertyName)]
        [string] $VaultName,
        [Parameter(ValueFromPipelineByPropertyName)]
        [hashtable] $AdditionalParameters
    )
    $status = Invoke-lpass 'status'
    return ($status -match "Logged in as .*")
}

function Get-SimpleSecret {
    [CmdletBinding()]
    param (
        $Fields,
        $Note
    )
    
    $username = $Fields.Where( { $_.key -eq 'Username' }, 'first') | Select-Object -ExpandProperty value
    $password = $Fields.Where( { $_.key -eq 'Password' }, 'first') | Select-Object -ExpandProperty value
    # Credentials
    if ($username -or $password) {
        if ($null -eq $username) { $username = '' }
        if ($null -eq $password) { $password = '' }
        if ("" -ne $password) { $password = $password | ConvertTo-SecureString -AsPlainText -Force }
        return [System.Management.Automation.PSCredential]::new($username, $password)
    }
    # Secure Note
    if ($null -ne $Note) {
        return $Note
    }
    # Empty secret
    return ''
}

function Get-ComplexSecret {
    [CmdletBinding()]
    param (
        $Fields,
        $Note
    )
    
    $Dupes = ($Fields | Group-Object key).Where( { $_.Count -gt 1 })
    # Notes is removed from the fields. If present, this mean we have another field using that name under a different case.
    $DupeNote = ($Fields.Contains('Notes') -and ![String]::IsNullOrEmpty($Note))
    if ($Dupes.Count -gt 0 -or $DupeNote) {
        Write-Verbose 'Creating case-sensitve hashtable'
        $Output = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::CurrentCultureIgnoreCase)
    } else {
        $Output = [Ordered]@{}
    }
    
    Foreach ($f in $Fields) {
        try {
            $Output.Add($f.key, $f.value) 
        }
        catch {
            Write-Warning "$($f.key) field was not added."
        }
    }
    if ($null -ne $Output.NoteType -and $DefaultNoteTypeMap.ContainsKey($Output.NoteType)) {
        $Output.NoteType = $DefaultNoteTypeMap.Item($Output.NoteType)
    }

    if (![String]::IsNullOrEmpty($Note)) { 
        $Output.Notes = $Note
    }

    return $Output
}