SecretManagement.KeyChain.Extension/SecretManagement.KeyChain.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
$keyChainName = 'SecretManagement.KeyChain'
$securityCmd = '/usr/bin/security'

# Helpers

# SecretManagement converts strings in hashtable to securestring before handing it to extensions
# since I need to serialize to json, we need to convert everything to just strings
function Convert-HashTable([hashtable]$h) {
    $newh = @{}
    foreach ($key in $h.Keys) {
        if ($h[$key] -is [hashtable]) {
            $newh.$key = Convert-HashTable $h[$key]
        }
        elseif ($h[$key] -is [PSCredential]) {
            $newh.$key = @{
                __type = 'PSCredential'
                UserName = $h[$key].UserName
                Password = $h[$key].Password | ConvertFrom-SecureString -AsPlainText
            }
        }
        elseif ($h[$key] -is [SecureString]) {
            $newh.$key = $h[$key] | ConvertFrom-SecureString -AsPlainText
        }
        else {
            $newh.$key = $h[$key]
        }
    }

    $newh
}

function Convert-HashTableCreds([hashtable]$h) {
    $newh = @{}
    foreach ($key in $h.Keys) {
        if ($h[$key].__type -eq 'PSCredential') {
            $newh.$key = [PSCredential]::new($h[$key].UserName, ($h[$key].Password | ConvertTo-SecureString -AsPlainText))
        }
        elseif ($h[$key] -is [hashtable]) {
            $newh.$key = Convert-HashTableCreds $h[$key]
        }
        else {
            $newh.$key = $h[$key]
        }
    }

    $newh
}

function ConvertTo-Base64([string]$text) {
    $bytes = [System.Text.Encoding]::UTF8.GetBytes($text)
    [System.Convert]::ToBase64String($bytes)
}

function ConvertFrom-Base64([string]$base64) {
    $bytes = [System.Convert]::FromBase64String($base64)
    [System.Text.Encoding]::UTF8.GetString($bytes)
}

function Get-SecretType($typename) {
    switch($typename) {
        'STRG' {
            [Microsoft.PowerShell.SecretManagement.SecretType]::String
        }
        'SSTR' {
            [Microsoft.PowerShell.SecretManagement.SecretType]::SecureString
        }
        'BYTE' {
            [Microsoft.PowerShell.SecretManagement.SecretType]::ByteArray
        }
        'CRED' {
            [Microsoft.PowerShell.SecretManagement.SecretType]::PSCredential
        }
        'HASH' {
            [Microsoft.PowerShell.SecretManagement.SecretType]::Hashtable
        }
        default {
            [Microsoft.PowerShell.SecretManagement.SecretType]::Unknown
        }
    }    
}

function Convert-KeyChainSecret([string]$text) {
    # Example output that needs to be parsed:
    #
    # keychain: "/Users/steve/Library/Keychains/SecretManagement.KeyChain-db"
    # version: 512
    # class: "genp"
    # attributes:
    # 0x00000007 <blob>="KeyChain"
    # 0x00000008 <blob>=<NULL>
    # "acct"<blob>="mysecret"
    # "cdat"<timedate>=0x32303230313030393233303831315A00 "20201009230811Z\000"
    # "crtr"<uint32>="STRG"
    # "cusi"<sint32>=<NULL>
    # "desc"<blob>=<NULL>
    # "gena"<blob>=<NULL>
    # "icmt"<blob>=<NULL>
    # "invi"<sint32>=<NULL>
    # "mdat"<timedate>=0x32303230313030393233303831315A00 "20201009230811Z\000"
    # "nega"<sint32>=<NULL>
    # "prot"<blob>=<NULL>
    # "scrp"<sint32>=<NULL>
    # "svce"<blob>="KeyChain"
    # "type"<uint32>=<NULL>
    # password: "secret"

    if ($text -match '"acct"\<blob\>="(.*?)"') {
        $name = $matches[1]
    }

    if ($text -match '"crtr"<uint32>="(.*?)"') {
        $typename = $matches[1]
    }

    if ($text -match 'password: "(.*?)"') {
        $secret = ConvertFrom-Base64 $matches[1]
    }

    if ($null -eq $name -or $null -eq $typename) {
        throw "Failed to parse KeyChain text output: $text"
    }

    [PSCustomObject]@{
        Name = $name
        TypeName = $typename
        Type = (Get-SecretType $typename)
        Secret = $secret
    }
}

# KeyChain is case sensitive, so make sure to use the original casing
function Get-VaultName([string]$name) {
    $vault = Get-SecretVault -Name $name
    $vault.Name
}

# Public functions
function Get-Secret {
    param (
        [string] $Name,
        [string] $VaultName,
        [hashtable] $AdditionalParameters
    )

    $Name = $Name.ToLower()
    $VaultName = Get-VaultName $VaultName

    $out = & $securityCmd find-generic-password -a $Name -s $VaultName -g $keyChainName 2>&1
    if (!$?) {
        throw $out
    }

    $secret = Convert-KeyChainSecret $out
    if ($null -eq $secret.Secret) {
        throw "Not able to parse KeyChain for secret"
    }

    switch ($secret.TypeName) {
        'STRG' {
            $secretObj = $secret.Secret
        }
        'SSTR' {
            $secretObj = ConvertTo-SecureString $secret.Secret -AsPlainText
        }
        'HASH' {
            $secretObj = $secret.Secret | ConvertFrom-Json -AsHashTable
            $secretObj = Convert-HashTableCreds $secretObj
        }
        'BYTE' {
            $secretObj = [byte[]]::new($secret.Secret.Length / 2)

            for ($i = 0; $i -lt $secret.Secret.Length; $i += 2) {
                $secretObj[$i/2] = [System.Convert]::ToByte($secret.Secret.Substring($i, 2), 16)
            }
        }
        'CRED' {
            $cred = $secret.Secret | ConvertFrom-Json
            $secretObj = [PSCredential]::new($cred.UserName, ($cred.Password | ConvertTo-SecureString -AsPlainText))
        }
        default {
            throw "Unknown type: $($secret.TypeName)"
        }
    }

    return $secretObj
}

function Set-Secret {
    param (
        [string] $Name,
        [object] $Secret,
        [string] $VaultName,
        [hashtable] $AdditionalParameters
    )

    $VaultName = Get-VaultName $VaultName
    Test-SecretVault -VaultName $VaultName

    # KeyChain is case-sensitive, so always use lowercase
    $Name = $Name.ToLower()

    switch ($Secret.GetType()) {
        'String' {
            $type = 'STRG'
        }
        'SecureString' {
            $type = 'SSTR'
            $Secret = $Secret | ConvertFrom-SecureString -AsPlainText
        }
        'Hashtable' {
            $type = 'HASH'
            $Secret = Convert-HashTable $secret | ConvertTo-Json -Depth 100 -Compress
        }
        'Byte[]' {
            $type = 'BYTE'
            $Secret = [System.BitConverter]::ToString($Secret).Replace('-','')
        }
        'PSCredential' {
            $type = 'CRED'
            $Secret = [PSCustomObject]@{
                UserName = $Secret.UserName
                Password = $Secret.Password | ConvertFrom-SecureString -AsPlainText
            } | ConvertTo-Json -Compress
        }
        default {
            throw "Unsupported object type: $($Secret.GetType().Name)"
        }
    }

    $Secret = ConvertTo-Base64 $Secret
    $out = & $securityCmd add-generic-password -a $Name -s $VaultName -c $type -w $Secret -U $keyChainName 2>&1
    if (!$?) {
        throw $out
    }

    return $?
}

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

    $VaultName = Get-VaultName $VaultName

    # KeyChain is case-sensitive, so always use lowercase
    $Name = $Name.ToLower()

    $out = & $securityCmd delete-generic-password -a $Name -s $VaultName $keyChainName 2>&1
    if (!$?) {
        throw $out
    }
    return $?
}

function Get-SecretInfo {
    param (
        [string] $Filter,
        [string] $VaultName,
        [hashtable] $AdditionalParameters
    )

    $VaultName = Get-VaultName $VaultName

    if ($filter.Contains('*')) {
        $output = & $securityCmd dump-keychain $keyChainName | Out-String
        if (!$?) {
            throw "Unable to get contents of KeyChain"
        }

        if ($null -eq $output) {
            return
        }

        foreach ($secretText in $output.Split('keychain:', [System.StringSplitOptions]::RemoveEmptyEntries)) {
            $secret = Convert-KeyChainSecret $secretText

            if ($secret.Name -like $Filter) {
                [Microsoft.PowerShell.SecretManagement.SecretInformation]::new(
                    $secret.Name,
                    $secret.Type,
                    $VaultName
                )
            }
        }
    }
    else {
        $output = & $securityCmd find-generic-password -a $Filter -s $VaultName $keyChainName | Out-String
        if (!$?) {
            return $null
        }

        $secret = Convert-KeyChainSecret $output
        [Microsoft.PowerShell.SecretManagement.SecretInformation]::new(
            $secret.Name,
            $secret.Type,
            $VaultName
        )
    }
}

function Test-SecretVault {
    param (
        [string] $VaultName,
        [hashtable] $AdditionalParameters
    )

    $null = & $securityCmd show-keychain-info $keyChainName 2>&1
    if (!$?) {
        & $securityCmd create-keychain -P $keyChainName
    }

    return $?
}